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
Thermopyle
Jul 1, 2003

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

JavaScript code:
function iTakeANumber(x: number) {
  return x * 2;
}
If I pass event.target.value to the function I do not get a warning from TypeScript even though it's actually a string I need to parse with parseInt. I'd like TypeScript to catch this error. Can I make that happen?


(This is actually a React SyntheticEvent, but I assume its the same as a native event?)

Adbot
ADBOT LOVES YOU

Skandranon
Sep 6, 2008
fucking stupid, dont listen to me

Thermopyle posted:

JavaScript code:
function iTakeANumber(x: number) {
  return x * 2;
}
If I pass event.target.value to the function I do not get a warning from TypeScript even though it's actually a string I need to parse with parseInt. I'd like TypeScript to catch this error. Can I make that happen?


(This is actually a React SyntheticEvent, but I assume its the same as a native event?)

So, your function specifies it wants a number, and that is pretty much all you can do on that end. However, I'm guessing the type of "event.target.value" is "any". This means it will never trigger compile errors because it COULD be a number. What you want is to either be specific about the type of .value before you pass it around, or make event.target into a generic so you can specify the value to be of type T (event.target<T>).

necrotic
Aug 2, 2005
I owe my brother big time for this!

peepsalot posted:

The project license is CC0, public domain, so yeah its pretty cool.

Lodash is MIT, though :confused:

https://raw.githubusercontent.com/lodash/lodash/4.17.4/LICENSE

And from the sound of it this is going on the NYSE floor so removing attribution is totally cool.

MrMoo
Sep 14, 2000

Samples are CC0 apparently, core base is MIT. I wonder what classifies as substantial though:

quote:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

peepsalot
Apr 24, 2007

        PEEP THIS...
           BITCH!

necrotic posted:

Lodash is MIT, though :confused:

https://raw.githubusercontent.com/lodash/lodash/4.17.4/LICENSE

And from the sound of it this is going on the NYSE floor so removing attribution is totally cool.
Ah, yeah my bad, I kinda skimmed real quick it and didn't see the "samples" qualifier on the CC0 part.

Thermopyle
Jul 1, 2003

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

Skandranon posted:

So, your function specifies it wants a number, and that is pretty much all you can do on that end. However, I'm guessing the type of "event.target.value" is "any". This means it will never trigger compile errors because it COULD be a number. What you want is to either be specific about the type of .value before you pass it around, or make event.target into a generic so you can specify the value to be of type T (event.target<T>).

Thanks for this. It got me thinking about the issue in the right way, and I eventually figured out that I can use React.FormEvent<HTMLInputElement> to type my incoming events.

Geno
Apr 26, 2004
STUPID
DICK
Ramping up on an Angular project, trying to figure out why this doesn't work:

I have a progress bar with a function that calculates its value:
code:
<uib-progressbar animate="false" value="inits.testProgress()" style="height:20px;" type="primary"><b>{{inits.testProgress()}}%</b></uib-progressbar>
When I run this code, the console.log shows in the console

code:
    $scope.inits.testProgress = function() {
        console.log('testsets');

        var len = 5;
        var numActionRequired = 0;
        console.log(Math.floor(numActionRequired / len * 100));
    }
but when I run this code, the first console.log line doesn't even show. Why is that? All variables are valid, no errors, etc.

code:
    $scope.inits.testProgress = function() {
        console.log('testsets');

        var len = $scope.inits.audit_details.items.length;
        var numActionRequired = 0;

        angular.forEach($scope.inits.audit_details.items, function(inv) {
            if (inv.action_required == 'No')
                numActionRequired++;
        })

        console.log(Math.floor(numActionRequired / len * 100));
    }

geeves
Sep 16, 2004

Geno posted:

but when I run this code, the first console.log line doesn't even show. Why is that? All variables are valid, no errors, etc.

code:
    $scope.inits.testProgress = function() {
        console.log('testsets');

        var len = $scope.inits.audit_details.items.length;
        var numActionRequired = 0;

        angular.forEach($scope.inits.audit_details.items, function(inv) {
            if (inv.action_required == 'No')
                numActionRequired++;
        })

        console.log(Math.floor(numActionRequired / len * 100));
    }

It's hard to tell without seeing the rest of your script. Are $scope.inits.auto_details and audit_details.items defined?

I would probably start with changing

console.log(testsets) to

console.dir($scope.inits.audit_details);

And comment out the rest of the method.

Skandranon
Sep 6, 2008
fucking stupid, dont listen to me

Geno posted:

Ramping up on an Angular project, trying to figure out why this doesn't work:

I have a progress bar with a function that calculates its value:
code:
<uib-progressbar animate="false" value="inits.testProgress()" style="height:20px;" type="primary"><b>{{inits.testProgress()}}%</b></uib-progressbar>
When I run this code, the console.log shows in the console


As geeves said, it's hard to tell without everything else, but there's a lot you are doing wrong here. At the very least, you don't actually return a value from either of your functions, so you can't possibly be doing anything useful for your progress bar. Second... well, if I start going on about not using $scope and so forth, will probably be more confusing than helpful. Where are you setting inits? It may not be getting set at the right stage in the Angular digest cycle, and value is getting rendered when it is still undefined, causing it to silently choke?

Geno
Apr 26, 2004
STUPID
DICK

geeves posted:

It's hard to tell without seeing the rest of your script. Are $scope.inits.auto_details and audit_details.items defined?

Thanks, the problem was not initializing audit_details.items.

duz
Jul 11, 2005

Come on Ilhan, lets go bag us a shitpost


huhu posted:

I have two check boxes that toggle the hidden class for a cell's row in a table based on whether the cell's value is "Incomplete" or "Complete. Is there an easy way to combine the following code because almost all of it is repetitive?

code:
// Toggle Complete Targets
$("#toggleOverallStatusComplete").click(function(){
    $('.col-overallStatus').each(function(){
        var overallStatus = $(this).text();
        if(overallStatus == "Complete"){
            $(this).parent().toggleClass("hidden");
        }
    })
});

// Toggle Incomplete Targets
$("#toggleOverallStatusIncomplete").click(function(){
    $('.col-overallStatus').each(function(){
        var overallStatus = $(this).text();
        if(overallStatus == "Incomplete"){
            $(this).parent().toggleClass("hidden");
        }
    })
});


As long as you won't have partial matching text like "Not Yet Complete" you can use contains().
code:
$("#toggleOverallStatusComplete").click(function(){
    $(".col-overallStatus:contains('Complete')").parent().toggleClass("hidden");
});

$("#toggleOverallStatusIncomplete").click(function(){
    $(".col-overallStatus:contains('Incomplete')").parent().toggleClass("hidden");
});
If you have checkboxes instead of buttons triggering it, you could reduce it a bit more. But then it might not be as obvious what's happening
code:
$(".toggleVis").change(function(){
    $(".col-overallStatus:contains('" + $(this).val() + "')").parent().toggle($(this).prop("checked"));
});
code:
<label>Show complete:<input type="checkbox" value="Complete" class="toggleVis"></label>
<label>Show incomplete:<input type="checkbox" value="Incomplete" class="toggleVis"></label>

duz fucked around with this message at 16:18 on Jun 10, 2017

icantfindaname
Jul 1, 2008


Hi, I'm trying to scrape data off this ASPX website with PhantomJS, and am having trouble figuring out how to set the various dropdown fields and then click the button. The following code should produce an error where it gives you red text asking to fill in the boxes, but the picture rendered shows no difference from a blank form. How do you select options in the drop down box? I have pretty much no idea what I'm doing with javascript, I took an intro level undergrad class on it a while ago and that's about it

http://worknet.wisconsin.gov/worknet/daindustry.aspx

code:
var page = require('webpage').create();
page.open('http://worknet.wisconsin.gov/worknet/daindustry.aspx', function(status) {
  console.log("Status: " + status);
  if(status === "success") {
	page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js", function() {

		page.evaluate(function() {
			$('#btnResults').click();
		});
	});
	
	page.render('example.png');
  }
  phantom.exit();
});

icantfindaname fucked around with this message at 17:36 on Jun 12, 2017

Munkeymon
Aug 14, 2003

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



icantfindaname posted:

Hi, I'm trying to scrape data off this ASPX website with PhantomJS, and am having trouble figuring out how to set the various dropdown fields and then click the button. The following code should produce an error where it gives you red text asking to fill in the boxes, but the picture rendered shows no difference from a blank form. I have pretty much no idea what I'm doing with javascript, I took an intro level undergrad class on it a while ago and that's about it

http://worknet.wisconsin.gov/worknet/daindustry.aspx

code:
var page = require('webpage').create();
page.open('http://worknet.wisconsin.gov/worknet/daindustry.aspx', function(status) {
  console.log("Status: " + status);
  if(status === "success") {
	page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js", function() {

		page.evaluate(function() {
			$('#btnResults').click();
		});
	});
	
	page.render('example.png');
  }
  phantom.exit();
});

Sorry to be all "the princess is in another castle" but you're probably going to want to use http://casperjs.org/ on top of Phantom because there's actually a shitload of annoying stuff you'd have to deal with manually otherwise.

icantfindaname
Jul 1, 2008


Okay, thanks

necrotic
Aug 2, 2005
I owe my brother big time for this!
However, the crux of the issue in your snippet is rendering the PNG too early. Invoking includeJs is an asynchronous operation, and so your rendering your PNG before jquery has even loaded. You will want to move the render call inside of the evaulate callback, though that likely will not be _quite_ enough as you still need to wait for whatever happens when you click the button to complete.

I haven't used casper before, but you will want to be aware of asynchronous behavior no matter what you use.

edit: glancing at the "Quickstart" for casper it should be fairly painless.

Love Stole the Day
Nov 4, 2012
Please give me free quality professional advice so I can be a baby about it and insult you
Working with DiscordJS and SQLite to make a personal bot and need a little help wrapping my head around a context issue:

How do I get a reference to my Bot class' SQLiteProvider database so that I can read/write from within my command.js file's context? Because I want the users to call a few commands that will:
  • read from a particular row element to verify whether it's empty
  • write a user's name to a given row in that table
  • display the contents of a given table

Here's the relevant JS that's involved (entry point on the right side of the image):





Basically I want to get a reference of the thing defined in the right-side file so that I can use it in the left-side file... or can I just instantiate a new thing entirely in the left-hand side and then read/write independently without having to worry about the right hand side thing? My understanding, though, is that I need to have a single reference to the database and then have some way to access it from other files.

My first impression of what to do is to instantiate the Bot's SQLProvider reference by importing it into the main file (right side of the above image) from a separate third .js file and then again importing it into the Command's .js file (left side of the picture) so that I have a reference to it? That doesn't sound right to me, though. Sorry for the stupid question. New to this JS stuff.

Love Stole the Day fucked around with this message at 06:45 on Jun 14, 2017

geeves
Sep 16, 2004


At first, I had panic attack and thought JS evolved from not requiring semi-colons to not requiring closing brackets and parentheses with some exotic syntax. :psyduck:

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Love Stole the Day posted:

Working with DiscordJS and SQLite to make a personal bot and need a little help wrapping my head around a context issue:

How do I get a reference to my Bot class' SQLiteProvider database so that I can read/write from within my command.js file's context? Because I want the users to call a few commands that will:
  • read from a particular row element to verify whether it's empty
  • write a user's name to a given row in that table
  • display the contents of a given table

Here's the relevant JS that's involved (entry point on the right side of the image):





Basically I want to get a reference of the thing defined in the right-side file so that I can use it in the left-side file... or can I just instantiate a new thing entirely in the left-hand side and then read/write independently without having to worry about the right hand side thing? My understanding, though, is that I need to have a single reference to the database and then have some way to access it from other files.

My first impression of what to do is to instantiate the Bot's SQLProvider reference by importing it into the main file (right side of the above image) from a separate third .js file and then again importing it into the Command's .js file (left side of the picture) so that I have a reference to it? That doesn't sound right to me, though. Sorry for the stupid question. New to this JS stuff.

I don't know what code makes your "SQLiteProvider database" but I'd do something like create an exported function from that right side file that hands out the reference, or maybe even make a class method that returns it.

ROFLburger
Jan 12, 2006

Hm that seems like less of a Javascript question and more of a discord-js-command API question if you're just trying to get a reference to the provider. Have you tried popping in to their Discord server and asking? I use a different Discord JS api but I've found those channels to be pretty helpful

huhu
Feb 24, 2006
https://jsfiddle.net/h8apd6bd/

What am I missing - why isn't the zebra striping being applied to only the visible rows?

geeves
Sep 16, 2004

huhu posted:

https://jsfiddle.net/h8apd6bd/

What am I missing - why isn't the zebra striping being applied to only the visible rows?

In the way you have it coded, CSS only cares about markup, not what JS hides or shows based on a CSS class

You can change it from hide/show based on class and use tr.hide() / tr.show() and try something like:

.stripes[@display=block]:nth-child(even)

edit, you may be able to substitute the class for the [@display=block]. I just usually use hide / show more often than trying to juggle classes.

geeves fucked around with this message at 19:08 on Jun 14, 2017

huhu
Feb 24, 2006

geeves posted:

In the way you have it coded, CSS only cares about markup, not what JS hides or shows based on a CSS class

You can change it from hide/show based on class and use tr.hide() / tr.show() and try something like:

.stripes[@display=block]:nth-child(even)

edit, you may be able to substitute the class for the [@display=block]. I just usually use hide / show more often than trying to juggle classes.

Any chance you could edit the JS fiddle? I don't quite follow.

geeves
Sep 16, 2004

huhu posted:

Any chance you could edit the JS fiddle? I don't quite follow.

I just re-looked at what we did and it was completely hacked together using extra attributes outside of CSS :doh:

code:
#searchResults tr :not(.hidden) :nth-child(even) {
    background-color: #ddd;
}
https://developer.mozilla.org/en-US/docs/Web/CSS/:not

Should work. But for some reason does not in the fiddle, and I've run into this before where we wrote a bunch of rear end in a top hat javascript to get it to work.

We did something like this: https://jsfiddle.net/h8apd6bd/14/ Like, I said, hackey as all poo poo.

Edit: Updated to latest version of fiddle with correct striping.

geeves fucked around with this message at 21:10 on Jun 14, 2017

LP0 ON FIRE
Jan 25, 2006

beep boop
Issue regarding letter spacing in canvas with text that has shadows:

Since the canvas element does not support line spacing when rendering text, I decided to add the unicode hair space character (code 8202) between letters of a text string for spacing. Unfortunately, different browsers display this character at different widths from one another, making it an unacceptable solution for my purpose.

An alternate solution I thought of using was to fill each character individually with an x offset that is defined by the spacing. The problem with this is when applying a shadow, the shadows that overlap will be darker than text that was filled all at once.

So it seems that both of these solutions won't work for me, but what are the alternatives?

LP0 ON FIRE fucked around with this message at 17:01 on Jun 15, 2017

Video Nasty
Jun 17, 2003

LP0 ON FIRE posted:

Issue regarding line spacing in canvas with text that has shadows:

Since the canvas element does not support line spacing when rendering text, I decided to add the unicode hair space character (code 8202) between letters of a text string for spacing. Unfortunately, different browsers display this character at different widths from one another, making it an unacceptable solution for my purpose.

An alternate solution I thought of using was to fill each character individually with an x offset that is defined by the spacing. The problem with this is when applying a shadow, the shadows that overlap will be darker than text that was filled all at once.

So it seems that both of these solutions won't work for me, but what are the alternatives?

code:
&thinsp;
or
&ensp;
?

Video Nasty fucked around with this message at 22:55 on Jun 14, 2017

huhu
Feb 24, 2006

geeves posted:

I just re-looked at what we did and it was completely hacked together using extra attributes outside of CSS :doh:

code:
#searchResults tr :not(.hidden) :nth-child(even) {
    background-color: #ddd;
}
https://developer.mozilla.org/en-US/docs/Web/CSS/:not

Should work. But for some reason does not in the fiddle, and I've run into this before where we wrote a bunch of rear end in a top hat javascript to get it to work.

We did something like this: https://jsfiddle.net/h8apd6bd/14/ Like, I said, hackey as all poo poo.

Edit: Updated to latest version of fiddle with correct striping.

Awesome, thanks. Is there something I can read up on about why all this JS is required?

geeves
Sep 16, 2004

huhu posted:

Awesome, thanks. Is there something I can read up on about why all this JS is required?

One of the other web threads may say there's a better CSS solution that does work (again, I do not know why :not(.hidden) didn't work for me).

JS-wise, it's because you're manipulating the DOM in ways that CSS might not be designed to understand. If you were actually removing rows from the DOM and re-inserting them, the CSS solution on its own should work. In your example, they still exist as part of the DOM since you are only hiding them.

If you wanted to add/remove on the fly, it ups the complexity even more as you have to manage state of your data in some way. Other libraries, such as React are better suited to this natively.

You actually can use VanillaJS pretty easily with little extra overhead for what you're trying to accomplish as well.

https://jsfiddle.net/pwaykhwn/1/

LP0 ON FIRE
Jan 25, 2006

beep boop

Video Nasty posted:

code:
&thinsp;
or
&ensp;
?

Those create very close letter spacing! Although I don't know if any slight difference will be acceptable, but it's way better thank you. It's being used for clients making titles, lower 3rds and what not for film online, and they are super strict about detail and having work stay consistent.

e: I keep calling it line spacing - but I meant letter spacing, but it looks like you knew what I meant. Updating post.

LP0 ON FIRE fucked around with this message at 17:02 on Jun 15, 2017

kiwid
Sep 30, 2013

I'm looking for a library/package that allows a user to upload an image from their computer in the original huge as 12 megapixel size, auto-resize the short side of the image with proportions locked and then allow the user to crop the remaining with a locked size so in the end I get a 300px by 300px profile picture. Any suggestions?

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense

kiwid posted:

I'm looking for a library/package that allows a user to upload an image from their computer in the original huge as 12 megapixel size, auto-resize the short side of the image with proportions locked and then allow the user to crop the remaining with a locked size so in the end I get a 300px by 300px profile picture. Any suggestions?

Something like this?

https://foliotek.github.io/Croppie/

If you have a bit of JS expertise you might be best off allowing the user to crop their photo before uploading a huge file. This can be done using canvas, loading the image into it, allowing them to move it around. The image can then be extracted from the canvas and sent with a post request to the server.

You'll have to do some reading on canvas to make that happen.

kiwid
Sep 30, 2013

Nolgthorn posted:

Something like this?

https://foliotek.github.io/Croppie/

If you have a bit of JS expertise you might be best off allowing the user to crop their photo before uploading a huge file. This can be done using canvas, loading the image into it, allowing them to move it around. The image can then be extracted from the canvas and sent with a post request to the server.

You'll have to do some reading on canvas to make that happen.

Croppie looks perfect.

Yeah I'm not strong with writing my own JavaScript so it looks like Croppie will do fine. Thanks.

hooah
Feb 6, 2006
WTF?
Any suggestions on a React course/tutorial (with optional Redux) that is neither 100% "watch me code" nor 100% "figure everything out yourself"? I liked the Google Android course on... edX maybe? They taught you some stuff by example, then you had to transfer that somewhat for the project at hand.

ddiddles
Oct 21, 2008

Roses are red, violets are blue, I'm a schizophrenic and so am I

hooah posted:

Any suggestions on a React course/tutorial (with optional Redux) that is neither 100% "watch me code" nor 100% "figure everything out yourself"? I liked the Google Android course on... edX maybe? They taught you some stuff by example, then you had to transfer that somewhat for the project at hand.

This one is pretty good: https://www.udemy.com/react-redux/learn/v4/overview

Though I got it on sale for $10, it's not worth that much more than that.

I guess its on sale now for $19, it's worth that.

Love Stole the Day
Nov 4, 2012
Please give me free quality professional advice so I can be a baby about it and insult you

hooah posted:

Any suggestions on a React course/tutorial (with optional Redux) that is neither 100% "watch me code" nor 100% "figure everything out yourself"? I liked the Google Android course on... edX maybe? They taught you some stuff by example, then you had to transfer that somewhat for the project at hand.

I really liked Ben Fhala's thing on Packt, which served as my intro to React. You can do their "1 month free trial"for the Mapt thing so that you can access it and all their other React stuff for free until the trial thing is up. I've been using it to cram with all sorts of stuff and it'll finish in 5 days.

hooah
Feb 6, 2006
WTF?

ddiddles posted:

This one is pretty good: https://www.udemy.com/react-redux/learn/v4/overview

Though I got it on sale for $10, it's not worth that much more than that.

I guess its on sale now for $19, it's worth that.

Haha, that's the exact one I recently went through. Decent explanations, but zero "figure this part out on your own" (unless you mistyped something).

teen phone cutie
Jun 18, 2012

last year i rewrote something awful from scratch because i hate myself
God i just took a coding test for an interview and i'm only realizing now comparing two arrays is such a pain in JS

I just turned them into strings and compared them that way but not sure if there's a better way :shrug:

teen phone cutie fucked around with this message at 15:14 on Jun 16, 2017

Vulture Culture
Jul 14, 2003

I was never enjoying it. I only eat it for the nutrients.

Grump posted:

God i just took a coding test for an interview and i'm only realizing now comparing two arrays is such a pain in JS

I just turned them into strings and compared them that way but not sure if there's a better way :shrug:
Depends on the exact parameters on what should come out of your function, and the exact semantics of object equality, and whether you need to descend into nested arrays, hashes, etc. but this is a pretty straightforward programming question that doesn't require any specific prior algorithms knowledge. Might be worth picking up Cracking the Coding Interview before your next one

Vulture Culture fucked around with this message at 15:30 on Jun 16, 2017

Skandranon
Sep 6, 2008
fucking stupid, dont listen to me

Grump posted:

God i just took a coding test for an interview and i'm only realizing now comparing two arrays is such a pain in JS

I just turned them into strings and compared them that way but not sure if there's a better way :shrug:

That works... but is sidestepping the real problem of "can you traverse arrays and make sense of them".

necrotic
Aug 2, 2005
I owe my brother big time for this!
It works if the values are all scalar. It will immediately fall over if anything else is in there.

Adbot
ADBOT LOVES YOU

teen phone cutie
Jun 18, 2012

last year i rewrote something awful from scratch because i hate myself
Yeah my answer worked fine im not really worried about that.

The point was more about me bitching about JS

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