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
MrMoo
Sep 14, 2000

Lumpy posted:

You will wonder why you used prototype for so long.

It's not too bad, it's just that jQuery is a lot less cluttered and all the APIs have a standard form. jQuery certainly has more progress these days than Scriptaculous.

Adbot
ADBOT LOVES YOU

MrMoo
Sep 14, 2000

RussianManiac posted:

is there any sycnrhonizatino in javacsript? Do most browsers implement pure user level threads for JS or do some of them actually might execute in parallel?

Check out HTML 5 or Gears for threading support,

http://code.google.com/apis/gears/api_workerpool.html

MrMoo
Sep 14, 2000

RussianManiac posted:

What are the event callbacks for when the javascript just loads

Common hack is to use a <script> element at the end of the page, otherwise use this:

http://api.jquery.com/ready/

MrMoo
Sep 14, 2000

Server sent events would be nicer for unidirectional communication, but JSON over XHR is the most convenient.

MrMoo
Sep 14, 2000

That's quite nice, a jQuery layer replicating web animations. Wonder what the performance is like at larger scale with the chaining mechanism. Using RAF tends to work better than CSS transitions though if you want 60fps.

MrMoo
Sep 14, 2000

Reading OK - FileReader API, writing requires a round-trip.

Also, there is AppCache and IndexedDB which may be of use.

MrMoo
Sep 14, 2000

Strong Sauce posted:

It's not recommended to use AppCache. Completely unusable. http://alistapart.com/article/application-cache-is-a-douchebag

You just have to not be dumb, read the follow up article http://flailingmonkey.com/application-cache-not-a-douchebag. Using AppCache in an iframe works pretty well.

MrMoo
Sep 14, 2000

The Insect Court posted:

You could take a look at http://google.github.io/tracing-framework/index.html if Chrome's default dev tools aren't extensive enough.


Nice although appears nothing much more than a search front end to the existing chrome://tracing data. The biggest issue is usually the fault is with GC and there is nothing one can do with that outside of closed environments. There is command line flag to enable an API to manually initiate GC and you can custom build chrome to increase the frequency of GC.

MrMoo
Sep 14, 2000

That seems a little problematic on scalability, you can capture standard console logging in Chrome or Firefox under Linux in its parent console. The biggest problem I found recently is that logging objects, e.g. console.log ("log this:", object) keeps a reference on the object until the log is wiped from memory! Incredibly dangerous implementation for long running pages.

MrMoo
Sep 14, 2000

<head> doesn't execute scripts until fully loaded, hence the inlining of scripts for faster execution. The use of RAF is for at least one render, i.e. a pseudo-DOMReady() event handler.

setTimeout(0) is always useful as a yield function as Javascript is a co-operative environment in a single thread.

MrMoo
Sep 14, 2000

Space Whale posted:

Is there already some sort of API I can call to do this or is this going to be a case of roll-your-own with storing (x,y), drawing to the page, calculating distance to the right side of the page, etc?

For a start you need to work with a resolution independent co-ordinate system and test out what is going to be legible on all target devices.

A popular project has been implemented fridge magnets for letters and letting everyone play with them. I think I even posted one here like ten years ago.

MrMoo fucked around with this message at 00:49 on Mar 5, 2015

MrMoo
Sep 14, 2000

Odette posted:

Here's my lovely npm package, how can I improve it? Any glaring errors or bad implementations of ... anything?


That looks like a custom license? Stick with one of the standard OSI ones. I found the MIT license reference in the package file.

The function names getStory() and getInfo() are not technically accurate but at least they are short.

MrMoo fucked around with this message at 16:27 on Nov 25, 2015

MrMoo
Sep 14, 2000

Raskolnikov2089 posted:

Working with API rate limits, is wrapping my requests in a setTimeout a bad way to go about it?

Not many APIs available, one can add requestIdleCallback to better integrate with animation if you are not calling in a service worker.

MrMoo
Sep 14, 2000

I've done the second one once because it was easier to read than !OtherCondition, the former I can only guess is from some crazy bug hunting session where every execution path "must be defined", i.e. dangling else statements and fruity indentation causing the programmer problems.

MrMoo
Sep 14, 2000

npm is the package manager for node.js thus some sort of ":lol: JavaScript programmers" comment, a.k.a. leftpad.

MrMoo
Sep 14, 2000

I cannot remember if it still works but add a desktop shortcut to Chrome with "--disable-web-security" on the command line.

Don't forget the OPTIONS pre-flight request if using a proxy, e.g.
code:
...
use_backend cors_preflight if METH_OPTIONS
...

backend cors_preflight
errorfile 503 /etc/haproxy/dummy.503
and the dummy file, you may need to add Access-Control-Allow-Headers:
code:
HTTP/1.1 200 OK
Access-Control-Allow-Methods: POST, GET, OPTIONS
Access-Control-Allow-Origin: *
Content-Length: 0
Cache-Control: private


