问:
How to set default selected values in multiselect with ngModel in Angular 2
How to set default selected values in multiselect. I get current_options and all_options from database and I want to update current_options and send new values do database again.

Updating database works but when I refresh page none of options are selected.

```<code>current_options = [{id:1, name:'name1'}];                    #from database
all_options = [{id:1, name:'name1'},{id:2, name:'name2'}];   #from database
</code>```

My template:

```<code><select multiple name="type" [(ngModel)]="current_options">
    <option  *ngFor="let option of all_options" [ngValue] = "option">
        {{option.name}}
    </option>
</select>`
</code>```

答:
current_options = [all_options[0]]
To initialize the default value of your input.

Current_options need to be initialize with an array containing the same objects present in all_options.

I forked the Plunker from another answer to illustrate it.

Keep in mind that :

```<code>{id:1, name:'name1'} !== {id:1, name:'name1'}
</code>```

Edit:

Assuming current_options is already containing some value you are receiving from your server:

```<code>current_options = current_options.map((current_option) => {
   return all_options.find((all_option) => current_option.id === all_option.id);
})
</code>```

Or probably more performant:

```<code>for (let i in all_options) {
   for (let j in current_options) {
      if (all_options[i].id === current_options[j].id ) {
         current_options[j] = all_options[i];
      }
   }
}
</code>```

Edit:
According to angular documentation you can use a compare with function to specify how to assume two objects are equal.

```<code><select multiple [compareWith]="compareFn" ...>
</select>

compareFn(c1: Category, c2: Category): boolean {
  return c1 && c2 ? c1.id === c2.id : c1 === c2;
}
</code>```

Body:
How to set default selected values in multiselect. I get current_options and all_options from database and I want to update current_options and send new values do database again.

Updating database works but when I refresh page none of options are selected.

current_options = [{id:1, name:'name1'}];                    #from database
all_options = [{id:1, name:'name1'},{id:2, name:'name2'}];   #from database

My template:

<select multiple name="type" [(ngModel)]="current_options">
    <option  *ngFor="let option of all_options" [ngValue] = "option">
        {{option.name}}
    </option>
</select>`

Body:
current_options = [all_options[0]]
To initialize the default value of your input.

Current_options need to be initialize with an array containing the same objects present in all_options.

I forked the Plunker from another answer to illustrate it.

Keep in mind that :

{id:1, name:'name1'} !== {id:1, name:'name1'}

Edit:

Assuming current_options is already containing some value you are receiving from your server:

current_options = current_options.map((current_option) => {
   return all_options.find((all_option) => current_option.id === all_option.id);
})

Or probably more performant:

for (let i in all_options) {
   for (let j in current_options) {
      if (all_options[i].id === current_options[j].id ) {
         current_options[j] = all_options[i];
      }
   }
}

Edit:
According to angular documentation you can use a compare with function to specify how to assume two objects are equal.

<select multiple [compareWith]="compareFn" ...>
</select>

compareFn(c1: Category, c2: Category): boolean {
  return c1 && c2 ? c1.id === c2.id : c1 === c2;
}


来源: stackexchange

问:
How to make sure docker's time syncs with that of the host?
I have dockers running on Linode servers. At times, I see that the time is not right on the dockers. Currently I have changed the run script in every docker to include the following lines of code.

```<code>yum install -y ntp
service ntpd stop
ntpdate pool.ntp.org
</code>```

What I would ideally like to do however is that the docker should sync time with the host. Is there a way to do this?

答:
I have the following in the compose file

volumes:
  - "/etc/timezone:/etc/timezone:ro"
  - "/etc/localtime:/etc/localtime:ro"
```

Then all good in Gerrit docker with its replication_log set with correct timestamp.

ContentLicense: CC BY-SA 3.0

Body:
I have dockers running on Linode servers. At times, I see that the time is not right on the dockers. Currently I have changed the run script in every docker to include the following lines of code.

yum install -y ntp
service ntpd stop
ntpdate pool.ntp.org

What I would ideally like to do however is that the docker should sync time with the host. Is there a way to do this?

Body:
I have the following in the compose file

volumes:
  - "/etc/timezone:/etc/timezone:ro"
  - "/etc/localtime:/etc/localtime:ro"

Then all good in Gerrit docker with its replication_log set with correct timestamp.

ContentLicense: CC BY-SA 4.0


问:
Tensorflow - Linear Regression
I code tensorflow program for linear regression. I am using Gradient Descent algorithm for optimizing(Minimising) loss function. But value of loss function is increasing while executing the program. My program and output is in follow.

```<code>    import tensorflow as tf
    W = tf.Variable([.3],dtype=tf.float32)
    b = tf.Variable([-.3],dtype=tf.float32)
    X = tf.placeholder(tf.float32)
    Y = tf.placeholder(tf.float32)
    sess = tf.Session()
    init = init = tf.global_variables_initializer()
   sess.run(init)
   lm = W*X + b
   delta = tf.square(lm-Y)
   loss = tf.reduce_sum(delta)
   optimizer = tf.train.GradientDescentOptimizer(0.01)
   train = optimizer.minimize(loss)
   for i in range(8):
      print(sess.run([W, b]))
      print("loss= %f" %sess.run(loss,{X:[10,20,30,40],Y:[1,2,3,4]}))
      sess.run(train, {X: [10,20,30,40],Y: [1,2,3,4]})
   sess.close()
</code>```

Output for my program is

```<code>2017-12-07 14:50:10.517685: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.1 instructions, but these are available on your machine and could speed up CPU computations.

[array([ 0.30000001], dtype=float32), array([-0.30000001],dtype=float32)]
loss= 108.359993

[array([-11.09999943], dtype=float32), array([-0.676], dtype=float32)]
loss= 377836.000000

[array([ 662.25195312], dtype=float32), array([ 21.77807617],  dtype=float32)]
loss= 1318221568.000000

[array([-39110.421875], dtype=float32), array([-1304.26794434],  dtype=float32)]
loss= 4599107289088.000000

[array([ 2310129.25], dtype=float32), array([ 77021.109375],  dtype=float32)]
loss= 16045701465112576.000000
[array([ -1.36451664e+08], dtype=float32), array([-4549399.],  dtype=float32)]
loss= 55981405829796462592.000000

[array([  8.05974733e+09], dtype=float32), array([  2.68717856e+08],  dtype=float32)]
loss= 195312036582209632600064.000000
</code>```

Please provide me a answer why value of loss is increasing instead of decreasing.

答:
Did you try changing the learning rate? Using a lower running rate (~1e-4) and more iterations should work.

More justification as to why a lower learning rate might be required. Note that your loss function is

L = \sum (Wx+b-Y)^2

and dL/dW = \sum 2(Wx+b-Y)*x

and hessian d^2L/d^2W = \sum 2x*x

Now, your loss is diverging because learning rate is more than inverse of hessian which there will be roughly 1/(2*2900). So you should try and decrease the learning rate here.

Note: I wasn't sure how to add math to StackOverflow answer so I had to add it this way.

Title: Tensorflow - Linear Regression

Body:
I code tensorflow program for linear regression. I am using Gradient Descent algorithm for optimizing(Minimising) loss function. But value of loss function is increasing while executing the program. My program and output is in follow.

    import tensorflow as tf
    W = tf.Variable([.3],dtype=tf.float32)
    b = tf.Variable([-.3],dtype=tf.float32)
    X = tf.placeholder(tf.float32)
    Y = tf.placeholder(tf.float32)
    sess = tf.Session()
    init = init = tf.global_variables_initializer()
   sess.run(init)
   lm = W*X + b
   delta = tf.square(lm-Y)
   loss = tf.reduce_sum(delta)
   optimizer = tf.train.GradientDescentOptimizer(0.01)
   train = optimizer.minimize(loss)
   for i in range(8):
      print(sess.run([W, b]))
      print("loss= %f" %sess.run(loss,{X:[10,20,30,40],Y:[1,2,3,4]}))
      sess.run(train, {X: [10,20,30,40],Y: [1,2,3,4]})
   sess.close()

Output for my program is

2017-12-07 14:50:10.517685: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.1 instructions, but these are available on your machine and could speed up CPU computations.

[array([ 0.30000001], dtype=float32), array([-0.30000001],dtype=float32)]
loss= 108.359993

[array([-11.09999943], dtype=float32), array([-0.676], dtype=float32)]
loss= 377836.000000

[array([ 662.25195312], dtype=float32), array([ 21.77807617],  dtype=float32)]
loss= 1318221568.000000

[array([-39110.421875], dtype=float32), array([-1304.26794434],  dtype=float32)]
loss= 4599107289088.000000

[array([ 2310129.25], dtype=float32), array([ 77021.109375],  dtype=float32)]
loss= 16045701465112576.000000
[array([ -1.36451664e+08], dtype=float32), array([-4549399.],  dtype=float32)]
loss= 55981405829796462592.000000

[array([  8.05974733e+09], dtype=float32), array([  2.68717856e+08],  dtype=float32)]
loss= 195312036582209632600064.000000

Please provide me a answer why value of loss is increasing instead of decreasing.


问:
Group array some values
Hi
I'm trying to display Array that has the same type but different value.
How can I show this array in a grouped way according to the value "CAT"?

My array:

```<code>$options  = array(
    array("cat" => "Impresoras","nameProd" => "Impresora 4"),
    array("cat" => "Destructoras","nameProd" => "Destructora 3"),
    array("cat" => "Impresoras","nameProd" => "Impresora 8"),
    array("cat" => "Destructoras","nameProd" => "Destructora 5")
);
</code>```

I need print:

Impresoras: Impresora 4, Impresora 8

Destructoras: Destructora 3, Destructora 5

答:
Try this

```<code>  $options  = array(
    array("cat" => "Impresoras","nameProd" => "Impresora 4"),
    array("cat" => "Destructoras","nameProd" => "Destructora 3"),
    array("cat" => "Impresoras","nameProd" => "Impresora 8"),
    array("cat" => "Destructoras","nameProd" => "Destructora 5")
  );

  foreach ($options as $key => $value) {
    $nArray[$value['cat']][] =  $value['nameProd'];
  }
  foreach ($nArray as $key => $value) {
    echo $key.":".implode(",", $value)."<br>";
  }
