split json into carousel cards - javascript

I get the results from a JSON file and I want to display it in carousel,
how can I do it?
Here is the code:
var req = http.request(options, function (res) {
console.log('STATUS: ' + res.statusCode);
if (res.statusCode !== 201) {
session.send("Sorry, service is not reachable at the moment, please try again later");
}
//session.send(res.statusCode.toString());
var chunks = [];
res.on("data", function (chunk) {
chunks.push(chunk);
var json = chunk.toString();
var graph = JSON.parse(json);
var attachmentList = [];
for (var i = 0; i < graph.clauses.length; i++) {
var obj = graph.clauses[i];
console.log(obj);
var clause_id;
var clause_text;
for (var key in obj) {
clause_id = key;
clause_text = obj[key].toString();
// session.send(clause_id+"<br>"+clause_text);
}
let card = new botbuilder_1.HeroCard(session)
.title(clause_id)
.subtitle(clause_text)
.buttons([botbuilder_1.CardAction.imBack(session, 'Mark as Relevant', 'Mark as Relevant')]);
let msg = new botbuilder_1.Message(session);
msg.attachmentLayout(botbuilder_1.AttachmentLayout.carousel);
msg.attachments([card]);
session.send(msg);
// session.endDialog(msg);
}
});
});
Here is the screenshot of the results:

You're sending a message on each iteration of the for loop, and each message only has one attachment. Try sending one message after the for loop and give that message the whole list of attachments.
var attachmentList = [];
for (var i = 0; i < graph.clauses.length; i++) {
var obj = graph.clauses[i];
console.log(obj);
var clause_id;
var clause_text;
for (var key in obj) {
clause_id = key;
clause_text = obj[key].toString();
// session.send(clause_id+"<br>"+clause_text);
}
let card = new botbuilder_1.HeroCard(session)
.title(clause_id)
.subtitle(clause_text)
.buttons([botbuilder_1.CardAction.imBack(session, 'Mark as Relevant', 'Mark as Relevant')]);
attachmentList.push(card);
}
let msg = new botbuilder_1.Message(session);
msg.attachmentLayout(botbuilder_1.AttachmentLayout.carousel);
msg.attachments(attachmentList);
session.send(msg);

Related

App Script create array from email string

