Adding picture to randomized list - javascript

I'm adding a button to a website that randomizes NBA teams and provides a picture with the answer. I have the randomizer set up to provide the random team when the button is pushed but I'm unsure how to get a picture to go along with the team selected.
My randomizer in JS:
let teams =
{
atlanta: "Atlanta Hawks",
boston: "Boston Celtics",
brooklyn: "Brooklyn Nets",
charlotte: "Charlotte Hornets",
chicago: "Chicago Bulls",
cleveland: "Cleveland Cavaliers",
dallas: "Dallas Mavericks",
denver: "Denver Nuggets",
detroit: "Detroit Pistons",
goldenState: "Golden State Warriors",
houston: "Houston Rockets",
indiana: "Indiana Pacers",
clippers: "Los Angeles Clippers",
lakers: "Los Angeles Lakers",
memphis: "Memphis Grizzlies",
miami: "Miami Heat",
milwaukee: "Milwaukee Bucks",
minnesota: "Minnesota Timberwolves",
pelicans: "New Orleans Pelicans",
knicks: "New York Knicks",
thunder: "Oklahoma City Thunder",
orlando: "Orlando Magic",
philadelphia: "Philadelphia 76ers",
phoenix: "Phoenix Suns",
portland: "Portland Trail Blazers",
sacramento: "Sacramento Kings",
spurs: "San Antonio Spurs",
toronto: "Toronto Raptors",
utah: "Utah Jazz",
washington: "Washington Wizards"
}
const values = Object.values(teams)
app.get("/api/teams", (req, res)=>{
const randomTeam = values[Math.floor(Math.random()*values.length)]
console.log(randomTeam)
res.status(200).send(randomTeam)
})
To add team name to HTML:
<script>
document.getElementById("button").onclick = function () {
axios.get("http://localhost:5151/api/teams").then(function(response) {
const data = response.data;
document.getElementById("randomTeamCard").innerHTML = [data].map(function(team) {
return `The team you should bandwagon is: ${data}!`;
})
.join("");
}).catch(function (err) {
document.getElementById("randomTeamCard").innerHTML =
'<li class="text-danger">' + err.message + "</li>";
});
};
</script>

Related

How to print web scrapping results to a file?

I want to save program results to file. Currently I'm printing them to console. How would I do it?
public static void main(String[] args) throws FileNotFoundException {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\Dejan Kostov\\IdeaProjects\\MavenSigmaSpeakers1\\src\\main\\resources\\chromedriver-74.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://sigma.world/eurasia/speakers/");
String[] expected = {"Gary Vaynerchuk", "John Lee", "Jordan Belfort", "Clinton Sparks", "Johnny Walker", "Dr. Sara Al Madani", "VESA", "Irina S. Litchfield", "Cal Evans", "Dr Jane Thomason", "Gordon Einstein", "Jimmy Nguyen", "Robert Dowling", "Aideen Shortt", "Dustin Plantholt", "Andres Meneses", "Arvin Khamseh", "Agne Linge", "Joshua Ellul", "Mike Prasad", "Paweł Łaskarzewski", "Obediah Ayton", "Jorge Sebastiao", "Wesley Ellul", "Nikita Sachdev", "Joseph F Borg", "Zack Ritchie", "Francisco Fernandez", "Gabriel Laender", "Reem Al Mosabbeh", "Cannelle Maricaux", "Onur Altan Tan", "Jitendra Vaswani", "Marco Funk", "James Bowater", "Susan Oh", "Laura K. Inamedinova", "Isabella Händel", "Tejinder Kumar", "Gustavo Montero", "Adel Bhurtun", "Vas Modinos", "Alexander Fazel", "Alexander Mihailovski", "Marc Taverner", "Pavlina Papalouka", "Emma Todd", "Cordelia Morgan Cooper", "Nick Spanos", "John Murillo", "Alex Tsepaev", "Anna Tutova", "H.E. Mr. Zulfiquar Ghadiyali", "Shafeeq Qureshi", "Bailey Dodds", "Joan de Ramón Brunet", "Amir Student", "Amna Usman Chaudhry", "Ayesha Mubarak Ali", "Nadia Dvoinos", "Mario Nawfal", "Alex J.", "Paula Tavangar", "Cinderella Amar", "Joel Michael", "Kevin Imani", "José. F. Pereira", "Paula Hajduczenia", "Dr Andreas Mathikolonis", "Alena Zharkovskaya", "Edward Condrat", "Wadih Al Sayah", "Aravind Swaminathan","Luca Tagliaferro"};
List<WebElement> elements = driver.findElements(By.tagName("h3"));
System.out.println("Number of elements with tag h3 : " + elements.size());
for (int i = 0; i < elements.size(); i++) {
WebElement element = elements.get(i);
System.out.println(i + " : " + element.getText());
if (element.getText().equals(expected[i])) {
System.out.println("Strings are equal");
} else {
System.out.println("Strings are NOT equal");
driver.quit();
}
}
}
}
Below code would write the console output to a specified file:
PrintStream printStream = new PrintStream(new File("C:\\Users\\username\\consoleOutput.txt"));
System.setOut(printStream);
Add the above 2 lines to your code anywhere before you start printing.

