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
huhu
Feb 24, 2006

Alligator posted:

FYI that --verbose is going to npm not webpack-dev-server. If you want to pass an argument to the thing npm is running you would need an extra set of hyphens: npm run start -- --verbose.

You don't have quiet or noInfo set to true in your webpack config do you?

I ended up finding this snippet of code online that gets it to work.

code:
+    "startDebug": "node $NODE_DEBUG_OPTION ./node_modules/webpack-dev-server/bin/webpack-dev-server.js",

Adbot
ADBOT LOVES YOU

Roadie
Jun 30, 2013

Knifegrab posted:

Unfortunately I cannot use find or for of because I am comparing each element in two different arrays, so of would only give me the element of one array. Similar reasons for find, since find would only return the found element (that is different) but cannot tell me how they differ.

For in also would not work because it does not respect order (it iterates based on when the particular key was added not the value of the key).

Zip the two arrays into tuples, then operate on the resulting array.

[[1, 2], [3, 4], [5, 6]] etc.

Doom Mathematic
Sep 2, 2008

Lumpy posted:

If you're going to mutate, why not go nuts!:

JavaScript code:
Ip(a, b) {

  // your stuff....
  a = a.split('.');
  b = b.split('.');
  if (a.length > b.length) {
     return 1;
  } else if (a.length < b.length) {
    return -1;
  }

  // terrible new stuff!
  while( a.length > 0 ) {
    let _a = parseInt( a.pop() ) ;
    let _b = parseInt( b.pop() );
    if( _a > _b ) return 1;
    if( _b > _a ) return -1;
  }
  return 0;
}

:eng101: Always use an explicit radix with parseInt!

Doom Mathematic
Sep 2, 2008

Knifegrab posted:

Sure, its just a really really simple bit of code to help sort IP addresses.

code:
    Ip(a, b) {
        a = a.split('.');
        b = b.split('.');

        if (a.length > b.length) {
            return 1;
        } else if (a.length < b.length) {
            return -1;
        }

        for (let i = 0; i < a.length; i++) {
            if ((a[i] = parseInt(a[i], 10)) > (b[i] = parseInt(b[i], 10))) {
                return 1;
            } else if (a[i] < b[i]) {
                return -1;
            }
        }
        return 0;
    }


From your code I take it these are IPv4 addresses, which means there's no need to check lengths and the loop can be painlessly unrolled:

JavaScript code:
lp(a, b) {
	const xs = a.split('.').map(x => parseInt(x, 10))
	const ys = b.split('.').map(y => parseInt(y, 10))

	return xs[0] - ys[0] || xs[1] - ys[1] || xs[2] - ys[2] || xs[3] - ys[3]
}

necrotic
Aug 2, 2005
I owe my brother big time for this!
You could just do while(a.length) :science:

edit: well i missed a couple posts there.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Doom Mathematic posted:

:eng101: Always use an explicit radix with parseInt!

I know, but when I'm typing fake code on a dead comedy forum using my iPad, sometimes I leave that out. :smith:

reversefungi
Nov 27, 2003

Master of the high hat!

Thermopyle posted:

Speaking of debugging with Jetbrains IDEs...

You can now use the browser <> IDE Javascript debugging with Chrome while DevTools is open. This is big news!

https://developers.google.com/web/updates/2017/10/devtools-release-notes#multi-client

In case you aren't aware of what I'm talking about you can set breakpoints in your code in your IDE, and when the browser hits those breakpoints it breaks in your IDE where you can inspect variables and all the other stuff you do while debugging.



This sounds really cool, is there any where I can see/read more about how this works? Like is it literally as simple as just making a breakpoint in VS Code and the browser will stop automatically? I'm guessing there's more to it/extra config/etc. but I'd like to learn more.

Thermopyle
Jul 1, 2003

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

The Dark Wind posted:

This sounds really cool, is there any where I can see/read more about how this works? Like is it literally as simple as just making a breakpoint in VS Code and the browser will stop automatically? I'm guessing there's more to it/extra config/etc. but I'd like to learn more.

I don't use vs code so I don't know.

There's lots of stuff for the clearly superior (haha, I make jokes to rile you up) webstorm if you search for "webstorm Javascript debug".

I never used it much precisely because you couldn't have dev tools open at the same time. I will definitely get back to trying it when I get into my next bout of js coding.