</code>```

Output

```<code>Impresoras:Impresora 4,Impresora 8
Destructoras:Destructora 3,Destructora 5
</code>```

Title: Group array some values

Body:
Hi
I'm trying to display Array that has the same type but different value.
How can I show this array in a grouped way according to the value "CAT"?

My array:

$options  = array(
    array("cat" => "Impresoras","nameProd" => "Impresora 4"),
    array("cat" => "Destructoras","nameProd" => "Destructora 3"),
    array("cat" => "Impresoras","nameProd" => "Impresora 8"),
    array("cat" => "Destructoras","nameProd" => "Destructora 5")
);

I need print:

Impresoras: Impresora 4, Impresora 8

Destructoras: Destructora 3, Destructora 5

Body:
Try this

  $options  = array(
    array("cat" => "Impresoras","nameProd" => "Impresora 4"),
    array("cat" => "Destructoras","nameProd" => "Destructora 3"),
    array("cat" => "Impresoras","nameProd" => "Impresora 8"),
    array("cat" => "Destructoras","nameProd" => "Destructora 5")
  );

  foreach ($options as $key => $value) {
    $nArray[$value['cat']][] =  $value['nameProd'];
  }
  foreach ($nArray as $key => $value) {
    echo $key.":".implode(",", $value)."<br>";
  }

Output

Impresoras:Impresora 4,Impresora 8
Destructoras:Destructora 3,Destructora 5


问:
Run app in tomcat using maven with IntelliJ
Without using maven, to run the app on tomcat from the Intellij IDE, all you have to do is create an artifact and a "tomcat" run configuration pointing to that artifact, this way you can see tomcat output, restart the server, and other stuff right in the IDE.

Now using maven, there's no need to create an artifact, because maven already does the compiling, packaging, etc.

I know i can deploy it using the command mvn tomcat7:redeploy but this way i can't see standart output/errors and debug.
So what is the standard way to run the app from IntelliJ without having to create an artifact?

答:
When you setup this: n IntelliJ, open Menu > View > Tool Windows > Maven Projects, you will see this menu:

When you click on this picture you can enter the goal of Maven, for example tomcat7:run


问:
Invalid static method invocation syntax: "[MSBuild]::IsRunningFromVisualStudio()"
After upgrading to Visual Studio 2017 15.5 none of my project will load correctly. All are marked unavailable.

I'm getting the following error for every project:

error  : Invalid static method invocation syntax: "[MSBuild]::IsRunningFromVisualStudio()". Method '[MSBuild]::IsRunningFromVisualStudio' not found. Static method invocation should be of the form: $([FullTypeName]::Method()), e.g. $([System.IO.Path]::Combine(a, b)).   C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets

Reloading project produces this error prompt:

Adding new projects produce this error prompt:

答: The solution, provided by henkmollema in this thread: https://github.com/Microsoft/msbuild/issues/2775 was to start the visual studio installer from the start menu and run a repair.


问:
c++ regex: matching a label followed by comma separated values
From the string

```<code>label: first, second, third
</code>```

I want to extract:

label

first

second

third

All of the following inputs are valid:

```<code>label: first, second, third
label: first
label
</code>```

(Edit: the list can have 0, 1 or n items)

i've come up with two different patterns, none of them gives me the "right" result:

```<code>(?:(\w+ (\d+))| -> (\w+)|, (\w+))+
</code>```

gives me

label: first, second, third

, third

label

first

third

re (\w+)(?:: (\w+))?(?:, (\w+))*

gives me

label: first, second, third

label

first

third

Here is a test implementation

How can i get it to output?

label: first, second, third

label

first

second

third

Body:
From the string

label: first, second, third

I want to extract:

label

first

second

third

All of the following inputs are valid:

label: first, second, third
label: first
label

(Edit: the list can have 0, 1 or n items)

i've come up with two different patterns, none of them gives me the "right" result:

(?:(\w+ (\d+))| -> (\w+)|, (\w+))+

gives me

label: first, second, third

, third

label

first

third

re (\w+)(?:: (\w+))?(?:, (\w+))*

gives me

label: first, second, third

label

first

third

Here is a test implementation

How can i get it to output?

label: first, second, third

label

first

second

third

Body:
You may use

(\w+)(?::\s*(\w+)(?:,\s*(\w+)(?:,\s*(\w+))?)?)?

Demo


问:
Convert an array of IDs to a map object
I'm looking for a concise way of creating an object whose property names match values from an array, where all properties have the same value (e.g. true). As an example:

My ID array looks like these arbitrary (in the actual software, not necessarily unique and not necessarily numeric, but primitive) values:

```<code>var ids = [4, 15, 8, 16, 42, 23];
</code>```

I am looking for some simple call to convert this into the following object:

```<code>{ 4: true, 15: true, 8: true, 16: true, 42: true, 23: true }
</code>```

With JavaScript objects internally being hashmaps, such an object should be much more convenient for quickly checking whether a given ID is contained in the array.

Now, of course I know how to generate this object. It's a four-liner:

```<code>var idMap = {};
ids.forEach(function (v) {
    idMap[v] = true;
});
</code>```

As this pattern occurs over and over in my code (lots of different item IDs being handled in this application), I feel the percentage of "boilerplate" in this is still too large. Furthermore, it appears to me that the four-liner occasionally distracts from the actually tricky algorithms for doing something with various of these ID lists. Therefore, I am looking for a shorter way to write this, hoping that there is something built-in either to standard JavaScript or to lodash, which is already in use in our application.

The most related question I could find appears to be lodash: mapping array to object. Yet, its proposed solutions are not really shorter and more legible than the above, basically replacing one sort of boilerplate code with another sort (as in my case, I'd usually throw away what the suggested solutions use as values for the object properties and always use true or some similarly small truthy value).

Is there something built-in that allows for a very simple command like

```<code>var idMap = arrayToMap(ids);
</code>```

or

```<code>var idMap = arrayToMap(ids, true);
</code>```

whose actual name I have not yet found?

(Obviously, the fallback solution is to simply write such a function in our application. I'd prefer to stick as closely as possible with the existing functions, though, hence this question.)

答:
Well, I think you can easily map the source array to array of pairs, and then construct the object (or even to ES6 Map) easily.

Just do:

_.fromPairs(ids.map(a=>[a,true])) and that's it.

Here is an working example:

var ids = [4, 15, 8, 16, 42, 23];

var idsMap = _.fromPairs(ids.map(a=>[a,true])); // however true can be replaced with a variable

console.log(idsMap);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script></code>```

Another way:

_(ids).keyBy(v=>v).mapValues(v=>true).value()

Here is the working example:

var ids = [4, 15, 8, 16, 42, 23];

var idsMap = _(ids).keyBy(v=>v).mapValues(x=>true).value();

console.log(idsMap)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script></code>```

And, If you are really sure that (consideration) all of your id will be truthy value, then you can take that as an advantage, and just create a map with the same key/value pair, and check for truthiness with any id directly with O(1)

Just Do:

_.keyBy(ids) And you are done :)

And you don't need the additional .mapValues(v=>true) from the 2nd solution as you are aware about truthiness of values.

Here is the working snippet:

var ids = [4, 15, 8, 16, 42, 23];

var idsMap = _.keyBy(ids);

console.log(idsMap);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script></code>```

Title: Convert an array of IDs to a map object

Body:
I'm looking for a concise way of creating an object whose property names match values from an array, where all properties have the same value (e.g. true). As an example:

My ID array looks like these arbitrary (in the actual software, not necessarily unique and not necessarily numeric, but primitive) values:

var ids = [4, 15, 8, 16, 42, 23];

I am looking for some simple call to convert this into the following object:

{ 4: true, 15: true, 8: true, 16: true, 42: true, 23: true }

With JavaScript objects internally being hashmaps, such an object should be much more convenient for quickly checking whether a given ID is contained in the array.

Now, of course I know how to generate this object. It's a four-liner:

var idMap = {};
ids.forEach(function (v) {
    idMap[v] = true;
});

As this pattern occurs over and over in my code (lots of different item IDs being handled in this application), I feel the percentage of "boilerplate" in this is still too large. Furthermore, it appears to me that the four-liner occasionally distracts from the actually tricky algorithms for doing something with various of these ID lists. Therefore, I am looking for a shorter way to write this, hoping that there is something built-in either to standard JavaScript or to lodash, which is already in use in our application.

