The array does not output properly - csv

let test = [];
d3.csv("cgvList.csv", function (data) {
if (data.poi_nm == "CGV") {
let obj = {};
obj.content = '<div>' + data.branch_nm + '</div>';
test.push(obj);
}
});
console.log(test);
console.log("test[0] : " + test[0]);
console.log("test.length : " + test.length);
[enter image description here][1]
I made the csv file into an object array.
And as a result of outputting the array, the array was output well,
enter image description here
but when outputting index 0, undefined came out and the length of the array was also 0.
It was printed properly when it was printed from the console.
What's the problem?
enter image description here

Without a jsfiddle or sandbox to play with, I can't tell exactly what is going on, but what I believe is happening is a mix of two things:
d3.csv is an async function, and therefore returns a promise.
The function you pass on to d3.csv is supposed to tell the function how to parse every element in the csv, and should return the parsed object, not add it to an external array or anything like that. Every element you return in that function will be an element in your resulting array
There's (at least) two possible ways you can deal with this:
await the async function, and its return value will be your required value, something like
const test = await d3.csv("cgvList.csv", function (data) {
if (data.poi_nm == "CGV") {
let obj = {};
obj.content = '<div>' + data.branch_nm + '</div>';
return obj;
}
});
console.log(test);
console.log("test[0] : " + test[0]);
console.log("test.length : " + test.length);
Notice that here the function you pass onto d3.csv returns the object in the way you want to format it!
Do your logic in a .then statement, which also waits for the promise to be fulfilled:
d3.csv("cgvList.csv", function (data) {
if (data.poi_nm == "CGV") {
let obj = {};
obj.content = '<div>' + data.branch_nm + '</div>';
return obj;
}
}).then((test) => {
console.log(test);
console.log("test[0] : " + test[0]);
console.log("test.length : " + test.length);
});

Related

Creating a custom formula with array having multiple arguments in columns with different data

Up to this point I've managed to get it to work for a single argument (body) but without the second argument (photoUrl):
function SendTelegram(body,photoUrl) {
if (body.map) {
var response = body.map(function(b) {return SendTelegram(b);});
} else {
var response = UrlFetchApp.fetch(
"https://api.telegram.org/bot" + 'AAA' +
"/sendPhoto?caption=" + encodeURIComponent(body) +
"&photo=" + encodeURIComponent(photoUrl) +
"&chat_id=" + 'BBB' +
"&disable_web_page_preview=true&parse_mode=HTML"
);
}
}
I'm not able to understand how I should proceed to work with this two different arguments, for example, the function in the spreadsheet would be:
=ARRAYFORMULA(SendTelegram(A1:A,B1:B))
In my attempts when I try to add the second argument, it always uses the first row value in all calls, it doesn't follow the array one by one.
In your script, at SendTelegram(b) of var response = body.map(function(b) {return SendTelegram(b);});, the 2nd argument is not set. By this, at 2nd loop, photoUrl is not declared. I thought that this might be the reason of your issue.
And, in your script, I thought that it might be required to return the response value. So, how about the following modification?
Modified script:
function SendTelegram(body, photoUrl) {
if (body.map) {
return body.map((b, i) => SendTelegram(b, photoUrl[i]));
} else if (body && photoUrl) {
return UrlFetchApp.fetch(
"https://api.telegram.org/bot" + 'AAA' +
"/sendPhoto?caption=" + encodeURIComponent(body) +
"&photo=" + encodeURIComponent(photoUrl) +
"&chat_id=" + 'BBB' +
"&disable_web_page_preview=true&parse_mode=HTML", { muteHttpExceptions: true }
).getContentText();
}
return null;
}
Note:
This is a simple modification. Because I cannot understand your expected value from the URL. So, please modify the script for your situation.

Understanding ES6 tagged template literal

