Categories
discuss

Javascript reference vs binding…what’s the difference?

I recently read the following in Kyle Simpson’s You Don’t Know JS: ES6

“[ES6 modules export] actual bindings (almost like pointers) to the identifiers in your inner module definition.”

My confusion is how these bindings differ from references…

I understand that a reference in JS is only applicable to non-primitive types (like objects), so that given

let object1 = {a: 1};
let object2 = object1;

object1 and object2 now refer to (they are both references to) the same object.
If I add a property to object2, I am also adding a property to object1

object2.b = 2;
console.log(object1.b); // 2

And I can see that a binding can apply to both primitive types and non-primitive types

// foo.js
export let count = 1;
export function incrementCount() { count++; }

// bar.js
import {count, incrementCount} from foo;
console.log(count); // 1
incrementCount();
console.log(count); // 2

Is a binding just like a reference, except that primitive values can also share a binding (while references are limited to non-primitive types)?

I feel like I’m missing something here…

Answer

A binding is a very generic term for “what a name refers to”. Every identifier in a scope is bound to something. Usually they resolve to variables in a variable environment (storage slots in an environment record), but there are exceptions (e.g. with or the global object).

A reference is a term for a pointer to some kind of structure. For example, objects are known as “reference values” because they reference the container of mutable properties with an identity.

ES6 modules are now introducing a new type of binding, one that was unknown before. It is not a usual variable, but literally a reference to another variable – the one exported from the other module. If the module variable changes, this will be reflected by the import – they both point to the same environment record slot.
An export declaration adds a mapping from a local name to a name in the module interface, while an import declaration adds a mapping from a name in the respective module interface to a local name. When a module is instantiated, an indirect binding is created that points to the same environment as the local binding in the exporting module.

Categories
discuss

Selenium Close File Picker Dialog

We are using Selenium-Webdriver on Jenkins box (running linux), to drive Firefox for testing a fairly complex web app. The web app requires the uploading of a photo for testing, and we have achieved that by using sendkeys to the input file dialog. Unfortunately (perhaps due to the way the uploader works, it is plupload and uploads through XHR and not a FORM post) the File Picker Dialog never closes. While this was slightly annoying, in the past the tests still passed fine. Switching from selenium-2.45.0 to selenium-2.53.1 and upgrading FireFox to 45 we discovered that our tests now failed because element is no longer visible due to the File Picker Dialog (at least we assume that is reason that the elements no longer react to clicks is because they are behind the file dialog).

I realize that there is no way to click on the close dialog button, and I have tried sending the escape key various ways to browser to close the dialog but nothing I have tried works:

((RemoteWebDriver)driver).getKeyboard().pressKey(Keys.ESCAPE);

Since the Jenkins server running on the tests is on a different server than the Firefox being driven by Selenium, Roboto and AutoIt aren’t an option. Is there some way to trigger closing of dialog that doesn’t involve interacting with the dialog box. My thought was injecting some javascript into the page to create a form around the file input, and then submit the form (to nowhere), and then reloading the page but that has proven unsuccessful.

File Upload Dialog

Answer

There’s probably a click event transmitted to the <input type="file"> element, which opens the file dialog.

One way to overcome this issue is to disable the internal click by overriding the method. This piece of JavaScript will disable the internal click for each <input type="file"> element:

((JavascriptExecutor)driver).executeScript(
    "HTMLInputElement.prototype.click = function() {                     " +
    "  if(this.type !== 'file') HTMLElement.prototype.click.call(this);  " +
    "};                                                                  " );

Then upload the file by calling .sendKeys("full file path") on the <input type="file"> element.

In some cases, the <input type="file"> only resides in memory. If that’s the case, you’ll have to insert it in the page:

((JavascriptExecutor)driver).executeScript(
    "HTMLInputElement.prototype.click = function () {" +
    "    if (this.type !== 'file') {" +
    "        HTMLElement.prototype.click.call(this);" +
    "    }" +
    "    else if (!this.parentNode) {" +
    "        this.style.display = 'none';" +
    "        this.ownerDocument.documentElement.appendChild(this);" +
    "        this.addEventListener('change', () => this.remove());" +
    "    }" +
    "}");

See https://gist.github.com/florentbr/d7bee068932bdf6e00af3b9f01af9af6

Categories
discuss

How to make a decision without an if statement

I’m taking a course in Java and we haven’t officially learned if statements yet. I was studying and saw this question:

Write a method called pay that accepts two parameters: a real number for a TA’s salary, and an integer for the number hours the TA worked this week. The method should return how much money to pay the TA. For example, the call pay(5.50, 6) should return 33.0. The TA should receive “overtime” pay of 1.5 times the normal salary for any hours above 8. For example, the call pay(4.00, 11) should return (4.00 * 8) + (6.00 * 3) or 50.0.

How do you solve this without using if statements? So far I’ve got this but I’m stuck on regular pay:

public static double pay (double salary, int hours) {

     double pay = 0;

     for (int i = hours; i > 8; i --) {
         pay += (salary * 1.5);
     }
}

Answer

To avoid direct use of flow control statements like if or while you can use Math.min and Math.max. For this particular problem using a loop would not be efficient either.

They may technically use an if statements or the equivalent, but so do a lot of your other standard library calls you already make:

public static double pay (double salary, int hours) {
     int hoursWorkedRegularTime = Math.min(8, hours);
     int hoursWorkedOverTime = Math.max(0, hours - 8);
     return (hoursWorkedRegularTime * salary) +
            (hoursWorkedOverTime  * (salary * 1.5));
}
Categories
discuss

Why does Log4J2 output differ on two systems when I am writing the same UTF-8?

I’m writing Unicode characters to a Log4J2 log. On one machine (Windows 8) I see this in the log:

2016-08-30 16:44:00.958|English:  The quick brown fox jumped over the lazy dog.
2016-08-30 16:44:00.960|German:  Falsches Üben von Xylophonmusik quält jeden größeren Zwerg.
2016-08-30 16:44:00.960|Russian 1:  В чащах юга жил бы цитрус? Да, но фальшивый экземпляр!
2016-08-30 16:44:00.960|Russian 2:  Съешь же ещё этих мягких французских булок да выпей чаю.
2016-08-30 16:44:00.960|Chinese:  中国智造,慧及全球
2016-08-30 16:44:00.960|Japanese:  いろはにほへと ちりぬるを わかよたれそ つねならむ うゐのおくやま けふこえて あさきゆめみし ゑひもせす
2016-08-30 16:44:00.960|Korean:  다람쥐 헌 쳇바퀴에 타고파

On another machine (Windows Server 2012R2) I see this:

2016-08-30 16:50:41.676|English:  The quick brown fox jumped over the lazy dog.
2016-08-30 16:50:41.676|German:  Falsches Üben von Xylophonmusik quält jeden größeren Zwerg.
2016-08-30 16:50:41.676|Russian 1:  ? ????? ??? ??? ?? ??????? ??, ?? ????????? ?????????!
2016-08-30 16:50:41.676|Russian 2:  ????? ?? ??? ???? ?????? ??????????? ????? ?? ????? ???.
2016-08-30 16:50:41.676|Chinese:  ?????????
2016-08-30 16:50:41.676|Japanese:  ??????? ????? ?????? ????? ??????? ????? ??????? ?????
2016-08-30 16:50:41.676|Korean:  ??? ? ???? ???

If Log4J2 writes UTF-8 by default, why does the log file on the 2nd system contain only question marks? That is, the second system may (and probably is) missing fonts, but the log file itself on the 2nd system contains actual question marks when, using a hexdump tool, I would expect to see at least the binary for the UTF-8 characters in the file. Put another way, I can understand why an unknown character might render incorrectly, I just don’t understand why the correct Unicode was not written to the file, if the process doing the writing is the JVM, which uses Unicode for characters.

Answer

Did you try to enforce the UTF-8 charset for your Log4j Layout, inside your Log4j configuration file? For example, using PatternLayout:

<Configuration ...>
    ...
    <PatternLayout pattern="..." charset="UTF-8"/>
    ...
</Configuration>

See https://logging.apache.org/log4j/2.x/manual/layouts.html for more information on Log4j encoding issues.

Categories
discuss

Check if battery optimization is enabled or not for an app

Android 6 and 7 have some power optimizations (doze mode) which restrict app networking when device is not used.

User may disable optimization mode for any app in Battery settings:

android settings screenshot

Is it possible to check if optimization is enabled for my app or not? I need to ask user to disable optimization for better app functionality, but I don’t know how to check it programatically.

Answer

This one was a bit tricky to track down: here’s what you are looking for

PowerManager.isIgnoringBatteryOptimizations()

Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..