The most related question I could find appears to be lodash: mapping array to object. Yet, its proposed solutions are not really shorter and more legible than the above, basically replacing one sort of boilerplate code with another sort (as in my case, I'd usually throw away what the suggested solutions use as values for the object properties and always use true or some similarly small truthy value).

Is there something built-in that allows for a very simple command like

var idMap = arrayToMap(ids);

or

var idMap = arrayToMap(ids, true);

whose actual name I have not yet found?

(Obviously, the fallback solution is to simply write such a function in our application. I'd prefer to stick as closely as possible with the existing functions, though, hence this question.)

Body:
Well, I think you can easily map the source array to array of pairs, and then construct the object (or even to ES6 Map) easily.

Just do:

_.fromPairs(ids.map(a=>[a,true])) and that's it.

Here is an working example:

var ids = [4, 15, 8, 16, 42, 23];

var idsMap = _.fromPairs(ids.map(a=>[a,true])); // however true can be replaced with a variable

console.log(idsMap);

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>

Another way:

_(ids).keyBy(v=>v).mapValues(v=>true).value()

Here is the working example:

var ids = [4, 15, 8, 16, 42, 23];

var idsMap = _(ids).keyBy(v=>v).mapValues(x=>true).value();

console.log(idsMap)

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>

And, If you are really sure that (consideration) all of your id will be truthy value, then you can take that as an advantage, and just create a map with the same key/value pair, and check for truthiness with any id directly with O(1)

Just Do:

_.keyBy(ids) And you are done :)

And you don't need the additional .mapValues(v=>true) from the 2nd solution as you are aware about truthiness of values.

Here is the working snippet:

var ids = [4, 15, 8, 16, 42, 23];

var idsMap = _.keyBy(ids);

console.log(idsMap);

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>


问:
Print the contents of a DIV
Whats the best way to print the contents of a DIV?</p>

答:
Note: This works with jQuery enabled sites only

It is very simple with this cool trick. It worked for me in Google Chrome browser. Firefox wont allow you to print to PDF without a plugin.

First, open the inspector using (Ctrl + Shift + I) / (Cmd + Option + I).

Type this code in the console:

```<code>var jqchild = document.createElement('script');
jqchild.src = "https://cdnjs.cloudflare.com/ajax/libs/jQuery.print/1.5.1/jQuery.print.min.js";
document.getElementsByTagName('body')[0].appendChild(jqchild);
$("#myDivWithStyles").print(); // Replace ID with yours
</code>```

It launches the print dialog. Take a physical print or save it to PDF(in chrome). Done!

The logic is simple. We are creating a new script tag and attaching it in front of closing body tag. We injected a jQuery print extension into the HTML. Change myDivWithStyles with your own Div tag ID. Now it takes cares of preparing a printable virtual window.

Try it on any site. Only caveat is sometimes trickily written CSS can cause missing of styles. But we get the content most of times.

ContentLicense: CC BY-SA 2.5

Title: Print the contents of a DIV

Body:
Note: This works with jQuery enabled sites only

It is very simple with this cool trick. It worked for me in Google Chrome browser. Firefox wont allow you to print to PDF without a plugin.

First, open the inspector using (Ctrl + Shift + I) / (Cmd + Option + I).

Type this code in the console:

var jqchild = document.createElement('script');
jqchild.src = "https://cdnjs.cloudflare.com/ajax/libs/jQuery.print/1.5.1/jQuery.print.min.js";
document.getElementsByTagName('body')[0].appendChild(jqchild);
$("#myDivWithStyles").print(); // Replace ID with yours

It launches the print dialog. Take a physical print or save it to PDF(in chrome). Done!

The logic is simple. We are creating a new script tag and attaching it in front of closing body tag. We injected a jQuery print extension into the HTML. Change myDivWithStyles with your own Div tag ID. Now it takes cares of preparing a printable virtual window.

Try it on any site. Only caveat is sometimes trickily written CSS can cause missing of styles. But we get the content most of times.


问:
How to know if an event is still bubbling?
I have an SVG element with some nested elements. I have attached a mouseout handler to the SVG element. When I press the mouse in the middle of the SVG element and move it out of the SVG element, I get the following list of events:

```<code>down
out <path ...>
out <circle r="39.5">
out <circle r="40">
out <circle r="49.5">
out <svg ...>
up
</code>```

This means the mouse has first left the path, than it has left the three concentric circles and finally it leaves the SVG element. I am just interested in the last event, which affects the element, who has the handler attached. The SVG element gets all the other events, because they bubble to the SVG element.

How can I know, if an event has been bubbled? How can I ignore those events, which do not affect the element, which has the handler attached?

答:
You can use event.target property to see actually which elements was triggered the event.

$('#myDiv').on('click', function(e) {
  console.log(e.target.id);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#myDiv {
  background-color: red;
  width: 100px;
  height: 100px;
}</code>```

  <button id='myButton'>Click me</button>

```

Body:
I have an SVG element with some nested elements. I have attached a mouseout handler to the SVG element. When I press the mouse in the middle of the SVG element and move it out of the SVG element, I get the following list of events:

down
out <path ...>
out <circle r="39.5">
out <circle r="40">
out <circle r="49.5">
out <svg ...>
up

This means the mouse has first left the path, than it has left the three concentric circles and finally it leaves the SVG element. I am just interested in the last event, which affects the element, who has the handler attached. The SVG element gets all the other events, because they bubble to the SVG element.

How can I know, if an event has been bubbled? How can I ignore those events, which do not affect the element, which has the handler attached?

Body:
You can use event.target property to see actually which elements was triggered the event.

$('#myDiv').on('click', function(e) {
  console.log(e.target.id);
});

#myDiv {
  background-color: red;
  width: 100px;
  height: 100px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='myDiv'>
  <button id='myButton'>Click me</button>
</div>


问:
how to set format while reading RTF files in java?
I need to read some RTF files in Java .So i got a code which worked fine initially . But my question is that  : Is it possible to set format (Eg: UTF-8 ,UTF-16,etc) while reading these files ?

Here i have posted the code which reads RTF file :

```<code>public static String rtf_read(String fileName) throws Exception, BadLocationException
{
JEditorPane p = new JEditorPane();
p.setContentType("text/rtf");
EditorKit rtfKit = p.getEditorKitForContentType("text/rtf");
rtfKit.read(new FileReader(fileName), p.getDocument(), 1);
rtfKit = null;
// convert to text
EditorKit txtKit = p.getEditorKitForContentType("text/plain");
Writer writer = new StringWriter();
txtKit.write(writer, p.getDocument(), 0, p.getDocument().getLength());
String documentText = writer.toString();
return documentText;
}
</code>```

答:
It works for me with the following lines of code:</p>

```<code>FileInputStream is = new FileInputStream(rtfFilePath);
InputStreamReader isr = new InputStreamReader(is, "UTF-8");
BufferedReader buffReader = new BufferedReader(isr);
rtfKit.read(buffReader, p.getDocument(), 0);
</code>```

Body:
I need to read some RTF files in Java .So i got a code which worked fine initially . But my question is that  : Is it possible to set format (Eg: UTF-8 ,UTF-16,etc) while reading these files ?

Here i have posted the code which reads RTF file :

public static String rtf_read(String fileName) throws Exception, BadLocationException
{
JEditorPane p = new JEditorPane();
p.setContentType("text/rtf");
EditorKit rtfKit = p.getEditorKitForContentType("text/rtf");
rtfKit.read(new FileReader(fileName), p.getDocument(), 1);
rtfKit = null;
// convert to text
EditorKit txtKit = p.getEditorKitForContentType("text/plain");
Writer writer = new StringWriter();
txtKit.write(writer, p.getDocument(), 0, p.getDocument().getLength());
String documentText = writer.toString();
return documentText;
}

Body:
It works for me with the following lines of code:

FileInputStream is = new FileInputStream(rtfFilePath);
InputStreamReader isr = new InputStreamReader(is, "UTF-8");
BufferedReader buffReader = new BufferedReader(isr);
rtfKit.read(buffReader, p.getDocument(), 0);


问:
Android install apk programmatically
Is it possible to install an apk programmatically in the background or does the user have to accept the installation.

My scenario is that I want my employees to all have the same set of applications installed.

Of course they can install applications by them self, but I want them all to have at least some applications installed.

I'm not talking about installing applications from the market.

答:
Some more requirements would be useful. Is the user required to have these apps? Do you want the apps to be updatable through the market? here's my thoughts in lieu of that information ...

The problem with not going through the market is that they won't get update notices and won't see those apps in the "my apps" list in the market. i'd rethink that ... It's probably not what the user wants, unless you are installing for example enterprise apps that aren't on the market anyway.

You could for example create a "recommended apps" app. It can show your list of apps, and indicate which are installed, and link to the market install page. This of course doesn't force them to have the app installed, but this is actually a friendlier thing to do.

There's also nothing stopping you from creating your own market app. The tools are all there in the SDK. Personally, I'd hate this as a user and would prefer the lighter weight integration on top of the existing market I mentioned above.

Title: Android install apk programmatically


问:
angular ng-repeat with condition
How do you do something like this in angular with ng-repeat?
I'll be using the example from the documentation which inits an array with 2 friends, what if I wanted to only do a repeat for all friends that are 26 and older?</p>

```<code>    <!doctype html>
<html ng-app>
<head>
<script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
</head>
<body>
<div ng-init="friends = [{name:'John', age:25}, {name:'Mary', age:28}]">
I have {{friends.length}} friends. They are:
<ul>
<li ng-repeat="friend in friends">
[{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
</li>
</ul>
</div>
</body>
</html>
</code>```

答:
I used a filter in ng-repeat to:

```<code><div ng-repeat="product in products | filter:{ colour: by_colour }">
</code>```

Title: angular ng-repeat with condition

Body:
How do you do something like this in angular with ng-repeat?
I'll be using the example from the documentation which inits an array with 2 friends, what if I wanted to only do a repeat for all friends that are 26 and older?

    <!doctype html>

I have {{friends.length}} friends. They are:

[{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.

Body:
I used a filter in ng-repeat to:

<div ng-repeat="product in products | filter:{ colour: by_colour }">


问:
'XCDYouTubeKit/XCDYouTubeKit.h' file not found
I am trying to import a new dependency. I successfully used XCDYouTubeKit before but now after I run the command "pod install" I get this error:

'XCDYouTubeKit/XCDYouTubeKit.h' file not found

Here is my podfile:

```<code>pod "XCDYouTubeKit", "~> 2.5.3"

platform :ios, '7.0'
pod 'CocoaLumberjack'

pod 'XCDLumberjackNSLogger', '~> 1.0.0'

target 'MyApp' do
    pod 'MBProgressHUD', '~> 1.0.0'
    pod 'QRCodeReaderViewController', '~> 4.0.2'
end
</code>```

Output of "pod install" on terminal:

```<code>Analyzing dependencies
Downloading dependencies
Using CocoaLumberjack (2.2.0)
Using MBProgressHUD (1.0.0)
Using NSLogger (1.5.1)
Using QRCodeReaderViewController (4.0.2)
Using XCDLumberjackNSLogger (1.0.2)
Using XCDYouTubeKit (2.5.3)
Generating Pods project
Integrating client project
Sending stats
Pod installation complete! There are 5 dependencies from the Podfile
and 6 total pods installed.
</code>```

答: in Edit Scheme - build uncheck "Projectname"Tests's analyze and run , then OK.</p>

Body:
I am trying to import a new dependency. I successfully used XCDYouTubeKit before but now after I run the command "pod install" I get this error:

'XCDYouTubeKit/XCDYouTubeKit.h' file not found

Here is my podfile:

pod "XCDYouTubeKit", "~> 2.5.3"

platform :ios, '7.0'
pod 'CocoaLumberjack'

pod 'XCDLumberjackNSLogger', '~> 1.0.0'

target 'MyApp' do
    pod 'MBProgressHUD', '~> 1.0.0'
    pod 'QRCodeReaderViewController', '~> 4.0.2'
end

Output of "pod install" on terminal:

Analyzing dependencies
Downloading dependencies
Using CocoaLumberjack (2.2.0)
Using MBProgressHUD (1.0.0)
Using NSLogger (1.5.1)
Using QRCodeReaderViewController (4.0.2)
Using XCDLumberjackNSLogger (1.0.2)
Using XCDYouTubeKit (2.5.3)
Generating Pods project
Integrating client project
Sending stats
Pod installation complete! There are 5 dependencies from the Podfile
and 6 total pods installed.


问:
How to change Text Value after presshed button, React native
I'm developing an app with react native, and now i should update a text of Text label after a button click. The problem is that I can't use state for do this, because I have a lot Text and more I don't know in first how many are these.
I've tried this piece of code:

```<code>_onPressAction = (txtItemValue)=> {
       console.log(txtItemValue);
       txtItemValue.props.children = "Hello";
}
</code>```

but in this mode I can see all property of my Text but I can't able to change it's value.
There is a method for do this, without use the state?

答:
Try this :

```<code>  updateText = () => {
  this.setState({myText: 'My Changed Text'})
</code>```

This can also be used if you want to change your text dynamically.

Body:
I'm developing an app with react native, and now i should update a text of Text label after a button click. The problem is that I can't use state for do this, because I have a lot Text and more I don't know in first how many are these.
I've tried this piece of code:

_onPressAction = (txtItemValue)=> {
       console.log(txtItemValue);
       txtItemValue.props.children = "Hello";
}

but in this mode I can see all property of my Text but I can't able to change it's value.
There is a method for do this, without use the state?

Body:
Try this :

  updateText = () => {
  this.setState({myText: 'My Changed Text'})

This can also be used if you want to change your text dynamically.


问:
Enabling SSL on localhost IIS
I run localhost on my Windows 8.1 (Bootcamp on Mac) and need to enable ssl.

I have already default server certificates on 127.0.0.1 and localhost.
I have the localhost one assigned to my websites on port 443.

https still returns security error so I need to work on http

My websites run on 44300 port (eg. localhost:44300)
I tried to bind the certificate to 44300, still it didn't work.

How to make my locahost to work with https? Thanks

EDIT

The certificate is issued by localhost and is within Trusted Root Certification Authorities:

Btw I followed this thread to issue the certificate for my website: Enable SSL in Visual Studio

答:
Try to install Microsoft IIS Administration from https://manage.iis.net/get
it will create a certification for your local server
then use https://manage.iis.net/connect , get an Access Token and connect it
check your localhost on https https://localhost

Title: Enabling SSL on localhost IIS


问:
Quick successful exit from C++ with lots of objects allocated
I'm looking for a way to quickly exit a C++ that has allocated a lot of structures in memory using C++ classes.  The program finishes correctly, but after the final "return" in the program, all of the auto-destructors kick in.  The problem is the program has allocated about 15GB of memory through lots of C++ class structures, and this auto-destruct process takes about 1 more hour itself to complete as it walks through all of the structures - even though I don't care about the results.  The program only took 1 hour to complete the task up to this point.  I would like to just return to the OS and let it do its normal wholesale process allocation deletion - which is very quick.  I've been doing this by manually killing the process during the cleanup stage - but am looking for a better programic solution.

I would like to return a success to the OS, but don't care to keep any of the memory content.  The program does perform a lot of dynamic allocation/deallocation during the normal processing, so it's not just simple heap management.

Any opinions?

答:
The possible strategies depend on the number of objects that are directly visible in main through which you access the 15GB of data and if these are local to main or statically allocated.

If all access to the 15GB of data is through local objects in main, then you can simply replace the return 0; at the end of main with exit(0);.

exit will terminate your application and trigger cleanup of statically allocated variables, but not of local variables.

If the data is accessed through a handful of statically allocated variables, you could turn them into pointers (or references) to dynamically allocated memory and deliberately leak that.


问:
HTML Form IF statements
I'm new to HTML and javascript and I have a problem with a code sample. Basically the code is intended to use with checkboxes but I want it to be used with a certain dropdownmenu aka select option.

```<code><input id="more" type="checkbox">Add More Users</input>
<div id="yourDiv"> ...other form... </div>

<script>
window.onload = function () {
    document.getElementById('more').onclick = function () {
        if (this.checked)
            document.getElementById('yourDiv').style.display = 'block';
        else
            document.getElementById('yourDiv').style.display = 'none';
    }
}
</script>
</code>```

What I want it to do is check the menubar onchange and show a new menubar depending on what selection the user picks. So for example option 1 would open menubar1 and so on.

So far I worked out the code below, I do not know if it's even close to a solution though.

So this code below is what triggers the script

```<code><select id="Ärende" name="Ärende" required onchange=FuncÄrende()>
          <option id="BeställningY" value="Beställning">Beställning</option>
          <option id="AnmälanY" value="Anmälan">Anmälan</option>
          <option id="BehörighetY" value="Behörighet">Behörighet</option>
          <option id="MiljörondY" value="Miljörond">Miljörond</option>
          <option id="AnnatY" value="Annat">Annat</option>
        </select>
</code>```

This code below is the script which will "unlock/show" the different divs I have all the other menubars in. This code is for the BeställningDiv. The rest of them looks the same with some differences ofc, so I only include one of em.

```<code>    <script>
            function FuncÄrende() {
              var Ärende = document.getElementById("Ärende");
              var ÄrendeValue = Ärende.options[Ärende.selectedIndex].value;

              if      (document.getElementById('BeställningY').value == "Beställning") {
                document.getElementById("BeställningDiv").style.display == "block";
                document.getElementById("AnmälanDiv").style.display == "none";
                document.getElementById("BehörighetDiv").style.display == "none";
                document.getElementById("MiljörondDiv").style.display == "none";
                document.getElementById("AnnatDiv").style.display == "none";
}
        }
      </script>
</code>```

And finally this code below is one example of the different divs that the script will unlock.

```<code><div id="BeställningDiv" style="display:none;">
    <h4 id="BeställningT">Beställning</h4>
        <select id="Beställning" name="Beställning">
          <option value="IT-Utrustning">IT-Utrustning</option>
          <option value="Kontors materiell">Kontors materiell</option>
          <option value="Belysning">Belysning</option>
          <option value="Ergonomi">Ergonomi</option>
        </select>
</div>
</code>```

And please supply me with easy to understand solutions as I'm very new to HTML. I spent about 9 hours in my whole life with HTML and this is how far Ive come. Thanks in advance - Kind regards,
Oliver

答:
Thanks for all the help, the final solution I decided to use was the following

```<code><script>
        $("#Kablarsladdarladdare").change(function(){
          if($(this).val() == "Sladd"){
            $("#SladdDetaljDiv").show();
            $("#SladdDetalj").prop("disabled", false);
          }else{
            $("#SladdDetaljDiv").hide();
            $("#SladdDetalj").prop("disabled", true);
          }
        });
      </script>
</code>```

This is repeating on each "select" to determine which new selection should be visible.

Title: HTML Form IF statements

Body:
I'm new to HTML and javascript and I have a problem with a code sample. Basically the code is intended to use with checkboxes but I want it to be used with a certain dropdownmenu aka select option.

<input id="more" type="checkbox">Add More Users</input>

 ...other form...

What I want it to do is check the menubar onchange and show a new menubar depending on what selection the user picks. So for example option 1 would open menubar1 and so on.

So far I worked out the code below, I do not know if it's even close to a solution though.

So this code below is what triggers the script

<select id="Ärende" name="Ärende" required onchange=FuncÄrende()>
          <option id="BeställningY" value="Beställning">Beställning</option>
          <option id="AnmälanY" value="Anmälan">Anmälan</option>
          <option id="BehörighetY" value="Behörighet">Behörighet</option>
          <option id="MiljörondY" value="Miljörond">Miljörond</option>
          <option id="AnnatY" value="Annat">Annat</option>
        </select>

This code below is the script which will "unlock/show" the different divs I have all the other menubars in. This code is for the BeställningDiv. The rest of them looks the same with some differences ofc, so I only include one of em.

And finally this code below is one example of the different divs that the script will unlock.

Beställning

        <select id="Beställning" name="Beställning">
          <option value="IT-Utrustning">IT-Utrustning</option>
          <option value="Kontors materiell">Kontors materiell</option>
          <option value="Belysning">Belysning</option>
          <option value="Ergonomi">Ergonomi</option>
        </select>

And please supply me with easy to understand solutions as I'm very new to HTML. I spent about 9 hours in my whole life with HTML and this is how far Ive come. Thanks in advance - Kind regards,
Oliver

Body:
Thanks for all the help, the final solution I decided to use was the following

<script>
        $("#Kablarsladdarladdare").change(function(){
          if($(this).val() == "Sladd"){
            $("#SladdDetaljDiv").show();
            $("#SladdDetalj").prop("disabled", false);
          }else{
            $("#SladdDetaljDiv").hide();
            $("#SladdDetalj").prop("disabled", true);
          }
        });
      </script>

This is repeating on each "select" to determine which new selection should be visible.


问:
Sum values grouped by key in list of dict
I have a list of dicts and now I am trying to find the total jobs for each remote identifier.

In this case I am expecting  for the id 64 -> 11 jobs and 68 -> 0 jobs

```<code>[{
    'jobs': {
        'count': 4
    },
    'remote_identifier': {
        'id': '64'
    }
}, {
    'jobs': {
        'count': 0
    },
    'remote_identifier': {
        'id': '68'
    }
}, {
    'jobs': {
        'count': 7
    },
    'remote_identifier': {
        'id': '64'
    }
}]
</code>```

I already tried something like this, but I don't know how to adapt it to my needs, since that only counts the number of occurrences.

```<code>from collections import Counter
print Counter(item['remote_identifier']['id'] for item in items )
</code>```

答:
You can use a defaultdict to add up the counts:

```<code>from collections import defaultdict

jobs = [{
    'jobs': {
        'count': 4
    },
    'remote_identifier': {
        'id': '64'
    }
}, {
    'jobs': {
        'count': 0
    },
    'remote_identifier': {
        'id': '68'
    }
}, {
    'jobs': {
        'count': 7
    },
    'remote_identifier': {
        'id': '64'
    }
}]

counts = defaultdict(int)

for job in jobs:
    counts[job['remote_identifier']['id']] += job['jobs']['count']

print(counts)
</code>```

Output:

```<code>defaultdict(<class 'int'>, {'64': 11, '68': 0})
</code>```

Body:
I have a list of dicts and now I am trying to find the total jobs for each remote identifier.

In this case I am expecting  for the id 64 -> 11 jobs and 68 -> 0 jobs

[{
    'jobs': {
        'count': 4
    },
    'remote_identifier': {
        'id': '64'
    }
}, {
    'jobs': {
        'count': 0
    },
    'remote_identifier': {
        'id': '68'
    }
}, {
    'jobs': {
        'count': 7
    },
    'remote_identifier': {
        'id': '64'
    }
}]

I already tried something like this, but I don't know how to adapt it to my needs, since that only counts the number of occurrences.

from collections import Counter
print Counter(item['remote_identifier']['id'] for item in items )

Body:
You can use a defaultdict to add up the counts:

from collections import defaultdict

jobs = [{
    'jobs': {
        'count': 4
    },
    'remote_identifier': {
        'id': '64'
    }
}, {
    'jobs': {
        'count': 0
    },
    'remote_identifier': {
        'id': '68'
    }
}, {
    'jobs': {
        'count': 7
    },
    'remote_identifier': {
        'id': '64'
    }
}]

counts = defaultdict(int)

for job in jobs:
    counts[job['remote_identifier']['id']] += job['jobs']['count']

print(counts)

Output:

defaultdict(<class 'int'>, {'64': 11, '68': 0})


问:
How do you turn a FileSet into a list of Files in a Mojo
I'm writing my first Maven Mojo, in it I'm wanting to take a file set and process all the files it refers to.

In pseudo code what I'd like to do...

```<code>void myCode(org.apache.maven.model.FileSet fileSet) {
    List<java.io.File> files = FileSetTransformer.toFileList(fileSet);
    for (File f : files) {
        doSomething(f);
    }
}
</code>```

So what I'm wanting is the real code for "FileSetTransformer.toFileList", it seems to me like a very common thing to want to do but I can't seem to find out how to do it.

答:
Thanks emeraldjava, that gives me enough to work out the answer to my question.

plexus-utils has a utility class called FileUtils, you can add a dependency on it thus:

```<code><dependency>
  <groupId>org.codehaus.plexus</groupId>
  <artifactId>plexus-utils</artifactId>
  <version>1.1</version>
</dependency>
</code>```

Once you have FileUtils you can implement the FileSetTransformer thus:

```<code>public final class FileSetTransformer {
        private FileSetTransformer () {
        }

        public static List<File> toFileList(FileSet fileSet) {
                File directory = new File(fileSet.getDirectory());
                String includes = toString(fileSet.getIncludes());
                String excludes = toString(fileSet.getExcludes());
                return FileUtils.getFiles(directory, includes, excludes);
        }

        private static String toString(List<String> strings) {
                StringBuilder sb = new StringBuilder();
                for (String string : strings) {
                        if (sb.length() > 0)
                                sb.append(", ");
                        sb.append(string);
                }
                return sb.toString();
        }
}
</code>```

Body:
I'm writing my first Maven Mojo, in it I'm wanting to take a file set and process all the files it refers to.

In pseudo code what I'd like to do...

void myCode(org.apache.maven.model.FileSet fileSet) {
    List<java.io.File> files = FileSetTransformer.toFileList(fileSet);
    for (File f : files) {
        doSomething(f);
    }
}

So what I'm wanting is the real code for "FileSetTransformer.toFileList", it seems to me like a very common thing to want to do but I can't seem to find out how to do it.

Body:
Thanks emeraldjava, that gives me enough to work out the answer to my question.

plexus-utils has a utility class called FileUtils, you can add a dependency on it thus:

<dependency>
  <groupId>org.codehaus.plexus</groupId>
  <artifactId>plexus-utils</artifactId>
  <version>1.1</version>
</dependency>

Once you have FileUtils you can implement the FileSetTransformer thus:

public final class FileSetTransformer {
        private FileSetTransformer () {
        }

        public static List<File> toFileList(FileSet fileSet) {
                File directory = new File(fileSet.getDirectory());
                String includes = toString(fileSet.getIncludes());
                String excludes = toString(fileSet.getExcludes());
                return FileUtils.getFiles(directory, includes, excludes);
        }

        private static String toString(List<String> strings) {
                StringBuilder sb = new StringBuilder();
                for (String string : strings) {
                        if (sb.length() > 0)
                                sb.append(", ");
                        sb.append(string);
                }
                return sb.toString();
        }
}


问:
Combine 2 Arrays of Different Lengths
I have two arrays, each of different counts, the example I'm working with is there's 132 in one and 136 in the other,

I need to array_combine() them (make the first one the key, and the second one the value). In my example I would like to keep 132 key/value pairs and drop of the extra 4 that have no corresponding match.

I have currently got this function (which I found on php.net's docs of array_combine()), but it isn't working:

```<code>function array_combine2($arr1, $arr2) {
            $count1 = count($arr1);
            $count2 = count($arr2);
            $numofloops = $count2/$count1;

            $i = 0;
            while($i < $numofloops){
                $arr3 = array_slice($arr2, $count1*$i, $count1);
                $arr4[] = array_combine($arr1,$arr3);
                $i++;
            }

            return $arr4;
     }
</code>```

I keep getting back

Warning: array_combine() [function.array-combine]: Both parameters
  should have an equal number of elements on the line that starts with
  $arr4[] = ...

Any advice would help,

thanks!

答:
```<code>function array_combine2($arr1, $arr2) {
    $count = min(count($arr1), count($arr2));
    return array_combine(array_slice($arr1, 0, $count), array_slice($arr2, 0, $count));
}
</code>```

Title: Combine 2 Arrays of Different Lengths

Body:
I have two arrays, each of different counts, the example I'm working with is there's 132 in one and 136 in the other,

I need to array_combine() them (make the first one the key, and the second one the value). In my example I would like to keep 132 key/value pairs and drop of the extra 4 that have no corresponding match.

I have currently got this function (which I found on php.net's docs of array_combine()), but it isn't working:

function array_combine2($arr1, $arr2) {
            $count1 = count($arr1);
            $count2 = count($arr2);
            $numofloops = $count2/$count1;

            $i = 0;
            while($i < $numofloops){
                $arr3 = array_slice($arr2, $count1*$i, $count1);
                $arr4[] = array_combine($arr1,$arr3);
                $i++;
            }

            return $arr4;
     }

I keep getting back

Warning: array_combine() [function.array-combine]: Both parameters
  should have an equal number of elements on the line that starts with
  $arr4[] = ...

Any advice would help,

thanks!


问:
Improve performance of dynamically adding views in a layout

Working on app in which there are forms.
Forms have categories A, B, C and D.

I receive JSON of form from server and i have to convert it in Form(layout).

A form may contain one field or 100 depending on category.

What i want: If there is a form with 100 fields how can improve performance of loading form.

What I'm doing: I have loop of fields size() and checking each field type if it is MCQ(Multiple Choice Question) I have model of RadioGroup which add in ViewGroup in loop.

答:
@A.H.Khawer, Two approaches can be used.

One is what you are doing it assuming that json response that you are receiving is not controlled by you then keep on doing it. There are some libraries that can be used to reduce some boilerplate code from your side but they still do the same thing.

Second approach, if json response that you are getting is from your own Web API to make the forms dynamic and change without App update then in that case, try ReactNative (link: https://facebook.github.io/react-native/).
There are many more JS based Frameworks available to do the same.


问:
How to find the last child in lodash map object?
I looping the array of lists by lodash map function and I've try to remove the Image on last child. But I couldn't find solution. </p>

```<code> const menus =[
    {
        name: 'Home',
        key:'dashboard'
    },
    {
        name:'change your pin',
        key:'resetpin'
    },
    {
        name:'Contact',
        key:'contact'
    },
    {
        name:'Sign Out',
        key:'signout'
    }
]
const menuList = map(menus, (el, i) => {
        return <Main>
            <Row>
                <Text />
                <Image />
            </Row>
        </Main>
})
</code>```

<p>I don't want the image on last loop </p>

答:
Actually the last child's Image only need to be removed. So I achieved by this code.    </p>

```<code>const menuLength = menus.length;
const menuList = map(menus, (el, i) => {
if (menuLength === i + 1) {
        return <Main>
            <Row>
                <Text />
            </Row>
        </Main>
}else {
return <Main>
            <Row>
                <Text />
                <Image />
            </Row>
        </Main>
})
</code>```

Body:
I looping the array of lists by lodash map function and I've try to remove the Image on last child. But I couldn't find solution.

 const menus =[
    {
        name: 'Home',
        key:'dashboard'
    },
    {
        name:'change your pin',
        key:'resetpin'
    },
    {
        name:'Contact',
        key:'contact'
    },
    {
        name:'Sign Out',
        key:'signout'
    }
]
const menuList = map(menus, (el, i) => {
        return
            <Row>
                <Text />
                <Image />
            </Row>

})

I don't want the image on last loop

Body:
Actually the last child's Image only need to be removed. So I achieved by this code.

const menuLength = menus.length;
const menuList = map(menus, (el, i) => {
if (menuLength === i + 1) {
        return <Main>
            <Row>
                <Text />
            </Row>
        </Main>
}else {
return <Main>
            <Row>
                <Text />
                <Image />
            </Row>
        </Main>
})


问:
How SQL query result insert in temp table?
I have a SQL query (SQL Server) and it generate reports, I want to store that exact report in temp table so I can play with it later. Now question is do I need to create temp table first and then store SQL query result into it, or is there any way to dynamically create table and store query result? </p>

答:
Suppose your existing reporting query  is </p>

```<code>Select EmployeeId,EmployeeName
from Employee
Where EmployeeId>101 order by EmployeeName
</code>```

<p>and you have to save this data into temparory table then you query goes to </p>

```<code>Select EmployeeId,EmployeeName
into #MyTempTable
from Employee
Where EmployeeId>101 order by EmployeeName
</code>```

Body:
Suppose your existing reporting query  is

Select EmployeeId,EmployeeName
from Employee
Where EmployeeId>101 order by EmployeeName

and you have to save this data into temparory table then you query goes to

Select EmployeeId,EmployeeName
into #MyTempTable
from Employee
Where EmployeeId>101 order by EmployeeName


问:
Firebase Storage for IOS not uploading .MOV from Camera Roll
I'm retrieving the URL (file:///var/mobile/Media/DCIM/100APPLE/IMG_0840.MOV) from PHAsset object and am able to replay the video fine on the device.  However, when it comes time to upload/putfile on Firebase Storage, I don't even get my completionHandler back.

```<code>    //requesting url from asset
    PHImageManager.default().requestAVAsset(forVideo: asset, options: options, resultHandler: { (videoAsset, audioMix, info) in

            if let assetURL = videoAsset as? AVURLAsset {

               let url = assetURL.url

               //upload from url
            let storageRef = Storage.storage().reference().child("videos").child("\(memory.ID!)")
            let uploadMetaData = StorageMetadata()
            uploadMetaData.contentType = "video/quicktime"
               self.storageRef.putFile(from: url, metadata: uploadMetaData) { (metaData, error) in

                if error != nil {
                    print(error!.localizedDescription)
                }
            }
</code>```

If I'm uploading an .mp4 file from AVFoundation capture with a local url like this, (file:///var/mobile/Containers/Data/Application/209BB017-13C7-4432-AFE4-EC3A13469900/Documents/ff49bbc9ac794ed28d6f25944f128933.mp4), it works fine.

I've also tried uploading an .MOV file on the Firebase Storage console and that also works.

Thanks

答:
Sometimes PHAssets does not returns us with a URLAsset so we must check whether the given Asset is an AVURLAsset and if not we must save this asset in our documents directory and then obtain the url from documents directory.

```<code>func uploadVideoToFirebase(content: PHAsset) {
    let options = PHVideoRequestOptions()
    options.isNetworkAccessAllowed = true
    PHImageManager.default().requestAVAsset(forVideo: content, options: options) { (asset, mix, args) in
        if let asset = asset as? AVURLAsset {
            let url = asset.url
            // URL OF THE VIDEO IS GOT HERE
        } else {
            guard let asset = asset else {return}
            self.startAnimating(message: "Processing.")
            self.saveVideoInDocumentsDirectory(withAsset: asset, completion: { (url, error) in
                if let error = error {
                    print(error.localizedDescription)
                }
                if let url = url {
                    // SAVED IN DOCUMENTS DIRECTORY AND URL IS GOT HERE
                }
            })
        }
    }
}
</code>```

Saving into Documents Directory:

```<code>func saveVideoInDocumentsDirectory(withAsset asset: AVAsset, completion: @escaping (_ url: URL?,_ error: Error?) -> Void) {
    let manager = FileManager.default
    guard let documentDirectory = try? manager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true) else {return}
    var outputURL = documentDirectory.appendingPathComponent("output")
    do {
        try manager.createDirectory(at: outputURL, withIntermediateDirectories: true, attributes: nil)
        let name = NSUUID().uuidString
        outputURL = outputURL.appendingPathComponent("\(name).mp4")
    }catch let error {
        print(error.localizedDescription)
    }
    //Remove existing file
    _ = try? manager.removeItem(at: outputURL)
    guard let exportSession = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetMediumQuality) else {return}
    exportSession.outputURL = outputURL
    exportSession.outputFileType = AVFileTypeMPEG4
    exportSession.exportAsynchronously {
        switch exportSession.status {
        case .completed:
            print("exported at \(outputURL)")
            completion(outputURL, exportSession.error)
        case .failed:
            print("failed \(exportSession.error?.localizedDescription ?? "")")
            completion(nil, exportSession.error)
        case .cancelled:
            print("cancelled \(exportSession.error?.localizedDescription ?? "")")
            completion(nil, exportSession.error)
        default: break
        }
    }
}
</code>```

We have to clear this unwanted video after successfull upload or clear it during the next app launch. I cleared it at the next app Launch using this method.

```<code>func clearDocumentsDirectory() {
    let manager = FileManager.default
    guard let documentDirectory = try? manager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true) else {return}
    let outputURL = documentDirectory.appendingPathComponent("output")
    //Remove existing file
    _ = try? manager.removeItem(at: outputURL)
}
</code>```

Hope this helps.

Body:
I'm retrieving the URL (file:///var/mobile/Media/DCIM/100APPLE/IMG_0840.MOV) from PHAsset object and am able to replay the video fine on the device.  However, when it comes time to upload/putfile on Firebase Storage, I don't even get my completionHandler back.

    //requesting url from asset
    PHImageManager.default().requestAVAsset(forVideo: asset, options: options, resultHandler: { (videoAsset, audioMix, info) in

            if let assetURL = videoAsset as? AVURLAsset {

               let url = assetURL.url

               //upload from url
            let storageRef = Storage.storage().reference().child("videos").child("\(memory.ID!)")
            let uploadMetaData = StorageMetadata()
            uploadMetaData.contentType = "video/quicktime"
               self.storageRef.putFile(from: url, metadata: uploadMetaData) { (metaData, error) in

                if error != nil {
                    print(error!.localizedDescription)
                }
            }

If I'm uploading an .mp4 file from AVFoundation capture with a local url like this, (file:///var/mobile/Containers/Data/Application/209BB017-13C7-4432-AFE4-EC3A13469900/Documents/ff49bbc9ac794ed28d6f25944f128933.mp4), it works fine.

I've also tried uploading an .MOV file on the Firebase Storage console and that also works.

Thanks

Body:
Sometimes PHAssets does not returns us with a URLAsset so we must check whether the given Asset is an AVURLAsset and if not we must save this asset in our documents directory and then obtain the url from documents directory.

func uploadVideoToFirebase(content: PHAsset) {
    let options = PHVideoRequestOptions()
    options.isNetworkAccessAllowed = true
    PHImageManager.default().requestAVAsset(forVideo: content, options: options) { (asset, mix, args) in
        if let asset = asset as? AVURLAsset {
            let url = asset.url
            // URL OF THE VIDEO IS GOT HERE
        } else {
            guard let asset = asset else {return}
            self.startAnimating(message: "Processing.")
            self.saveVideoInDocumentsDirectory(withAsset: asset, completion: { (url, error) in
                if let error = error {
                    print(error.localizedDescription)
                }
                if let url = url {
                    // SAVED IN DOCUMENTS DIRECTORY AND URL IS GOT HERE
                }
            })
        }
    }
}

Saving into Documents Directory:

func saveVideoInDocumentsDirectory(withAsset asset: AVAsset, completion: @escaping (_ url: URL?,_ error: Error?) -> Void) {
    let manager = FileManager.default
    guard let documentDirectory = try? manager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true) else {return}
    var outputURL = documentDirectory.appendingPathComponent("output")
    do {
        try manager.createDirectory(at: outputURL, withIntermediateDirectories: true, attributes: nil)
        let name = NSUUID().uuidString
        outputURL = outputURL.appendingPathComponent("\(name).mp4")
    }catch let error {
        print(error.localizedDescription)
    }
    //Remove existing file
    _ = try? manager.removeItem(at: outputURL)
    guard let exportSession = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetMediumQuality) else {return}
    exportSession.outputURL = outputURL
    exportSession.outputFileType = AVFileTypeMPEG4
    exportSession.exportAsynchronously {
        switch exportSession.status {
        case .completed:
            print("exported at \(outputURL)")
            completion(outputURL, exportSession.error)
        case .failed:
            print("failed \(exportSession.error?.localizedDescription ?? "")")
            completion(nil, exportSession.error)
        case .cancelled:
            print("cancelled \(exportSession.error?.localizedDescription ?? "")")
            completion(nil, exportSession.error)
        default: break
        }
    }
}

We have to clear this unwanted video after successfull upload or clear it during the next app launch. I cleared it at the next app Launch using this method.

func clearDocumentsDirectory() {
    let manager = FileManager.default
    guard let documentDirectory = try? manager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true) else {return}
    let outputURL = documentDirectory.appendingPathComponent("output")
    //Remove existing file
    _ = try? manager.removeItem(at: outputURL)
}

Hope this helps.


答:
This should do the trick:</p>

```<code>result = {}
for i in items:
    ri = i['remote_identifier']['id']
    j = i['jobs']['count']
    if ri in result:
        result[ri] += j
    else:
        result[ri] = j
result
#{'68': 0, '64': 11}
</code>```

Title: Sum values grouped by key in list of dict

Body:
This should do the trick:

result = {}
for i in items:
    ri = i['remote_identifier']['id']
    j = i['jobs']['count']
    if ri in result:
        result[ri] += j
    else:
        result[ri] = j
result
#{'68': 0, '64': 11}


问:
npm not working - "read ECONNRESET"
I'm having a problem with npm, I cant install anything. Here is the error messages:

```<code>C:\Windows\system32>npm install -g yo
npm http GET https://registry.npmjs.org/yo
npm http GET https://registry.npmjs.org/yo
npm http GET https://registry.npmjs.org/yo
npm ERR! network read ECONNRESET
npm ERR! network This is most likely not a problem with npm itself
npm ERR! network and is related to network connectivity.
npm ERR! network In most cases you are behind a proxy or have bad network settin
gs.
npm ERR! network
npm ERR! network If you are behind a proxy, please make sure that the
npm ERR! network 'proxy' config is set properly.  See: 'npm help config'

npm ERR! System Windows_NT 6.2.9200
npm ERR! command "C:\\Program Files\\nodejs\\\\node.exe" "C:\\Program Files\\nod
ejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "-g" "yo"
npm ERR! cwd C:\Windows\system32
npm ERR! node -v v0.10.17
npm ERR! npm -v 1.3.8
npm ERR! syscall read
npm ERR! code ECONNRESET
npm ERR! errno ECONNRESET
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR!     C:\Windows\system32\npm-debug.log
npm ERR! not ok code 0
</code>```

Any idea why is this? Here are my network settings and it seems I dont have any proxy configured. I also disabled all the firewalls.

答:
I had the same problem on my local home network without proxy. Other answers in this thread didn't work for me. What I ended up doing was using yarn which can be used interchangeably with npm:

```<code>yarn add
</code>```

To this day I don't know why my npm still don't work. I know for sure that it's a problem with my Wi-Fi, because when I connect to LTE internet broadcasted from my smartphone npm install works again. It has probably something to do with router settings (problems started when I upgraded my internet speed and ISP worker replaced my old router with a new one).

Title: npm not working - "read ECONNRESET"

Body:
I'm having a problem with npm, I cant install anything. Here is the error messages:

C:\Windows\system32>npm install -g yo
npm http GET https://registry.npmjs.org/yo
npm http GET https://registry.npmjs.org/yo
npm http GET https://registry.npmjs.org/yo
npm ERR! network read ECONNRESET
npm ERR! network This is most likely not a problem with npm itself
npm ERR! network and is related to network connectivity.
npm ERR! network In most cases you are behind a proxy or have bad network settin
gs.
npm ERR! network
npm ERR! network If you are behind a proxy, please make sure that the
npm ERR! network 'proxy' config is set properly.  See: 'npm help config'

npm ERR! System Windows_NT 6.2.9200
npm ERR! command "C:\\Program Files\\nodejs\\\\node.exe" "C:\\Program Files\\nod
ejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "-g" "yo"
npm ERR! cwd C:\Windows\system32
npm ERR! node -v v0.10.17
npm ERR! npm -v 1.3.8
npm ERR! syscall read
npm ERR! code ECONNRESET
npm ERR! errno ECONNRESET
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR!     C:\Windows\system32\npm-debug.log
npm ERR! not ok code 0

Any idea why is this? Here are my network settings and it seems I dont have any proxy configured. I also disabled all the firewalls.

Body:
I had the same problem on my local home network without proxy. Other answers in this thread didn't work for me. What I ended up doing was using yarn which can be used interchangeably with npm:

yarn add

To this day I don't know why my npm still don't work. I know for sure that it's a problem with my Wi-Fi, because when I connect to LTE internet broadcasted from my smartphone npm install works again. It has probably something to do with router settings (problems started when I upgraded my internet speed and ISP worker replaced my old router with a new one).


问:
Getting error when run react-native run-android
```<code>A problem occurred configuring project ':app'.
   > Could not resolve all dependencies for configuration ':app:_debugApk'.
     > A problem occurred configuring project ':react-native-fbsdk'.
       > Could not resolve all dependencies for configuration ':react-native-fbsdk:_debugPublishCopy'.
         > Could not find com.android.support:appcompat-v7:27.0.1.
           Searched in the following locations:
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.pom
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.jar
             file:/home/ubuntu/git/mstore-pro/android/sdk-manager/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.jar
           Required by:
             beostore:react-native-fbsdk:unspecified
         > Could not find com.android.support:appcompat-v7:27.0.1.
           Searched in the following locations:
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.pom
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.jar
             file:/home/ubuntu/git/mstore-pro/android/sdk-manager/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.jar
           Required by:
             beostore:react-native-fbsdk:unspecified > com.facebook.react:react-native:0.46.4
         > Could not find com.android.support:support-annotations:27.0.1.
           Searched in the following locations:
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/support-annotations/27.0.1/support-annotations-27.0.1.pom
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/support-annotations/27.0.1/support-annotations-27.0.1.jar
             file:/home/ubuntu/git/mstore-pro/android/sdk-manager/com/android/support/support-annotations/27.0.1/support-annotations-27.0.1.jar
           Required by:
             beostore:react-native-fbsdk:unspecified > com.facebook.android:facebook-android-sdk:4.29.0 > com.facebook.android:facebook-core:4.29.0
         > Could not find com.android.support:support-core-utils:27.0.1.
           Searched in the following locations:
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/support-core-utils/27.0.1/support-core-utils-27.0.1.pom
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/support-core-utils/27.0.1/support-core-utils-27.0.1.jar
             file:/home/ubuntu/git/mstore-pro/android/sdk-manager/com/android/support/support-core-utils/27.0.1/support-core-utils-27.0.1.jar
           Required by:
             beostore:react-native-fbsdk:unspecified > com.facebook.android:facebook-android-sdk:4.29.0 > com.facebook.android:facebook-core:4.29.0
         > Could not find com.android.support:appcompat-v7:27.0.1.
           Searched in the following locations:
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.pom
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.jar
             file:/home/ubuntu/git/mstore-pro/android/sdk-manager/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.jar
           Required by:
             beostore:react-native-fbsdk:unspecified > com.facebook.android:facebook-android-sdk:4.29.0 > com.facebook.android:facebook-common:4.29.0
         > Could not find com.android.support:cardview-v7:27.0.1.
           Searched in the following locations:
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/cardview-v7/27.0.1/cardview-v7-27.0.1.pom
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/cardview-v7/27.0.1/cardview-v7-27.0.1.jar
             file:/home/ubuntu/git/mstore-pro/android/sdk-manager/com/android/support/cardview-v7/27.0.1/cardview-v7-27.0.1.jar
           Required by:
             beostore:react-native-fbsdk:unspecified > com.facebook.android:facebook-android-sdk:4.29.0 > com.facebook.android:facebook-common:4.29.0
         > Could not find com.android.support:customtabs:27.0.1.
           Searched in the following locations:
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/customtabs/27.0.1/customtabs-27.0.1.pom
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/customtabs/27.0.1/customtabs-27.0.1.jar
             file:/home/ubuntu/git/mstore-pro/android/sdk-manager/com/android/support/customtabs/27.0.1/customtabs-27.0.1.jar
           Required by:
             beostore:react-native-fbsdk:unspecified > com.facebook.android:facebook-android-sdk:4.29.0 > com.facebook.android:facebook-common:4.29.0
         > Could not find com.android.support:support-v4:27.0.1.
           Searched in the following locations:
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/support-v4/27.0.1/support-v4-27.0.1.pom
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/support-v4/27.0.1/support-v4-27.0.1.jar
             file:/home/ubuntu/git/mstore-pro/android/sdk-manager/com/android/support/support-v4/27.0.1/support-v4-27.0.1.jar
           Required by:
             beostore:react-native-fbsdk:unspecified > com.facebook.android:facebook-android-sdk:4.29.0 > com.facebook.android:facebook-common:4.29.0
</code>```

compileSdkVersion 25

buildToolsVersion "25.0.0"

targetSdkVersion 25

答:
The accepted answer does the trick but a cleaner solution would be to restrict the android fbsdk version used in the react native fbsdk library. Adding the below code to project(root) build.gradle made sure that the specified version of fbsdk is used by all library projects.</p>

```<code>allprojects {
    repositories {
        ...
        configurations.all {
            resolutionStrategy {
                force 'com.facebook.android:facebook-android-sdk:4.28.0'
            }
        }
    }
}
</code>```

Body:
A problem occurred configuring project ':app'.
   > Could not resolve all dependencies for configuration ':app:_debugApk'.
     > A problem occurred configuring project ':react-native-fbsdk'.
       > Could not resolve all dependencies for configuration ':react-native-fbsdk:_debugPublishCopy'.
         > Could not find com.android.support:appcompat-v7:27.0.1.
           Searched in the following locations:
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.pom
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.jar
             file:/home/ubuntu/git/mstore-pro/android/sdk-manager/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.jar
           Required by:
             beostore:react-native-fbsdk:unspecified
         > Could not find com.android.support:appcompat-v7:27.0.1.
           Searched in the following locations:
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.pom
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.jar
             file:/home/ubuntu/git/mstore-pro/android/sdk-manager/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.jar
           Required by:
             beostore:react-native-fbsdk:unspecified > com.facebook.react:react-native:0.46.4
         > Could not find com.android.support:support-annotations:27.0.1.
           Searched in the following locations:
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/support-annotations/27.0.1/support-annotations-27.0.1.pom
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/support-annotations/27.0.1/support-annotations-27.0.1.jar
             file:/home/ubuntu/git/mstore-pro/android/sdk-manager/com/android/support/support-annotations/27.0.1/support-annotations-27.0.1.jar
           Required by:
             beostore:react-native-fbsdk:unspecified > com.facebook.android:facebook-android-sdk:4.29.0 > com.facebook.android:facebook-core:4.29.0
         > Could not find com.android.support:support-core-utils:27.0.1.
           Searched in the following locations:
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/support-core-utils/27.0.1/support-core-utils-27.0.1.pom
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/support-core-utils/27.0.1/support-core-utils-27.0.1.jar
             file:/home/ubuntu/git/mstore-pro/android/sdk-manager/com/android/support/support-core-utils/27.0.1/support-core-utils-27.0.1.jar
           Required by:
             beostore:react-native-fbsdk:unspecified > com.facebook.android:facebook-android-sdk:4.29.0 > com.facebook.android:facebook-core:4.29.0
         > Could not find com.android.support:appcompat-v7:27.0.1.
           Searched in the following locations:
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.pom
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.jar
             file:/home/ubuntu/git/mstore-pro/android/sdk-manager/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.jar
           Required by:
             beostore:react-native-fbsdk:unspecified > com.facebook.android:facebook-android-sdk:4.29.0 > com.facebook.android:facebook-common:4.29.0
         > Could not find com.android.support:cardview-v7:27.0.1.
           Searched in the following locations:
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/cardview-v7/27.0.1/cardview-v7-27.0.1.pom
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/cardview-v7/27.0.1/cardview-v7-27.0.1.jar
             file:/home/ubuntu/git/mstore-pro/android/sdk-manager/com/android/support/cardview-v7/27.0.1/cardview-v7-27.0.1.jar
           Required by:
             beostore:react-native-fbsdk:unspecified > com.facebook.android:facebook-android-sdk:4.29.0 > com.facebook.android:facebook-common:4.29.0
         > Could not find com.android.support:customtabs:27.0.1.
           Searched in the following locations:
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/customtabs/27.0.1/customtabs-27.0.1.pom
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/customtabs/27.0.1/customtabs-27.0.1.jar
             file:/home/ubuntu/git/mstore-pro/android/sdk-manager/com/android/support/customtabs/27.0.1/customtabs-27.0.1.jar
           Required by:
             beostore:react-native-fbsdk:unspecified > com.facebook.android:facebook-android-sdk:4.29.0 > com.facebook.android:facebook-common:4.29.0
         > Could not find com.android.support:support-v4:27.0.1.
           Searched in the following locations:
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/support-v4/27.0.1/support-v4-27.0.1.pom
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/support-v4/27.0.1/support-v4-27.0.1.jar
             file:/home/ubuntu/git/mstore-pro/android/sdk-manager/com/android/support/support-v4/27.0.1/support-v4-27.0.1.jar
           Required by:
             beostore:react-native-fbsdk:unspecified > com.facebook.android:facebook-android-sdk:4.29.0 > com.facebook.android:facebook-common:4.29.0

compileSdkVersion 25

buildToolsVersion "25.0.0"

targetSdkVersion 25

Body:
The accepted answer does the trick but a cleaner solution would be to restrict the android fbsdk version used in the react native fbsdk library. Adding the below code to project(root) build.gradle made sure that the specified version of fbsdk is used by all library projects.

allprojects {
    repositories {
        ...
        configurations.all {
            resolutionStrategy {
                force 'com.facebook.android:facebook-android-sdk:4.28.0'
            }
        }
    }
}


问:
Better way to test (automatically) a parser?
I’m recently writing a small programming language, and have finished writing its parser. I want to write an automated test for the parser (that its result is an abstract syntax tree), but I’m not sure which way is better.

First what I tried is just to serialize AST to S-expression text and compare it to the expected output text I wrote by hand, but it has some problems:

There are trivial meaningless differences between a serialized text and the expected output like whitespaces. For example, there is no difference between:

```<code>(attribute (symbol str) (symbol length))
</code>```

(that is serialized) and:

```<code>(attribute (symbol str)
           (symbol length))
</code>```

(that is handwritten by me) in their meanings, but string comparison distincts them of course. Okay, I could resolve it by normalization.

When a test fails, it doesn’t show the difference between actual tree and expected tree concisely. I want to show only a difference node, not whole tree.

Second what I tried is to write S-expression parser and compare AST that parser (to be tested) generates to AST that S-expression parser (that I just implemented) generates from the handwritten expected output. However I realized that S-expression have to be tested also and it could be really nonsense.

I wonder what is the typical and easy way to test the parser.

PS. I am using Java, and dont’t want any dependencies to third-party libraries.

答:
Here's what. A grammar defines a language. The language is the set of string that the grammar generates, or that a parser for the grammar accepts.

Given that, more than testing if the ASTs seem right, it's important to test that the parser accepts strings intended to be in the language and rejects strings that in your mind shouldn't belong to it.

In that sense, a simple accept or reject (bonus point for input position for the rejection) is enough to build a nice and large set of test cases.

Examples:

```<code>()
(a)
((((((((((a))))))))))
((((((((((a)))))))))
(a (a (a (a (a (a (b)))))))
(((((((b) a) a) a) a) a) a)
(((((((b a) a) a) a) a) a)
((a)(a)(a)(a))
((a)(a a)(a))
(())
(()())
((()())(()())(()()))
((()())()()(()()))
...
</code>```

Body:
I’m recently writing a small programming language, and have finished writing its parser. I want to write an automated test for the parser (that its result is an abstract syntax tree), but I’m not sure which way is better.

First what I tried is just to serialize AST to S-expression text and compare it to the expected output text I wrote by hand, but it has some problems:

There are trivial meaningless differences between a serialized text and the expected output like whitespaces. For example, there is no difference between:

(attribute (symbol str) (symbol length))

(that is serialized) and:

(attribute (symbol str)
           (symbol length))

(that is handwritten by me) in their meanings, but string comparison distincts them of course. Okay, I could resolve it by normalization.

When a test fails, it doesn’t show the difference between actual tree and expected tree concisely. I want to show only a difference node, not whole tree.

Second what I tried is to write S-expression parser and compare AST that parser (to be tested) generates to AST that S-expression parser (that I just implemented) generates from the handwritten expected output. However I realized that S-expression have to be tested also and it could be really nonsense.

I wonder what is the typical and easy way to test the parser.

PS. I am using Java, and dont’t want any dependencies to third-party libraries.

Body:
Here's what. A grammar defines a language. The language is the set of string that the grammar generates, or that a parser for the grammar accepts.

Given that, more than testing if the ASTs seem right, it's important to test that the parser accepts strings intended to be in the language and rejects strings that in your mind shouldn't belong to it.

In that sense, a simple accept or reject (bonus point for input position for the rejection) is enough to build a nice and large set of test cases.

Examples:

()
(a)
((((((((((a))))))))))
((((((((((a)))))))))
(a (a (a (a (a (a (b)))))))
(((((((b) a) a) a) a) a) a)
(((((((b a) a) a) a) a) a)
((a)(a)(a)(a))
((a)(a a)(a))
(())
(()())
((()())(()())(()()))
((()())()()(()()))
...


问:
.Net dynamic list conversion
I have to do a comparison of 2 lists. The problem is that I don't know of what type the field inside the list are, they can be int, string, decimal, enums or even other objects.

I will know the type only on runtime. I was thinking of creating a list of object and cast them to object the problem is that let's say I have a List<int> and I'm trying to cast it to object it fails.

Another problem is that  I know there is a list only on runtime. so on runtime I need to transform the variable of type object to a list.

How can I cast that object to List and how can I cast it to let's say list of objects?

Update:

I have and object and by reflection I'm getting the the property of it with

```<code>var oldProperty = property.GetValue(old);
var newProperty = property.GetValue(new);
</code>```

Once I have the properties values and I can see it's a list I will need to compare those 2. Let's say oldProperty is of type List
I've tried to do something like:

```<code>var myOldList = (List<object>)oldProperty;
</code>```

If the cast fails with

```<code>Unable to cast object of type 'System.Collections.Generic.List`1[System.Int32]' to type 'System.Collections.Generic.List`1[System.Object]'
</code>```

Here you have a look of the function i;m trying to create. Please don't mind of null objects(is not in the scope)

```<code> public void SetDifference(object first, object second)
    {
        var properties = first.GetType().GetProperties();
        foreach (PropertyInfo property in properties)
        {
            var oldValue = property.GetValue(first);
            var newValue = property.GetValue(second);
            if (Convert.GetTypeCode(newValue) != TypeCode.Object)
            {
                if (!oldValue.Equals(newValue))
                {
                    result.AddDifference(new PrimitiveComparison()
                    {
                        BeforeValue = oldValue.ToString(),
                        AfterValue = newValue.ToString(),
                        PropertyName = property.Name
                    });
                }
            }
            else
            {
                if (property.PropertyType.Name.Contains("List"))
                {
                    // here fails with the error from above
                    var oldList = (List<object>)oldValue;
                    var newList = (List<object>)newValue;
                    if (oldList.Count != newList.Count)
                    {
                        result.AddDifference(new PrimitiveComparison()
                        {
                            BeforeValue = oldList.Count.ToString(),
                            AfterValue = newList.Count.ToString(),
                            PropertyName = property.Name + "Count"
                        });
                    }
                    // add the list differences
                    result.AddDifference(SetListDifference(oldList, newList);
                }
                else
                {
                    var diffrence = SetDifference(oldValue, newValue);
                    if (!diffrence.areEqual)
                    {
                        result.AddDifference(diffrence);
                    }
                }

            }
        }

}
</code>```

答:
You can just cast your two values to IList and compare them, for example like this:

```<code>static bool AreEqual(IList first, IList second) {
    if (first.Count != second.Count)
        return false;
    for (int i = 0; i < first.Count; i++) {
        if (!object.Equals(first[i], second[i]))
            return false;
    }
    return true;
}
</code>```

Title: .Net dynamic list conversion

Body:
I have to do a comparison of 2 lists. The problem is that I don't know of what type the field inside the list are, they can be int, string, decimal, enums or even other objects.

I will know the type only on runtime. I was thinking of creating a list of object and cast them to object the problem is that let's say I have a List<int> and I'm trying to cast it to object it fails.

Another problem is that  I know there is a list only on runtime. so on runtime I need to transform the variable of type object to a list.

How can I cast that object to List and how can I cast it to let's say list of objects?

Update:

I have and object and by reflection I'm getting the the property of it with

var oldProperty = property.GetValue(old);
var newProperty = property.GetValue(new);

Once I have the properties values and I can see it's a list I will need to compare those 2. Let's say oldProperty is of type List
I've tried to do something like:

var myOldList = (List<object>)oldProperty;

If the cast fails with

Unable to cast object of type 'System.Collections.Generic.List`1[System.Int32]' to type 'System.Collections.Generic.List`1[System.Object]'

Here you have a look of the function i;m trying to create. Please don't mind of null objects(is not in the scope)

 public void SetDifference(object first, object second)
    {
        var properties = first.GetType().GetProperties();
        foreach (PropertyInfo property in properties)
        {
            var oldValue = property.GetValue(first);
            var newValue = property.GetValue(second);
            if (Convert.GetTypeCode(newValue) != TypeCode.Object)
            {
                if (!oldValue.Equals(newValue))
                {
                    result.AddDifference(new PrimitiveComparison()
                    {
                        BeforeValue = oldValue.ToString(),
                        AfterValue = newValue.ToString(),
                        PropertyName = property.Name
                    });
                }
            }
            else
            {
                if (property.PropertyType.Name.Contains("List"))
                {
                    // here fails with the error from above
                    var oldList = (List<object>)oldValue;
                    var newList = (List<object>)newValue;
                    if (oldList.Count != newList.Count)
                    {
                        result.AddDifference(new PrimitiveComparison()
                        {
                            BeforeValue = oldList.Count.ToString(),
                            AfterValue = newList.Count.ToString(),
                            PropertyName = property.Name + "Count"
                        });
                    }
                    // add the list differences
                    result.AddDifference(SetListDifference(oldList, newList);
                }
                else
                {
                    var diffrence = SetDifference(oldValue, newValue);
                    if (!diffrence.areEqual)
                    {
                        result.AddDifference(diffrence);
                    }
                }

            }
        }

}

Body:
You can just cast your two values to IList and compare them, for example like this:

static bool AreEqual(IList first, IList second) {
    if (first.Count != second.Count)
        return false;
    for (int i = 0; i < first.Count; i++) {
        if (!object.Equals(first[i], second[i]))
            return false;
    }
    return true;
}


问:
How to Fix those Radio Buttons? I need first one selected by default, but it's not working
I am trying to configure those radio buttons. When I run the app no one of those radio buttons is selected, while I need first one selected by default. I am using this code:

```<code>import React, { Component } from "react";
import { Container, Header, Content, ListItem, Text, Radio, Right } from "native-base";

export default class RadioButtonExample extends Component {

  constructor() {
    super();
    this.state = {
      itemSelected: "itemOne",
    };
  }

  render() {
    return (
      <Container>
        <Header />
        <Content>
          <ListItem onPress={() => this.setState({ itemSelected: "itemOne" })}>
            <Text>Daily Stand Up</Text>
            <Right>
              <Radio selected={this.state.itemSelected == "itemOne"} />
            </Right>
          </ListItem>
          <ListItem onPress={() => this.setState({ itemSelected: "itemTwo" })}>
            <Text>Discussion with Client</Text>
            <Right>
              <Radio selected={this.state.itemSelected == "itemTwo"} />
            </Right>
          </ListItem>
        </Content>
      </Container>
    );
  }
}
</code>```

What should be fixed to make it work?

答: You have to use "checked" attribute, try it.</p>

Body:
I am trying to configure those radio buttons. When I run the app no one of those radio buttons is selected, while I need first one selected by default. I am using this code:

import React, { Component } from "react";
import { Container, Header, Content, ListItem, Text, Radio, Right } from "native-base";

export default class RadioButtonExample extends Component {

  constructor() {
    super();
    this.state = {
      itemSelected: "itemOne",
    };
  }

  render() {
    return (
      <Container>

        <Content>
          <ListItem onPress={() => this.setState({ itemSelected: "itemOne" })}>
            <Text>Daily Stand Up</Text>
            <Right>
              <Radio selected={this.state.itemSelected == "itemOne"} />
            </Right>
          </ListItem>
          <ListItem onPress={() => this.setState({ itemSelected: "itemTwo" })}>
            <Text>Discussion with Client</Text>
            <Right>
              <Radio selected={this.state.itemSelected == "itemTwo"} />
            </Right>
          </ListItem>
        </Content>
      </Container>
    );
  }
}

What should be fixed to make it work?


问:
How to pass a list of strings to a batch-script as a parameter?
My batch script is used to process a list of strings and I would like to parameterize it so it will accept this list as a parameter from the user.

This is how my code is processing this list currently:

```<code>set QUEUES=cars plans others
FOR %%q IN (%QUEUES%) DO Call :defineQueues %%q
</code>```

How should I pass this list to the QUEUES varibale as a parameter?

For example, how should I pass it to this script:

```<code>myScript.bat ?
</code>```

答:
You can call it as myScript.bat %QUEUES%
and you can use below code to fetch it in your myScript.bat :

```<code>setlocal EnableDelayedExpansion
FOR %%q in (!%1!) DO echo %%q
</code>```

Body:
My batch script is used to process a list of strings and I would like to parameterize it so it will accept this list as a parameter from the user.

This is how my code is processing this list currently:

set QUEUES=cars plans others
FOR %%q IN (%QUEUES%) DO Call :defineQueues %%q

How should I pass this list to the QUEUES varibale as a parameter?

For example, how should I pass it to this script:

myScript.bat ?

Body:
You can call it as myScript.bat %QUEUES%
and you can use below code to fetch it in your myScript.bat :

setlocal EnableDelayedExpansion
FOR %%q in (!%1!) DO echo %%q