Following code snippet is used on Mozilla (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals) to explain Tagged Template literal, please help me understand what following function is doing, i am unable to get the actual flow of the function, since they have used keys.foreach and when i inspected in Chrome, keys was a function, so not able to understand
function template(strings, ...keys) {
return (function(...values) {
var dict = values[values.length - 1] || {};
var result = [strings[0]];
keys.forEach(function(key, i) {
var value = Number.isInteger(key) ? values[key] : dict[key];
result.push(value, strings[i + 1]);
});
return result.join('');
});
}
var t1Closure = template`${0}${1}${0}!`;
t1Closure('Y', 'A'); // "YAY!"
var t2Closure = template`${0} ${'foo'}!`;
t2Closure('Hello', {foo: 'World'}); // "Hello World!"
Most of the complexity in the example comes from the overloaded function and the forEach invocation, not from the tagged template literals. It might better have been written as two separate cases:
function dictionaryTemplate(strings, ...keys) {
return function(dict) {
var result = "";
for (var i=0; i<keys.length; i++)
result += strings[i] + dict[keys[i]];
result += strings[i];
return result;
};
}
const t = dictionaryTemplate`${0} ${'foo'}!`;
t({0: 'Hello', foo: 'World'}); // "Hello World!"
function argumentsTemplate(strings, ...keys) {
is (!keys.every(Number.isInteger))
throw new RangeError("The keys must be integers");
return function(...values) {
var result = "";
for (var i=0; i<keys.length; i++)
result += strings[i] + values[keys[i]];
result += strings[i];
return result;
};
}
const t = argumentsTemplate`${0}${1}${0}!`;
t('Y', 'A'); // "YAY!"
Template is a custom function defined by us to parse the template string, whenever a function is used to parse the template stringThe first argument of a tag function contains an array of string values. The remaining arguments are related to the expressions. so here specifically we have written the function to that given output I had got confused because when in inspected keys inside the forEach, i got a function in console, but inspecting the function before forEach gave keys as the array of configurable string ${0} and ${1} in first example

Getting response with NodeJS request module

I just started using the twitch kraken api and I have a few questions.
Whenever I attempt to get a JSON object there is no response. I am attempting to run this function through Amazon AWS Lambda, and don't have access to a console.
In the code below my callback function will always print out "SUCCESS got streamers ERROR". I am pretty certain right now the "ERROR" comes from my initial setting of result.
How come result does not get changed into the proper JSON?
I have used postman and it returns the proper thing with the query and param, and headers:
function getJSON(callback){
var result = "ERROR";
request.get(url(games[0]),function(error,response,body){
console.log("requested for url: " + url(games[0]));
var d = JSON.parse(body);
result = d.streams[0];//.channel.display_name;
// for(var i = 0; i < limit; i++){
// streamers.push(d.streams[i].channel.display_name)
// }
streamers.push(result);
});
if (streamers.length < 0){
callback("ERROR");
}else{
callback("SUCCESS got streamers " + result);
}
}
function url(game){
return {
url: "https://api.twitch.tv/kraken/streams/",//twitchlimit,
qs : {
'game' : 'overwatch',
'limit' : 2
},
headers: {
'Client-ID': clientID,
'Accept': 'application/json',
'Accept-Charset': 'utf-8',
}
};
}
I think your streamers code
if (streamers.length < 0){
callback("ERROR");
}else{
callback("SUCCESS got streamers " + result);
}
should be included in the request callback because currently it's not waiting for the request to finish, it's just carrying on so therefore the value of result will not change. Also the array length cannot be less than 0 so it will always go to the else and say "SUCCESS got streamers ERROR"
Thank you guys for the suggestions. I did have a few oversights and attempted to fix them.
I have implemented you suggestions and it seems to have worked a bit. I ended up putting the json.parse into a try/catch block, and moved the if/else statements inside the getJSON method. However, now I don't get any output.
This is how I am invoking the getJSON method:
function handleGameResponse(intent,session,callback){
//gets the game
var game = intent.slots.game.value;
if (!games.includes(game)){
var speechOutput = "You asked for: " + intent.slots.game.value;
//var speechOutput = "You asked for: " + games[game] + " That game is currently not an option. These are your current options: " + arrayToString(games)
var repromptText = "Please ask one from the current options.";
var header = "Invalid Game";
}else {
getJSON(function(data){
if(data !== "ERROR"){
var speechOutput = data; //capitalizeFirst(game) + " top three streamers are: " + arrayToString(streamers) + '.';
var repromptText = "Do you want to hear more about games?";
var header = capitalizeFirst(game);
}else{
var speechOutput = "I'm sorry, something went wrong and I could not get the streamers.";
}
//speechOutput = data;
});
//speechOutput = games[0] + " games[0], game= " + game; //this executes so the getJSON isn't executing
}
var shouldEndSession = false;
callback(session.attributes,buildSpeechletResponse(header,speechOutput,repromptText,shouldEndSession));
}
Does the above execute the same way? As in the shouldEndSession and callback execute before the getJSON has time to give a response?
For ref, this is the getJSON method now:
function getJSON(callback){
var result = "ERROR";
request.get(url(games[0]),function(error,response,body){
try{
var d = JSON.parse(body);
} catch (err){
callback("Sorry, something seems to have malfunctioned while getting the streamers");
}
result = d.streams[0].channel.display_name;
// for(var i = 0; i < limit; i++){
// streamers.push(d.streams[i].channel.display_name)
// }
streamers.push(result);
if (streamers.length <= 0){
callback("ERROR");
}else{
callback("SUCCESS got streamers " + result);
}
});
}