MrMoo fucked around with this message at 21:03 on May 31, 2016

MrMoo
Sep 14, 2000

Subjunctive posted:

Please, no. This is super dangerous. If you accidentally end up browsing the internet with that flag set you are incredibly vulnerable. The flag's name is not overstated.

Reuters API docs used to recommend it after I pointed out a defect due to security changes in Chrome, now it is a little better:

quote:

*Warning* Your browser is detected as "Chrome". If you are accessing this help system directly from file(s), please make sure to use the Chrome parameter --allow-file-access-from-files (eg. “<*path*>/chrome.exe" --allow-file-access-from-files) . If this parameter is not used, please use Classic Documentation or use a different browser.
But there is one site that even has a funky popup telling you to disable security, :lol:

MrMoo
Sep 14, 2000

Analytic Engine posted:

window.performance

Things are getting better too: https://www.w3.org/TR/navigation-timing-2/

MrMoo
Sep 14, 2000

What does Google docs use for screenshots in the help system, is it something like dom-to-image?

MrMoo
Sep 14, 2000

Isn't the crappy situation of browsers not supporting ECMAScript import but everything else does?

MrMoo
Sep 14, 2000

meinstein posted:

Edit: A large amount of "professional" JavaScript is written by people that don't know what they're doing, and are flying by the seat of their pants cobbling together half-understood examples from Stack Overflow. If you read those two you'll be streets ahead.

I've been skimming around on debounce and throttle functions and there are many articles on the topic. Common theme was not to implement your own because libraries are awesome and peer reviewed by Trump himself and so they must be great. So I picked up Lodash and tried their throttle() API and guess what, it is fundamentally flawed and broken, spent this morning rewriting it to be less brain dead but still shines of authors trying too hard for a relatively simple requirement.

quote:

Creates a throttled function that only invokes func at most once per every wait milliseconds.

So the authors decide to implement the rate limit tracking on the incoming calls to the throttle rather than the actual function that is supposed to be throttled. It is just so weird when you attach it to something graphical.

MrMoo
Sep 14, 2000

Jabor posted:

I'm not sure I understand the objection. How are you using it? What are you expecting to happen, and how is this different from what it actually does?

Looks like it has been logged before, they are impressively zealous on closing issues in their tracker:

https://github.com/lodash/lodash/issues/3051

I used it to throttle updates to a Polymer field which is tied to a display item on the page. The Lodash implementation causes the item to randomly double update.



This is my version:

MrMoo fucked around with this message at 18:01 on Jun 8, 2017

MrMoo
Sep 14, 2000

"Professional integrator" version, i.e. I copied the debounce() implementation and replaced all Lodash functions with standard ECMA functions where I could be bothered (no exception on function parameter not being a function) and fixed it by using lastInvokeTime instead of lastCallTime for rate checks, everything else as ugly as it was.

http://ahyoomee.miru.hk/donald/throttle/throttle.js

MrMoo
Sep 14, 2000

I think they want a PR and a contributor agreement, :effort:

I haven't decided what to do with it yet, it's just in a branch for testing a specific data flag. It's F/OSS so good luck stealing it.

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.

MrMoo
Sep 14, 2000

The classic JSON.stringify(a) === JSON.stringify(b) is still valid for comparing objects. With arrays there is room for interpretation of what equality means, the Polymer project has this issue when detecting changes in an array:

https://www.polymer-project.org/1.0/docs/devguide/model-data

MrMoo
Sep 14, 2000

Made me remember this:

https://twitter.com/ID_AA_Carmack/status/844885670732685313

MrMoo
Sep 14, 2000

geeves posted:

The correct answer is, "Who ever wrote that should be defenestrated immediately."

Or just: "so you need a new team lead then?"

MrMoo
Sep 14, 2000

Anyone recommend a non-terrible library for extracting the background colour of an image? I have found a few that are poorly written but generally rely on a third party to do the actual logic, e.g. modified median cut quantization. It's not simply the dominant colour of the entire image though as I'm dealing with logos with mainly transparent backgrounds which would produce an incorrect result.



So I can create a canvas taking the full available height, center the actual logo and backfill with yellow.

Similar example:

MrMoo fucked around with this message at 18:07 on Aug 15, 2017

MrMoo
Sep 14, 2000

Some really inconvenient logos to work with, I ended up scanning alternating pixels on the top second two lines and bottom last-but one pair of lines and comparing the values to prevent breaking on a asymmetric gradient.

:lol:




This is functional for logos with solid colours otherwise a more astute algo is required.
JavaScript code:
this._logo_ctx.clearRect(0, 0, this._logo_canvas.width, this._logo_canvas.height);
const top = (this._logo_canvas.height - imageBitmap.height) / 2;
this._logo_ctx.drawImage(imageBitmap, 0, top);
const d1 = this._logo_ctx.getImageData(0, top + 1, imageBitmap.width, 2);
const d2 = this._logo_ctx.getImageData(0, imageBitmap.height - 2, imageBitmap.width, 2);
let r = 0, g = 0, b = 0;
for(let i = 0, j = 0; i < imageBitmap.width; i+=2, j+=16) {
        r += d1.data[j]   + d2.data[j];
        g += d1.data[j+1] + d2.data[j+1];
        b += d1.data[j+2] + d2.data[j+2];
}
r = ~~(r/imageBitmap.width);
g = ~~(g/imageBitmap.width);
b = ~~(b/imageBitmap.width);
if(r === d1.data[0] && g === d1.data[1] && b === d1.data[2]) {
        this._logo_ctx.fillStyle = "rgb(" + r + "," + g + "," + b + ")";
        this._logo_ctx.fillRect(0, 0, this._logo_canvas.width, top + 1);
        this._logo_ctx.fillRect(0, top + imageBitmap.height - 1, this._logo_canvas.width, top + 1);
}

MrMoo fucked around with this message at 21:43 on Aug 15, 2017

MrMoo
Sep 14, 2000

Normally the createImageBitmap(blob) promise will do that.

MrMoo
Sep 14, 2000

Joda posted:

Not sure if this is the right thread to ask this, but if I compile some C++ to webassembly and am using multithreading (e.g. std::thread, std::future etc.) will that execute on multiple threads, or is webassembly stuck with one thread like JS? If so, to get parallel execution when compiling with gcc for native execution I have to add the compiler flag -pthread to get mutexes and such to act like they're supposed to, do I have to do something similar for webassembly compilation?

Multi-threading is supposed to be landing this monthyear 🤞 around Chrome 63.

https://wasmdash.appspot.com

Kinda meh page:

https://github.com/WebAssembly/threads

MrMoo fucked around with this message at 20:27 on Oct 9, 2017

MrMoo
Sep 14, 2000

You could probably just use WebAssembly now and dump to a JS string.

MrMoo
Sep 14, 2000

ArcticZombie posted:

With synchronous XHR being deprecated, is there a go to method if a request absolutely must be synchronous?
Try the Fetch API?
code:
let response = await fetch("http://&#128169;.com")

MrMoo
Sep 14, 2000

:golfclap:

MrMoo
Sep 14, 2000

Socket.io does that for you, fundamentally WebSockets are quite different in the browser to Node.JS as one yields errors synchronously and the other asynchronously. It sucks.

MrMoo
Sep 14, 2000

I found this today and had to nudge it a bit because I was compiling to ES2015 and it was breaking. A Promise wrapper that performs retries inside another Promise.
JavaScript code:
function wait(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
}
function retry(fn, delay, retry_count) {
        return new Promise((resolve, reject) => {
                return fn()
                .then(response => {
                        resolve(response);
                })      
                .catch(reason => {
                        if (retry_count) {
                                return wait(delay)
                                .then(retry.bind(null, fn, delay, retry_count - 1))
                                .then(resolve)
                                .catch(reject);
                        }               
                        return reject(reason);
                });     
        });             
}    
Looks pretty much the same as the one from Yair Kukielka.

Use it something like this:
JavaScript code:
retry(() => fetch(url, {
        method: "GET",
        headers: {
                "Accept": "application/json",
        },
        mode: "cors",
        credentials: "include",
        cache: "no-cache",
        redirect: "follow",
}), CMS_TIMEOUT * 1000, CURL_RETRIES)
.then(response => response.json())
.then(json => console.log(json))
.catch(error => console.error(error));

MrMoo
Sep 14, 2000

Roadie posted:

Use p-retry instead. It has better coverage for various edge cases including being able to abort the retries from the outside.

Probably need something with a configurable increasing delay and randomization, node-promise-retry has that.

MrMoo
Sep 14, 2000

TheFluff posted:

Just use the async library for everything. It does everything you could possibly want to do with asynchronous functions and is far better than anything else I've seen. It lets you run asynchronous tasks in series, in parallel, or in parallel with a limit on concurrent tasks. It supports asynchronous iterators for all the usual suspects (map, filter, reduce, etc) as well as asynchronous control flow. async.auto is the greatest thing to happen to Javascript since the arrow function.

Nice, but weird all the callbacks instead of using Promise chains. 2 steps forward, 2 steps back kind of thing.

Adbot
ADBOT LOVES YOU

MrMoo
Sep 14, 2000

Although it is almost one liner normally anyway:
JavaScript code:
thingies.reduce((promise, thingy) => 
    promise.then(result => doAsyncStuffWithThingy(thingy)), Promise.resolve());

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