Using app scripts I'm trying to extract all the email addresses from email messages and put them in an array. From my console.log messages, I'm getting stuck because it looks like instead of an array I just get a string. i'm not too familiar with javascript. Any help would be great. I'm looking for an array of email address. The methods of message.get() return a string. I want to split out the email address and create a single, unified array.
var ui = SpreadsheetApp.getUi();
function onOpen(e){
ui.createMenu("Gmail Manager").addItem("Get Emails by Label", "getGmailEmails").addToUi();
}
function getGmailEmails(){
var label = GmailApp.getUserLabelByName("MyLabel");
var threads = label.getThreads();
var fullArray = [];
for(var i = threads.length - 1; i >=0; i--){
var messages = threads[i].getMessages();
for (var j = 0; j <messages.length; j++){
var message = messages[j];
if (message.isUnread()){
fullArray.push(extractDetails(message));
}
}
}
console.log("FullArray:"+fullArray);
for(var i=0; i<fullArray.length; i++){
console.log("printing array " + i + ": "+fullArray[i])
}
}
function extractDetails(message){
var dateTime = message.getDate();
var subjectText = message.getSubject();
var senderDetails = message.getFrom();
var ccEmails = message.getCc();
var replyEmail = message.getReplyTo();
var toEmail = message.getTo();
var emailArray = []
var senderArray = senderDetails.split(',');
var ccArray = ccEmails.split(',');
var replyArray = replyEmail.split(',');
var toArray = toEmail.split(',');
for (var i =0 ; i<toArray.length; i++){
console.log("toArray Loop"+ i + " : "+ toArray[i]);
emailArray.push([toArray[i]]);
}
for (var i =0 ; i<ccArray.length; i++){
console.log("ccArray Loop"+ i + " : "+ ccArray[i]);
emailArray.push([ccArray[i]]);
}
console.log("Email Array: "+ emailArray);
var activeSheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
activeSheet.appendRow([dateTime, senderDetails, subjectText, ccEmails,replyEmail,toEmail,emailArray]);
return emailArray;
}
I think the problem is just the console output. If you change console.log("Email Array: "+ emailArray); to console.log("Email Array: ", emailArray);, then it shows an array of arrays. You could simplify your extract method as follows:
function extractDetails(message) {
/* ... */
var senderDetails = message.getFrom();
var ccEmails = message.getCc();
var replyEmails = message.getReplyTo();
var toEmails = message.getTo();
let emailArray = [senderDetails, ccEmails, replyEmails, toEmails].reduce(
(array, string) => {
//remove names (like "Name <name#company.com>") and filter empty values
let emails = string
.split(/\s*,\s*/)
.map(e => e.replace(/.*?([^#<\s]+#[^#\s>]+).*?/g, "$1"))
.filter(Boolean);
if(emails.length > 0)
return array.concat(emails)
return array
}, []);
/* ... */
}

How to send a variable back from foreground.js to background.js

I tried to send my variable back from foreground.js to background.js by using an unchanged variable, and it works. Now I can't send some data that I use my AddEventListener syntax to store the data into the variable to call its back to background.js here are my code on foreground.js
foreground.js
console.log("foreground.js injected");
var pswdBtns = [];
let hrefLists = [];
var data = {};
var i;
function readUUID(){
var navigator_info = window.navigator;
var screen_info = window.screen;
var uid = navigator_info.mimeTypes.length;
uid += navigator_info.userAgent.replace(/\D+/g, '');
uid += navigator_info.plugins.length;
uid += screen_info.height || '';
uid += screen_info.width || '';
uid += screen_info.pixelDepth || '';
return uid;
}
async function passwordProtected(pointerList){
const date = new Date();
const uid = readUUID();
alert("You are in dangerous on \'"+ pointerList.title + "\' row = " + pointerList.id.slice(20));
data = {
"Webtitle": pointerList.href,
"Title": pointerList.title,
"Time": date.toString(),
"UUID": uid
}
console.log("foreground = ", data);
return data;
}
console.log("Start loop")
//This function made for collect each id in passwordShowPasswordButton
for(i = 0; i<=pswdBtns.length; i++){
if(document.querySelector("#passwordShowPasswordButton_"+ i) == null){
console.log("This is your limit!!");
}
else{
hrefLists[i] = document.querySelector("#passwordWebsitelink_"+ i);
pswdBtns[i] = document.querySelector("#passwordShowPasswordButton_"+ i);;
data = pswdBtns[i].addEventListener('click', passwordProtected.bind(pswdBtns[i], hrefLists[i]));
console.log(hrefLists[i].title); /* Title VARCHAR(30) */
console.log(hrefLists[i].href); /* Website VARCHAR(50) */
}
}
console.log("End");
and these are my code on background.js
background.js
const edgePswd = "edge://settings/passwords";
const settingPage = "edge://settings/";
chrome.tabs.onActivated.addListener(async (tab) => {
await chrome.tabs.get(tab.tabId, (current_tab_info) => {
var pswdPageChecked = 1;
while(pswdPageChecked < 2) {
if (edgePswd == current_tab_info.url) {
chrome.tabs.executeScript(null, { file: "/extension/foreground.js" }, (data) => {
console.log("Coming to foreground");
console.log(data);
});
pswdPageChecked++;
}
}
});
});
It would be a pleasure if someone can figure this.

Error with setTimeout() function in for loop

I have the following script that I need to adjust so that each iteration has a one second pause before or after it executes the loop (it doesn't really matter which as long as the lag is there). I tried to add the setTimeout() function into the Try section of my code but it is still consistently failing. I also have tried to use "let" instead of "var" in the for loop but that failed as well. Any advice on how to add it in would be very appreciated. I'm having trouble finding an example of a similar setTimeout() function within a for loop online.
var ZB_DataExtension = 'C7_Unsubscribe_Response';
var ZB_DataExtension_Response = 'C7_Unsubscribe_Response';
var ZB_DataExtension_Logs = 'C7_CustUnsubscribe_Logs';
//Endpoint
var zeroBounceFullUrl = 'https://api.commerce7.com/v1//customer/CUST_ID';
//Extract results from Data Extension using DE key
var results = DataExtension.Init(ZB_DataExtension).Rows.Retrieve();
var updateDE_ZB = DataExtension.Init(ZB_DataExtension_Response);
var logsDE_ZB = DataExtension.Init(ZB_DataExtension_Logs);
var today = Format(Now(), "YYYY-MM-DD ");
for (var i = 0; i < results.length; i++ ) {
var item = results[i];
var zeroBounceUrlItem = "";
var ZB_Status = "";
var currentDateTime = Now();
try{
setTimeout(() => (
zeroBounceUrlItem = String(zeroBounceFullUrl).split("CUST_ID").join(String(item.C7_CustID));
var req = new Script.Util.HttpRequest(zeroBounceUrlItem);
req.emptyContentHandling = 0;
req.retries = 3;
req.continueOnError = true;
req.contentType = "application/json";
req.method = "PUT";
var payload='{"emailMarketingStatus": "Unsubscribed"}'
req.postData = payload ;
var resp = req.send();
var returnStatus= resp.returnStatus;
updateDE_ZB.Rows.Update({C7_API_Answer:String(returnStatus),ValidationDate:currentDateTime,ValidationUrl:String(zeroBounceUrlItem),EmailAddress:String(item.EmailAddress)}, ["C7_CustID"], [String(item.C7_CustID)]);
if (returnStatus==0) {
updateDE_ZB.Rows.Update({C7_API_Answer:String("Success"),ValidationDate:currentDateTime,ValidationUrl:String(zeroBounceUrlItem),EmailAddress:String(item.EmailAddress)}, ["C7_CustID"], [String(item.C7_CustID)]);
}
else {
//ZB_Status = String("ERRO ZB API Call");
//var responseJson = Platform.Function.ParseJSON(String(resp.content));
updateDE_ZB.Rows.Update({C7_API_Answer:String("Failure"),ValidationDate:currentDateTime,ValidationUrl:String(zeroBounceUrlItem),EmailAddress:String(item.EmailAddress)}, ["C7_CustID"], [String(item.C7_CustID)]);
}
var randomID = Platform.Function.GUID();
logsDE_ZB.Rows.Add({log_guid:String(randomID),C7_CustID:String(item.C7_CustID),Status:String("Success"),ValidationDate:currentDateTime,ValidationUrl:String(zeroBounceUrlItem)});
), 1000*i}
catch (err) {
var randomID = Platform.Function.GUID();
ZB_Status = String("ERRO AMPScript");
logsDE_ZB.Rows.Add({log_guid:String(randomID),C7_CustID:String(item.C7_CustID),Status:String("Failure"),ValidationDate:currentDateTime,ValidationUrl:String(zeroBounceUrlItem)});
}
}
</script>
Your loop will execute the right number of times and at the right interval, but the value of the variable item inside the timeout might not be what you expect.
Try this:
for (var i = 0; i < results.length; i++ ) {
(function(i){
setTimeout(function(){
var item = results[i];
var zeroBounceUrlItem = "";
var ZB_Status = "";
var currentDateTime = Now();
try{
zeroBounceUrlItem = String(zeroBounceFullUrl).split("CUST_ID").join(String(item.C7_CustID));
var req = new Script.Util.HttpRequest(zeroBounceUrlItem);
req.emptyContentHandling = 0;
req.retries = 3;
req.continueOnError = true;
req.contentType = "application/json";
req.method = "PUT";
var payload='{"emailMarketingStatus": "Unsubscribed"}'
req.postData = payload ;
var resp = req.send();
var returnStatus= resp.returnStatus;
updateDE_ZB.Rows.Update({C7_API_Answer:String(returnStatus),ValidationDate:currentDateTime,ValidationUrl:String(zeroBounceUrlItem),EmailAddress:String(item.EmailAddress)}, ["C7_CustID"], [String(item.C7_CustID)]);
if (returnStatus==0) {
updateDE_ZB.Rows.Update({C7_API_Answer:String("Success"),ValidationDate:currentDateTime,ValidationUrl:String(zeroBounceUrlItem),EmailAddress:String(item.EmailAddress)}, ["C7_CustID"], [String(item.C7_CustID)]);
}
else {
//ZB_Status = String("ERRO ZB API Call");
//var responseJson = Platform.Function.ParseJSON(String(resp.content));
updateDE_ZB.Rows.Update({C7_API_Answer:String("Failure"),ValidationDate:currentDateTime,ValidationUrl:String(zeroBounceUrlItem),EmailAddress:String(item.EmailAddress)}, ["C7_CustID"], [String(item.C7_CustID)]);
}
var randomID = Platform.Function.GUID();
logsDE_ZB.Rows.Add({log_guid:String(randomID),C7_CustID:String(item.C7_CustID),Status:String("Success"),ValidationDate:currentDateTime,ValidationUrl:String(zeroBounceUrlItem)});
catch (err) {
var randomID = Platform.Function.GUID();
ZB_Status = String("ERRO AMPScript");
logsDE_ZB.Rows.Add({log_guid:String(randomID),C7_CustID:String(item.C7_CustID),Status:String("Failure"),ValidationDate:currentDateTime,ValidationUrl:String(zeroBounceUrlItem)});
}
}, i*1000);
})(i);
}

How can I convert CSV data to JSON data?

I wrote the code that gets data from a device.
The form of the data is csv. Below is the data value.
1,1.635946,1.636609,1.640240,1.636091
2,1.642825,1.640267,1.639013,1.636568
3,1.636835,1.636022,1.637664,1.637144
4,1.641332,1.641166,1.637950,1.640760
5,1.636041,1.637437,1.640702,1.633678
But I want the data in json format. So I tried using an online converter and got the following values:
[
{
"1": 2,
"1.635946": 1.642825,
"1.636609": 1.640267,
"1.640240": 1.639013,
"1.636091": 1.636568
},
{
"1": 3,
"1.635946": 1.636835,
"1.636609": 1.636022,
"1.640240": 1.637664,
"1.636091": 1.637144
}
]
What parts of my code should I modify if I want to get these values?
Below is my code.
var Timer;
var i = 0 ;
setTimeout(function(){
Timer = setInterval(function(){
port.write(meascommand+'\n');
i++;
if(i==5){
clearInterval(Timer);
}
},5000);
},1000);
port.on('data',function(devicevalue){
arrayvalue = devicevalue.toString();
eachvalue = arrayvalue.split(';');
var results = [];
var index = i ;
var ch0value = eachvalue[0] ;
var ch1value = eachvalue[1] ;
var ch2value = eachvalue[2] ;
var ch3value = eachvalue[3] ;
results[0] = index ;
results[1] = ch0value ;
results[2] = ch1value ;
results[3] = ch2value ;
results[4] = ch3value ;
console.log(results);
fs.appendFile(file,results+'\r\n',function(err){
if(err)
console.log(err);
});
});
};
function processFiles(files) {
var file = files[0];
var reader = new FileReader();
reader.onload = function (e) {
var output = document.getElementById("fileOutput");
var texto = e.target.result;
csvJSON(texto);
};
reader.readAsText(file);
}
function csvJSON(csv) {
var lines = csv.split("\n");
var result = [];
var headers;
for (var i = 0; i < lines.length; i++) {
headers = lines[i].split("\n");
}
var cont = 0;
for (var i = 0; i < lines.length; i++) {
var obj = {};
var currentline = lines[i].split("\n");
for (var j = 0; j < headers.length; j++) {
obj[cont] = currentline[j];
}
cont++;
result.push(obj);
}
return JSON.stringify(result); //JSON
}
Try to use below code. Credits go to: https://gist.github.com/iwek/7154578
NOTE: split(","). If lines contains , snippet won't work. But thats not the case in your data, as far as I can see.
function csvJSON(csv){
var lines=csv.split("\n");
var result = [];
var headers=lines[0].split(",");
for(var i=1;i<lines.length;i++){
var obj = {};
var currentline=lines[i].split(",");
for(var j=0;j<headers.length;j++){
obj[headers[j]] = currentline[j];
}
result.push(obj);
}
//return result; //JavaScript object
return JSON.stringify(result); //JSON
}

Get data out from callback inside query

I am trying to get data out from query inside the query. I tried everything without success.
getvideos() {
var sectionHolder = [];
var ids = [];
var titles = [];
var videos = [];
var challengeCl = Parse.Object.extend("Challenges");
var query = new Parse.Query(challengeCl);
query.find().then((data) => {
for(var key = 0; key < data.length; key++) {
var object = data[key];
var videoid = object.id;
var title = object.get('title');
ids.push(videoid)
titles.push(title)
var video = Parse.Object.extend('Videos');
var queryv = new Parse.Query(video);
queryv.equalTo('challengeid', videoid);
queryv.find().then(
(video) => {
videos.push(video); //i want to get this data out from this scope
});
sectionHolder.push({title: title, data: videos}); // <---- i want to put videos data in data
}
console.log(sectionHolder);
this.setState({listData: sectionHolder});
});
}
I read parse documentation but there is nothing related to this.

Categories

Resources