Create new KO.observable array and populate it from an array object

Is possible to create an ko.observable array and populate it using an array object?
My goal here is to create a ko.observable array with all the description/objects that are with the original array.
//Sample data the original data is coming from an socket query and being push on the array("people")
var people = [{
name: "Contact 1",
address: "1, a street, a town, a city, AB12 3CD",
tel: "0123456789",
email: "anemail#me.com",
type: "family"
},
{
name: "Contact 2",
address: "1, a street, a town, a city, AB12 3CD",
tel: "0123456789",
email: "anemail#me.com",
type: "friend"
}
];.
var people = [{
name: "Contact 1",
address: "1, a street, a town, a city, AB12 3CD",
tel: "0123456789",
email: "anemail#me.com",
type: "family"
},
{
name: "Contact 2",
address: "1, a street, a town, a city, AB12 3CD",
tel: "0123456789",
email: "anemail#me.com",
type: "friend"
}
];
var quotesarray = function(items) {
this.items = ko.observableArray(items);
this.itemToAdd = ko.observable("");
this.addItem = function() {
if (this.itemToAdd() != "") {
this.items.push(this.itemToAdd());
this.itemToAdd("");
}
}.bind(this);
};
ko.applyBindings(new quotesarray(people));
console.log(people);
You just needed to make it items instead of quotesarray
var people = [
{ name: "Contact 1", address: "1, a street, a town, a city, AB12 3CD", tel: "0123456789", email: "anemail#me.com", type: "family" },
{ name: "Contact 2", address: "1, a street, a town, a city, AB12 3CD", tel: "0123456789", email: "anemail#me.com", type: "friend" }
];
var quotesarray = function(items){
this.items = ko.observableArray(items);
this.itemToAdd = ko.observable("");
this.addItem = function(){
if (this.itemToAdd() != ""){
this.items.push(this.itemToAdd());
this.itemToAdd("");
}
}.bind(this);
};
ko.applyBindings(new quotesarray(people));
console.log(people);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<table>
<thead>
<tr><th>name</th><th>address</th></tr>
</thead>
<tbody data-bind="foreach: items">
<tr>
<td data-bind="text: name"></td>
<td data-bind="text: address"></td>
</tr>
</tbody>
</table>
You can create an observableArray to which the socket writes messages. You subscribe to the array to be automatically notified when the contents change (i.e. after every write by the socket).
In the subscribe callback you empty the array and add the items to your viewmodel's property.
If you expect to receive many rapidly succeeding messages, you can rateLimit the array to which you write to ensure you don't update the DOM too many times.
Here's an example. The explanations are in the code comments.
const UPDATE_EVERY_MS = 500;
// The observable array the socket writes to
const received = ko.observableArray([])
// Use a rateLimit extension if you expect to
// receive many updates from your socket
.extend({ rateLimit: UPDATE_EVERY_MS });
// The observable array in your viewmodel
const rendered = ko.observableArray([]);
received.subscribe(items => {
// Write "inbox" to viewmodel's list
rendered(rendered().concat(items));
// Clear received without triggering notification
items.length = 0;
});
ko.applyBindings({ items: rendered });
// Mock a socket that writes to `received`
setInterval(() => received.push(Math.random()), 200);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<ul data-bind="foreach: rendered">
<li data-bind="text: $data"></li>
</ul>