But anyway, the little bit I have tried it in the past, you had to have an extension installed in Chrome, and then it was literally as simple as setting a breakpoint in your IDE and the code would pause in the browser when it hit that line and you could inspect and modify variables via your IDE and all the other stuff you expect out of a modern debugger.

Thermopyle fucked around with this message at 05:55 on Oct 26, 2017

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.

The Dark Wind posted:

Like is it literally as simple as just making a breakpoint in VS Code and the browser will stop automatically? I'm guessing there's more to it/extra config/etc. but I'd like to learn more.

You've got to set up a launch.json for your project in the .vscode folder. Not typically complicated. Here's one from a create-react-app project that I'm working on:

JavaScript code:
{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Chrome",
            "type": "chrome",
            "request": "launch",
            "url": "http://localhost:3000",
            "webRoot": "${workspaceRoot}/src",
            "userDataDir": "${workspaceRoot}/.vscode/chrome",
            "sourceMapPathOverrides": {
                "webpack:///src/*": "${webRoot}/*"
            }
        }
    ]
}
The nice thing is that VSCode has a bunch of great intellisense set up specifically for this file. Create a launch.json, hit ctrl+space inside of some curlies ({}), and a bunch of canned configurations are available. After this, it's just f5 to run, and it behaves just like a (eg) Visual Studio or Eclipse debugger.

Knifegrab
Jul 30, 2014

Gadzooks! I'm terrified of this little child who is going to stab me with a knife. I must wrest the knife away from his control and therefore gain the upperhand.

Doom Mathematic posted:

From your code I take it these are IPv4 addresses, which means there's no need to check lengths and the loop can be painlessly unrolled:

JavaScript code:
lp(a, b) {
	const xs = a.split('.').map(x => parseInt(x, 10))
	const ys = b.split('.').map(y => parseInt(y, 10))

	return xs[0] - ys[0] || xs[1] - ys[1] || xs[2] - ys[2] || xs[3] - ys[3]
}

Haha thanks for the laughs everyone, solving dumb problems is fun! (You all make me sick!)

huhu
Feb 24, 2006
Is there a clearer way to swap two elements in an array when the original array needs to remain constant?

