Can anyone explain how to work with conversationThreading-js? - javascript

I am trying to use this conversationThreading-js code to group emails into threads but documentation is scant and/or I am not able to understand it. Has anyone used this bit of code before or used the JWZ email conversation threading algorithm on which it is based?
This is where I am so far:
using Electron I load and parse a local mbox using node-mbox and node-mailparser
I build an array of javascript objects which have key value pairs of messageId, inReplyTo and references.
Using example code from the test file for this lib I try to build the threads but apparently I am not doing it right. I get no errors but I also get no threads (and my test mbox does contain threaded conversations).
Maybe I am misunderstanding what the result should be? Or I am just "doing it wrong"? My end goal here is to be able to display the resulting threads in some sort of directed graph using D3 – but that is not going to happen if I can't get the data set up correctly.
function makeThread(emails) {
var thread = jwz.messageThread().thread(emails.map(
function (message) {
return jwz.message(message.subject, message.messageId, message.references);
}
));
console.log('thread',thread);
}

It's pretty unclear how it works, but I managed to write some code that prints the "thread tree":
function recurse(node, level) {
level = level || 0;
let prefix = '\t'.repeat(level);
(node.children || []).forEach(function(child) {
child.children = child.children || [];
console.log(prefix, level ? '' : '-', child.message ? child.message.subject : '??', `[${ child.children.length }]`);
return recurse(child, level + 1);
});
}
recurse(jwz.messageThread().thread(messages));
(messages is an array of jwz.message() objects, similar to how you're creating it)

Related

API can't handle my request because of template literals to make the API dynamic

For a school project, I have to make a quiz app. It is possible to chose a difficulty, a category and an amount of desired questions. The api is a url which can be modified easily by changing some values. For example: https://quizapi.io/api/v1/questions?apiKey=MYAPIKEY&limit=15&difficulty=hard&category=cms. If you would just change the php to code in the url, you would get a max amount of 15 questions on a hard difficulty about HTML and CSS. I think you see where this is going.
However. I have setup my code that the difficulty, category and amount are stored in localstorage and they are fetched when the quiz is started. At the moment, I get the amout of questions I desire but I can't change my difficulty or category because probably Template Literals aren't working in a fetch api.. Maybe someone can give me an idea or maybe I'm making a mistake in my current code
let storageDif = localStorage.getItem("mD");
console.log(storageDif.toString());
let storageCat = localStorage.getItem("mC");
console.log(storageCat);
let geslideVragen = localStorage.getItem("slider");
let MAX_VRAGEN = geslideVragen;
console.log(MAX_VRAGEN);
let vragen = [];
fetch(`https://quizapi.io/api/v1/questions?apiKey=kAFKilHLeEcfLkGE2H0Ia9uTIp1rYHDTIYIHs9qf&limit=15&difficulty=hard&category=${storageCat}`)
.then((res) => {
return res.json();
})
.then((loadedQuestions) => {
for (let i = 0; i < MAX_VRAGEN; i++) {
vragen = loadedQuestions;
console.log(vragen[i].question);
};
startGame();
})
.catch( err => {
console.error(err);
});
I'm sure you found out by now that you're only interpolating the category. To get it to be correctly, you'd need to do this:
`https://quizapi.io/api/v1/questions?apiKey=kAFKilHLeEcfLkGE2H0Ia9uTIp1rYHDTIYIHs9qf&limit=${MAX_VRAGEN}&difficulty=${storageDif}&category=${storageCat}`
That being said, you should never expose your API keys this way, because especially for cloud services, it can easily cost you over 5 digits in a single day if someone decided to use it for their own means. There are plenty of scrapers that scour GitHub for exposed API keys for illegitimate uses.
Also, should apply a check to make sure all values are present using an if() statement so that it doesn't fetch anything if a value is undefined.

How to properly import a javascript file/function API to a React.js app?

Hey Stackoverflow :) Long time reader, first time poster. To the point:
I'm fairly new to web programming (done much more C# and game programming). I've been given a task that requires me to write a simple React.js app. I am to use an included api.min.js javascript file that includes an "API", that is supposed to sort of mimic a server, has a set of built in functions to fetch data ('/getitem', '/getusers', '/putitem', etc), and mimics lost requests now and then. The API code has been minified and is one single line of some 4500 characters, and sadly i don't think i can include all the code from this file, since it's not mine (and, well it's 4500 chars :P). But some clues: when beautified it starts off like this:
var api = function() {
function t(t) {
for (var e = t.length - 1; e > 0; e--) {
var n = Math.floor(Math.random() * (e + 1)),
r = t[e];
t[e] = t[n], t[n] = r
}
return t
etc...
And ends like this:
etc...
},
setRequestHeaders: function(t, e) {
if ("number" != typeof t && "string" != typeof t && "number" != typeof e && "string" != typeof e) throw new Error("Arguments both header and value must be numbers or strings");
l[t] = e
}
};
return m
};
return {
XMLHttpRequest: y
}
}();
One of the examples included in the file looks like this:
// Example 1:
var x = api.XMLHttpRequest();
x.onreadystatechange = function() {
console.log(x.readyState, x.status, x.responseText);
};
x.open("GET", "/getusers");
x.send();
If i paste the API line and the example code into say, jsfiddle.net, it works fine and gives me the data in a format i would know how to use. But i can't seem to get it to work in my React-project in VScode. Whenever i try to import the file, i get errors of the type
Line 6:7: Expected an assignment or function call and instead saw an expression no-unused-expressions
That would be the line:
t[e] = t[n], t[n] = r
... from the first code example above.
So I'm a bit clueless as to how to proceed atm... Does anyone have any suggestions on how i could include this API in my VScode React.js project and access the functions from the api.min.js file? I feel like there probably is some really simple solution to this, but as i said, i am fairly new to web programming and i still lack some of the fundamentals i think. I've looked around here, google, youtube etc but i can't seem to find what I'm looking for. Might be because i don't really know what i'm looking for :)
If anyone could help i would be ever grateful!
Thanks