JS: If statement to check if var exists in array

I have a AngularJS app where I have an array defined that has a group of dealers. Something like this:
$scope.dealers = [{
name: "Dealer Name",
address: "Address goes here",
website:"site.com",
lat: "latitude",
lng: "longitude"
territory: ['County1', 'County2', 'County3']
},
{
name: "Dealer Name",
address: "Address goes here",
website:"site.com",
lat: "latitude",
lng: "longitude",
territory: ['County1', 'County2', 'County3']
},
];
A user will input their zip code, and then using the Google Geocode API, I convert their zip code to lat/long coordinates and find their closest dealer based off of coordinates between them, and all of the dealers.
That is working fine.
Here is where I need help. Each dealer has a territory (in the array as counties) that needs to be checked first, before finding the closest dealer, because some dealers have counties in their territories that are actually geographically closer to another dealer.
I have a var that stores the users County based on their zip. So I need to make an IF statement that checks the userZip variable against the dealers array to see if that county exists anywhere in the array. If it does, then I need to return the name of that dealer. If it does not, I will have an ELSE statement that just runs the function I already have, which will just find the closest dealer to their location.
You can use Array.prototype.find()
let dealers = [{
name: "Dealer Name",
address: "Address goes here",
website: "site.com",
lat: "latitude",
lng: "longitude",
territory: ['County1', 'County2', 'County3']
},
{
name: "Dealer Name",
address: "Address goes here",
website: "site.com",
lat: "latitude",
lng: "longitude",
territory: ['County1', 'County2', 'County3']
},
];
let country = 'County2';
let found = dealers.find(d => d.territory.includes(country));
if(found)
console.log(found);
else
console.log("..find closest...");
//another case
country = 'NotAnywhere';
found = dealers.find(d => d.territory.includes(country));
if(found)
console.log(found);
else
console.log("..find closest...");

Display the length of a string on the page

