NodeJs Readline value put into array - arrays

I'm using NodeJS readline module to read from a text file. Its returning every line to the console however I want it to add the returned lines to an array. This is the code I got so far, but its not working. I thought the rd.on acted as a sortof for loop but it doesn't look like it. Any help would be appreciated!
function getinfomation2(){
var firstfile = [];
var secondfile = [];
var countvar = 0;
readline = require('readline');
var rd = readline.createInterface({
input: fs.createReadStream('../FixtureProfiles/CFIP1.json'),
output: process.stdout,
terminal: false
});
// Add fixture details from file to array to later be called
rd.on('line', function(line) {
// if fails console.log(line) returns line in console
firstfile(countvar) = line;
console.log(firstfile(countvar))
countvar = countvar +1;
});
}

firstfile(countvar) = line is incorrect.
Array access operators are [ and ] (see Array docs on MDN).
Also check out Array.push:
firstfile.push(line)

Related

modifying object in componentDidMount() [duplicate]

I’ll start with the code:
var s = ["hi"];
console.log(s);
s[0] = "bye";
console.log(s);
Simple, right? In response to this, the Firefox console says:
[ "hi" ]
[ "bye" ]
Wonderful, but Chrome’s JavaScript console (7.0.517.41 beta) says:
[ "bye" ]
[ "bye" ]
Have I done something wrong, or is Chrome’s JavaScript console being exceptionally lazy about evaluating my array?
Thanks for the comment, tec. I was able to find an existing unconfirmed Webkit bug that explains this issue: https://bugs.webkit.org/show_bug.cgi?id=35801 (EDIT: now fixed!)
There appears to be some debate regarding just how much of a bug it is and whether it's fixable. It does seem like bad behavior to me. It was especially troubling to me because, in Chrome at least, it occurs when the code resides in scripts that are executed immediately (before the page is loaded), even when the console is open, whenever the page is refreshed. Calling console.log when the console is not yet active only results in a reference to the object being queued, not the output the console will contain. Therefore, the array (or any object), will not be evaluated until the console is ready. It really is a case of lazy evaluation.
However, there is a simple way to avoid this in your code:
var s = ["hi"];
console.log(s.toString());
s[0] = "bye";
console.log(s.toString());
By calling toString, you create a representation in memory that will not be altered by following statements, which the console will read when it is ready. The console output is slightly different from passing the object directly, but it seems acceptable:
hi
bye
From Eric's explanation, it is due to console.log() being queued up, and it prints a later value of the array (or object).
There can be 5 solutions:
1. arr.toString() // not well for [1,[2,3]] as it shows 1,2,3
2. arr.join() // same as above
3. arr.slice(0) // a new array is created, but if arr is [1, 2, arr2, 3]
// and arr2 changes, then later value might be shown
4. arr.concat() // a new array is created, but same issue as slice(0)
5. JSON.stringify(arr) // works well as it takes a snapshot of the whole array
// or object, and the format shows the exact structure
You can clone an array with Array#slice:
console.log(s); // ["bye"], i.e. incorrect
console.log(s.slice()); // ["hi"], i.e. correct
A function that you can use instead of console.log that doesn't have this problem is as follows:
console.logShallowCopy = function () {
function slicedIfArray(arg) {
return Array.isArray(arg) ? arg.slice() : arg;
}
var argsSnapshot = Array.prototype.map.call(arguments, slicedIfArray);
return console.log.apply(console, argsSnapshot);
};
For the case of objects, unfortunately, the best method appears to be to debug first with a non-WebKit browser, or to write a complicated function to clone. If you are only working with simple objects, where order of keys doesn't matter and there are no functions, you could always do:
console.logSanitizedCopy = function () {
var args = Array.prototype.slice.call(arguments);
var sanitizedArgs = JSON.parse(JSON.stringify(args));
return console.log.apply(console, sanitizedArgs);
};
All of these methods are obviously very slow, so even more so than with normal console.logs, you have to strip them off after you're done debugging.
This has been patched in Webkit, however when using the React framework this happens for me in some circumstances, if you have such problems just use as others suggest:
console.log(JSON.stringify(the_array));
Looks like Chrome is replacing in its "pre compile" phase any instance of "s" with pointer to the actual array.
One way around is by cloning the array, logging fresh copy instead:
var s = ["hi"];
console.log(CloneArray(s));
s[0] = "bye";
console.log(CloneArray(s));
function CloneArray(array)
{
var clone = new Array();
for (var i = 0; i < array.length; i++)
clone[clone.length] = array[i];
return clone;
}
the shortest solution so far is to use array or object spread syntax to get a clone of values to be preserved as in time of logging, ie:
console.log({...myObject});
console.log([...myArray]);
however be warned as it does a shallow copy, so any deep nested non-primitive values will not be cloned and thus shown in their modified state in the console
This is already answered, but I'll drop my answer anyway. I implemented a simple console wrapper which doesn't suffer from this issue. Requires jQuery.
It implements only log, warn and error methods, you will have to add some more in order for it to be interchangeable with a regular console.
var fixedConsole;
(function($) {
var _freezeOne = function(arg) {
if (typeof arg === 'object') {
return $.extend(true, {}, arg);
} else {
return arg;
}
};
var _freezeAll = function(args) {
var frozen = [];
for (var i=0; i<args.length; i++) {
frozen.push(_freezeOne(args[i]));
}
return frozen;
};
fixedConsole = {
log: function() { console.log.apply(console, _freezeAll(arguments)); },
warn: function() { console.warn.apply(console, _freezeAll(arguments)); },
error: function() { console.error.apply(console, _freezeAll(arguments)); }
};
})(jQuery);

