Categories
discuss

Create json string from js Map and String

My REST controller expects request input of the following format, which it successfully converts to a Java object containing a Map and a String as parameters:

{ 
"myMap" : { 
    "key1": "value1", 
    "key2": "value2", 
    "key3": "value3"},
"myString": "string value"
}

I am getting my data from an html form like so:

var myMap = new Map();
var String = document.getElementById('String').value;
for (var i = 0 ; i<anArray.length ; i++){
    var input = document.getElementsByClassName('input_' + (i+1));
    for (var j = 0 ; j<3 ; j++){
        if (input[j].checked){
            myMap.set(input[j].name, input[j].id);
        }
    }
}

Basically, this code boils down to:

var myMap = new Map();
myMap.set("key1", "value1");
myMap.set("key2", "value2");
myMap.set("key3", "value3");

This results in a map containing {key1 => value1, key2 => value2, etc} and a String. I have been trying to turn this into a json string like so, but it doesn’t seem to work:

var myJson = {};
myJson.myMap = myMap;
myJson.myString = myString;
var json = JSON.stringify(myJson);

However, I am ending up with the following string: `{“myMap”:{},”String”:”myString”}’ . So I probably have to do something different to stringify a map, but nothing I try is working.

Can anyone help me out?

Answer

You can write a short conversion function to make a map into an object that can be stringified.

console.clear()

function mapToObj(map){
  const obj = {}
  for (let [k,v] of map)
    obj[k] = v
  return obj
}

const myMap = new Map();
myMap.set("key1", "value1");
myMap.set("key2", "value2");
myMap.set("key3", "value3");

const myString = "string value"

const myJson = {};
myJson.myMap = mapToObj(myMap);
myJson.myString = myString;
const json = JSON.stringify(myJson);

console.log(json)

Here is a version that that presumably would work where Map exists but some other ES6 constructs do not (though, this seems like an editor settings issue).

console.clear()

function mapToObj(map){
  var obj = {}
  map.forEach(function(v, k){
    obj[k] = v
  })
  return obj
}

var myMap = new Map();
myMap.set("key1", "value1");
myMap.set("key2", "value2");
myMap.set("key3", "value3");

var myString = "string value"

var myJson = {};
myJson.myMap = mapToObj(myMap);
myJson.myString = myString;
var json = JSON.stringify(myJson);

console.log(json)
Categories
discuss

Cordova – how to modify webview flags?

I want to ask about flags that are available in the normal Chrome browser (chrome://flags). Previously I was using Crosswalk with Cordova and I had the option to change stuff in config.xml by adding the preference xwalkCommandLine.

<preference name="xwalkCommandLine" value="--enable-experimental-canvas-features --ignore-gpu-blacklist" />

Since Crosswalk is basically dead, is it possible to do the same thing in Cordova? Are there other preference names (or maybe even plugins) that will enable this feature?

Answer

This does not appear to be possible in the underlying Chrome WebView that Cordova is using. Experimental features are purposely inaccessible in the WebView API that Android apps use. See the answer below about why this is not supported:

https://stackoverflow.com/a/43798884

Categories
discuss

Java flatmap Iterator, Stream>> to Pair, Stream>

I’m trying to implement a method with the following signature:

public static <A,B> Pair<Stream<A>, Stream<B>> flatten(Iterator<Pair<Stream<A>, Stream<B>>> iterator);

Where the goal of the method is to flatten each of the stream types into a single stream and wrap the output in a pair. I only have an Iterator (not an Iterable) and I can’t alter the method signature, so I have to perform the flattening in a single iteration.

My current best implementation is

public static <A,B> Pair<Stream<A>, Stream<B>> flatten(Iterator<Pair<Stream<A>, Stream<B>> iterator) {
    Stream<A> aStream = Stream.empty();
    Stream<B> bStream = Stream.empty();
    while(iterator.hasNext()) {
        Pair<Stream<A>, Stream<B>> elm = iterator.next();
        aStream = Stream.concat(aStream, elm.first);
        bStream = Stream.concat(bStream, elm.second);
    }
    return Pair.of(aStream, bStream);
}

But while this is technically correct I’m not super happy with this for two reasons:

  1. Stream.concat warns against doing this kind of thing because it may lead to a StackOverflowError.
  2. Stylistically I’d rather it be purely functional if possible instead of having to loop over the iterator and re-assign the streams throughout.

It feels like Stream#flatMap should be suited here (after transforming the input Iterator to a Stream using Guava’s Streams.stream(Iterator), but it seems to not work because of the Pair type in the middle.

One additional requirement is that any of the iterator/streams may be very large (the input could contain anywhere from a single pair of exceedingly large streams to many of one item streams, for example) so solutions ideally shouldn’t contain collecting results into in-memory collections.

Answer

Well guava’s Streams.stream is no magic and it’s actually internally just:

StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, 0), false);

So probably no need to link that to your method while you could use it directly.

And you could use Stream.Builder just for that:

public static <A, B> Pair<Stream<A>, Stream<B>> flatten(Iterator<Pair<Stream<A>, Stream<B>>> iterator) {

    Stream.Builder<Stream<A>> builderA = Stream.builder();
    Stream.Builder<Stream<B>> builderB = Stream.builder();

    iterator.forEachRemaining(pair -> {
        builderA.add(pair.first);
        builderB.add(pair.second);
    });

    return Pair.of(builderA.build().flatMap(Function.identity()), builderB.build().flatMap(Function.identity()));
}
Categories
discuss

How to add JVM options to program started by mvn spring-boot:run

What is the best way to add JVM options to the program started by mvn spring-boot:run?

Answer

You can configure spring-boot-maven-plugin to always include you jvm options when run:

<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <configuration>
        <jvmArguments>
            -Dapp.name=test
        </jvmArguments>
    </configuration>
</plugin>

Or if you don’t need that arguments to stay permanently, use this on the command line:

mvn spring-boot:run -Drun.jvmArguments="..."

Check documentation for details.

Categories
discuss

What does {app, BrowserWindow} means in JavaScript (node.js)?

While reading docs of making softwares with electron, I came across this type of code in the beginning of index.js file (the file where generally execution starts)

const {app, BrowserWindow} = require('electron')

What does {app, BrowserWindow} (the syntax, not the keywords) really means? Is it a JavaScript syntax, or a node.js thing or something exclusively related to electron?

Answer

This syntax is called ‘object destructuring’, and it is a feature of the latest version of JavaScript (JavaScript2015 aka ECMAScript 6/ES6) – app and BrowserWindow are just particular parts of electron that you want to use in this portion of your application.

It’s a way to simplify your code and to easily reference critical parts of a dependency.

Here’s a very basic example from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

var o = {p: 42, q: true};
var {p, q} = o;

console.log(p); // 42
console.log(q); // true

So in your case, electron is an imported module that would look something like (again, a gross oversimplification here):

var electron = {
    app: {
        greet: () => {
            console.log("Hello, world!")
        }
    },
    BrowserWindow: {/* some other stuff */},
    anotherMethod: {/* other stuff, which we will ignore in your app */}
}

module.exports electron

Then in your app, you import this module and you can reference the imported attributes directly:

const {app, BrowserWindow} = require('electron')

app.greet()
// "Hello, world!"

And similarly, you can reference BrowserWindow… however, you couldn’t reference anotherMethod without including it in the destructuring assignment.

Hope that’s helpful.

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..