assign Json value to a variable using $.each()

I am trying to pass the result of this query as a Json string to Jquery so that I can assign the value to a JQuery variable. Actually there will be more than one key:value pair but I am illustrating my problem with a single pair for simplicity. I am able to console.log the index and value however when I try to assign the value to a variable I get an "undefined" message. I have done this successfully elsewhere and am not sure what i am missing here:
$query = (
"SELECT MedCondPrimary, Count(MedCondPrimary) as Count
FROM Comments
WHERE MedCondPrimary='Arthritis'");
$result = mysqli_query($dbc, $query);
WHILE($rows = mysqli_fetch_array($result)) {
$medcond = $rows['MedCondPrimary'];
$array3[$medcond] = $rows['Count'];
};
$json_count=json_encode($array3);
echo $json_count; // {"Arthritis":"26"}
JQ:
var tally = ;
console.log(tally);// Object { Arthritis="26"} should be a string?
$.each(tally, function(index, value) {
console.log(index+":"+value); //Arthritis:26
var arthritis = value.Arthritis;
console.log(arthritis); //undefined
});
Your jQuery code should be using each() instead of $.each() here.
$( tally ).each(function( index, obj ) {
console.log( index + ":" + obj.Arthritis); // Arthritis:26
var arthritis = obj.Arthritis;
console.log( arthritis ); // 26
});
each() passes the object while $.each() passes property-value pairs for an object. You're $.each() at the other place must be working because you passed it an array as shown below:
// iterating an array
$.each( [{Arthritis:26}], function( index, obj) {
console.log( obj.Arthritis ); // 26
});
PHP Edit :
$json_count=json_encode($array3);
echo "[" . $json_count . "]";

Problem in getting right result for select box

I am using jQuery as:
$(document).ready(function(){
test("price");
alert("hi");
$("#item2").change(function()
{
sort= $("#item2").val();
test(sort);
});
});
Function test() is some JavaScript function, my problem is when page loads function calls by "price" parameter. Now when I select some item from select box function test() is called using sort parameter (verify by alert box). but I am not getting the correct result. I mean when I select option from select box than also my result of test() is as with "price" , I suppose it might be the problem because of jQuery's $(document).ready(function(){,. test() function make some html code based on the parameter and show it on the web page.
Please suggest me what can be the solution
EDIT:
function test() is :
function test(sort)
{
<%
Ampliflex ms = Ampliflex.getInstance();
String solrIP = ms.getSolrIP();
String solrPort = ms.getSolrPort();
String rows = ms.getSearchResultCount();
%>
solrIP='<%= solrIP %>'; // get Solr IP address
solrPort='<%= solrPort %>'; // get Solr Port number
rows='<%= rows %>'; // get number of results to return
solrURL="http://"+solrIP+":"+solrPort;
var query="${searchStr}"; // get the query string entered by ECommerce user
query=query.replace(/[^a-zA-Z 0-9*?:.+-^""_]+/g,''); // Remove special characters
query=query.replace(/\*+/g,'*'); // Replace multiple occurrence of "*" with single "*"
var newquery=query;
if(parseInt(query)==NaN)
{
var lowerCaseQuery=query.toLowerCase();
newquery=lowerCaseQuery;
}
else{
var lowerCaseQuery=query;
}
// sort= document.getElementById("item2").value;
$.getJSON(solrURL+"/solr/db/select/?qt=dismax&wt=json&&start=0&rows="+rows+"&q="+lowerCaseQuery+"&hl=true&hl.fl=text&hl.usePhraseHighlighter=true&sort="+sort+" desc&json.wrf=?", function(result){
var highlight = new Array(result.response.numFound);
$.each(result.highlighting, function(i, hitem){
var rg = /<em>(.*?)<\/em>/g;
var res = new Array();
var match = rg.exec(hitem.text[0]);
while(match != null){
res.push(match[1])
match = rg.exec(hitem.text[0]);
}
highlight[i]=res[0]
for (j=1 ;j<res.length;j++)
{
highlight[i]= highlight[i]+","+res[j];
}
});
var html="<table><tr>"
var count=0;
var alt="NoImage";
var size="3pt";
var id;
var flag=1; // Flag for error messages
border="1";
// If no search results
if(result.response.numFound==0)
{
var msg= "<hr /><font size="+size+" >We're sorry, we found no results for <b>"+document.getElementById("queryString").value+"</font><hr />";
}
else
{
/* var msg= "<hr /><font size="+size+" >Total Results Found <b> "+ result.response.numFound+"</b> for "+"<b>"+document.getElementById("queryString").value+"</b> keyword</font><hr /> ";*/
if (newquery==lowerCaseQuery)
{
var msg= "<hr /><font size="+size+" >Total Results Found <b> "+ result.response.numFound+"</b> for "+"<b>"+query+"</b> </font><hr /> ";
}
else
{
var msg= "<hr /><font size="+size+" >There were no exact matches for <b> "+ query+"</b> , so we searched automatically for "+"<b>"+query+"</b> and yielded "+result.response.numFound+" result(s)</font><hr /> ";
}
// Parse solr response and display it on web page
$.each(result.response.docs, function(i,item){
var word = new Array();
word=highlight[item["UID_PK"]].split(",");
var result="";
var j=0;
for (j=0 ;j<=item.text.length;j++)
{
result = result+item.text[j]+"<br>";
}
for (j=0 ;j<word.length;j++)
{
result=result.replace(word[j],'<em>' + word[j] + '</em>');
}
html+="<td><table>";
var src=item.image;
id="id";
if(src!= null && src!= ""){
html+="<p><tr><td><br>"+"<img id= "+id+ " src="+src+ " border="+border+ " /></td></tr>";
count=count+1;
html += "<tr><td><b>ImagePath</b> "+ item.image+"</td></tr>";
}
// If not insert a default image
else
{
src="images/products/default.jpg";
html+="<tr><td><br><p>"+"<img id= "+id+ " src="+src+ " border="+border+" /></td></tr>";
count=count+1;
html += "<tr><td><b>ImagePath</b> "+"No image path found" +"</td></tr>";
}
html += "<tr><td>UID_PK: "+ item.UID_PK+"</td></tr>";
html += "<tr><td>Name: "+ item.name+"</td></tr>";
html+="<tr><td><b>Price: $"+item.price+"</td></tr>";
html+="<tr><td> "+result+"<br></td></tr>";
html+="</p></table></td>"
if(count%3==0)
{
html+="</tr>"
html+="<tr>"
}
});
html+="</table>"
}
$("#text_container").html(msg);
$("#result").append(html);
}
});
});
}
Your question isn't particularly clear, but your alert code only fires when the document is ready - it is not inside the "change" event function.
Try using the following to see what value is being returned when you change the select box:
$(document).ready(function(){
test("price");
$("#item2").change(function()
{
sort= $("#item2").val();
alert(sort);
test(sort);
});
});
When changing the select box, you should get an alert with the value you have chosen, which will help you understand why the test() function isn't functioning as you expect.
If you amend your question to include the HTML of the select box and the test() function itself I will amend my answer to help.
The JQuery code that you have posted is working fine. Demo: http://jsfiddle.net/DtnUr/
We need more details to figure out the issue, such as your HTML code and JS functions.