Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
LP0 ON FIRE
Jan 25, 2006

beep boop

Subjunctive posted:

In that case [w.IDNum][0][1] should be "groceryStore.jpg", if I'm understanding your post correctly, so I suspect you're not interpreting the error correctly, or else we're misunderstanding each other about what to print here. :shrug:

See my edit. It reports it as undefined, then I click the error button again in inspector and it shows that they are defined as ["default", "groceryStore.jpg"]. No interval is running.

edit: It looks like clicking that error button unfolds something below my console.log and shows what it is, but below that it says undefined.



This is what it looks initially before clicking the red error button again:

LP0 ON FIRE fucked around with this message at 16:46 on Jul 22, 2014

Adbot
ADBOT LOVES YOU

qntm
Jun 17, 2009
The value "undefined" is the value returned by your call to console.log().

console.log() doesn't return a value; it prints a value out to the console, then returns nothing (i.e. undefined).

Try typing "keyTimesAndImages[0]" at the console, all on its own.

LP0 ON FIRE
Jan 25, 2006

beep boop

qntm posted:

The value "undefined" is the value returned by your call to console.log().

console.log() doesn't return a value; it prints a value out to the console, then returns nothing (i.e. undefined).

Try typing "keyTimesAndImages[0]" at the console, all on its own.

Thanks. I get ["default", "groceryStore.jpg"]

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

Is this while you're stopped at the error, or later? If that's the value when it's evaluating that expression, I'm stumped.

LP0 ON FIRE
Jan 25, 2006

beep boop
It's not like a breakpoint that stops at the error. The page run continues to run normally even if times start. Specifically it says:

TypeError: 'undefined' is not an object (evaluating 'keyTimesAndImages[window.IDNum][0]')

And I just tested, even if window.IDNum doesn't change later down the line, I still get the error. It shouldn't have mattered anyway though.


Update - I test for both of these before evaluating and it works without errors:

code:
if(keyTimesAndImages[window.IDNum] && keyTimesAndImages[window.IDNum][0]){
I was only testing if(keyTimesAndImages[window.IDNum] == 'undefined)

LP0 ON FIRE fucked around with this message at 17:40 on Jul 22, 2014

Analytic Engine
May 18, 2009

not the analytical engine
Is there a reason to use == instead of ===?

People reference Doug Crawford's opinion and I've seen arguments for always using ===, but I don't know about edge cases.

LP0 ON FIRE
Jan 25, 2006

beep boop

Analytic Engine posted:

Is there a reason to use == instead of ===?

People reference Doug Crawford's opinion and I've seen arguments for always using ===, but I don't know about edge cases.

Definitely! This is very important. Just look up the differences. http://stackoverflow.com/questions/523643/difference-between-and-in-javascript

The case being if you're doing a strict vs non-strict comparison.

quote:

JavaScript has both strict and type-converting equality comparison. For strict equality the objects being compared must have the same type and:

Two strings are strictly equal when they have the same sequence of characters, same length, and same characters in corresponding positions.
Two numbers are strictly equal when they are numerically equal (have the same number value). NaN is not equal to anything, including NaN. Positive and negative zeros are equal to one another.
Two Boolean operands are strictly equal if both are true or both are false.
Two objects are strictly equal if they refer to the same Object.
Null and Undefined types are == (but not ===). [I.e. Null==Undefined (but not Null===Undefined)]

It's also important to mention that === is only true if the operands are the same type. == is used for abstract comparisons and converts it to the same type before making a comparison.

LP0 ON FIRE fucked around with this message at 18:25 on Jul 22, 2014

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

Analytic Engine posted:

Is there a reason to use == instead of ===?

People reference Doug Crawford's opinion and I've seen arguments for always using ===, but I don't know about edge cases.

Use === when you want to make sure the operands are the same type. If you don't care whether a variable holds a 2 or a "2", you can use ==. Even then, I would probably use something like if(Number(variable) === 2)

Analytic Engine
May 18, 2009

not the analytical engine

LP0 ON FIRE posted:

Definitely! This is very important. Just look up the differences. http://stackoverflow.com/questions/...d-in-javascript

The case being if you're doing a strict vs non-strict comparison.

quote:

JavaScript has both strict and type-converting equality comparison. For strict equality the objects being compared must have the same type and:

Two strings are strictly equal when they have the same sequence of characters, same length, and same characters in corresponding positions.
Two numbers are strictly equal when they are numerically equal (have the same number value). NaN is not equal to anything, including NaN. Positive and negative zeros are equal to one another.
Two Boolean operands are strictly equal if both are true or both are false.
Two objects are strictly equal if they refer to the same Object.
Null and Undefined types are == (but not ===). [I.e. Null==Undefined (but not Null===Undefined)]

It's also important to mention that === is only true if the operands are the same type. == is used for abstract comparisons and converts it to the same type before making a comparison.

Wheany posted:

Use === when you want to make sure the operands are the same type. If you don't care whether a variable holds a 2 or a "2", you can use ==.

Thanks, that backs up what I've read and tested out. I'm trying to improve my Javascript habits and it sounds like thinking of === first is a good one. I'll use == for specific cases like user input and reading text files.

Wheany posted:

Even then, I would probably use something like if(Number(variable) === 2)

Didn't think of this, even more specificity could come in handy.

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

Analytic Engine posted:

Didn't think of this, even more specificity could come in handy.

Switch-case uses strict comparison, so switch(Number(variable)) is probably the most common use case for me, actually

Analytic Engine
May 18, 2009

not the analytical engine

Wheany posted:

Switch-case uses strict comparison, so switch(Number(variable)) is probably the most common use case for me, actually

Cool, I also didn't know about === in switch ( ).

And after testing, it looks like leaving out an equality condition in if ( ) will default to trying ==.
code:
if (variable) {
	// Will run for values like
	// 	true, 'true', 1, 2, 'True', 'false', '0', '1', '2'
}
Edit: That is wrong ^^^

Analytic Engine fucked around with this message at 23:27 on Aug 18, 2014

Space Kablooey
May 6, 2009


code:
>> difference
-8.881784197001252e-16
>> difference.toFixed(2)
"-0.00"
>> difference == 0
false
>> Math.round(difference)
-0
:v:


EDIT: Nevermind, got it.

Space Kablooey fucked around with this message at 21:03 on Jul 22, 2014

OddObserver
Apr 3, 2009
^^^
Dunno, but why would you want to? -0.0 is different from 0.0.

Analytic Engine posted:

Cool, I also didn't know about === in switch ( ).

And after testing, it looks like leaving out an equality condition in if ( ) will default to trying ==.
== to what? And at any rate, it's not comparing it with anything; it's using a Boolean conversion. That's actually observable,
since it's always true for objects, regardless of what their values are:
code:
a = {}
a.valueOf = function() { return false; }
if (a) { console.log("yes"); } else { console.log("no") }
>> yes
if (a + 0) { console.log("yes"); } else { console.log("no") }
>> no

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

Analytic Engine posted:

Cool, I also didn't know about === in switch ( ).

And after testing, it looks like leaving out an equality condition in if ( ) will default to trying ==.
code:
if (variable) {
	// Will run for values like
	// 	true, 'true', 1, 2, 'True', 'false', '0', '1', '2'
}

Here's a weird old trick to converting a variable to boolean: !!variable
Also for setting a default value for a variable, you might see somthing like this:

function(setting){
var value = setting || "default value";
}

Analytic Engine
May 18, 2009

not the analytical engine

OddObserver posted:

== to what? And at any rate, it's not comparing it with anything; it's using a Boolean conversion. That's actually observable,
since it's always true for objects, regardless of what their values are:
code:
a = {}
a.valueOf = function() { return false; }
if (a) { console.log("yes"); } else { console.log("no") }
>> yes
if (a + 0) { console.log("yes"); } else { console.log("no") }
>> no

You're right, I was confused. Never tried boolean conversion before.
I had thought these lines were equivalent:
code:
if (variable)       { // Logic }
if (variable==true) { // Logic }
Just ran a test and I had it wrong. This came up because I've been using if(variable==true) and wanted to switch to if(variable===true) or if(variable), and now the difference is pretty clear.


Wheany posted:

Here's a weird old trick to converting a variable to boolean: !!variable
Also for setting a default value for a variable, you might see somthing like this:

function(setting){
var value = setting || "default value";
}

Ha, I saw that when starting Javascript and had no clue. Some tutorials launch right in.

Analytic Engine fucked around with this message at 22:07 on Jul 22, 2014

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe

Subjunctive posted:

That's not my recollection, and I think I was the first person to implement JS exceptions. JScript had a bug where it created the variable in the enclosing function's scope, rather than one that matched the duration of the catch block, which I think is the opposite of what you're describing, but exceptions were always specified to create a new scope chain entry with the identifier bound.

15 years, though, so yeah I'd love a reference if you have one.

I remember it being an off-hand remark by some engineer in #whatwg, #jsapi, or on a mailing list like es-discuss or whatwg. Sorry I don't have a better reference, and my limited attempts to look through the archvies didn't pull up anything.

revmoo
May 25, 2006

#basta
I've been asked to provide a page that generates MD5, SHA1, DES, and 3DES keys to be used in securing a bunch of systems. Is this as bad of an idea as it sounds? Is there a safe method to generate these keys in-browser in a secure way? I'm guessing I can use crypto-js to generate the keys and then pass Math.random values into it or something for entropy, but is this actually going to be safe?

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

revmoo posted:

I'm guessing I can use crypto-js to generate the keys and then pass Math.random values into it or something for entropy, but is this actually going to be safe?

My first guess is that Math.random is worthless for cryptography. My second guess is that maybe you could use mouse movements or something to gather entropy.

But the number 1 rule w/r/t cryptography is "Never roll your own."

Also you can't trust any client-provided values, you have to do the calculation server-side.

revmoo
May 25, 2006

#basta

Wheany posted:

My first guess is that Math.random is worthless for cryptography. My second guess is that maybe you could use mouse movements or something to gather entropy.

But the number 1 rule w/r/t cryptography is "Never roll your own."

Also you can't trust any client-provided values, you have to do the calculation server-side.

Your first guess is also my first guess. I can actually probably trust the client on this one because they are inputting a key for their personal device and they're permitted to override the generated value if they want. But I'm really not sure what a safe way to generate these keys would be, even it's even possible.

Plorkyeran
Mar 22, 2007

To Escape The Shackles Of The Old Forums, We Must Reject The Tribal Negativity He Endorsed
Math.random is about as far from a CRNG as you can get. It's sometimes even worse than return 2; as it's sometimes an easy to predict PRNG that leaks state between pages.

revmoo
May 25, 2006

#basta
Well I left someone else make the decision and sign off on it, but basically what I ended up doing is seeding crypto-js with the output from seedrandom: https://github.com/davidbau/seedrandom

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

Are there any tools for traversing a hyperlinked JSON API?

For example, say an API request to http://0.0.0.0/api/moms/ returns:

JavaScript code:
{
    "id": 1,
    "name": "Your Mom",
    "relations": [
        "http://0.0.0.0/api/relations/11/",
        ...
    ]
}
And http://0.0.0.0/api/relations/11/ returns something like:
JavaScript code:
{
    "id": 11,
    "name": "Me",
    "location": "in the kitchen",
    "mom": "http://0.0.0.0/api/moms/1/"
}
I'd like something to turn that into:
JavaScript code:
{
    "id": 1,
    "name": "Your Mom",
    "relations": [
        {
            "id": 11,
            "name": "Me",
            "location": "in the kitchen",
             "mom": "http://0.0.0.0/api/moms/1/" // This could be removed as it is redundant in this view
        },
        ...
    ]
}
Obviously, I can just do the requests myself and build the object, I'm just wondering if there is a generalized tool or method of consuming an API that presents related objects as URLS rather than nesting the related objects.

Plorkyeran
Mar 22, 2007

To Escape The Shackles Of The Old Forums, We Must Reject The Tribal Negativity He Endorsed
My general experience with things (not in JS) that try to magically handle HATEAOSy APIs is that they don't end up doing anything useful. The lack of standards means that unless you're designing the API to fit what the library wants, configuring the library is at least as much work as just rolling something yourself would be, and you probably can't get away with eagerly fetching the graph (since that may involve a very large number of requests), so all you really want is some helper methods to make it easy to resolve links.

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe

Plorkyeran posted:

HATEAOSy APIs

Gesundheit!

The Insect Court
Nov 22, 2012

by FactsAreUseless

Wheany posted:

Here's a weird old trick to converting a variable to boolean: !!variable
Also for setting a default value for a variable, you might see somthing like this:

function(setting){
var value = setting || "default value";
}

The problem with that second one is that there are lots of values in Javascript that are false-y besides False. There are scenarios where you might want to pass one of them as an argument and not have the function provide a default value. You could use the slightly more verbose and ungainly:
code:
function (optional) {
	optional = (optional === undefined) ? /* default value */ : optional;
}
edit: You're right on Object and Array, but "" and 0 are still false. The empty string might not be a common corner case but it's easy to be bit by passing in 0 and having it overwritten by a default.

The Insect Court fucked around with this message at 09:17 on Jul 24, 2014

Strong Sauce
Jul 2, 2003

You know I am not really your father.





The Insect Court posted:

The problem with that second one is that there are lots of values in Javascript that are false-y besides False. There are scenarios where you might want to pass an empty Object or Array or String as an argument and not have the function provide a default value. You could use the slightly more verbose and ungainly:
code:
function (optional) {
	optional = (optional === undefined) ? /* default value */ : optional;
}
Empty Objects and Arrays are truthy, not falsy.

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope
Besides, if you look at the source code of some libraries, you will see that pattern used, so it's good to recognize it.

LP0 ON FIRE
Jan 25, 2006

beep boop
It looks like using overflow:auto is throwing off my getBoundingClientRect() left and top properties, but it also behaves the same if I calculate an elements offset with a loop.

I discovered this when I took away the line height of an article with a long image next to it set to float:right; the content underneath it settles right below the article and not the image. So I wrapped it in a div and added overflow:auto;

code:

<div style='overflow:auto;'>

	<div class='playControls'>
		<a href="#" id=<?= "restartButton".$IDNum ?> onclick="restartAndPlay('<?= $IDNum ?>'); 
return false;">&lt;&lt;</a>
&nbsp;&nbsp;&nbsp;<a href="#" id=<?= "playButton".$IDNum ?> onclick="playAudio('<?= $IDNum ?>'); 
return false;">Play</a>
	</div>
		
	<img style='float:right;' id=<?= "audioTextFollowImage".$IDNum ?>>
		
	<article id=<?= "resultingText".$IDNum ?> style='width: 500px;'> </article>
		
</div>

This fixes any content under this to be under the image next to my article:





But it causes whatever depends on using getBoundingClientRect() to be offset upwards from where they should be. In my case it's buttons that are further down the page. Maybe the solution is to use something other than the wrapper div with overflow:auto, but I'm not quite what that would be.


Update - Figured this out finally. The image next to it was part of a slideshow that changed. The y position of the buttons below were basing it off the height of the shortest image. So I ended up giving the div a height and will probably base it off the tallest image eventually.

LP0 ON FIRE fucked around with this message at 14:39 on Jul 28, 2014

fuf
Sep 12, 2004

haha
Is this the right place for obscure Node questions?

I need to watch a directory for new files, including files that might be in a subdirectory.

I've tried 3 modules:
https://github.com/mikeal/watch
https://github.com/yuanchuan/node-watch
https://github.com/bevry/watchr

but they all have the same problem: if I copy a directory that contains a file into the watch folder, they only pick up on the "new directory" event, and ignore the file.

If I create the directory first, then copy the file into it, both events get picked up fine. But I need to copy folders that already contain files into my watch directory and have them all picked up at once.

Any ideas? Is this the kind of thing that I should raise an issue about on github? (kinda scared because I've never done that)

Or should I give up on the modules and write my own "walker" function that gets called periodically?

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

fuf posted:

Is this the right place for obscure Node questions?

I need to watch a directory for new files, including files that might be in a subdirectory.

I've tried 3 modules:
https://github.com/mikeal/watch
https://github.com/yuanchuan/node-watch
https://github.com/bevry/watchr

but they all have the same problem: if I copy a directory that contains a file into the watch folder, they only pick up on the "new directory" event, and ignore the file.

If I create the directory first, then copy the file into it, both events get picked up fine. But I need to copy folders that already contain files into my watch directory and have them all picked up at once.

Any ideas? Is this the kind of thing that I should raise an issue about on github? (kinda scared because I've never done that)

Or should I give up on the modules and write my own "walker" function that gets called periodically?

In the "created" handler that picks up the "new dirctory" event, can't you just list the files in that new directory and do whatever you want with them?

fuf
Sep 12, 2004

haha
Oh hey I guess I could.

I kept hesitating between whether to use a "watcher" or a "walker", but I guess what I could do is watch for new directories, then walk through them to get the files.

Life would be a lot easier if the watchers just picked up every actual change though.

Anyway thanks :)

Raskolnikov2089
Nov 3, 2006

Schizzy to the matic
I've been staring at this for the last 1/2 hour trying to figure out where my syntax error is.

code:
var k = [NaN, 5, 7];

 function testNaN(){
	if(isNaN(k[0]){
		console.log("Not a Number");
	}
	else{
		console.log("A Number!");
	}
};

Or can I not use if(isNaN()) on an index value?

Raskolnikov2089 fucked around with this message at 03:00 on Jul 26, 2014

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Raskolnikov2089 posted:

I've been staring at this for the last 1/2 hour trying to figure out where my syntax error is.

code:
var k = [NaN, 5, 7];

 function testNaN(){
	if(isNaN(k[0]){
		console.log("Not a Number");
	}
	else{
		console.log("A Number!");
	}
};

Or can I not use isNaN() on an index value?

You're missing a closing parenthesis on the line with the if statement

Raskolnikov2089
Nov 3, 2006

Schizzy to the matic
Ughhhhh okay, thats enough for the night.

Thank you.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Raskolnikov2089 posted:

Ughhhhh okay, thats enough for the night.

Thank you.

Is your debugger not giving you useful error messages? All I did was paste it into jsfiddle, open the Firebug console, hit Run, and it gave me a very clear error message:

Raskolnikov2089
Nov 3, 2006

Schizzy to the matic
That's actually more helpful than chrome, which gives me

Uncaught SyntaxError: Unexpected token {

Which told me there was a syntax error which is usually enough, but the firebug message would have been a lot more helpful given how burnt out I was on staring at a pc screen.

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.
I've done more javascript over the past week than in the rest of my life combined, and this sort of thing is driving me insane. I was two hours with this piece of jQuery, which would be plain skipped over by the debugger rather than even causing an error. As in, the debugging cursor would jump directly from the first line here to the further code below.

code:
$(.ItemList > a).each(function (){
  alert($(this).text); // should be 'this.text' instead
});

//code
Are there any secrets that I'm not aware of or is it just a matter of getting better at recognizing the sorts of problems that are indicated by the different ways that things screw up? What sorts of things are in the scope of programs like JSLint? I've just looked and saw that there's a VS plugin for it.

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

Newf posted:

I've done more javascript over the past week than in the rest of my life combined, and this sort of thing is driving me insane. I was two hours with this piece of jQuery, which would be plain skipped over by the debugger rather than even causing an error. As in, the debugging cursor would jump directly from the first line here to the further code below.

code:

$(.ItemList > a).each(function (){
  alert($(this).text); // should be 'this.text' instead
});

//code

If the $(".ItemList > a") selector doesn't find any elements, then each won't call the function. Were you stepping over or into?

Raskolnikov2089
Nov 3, 2006

Schizzy to the matic
http://jsfiddle.net/2duEv/


code:
loanType = ["home", "auto", "health", "dental"];
loanAmt = [NaN, NaN, 25, 100];


for(var x=0; x<loanAmt.length; x++){
		if(isNaN(loanAmt[x])){
			loanAmt.splice(x,1);
			loanType.splice(x,1);
		};
};
alert(loanAmt);
alert(loanType);
I'm trying to find indices with NaN in loanAmt, and remove it and the corresponding index in loanType. It's only removing the first NaN and "home" while leaving the second NaN and "auto" alone.

Maybe I don't understand for loops as well as I thought I did.

Adbot
ADBOT LOVES YOU

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

Raskolnikov2089 posted:

http://jsfiddle.net/2duEv/


code:
loanType = ["home", "auto", "health", "dental"];
loanAmt = [NaN, NaN, 25, 100];


for(var x=0; x<loanAmt.length; x++){
		if(isNaN(loanAmt[x])){
			loanAmt.splice(x,1);
			loanType.splice(x,1);
		};
};
alert(loanAmt);
alert(loanType);
I'm trying to find indices with NaN in loanAmt, and remove it and the corresponding index in loanType. It's only removing the first NaN and "home" while leaving the second NaN and "auto" alone.

Maybe I don't understand for loops as well as I thought I did.

When you splice, you are moving the other elements backward. So you have this pattern:

code:
loanAmt == [NaN, NaN, 25, 100];
x = 0;
loanAmt[x] is NaN

splice();

loanAmt == [NaN, 25, 100];
x = 1;
loanAmt[x] is 25
If you add "x--" to your if block, you will find that it works. It's sort of gross to play with the index variable like that, so you might prefer to group the amounts and types in objects like

code:
loans = [{type: "home", amt: NaN}, {type: "auto", amt: NaN}, ... ];
Then you can filter out the ones you don't want:

code:
loans = loans.filter(function (loan) { return !isNaN(loan.amt); });
You may need to polyfill Array.prototype.filter for older IE, or you can copy in a loop the cases that you want to keep:

code:
newLoans = [];
for (int i = 0; i < loans.length; i++) {
    if (!isNaN(loans[i].amt)) {
        newLoans.push(loans[i]);
    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply