I have an array of objects that i get from a json file. After getting the array with fs.readFileSync.
jsonData = JSON.stringify(fs.readFileSync('data.json'.toString(), 'utf8'));
parsedJsonData = JSON.parse(jsonData);
and when I do:
console.log(parsedJsonData);
it returns: 710, instead of what i expect to be 1
here is the array(with only one object)
[
{
"email": "ibrahim.m.fadel#gmail.com",
"username": "ibrahim fadel",
"password": {
"type": "Buffer",
"data": [
25,
0,
0,
0,
2,
115,
116,
114,
105,
110,
103,
0,
8,
0,
0,
0,
99,
97,
114,
101,
121,
51,
49,
0,
0
]
},
"id": 0
}
]
I simply want to find the amount of objects that there are in the array, which is 1 so I can loop through it
The unnecessary JSON.stringify() over a string is causing problems, look at this:
console.log(JSON.stringify("[\n" + "{\n" + " \"email\": \"ibrahim.m.fadel#gmail.com\",\n" + " \"username\": \"ibrahim fadel\",\n" + " \"password\": {\n" + " \"type\": \"Buffer\",\n" + " \"data\": [\n" + " 25,\n" + " 0,\n" + " 0,\n" + " 0,\n" + " 2,\n" + " 115,\n" + " 116,\n" + " 114,\n" + " 105,\n" + " 110,\n" + " 103,\n" + " 0,\n" + " 8,\n" + " 0,\n" + " 0,\n" + " 0,\n" + " 99,\n" + " 97,\n" + " 114,\n" + " 101,\n" + " 121,\n" + " 51,\n" + " 49,\n" + " 0,\n" + " 0\n" + " ]\n" + " },\n" + " \"id\": 0\n" + "}\n" + "]"))
.as-console-wrapper { max-height: 100% !important; top: 0; }
Is returning a escaped string, so when you call the function JSON.parse() this function actually is returning a string:
console.log(typeof JSON.parse(JSON.stringify("[\n" + "{\n" + " \"email\": \"ibrahim.m.fadel#gmail.com\",\n" + " \"username\": \"ibrahim fadel\",\n" + " \"password\": {\n" + " \"type\": \"Buffer\",\n" + " \"data\": [\n" + " 25,\n" + " 0,\n" + " 0,\n" + " 0,\n" + " 2,\n" + " 115,\n" + " 116,\n" + " 114,\n" + " 105,\n" + " 110,\n" + " 103,\n" + " 0,\n" + " 8,\n" + " 0,\n" + " 0,\n" + " 0,\n" + " 99,\n" + " 97,\n" + " 114,\n" + " 101,\n" + " 121,\n" + " 51,\n" + " 49,\n" + " 0,\n" + " 0\n" + " ]\n" + " },\n" + " \"id\": 0\n" + "}\n" + "]")))
.as-console-wrapper { max-height: 100% !important; top: 0; }
The solution is removing the call of JSON.stringify
console.log(JSON.parse("[\n" + "{\n" + " \"email\": \"ibrahim.m.fadel#gmail.com\",\n" + " \"username\": \"ibrahim fadel\",\n" + " \"password\": {\n" + " \"type\": \"Buffer\",\n" + " \"data\": [\n" + " 25,\n" + " 0,\n" + " 0,\n" + " 0,\n" + " 2,\n" + " 115,\n" + " 116,\n" + " 114,\n" + " 105,\n" + " 110,\n" + " 103,\n" + " 0,\n" + " 8,\n" + " 0,\n" + " 0,\n" + " 0,\n" + " 99,\n" + " 97,\n" + " 114,\n" + " 101,\n" + " 121,\n" + " 51,\n" + " 49,\n" + " 0,\n" + " 0\n" + " ]\n" + " },\n" + " \"id\": 0\n" + "}\n" + "]")
.length)
.as-console-wrapper { max-height: 100% !important; top: 0; }
Related
So I'm trying to display the values of a book in myLibrary but the when I do it displays it like this :
Zero To one
Peter Thiel
210
Has been read already
function() { return title + " " + "by" + " " + author + " " + pages + " " + "pages" + " " + isRead; }
It shouldn't display this part:
function() { return title + " " + "by" + " " + author + " " + pages + " " + "pages" + " " + isRead; }
Here's my code:
this.pages = pages;
this.isRead = isRead;
this.info = function() {
return title + " " + "by" + " " + author + " " + pages + " " + "pages" + " " + isRead;
}
}
const zeroToOne = new Book("Zero To one", "Peter Thiel", "210", "Has been read already");
function addBookToLibrary(bookToAdd) {
myLibrary.push(bookToAdd);
console.log(myLibrary);
for (let obj of myLibrary) {
console.log(obj);
card.textContent = Object.values(obj);
}
}
You have to call the info function :
console.log(obj.info());
More specifically, I'm referring to this method from Lodash and this JavaScript method.
When would you choose to use one over the other?
In my limited test below, Lodash handles null & undefined by returning an empty string. It also contradicts the ECMAScript standard by returning -0 for -0 where the native method returns 0. (see: 6.1.6.1.20)
You can check out the source for lodash here for implementation details: https://github.com/lodash/lodash/blob/master/toString.js
The native toString behavior is defined by tc39's ECMAScript 2021 Language Specification 7.1.17
The tests are not exhaustive so feel free to add your own.
console.log("native: " + [1,2,3].toString());
console.log("lodash: " + _.toString([1,2,3]));
console.log("native: " + [[1,2,3],[1,2,3],[1,2,3]].toString());
console.log("lodash: " + _.toString([[1,2,3],[1,2,3],[1,2,3]]));
console.log("native: " + (-0).toString());
console.log("lodash: " + _.toString(-0));
console.log("native: " + (-0.0).toString());
console.log("lodash: " + _.toString(-0.0));
console.log("native: " + (Infinity).toString());
console.log("lodash: " + _.toString(Infinity));
console.log("native: " + (-Infinity).toString());
console.log("lodash: " + _.toString(-Infinity));
console.log("native: " + (NaN).toString());
console.log("lodash: " + _.toString(NaN));
console.log("native: " + ({foo:'bar'}).toString());
console.log("lodash: " + _.toString({foo: 'bar'}));
console.log("native: " + [{foo:'bar'},{foo:'bar'},{foo:'bar'}].toString());
console.log("lodash: " + _.toString([{foo:'bar'},{foo:'bar'},{foo:'bar'}]));
console.log("native: " + Object.prototype.toString.call(null));
console.log("lodash: " + _.toString(null));
console.log("native: " + Object.prototype.toString.call(undefined));
console.log("lodash: " + _.toString(undefined));
console.log("native: " + document.toString());
console.log("lodash: " + _.toString(document));
console.log("native: " + (new Set()).toString());
console.log("lodash: " + _.toString(new Set()));
console.log("native: " + Symbol('foo').toString());
console.log("lodash: " + _.toString(Symbol('foo')));
console.log("native: " + 'foo'.toString());
console.log("lodash: " + _.toString('foo'));
console.log("native: " + (true).toString());
console.log("lodash: " + _.toString(true));
console.log("native: " + (BigInt(100000000000000000000)).toString());
console.log("lodash: " + _.toString(BigInt(100000000000000000000)));
console.log("native: " + (new Date()).toString());
console.log("lodash: " + _.toString(new Date()));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>
Using Selenium, the following is the code I am running on Python to get my geo-coordinates via use of the navigator web api:
coordinates = driver.execute_script(
" return () => { " +
" var savedCoordinates; " +
" " +
" navigator.geolocation.getCurrentPosition( " +
" (pos) => savedCoordinates = pos.coords, " +
" error, " +
" options); " +
" " +
" let options = { " +
" enableHighAccuracy: true, " +
" timeout: 5000, " +
" maximumAge: 0 " +
" }; " +
" " +
" function error(err) { " +
" console.warn(`ERROR(${err.code}): ${err.message}`); " +
" }; " +
" " +
" return savedCoordinates; " +
" } " )
print(coordinates)
Expected output: {latitude: XXX.XXX, longitude XX.XXXX}
Actual output: {}
Can someone help me figure out how I can get my geo-coordinates using this method?
It should work without return () => { }
coordinates = driver.execute_script(
" var savedCoordinates; " +
" " +
" navigator.geolocation.getCurrentPosition( " +
" (pos) => savedCoordinates = pos.coords, " +
" error, " +
" options); " +
" " +
" let options = { " +
" enableHighAccuracy: true, " +
" timeout: 5000, " +
" maximumAge: 0 " +
" }; " +
" " +
" function error(err) { " +
" console.warn(`ERROR(${err.code}): ${err.message}`); " +
" }; " +
" " +
" return savedCoordinates; " )
print(coordinates)
As for me this () => {} only defines function but it doesn't run it - so it returns this function, not result from function. You may need () to run it
return (() => {...code...})()
Given the following snippet:
out.println("<form action=" + "./post" + " " + "method=" + "post" + " " + "id=" + "tweetForm" + ">");
for (int i = 1; i <= twParser.currentTweetIndex; i++) {
output = twParser.tweetArray[i] + newLine;
out.println("<p>");
out.println("<textarea" + " " + "name=text" + " " + "id=\"styled\"" + " " + "maxlength=140" + " " + "cols=" + "140" + " " + "rows=" + "1" + " " + "tag=" + "text_" + String.valueOf(i) + " " + "form=" + "tweetForm" + " " + "onfocus=\"setbg('#e5fff3');\" onblur=\"setbg('white')\"" + ">" + output + "</textarea>");
out.println("<span class=label-style-countdown" + " " + "id=" + "chars" + String.valueOf(i) + ">" + String.valueOf(140 - twParser.tweetArray[i].length()) + "</span> characters remaining");
out.println("<p>");
}
out.println("<input type=" + "submit" + " " + "name=" + "post" + " " + "value=" + "post" + " " + "style=\"float: left;\"" + "/>");
out.println("<button type=\"reset\" value=\"Reset\">Reset</button>"
...that creates HTML multiple textarea elements and posts them to a servlet. But since all the textareas have the same name, only the contents of the first textarea are posted.
Is there a way to post them all?
Thanks
To have multiple inputs from same name you can use name array like
<textarea name="text[]">You text here</textarea>
which will post all the values having same name as an array.
PS: This can be done with any input types expect radio buttons
On this line:
out.println("<textarea" + " " + "name=text" + " " ...
Append i to the name of the textarea, such that the names increase as text1, text2 etc.
out.println("<textarea" + " " + "name=text" + i.toString() + " " ...
Perform the same loop on the server when receiving the POST request to receive from each textarea.
I receive from the server xhtml code which I want to show in Android app like ebook reader. For this the Monocle library was chosen.
Next I prepare webview with follow code:
contentView.addJavascriptInterface(new LectureJSInterface(), "Android");
contentView.getSettings().setAllowFileAccess(true);
contentView.getSettings().setJavaScriptEnabled(true);
contentView.setBackgroundColor(0xFFECECEC);
contentView.setWebChromeClient(new WebChromeClient());
contentView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
Global.dismissProgressDialog();
}
});
After this I download the xhtml code from the server and add to it JS code for working with Monocle:
private String prepareCode(String code) {
if ((code == null) || code.equals("")) return "";
String newCode = code.substring(code.indexOf("<html"), code.indexOf("<head>")+6);
newCode = newCode.concat(
"<script src=\"file:///android_asset/monocore.js\"></script>\n" +
"<link rel=\"stylesheet\" type=\"text/css\" href=\"file:///android_asset/monocore.css\" />\n" +
"<style>\n" +
" #reader {\n" +
" width: 100%;\n" +
" height: 100%;\n" +
" border: 0px solid #000;\n" +
" }\n" +
"</style>\n" +
"<script>\n" +
"\n" +
" var isNightMode = false;\n" +
" var isFirstLoading = false;\n" +
" var startPageNumber = 1;\n" +
"\n" +
" function setSettingsForFirstLoading(fontSize, pageNumber, nightMode) {\n" +
" Android.printLogInfo('setSettingsForFirstLoading()');\n" +
" isFirstLoading = true;\n" +
" isNightMode = nightMode;\n" +
" startPageNumber = pageNumber;\n" +
" window.changeFontSize(fontSize);\n" +
" }\n" +
"\n" +
" function changeFontSize(fontSize) {\n" +
" Android.printLogInfo('changeFontSize()');\n" +
" window.reader.formatting.setFontScale(fontSize);\n" +
" }\n" +
"\n" +
" function nightModeOn() {\n" +
" Android.printLogInfo('nightModeOn()');\n" +
" isNightMode = true;\n" +
" var i = 0;\n" +
" var frame;\n" +
" while (frame = window.reader.dom.find('component', i++)) {\n" +
" frame.contentDocument.body.style.backgroundColor = '#1F1F1F';\n" +
" frame.contentDocument.body.style.color = '#ECECEC';\n" +
" }\n" +
" }\n" +
"\n" +
" function nightModeOff() {\n" +
" Android.printLogInfo('nightModeOff()');\n" +
" isNightMode = false;\n" +
" var i = 0;\n" +
" var frame;\n" +
" while (frame = window.reader.dom.find('component', i++)) {\n" +
" frame.contentDocument.body.style.backgroundColor = '#ECECEC';\n" +
" frame.contentDocument.body.style.color = '#1F1F1F';\n" +
" }\n" +
" }\n" +
"\n" +
" function turnPage(pageNumber) {\n" +
" Android.printLogInfo('turnPage(' + pageNumber + ')');\n" +
" window.reader.moveTo({ page: pageNumber });\n" +
" }\n" +
"\n" +
" function savePercents() {\n" +
" Android.printLogInfo('savePercents()');\n" +
" Android.savePercents(window.reader.getPlace().percentAtTopOfPage());\n" +
" }\n" +
"\n" +
" function moveToPercents(percent) {\n" +
" Android.printLogInfo('moveToPercents(' + percent + ')');\n" +
" turnPage(window.reader.getPlace().pageAtPercentageThrough(percent));\n" +
" }\n" +
"\n" +
" function listenFor(evtName) {\n" +
" Monocle.Events.listen('reader', evtName, report);\n" +
" }\n" +
"\n" +
" function report(evt) {\n" +
" switch (evt.type) {\n" +
" case 'monocle:loaded':\n" +
" Android.calculateSeekBar(window.reader.getPlace().properties.component.lastPageNumber());\n" +
" break;\n" +
"\n" +
" case 'monocle:turn':\n" +
" Android.updatePagesCounter(window.reader.getPlace().pageNumber());\n" +
" break;\n" +
"\n" +
" case 'monocle:recalculated':\n" +
" if (isNightMode) nightModeOn();\n" +
" if (isFirstLoading) { isFirstLoading = false; turnPage(startPageNumber); }\n" +
" Android.calculateSeekBar(window.reader.getPlace().properties.component.lastPageNumber());\n" +
" Android.updatePagesCounter(window.reader.getPlace().pageNumber());\n" +
" break;\n" +
" }\n" +
" }\n" +
"\n" +
" function init() {\n" +
" var options = {\n" +
" flipper: Monocle.Flippers.Slider\n" +
" }\n" +
"\n" +
" listenFor('monocle:turn');\n" +
" listenFor('monocle:loaded');\n" +
" listenFor('monocle:recalculated');\n" +
"\n" +
" window.reader = Monocle.Reader('reader', null, options);\n" +
" }\n" +
"\n" +
" Monocle.Events.listen(window, 'load', init);\n" +
"</script>\n");
newCode = newCode.concat(code.substring(code.indexOf("<head>") + 6, code.indexOf("<body>") + 6));
newCode = newCode.concat("<div id=\"reader\">");
newCode = newCode.concat(code.substring(code.indexOf("<body>") + 6, code.indexOf("</body>")));
newCode = newCode.concat("</div>");
newCode = newCode.concat(code.substring(code.indexOf("</body>")));
return newCode;
}
After finishing this task the WebView loads it:
contentView.loadDataWithBaseURL(baseUrl, prepareCode(code), "text/html", "UTF-8", null);
What I have as results? I tested this app on six devices with Android 4.x and 5.x. On Android 4.x the entire content is shown correctly, but on Android 5.x I see a blank page. I should notice that the xhtml code was loaded because I can call JS-functions and get its results via JS Interface.
Are there any ideas about ways to fixing this bug?
Thanks in advance!
You can try uninstalling the webview system update.
or
Try monocle 2.3.1
or
https://github.com/joseph/Monocle/issues/259