I have a simple program that stores male, female and unisex names, you click a button and one is chosen at random and displayed on the page.
I am constantly adding new names into the database, so I want a simple javascript that records how many names are stored in each separate database (male, female and unisex) and displays in in a text that reads "There are currently ### males name, ### female names, and ### unisex names."
The site is live at: http://surrealmayhem.com/stuff/name_generator.html
The only things I can find online is a console.log using
var = randomOtherNames.length;
but I need it to display in the html via a span or bold tag and an ID name. I know it would be something along the lines of
document.getElementById("male_num");
but passed that, Im not sure how to put it all together and make it display on the page. Im still very new to javascript, and I dont entirely understand how the text that does display when you click the buttons even works. I feel like I might be able to reuse the script I already have, but I could use some help.
<button Onclick="click" id="other_button" style="font-size: 25px;"> Click Me </button>
<br /><br />
<b id="other_name" style="font-size: 25px;"></b>
<script type="text/javascript" charset="utf-8">
var other_string = randomOtherNames.length;
var randomOtherNames = [
"Jamie",
"Shannon",
"Kelly",
"Aeron",
"Shain",
"Kasey",
"Jordan",
"Jesse / Jessie",
"Sage",
"Evan",
"Alex",
"Stephen",
"Renee",
"Tracy",
"Avery",
"Dallas",
"Denver",
"Taylor",
"Elliot",
"Terry",
"Jeri",
"Percy",
"Raven",
"Jean",
"Jan",
"Christian",
"Adrian",
"Jude",
"Quinn",
"Piper",
"Harper",
"Payton",
"Walker",
"Cameron",
"Terran",
"Riley",
"River",
"Andren",
"Camden",
"Jiles",
"Pax",
"Rayne",
"Skylar",
"Kalin",
"Justice",
"July",
"Kensington",
"Kendall",
"Grey",
"Genesis",
"Hollis",
"Keagan",
"Kai",
"Bristol",
"Angel",
"Azure",
"Bailey",
"Carmen",
"Echo",
"Embry",
"Ember",
"Gale",
"Freedom",
"Haven",
"Kyler",
"Kylan",
"Miracle",
"Myka",
"Peace",
"Zene",
"Winter",
"Xannon",
"Valor",
"Urban",
"Valentine",
"Storm",
"Tai",
"Shae",
"Sailor",
"Red",
"Reign",
"Ramsey",
"Reed",
"Reggie",
"Ocean",
"Nalo",
"Neo",
"London",
"Ash",
"Brook",
"Crane",
"Crimson",
"Corin",
"Cresant",
"Indigo",
"Jazz",
"Cassidy",
"Kin",
"Monroe",
"Moral",
"Poet",
"Ryder",
"Saxton",
"Sidney",
"Tanner",
"Torrance",
"Torrin",
"Lex / Lexi",
"Zane",
"Zanas",
"Ari",
"Brynn",
"Greer",
"Kennedy",
"Lyle",
"Lonnie",
"Rune",
"Rylan",
"Sparrow",
"Sunny",
"Emerald",
"Cloud",
"Star",
"Kensey",
];
var other_div = document.getElementById("other_name");
document.getElementById("other_button").addEventListener("click", function() {
randomIndex = Math.ceil((Math.random()*randomOtherNames.length-1));
newText = randomOtherNames[randomIndex];
other_div.innerHTML = newText;
});
</script>
At the top, add an element that you will use to display the count. Then in your script, set the innerHTML for the new element:
var randomOtherNames = ["Jamie", "Shannon", "Kelly", "Aeron", "Shain", "Kasey", "Jordan", "Jesse / Jessie", "Sage", "Evan", "Alex", "Stephen", "Renee", "Tracy", "Avery", "Dallas", "Denver", "Taylor", "Elliot", "Terry", "Jeri", "Percy", "Raven", "Jean", "Jan", "Christian", "Adrian", "Jude", "Quinn", "Piper", "Harper", "Payton", "Walker", "Cameron", "Terran", "Riley", "River", "Andren", "Camden", "Jiles", "Pax", "Rayne", "Skylar", "Kalin", "Justice", "July", "Kensington", "Kendall", "Grey", "Genesis", "Hollis", "Keagan", "Kai", "Bristol", "Angel", "Azure", "Bailey", "Carmen", "Echo", "Embry", "Ember", "Gale", "Freedom", "Haven", "Kyler", "Kylan", "Miracle", "Myka", "Peace", "Zene", "Winter", "Xannon", "Valor", "Urban", "Valentine", "Storm", "Tai", "Shae", "Sailor", "Red", "Reign", "Ramsey", "Reed", "Reggie", "Ocean", "Nalo", "Neo", "London", "Ash", "Brook", "Crane", "Crimson", "Corin", "Cresant", "Indigo", "Jazz", "Cassidy", "Kin", "Monroe", "Moral", "Poet", "Ryder", "Saxton", "Sidney", "Tanner", "Torrance", "Torrin", "Lex / Lexi", "Zane", "Zanas", "Ari", "Brynn", "Greer", "Kennedy", "Lyle", "Lonnie", "Rune", "Rylan", "Sparrow", "Sunny", "Emerald", "Cloud", "Star", "Kensey"];
var other_string = randomOtherNames.length;
var other_div = document.getElementById("other_name");
var other_count_div = document.getElementById("other_name_count");
//populate the innerHTML of "other_count_div" on page load:
other_name_count.innerHTML = randomOtherNames.length;
var findName = function() {
randomIndex = Math.ceil((Math.random() * randomOtherNames.length - 1));
newText = randomOtherNames[randomIndex];
other_div.innerHTML = newText;
other_name_count.innerHTML = randomOtherNames.length;
};
document.getElementById("other_button").addEventListener("click", findName);
<button Onclick="click" id="other_button" style="font-size: 25px;"> Click Me </button>
<br /><br />
<b id="other_name" style="font-size: 25px;"></b>
<span id="other_name_count"></span>