code:
const BUTTONS = {'a' : 'A', 'b': 'B",'c': 'C'}
const { selectedButton } = this.state;
const selectedButtonIdx = BUTTONS.findIndex((b) => b.name === selectedButton);
const mobileButtons = [
  BUTTONS[selectedButtonIdx],
  ...BUTTONS.slice(0, selectedButtonIdx),
  ...BUTTONS.slice(selectedButtonIdx + 1)];

necrotic
Aug 2, 2005
I owe my brother big time for this!
I assume that's not quite correctly cleaned up code, is BUTTONS actually an array or an object as you posted?

As for "swapping" into a new array, your approach is pretty much it in JS. There are other solutions but if you have the spread operator this reads the best.

huhu
Feb 24, 2006

necrotic posted:

I assume that's not quite correctly cleaned up code, is BUTTONS actually an array or an object as you posted?

As for "swapping" into a new array, your approach is pretty much it in JS. There are other solutions but if you have the spread operator this reads the best.

Sorry yeah, BUTTONS is an array of objects.

const BUTTONS = [{'a' : 'A'}, {'b': 'B"},{'c': 'C'}]

Guessing that probably doesn't change that.

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope
Were discussing possible technologies to use with a future project and I suggested React for the UI part. Another person suggested Angular.

So my question is: Is Angular good now?

edit: also if it isn't, why? (I'm sure they'll ask me the same thing)

Wheany fucked around with this message at 12:55 on Oct 30, 2017

Thermopyle
Jul 1, 2003

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

People like both.

Which you prefer seems to mostly boils down to which you used first.

However there are significant ergonomic differences between the two, so just build a toy project with each to get a feel.

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



Thermopyle posted:

People like both.

Which you prefer seems to mostly boils down to which you used first.

However there are significant ergonomic differences between the two, so just build a toy project with each to get a feel.

I tried Angular first but like React more because it's closer to the pattern I'd fallen into using when I had to use jQuery to generate markup from JSON (or XML in one particularly dark period). My observation is that it depends more on whether/how much you 'get' functional programming and how much magical stuff you're willing to let your framework do for you.

Thermopyle
Jul 1, 2003

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

Munkeymon posted:

I tried Angular first but like React more because it's closer to the pattern I'd fallen into using when I had to use jQuery to generate markup from JSON (or XML in one particularly dark period). My observation is that it depends more on whether/how much you 'get' functional programming and how much magical stuff you're willing to let your framework do for you.

So...yeah, you're right.

By "which you used first" I was actually thinking "which you used first to do a significant project", but that's actually just a dumb proxy for which felt best to you. If you have a choice why wouldn't you use the one that was most comfortable?

Knifegrab
Jul 30, 2014

Gadzooks! I'm terrified of this little child who is going to stab me with a knife. I must wrest the knife away from his control and therefore gain the upperhand.
Back with another head scratcher!

So I am streaming a butt-ton of data to the client (for valid reasons).

There is an elaborate underbelly here, and there is so much data I have to stream it, storing it in memory as an object or something is risky. So I am piping my output through a transformer, formatting every line and sending it back to the client (using express).

The issue here is, what do I do if I encounter an error mid-stream?

I know once my stream is established I set my headers appropriately and then begin piping the output to the client. At this point the headers have been set and sent and trying to send an error message using the req object results in express yelling at me because "The Headers cannot be set after they are sent!"

So how do I let the client know that the blob of data is now bullshit?

Dogcow
Jun 21, 2005

Knifegrab posted:

Back with another head scratcher!

So I am streaming a butt-ton of data to the client (for valid reasons).

There is an elaborate underbelly here, and there is so much data I have to stream it, storing it in memory as an object or something is risky. So I am piping my output through a transformer, formatting every line and sending it back to the client (using express).

The issue here is, what do I do if I encounter an error mid-stream?

I know once my stream is established I set my headers appropriately and then begin piping the output to the client. At this point the headers have been set and sent and trying to send an error message using the req object results in express yelling at me because "The Headers cannot be set after they are sent!"

So how do I let the client know that the blob of data is now bullshit?

So is there any way to terminate the stream at all? Wouldn’t you just terminate the stream and have the client look for an error as the last output? These are probably super dumb questions since I don’t really know what you mean by stream except to assume a websocket or something like that? Guess I need more info/am too dumb about streaming web stuff.

fantastic in plastic
Jun 15, 2007

The Socialist Workers Party's newspaper proved to be a tough sell to downtown businessmen.
edit: solved problem, had errors with async callback logic

fantastic in plastic fucked around with this message at 09:35 on Nov 1, 2017

Knifegrab
Jul 30, 2014

Gadzooks! I'm terrified of this little child who is going to stab me with a knife. I must wrest the knife away from his control and therefore gain the upperhand.

Dogcow posted:

So is there any way to terminate the stream at all? Wouldn’t you just terminate the stream and have the client look for an error as the last output? These are probably super dumb questions since I don’t really know what you mean by stream except to assume a websocket or something like that? Guess I need more info/am too dumb about streaming web stuff.

Oh if it happens I stop streaming to the client. I terminate the transform.

For clarity, I am spawning a process, and piping the stdout to a transform, I am using this package: http://csv.adaltas.com/transform/, and I am taking the transform, doing a bit of post process on the line, and then piping the transform to the req object (which streams it to the client). So no websockets or any of that nonsense, this is just a standard request.

Knifegrab fucked around with this message at 18:31 on Nov 1, 2017

necrotic
Aug 2, 2005
I owe my brother big time for this!
There's no standard way to indicate failure there, you've already sent headers and content. I would simply stop the stream, as you are, and document the behavior. If you want to surface an error to the client you'll have to define a specific prefix string for the client to watch out for, unless the format you're streaming out has some mechanism built-in for this.

Dogcow
Jun 21, 2005

necrotic posted:

There's no standard way to indicate failure there, you've already sent headers and content. I would simply stop the stream, as you are, and document the behavior. If you want to surface an error to the client you'll have to define a specific prefix string for the client to watch out for, unless the format you're streaming out has some mechanism built-in for this.

Yeah it’s not really possible to handle it in standard HTTP/headers way. Maybe you could set the expected error string in a custom header initially at least to keep from having to incorporate it into the stream itself. That package inherits from the built in Node Transform class/module and you’re supposed to be able to emit an error with transform.destroy so maybe that can emit the expected error string to the stream.

Knifegrab
Jul 30, 2014

Gadzooks! I'm terrified of this little child who is going to stab me with a knife. I must wrest the knife away from his control and therefore gain the upperhand.
Thats really suprising there is no standard way to abort a streaming response in express. Surely this is a common enough problem, an unknown error occurs, the end user needs to know he didn't get the full package...

Dogcow
Jun 21, 2005

Knifegrab posted:

Thats really suprising there is no standard way to abort a streaming response in express. Surely this is a common enough problem, an unknown error occurs, the end user needs to know he didn't get the full package...

Oh I assumed you were just open ended-ly streaming while the client is connected. If you know/can calculate the final size of the content then you can set the 'content-length' header and the client can detect a mismatch when the connection is closed prematurely. I know this can/is supposed to cause the "net::ERR_CONTENT_LENGTH_MISMATCH" error in Chrome but I don't know how or if that is detectable within JS directly or whether you have to do the comparison of the 'content-length' and actual downloaded bytes yourself. It isn't really a problem specific to Express or Node it's more a general HTTP stream issue unless I'm missing something.

Knifegrab
Jul 30, 2014

Gadzooks! I'm terrified of this little child who is going to stab me with a knife. I must wrest the knife away from his control and therefore gain the upperhand.

Dogcow posted:

Oh I assumed you were just open ended-ly streaming while the client is connected. If you know/can calculate the final size of the content then you can set the 'content-length' header and the client can detect a mismatch when the connection is closed prematurely. I know this can/is supposed to cause the "net::ERR_CONTENT_LENGTH_MISMATCH" error in Chrome but I don't know how or if that is detectable within JS directly or whether you have to do the comparison of the 'content-length' and actual downloaded bytes yourself. It isn't really a problem specific to Express or Node it's more a general HTTP stream issue unless I'm missing something.

I actually don't know what the size of the payload is while I'm streaming it. it could be infinitely big or teeny tiny.

The hack I have come up with for now is:

code:
                transformer.on('error', (err) => {
                    console.error("An error occured during the streaming of data: ", err);

                    //This insure the json fails to parse and thus responds on the client with an error.
                    transformer.push('}}}]]ERROR 500: INTERNAL SERVER ERROR');
                    transformer.end();
                });
This insures that the json won't parse, but it feels like a total bogus nightmare. But hey it works?

Dogcow
Jun 21, 2005

Knifegrab posted:

This insures that the json won't parse, but it feels like a total bogus nightmare. But hey it works?

Eh from your description this scenario means the data is invalid and shouldn't be parsed anyway so doesn't seem to be a problem to me. Wrap that sucker in try/catch, regex out your dumped error in the catch and you're golden. If you don't know the size beforehand I don't know how you can do any better.

Edit: minor thing but I don't see how the JSON would ever be valid in this scenario (breaking off mid streaming) so you're insurance ('}}}]]') to make the parser break shouldn't be necessary. Though if you do actually want to pull out an error on the client rather than just saying "JSON crapped out" you need some sort of error signifier in the raw string anyway I suppose.

Dogcow fucked around with this message at 21:35 on Nov 1, 2017

necrotic
Aug 2, 2005
I owe my brother big time for this!
Yeah that's what you are stuck with in this approach. The Content-Length one is the best, but I had assumed (correctly) you wouldn't know that based on the streaming behavior so didn't mention it.

Knifegrab
Jul 30, 2014

Gadzooks! I'm terrified of this little child who is going to stab me with a knife. I must wrest the knife away from his control and therefore gain the upperhand.

Dogcow posted:

Eh from your description this scenario means the data is invalid and shouldn't be parsed anyway so doesn't seem to be a problem to me. Wrap that sucker in try/catch, regex out your dumped error in the catch and you're golden. If you don't know the size beforehand I don't know how you can do any better.

Edit: minor thing but I don't see how the JSON would ever be valid in this scenario (breaking off mid streaming) so you're insurance ('}}}]]') to make the parser break shouldn't be necessary. Though if you do actually want to pull out an error on the client rather than just saying "JSON crapped out" you need some sort of error signifier in the raw string anyway I suppose.

So the dumb thing is, I have to use _flush on the transformer to tidy up the json at the end of the transmission. I cannot figure out how to make the tranformer end without calling flush so if I don't do the extra json character bits, flush is still called and it does close hte json neatly. Now it may still not parse but this is just double insurance.

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.
Having a brainfart. Trying to set an onClick for some menu items in a react app, where each item calls a loadFile function (passed as a prop) with the item's text.

code:
<SplitButton title={this.props.user.currentFile} id="fileSelect">
	//...
    {this.props.user.getFileNames().map(
        (file, index) =>
            (<MenuItem
                key={index}
                eventKey={index}
                title="Load this file..."
		onclick={this.props.loadFile(file)} // doesn't pass the TS checker, because it sees the 'void' return value of the fcn - wants a function
		onclick={this.props.loadFile.bind(null, file) // fails because the application loses access to its own data
	     >
                {file}
            </MenuItem>)
    )}
	//...
</SplitButton>
Is there a 'bind' variant where I can bind the input to the file without altering the 'this' object of the function? The only thing I can think to do immediately is to pass the application itself as a prop to this menu, but that seems Very Wrong.

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.

Newf posted:

Having a brainfart.

Slightly unfarted. The answer was

onclick={ () => { this.props.loadFile(file); } }

Knifegrab
Jul 30, 2014

Gadzooks! I'm terrified of this little child who is going to stab me with a knife. I must wrest the knife away from his control and therefore gain the upperhand.

Newf posted:

Slightly unfarted. The answer was

onclick={ () => { this.props.loadFile(file); } }

Cool! Just so you know with a single line like this you don't need the extra brackets.

code:
 () => this.props.loadFile(file)
Is equivalent to:

code:
() => {
   return this.props.loadFile(file);
}
Its just a bit of sugar to make life easier, and yes the return is implied in the single line approach, you don't even need to write it!

Sedro
Dec 31, 2008

Knifegrab posted:

Its just a bit of sugar to make life easier, and yes the return is implied in the single line approach, you don't even need to write it!

The return value can change the behavior of the event handler.

Knifegrab
Jul 30, 2014

Gadzooks! I'm terrified of this little child who is going to stab me with a knife. I must wrest the knife away from his control and therefore gain the upperhand.

Sedro posted:

The return value can change the behavior of the event handler.

How so? The event handler shouldn't be expecting doing anything with a returned value, in the case of an onClick event. As far as I am aware that is bubble down only.

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



Knifegrab posted:

How so? The event handler shouldn't be expecting doing anything with a returned value, in the case of an onClick event. As far as I am aware that is bubble down only.

What do you mean by 'down'? Click bubbles to parents which I would think of as 'up'.

Anyway, events added using the .on___ properties can have their propagation stopped by returning false from the handler. jQuery might maintain that illusion by checking handler return values while adding events the new/'right' way.

Knifegrab
Jul 30, 2014

Gadzooks! I'm terrified of this little child who is going to stab me with a knife. I must wrest the knife away from his control and therefore gain the upperhand.

Munkeymon posted:

What do you mean by 'down'? Click bubbles to parents which I would think of as 'up'.

Anyway, events added using the .on___ properties can have their propagation stopped by returning false from the handler. jQuery might maintain that illusion by checking handler return values while adding events the new/'right' way.

I thought e.stopProppagation is how you stopped the event from propagating.

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



Knifegrab posted:

I thought e.stopProppagation is how you stopped the event from propagating.

That's the modern way, yes. I'm not sure that'll even work if you bind using the property, though, and I've been defensively doing both return false; and stopProppagation for years just in case :shepicide:

I guess returning false doesn't work anymore https://codepen.io/dtanders/pen/LOxBed

Munkeymon fucked around with this message at 20:29 on Nov 9, 2017

There Will Be Penalty
May 18, 2002

Makes a great pet!
return false; is an almost-equivalent of event.preventDefault();. event.stopPropagation(); is a different beast.

Knifegrab
Jul 30, 2014

Gadzooks! I'm terrified of this little child who is going to stab me with a knife. I must wrest the knife away from his control and therefore gain the upperhand.

Munkeymon posted:

That's the modern way, yes. I'm not sure that'll even work if you bind using the property, though, and I've been defensively doing both return false; and stopProppagation for years just in case :shepicide:

I guess returning false doesn't work anymore https://codepen.io/dtanders/pen/LOxBed

Its ok man, I had no idea this was ever even a standard so who knows what damage I've unknowingly done in the past :negative:

Adbot
ADBOT LOVES YOU

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



There Will Be Penalty posted:

return false; is an almost-equivalent of event.preventDefault();. event.stopPropagation(); is a different beast.

:doh: I got them mixed up which is what I get for trying to remember things instead of looking poo poo up

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