test('transform', () => {
const code = [
...
' write (i < 10) do',
...
].join('\n')
expect(transform(code)).toBe([
...
' while (i < 10) { ',
...
].join('\n'))
})
Image with yelloc diff
both line are identical for me
Mean a small diff, solution
test('transform', () => {
const code = [
...
' write (i < 10) do',
...
].join('\n')
expect(transform(code)).toBe([
...
' while (i < 10) { ',
...
''
].join('\n'))
})
references
What does "## -1 +1 ##" mean in Git's diff output?
Related
I am writing a script that is designed to take in an array and replace a designated row in a csv(buffer) then output a csv(buffer) in nodejs. However, I have found that whenever I have the following combination of characters: ",\n", it is doubling the comma. I have tried using \r instead or \n, but the system I am importing the csv has issues with the \r. I also found that by adding an extra whitespace: ", \n it prevents the double comma, but again, the system I'm importing the final result into won't accept the extra space. Does anyone know what is causing the extra comma and/or a way to not get the extra comma?
Script that replaces CSV row:
node.on('input', function(msg) {
node.rowNumber = msg.rowNumber || config.rowNumber || 0; //Row being replaced.
node.newRow = msg.newRow || config.newRow; //New Row Array or Comma Separated String
var payload = msg.file || config.file || RED.util.getMessageProperty(msg, "payload"); //File path or buffer.
if (!Buffer.isBuffer(payload)) {
payload = payload.replace('\\', '/');
payload = fs.readFileSync(payload);
}
if (!Array.isArray(this.newRow)) {
node.newRow = node.newRow.split(',');
}
var dataArray = [];
var csvArr = [];
const readable = new Stream.Readable()
readable._read = () => {}
readable.push(payload)
readable.push(null)
readable.pipe(csv())
.on('data', function (data) {
dataArray.push(data);
})
.on('end', function(){
csvArr.push(Object.keys(dataArray[0]));
dataArray.forEach((item, i) => {
csvArr.push(_.values(item));
});
if (node.rowNumber == 0) {
csvArr.push(node.newRow);
}
else {
csvArr.splice(node.rowNumber - 1, 1, node.newRow);
}
var finalCSV = csvArr.join('\n');
msg.payload = Buffer.from(finalCSV);
node.send(msg); //Returns the msg object
});
});
Input:
[
`""{
""""actions"""":{
""""validation"""":[
],
""""reconciliation"""":[
]
},
""""enforce_all_required_fields"""":"""""""",
""""form_history"""":""""12c2acda35980131f98acf2a39c1aafe"""",
""""form_id"""":""""228"""",
""""options"""":[
],
""""record_action"""":""""both"""",
""""secondary_form_history"""":"""""""",
""""secondary_form_id"""":""""0"""",
""""secondary_form_name"""":"""""""",
""""secondary_is_tier1_form"""":"""""""",
""""selected_columns"""":[
""""field_9326"""",
""""field_3742_first"""",
""""field_3742_last"""",
""""field_9325"""",
""""field_9327"""",
],
""""skip_headers"""":"""""""",
""""target_match_type"""":""""""""
}""`
]
Undesired output:
"{
""actions"":{
""validation"":[
],
""reconciliation"":[
]
},
""enforce_all_required_fields"":"""",,
""form_history"":""12c2acda35980131f98acf2a39c1aafe"",,
""form_id"":""228"",,
""options"":[
],
""record_action"":""both"",,
""secondary_form_history"":"""",,
""secondary_form_id"":""0"",,
""secondary_form_name"":"""",,
""secondary_is_tier1_form"":"""",,
""selected_columns"":[
""field_9326"",,
""field_3742_first"",,
""field_3742_last"",,
""field_9325"",,
""field_9327"",,
],
""skip_headers"":"""",,
""target_match_type"":""""
}"
Notice the double commas?
I have file users.json, which contain, among others, data like this:
[
{
"nick": "user123",
"active24": 579
...
}, {
"nick": "nick",
"active24": 259
...
}
]
I want to make leaderboard, showing top 10 users nicks (from uknown max value of users), based on ther "active24" (from biggest to smallest). I can do it using array, but problem is that bot can't send it using vk-io (reason is not important, so i don't describe it much here, but please, do not save final input as array, but as variables or etc). I want output like:
Var_top1 = `${nick}: ${active24}`;
Var_top2 = `${nick}: ${active24}`;
Var_top3 = `${nick}: ${active24}`;
...
Var_top10 = `${nick}: ${active24}`;
P.S sorry for my bad English
do you want something like this?
const data = [
{
nick: "user111",
active24: 579
},
{
nick: "nick222",
active24: 0
},
{
nick: "nick333",
active24: 84
},
{
nick: "nick444",
active24: 9459
}
];
const sorted = data.sort((a, b) => b.active24 - a.active24);
console.log(JSON.stringify(sorted));
//[{"nick":"nick444","active24":9459},{"nick":"user111","active24":579},{"nick":"nick333","active24":84},{"nick":"nick222","active24":0}]
const top1 = sorted[0];
const top2 = sorted[1];
const top3 = sorted[2];
const top4 = sorted[3];
Order the array using a methodology such as
array.prototype.sort.
Once the array has all members sorted, you just need to print them array[0].nick + ":" + array[0].active24
let jsonObject = [
{
"nick": "user123",
"active24": 579
},
{
"nick": "user234",
"active24": 1
},
{
"nick": "nick",
"active24": 259
}
];
// Orders the array
jsonObject.sort((firstElem, secondElem) => {
if (firstElem.active24 > secondElem.active24) return 1;
if (firstElem.active24 < secondElem.active24) return -1;
return 0;
})
// Prints the entire ordered array
console.log(JSON.stringify(jsonObject, null, 2));
// Prints the nick and the active24 value
for (let i = 0; i < jsonObject.length; i++) {
console.log(jsonObject[i].nick + ":" + jsonObject[i].active24);
}
i know this error is already solved but in another form i could't solve my error:
if(msg.content.startsWith(`${prefix}roles`)) {
const spaces = ' ';
const roles = [];
msg.guild.roles.filter(r => r.name !== '#everyone').forEach(c => {
let list = roles.push(`${c.name} ${spaces.substring(c.name.length)} ${c.members.size} member`);
if(c.members.size < 2) roles.push(`${c.name} ${spaces.substring(c.name.length)} ${c.members.size} member`);
if(c.members.size >= 2) roles.push(`${c.name} ${spaces.substring(c.name.length)} ${c.members.size} members`);
});
msg.channel.send(`\`\`\` ${roles.join('\n')} \`\`\``);
}
});
Thanks.
Well that's probably because you are pushing to the array 2 times for each role
Once here:
let list = roles.push(${c.name} ${spaces.substring(c.name.length)} ${c.members.size} member);
And another time after that with the if statements,
After you change it to one time, it should fix it unless you have like 100 roles, and in which case you can just add the option split: true inside of message.channel.send
https://discord.js.org/#/docs/main/stable/typedef/MessageOptions
https://discord.js.org/#/docs/main/stable/typedef/SplitOptions
if (msg.content.startsWith(`${prefix}roles`)) {
const spaces = ' ';
const roles = [];
msg.guild.roles.filter(r => r.name !== '#everyone').forEach(role => {
let string = `${c.name} ${spaces.substring(c.name.length)} ${c.members.size} member`;
if (role.members.size >= 2) {
string += "s";
}
roles.push(string);
});
//all those escape characters look bad, just concat strings
msg.channel.send("```\n" + roles.join('\n') + "\n```", { split: true });
}
I have a message which is lets say about 2k characters so how can i split the message so that it will send the messages in fragments
Example my Help command exceeded 2000 characters
if (!args[0]) {
// Load guild settings (for prefixes and eventually per-guild tweaks)
const settings = message.settings;
// Filter all commands by which are available for the user's level, using the <Collection>.filter() method.
const myCommands = message.guild ? client.commands.filter(cmd => client.levelCache[cmd.conf.permLevel] <= level) : client.commands.filter(cmd => client.levelCache[cmd.conf.permLevel] <= level && cmd.conf.guildOnly !== true);
// Here we have to get the command names only, and we use that array to get the longest name.
// This make the help commands "aligned" in the output.
const commandNames = myCommands.keyArray();
const longest = commandNames.reduce((long, str) => Math.max(long, str.length), 0);
let currentCategory = "";
let output = `= Command List =\n\n[Use ${settings.prefix}help <commandname> for details]\n`;
const sorted = myCommands.array().sort((p, c) => p.help.category > c.help.category ? 1 : p.help.name > c.help.name && p.help.category === c.help.category ? 1 : -1 );
sorted.forEach( c => {
const cat = c.help.category.toProperCase();
if (currentCategory !== cat) {
output += `\n== ${cat} ==\n`;
currentCategory = cat;
}
output += `${settings.prefix}${c.help.name}${" ".repeat(longest - c.help.name.length)} :: ${c.help.description}\n`;
});
message.channel.send(output, {code:"asciidoc"});
} else {
// Show individual command's help.
let command = args[0];
if (client.commands.has(command)) {
command = client.commands.get(command);
if (level < client.levelCache[command.conf.permLevel]) return;
message.channel.send(`= ${command.help.name} = \n${command.help.description}\nusage::${command.help.usage}`, {code:"asciidoc"});
}
}
any easy way to split the message
I saw something https://stackoverflow.com/a/52863304/12843955 but didnt get it
I tried
let output = `= Command List =\n\n[Use ${settings.prefix}help <commandname> for details]\n`;
let output1 =`` , output2 = ``;
if (output.length < 1900 ) output += `${settings.prefix}${c.help.name}${" ".repeat(longest - c.help.name.length)} :: ${c.help.description}\n`;
else if (output.length > 1900){
output1 += `${settings.prefix}${c.help.name}${" ".repeat(longest - c.help.name.length)} :: ${c.help.description}\n`;
}
else if(output1.length >1900 && output.length > 1900 ) output2 += `${settings.prefix}${c.help.name}${" ".repeat(longest - c.help.name.length)} :: ${c.help.description}\n`;
message.channel.send(output, {code:"asciidoc"});
if(output1 !== ``) message.channel.send(output1, {code:"asciidoc"});
if(output2 !== ``) message.channel.send(output2, {code:"asciidoc"});
and its working but still any better solution than this ?
I am looking at this example. How this can be done using Raphael for below example ?
Raphael("canvas", function () {
var win = Raphael._g.win,
doc = win.document,
hasTouch = "createTouch" in doc,
M = "M",
L = "L",
d = "d",
COMMA = ",",
// constant for waiting doodle stop
INTERRUPT_TIMEOUT_MS = hasTouch ? 100 : 1,
// offset for better visual accuracy
CURSOR_OFFSET = hasTouch ? 0 : -10,
paper = this,
path = "", // hold doodle path commands
// this element draws the doodle
doodle = paper.path(path).attr({
"stroke": "rgb(255,0,0)"
}),
// this is to capture mouse movements
tracker = paper.rect(0, 0, paper.width, paper.height).attr({
"fill": "rgb(255,255,255)",
"fill-opacity": "0.01"
}),
active = false, // flag to check active doodling
repath = false, // flag to check if a new segment starts
interrupt; // this is to connect jittery touch
tracker.mousedown(function () {
interrupt && (interrupt = clearTimeout(interrupt));
active = true;
repath = true;
});
tracker.mousemove(function (e, x, y) {
// do nothing if doodling is inactive
if (!active) {
return;
}
// Fix for Raphael's touch xy bug
if (hasTouch &&
(e.originalEvent.targetTouches.length === 1)) {
x = e.clientX +
(doc.documentElement.scrollTop || doc.body.scrollTop || 0);
y = e.clientY +
(doc.documentElement.scrollLeft || doc.body.scrollLeft || 0);
e.preventDefault();
}
// Insert move command for a new segment
if (repath) {
path += M + (x + CURSOR_OFFSET) + COMMA +
(y + CURSOR_OFFSET);
repath = false;
}
path += L + (x + CURSOR_OFFSET) + COMMA +
(y + CURSOR_OFFSET); // append line point
// directly access SVG element and set path
doodle.node.setAttribute(d, path);
});
// track window mouse up to ensure mouse up even outside
// paper works.
Raphael.mouseup(function () {
interrupt && (interrupt = clearTimeout(interrupt));
// wait sometime before deactivating doodle
interrupt = setTimeout(function () {
active = false;
}, INTERRUPT_TIMEOUT_MS);
});
Above code is copied from https://stackoverflow.com/a/17781275/1595858
To create a smooth line through several points, use Raphael's Catmull-Rom extension to SVG paths. See: http://raphaeljs.com/reference.html#Paper.path .
// Creating a line:
var line = paper.path("M x0 y0 R x1 y1 x2 y2 x3 y3 x4 y4");
// Adding next point:
line.attr("path", line.attr("path") + " x5 y5");
The easiest way to smoothen the lines in your case (using Raphael) is to use the Raphael._path2curve function.
The place where you are doing doodle.node.setAttribute(d, path); replace it with the following line, thus replacing all line segments with curves.
doodle.node.setAttribute(d, Raphael._path2curve(path));
Note that this will result in degradation of performance. There is a huge scope of improvement of this by realtime converting path to curves instead of converting the entire path every time.