Cannot push past 1 element to basic AS3 Array

I am very new to this and hoping it's something that should have been obvious.
When I run the code below, the Array newHole and newArray both return 1 on the trace. Originally the code was built with only the newHole array, but I created the newArray in the hopes of troubleshooting. It did not help. The class for bulletHole contains no extra code so I didn't post that.
Thank you.
import flash.display.*;
import flash.events.*;
import flash.ui.Mouse;
Mouse.hide();
var myReticle:MovieClip;
var holeArray:Array = new Array();
var randomHole:Number = randomNumber(1, 5);
var newHole:bulletHole = new bulletHole();
var newArray:Array = new Array();
stage.addEventListener(MouseEvent.MOUSE_MOVE, followReticle);
stage.addEventListener(MouseEvent.CLICK, myFire);
stage.addEventListener(MouseEvent.CLICK, checkCount);
function followReticle(event:MouseEvent):void
{
myReticle.x = mouseX;
myReticle.y = mouseY;
}
function myFire(int):void
{
stage.addChild(newHole);
newHole.x = myReticle.x;
newHole.y = myReticle.y;
//holeArray.push(newHole);
newHole.gotoAndStop(randomHole);
//trace(holeArray.length);
}
function checkCount(int):void
{
newArray.push("A");
trace(newArray.length);
}
function randomNumber(low:Number=0, high:Number=1):Number
{
return Math.floor(Math.random() * (1+high-low)) + low;
}
Most likely the issue is that the code you've posted is running over and over again. In other words, you have a looping timeline that eventually goes back to the frame that the code you've shown is on.
Whenever that frame is reached, you have the following:
var holeArray:Array = new Array();
Which creates a new array replacing what used to be in that var.
To solve this, you either need to:
take the code out of the timeline (put it in a class file and attach that as the document class of your project)
re-architect your timeline so the first frame is only reached 1 time
put some checks in so that the code only runs the first time the frame is reached.
Here is an example of the latter option:
//just define the array, don't create it
var holeArray:Array;
//if the array is null, create it (it will only be null the first time this code is run
if(!holeArray){
holeArray = new Array();
}
This line is incorrect:
function myFire(int):void {
Because the function is triggered from a mouse event listener it should read:
function myFire(e:MouseEvent):void {
What you are doing is passing a undefined int to the function. Hope this helps.
EDIT: You should delete the clickCount event listener and function as they're not needed.
Also notice that you should move this line to the top of your myFire function or else you will keep replacing this MovieClip instead of creating it again:
var newHole:bulletHole = new bulletHole();

Generation of an array of substring from a string in swift

I have a problem with generation of an array of substrings from a string in the following code
var primers=[String]()
var lengthOfPrimer = 20
var lentghOfText = str1.characters.count
var rest = lentghOfText - lengthOfPrimer
for var i = 0; i <= str1.characters.count; ++i
{
var temp = rest - i
var substring1 = str1.substringWithRange(Range<String.Index>(start: advance(str1.startIndex, i), end: advance(str1.endIndex, -temp)))
primers.append(substring1)
}
In playground I have the following error at the line with the substring1 code – Execution was interrupted: reason: EXC_BAD_INSTRUCTION (code=EXC 1386_INVOP, subcode=0x0.
In spite of error sign, I can see in playground the generated set of substrings in loop, but when I tried to use this code in program this code also did not work, What is wrong? What should I do?
Your error is coming from trying to advance the endIndex.
But how about something a little simpler? (Swift 2)
var first = str1.startIndex
var last = advance(first, 20 - 1, str1.endIndex)
while last != str1.endIndex {
primers.append(str1[first++ ... last++])
}
print("\n".join(primers))
// output:
// ACAAGATGCCATTGTCCCCC
// CAAGATGCCATTGTCCCCCG
// AAGATGCCATTGTCCCCCGG
// AGATGCCATTGTCCCCCGGC
// GATGCCATTGTCCCCCGGCC
// ATGCCATTGTCCCCCGGCCT
// TGCCATTGTCCCCCGGCCTC
// GCCATTGTCCCCCGGCCTCC
// CCATTGTCCCCCGGCCTCCT
// CATTGTCCCCCGGCCTCCTG
// ATTGTCCCCCGGCCTCCTGC
// TTGTCCCCCGGCCTCCTGCT
// ...
Or the for loop way:
for var first = str1.startIndex, last = advance(first, 20 - 1, str1.endIndex);
last != str1.endIndex;
++first, ++last
{
primers.append(str1[first...last])
}
for var i = 0; i <= str1.characters.count; ++i
Without getting into the rest of this code, this for loop is wrong. You are reading past the end of the string because you are using <= when you should be using <.
Also you are calling str1.characters.count in the loop even though you have that value in a variable, which is slow.
Try:
for var i = 0; i < lengthOfText; ++i

How does Protractor executes the function calls. (E2E AngularJS + Protractor + Jasmine)

I am new to protractor and currently experimenting with an internal Angular JS application. In the below snippet of code, I am unable to understand on how Protractor is executing the statements and function calls. The behaviour seems weird OR I am doing something completely wrong. Appreciate all the help.
describe('Describe Function', function()
{
it('Should return a value',function(){
var IndexValue = ' ';
var col_model = element.all(by.repeater('col in renderedColumns'));
var row_model = element.all(by.repeater('row in renderedRows'));
browser.get('URL');
ptor = protractor.getInstance();
var user = element(by.model('login.user_id_1'));
user.sendKeys('demo');
element(by.id('txtusername')).getAttribute('value').then(function(text) {
console.log(text); // This line prints 'demo'
});
var pwd = element(by.model('login.password_1'));
pwd.sendKeys('demo');
var submit = element(by.className('login-submit'));
submit.click();
browser.driver.sleep(1000);
var colCount = element.all(by.repeater('col in renderedColumns')).count(); 
colCount.then(console.log) // This prints '80'
var items = [];
getArrayList();
function getArrayList() // Function to capture all the content of the table in an array
{
console.log('Array List function started');
colCount.then(function(Col_count){
for(var i=0; i < Col_count; ++i){
var grid = browser.findElement(by.repeater('col in renderedColumns').row(i));
grid.getText().then(function(gridValue){
items.push(gridValue.trim());
console.log('For loop')
});
}
});
console.log('Array List function completed');
}
console.log(items); // This prints []
getGridValue('Prospect');
function getGridValue(name)
{
console.log('Inside grid value');
}
});
});
When I execute the above code, even before the browser is invoked and the application is launched, first 4 lines (specified below) are printed on the console. What surprises me is the fact that point 1 and 3 are part of the function call which indeed is printing point 7. Looks like all the independent "console.log" are executed first and then the "console.log" associated with "element." statements are executed. Its really confusing. Plz let me know where am I going wrong. Thanks.
OUTPUT ON THE CONSOLE
1. Array List function started
2. []
3. Array List function completed
4. Inside grid value
5. demo
6. 80
7. For loop
For loop
For loop
For loop
.... so on until the loop ends
At first: well, protractor does, what you told it to do... You may read a bit about promises and async JavaScript.
I try to explain a bit, please understand, that explaining everything would take a lot of time.
Starting protractor calls your script (spec). The most lines you wrote before calling getArrayList() are function calls which return promises. This means, the function is called, and when ready, it's callback function gets called (e.g.: then(...))
An example:
var colCount = element.all(by.repeater('col in renderedColumns')).count();
colCount.then(console.log) // This prints '80'
In this two lines you are searching the DOM for every element which can be located by col in renderedColumns, then, if ready, count them and return the value to its callback then, afterwards print it via console.log.
But all of this takes time, and this is the reason why console.log('Array List function started'); gets printed before colCount.then(console.log).
Hope I could help a bit, as mentioned before, you may read a bit about promises.

Cannot push to an array with Node EventEmitter .on method

Using readLine to read from a file I have:
fs = require 'fs'
readline = require 'readline'
stream = require 'stream'
instream = fs.createReadStream './test.txt'
outstream = new stream
outstream.readable = true
outstream.writable = true
rl = readline.createInterface({input: instream, output: outstream, terminal: false})
arr = []
rl.on 'line', (line) ->
arr.push line
console.log arr
I'm trying to push each line to an array, but the callback in rl.on doesn't seem to complete the push() method, but if I replace the push with console.log it will print every line of the file. I realise there are probably far better ways of achieving the same outcome, but this is an experiment that failed and I don't understand why.
Why is the .on callback not able to push the line to an array?

Resources