repeat(1000, function() {
console.log("REPEAT");
var i = 1;
var max = 1;
var mS = ini.parse(fs.readFileSync(__dirname + '/XXX/Temp/MS.ini', 'utf-8'));
var array = new Array();
while(i<=max){
if(typeof mS[i] != 'undefined'){
if(mS[i]['10'] == true){
array.push(i);
console.log(array);
}else{
console.log("ERROR");
}
i++;
max++;
}else{ //if undefined
if(mS[i+1] == 'undefined' && mS[i+2] == 'undefined') i++;
else{ i++; max++; }
}
}//while
});
It works without repeat function. (waitjs module)
Also repeat works without while loop.
I am trying to become reconciled to node.js (single thread). But i do not know, where is the mistake?
var i = 1;
var max = 1;
while(i<=max){
This condition is valid only once.
Update (due to #user949300 comments):
How many times your loop executes depends on your ini file. I recommend you to step into your code with a debugger.
Related
My bot has a skip and stop commands it gives this error when I try that command
Cannot read property '706142720527171634' of undefined
I also re-wrote the code,
These are the two commands' codes
if(msg.content === 'r!' + 'skip'){
server.dispatcher = connection.play(ytdl(server.queue[0],{filter: "audioonly"}));
var server = servers[msg.guild.id];
if (server.dispatcher) server.dispatcher.end();
}
if(msg.content === 'r!' + 'stop'){
var server = server[msg.guild.id];
if(msg.guild.voice.connection){
for(var i = server.queue.length -1; i >=0; i--){
server.queue.splice(i, 1);
}
Here, you used server instead of servers: server[msg.guild.id];.
The following should work:
if(msg.content === 'r!' + 'skip'){
server.dispatcher = connection.play(ytdl(server.queue[0],{filter: "audioonly"}));
var server = servers[msg.guild.id];
if (server.dispatcher) server.dispatcher.end();
}
if(msg.content === 'r!' + 'stop'){
var server = servers[msg.guild.id];
if(msg.guild.voice.connection){
for(var i = server.queue.length -1; i >=0; i--){
server.queue.splice(i, 1);
}
I have been working on this code to read through a PDF file and grab the keywords of company names and display them. It all works fine except for one part where the else if statement outputs one line (which is what I want) but the else statement that comes last, which is supposed to output "Not Found" loops 20 times where I only want it to display the output only once instead of 20 times.
I have tried numerous ways by going through the internet to change my code, most recommended that forEach is not a proper way to do things and that I should use for instead but when I do, I just can't seem to get it right.
l.forEach(function(element) {
var j = element['fullTextAnnotation']['text'];
var sd = 'SDN. BHD.';
var bd = 'BHD.';
var et = 'Enterprise';
var inc = 'Incorporated';
var regtoken = new natural.RegexpTokenizer({pattern:/\n/});
var f = regtoken.tokenize(jsondata);
for(o = 0 ; o < f.length; o++){
var arrayline1 = natural.LevenshteinDistance(sd,f[o],{search:true});
var arrayline2 = natural.LevenshteinDistance(bd,f[o],{search:true});
var arrayline3 = natural.LevenshteinDistance(et,f[o],{search:true});
var arrayline4 = natural.LevenshteinDistance(inc,f[o],{search:true});
var arrayline5 = natural.LevenshteinDistance(nf,f[o],{search:false});
var onedata1 = arrayline1['substring'];
var onedata2 = arrayline2['substring'];
var onedata3 = arrayline3['substring'];
var onedata4 = arrayline4['substring'];
var onedata5 = arrayline5['substring'];
if (onedata1 === sd)
{
tokends = f[o];
break;
} else if(onedata3 === et)
{
tokends = f[o];
break;
} else if(onedata2 === bd)
{
tokends = f[o];
console.log(tokends);
break;
} else if(onedata4 === inc)
{
tokends = f[o];
console.log(tokends);
break;
} else{
console.log("Not Found");
return false;
}
}
});
I wish to get only one "Not Found" output for the else statement rather than it looping it for 20 times over. Hopefully I could get some insight to this problem. Thank you.
You are actually using the .forEach Array's method which actually take a function in parameter.
The keywork return breaks actually the loop of the current function executed.
For example :
const data = ['Toto', 'Tata', 'Titi'];
data.forEach(function(element) {
console.log(element);
if (element === 'Tata') {
return false;
}
});
// Will print everything :
// Print Toto
// Print Tata
// Print Titi
for (let element of data) {
console.log(element);
if (element === 'Tata') {
return false;
}
}
// Will print :
// Print Toto
// Print Tata
I'm creating a nodejs application with socket.IO, for some home automation. In app.js I receive calls from the interface which works fine, I send those calls to another file/raspberry pi. this also works fine, for basic things like: turn on/off, change color etc. I created this fade() function which fades between the led colors, when I call this function(which keep looping as it should) it only loops, and stops receiving other socket calls.
i just need a method to run the fade() function at the same time, or another(better?) approach.
underneath my code:
let Gpio = require('pigpio').Gpio;
let socket = require('socket.io-client')('http://localhost:8080');
let delay = require('delay');
let ledRed = new Gpio(27, {mode: Gpio.OUTPUT});
let ledGreen = new Gpio(17, {mode: Gpio.OUTPUT});
let ledBlue = new Gpio(22, {mode: Gpio.OUTPUT});
let fadeState = false;
socket.on('fadeClient',function(data){
if (fadeState === false){
fadeState = data;
// fade()
}
console.log("fade " + data);
fadeState = data;
console.log("data");
});
function setRGBVal(red, blue, green){
// console.log('red: ' +red);
// console.log('blue: ' +blue);
// console.log('green: ' +green);
ledRed.pwmWrite(0);
ledGreen.pwmWrite(0);
ledBlue.pwmWrite(0);
ledRed.pwmWrite(Math.round(red));
ledGreen.pwmWrite(Math.round(blue));
ledBlue.pwmWrite(Math.round(green));
}
function fade(){
console.log("inFade");
while(fadeState === true) {
console.log(fadeState)
for (i = 0; i < 255; i++) {
setRGBVal(i, 0, 0);
delay(500);
if (fadeState === true){
break;
console.log("piemel");
}
}
for (i = 0; i < 255; i++) {
setRGBVal(0, i, 0);
delay(500);
if (fadeState === true){
break;
console.log("piemel");
}
}
for (i = 0; i < 255; i++) {
setRGBVal(0, 0, i);
delay(500);
if (fadeState === true){
break;
console.log("piemel");
}
}
}
};
Node.js is single-threaded so a delay() will block the whole application, as you discovered. Use setTimeout() instead, just like in frontend web applications. Something like this:
fadeNext(0);
function fadeNext(i) {
setRGBVal(i, 0, 0);
if (i < 255) {
setTimeout(function() { fadeNext(i+1); }, 500);
}
}
So I have written this code :
manager.getInventoryContents(730, 2, true, (err,inventory,currencies) => {
if (err){
console.log(err)
} else {
console.log("Create order for : " + orderitemname.length + " items.")
var otn = orderitemname.length -1;
while (otn !== -1) {
var li= inventory.length - 1;
while (li !== -1){
if (inventory[li].market_name === orderitemname[otn]){
console.log("Add item to trade " + orderitemname[otn]);
li = li -1;
otn = otn -1;
} else {
console.log("ERR !!! ITEM NOT IN INVENTORY !!! " + orderitemname[otn]);
//Change Order Status To Failed !!
n = n-1;
otn = -1;
li = -1;
}
}
}
}
})
So what is happening is that the process is calling this event multiple times (since it is in a while loop), and the node module is ignoreing it saying :
Error: The request is a duplicate and the action has already occurred in the past, ignored this time
So is there a way I can just call the event once, save it to a variable or something and then use the data multiple time ?
You can wrap everything in a new context and initiate whatever variable you need there. Then, the variable will be accessible from within your callback function.
Something like this:
(() => {
let ctx_data = 0;
manager.getInventoryContents(730, 2, true, (err,inventory,currencies) => {
console.log(++ctx_data);
});
})();
I have a client script which is doing two things:
Calculate total weight of sales order on add of line
Copy tax code from custom field to native field
The script deploys correctly when adding lines in the UI from the sublist but when using the "add multiple" button and selecting and adding multiple lines at once, the script does not trigger. Here is the script as I have it written so far (I have 2 versions, one which is validateLine and one which is postSourcing).
Validate Line:
function calculateTotalWeight(type){
var lines = nlapiGetLineItemCount('item');
var totalWeight = 0 ;
for(var i=1; i< lines+1 ; i++){
var weight = nlapiGetLineItemValue('item', 'custcol_itemweight', i);
var quantity = nlapiGetLineItemValue('item', 'quantity', i);
var weightTimesQuantity = weight * quantity;
totalWeight = totalWeight + weightTimesQuantity ;
}
nlapiSetFieldValue('custbody_items_total_weight', totalWeight);
}
function validateLine(type){
var taxableCustomer = nlapiGetFieldValue('custbody_taxable');
if (taxableCustomer == 'T'){
var customTax = nlapiGetCurrentLineItemValue(type,'custcol_taxcode');
nlapiLogExecution('DEBUG', 'Custom Tax Value',customTax);
nlapiSetCurrentLineItemValue('item','taxcode',customTax,true,true);
}
return true;
}
postSourcing:
function calculateTotalWeight(type){
var lines = nlapiGetLineItemCount('item');
var totalWeight = 0 ;
for(var i=1; i< lines+1 ; i++){
var weight = nlapiGetLineItemValue('item', 'custcol_itemweight', i);
var quantity = nlapiGetLineItemValue('item', 'quantity', i);
var weightTimesQuantity = weight * quantity;
totalWeight = totalWeight + weightTimesQuantity ;
}
nlapiSetFieldValue('custbody_items_total_weight', totalWeight);
}
function postSourcing(type, name)
{
if(type === 'item' && name === 'item')
{
var custcol_taxcode = nlapiGetCurrentLineItemValue('item', 'custcol_taxcode');
var line = nlapiGetCurrentLineItemIndex(type);
{
nlapiSetCurrentLineItemValue('item', 'taxcode', custcol_taxcode);
}
}
}
How can I get this script to trigger with the add multiple button?
You’ll need to calculate the weight on the recalc event. The following is from a script that works as a scriptable cart/checkout script. It can be deployed in an eCommerce context or the UI context. (i.e. a deployed client script as opposed to a client script attached to a form)
Note:You should set up your tax codes so that they are assigned automatically. It is possible to script those but it's a fair pain to do.
the field custbody_sco_toggle is a checkbox field that keeps the script out of an infinite loop if your recalc scripts might change the order total.
var scriptableCart = (function(){
var cartScript = {};
var isUI = ('userinterface' == nlapiGetContext().getExecutionContext());
var isWeb = !isUI;
function tty(type, title, detail){
var haveWindow = typeof window != 'undefined';
if(isUI && haveWindow && window.console) window.console.log(title, detail);
else if(isWeb || !haveWindow) nlapiLogExecution(type, title, (detail || '') +' '+entranceId +' '+nlapiGetContext().getExecutionContext()); // this slows down the NS GUI
}
function calculateTotalWeight(type){...}
cartScript.recalc = function(type){
tty("DEBUG", "entered "+ type +" with toggle: "+ nlapiGetFieldValue('custbody_sco_toggle'));
if('F' == nlapiGetFieldValue('custbody_sco_toggle')){
try{
nlapiSetFieldValue('custbody_sco_toggle', 'T', false, true);
if(type == 'item'){
calculateTotalWeight(type);
}
}catch(e){
tty('ERROR', 'In recalc for '+ type, (e.message || e.toString()) + (e.getStackTrace ? (' \n \n' + e.getStackTrace().join(' \n')) : ''));
}finally{
nlapiSetFieldValue('custbody_sco_toggle', 'F');
}
}
};
return cartScript;
})();