Cannot get the full json with request json

When I am actually entering the XXXX YYYY, then I am getting the players json code in my html page (around 150 values).
But when I am trying to use a function on the players list it somewhy does not contain all the 150 values and the try throws me into the catch error part, where I can see that players json has only 100 players inside there.
Any idea what could be the problem?
if(yourID === "XXXX" && targetID === "YYYY"){
return players;
}
try{
if(isUserAlive(yourID)){
if(targetID === ""){
return userTargetInfo(yourID);
}
var checkForMatch = getUserTarget(yourID);
if(checkForMatch === targetID){
killTarget(targetID);
getUser(yourID).targetID = getTargetTarget(targetID);
addScore(yourID);
return userTargetInfo(yourID);
//return getTargetTargetStats(targetID);
}else{
return "INVALID";
}
}else{
return "DEAD"
}
}catch(err){
console.log("Error",console.log(players))
return "INVALID"
}
Edit: Since I had no time, I created 2 websites and divided the database into 2 different databases, so it would work under 100 people on each. Did not have time to fix the error at this point. So I won't be choosing the solution to that since I won't be trying that any time soon.
Thank you for all your help!
Check the link api that you are using , it might have pagination integrated with it . in that case i will return certain number of object 1st and then you can re-request to get next batch . Most likely they might have a option to change the no of object returned (sometimes with max value)
I'm pretty sure body is returned as a string. Try changing it to an object so you can work with it easier.
Change:
players = body;
to:
players = JSON.parse(body);
I'm not sure the rest of your code, but you may want to add var on your players variable declaration because this looks like the first time you are setting it.
Research: namespace collisions
If you are still having issues, edit your question to include the response you are getting from console.log(JSON.parse(body));. You will be able to get more helpful answers. Personally, I am curious to see the keys such as:
{ query:
{ count: 1,
created: '2017-04-23T22:03:31Z',
lang: 'en-US',
results: { channel: [Object] } } }
If it's paginated, you should see some kind of cursor key in there, or prev and next along with some kind of totalCount.
Hope this helps.

Using i18next to build a menu

I have a page using i18next on node.
In the translation files, there are translations (duh) for various things (it's like a database for little helper snippets)
now i want to build a page, where the user can view them individually.
idea
i want to access the loaded xx-translation.json and make a (dropdown?) menu containing all the entries in one namespace
{
"category": {
"subcategory": { // i want to get ["bla", "blu", "bli"] as result
"bla" : "ble",
"blu" : "blo",
"bli" : "bly"
}
}
}
i'm thinking about a simple loop like
var amountOfEntries = translationJSON.category.subcategory.length;
for (var i = 0; i < amountOfEntries; i++) {
$('#menu'). //append that entry somehow
}
tldr questions
is there a way to access the translation.json inside my "normal" js and count the number of entries?
and
how can i build a menu piece by piece with the entries? (this is bonus, i think i'd manage to do that. the main question is the first one)
thanks
Check out lodash.js for some good collection utility functions. You can iterate over the object with something like:
_.each(subcategory, function(val, key){
$(".menu").append("<li>" + key + ": " + val + "</li>");
});
is that helpful?
UPDATE
After clarifying your question in the comments above, I think what you're looking for is either getResource() or getResourceBundle().

Error during synchronous write using Node.js

I have written code that parses a dictionary returned from Firebase containing images encoded using base64. I want it to simply write these images to file, and it does, but I receive the following error after my writes finish:
smalloc.cc:280: void node::smalloc::SliceOnto(const v8::FunctionCallbackInfo<v8::Value>&): Assertion `end <= source_len' failed.
This is my code:
// Iterate through each key in each page if each request
for (var key in request) {
var obj = request[key];
if (typeof (obj) == "object") {
for (var prop in obj) {
item++;
if(obj.hasOwnProperty(prop)) {
switch (prop) {
case "img":
var media = new ReceivedMedia(obj[prop]);
var filename = transaction.tid + "-" + item + "." + media.extension;
filename = filename.slice(10);
require('fs').writeFileSync(filename, media.b64, 'base64', function(err) {
if (err) throw err;
});
break;
}
}
}
}
}
My images come out fine, but the error is a little weird and I would prefer to not to occur. Would anyone have an idea as to why this is happening? That would be super helpful :)
Note: ReceivedMedia is a class I defined as:
function ReceivedMedia(media) {
this.b64 = media.b64;
this.extension = media.extension;
this.posx = media.posx;
this.posy = media.posy;
}
Side question: If I use writeFile instead of writeFileSync one of my images is corrupted and the other contains no data. If after that happens I run my node script again, the files save correctly. I would also like some explanation as to why that happens, from my understanding one of these is synchronous (writeFileSync I am guessing) and the other is asynchronous (writeFile I am assuming).
A Google search for your error message description found this discussion of the issue in io.js and this discussion in node.js and it sounds like it is a bug that has been fixed (not sure if the fix has been released in a full build yet).
The node.js fix is here.
If you were desparate to fix it now in your own build, you'd have to apply the fix to your own code tree and rebuild it. Otherwise, you'll have to investigate or inquire when this fix will get into an official release (I'm not personally sure how that process works for node.js).

Categories