how to get complex json object and render it in views in node js?

I have following json with arrays in it
In server I'm sending json like this
getTrips: function getTrips(req, res, next){
var url = '/CTB-WS/rest/trips?from='+ req.tripinfo.fromCityId + '&to=' + req.tripinfo.toCityId + '&depart-date=' + req.tripinfo.departDate+ '&pax=1';
console.log(url);
rest.get(url).on('complete', function(trips) {
if (trips instanceof Error) {
console.log('Error:', trips.message);
} else {
console.log('trips'+ JSON.stringify(trips));
console.log('onward trips'+ JSON.stringify(trips['onwardTrips']));
trips = trips || [];
req.trips = trips['onwardTrips'];
next();
}
});
},
sendTrips: function sendTrips(req, res, next){
res.render('trips', { trips: req.trips});
}
In view , I'm able to catch trip id, but not pickupPointDetails and dropoffPointDetails which are inside array, how can I render it in view?
extends layout
block content
h3 Trip Selection
form.form-horizontal(id="Findtrips", accept-charset="UTF-8", action="", method="post" enctype="multipart/form-data")
each trip, key in trips
p
a(href="") #{trip.tripId} #{key} #{trips.length}
p= trip.pickupPointDetails[0].pickupPointId //[0] [1] works but when i give key as value Unexpected token =
JSON object
{
"onwardTrips": [
{
"tripId": "1285758",
"fromCity": "Singapore",
"toCity": "Shah Alam",
"operatorCode": "SA",
"operatorName": "Starmart Express",
"departTime": "2014-01-24 11:30:00.0",
"busType": "Executive",
"pickupPointDetails": [
{
"pickupPointId": "78",
"departureTime": "2014-01-24 11:30:00.0",
"pickupPointName": "Golden Mile Tower, Beach Road"
}
],
"dropoffPointDetails": [
{
"dropOffPointName": "Shah Alam Bus Terminal",
"dropOffPointId": "1285758"
}
],
"fareDetails": {
"adultFare": "91.0"
}
},
{
"tripId": "1285856",
"fromCity": "Singapore",
"toCity": "Shah Alam",
"operatorCode": "SA",
"operatorName": "Starmart Express",
"departTime": "2014-01-24 21:00:00.0",
"busType": "Executive",
"pickupPointDetails": [
{
"pickupPointId": "78",
"departureTime": "2014-01-24 21:00:00.0",
"pickupPointName": "Golden Mile Tower, Beach Road"
}
],
"dropoffPointDetails": [
{
"dropOffPointName": "Shah Alam Bus Terminal",
"dropOffPointId": "1285856"
}
],
"fareDetails": {
"adultFare": "91.0"
}
}
],
"errorCode": 0
}
You need to nest another loop if you wish to access each object in the sub array:
Example JSON object:
{
"array": [
{
"property": "Hello",
"nestedArray": [
{
"nestedArrayProp": "World"
}
]
}
]
}
Example Jade template:
each object in array
each nestedObject in object.nestedArray
p= object.property + ' ' + nestedObject.nestedArrayProp
Which will output:
<p>Hello World</p>

Categories