Hello these code does request to Steam Web API
const request = require("request");
request({
url: "https://api.steampowered.com/IEconService/GetTradeOffers/v1/?key=MYAPIKEY&get_sent_offers=1&active_only=1&format=json",
json: true
}, (err, responser, body) => {
console.log(body.response['trade_offers_sent']);
});
And this is what it returns:
{
trade_offers_sent: [
{
tradeofferid: '3974708687',
accountid_other: 82613664,
message: 'test message',
expiration_time: 1587017229,
trade_offer_state: 9,
items_to_give: [Array],
is_our_offer: true,
time_created: 1585807629,
time_updated: 1585807629,
from_real_time_trade: false,
escrow_end_date: 0,
confirmation_method: 2
}
]
}
But when i'm trying to get value of accountid_other this way:
console.log(body.response['trade_offers_sent'].accountid_other);
it returns undefined
The square brackets [ ... ] within trade_offers_sent indicate that it holds an array and not just a single item (it just happens to be a single item in the array). Thus to obtain you value you are interested in you need to specify the index of the item you want or use a loop to go through it. In this case you want the first item and you can use ['trade_offers_sent'][0] to obtain it.
Trying to construct a request body with values from a .csv file, but my points array is not getting updated. I've done console.log() for the points array inside and at the end of the on() function, and the values are there as expected. But I console.log outside of the on() and it says the array is empty.
I know this is a scope issue, but not familiar with Node.js so much, so can't figure it out. Thanks.
// Detect anomalies in your spreadsheet
var points = []
var dict = {}
// Read the .csv file, convert date to Date object and number to float.
readline.createInterface({
input: fs.createReadStream(CSV_FILE),
terminal: false
}).on('line', function(line) {
var row = line.split(",")
dict[new Date(row[0])] = parseFloat(row[1])
points.push(dict)
});
// Create request body for API call
let body = { series: points, granularity: 'hourly' }
// Make the call
anomalyDetectorClient.entireDetect(body)
.then((response) => {
for (item in response.isAnomaly) {
if (item) {
console.log("An anomaly was detected from the series.")
console.log("Value: " + response.expectedValues[response.indexOf(item)])
}
}
}).catch((error) => {
console.log(error)
})
UPDATE:
I'm trying to move the async function into the on(), so the points[] has values in it...but there is a bad body in the request, my points array is taking an accumulative dictionary instead of a new dictionary each time it pushes. So that needs to be fixed first, before I can look again at the un-updated points[] outside of the last on().
Current code, I moved the API call into the last on() function (previously it was outside of it, with an await before it):
async function main() {
let CSV_FILE = './request-data.csv'
// Detect anomalies in your spreadsheet
var points = []
// Read the .csv file
await readline.createInterface({
input: fs.createReadStream(CSV_FILE),
terminal: false
}).on('line', function(line) {
var row = line.split(",")
// Convert date to Date object and number to float.
var date = new Date(row[0])
var dict = {}
dict[date] = parseFloat(row[1])
points.push(dict)
console.log(points)
}).on('close', function() {
// Create request body for API call
let body = { series: points, granularity: 'hourly' }
console.log("Body series: " + body.series.timestamp + "Body granularity: " + body.granularity)
// Make the call
anomalyDetectorClient.entireDetect(body)
.then((response) => {
for (item in response.isAnomaly) {
if (item) {
console.log("An anomaly was detected from the series.")
console.log("Value: " + response.expectedValues[response.indexOf(item)])
}
}
}).catch((error) => {
console.log(error)
})
})
UPDATE 2:
Using new code in the answer, there is a new error:
Body series: undefinedBody granularity: hourly
{ Error: Time points should be uniformly spaced in time in hourly granularity with 1 gran as interval, ratio of missing points should be less than 10%, between 2018-03-01 00:00:00 and 2018-04-16 00:00:00 there should be at least 994 points, but got 47 points. What does this means?
Confused because the body object looks good, it was printed with the error:
{ Error: Time points should be uniformly spaced in time in hourly granularity with 1 gran as interval, ratio of missing points should be less than 10%, between 2018-03-01 00:00:00 and 2018-04-16 00:00:00 there should be at least 994 points, but got 47 points.
at new RestError (C:\Users\v-wiazur\Desktop\Anomaly Detector\node_modules\#azure\ms-rest-js\dist\msRest.node.js:1399:28)
at C:\Users\v-wiazur\Desktop\Anomaly Detector\node_modules\#azure\ms-rest-js\dist\msRest.node.js:2494:37
at process._tickCallback (internal/process/next_tick.js:68:7)
code: 'InvalidSeries',
statusCode: 400,
request:
WebResource {
streamResponseBody: false,
url:
'https://winonaanomalydetector.cognitiveservices.azure.com/anomalydetector/v1.0/timeseries/entire/detect',
method: 'POST',
headers: HttpHeaders { _headersMap: [Object] },
body:
'{"series":[{"timestamp":"2018-03-01T00:00:00.000Z","value":32858923},{"timestamp":"2018-03-02T00:00:00.000Z","value":29615278},{"timestamp":"2018-03-03T00:00:00.000Z","value":22839355},{"timestamp":"2018-03-04T00:00:00.000Z","value":25948736},{"timestamp":"2018-03-05T00:00:00.000Z","value":34139159},{"timestamp":"2018-03-06T00:00:00.000Z","value":33843985},{"timestamp":"2018-03-07T00:00:00.000Z","value":33637661},{"timestamp":"2018-03-08T00:00:00.000Z","value":32627350},{"timestamp":"2018-03-09T00:00:00.000Z","value":29881076},{"timestamp":"2018-03-10T00:00:00.000Z","value":22681575},{"timestamp":"2018-03-11T00:00:00.000Z","value":24629393},{"timestamp":"2018-03-12T00:00:00.000Z","value":34010679},{"timestamp":"2018-03-13T00:00:00.000Z","value":33893888},{"timestamp":"2018-03-14T00:00:00.000Z","value":33760076},{"timestamp":"2018-03-15T00:00:00.000Z","value":33093515},{"timestamp":"2018-03-16T00:00:00.000Z","value":29945555},{"timestamp":"2018-03-17T00:00:00.000Z","value":22676212},{"timestamp":"2018-03-18T00:00:00.000Z","value":25262514},{"timestamp":"2018-03-19T00:00:00.000Z","value":33631649},{"timestamp":"2018-03-20T00:00:00.000Z","value":34468310},{"timestamp":"2018-03-21T00:00:00.000Z","value":34212281},{"timestamp":"2018-03-22T00:00:00.000Z","value":38144434},{"timestamp":"2018-03-23T00:00:00.000Z","value":34662949},{"timestamp":"2018-03-24T00:00:00.000Z","value":24623684},{"timestamp":"2018-03-25T00:00:00.000Z","value":26530491},{"timestamp":"2018-03-26T00:00:00.000Z","value":35445003},{"timestamp":"2018-03-27T00:00:00.000Z","value":34250789},{"timestamp":"2018-03-28T00:00:00.000Z","value":33423012},{"timestamp":"2018-03-29T00:00:00.000Z","value":30744783},{"timestamp":"2018-03-30T00:00:00.000Z","value":25825128},{"timestamp":"2018-03-31T00:00:00.000Z","value":21244209},{"timestamp":"2018-04-01T00:00:00.000Z","value":22576956},{"timestamp":"2018-04-02T00:00:00.000Z","value":31957221},{"timestamp":"2018-04-03T00:00:00.000Z","value":33841228},{"timestamp":"2018-04-04T00:00:00.000Z","value":33554483},{"timestamp":"2018-04-05T00:00:00.000Z","value":32383350},{"timestamp":"2018-04-06T00:00:00.000Z","value":29494850},{"timestamp":"2018-04-07T00:00:00.000Z","value":22815534},{"timestamp":"2018-04-08T00:00:00.000Z","value":25557267},{"timestamp":"2018-04-09T00:00:00.000Z","value":34858252},{"timestamp":"2018-04-10T00:00:00.000Z","value":34750597},{"timestamp":"2018-04-11T00:00:00.000Z","value":34717956},{"timestamp":"2018-04-12T00:00:00.000Z","value":34132534},{"timestamp":"2018-04-13T00:00:00.000Z","value":30762236},{"timestamp":"2018-04-14T00:00:00.000Z","value":22504059},{"timestamp":"2018-04-15T00:00:00.000Z","value":26149060},{"timestamp":"2018-04-16T00:00:00.000Z","value":35250105}],"granularity":"hourly"}',
query: undefined,
formData: undefined,
withCredentials: false,
abortSignal: undefined,
timeout: 0,
onUploadProgress: undefined,
onDownloadProgress: undefined,
proxySettings: undefined,
operationSpec:
{ httpMethod: 'POST',
path: 'timeseries/entire/detect',
urlParameters: [Array],
requestBody: [Object],
responses: [Object],
serializer: [Serializer] } },
response:
{ body:
'{"code":"InvalidSeries","message":"Time points should be uniformly spaced in time in hourly granularity with 1 gran as interval, ratio of missing points should be less than 10%, between 2018-03-01 00:00:00 and 2018-04-16 00:00:00 there should be at least 994 points, but got 47 points."}\n',
headers: HttpHeaders { _headersMap: [Object] },
status: 400 },
body:
{ code: 'InvalidSeries',
message:
'Time points should be uniformly spaced in time in hourly granularity with 1 gran as interval, ratio of missing points should be less than 10%, between 2018-03-01 00:00:00 and 2018-04-16 00:00:00 there should be at least 994 points, but got 47 points.' } }
Your array is getting updated. If you do console.log(points) inside your line event handler, you will see it accumulate date each time.
The issue is that you are looking at the array in the wrong place, before it has been populated. The readline interface is asynchronous. So, you call readline.createInterface() and set your event handler for the line event and then your code just keeps on running. You are immediately calling anomalyDetectorClient.entireDetect() before the readline operation has done it's job.
The solution is to wait until the readline interface is done reading the whole file and until your points array is fully populated before you try to use the points array.
Here's one way to do that, where you process the points array in the close event handler for the readline interface:
// Detect anomalies in your spreadsheet
var points = [];
var dict = {};
// Read the .csv file, convert date to Date object and number to float.
readline.createInterface({
input: fs.createReadStream(CSV_FILE),
terminal: false
}).on('line', function(line) {
var row = line.split(",");
let point = {
timestamp: new Date(row[0]),
value: parseFloat(row[1])
};
dict[point.date] = point.value;
points.push(point);
console.log(points);
}).on('close', function() {
// now we're done reading the file
console.log(points); // all the points are here
// now process the points
// Create request body for API call
let body = { series: points, granularity: 'hourly' };
// Make the call
anomalyDetectorClient.entireDetect(body).then((response) => {
for (let item in response.isAnomaly) {
if (item) {
console.log("An anomaly was detected from the series.")
console.log("Value: " + response.expectedValues[response.indexOf(item)])
}
}
}).catch((error) => {
console.log(error)
});
}).on('error', function(err) {
// handle errors here
console.log(err);
});
FYI, are you really sure you should be using item in response.isAnomaly? in is NOT for arrays, it's for properties of objects. It sorta, kinda works for arrays, but it can also not work lots of times. for/of is built specifically for arrays as in for (let item of response.isAnomaly) {...}. Also, for an array, in gets you the index of the value, not the array value. of gets you the array value which is usually what you want.
I cannot get quickreplies to work in node-wit messenger.js example.
I tried may things including:
1) Updated this line of code Our bot actions (messenger.js):
const actions = { send({sessionId}, {text,quickreplies})
2) And Updated this line of code Our bot actions (messenger.js):
return fbMessage(recipientId, text,quickreplies)
3) Updated my custom action in messenger.js :
getWelcome({context, entities})
{
context.welcome = "how are you. Please select from the options below";
context.welcome.quickreplies = [
{
title: 'Choice A',
content_type: 'text',
payload: 'empty'
},
{
title: 'Choice B',
content_type: 'text',
payload: 'empty'
},
]
return context;
},
4) I tried so many permutations. I cant get it to work with node-wit messenger.js example. The quick repliess are not displayed I searched and read all documentation
5) Can you help with this and also exactly how to retrieve the quick reply selected in messenger.js
Thanks
Sorry if it is late, but I guess you were looking for this:
send(request, response) {
const {sessionId, context, entities} = request;
let {text, quickreplies} = response;
if(text.substring(0,6) === IDENTIFY_PAYLOAD){
text = text.substring(6); // It is a payload, not raw text
} else {
text = {"text": text};
}
if(typeof quickreplies !== "undefined"){
text.quick_replies = response.quickreplies
.map(x => { return {
"title": x, "content_type": "text", "payload": "empty"}
});
}
}
What I did was sending a payload with a string that identifies it is not raw text (That's why I use an identifier for a payload), then in the send action I receive the two parameters request and response, and I get their attributes. Finally, I convert the payload params using a routine which I find on internet and that in fact works well to map the quick replies.
I have the following JavaScript to populate dropdown list using select2 https://select2.github.io/
It works fine, and populates the list on the first load of the page.
From then on it does not refresh the list even when data is added because it only does the AJAX call once. Even if I reload the page, the dropdown list is not refreshed and the AJAX call is not triggered (unless I close and reopen the browser, then the AJAX call is fired)
Is there a way to undertake the ajax call each time the dropdown is opened. I tried the .on("select2-open") option but didn't have any luck.
Sorry JavaScript is not something I know much about.
$("#Location").select2({
placeholder: "Select a known location", // Placeholder text
allowClear: true, //Allows deselection of chosen address
ajax: {
url: '/AlertInterface/NewAlertLocations', // Where we want the ajax to call
dataType: 'json', // The datatype we are expecting to be returned
type: "GET", //Just a get method
//Data: allows us to pass a parameter to the controller
data: function (query) {
console.log(query)
return { search: query.term }
},
//processes the results from the JSON method and gives us the select list
processResults: function (data) {
console.log(data)
return {
results: JSON.parse(data)
};
}
}
});
EDIT:
I did try to use
$("#Location").on("select2:open", function () { $("#Location").select2(); })
but that didn't help. :-(
You have a syntax error in your code.
Please check the below code,
$("#Location").select2({
placeholder: "Select a known location", // Placeholder text
allowClear: true, //Allows deselection of chosen address
ajax: {
url: '/AlertInterface/NewAlertLocations', // Where we want the ajax to call
dataType: 'json', // The datatype we are expecting to be returned
type: "GET", //Just a get method
//Data: allows us to pass a parameter to the controller
data: function (query) {
console.log(query)
return { search: query.term }
},
//processes the results from the JSON method and gives us the select list
processResults: function (data) {
console.log(data)
return {
results: JSON.parse(data)
};
}
}
});
Trying to get Select2 to remove an item and figure out why it keeps adding a new tag on update.
Using Select2.JS V3.5
Followed ActiveAdmin / Select2 example
When I try to delete an item, it does not remove it. It also ends up combining the tag list to a new STRING creating a new tag. i.e. If I have ["play", "doe"] and I update another field, it creates a new tag called "play doe" resulting in ["play", "doe", "play doe"]. This continues every time I update.
Here's my JS code
// Generated by CoffeeScript 1.9.3
$(document).ready(function() {
$('.tagselect').each(function() {
var placeholder, saved, url;
placeholder = $(this).data('placeholder');
url = $(this).data('url');
saved = $(this).data('saved');
$(this).select2({
tags: true,
placeholder: placeholder,
minimumInputLength: 3,
allowClear: true,
multiple: true,
debug: true,
initSelection: function(element, callback) {
saved && callback(saved);
},
ajax: {
url: url,
dataType: 'json',
data: function(term) {
return {
q: term
};
},
results: function(data) {
return {
results: data
};
}
},
createSearchChoice: function(term, data) {
if ($(data).filter((function() {
return this.text.localeCompare(term) === 0;
})).length === 0) {
return {
id: term,
text: term
};
}
}
});
});
});
Saw https://github.com/mbleigh/acts-as-taggable-on/issues/676
adding the block in my model, fixes the formtastic bug where all tags where coming in as a flat string vs a comma separated string. Monkey Patch for now.
class MyModel < ActiveRecord::Base
...
def tag_list
super.to_s
end
end