问:
what is the default hidden state of GRU in KERAS?
```<code>keras.layers.GRU(units, activation='tanh', recurrent_activation='hard_sigmoid', use_bias=True, kernel_initializer='glorot_uniform', recurrent_initializer='orthogonal', bias_initializer='zeros', kernel_regularizer=None, recurrent_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, recurrent_constraint=None, bias_constraint=None, dropout=0.0, recurrent_dropout=0.0, implementation=1, return_sequences=False, return_state=False, go_backwards=False, stateful=False, unroll=False)
</code>```

I know that the initializer of input's weight is 'glorot_uniform' and the initializer of hidden stats's weight is 'orthognal' and the initializer of bias is 'zeros'.

But I don't know the initializer of the first hidden state of GRU

答:
It's zeros. You can find the following lines in recurrent.py.

def get_initial_state(self, inputs):
    # build an all-zero tensor of shape (samples, output_dim)
    initial_state = K.zeros_like(inputs)  # (samples, timesteps, input_dim)
    initial_state = K.sum(initial_state, axis=(1, 2))  # (samples,)
    initial_state = K.expand_dims(initial_state)  # (samples, 1)
    if hasattr(self.cell.state_size, '__len__'):
        return [K.tile(initial_state, [1, dim])
                for dim in self.cell.state_size]
    else:
        return [K.tile(initial_state, [1, self.cell.state_size])]
```

<p>This function is used to get the first hidden state when you call a <code>GRU</code> layer without specifying an initial state and the layer is not stateful, i.e. the common usage <code>GRU(...)(x)</code>.</p>

<pre class="lang-py prettyprint-override"><code>def call(self,
         inputs,
         mask=None,
         training=None,
         initial_state=None,
         constants=None):
    # input shape: `(samples, time (padded with zeros), input_dim)`
    # note that the .build() method of subclasses MUST define
    # self.input_spec and self.state_spec with complete input shapes.
    if isinstance(inputs, list):
        inputs = inputs[0]
    if initial_state is not None:
        pass
    elif self.stateful:
        initial_state = self.states
    else:
        initial_state = self.get_initial_state(inputs)
</code>```

Body:
keras.layers.GRU(units, activation='tanh', recurrent_activation='hard_sigmoid', use_bias=True, kernel_initializer='glorot_uniform', recurrent_initializer='orthogonal', bias_initializer='zeros', kernel_regularizer=None, recurrent_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, recurrent_constraint=None, bias_constraint=None, dropout=0.0, recurrent_dropout=0.0, implementation=1, return_sequences=False, return_state=False, go_backwards=False, stateful=False, unroll=False)

I know that the initializer of input's weight is 'glorot_uniform' and the initializer of hidden stats's weight is 'orthognal' and the initializer of bias is 'zeros'.

But I don't know the initializer of the first hidden state of GRU

Body:
It's zeros. You can find the following lines in recurrent.py.

def get_initial_state(self, inputs):
    # build an all-zero tensor of shape (samples, output_dim)
    initial_state = K.zeros_like(inputs)  # (samples, timesteps, input_dim)
    initial_state = K.sum(initial_state, axis=(1, 2))  # (samples,)
    initial_state = K.expand_dims(initial_state)  # (samples, 1)
    if hasattr(self.cell.state_size, '__len__'):
        return [K.tile(initial_state, [1, dim])
                for dim in self.cell.state_size]
    else:
        return [K.tile(initial_state, [1, self.cell.state_size])]

This function is used to get the first hidden state when you call a GRU layer without specifying an initial state and the layer is not stateful, i.e. the common usage GRU(...)(x).

def call(self,
         inputs,
         mask=None,
         training=None,
         initial_state=None,
         constants=None):
    # input shape: `(samples, time (padded with zeros), input_dim)`
    # note that the .build() method of subclasses MUST define
    # self.input_spec and self.state_spec with complete input shapes.
    if isinstance(inputs, list):
        inputs = inputs[0]
    if initial_state is not None:
        pass
    elif self.stateful:
        initial_state = self.states
    else:
        initial_state = self.get_initial_state(inputs)


来源: stackexchange

问:
Is this an abuse of Scala pattern matching?
As in most languages, Scala has an if statement. However, using pattern matching I can achieve the exact (?) same result using code of the form:

```<code>(condition) match {
  case true =>  { /* handle the true case */ }
  case false => { /* handle the false case */ }
}
</code>```

This feels like an abuse of the mechanism, but I find it hard to explain why. Can wiser heads help me understand the position?

答:
I wouldn't normally use it, although yes, it's a matter of taste. But there are cases where I might resort to this construction. For example when I need to send as argument a higher order function that reveives a Boolean value (using Scala's PartialFunction syntax):

```<code>future.onSuccess {
  case true => ???
  case false => ???
}
</code>```

Or when there are extra conditions, something along these lines:

```<code>value match {
  case true if condition1 => ???
  case true if condition2 => ???
  case true if condition3 => ???
  case false => ???
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
As in most languages, Scala has an if statement. However, using pattern matching I can achieve the exact (?) same result using code of the form:

(condition) match {
  case true =>  { /* handle the true case */ }
  case false => { /* handle the false case */ }
}

This feels like an abuse of the mechanism, but I find it hard to explain why. Can wiser heads help me understand the position?

Body:
I wouldn't normally use it, although yes, it's a matter of taste. But there are cases where I might resort to this construction. For example when I need to send as argument a higher order function that reveives a Boolean value (using Scala's PartialFunction syntax):

future.onSuccess {
  case true => ???
  case false => ???
}

Or when there are extra conditions, something along these lines:

value match {
  case true if condition1 => ???
  case true if condition2 => ???
  case true if condition3 => ???
  case false => ???
}


问:
Make a Swift dictionary where the key is "Type"?
I'm trying to do this sort of thing ..

```<code>static var recycle: [Type: [CellThing]] = []
</code>```

but - I can't  :)

Undeclared type 'Type'

In the example, CellThing is my base class, so A:CellThing, B:CellThing, C:CellThing and so on.  The idea is I would store various A A A, B B, C C C C in the dictionary arrays.

How to make a "Type" (ideally I guess, constrained to CellThing) be the key in a Swift dictionary?

I appreciate I could (perhaps?) use String(describing: T.self), but that would make me lose sleep.

Here's a use case, envisaged code would look something like this ...

```<code>@discardableResult class func make(...)->Self {
  return makeHelper(...)
  }

private class func makeHelper<T: CellThing>(...)->T {
  let c = instantiateViewController(...) as! T
  return c
  }
</code>```

So then something like ...

```<code>static var recycle: [Type: [CellThing]] = []

private class func makeHelper<T: CellThing>(...)->T {
  let c = instantiateViewController(...) as! T

  let t = type whatever of c (so, maybe "A" or "B")
  recycle[t].append( c )

  let k = recycle[t].count
  print wow, you have k of those already!

  return c
  }
</code>```

答:
Hope AnyHashable helps. But It appeared in Xcode 8.0

You can do something like:

```<code>var info: [AnyHashable : Any]? = nil
</code>```

Body:
I'm trying to do this sort of thing ..

static var recycle: [Type: [CellThing]] = []

but - I can't  :)

Undeclared type 'Type'

In the example, CellThing is my base class, so A:CellThing, B:CellThing, C:CellThing and so on.  The idea is I would store various A A A, B B, C C C C in the dictionary arrays.

How to make a "Type" (ideally I guess, constrained to CellThing) be the key in a Swift dictionary?

I appreciate I could (perhaps?) use String(describing: T.self), but that would make me lose sleep.

Here's a use case, envisaged code would look something like this ...

@discardableResult class func make(...)->Self {
  return makeHelper(...)
  }

private class func makeHelper<T: CellThing>(...)->T {
  let c = instantiateViewController(...) as! T
  return c
  }

So then something like ...

static var recycle: [Type: [CellThing]] = []

private class func makeHelper<T: CellThing>(...)->T {
  let c = instantiateViewController(...) as! T

  let t = type whatever of c (so, maybe "A" or "B")
  recycle[t].append( c )

  let k = recycle[t].count
  print wow, you have k of those already!

  return c
  }

Body:
Hope AnyHashable helps. But It appeared in Xcode 8.0

You can do something like:

var info: [AnyHashable : Any]? = nil


问:
Running npm run watch from route in laravel
I am building a cms in laravel and was wondering if it's possible to use the command npm run watch from a route?

I've found out that it's easy to use php artisan commands but can't find anything about building a command to compile assets from a route.

Really hope someone can help me out.

答: no, you can't do that, use npm run build instead, before deploy on stage xor production


问:
Angular 2 get element by dynamic id
How can I get/update value of element with dynamic id?

```<code><input type="text" class="form-control" id="{{'lat' + ind}}" formControlName="lat">
</code>```

I can't use ngAfterViewInit() {} because I need to update dynamic input after server responce

```<code>this.someService.getData().subscribe(
                  (response) => {this.data = response.json()
                                 this.lon = this.data.x;
                                 this.lat = this.data.y;
                                 this.ind = this.data.ind;
                                // UPDATE MY 'lat+ind' and 'lon+ind' HERE
                  },
                  (error) => console.log('ERROR: ' + error)
          );
</code>```

答:
There might be a better solution for Angular, but you could use querySelector.

Here's an example:

```<code>const input = <HTMLInputElement>document.querySelector('#lat' + this.ind);

input.value = 'value'; // set value
</code>```

Edit

Please read https://angular.io/guide/forms to understand how forms work with Angular.

Title: Angular 2 get element by dynamic id

Body:
How can I get/update value of element with dynamic id?

<input type="text" class="form-control" id="{{'lat' + ind}}" formControlName="lat">

I can't use ngAfterViewInit() {} because I need to update dynamic input after server responce

this.someService.getData().subscribe(
                  (response) => {this.data = response.json()
                                 this.lon = this.data.x;
                                 this.lat = this.data.y;
                                 this.ind = this.data.ind;
                                // UPDATE MY 'lat+ind' and 'lon+ind' HERE
                  },
                  (error) => console.log('ERROR: ' + error)
          );

Body:
There might be a better solution for Angular, but you could use querySelector.

Here's an example:

const input = <HTMLInputElement>document.querySelector('#lat' + this.ind);

input.value = 'value'; // set value

Edit

Please read https://angular.io/guide/forms to understand how forms work with Angular.


问:
Bootstrap Collapse is not working with dust
I am very new to express js and bootstrap.
I am using Dust view engine. Everything was working fine except the collapse functionality.It is not working.
My layout.dust file include jquery and bootstrap -

```<code>    <!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
    <link rel = "stylesheet" href = "/stylesheets/bootstrap.css" />
    <link rel = "stylesheet" href = "/stylesheets/style.css" />
</head>
<body>
    <div class = "container" >
        <div class = "row">
            <div class = "col-md-offset-2 col-md-7">
                {+body /}
            </div>
        </div>
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
    <script src = "/javascripts/bootstrap.js"/>
</body>
</html>
</code>```

I am trying to get a collapse effect in my index.dust for clicking on button but unfortunately it is not working

```<code>{> "layout"/}
{<body}
   {#models}
    <div class = "well">
        <h4>{Name} <button class="btn btn-default pull-right" data-toggle="collapse"
        data-target="#models_{Name}" aria-expanded="false" aria-controls="models_{Name}">View</button></h4>
        <div class="collapse" id="models_{Name}">
            TREST
        </div>

    </div>
   {/models}
   {/body}
</code>```

could anyone please help me?

答:
I'm new to this I think you might be missing the href attribute?

have you tried?:

```<code>{> "layout"/}
{<body}
   {#models}
    <div class = "well">
        <h4>{Name} <button class="btn btn-default pull-right" data-toggle="collapse"
        data-target="#models_{Name}" href="#models_{Name}" aria-expanded="false" aria-controls="models_{Name}">View</button></h4>
        <div class="collapse" id="models_{Name}">
            TREST
        </div>

    </div>
   {/models}
   {/body}
</code>```

Body:
I am very new to express js and bootstrap.
I am using Dust view engine. Everything was working fine except the collapse functionality.It is not working.
My layout.dust file include jquery and bootstrap -

    <!DOCTYPE html>

<title>Page Title</title>
    <link rel = "stylesheet" href = "/stylesheets/bootstrap.css" />
    <link rel = "stylesheet" href = "/stylesheets/style.css" />

                {+body /}

Body:
I'm new to this I think you might be missing the href attribute?

have you tried?:

{> "layout"/}
{<body}
   {#models}
    <div class = "well">
        <h4>{Name} <button class="btn btn-default pull-right" data-toggle="collapse"
        data-target="#models_{Name}" href="#models_{Name}" aria-expanded="false" aria-controls="models_{Name}">View</button></h4>
        <div class="collapse" id="models_{Name}">
            TREST
        </div>

    </div>
   {/models}
   {/body}


问:
Need to read a file and use results as named variables in a shell script
I have the following output file from a venn program.

```<code>[1, 2],106
[1, 3],2556
[2, 3],5207
[1, 2, 3],232
[2],7566
[3],8840
[1],5320
</code>```

I need a command to get each line result number as variable argument in a script like this:

```<code>$area1=here it must come the results after [1],
$area2=here it must come the results after [2],
$area3=here it must come the results after [3],
$n12=here it must come the results after [1, 2],
$n13=here it must come the results after [1, 3],
$n23=here it must come the results after [2, 3],
$n123=here it must come the results after [1, 2, 3],
</code>```

these results will then be used in the script below to draw a venn diagram.

```<code>cat << catfile >> $prefix1-VennDiagram.R
library(VennDiagram);
venn.diagram(
    x = list(
        "$sample1" = c(1:$area1, $(($area1+1)):$(($area1+$n12)), $(($area1+$n12+1)):$(($area1+$n12+$n123)), $(($area1+$n12+$n123+1)):$(($area1+$n12+$n123+$n13))),
        "$sample2" = c($(($area1+$n12+$n123+$n13+1)):$(($area1+$n12+$n123+$n13+$area2)), $(($area1+1)):$(($area1+$n12)), $(($area1+$n12+1)):$(($area1+$n12+$n123)), $(($area1+$n12+$n123+$n13+$area2+1)):$(($area1+$n12+$n123+$n13+$area2+$n23))),
        "$sample3" = c($(($area1+$n12+$n123+$n13+$area2+$n23+1)):$(($area1+$n12+$n123+$n13+$area2+$n23+$area3)),  $(($area1+$n12+1)):$(($area1+$n12+$n123)), $(($area1+$n12+$n123+1)):$(($area1+$n12+$n123+$n13)), $(($area1+$n12+$n123+$n13+$area2+1)):$(($area1+$n12+$n123+$n13+$area2+$n23)))
        ),
    filename = "$prefix1-VennDiagram.tiff",
    col = "transparent",
    fill = c("red", "blue", "green"),
    alpha = 0.5,
    label.col = c("darkred", "white", "darkblue", "white", "white", "white", "darkgreen"),
    cex = 2.5,
    fontfamily = "arial",
    fontface = "bold",
    cat.default.pos = "text",
    cat.col = c("darkred", "darkblue", "darkgreen"),
    cat.cex = 2.0,
    cat.fontfamily = "arial",
    cat.fontface = "italic",
    cat.dist = c(0.06, 0.06, 0.03),
    cat.pos = 0
    );
catfile

Rscript $prefix1-VennDiagram.R
exit
</code>```

答:
In BASH it would be convenient to store the values in an associative array first and then assign them to the correct variables.

Suppose the output of venn is stored in venn.txt
then the following code could parse it for you

```<code>declare -A venn
while read line ; do
   key=$(echo "$line" | sed 's/^\(\[[^]]*\]\).*/\1/')
   value=$(echo "$line" | sed 's/^\[[^]]*\],\(.*\)/\1/')
   if [ -n "$key" ] ; then # This check is necessary
                           # to protect against empty lines
     venn["$key"]="$value" ;
   fi
done <<< "$( cat venn.txt )"
</code>```

Now you could extract the variables from the array in your script

```<code>area1=${venn["[1]"]}
area2=${venn["[2]"]}
area3=${venn["[3]"]}
n12=${venn["[1, 2]"]}
n13=${venn["[1, 3]"]}
n23=${venn["[2, 3]"]}
n123=${venn["[1, 2, 3]"]}
</code>```

In the parsing code we use Here String <<<word syntax in order to have the loop executed in the same shell instance as the rest of the code, so that the changes to the associative array were recorded.

Body:
I have the following output file from a venn program.

[1, 2],106
[1, 3],2556
[2, 3],5207
[1, 2, 3],232
[2],7566
[3],8840
[1],5320

I need a command to get each line result number as variable argument in a script like this:

$area1=here it must come the results after [1],
$area2=here it must come the results after [2],
$area3=here it must come the results after [3],
$n12=here it must come the results after [1, 2],
$n13=here it must come the results after [1, 3],
$n23=here it must come the results after [2, 3],
$n123=here it must come the results after [1, 2, 3],

these results will then be used in the script below to draw a venn diagram.

cat << catfile >> $prefix1-VennDiagram.R
library(VennDiagram);
venn.diagram(
    x = list(
        "$sample1" = c(1:$area1, $(($area1+1)):$(($area1+$n12)), $(($area1+$n12+1)):$(($area1+$n12+$n123)), $(($area1+$n12+$n123+1)):$(($area1+$n12+$n123+$n13))),
        "$sample2" = c($(($area1+$n12+$n123+$n13+1)):$(($area1+$n12+$n123+$n13+$area2)), $(($area1+1)):$(($area1+$n12)), $(($area1+$n12+1)):$(($area1+$n12+$n123)), $(($area1+$n12+$n123+$n13+$area2+1)):$(($area1+$n12+$n123+$n13+$area2+$n23))),
        "$sample3" = c($(($area1+$n12+$n123+$n13+$area2+$n23+1)):$(($area1+$n12+$n123+$n13+$area2+$n23+$area3)),  $(($area1+$n12+1)):$(($area1+$n12+$n123)), $(($area1+$n12+$n123+1)):$(($area1+$n12+$n123+$n13)), $(($area1+$n12+$n123+$n13+$area2+1)):$(($area1+$n12+$n123+$n13+$area2+$n23)))
        ),
    filename = "$prefix1-VennDiagram.tiff",
    col = "transparent",
    fill = c("red", "blue", "green"),
    alpha = 0.5,
    label.col = c("darkred", "white", "darkblue", "white", "white", "white", "darkgreen"),
    cex = 2.5,
    fontfamily = "arial",
    fontface = "bold",
    cat.default.pos = "text",
    cat.col = c("darkred", "darkblue", "darkgreen"),
    cat.cex = 2.0,
    cat.fontfamily = "arial",
    cat.fontface = "italic",
    cat.dist = c(0.06, 0.06, 0.03),
    cat.pos = 0
    );
catfile

Rscript $prefix1-VennDiagram.R
exit

Body:
In BASH it would be convenient to store the values in an associative array first and then assign them to the correct variables.

Suppose the output of venn is stored in venn.txt
then the following code could parse it for you

declare -A venn
while read line ; do
   key=$(echo "$line" | sed 's/^\(\[[^]]*\]\).*/\1/')
   value=$(echo "$line" | sed 's/^\[[^]]*\],\(.*\)/\1/')
   if [ -n "$key" ] ; then # This check is necessary
                           # to protect against empty lines
     venn["$key"]="$value" ;
   fi
done <<< "$( cat venn.txt )"

Now you could extract the variables from the array in your script

area1=${venn["[1]"]}
area2=${venn["[2]"]}
area3=${venn["[3]"]}
n12=${venn["[1, 2]"]}
n13=${venn["[1, 3]"]}
n23=${venn["[2, 3]"]}
n123=${venn["[1, 2, 3]"]}

In the parsing code we use Here String <<<word syntax in order to have the loop executed in the same shell instance as the rest of the code, so that the changes to the associative array were recorded.


问:
How to translate the Nation name into the current culture?
I've a List of Nations that's scraped from the web, this is returned in english. I saved each Nation inside a list like this:

```<code>List<Nation> Nations { get; set; } = new List<Nation>();
</code>```

where Nation have this implementation:

```<code>public Nation
{
    public string Name { get; set; }
    public string Link { get; set; }
}
</code>```

the property Name contains the name of the Nation in English, so essentially I'll get something similar to:

```<code>England
Italy
France
...
</code>```

I'm looking for a way to translate the name of each item of the list Nations in the current culture, so suppose that the current software language is italian:

```<code>Thread.CurrentThread.CurrentCulture = Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture("it");
</code>```

how can I translate all the nations in italian language?

I doesn't found any method in .NET framework that allow this in a simple way like:

```<code>//Get the current language of the app
var language = Thread.CurrentThread.CurrentCulture;

//Iterate through all items of the list and change the language
foreach(var nation in nations)
{
    nation.Name = GetTranslatedName(nation.Name);
}
</code>```

any suggestions? Ideas?

Thanks.

答:
I think there's no native support in .NET for this.
I'd suggest to use this third-party API:

For instance: https://restcountries.eu/rest/v2/name/Ukraine

Body:
I've a List of Nations that's scraped from the web, this is returned in english. I saved each Nation inside a list like this:

List<Nation> Nations { get; set; } = new List<Nation>();

where Nation have this implementation:

public Nation
{
    public string Name { get; set; }
    public string Link { get; set; }
}

the property Name contains the name of the Nation in English, so essentially I'll get something similar to:

England
Italy
France
...

I'm looking for a way to translate the name of each item of the list Nations in the current culture, so suppose that the current software language is italian:

Thread.CurrentThread.CurrentCulture = Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture("it");

how can I translate all the nations in italian language?

I doesn't found any method in .NET framework that allow this in a simple way like:

//Get the current language of the app
var language = Thread.CurrentThread.CurrentCulture;

//Iterate through all items of the list and change the language
foreach(var nation in nations)
{
    nation.Name = GetTranslatedName(nation.Name);
}

any suggestions? Ideas?

Thanks.


问:
Unity3D setting velocity won't take effect immediately in OnCollisionEnter
I have a simple script to set the velocity to zero when a collision with something, but seems it won't work immediately:

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MoveController : MonoBehaviour {

    [SerializeField]
    private float shootVelocity=30f;

    void Start () {

    }

    private void OnGUI()
    {
        if(GUI.Button(new Rect(0,0,100,100), "shoot"))
        {
            GetComponent<Rigidbody>().velocity = shootVelocity * Vector3.forward;
        }
    }

    private void OnCollisionEnter(Collision collision)
    {
        GetComponent<Rigidbody>().velocity = Vector3.zero;
        GetComponent<Rigidbody>().isKinematic = true;
    }

}
</code>```

I also have made a youtube video to demonstrate the problem.

It's really important to make the ball stop immediately after a collision happens.

How to do that?

答:
You get this problem because there is specific time step after which physics calculation takes place, you can read more about it here https://docs.unity3d.com/Manual/class-TimeManager.html

Imagine this situation, object are not colliding this frame, next frame first object moves for some distance and it is now colliding with second object, but it is already somewhere inside that object since it moves very fast, then the collision is detected but it is already too late. Sometimes if the object are very small and/or moving very fast collision doesn't get detected, because when it first check object one is before object two, when it checks second time object one is already passed object two, so no collision detected.

One way to do it is to make this time step smaller so Unity will check for collision more often, but this increases overhead, especially if you have a lot of physics calculations going around and position when sphere stops will never be perfect. What I suggest is you write your own calculation with this to work together with Unity's simulation.

I will give you example how to calculate perfect stopping position (position where two objects are just touching at one point) if object is moving always in same direction when  it is passing through other object and you are working with two sphere colliders whose radiuses in world scale you know. Let's name them radius1 and radius2, and parameter "t" that represents how much forward/backwards object needs to move to get perfect collision position.

When colision is detected you can do following calculation.

Vector3 firstVector = transform.position-collidedObject.transform.position;
 Vector3 secondVector = direction;
 float r = radius1+radius2;

(firstVector - secondVector*t).sqrMagnitude = r^2;

Expand your equation

or in text mode =\sqrt{2x_2^2t^2+z_2^2t^2-2x_1x_2t-2z_1x_2t-2z_1z_2t+x_1^2+2z_1^2}

Now solve for t and you will get two values, because you have two perfect collision positions for given direction (one before the second object and one after).

You get this equation

Link to Symbolab equations

It might look complex but you can see that there is only one difference in these two solutions for t (in that minus sign) and rest of it is same, you can split this in 3 variables to make it looks simple, this is just all focused in one equation so it looks like a lot.

Let's say now you have "t1" and "t2" with values for equation, you can now do

```<code>float finalT = Mathf.Abs(t1) < Mathf.Abs(t2) ? t1 : t2;
transform.position += dir*t;
</code>```

You need to calculate all this only when collision is detected, I would also suggest to do this only when:

```<code>if((transform.position-collidedObject.transform.position).sqrMagnitude > (radius1+radius2 + someThresholdValue)^2)
</code>```

So you ignore the calculation if objects are already positioned pretty nicely by Unity engine. Let me know how it goes, hope this helps!

Note: even if the object doesn't have constant direction you can approximate it by taking the last know direction and for the sake of calculation make it constant on that value. You won't get almost no difference and it solves the calculations tremendously.

Body:
I have a simple script to set the velocity to zero when a collision with something, but seems it won't work immediately:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MoveController : MonoBehaviour {

    [SerializeField]
    private float shootVelocity=30f;

    void Start () {

    }

    private void OnGUI()
    {
        if(GUI.Button(new Rect(0,0,100,100), "shoot"))
        {
            GetComponent<Rigidbody>().velocity = shootVelocity * Vector3.forward;
        }
    }

    private void OnCollisionEnter(Collision collision)
    {
        GetComponent<Rigidbody>().velocity = Vector3.zero;
        GetComponent<Rigidbody>().isKinematic = true;
    }

}

I also have made a youtube video to demonstrate the problem.

It's really important to make the ball stop immediately after a collision happens.

How to do that?

Body:
You get this problem because there is specific time step after which physics calculation takes place, you can read more about it here https://docs.unity3d.com/Manual/class-TimeManager.html

Imagine this situation, object are not colliding this frame, next frame first object moves for some distance and it is now colliding with second object, but it is already somewhere inside that object since it moves very fast, then the collision is detected but it is already too late. Sometimes if the object are very small and/or moving very fast collision doesn't get detected, because when it first check object one is before object two, when it checks second time object one is already passed object two, so no collision detected.

One way to do it is to make this time step smaller so Unity will check for collision more often, but this increases overhead, especially if you have a lot of physics calculations going around and position when sphere stops will never be perfect. What I suggest is you write your own calculation with this to work together with Unity's simulation.

I will give you example how to calculate perfect stopping position (position where two objects are just touching at one point) if object is moving always in same direction when  it is passing through other object and you are working with two sphere colliders whose radiuses in world scale you know. Let's name them radius1 and radius2, and parameter "t" that represents how much forward/backwards object needs to move to get perfect collision position.

When colision is detected you can do following calculation.

Vector3 firstVector = transform.position-collidedObject.transform.position;
 Vector3 secondVector = direction;
 float r = radius1+radius2;

(firstVector - secondVector*t).sqrMagnitude = r^2;

Expand your equation

or in text mode =\sqrt{2x_2^2t^2+z_2^2t^2-2x_1x_2t-2z_1x_2t-2z_1z_2t+x_1^2+2z_1^2}

Now solve for t and you will get two values, because you have two perfect collision positions for given direction (one before the second object and one after).

You get this equation

Link to Symbolab equations

It might look complex but you can see that there is only one difference in these two solutions for t (in that minus sign) and rest of it is same, you can split this in 3 variables to make it looks simple, this is just all focused in one equation so it looks like a lot.

Let's say now you have "t1" and "t2" with values for equation, you can now do

float finalT = Mathf.Abs(t1) < Mathf.Abs(t2) ? t1 : t2;
transform.position += dir*t;

You need to calculate all this only when collision is detected, I would also suggest to do this only when:

if((transform.position-collidedObject.transform.position).sqrMagnitude > (radius1+radius2 + someThresholdValue)^2)

So you ignore the calculation if objects are already positioned pretty nicely by Unity engine. Let me know how it goes, hope this helps!

Note: even if the object doesn't have constant direction you can approximate it by taking the last know direction and for the sake of calculation make it constant on that value. You won't get almost no difference and it solves the calculations tremendously.


问:
Replace array key value
I want to replace array values (1, 2, 3 and 4) to corresponding text

```<code>1 = OK;
2 = nOK;
3 = Warning;
4 = Other
</code>```

Here is some code:

```<code>$status = $row['status'];
</code>```

(I stored $status text in mysql row 1,2,3,4,1,2,4,4,1, etc)

```<code>$myarray = array($status);
foreach($myarray as $key => $val)
{
    print_r($val);
}
</code>```

Output of this is:

```<code>Array ( [0] => 2 [1] => 3 [2] => 1 [3] => 4 [4] => 1 [5] => 1 [6] => 3 [7] => 4 [8] => 1 [9] => 2 )
</code>```

How to do this? Thanks!

答:
```<code>$array = array(1,2,3,4);
$string_array = array(
                    1 => "OK",
                    2 => "nOK",
                    3 => "Warning",
                    4 => "Other"
                );
$output = array_flip($string_array);
</code>```

Title: Replace array key value

Body:
I want to replace array values (1, 2, 3 and 4) to corresponding text

1 = OK;
2 = nOK;
3 = Warning;
4 = Other

Here is some code:

$status = $row['status'];

(I stored $status text in mysql row 1,2,3,4,1,2,4,4,1, etc)

$myarray = array($status);
foreach($myarray as $key => $val)
{
    print_r($val);
}

Output of this is:

Array ( [0] => 2 [1] => 3 [2] => 1 [3] => 4 [4] => 1 [5] => 1 [6] => 3 [7] => 4 [8] => 1 [9] => 2 )

How to do this? Thanks!


问:
is there is any way to get all keys from localizable string file?
So basically I want to get keys structure from the localizable file because when we have too much string in the local file then it's very pathetic to open a file and search for specific string each time.

ex:

```<code>let localizeStr = NSLocalizedString(Local.keyName, comment: "")
</code>```

keyName = any key in localizable.strings file

答: Try to read the file and parse it's content line by line and store it's keys in an NSArray , then you ready to do what you want ...

Body:
So basically I want to get keys structure from the localizable file because when we have too much string in the local file then it's very pathetic to open a file and search for specific string each time.

ex:

let localizeStr = NSLocalizedString(Local.keyName, comment: "")

keyName = any key in localizable.strings file


问:
Connectivity issues to mysql database from hybris
I was trying to setup hybris but when I tried to initialize from the CLI, the build failed due to Mysql connectivity issue.
However I am able to connect to mysql database from hybris node using mysql client.

Can any one help me on this ? Could it be some additional privileges required ?

Following is the error thrown at last when performing "ant initialize":

```<code> [java] ERROR [main] [DataSourceImpl] error connecting to DataSource having url jdbc:mysql://<mysql-ip>:3306/hybrisdatabase?useConfigs=maxPerformance&characterEncoding=utf8&useSSL=false: Unknown error 1045
</code>```

Full Error Logs

```<code>server:
     [echo]
     [echo] Configuring server at /ABC/hybris/bin/platform/tomcat
     [echo] Using config set at /ABC/hybris/config/tomcat
     [echo]
     [echo] copying from /ABC/hybris/config/tomcat to /ABC/hybris/bin/platform/tomcat
     [copy] Copying 9 files to /ABC/hybris/bin/platform/tomcat
     [copy] Copying 3 files to /ABC/hybris/bin/platform/tomcat
     [copy] Copying 2 files to /ABC/hybris/bin/platform/tomcat
     [copy] Copying 1 file to /ABC/hybris/bin/platform/tomcat/lib
     [echo]
     [echo] Embedded server does not seem to be running (no PID found). No restart necessary.
     [echo]

initialize:
    [input] skipping input as property tenant has already been set.
     [java] ---------------------------------------------------------------
     [java] Warning: you're using at least one deprecated extension!
     [java] Please note that they may not be available in future releases.
     [java]
     [java] Deprecated extensions: [liveeditaddon, sapcoreodata]
     [java] ---------------------------------------------------------------
     [java] ---------------------------------------------------------------
     [java] Warning: you're using at least one deprecated extension!
     [java] Please note that they may not be available in future releases.
     [java]
     [java] Deprecated extensions: [liveeditaddon, sapcoreodata]
     [java] ---------------------------------------------------------------
     [java] Exception in thread "main" java.lang.reflect.InvocationTargetException
     [java]     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
     [java]     at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
     [java]     at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
     [java]     at java.lang.reflect.Method.invoke(Method.java:498)
     [java]     at de.hybris.bootstrap.loader.Loader.execute(Loader.java:142)
     [java]     at de.hybris.bootstrap.loader.Loader.main(Loader.java:118)
     [java] Caused by: java.lang.RuntimeException: java.sql.SQLException: Unknown error 1045
     [java]     at de.hybris.platform.jdbcwrapper.DataSourceImpl.adjustDatabaseInfos(DataSourceImpl.java:647)
     [java]     at de.hybris.platform.jdbcwrapper.DataSourceImpl.<init>(DataSourceImpl.java:213)
     [java]     at de.hybris.platform.jdbcwrapper.DataSourceImpl.<init>(DataSourceImpl.java:149)
     [java]     at de.hybris.platform.core.DataSourceImplFactory.createDataSource(DataSourceImplFactory.java:51)
     [java]     at de.hybris.platform.core.AbstractTenant$HybrisDataSourceBuilder.createMasterDataSource(AbstractTenant.java:2869)
     [java]     at de.hybris.platform.core.AbstractTenant$HybrisDataSourceBuilder.buildMasterDataSourceOnce(AbstractTenant.java:2631)
     [java]     at de.hybris.platform.core.AbstractTenant$HybrisDataSourceBuilder.build(AbstractTenant.java:2577)
     [java]     at de.hybris.platform.core.AbstractTenant.doInitializeSafe(AbstractTenant.java:329)
     [java]     at de.hybris.platform.core.AbstractTenant.doInitialize(AbstractTenant.java:308)
     [java]     at de.hybris.platform.core.AbstractTenant.doStartUp(AbstractTenant.java:674)
     [java]     at de.hybris.platform.core.Registry.assureTenantStarted(Registry.java:648)
     [java]     at de.hybris.platform.core.Registry.activateTenant(Registry.java:709)
     [java]     at de.hybris.platform.core.Registry.setCurrentTenant(Registry.java:556)
     [java]     at de.hybris.platform.core.Registry.activateMasterTenantForInit(Registry.java:625)
     [java]     at de.hybris.platform.util.ClientExecuter.execute(ClientExecuter.java:39)
     [java]     ... 6 more
     [java] Caused by: java.sql.SQLException: Unknown error 1045
     [java]     at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:964)
     [java]     at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3970)
     [java]     at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3906)
     [java]     at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:873)
     [java]     at com.mysql.jdbc.MysqlIO.proceedHandshakeWithPluggableAuthentication(MysqlIO.java:1710)
     [java]     at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1226)
     [java]     at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2253)
     [java]     at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2284)
     [java]     at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2083)
     [java]     at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:806)
     [java]     at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
     [java]     at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
     [java]     at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
     [java]     at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
     [java]     at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
     [java]     at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
     [java]     at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:410)
     [java]     at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:328)
     [java]     at de.hybris.platform.jdbcwrapper.JDBCConnectionFactory.createRawSQLConnection(JDBCConnectionFactory.java:189)
     [java]     at de.hybris.platform.jdbcwrapper.JDBCConnectionFactory.createSQLConnection(JDBCConnectionFactory.java:220)
     [java]     at de.hybris.platform.jdbcwrapper.JDBCConnectionFactory.makeObject(JDBCConnectionFactory.java:109)
     [java]     at org.apache.commons.pool2.impl.GenericObjectPool.create(GenericObjectPool.java:868)
     [java]     at org.apache.commons.pool2.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:435)
     [java]     at org.apache.commons.pool2.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:363)
     [java]     at de.hybris.platform.jdbcwrapper.JDBCConnectionPool.borrowConnection(JDBCConnectionPool.java:113)
     [java]     at de.hybris.platform.jdbcwrapper.ConnectionErrorCheckingJDBCConnectionPool.borrowConnection(ConnectionErrorCheckingJDBCConnectionPool.java:97)
     [java]     at de.hybris.platform.jdbcwrapper.DataSourceImpl.adjustDatabaseInfos(DataSourceImpl.java:629)
     [java]     ... 20 more
     [java] ERROR [main] [DataSourceImpl] error connecting to DataSource having url jdbc:mysql://10.43.4.168:3306/hemdevhybris?useConfigs=maxPerformance&characterEncoding=utf8&useSSL=false: Unknown error 1045
     [java] shutting down hybris registry..

BUILD FAILED
/TK/hybris/bin/platform/build.xml:123: The following error occurred while executing this line:
/ABC/hybris/bin/platform/resources/ant/antmacros.xml:1021: The following error occurred while executing this line:
/ABC/hybris/bin/platform/resources/ant/platformadministration.xml:51: The following error occurred while executing this line:
/ABC/hybris/bin/platform/resources/ant/antmacros.xml:878: Java returned: 1
</code>```

Hybris local.properties:

```<code>db.url=jdbc:mysql://<mysql-IP>:3306/hybrisdatabase?useConfigs=maxPerformance&characterEncoding=utf8&useSSL=false
db.driver=com.mysql.jdbc.Driver
db.username=hybris-user
db.password=*****
db.tableprefix=
mysql.optional.tabledefs=CHARSET=utf8 COLLATE=utf8_bin
mysql.tabletype=InnoDB
</code>```

Mysql connectivity from hybris node:

```<code>[hybris@****platform]$ mysql -h <mysql-ip> -u hybris-user -p'password'
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MySQL connection id is 2188
Server version: 5.7.20 MySQL Community Server (GPL)

Copyright (c) 2000, 2017, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MySQL [(none)]> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| hybrisdatabase       |
+--------------------+
2 rows in set (0.01 sec)

MySQL [(none)]>  SHOW GRANTS FOR 'hybris-user'@'%';
+------------------------------------------------------------------+
| Grants for hybris-user@%                                      |
+------------------------------------------------------------------+
| GRANT USAGE ON *.* TO 'hybris-user'@'%'                       |
| GRANT ALL PRIVILEGES ON `hybrisdatabase`.* TO 'hybris-user'@'%' |
+------------------------------------------------------------------+
2 rows in set (0.00 sec)

MySQL [(none)]> use hybrisdatabase;
Database changed
MySQL [hybrisdatabase]> show tables;
Empty set (0.01 sec)
</code>```

答: Did you copy the MySQL lib to /hybris/bin/platform/lib/dbdriver/? MySQL lib is not shipped with standard hybris. </p>

Body:
I was trying to setup hybris but when I tried to initialize from the CLI, the build failed due to Mysql connectivity issue.
However I am able to connect to mysql database from hybris node using mysql client.

Can any one help me on this ? Could it be some additional privileges required ?

Following is the error thrown at last when performing "ant initialize":

 [java] ERROR [main] [DataSourceImpl] error connecting to DataSource having url jdbc:mysql://<mysql-ip>:3306/hybrisdatabase?useConfigs=maxPerformance&characterEncoding=utf8&useSSL=false: Unknown error 1045

Full Error Logs

server:
     [echo]
     [echo] Configuring server at /ABC/hybris/bin/platform/tomcat
     [echo] Using config set at /ABC/hybris/config/tomcat
     [echo]
     [echo] copying from /ABC/hybris/config/tomcat to /ABC/hybris/bin/platform/tomcat
     [copy] Copying 9 files to /ABC/hybris/bin/platform/tomcat
     [copy] Copying 3 files to /ABC/hybris/bin/platform/tomcat
     [copy] Copying 2 files to /ABC/hybris/bin/platform/tomcat
     [copy] Copying 1 file to /ABC/hybris/bin/platform/tomcat/lib
     [echo]
     [echo] Embedded server does not seem to be running (no PID found). No restart necessary.
     [echo]

initialize:
    [input] skipping input as property tenant has already been set.
     [java] ---------------------------------------------------------------
     [java] Warning: you're using at least one deprecated extension!
     [java] Please note that they may not be available in future releases.
     [java]
     [java] Deprecated extensions: [liveeditaddon, sapcoreodata]
     [java] ---------------------------------------------------------------
     [java] ---------------------------------------------------------------
     [java] Warning: you're using at least one deprecated extension!
     [java] Please note that they may not be available in future releases.
     [java]
     [java] Deprecated extensions: [liveeditaddon, sapcoreodata]
     [java] ---------------------------------------------------------------
     [java] Exception in thread "main" java.lang.reflect.InvocationTargetException
     [java]     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
     [java]     at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
     [java]     at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
     [java]     at java.lang.reflect.Method.invoke(Method.java:498)
     [java]     at de.hybris.bootstrap.loader.Loader.execute(Loader.java:142)
     [java]     at de.hybris.bootstrap.loader.Loader.main(Loader.java:118)
     [java] Caused by: java.lang.RuntimeException: java.sql.SQLException: Unknown error 1045
     [java]     at de.hybris.platform.jdbcwrapper.DataSourceImpl.adjustDatabaseInfos(DataSourceImpl.java:647)
     [java]     at de.hybris.platform.jdbcwrapper.DataSourceImpl.<init>(DataSourceImpl.java:213)
     [java]     at de.hybris.platform.jdbcwrapper.DataSourceImpl.<init>(DataSourceImpl.java:149)
     [java]     at de.hybris.platform.core.DataSourceImplFactory.createDataSource(DataSourceImplFactory.java:51)
     [java]     at de.hybris.platform.core.AbstractTenant$HybrisDataSourceBuilder.createMasterDataSource(AbstractTenant.java:2869)
     [java]     at de.hybris.platform.core.AbstractTenant$HybrisDataSourceBuilder.buildMasterDataSourceOnce(AbstractTenant.java:2631)
     [java]     at de.hybris.platform.core.AbstractTenant$HybrisDataSourceBuilder.build(AbstractTenant.java:2577)
     [java]     at de.hybris.platform.core.AbstractTenant.doInitializeSafe(AbstractTenant.java:329)
     [java]     at de.hybris.platform.core.AbstractTenant.doInitialize(AbstractTenant.java:308)
     [java]     at de.hybris.platform.core.AbstractTenant.doStartUp(AbstractTenant.java:674)
     [java]     at de.hybris.platform.core.Registry.assureTenantStarted(Registry.java:648)
     [java]     at de.hybris.platform.core.Registry.activateTenant(Registry.java:709)
     [java]     at de.hybris.platform.core.Registry.setCurrentTenant(Registry.java:556)
     [java]     at de.hybris.platform.core.Registry.activateMasterTenantForInit(Registry.java:625)
     [java]     at de.hybris.platform.util.ClientExecuter.execute(ClientExecuter.java:39)
     [java]     ... 6 more
     [java] Caused by: java.sql.SQLException: Unknown error 1045
     [java]     at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:964)
     [java]     at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3970)
     [java]     at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3906)
     [java]     at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:873)
     [java]     at com.mysql.jdbc.MysqlIO.proceedHandshakeWithPluggableAuthentication(MysqlIO.java:1710)
     [java]     at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1226)
     [java]     at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2253)
     [java]     at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2284)
     [java]     at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2083)
     [java]     at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:806)
     [java]     at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
     [java]     at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
     [java]     at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
     [java]     at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
     [java]     at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
     [java]     at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
     [java]     at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:410)
     [java]     at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:328)
     [java]     at de.hybris.platform.jdbcwrapper.JDBCConnectionFactory.createRawSQLConnection(JDBCConnectionFactory.java:189)
     [java]     at de.hybris.platform.jdbcwrapper.JDBCConnectionFactory.createSQLConnection(JDBCConnectionFactory.java:220)
     [java]     at de.hybris.platform.jdbcwrapper.JDBCConnectionFactory.makeObject(JDBCConnectionFactory.java:109)
     [java]     at org.apache.commons.pool2.impl.GenericObjectPool.create(GenericObjectPool.java:868)
     [java]     at org.apache.commons.pool2.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:435)
     [java]     at org.apache.commons.pool2.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:363)
     [java]     at de.hybris.platform.jdbcwrapper.JDBCConnectionPool.borrowConnection(JDBCConnectionPool.java:113)
     [java]     at de.hybris.platform.jdbcwrapper.ConnectionErrorCheckingJDBCConnectionPool.borrowConnection(ConnectionErrorCheckingJDBCConnectionPool.java:97)
     [java]     at de.hybris.platform.jdbcwrapper.DataSourceImpl.adjustDatabaseInfos(DataSourceImpl.java:629)
     [java]     ... 20 more
     [java] ERROR [main] [DataSourceImpl] error connecting to DataSource having url jdbc:mysql://10.43.4.168:3306/hemdevhybris?useConfigs=maxPerformance&characterEncoding=utf8&useSSL=false: Unknown error 1045
     [java] shutting down hybris registry..

BUILD FAILED
/TK/hybris/bin/platform/build.xml:123: The following error occurred while executing this line:
/ABC/hybris/bin/platform/resources/ant/antmacros.xml:1021: The following error occurred while executing this line:
/ABC/hybris/bin/platform/resources/ant/platformadministration.xml:51: The following error occurred while executing this line:
/ABC/hybris/bin/platform/resources/ant/antmacros.xml:878: Java returned: 1

Hybris local.properties:

db.url=jdbc:mysql://<mysql-IP>:3306/hybrisdatabase?useConfigs=maxPerformance&characterEncoding=utf8&useSSL=false
db.driver=com.mysql.jdbc.Driver
db.username=hybris-user
db.password=*****
db.tableprefix=
mysql.optional.tabledefs=CHARSET=utf8 COLLATE=utf8_bin
mysql.tabletype=InnoDB

Mysql connectivity from hybris node:

[hybris@****platform]$ mysql -h <mysql-ip> -u hybris-user -p'password'
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MySQL connection id is 2188
Server version: 5.7.20 MySQL Community Server (GPL)

Copyright (c) 2000, 2017, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MySQL [(none)]> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| hybrisdatabase       |
+--------------------+
2 rows in set (0.01 sec)

MySQL [(none)]>  SHOW GRANTS FOR 'hybris-user'@'%';
+------------------------------------------------------------------+
| Grants for hybris-user@%                                      |
+------------------------------------------------------------------+
| GRANT USAGE ON *.* TO 'hybris-user'@'%'                       |
| GRANT ALL PRIVILEGES ON `hybrisdatabase`.* TO 'hybris-user'@'%' |
+------------------------------------------------------------------+
2 rows in set (0.00 sec)

MySQL [(none)]> use hybrisdatabase;
Database changed
MySQL [hybrisdatabase]> show tables;
Empty set (0.01 sec)


问:
org.w3c.dom.Node with Android version less than 2.2
getTextContent() is not a recognized function.  getNodeValue() works fine for strings, but anytime I try to parse a number using getNodeValue(), it returns null!

How can I parse a Long from XML using this class?

答:
The root cause of this is that the getTextContent() method is a W3C DOM Level 3 method; see the changes section of the DOM level 3 core spec.

The Node interface has two new attributes, Node.baseURI and Node.textContent. ...

and getTextContent() is the getter for the new attribute.

(Presumably, older versions of Android don't implement the DOM level 3 APIs.)

The behavior of getTextContent() is a bit complicated in the general case; see the spec for the textContext attribute.  In the simple case where the target node is an Element with (only) text contents, node.getTextContext() is the same as node.getFirstChild().getNodeValue().

ContentLicense: CC BY-SA 2.5


答:
If your $myarray is multi dimensional array the use the following code

```<code>$array = [
    1 => 'OK'
    2 => 'nOK'
    3 => 'warning'
    4 => 'Other'
];

foreach($myarray as $key => $subarray)
{
    foreach($subarray as $ele)
    print_r($array[$ele]);
}
</code>```

Title: Replace array key value

Body:
If your $myarray is multi dimensional array the use the following code

$array = [
    1 => 'OK'
    2 => 'nOK'
    3 => 'warning'
    4 => 'Other'
];

foreach($myarray as $key => $subarray)
{
    foreach($subarray as $ele)
    print_r($array[$ele]);
}


问:
How do you stop users directly accessing files on a website in IIS
I want to stop users on the internet being able to enter this URL into a browser and access these files directly. How can I do this?

note: application developed in asp.net

for example: mysite/uploadedfiles/file1.txt

is there any iis rule? Please help me.

答:
Try to use the requestFiltering and hidden segments security feature in web.config.</p>

```<code><configuration>
   <system.webServer>
      <security>
         <requestFiltering>
            <hiddenSegments applyToWebDAV="false">
               <add segment="uploadedfiles" />
            </hiddenSegments>
         </requestFiltering>
      </security>
   </system.webServer>
</configuration>
</code>```

Body:
Try to use the requestFiltering and hidden segments security feature in web.config.

<configuration>
   <system.webServer>
      <security>
         <requestFiltering>
            <hiddenSegments applyToWebDAV="false">
               <add segment="uploadedfiles" />
            </hiddenSegments>
         </requestFiltering>
      </security>
   </system.webServer>
</configuration>


问:
Magento 2 : Message Notification not working in chrome browser
I had developed "Test Message" extension in Magento 2. In this extension, i create \Magento\Framework\Message\ManagerInterface class object and called addSuccess() and addError() Method.

```<code>$this->messageManager->addSuccess('Custom success message');
$this->messageManager->addError('Custom Error message');
</code>```

But it only works in Firefox. When i run this extension in chrome, success and error message not working ?

Also Magento 2 in-built system messages only display in Firefox. Those system messages are also not display in chrome.
so..It is Magento 2 bug ? and if this not bug then what is solution for this problem ?

Please help me. Any help would be appreciated.

答:
Try to Use addSuccessMessage(),addErrorMessage()

Or
Clear your browser cache and cookies, then try it.

Body:
I had developed "Test Message" extension in Magento 2. In this extension, i create \Magento\Framework\Message\ManagerInterface class object and called addSuccess() and addError() Method.

$this->messageManager->addSuccess('Custom success message');
$this->messageManager->addError('Custom Error message');

But it only works in Firefox. When i run this extension in chrome, success and error message not working ?

Also Magento 2 in-built system messages only display in Firefox. Those system messages are also not display in chrome.
so..It is Magento 2 bug ? and if this not bug then what is solution for this problem ?

Please help me. Any help would be appreciated.


问:
Why i can't take address of variable?
guys!
Why i can't take address of "t" - variable ?

```<code>flygs->type == 'X' ? t = a_ib_u(u->us, 16) : (a_lowcasealph(&(t = a_ib_u(u->us, 16))));
\\a_ib_u returns *char, a_lowcasealph take **char argument
</code>```

error: cannot take the address of an rvalue of type 'char *'

答:
You're not actually taking the address of a variable here:

```<code>&(t = a_ib_u(u->us, 16))
</code>```

What you have here is an expression which is the assignment operator, and whose value is the value assigned.  This is not the same as taking the address of a variable.  As was mentioned in the comments, a variable is an lvalue, while an expression involving one or more operators an rvalue.  You can only take the address of an lvalue.

To get around this, you can use the comma operator:

```<code>flygs->type == 'X' ? t = a_ib_u(u->us, 16) :
                     a_lowcasealph(((t = a_ib_u(u->us, 16)), &t));
</code>```

Note that you need an extra pair of parenthesis around the comma operator expression to prevent the comma from being interpreted as a separator for function arguments.

Title: Why i can't take address of variable?

Body:
guys!
Why i can't take address of "t" - variable ?

flygs->type == 'X' ? t = a_ib_u(u->us, 16) : (a_lowcasealph(&(t = a_ib_u(u->us, 16))));
\\a_ib_u returns *char, a_lowcasealph take **char argument

error: cannot take the address of an rvalue of type 'char *'

Body:
You're not actually taking the address of a variable here:

&(t = a_ib_u(u->us, 16))

What you have here is an expression which is the assignment operator, and whose value is the value assigned.  This is not the same as taking the address of a variable.  As was mentioned in the comments, a variable is an lvalue, while an expression involving one or more operators an rvalue.  You can only take the address of an lvalue.

To get around this, you can use the comma operator:

flygs->type == 'X' ? t = a_ib_u(u->us, 16) :
                     a_lowcasealph(((t = a_ib_u(u->us, 16)), &t));

Note that you need an extra pair of parenthesis around the comma operator expression to prevent the comma from being interpreted as a separator for function arguments.


问:
How to overcome app not installed error when building from Android Studio 3.0?
For giving build for a debug Android app from Android Studio 3.0, it’s not installing in Mobile having Marshmallow and up (in Lollipop not tested).

I have used many solutions from Stack overflow but it’s still not working.

It’s always showing App Not Installed on mobile phone.

答:
None of the other answers solved the issue. The build and install was going fine when it's triggered from android studio with a device connected to the computer or with an emulator, the only issue was when sending the apk via email or hockey app.

How I could fix it (and this might not be the solution for everybody), I enabled the multidex support by adding this to the default config:

```<code>// Enabling multidex support.
    multiDexEnabled true
</code>```

PS: Usually Android Studio build would fail if the multidex support has to be enabled, in this new version this didn't happen, but my Jenkins build was broken and this is how I could solve it.

ContentLicense: CC BY-SA 4.0

Body:
None of the other answers solved the issue. The build and install was going fine when it's triggered from android studio with a device connected to the computer or with an emulator, the only issue was when sending the apk via email or hockey app.

How I could fix it (and this might not be the solution for everybody), I enabled the multidex support by adding this to the default config:

// Enabling multidex support.
    multiDexEnabled true

PS: Usually Android Studio build would fail if the multidex support has to be enabled, in this new version this didn't happen, but my Jenkins build was broken and this is how I could solve it.


问:
updating Multiple lines in the same time with Python
```<code>with open('G1.txt', 'r') as f:
    lines = f.readlines()

with open('G1.txt', 'w') as f:
    for i,line in enumerate(lines):
        if i==10:
               f.write ("in1  G  OP  RE 1* " + str(g)+ "3500  /"+ '\n')
               f.write ("in2  G  OP  RE 1* " + str(g)+ "3500  /"+ '\n')
        elif i==20:
            f.write(str(t)+ "*31 /"+'\n')
</code>```

I have multiple line update inside a big file, and some of those lines are multiple lines
Every time I run the code, it removes the first line only and add the new lines to it. The output looks like this

```<code>in1  W  OP  RE 1*  19000  3500  /
in2  W  OP  RE 1*  19000  3500  /
in2  W  OP  RE 1*  10000  3500  /
10*31
</code>```

In this example, you will see there is 2 in2 in the file. So, every time i run the code those lines will add up to each other. so instead of having 2 lines I might end up with extra 5 lines

```<code>Is there a way to remove the old second line and update it with the new one without repeating `elif i==` for every single line
Because sometime I have to update 7 or ten new lines in the same section and for different sections
</code>```

Best Regards

答:
You have multiple issues with the code you have posted, but do you mean this:

```<code>with open('G1.txt', 'r') as f:
    lines = f.readlines()

with open('G1.txt', 'w') as f:
    for i,line in enumerate(lines):
        if i == 10:
            f.write( ...
            f.write( ...
        elif i == 11:
            pass
        # etc etc

        else:
            f.write(line)
</code>```

When the code reaches line 10 it writes the two lines you want, plus when it reaches the old line 11 it doesn't write out the old line.

(Plus all lines not mentioned by line number are written back to the file)

Update:

```<code>with open('G1.txt', 'r') as f:
    lines = f.readlines()

with open('G1.txt', 'w') as f:
    for i,line in enumerate(lines):
        if i == 2:
            f.write('New line 3\n')
            f.write('New line 4\n')
        elif i == 3:
            pass
        # etc etc

        else:
            f.write(line)
</code>```

The above code (tested with Thonny and Py3.6) transforms original file:

```<code>line 1
line 2
line 3
line 4
line 5
line 6
</code>```

Into new file:

```<code>line 1
line 2
New line 3
New line 4
line 5
line 6
</code>```

And repeated runs always leaves the file in the second state

Body:
with open('G1.txt', 'r') as f:
    lines = f.readlines()

with open('G1.txt', 'w') as f:
    for i,line in enumerate(lines):
        if i==10:
               f.write ("in1  G  OP  RE 1* " + str(g)+ "3500  /"+ '\n')
               f.write ("in2  G  OP  RE 1* " + str(g)+ "3500  /"+ '\n')
        elif i==20:
            f.write(str(t)+ "*31 /"+'\n')

I have multiple line update inside a big file, and some of those lines are multiple lines
Every time I run the code, it removes the first line only and add the new lines to it. The output looks like this

in1  W  OP  RE 1*  19000  3500  /
in2  W  OP  RE 1*  19000  3500  /
in2  W  OP  RE 1*  10000  3500  /
10*31

In this example, you will see there is 2 in2 in the file. So, every time i run the code those lines will add up to each other. so instead of having 2 lines I might end up with extra 5 lines

Is there a way to remove the old second line and update it with the new one without repeating `elif i==` for every single line
Because sometime I have to update 7 or ten new lines in the same section and for different sections

Best Regards

Body:
You have multiple issues with the code you have posted, but do you mean this:

with open('G1.txt', 'r') as f:
    lines = f.readlines()

with open('G1.txt', 'w') as f:
    for i,line in enumerate(lines):
        if i == 10:
            f.write( ...
            f.write( ...
        elif i == 11:
            pass
        # etc etc

        else:
            f.write(line)

When the code reaches line 10 it writes the two lines you want, plus when it reaches the old line 11 it doesn't write out the old line.

(Plus all lines not mentioned by line number are written back to the file)

Update:

with open('G1.txt', 'r') as f:
    lines = f.readlines()

with open('G1.txt', 'w') as f:
    for i,line in enumerate(lines):
        if i == 2:
            f.write('New line 3\n')
            f.write('New line 4\n')
        elif i == 3:
            pass
        # etc etc

        else:
            f.write(line)

The above code (tested with Thonny and Py3.6) transforms original file:

line 1
line 2
line 3
line 4
line 5
line 6

Into new file:

line 1
line 2
New line 3
New line 4
line 5
line 6

And repeated runs always leaves the file in the second state


问:
Error in upgrading report server project in Visual Studio 2017
I recently have attempted to migrate a solution created and developed in Visual Studio (VS) 2012 to VS 2017.

I've managed to migrate all projects of my solution except for a Report Server Project. When I try to open my solution in VS 2017 I get the following message:

I click on Yes and VS automatically upgrades the project file (this is a file having the extension .rptproj)

When I now try to build the project I get the following error message:

Error     Copying file Reports\Report\Project1\MyReportProject.rptproj.user to
  obj\Debug\AspnetCompileMerge\Source\Reports\Report
  Project1\MyReportProject.rptproj.user failed. Could not find file
  'Reports\Report Project1\MyReportProject.rptproj.user'

I thought the upgrade would be performed transparently. Am I missing something? Is there any extra step I should take in order to do the upgrade?

Note: I've already downloaded and installed the latest version of Microsoft Reporting Services Projects .vsix package.

答:
You can try the latest msbuild.exe for SSRS is here.

This includes steps of up-gradation of SSRS for both VS15 and VS17.

Once you install the latest update, depending on which version of Visual Studio you’re using, the new files enabling MSBuild for your projects will be installed in different folder path:

In Visual Studio 2017, it’ll will be a nested folder in your Visual Studio folder hierarchy. For example, the location with the Community Edition is in the Community folder:

Edit 1:

Try these steps:

1) Close Visual Studio - 17

2) Open VS-17 Installer

3) Try to install the SSDT workflow as:


问:
XCUI Test: How to fetch List of elements from the iOS screen
I have recently started automating iOS apps on iPhone real devices with the XCUI test setup.

I got a scenario where my app contains 5 screens in the home page, each screen contains a unique card number and its balance so i have to fetch the card number from the screen and verify it with my input(expected) card number, if both are same then i have to click on the card screen otherwise if both are not same then i have to swipe right to the second screen and do the same process.

I was able to automate this scenrio in android perfectly because in android each screen is clearly differentiated with a unique card number but when i inspect the card number screen on iOS app it was showing all the list of cards attached to the app. in this case its getting difficult for me to get the card number from the app and verify it with my input card number . please see the below code which am already using it for android

```<code>String oysterCardVisibleNumberOnApp= data.get("PrestigeCardNumber");

while(!action.getText(HomePage.oysterCardNumber,"oysterCardNumber").equalsIgnorecase(oysterCardVisibleNumberOnApp))){
      action.swipeRightToLeft();
     }
</code>```

it would be great if any one has any idea how to retrieve the list of elements/cards from the iOS app please let me know. or if you know any new methods in XCUI setup will help me to achieve this then please let me know. your help will be much appreciated :)

Please see the below Android Screen & iOS Screen pictures for getting more clarity

Android Screen

iOS Screen

Thank you

答:
You might be able to use the Accessibility Inspector in xcode for this:

https://developer.apple.com/library/content/documentation/Accessibility/Conceptual/AccessibilityMacOSX/OSXAXTestingApps.html

Based on areas you select in your app, it gives back detailed descriptions on each one. But what it brings back depends on the structure of your application. I was trying to do something similar in my own ios application and this helped me a bit.

Body:
I have recently started automating iOS apps on iPhone real devices with the XCUI test setup.

I got a scenario where my app contains 5 screens in the home page, each screen contains a unique card number and its balance so i have to fetch the card number from the screen and verify it with my input(expected) card number, if both are same then i have to click on the card screen otherwise if both are not same then i have to swipe right to the second screen and do the same process.

I was able to automate this scenrio in android perfectly because in android each screen is clearly differentiated with a unique card number but when i inspect the card number screen on iOS app it was showing all the list of cards attached to the app. in this case its getting difficult for me to get the card number from the app and verify it with my input card number . please see the below code which am already using it for android

String oysterCardVisibleNumberOnApp= data.get("PrestigeCardNumber");

while(!action.getText(HomePage.oysterCardNumber,"oysterCardNumber").equalsIgnorecase(oysterCardVisibleNumberOnApp))){
      action.swipeRightToLeft();
     }

it would be great if any one has any idea how to retrieve the list of elements/cards from the iOS app please let me know. or if you know any new methods in XCUI setup will help me to achieve this then please let me know. your help will be much appreciated :)

Please see the below Android Screen & iOS Screen pictures for getting more clarity

Android Screen

iOS Screen

Thank you


问:
Splinter fill function is very slow, with IE Webdriver
So, I've followed this tutorial to use the Splinter framework with Internet Explorer (https://stirunagari.wordpress.com/2017/08/20/using-internet-explorer-web-driver-with-splinter-framework/), and It's working....well kind of working.

```<code>from splinter import Browser
browser = Browser('iexplorer')
browser.visit('http://google.com')
browser.fill('q', 'Text to fill in the search bar')
</code>```

The search field is being filled but at a very slow rate, like 1 keystroke in 1-2 seconds. While using Chrome or Firefox as the browser the browser.fill is working well.
I know that this issue is most probably because IE is not directly supported by Splinter, but maybe someone knows a workaround or something?

Edit: I don't know what IEDriver I was using before, but I replaced it with IEDriverServer_Win32 from Here,and it's working fine now. I can't answer my question because someone deleted my answer...

答: Sounds like you are using 32-bit version of IE Driver. You should use 64 bit version of IE driver not sure why but it much more faster.</p>

Body:
So, I've followed this tutorial to use the Splinter framework with Internet Explorer (https://stirunagari.wordpress.com/2017/08/20/using-internet-explorer-web-driver-with-splinter-framework/), and It's working....well kind of working.

from splinter import Browser
browser = Browser('iexplorer')
browser.visit('http://google.com')
browser.fill('q', 'Text to fill in the search bar')

The search field is being filled but at a very slow rate, like 1 keystroke in 1-2 seconds. While using Chrome or Firefox as the browser the browser.fill is working well.
I know that this issue is most probably because IE is not directly supported by Splinter, but maybe someone knows a workaround or something?

Edit: I don't know what IEDriver I was using before, but I replaced it with IEDriverServer_Win32 from Here,and it's working fine now. I can't answer my question because someone deleted my answer...


问:
How do I convert a Char to Int?
So I have a String of integers that looks like "82389235", but I wanted to iterate through it to add each number individually to a MutableList. However, when I go about it the way I think it would be handled:

```<code>var text = "82389235"

for (num in text) numbers.add(num.toInt())
</code>```

This adds numbers completely unrelated to the string to the list. Yet, if I use println to output it to the console it iterates through the string perfectly fine.

How do I properly convert a Char to an Int?

答:
On JVM there is efficient java.lang.Character.getNumericValue() available: </p>

```<code>val numbers: List<Int> = "82389235".map(Character::getNumericValue)
</code>```

Title: How do I convert a Char to Int?

Body:
So I have a String of integers that looks like "82389235", but I wanted to iterate through it to add each number individually to a MutableList. However, when I go about it the way I think it would be handled:

var text = "82389235"

for (num in text) numbers.add(num.toInt())

This adds numbers completely unrelated to the string to the list. Yet, if I use println to output it to the console it iterates through the string perfectly fine.

How do I properly convert a Char to an Int?

Body:
On JVM there is efficient java.lang.Character.getNumericValue() available:

val numbers: List<Int> = "82389235".map(Character::getNumericValue)


问:
"WHERE column IS NOT NULL" with Kohana v3 Query Builder
Is it possible with Kohana v3 Query Builder to use the IS NOT NULL operator?

The where($column, $op, $value) method requires all three parameters and even if I specify

```<code>->where('col', 'IS NOT NULL', '')
</code>```

it builds and invalid query eg.

```<code>SELECT * FROM table WHERE col IS NOT NULL '';
</code>```

答:
The operator is not escaped:

```<code>->where('col', 'IS NOT', NULL)
</code>```

No need to use DB::expr, Kohana already supports what you want.

Body:
Is it possible with Kohana v3 Query Builder to use the IS NOT NULL operator?

The where($column, $op, $value) method requires all three parameters and even if I specify

->where('col', 'IS NOT NULL', '')

it builds and invalid query eg.

SELECT * FROM table WHERE col IS NOT NULL '';

Body:
The operator is not escaped:

->where('col', 'IS NOT', NULL)

No need to use DB::expr, Kohana already supports what you want.


问:
unresolved external symbol _DEVPKEY_Device_BusReportedDeviceDesc
For devices attached to my machine I want to retrieve device-property Bus Reported Device Description. For this purpose I use function SetupDiGetDeviceProperty of Setup API. In devpkey.h I found the defintion DEVPKEY_Device_BusReportedDeviceDesc.

But if I use DEVPKEY_Device_BusReportedDeviceDesc I receive unresolved external symbol _DEVPKEY_Device_BusReportedDeviceDesc while linking.

Here is my code (only included minimal code to reproduce issue):

```<code>#include "stdafx.h"

#include <Windows.h>
#include <devpropdef.h>
#include <devpkey.h>

int main()
{
    DEVPROPKEY x = DEVPKEY_Device_BusReportedDeviceDesc;

    return 0;
}
</code>```

Here is the full error code:

error LNK2001: unresolved external symbol
  _DEVPKEY_Device_BusReportedDeviceDesc

How can I fix this issue ?

答:
To fix this issue you need to include initguid.h. This include must before devpropdef.h and devpkey.h.

```<code>#include "stdafx.h"
#include <initguid.h>   // include before devpropdef.h
#include <Windows.h>
#include <devpropdef.h>
#include <devpkey.h>

int main()
{
    DEVPROPKEY x = DEVPKEY_Device_BusReportedDeviceDesc;

    return 0;
}
</code>```

Body:
For devices attached to my machine I want to retrieve device-property Bus Reported Device Description. For this purpose I use function SetupDiGetDeviceProperty of Setup API. In devpkey.h I found the defintion DEVPKEY_Device_BusReportedDeviceDesc.

But if I use DEVPKEY_Device_BusReportedDeviceDesc I receive unresolved external symbol _DEVPKEY_Device_BusReportedDeviceDesc while linking.

Here is my code (only included minimal code to reproduce issue):

#include "stdafx.h"

#include <Windows.h>
#include <devpropdef.h>
#include <devpkey.h>

int main()
{
    DEVPROPKEY x = DEVPKEY_Device_BusReportedDeviceDesc;

    return 0;
}

Here is the full error code:

error LNK2001: unresolved external symbol
  _DEVPKEY_Device_BusReportedDeviceDesc

How can I fix this issue ?

Body:
To fix this issue you need to include initguid.h. This include must before devpropdef.h and devpkey.h.

#include "stdafx.h"
#include <initguid.h>   // include before devpropdef.h
#include <Windows.h>
#include <devpropdef.h>
#include <devpkey.h>

int main()
{
    DEVPROPKEY x = DEVPKEY_Device_BusReportedDeviceDesc;

    return 0;
}


问:
How to slice particular values from a string using regular expression in JavaScript or Java
How do I slice, and get only string values excluding characters inside {} braces.

I'm able to get characters inside curly braces, but how to get contents outside the curly braces?

I have a string like this:

name is {response.vital.name} and disease is {response.vital.some} and drug is {response.vital.dis}

I want output array like this:

["the name is","and disease is","and drug is"]

答:
In JavaScript you can do the following:

```<code>s = "name is {response.vital.name} and disease is {response.vital.some} and drug is {response.vital.dis}";
a = s.split(/\s*\{[^\}]*\}\s*/)
</code>```

The Java solution looks quite similar:

```<code>String s = "name is {response.vital.name} and disease is {response.vital.some} and drug is {response.vital.dis}";
String[] a = s.split("\\s*\\{[^\\}]*\\}\\s*");
</code>```

Body:
In JavaScript you can do the following:

s = "name is {response.vital.name} and disease is {response.vital.some} and drug is {response.vital.dis}";
a = s.split(/\s*\{[^\}]*\}\s*/)

The Java solution looks quite similar:

String s = "name is {response.vital.name} and disease is {response.vital.some} and drug is {response.vital.dis}";
String[] a = s.split("\\s*\\{[^\\}]*\\}\\s*");


答:
A solution in JS:

var str = "name is {response.vital.name} and disease is {response.vital.some} and drug is {response.vital.dis}";
var res = str.split('{').reduce((m, o) => {
    if (o.indexOf('}') > -1 && o.split('}')[1]) {
        m.push(o.split('}')[1].trim());
    } else {
        m.push(o.trim());
    }
    return m;
}, []);

console.log(res);```

Title: How to slice particular values from a string using regular expression in JavaScript or Java

Body:
How do I slice, and get only string values excluding characters inside {} braces.

I'm able to get characters inside curly braces, but how to get contents outside the curly braces?

I have a string like this:

name is {response.vital.name} and disease is {response.vital.some} and drug is {response.vital.dis}

I want output array like this:

["the name is","and disease is","and drug is"]


问:
Not found: Op type not registered 'CountExtremelyRandomStats'
I am getting the following error while running bazel command in the docker container.

command ran :

- bazel-bin/tensorflow_serving/model_servers/tensorflow_model_server --port=9000 --model_name=rf_quora --model_base_path=/serving/rf_model &> rf_log &

error:

Not found: Op type not registered 'CountExtremelyRandomStats' in binary running on 864822af1c6c. Make sure the Op and Kernel are
  registered in the binary running in this process.

I tried my search with the following link but in vain.
https://github.com/tensorflow/tensorflow/issues/11847

I am trying to do inference using tensorflow tensorserving, but I am getting blocked by the above error.
Using Tensorflow 1.3 and using tensor_forest api present in tf.contrib.tensor_forest_python.

Can anyone help me with this error as it is blocking my testing.

Note:- I have successfully ran tensorserving inference for mnist and inception examples models.

答:
Issue got resolved after upgrading to latest tensorflow version i.e. from 1.3.0 to 1.4 version.

Reference:-
https://github.com/tensorflow/tensorflow/issues/14358


问:
How to get the signature of a C++ bind(...) expression
I am trying to write a metafunction named signature_of which, given the type of a function (pointer), functor, or lambda, returns its signature.

Here's what I have so far:

```<code>#include <boost/mpl/pop_front.hpp>
#include <boost/mpl/push_front.hpp>
#include <boost/function_types/is_member_function_pointer.hpp>
#include <boost/function_types/function_type.hpp>
#include <boost/function_types/result_type.hpp>
#include <boost/function_types/parameter_types.hpp>

#include <type_traits>

template <typename F>
struct signature_of_member
{
    typedef typename boost::function_types::result_type<F>::type result_type;
    typedef typename boost::function_types::parameter_types<F>::type parameter_types;
    typedef typename boost::mpl::pop_front<parameter_types>::type base;
    typedef typename boost::mpl::push_front<base, result_type>::type L;
    typedef typename boost::function_types::function_type<L>::type type;
};

template <typename F, bool is_class>
struct signature_of_impl
{
    typedef typename boost::function_types::function_type<F>::type type;
};

template <typename F>
struct signature_of_impl<F, true>
{
    typedef typename signature_of_member<decltype(&F::operator())>::type type;
};

template <typename F>
struct signature_of
{
    typedef typename signature_of_impl<F, std::is_class<F>::value>::type type;
};
</code>```

It's pretty straightforward, with most of the real work being done by the boost::function_types library.
The general idea is:

use std::is_class to discriminate
between built-in functions (including
lambdas) and functors

for built-in function types, use boost::function_types::function_type to get its signature

for functors, get the type of their operator(), get its signature, and doctor it to remove the "this" parameter

This works for built-in functions:

```<code>int f(int);
typedef signature_of<decltype(f)>::type Sig;  // Sig is int(int)
</code>```

for lambdas:

```<code>auto f = [](int) { return 0; }
typedef signature_of<decltype(f)>::type Sig;  // Sig is int(int)
</code>```

and for functors:

```<code>struct A
{
    int operator()(int);
};
typedef signature_of<A>::type Sig;  // Sig is int(int)
</code>```

However, it doesn't work for bind() expressions (which are a special case of functors). If I try this:

```<code>#include <functional>
int g(int);
typedef signature_of<decltype(std::bind(g, 0))>::type Sig;
</code>```

I get a compiler error:

```<code>In file included from test.cpp:3:0:
signature_of.hpp: In instantiation of 'signature_of_impl<
        _Bind<int (*(int))(int)>, true
    >':
signature_of.hpp:45:74:   instantiated from 'signature_of<
        _Bind<int (*(int))(int)>
    >'
test.cpp:21:52:   instantiated from here
signature_of.hpp:39:74: error: type of '& _Bind<
        int (*)(int)({int} ...)
    >::operator()' is unknown
</code>```

The problem is that the operator() of the functor returned by bind() is a template, and so its type cannot be determined.

Is it possible to get the signature of a bind() expression another way?

答: If the operator is templated, then it doesn't have a signature.

Body:
I am trying to write a metafunction named signature_of which, given the type of a function (pointer), functor, or lambda, returns its signature.

Here's what I have so far:

#include <boost/mpl/pop_front.hpp>
#include <boost/mpl/push_front.hpp>
#include <boost/function_types/is_member_function_pointer.hpp>
#include <boost/function_types/function_type.hpp>
#include <boost/function_types/result_type.hpp>
#include <boost/function_types/parameter_types.hpp>

#include <type_traits>

template <typename F>
struct signature_of_member
{
    typedef typename boost::function_types::result_type<F>::type result_type;
    typedef typename boost::function_types::parameter_types<F>::type parameter_types;
    typedef typename boost::mpl::pop_front<parameter_types>::type base;
    typedef typename boost::mpl::push_front<base, result_type>::type L;
    typedef typename boost::function_types::function_type<L>::type type;
};

template <typename F, bool is_class>
struct signature_of_impl
{
    typedef typename boost::function_types::function_type<F>::type type;
};

template <typename F>
struct signature_of_impl<F, true>
{
    typedef typename signature_of_member<decltype(&F::operator())>::type type;
};

template <typename F>
struct signature_of
{
    typedef typename signature_of_impl<F, std::is_class<F>::value>::type type;
};

It's pretty straightforward, with most of the real work being done by the boost::function_types library.
The general idea is:

use std::is_class to discriminate
between built-in functions (including
lambdas) and functors

for built-in function types, use boost::function_types::function_type to get its signature

for functors, get the type of their operator(), get its signature, and doctor it to remove the "this" parameter

This works for built-in functions:

int f(int);
typedef signature_of<decltype(f)>::type Sig;  // Sig is int(int)

for lambdas:

auto f = [](int) { return 0; }
typedef signature_of<decltype(f)>::type Sig;  // Sig is int(int)

and for functors:

struct A
{
    int operator()(int);
};
typedef signature_of::type Sig;  // Sig is int(int)

However, it doesn't work for bind() expressions (which are a special case of functors). If I try this:

#include <functional>
int g(int);
typedef signature_of<decltype(std::bind(g, 0))>::type Sig;

I get a compiler error:

In file included from test.cpp:3:0:
signature_of.hpp: In instantiation of 'signature_of_impl<
        _Bind<int (*(int))(int)>, true
    >':
signature_of.hpp:45:74:   instantiated from 'signature_of<
        _Bind<int (*(int))(int)>
    >'
test.cpp:21:52:   instantiated from here
signature_of.hpp:39:74: error: type of '& _Bind<
        int (*)(int)({int} ...)
    >::operator()' is unknown

The problem is that the operator() of the functor returned by bind() is a template, and so its type cannot be determined.

Is it possible to get the signature of a bind() expression another way?


问:
VBA Excel - Putting columns into range in right order
so recently I have been looking into using defined ranges to copy data instead of selecting, copying and pasting cells. This way I hope to optimise the performance and the runtime of my code.

Unfortunately I have come to face a problem I wasn't able to solve on my own.

When defining a range I want to rearrange the columns in a different order.

For example:

```<code>Set my_range = Sheets("Sheet1").Range("A2:E2,G2:H2,J2:K2,M2")
</code>```

Works well, as the columns I fill into the range are behind each other in the sheet. But now I have this:

```<code>Set yo_range = Sheets("Sheet2").Range("D2,AV2,L2,H2,Q2,AE2,AG2")
</code>```

If I fill these ranges into a new sheet the yo_range will fill the columns I put into it but not in the order I written down. It will put it down in the order according to the original one. In this example yo_range would put the data in this order into the new sheet:

D2 | H2 | L2 | Q2 | AE2 | AG2 | AV2

How can I fix this? I want the order to be another one than the original one.
Also - as you can see my_range has more columns than yo_range. How can I let yo_range be filled into the new sheet but at certain points leave columns out? For example:

my_range(A2:E2) goes into A2:E2 in the new sheet

yo_range(D2,AV2) goes into A:B in the new sheet, then leave C out and then paste yo_range(L2,H2) into D:E in the new sheet

I hope that I was able to explain my problem well and that there is somebody able and willing to help me. Any help is appreciated.

Edit:

Here's the code that puts the values from the ranges into the new sheet

```<code>Do
    If Application.WorksheetFunction.CountA(my_range) > 0 Then
    my_range.Copy ws.Range("A" & ws.Rows.Count).End(xlUp).Offset(1, 0)
    Set my_range = my_range.Offset(1, 0)
    Else
    Exit Do
    End If
Loop

Do
    If Application.WorksheetFunction.CountA(yo_range) > 0 Then
    yo_range.Copy ws.Range("A" & ws.Rows.Count).End(xlUp).Offset(1, 0)
    Set yo_range = yo_range.Offset(1, 0)
    Else
    Exit Do
    End If
Loop
</code>```

答:
We can see that the Copy method will re-arrange the data left-to-right. Try this:

```<code>Option Explicit

Public Sub CheckClipboard()

    Dim ws As Worksheet
    Dim rngToCopy As Range
    Dim objData As Object
    Dim varContents As Variant

    ' test data b,c,d,e,f,g in Sheet1!B1:G1
    Set ws = ThisWorkbook.Worksheets("Sheet1")
    ws.Range("B1:G1").Value = Array("b", "c", "d", "e", "f", "g")

    Set rngToCopy = ws.Range("E1:F1,G1,B1:C1") '<-- note not left-to-right order
    rngToCopy.Copy '<-- copy

    ' this is a late bound MSForms.DataObject
    Set objData = CreateObject("New:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")

    ' copy current cell formula to clipboard
    objData.GetFromClipboard
    varContents = objData.GetText

    Debug.Print varContents '<-- re-arranged left-to-right

    ' cancel copy
    Application.CutCopyMode = False

End Sub
</code>```

I get this in the immediate window:

```<code>b   c   d   e   f   g
</code>```

So, using Copy is not going to work for what you want to do.

In order to 'paste' the data in the order that you set it in the Range, you need to iterate each Area of the Range and then each cell (i.e. Range) in each Area. See the test code below which replicates your issue and presents a solution:

```<code>Option Explicit

Sub MixColumns()

    Dim ws As Worksheet
    Dim rngIn As Range
    Dim rngOut As Range
    Dim lng As Long
    Dim rngArea As Range
    Dim rngCell As Range

    Set ws = ThisWorkbook.Worksheets("Sheet1")

    ' example 1
    Set rngIn = ws.Range("B1:C1,E1:F1,G1") '<-- 5 cells, non-contiguous, forward order
    Set rngOut = ws.Range("B2:F2") '<-- 5 contiguous cells

    rngIn.Copy rngOut '<-- works

    ' example 2 - OP problem
    Set rngIn = ws.Range("E1:F1,G1,B1:C1") '<-- 5 cells, non-contiguous, odd order
    Set rngOut = ws.Range("B3:F3") '<-- 5 contiguous cells

    rngIn.Copy rngOut '<-- should be e,f,g,b,c but gets b,c,e,f,g

    ' example 3 - solution for OP problem
    Set rngIn = ws.Range("E1:F1,G1,B1:C1") '<-- 5 cells, non-contiguous, odd order
    Set rngOut = ws.Range("B4:F4") '<-- 5 contiguous cells

    lng = 1 '<-- rngOut cell counter
    ' iterate areas
    For Each rngArea In rngIn.Areas
        ' iterate cells in area
        For Each rngCell In rngArea.Cells
            rngOut.Cells(1, lng).Value = rngCell.Value '<-- copy single value
            lng = lng + 1 '<-- increment rngOut counter
        Next rngCell
    Next rngArea '<-- results in e,f,g,b,c

End Sub
</code>```

Give this output:

Body:
so recently I have been looking into using defined ranges to copy data instead of selecting, copying and pasting cells. This way I hope to optimise the performance and the runtime of my code.

Unfortunately I have come to face a problem I wasn't able to solve on my own.

When defining a range I want to rearrange the columns in a different order.

For example:

Set my_range = Sheets("Sheet1").Range("A2:E2,G2:H2,J2:K2,M2")

Works well, as the columns I fill into the range are behind each other in the sheet. But now I have this:

Set yo_range = Sheets("Sheet2").Range("D2,AV2,L2,H2,Q2,AE2,AG2")

If I fill these ranges into a new sheet the yo_range will fill the columns I put into it but not in the order I written down. It will put it down in the order according to the original one. In this example yo_range would put the data in this order into the new sheet:

D2 | H2 | L2 | Q2 | AE2 | AG2 | AV2

How can I fix this? I want the order to be another one than the original one.
Also - as you can see my_range has more columns than yo_range. How can I let yo_range be filled into the new sheet but at certain points leave columns out? For example:

my_range(A2:E2) goes into A2:E2 in the new sheet

yo_range(D2,AV2) goes into A:B in the new sheet, then leave C out and then paste yo_range(L2,H2) into D:E in the new sheet

I hope that I was able to explain my problem well and that there is somebody able and willing to help me. Any help is appreciated.

Edit:

Here's the code that puts the values from the ranges into the new sheet

Do
    If Application.WorksheetFunction.CountA(my_range) > 0 Then
    my_range.Copy ws.Range("A" & ws.Rows.Count).End(xlUp).Offset(1, 0)
    Set my_range = my_range.Offset(1, 0)
    Else
    Exit Do
    End If
Loop

Do
    If Application.WorksheetFunction.CountA(yo_range) > 0 Then
    yo_range.Copy ws.Range("A" & ws.Rows.Count).End(xlUp).Offset(1, 0)
    Set yo_range = yo_range.Offset(1, 0)
    Else
    Exit Do
    End If
Loop

Body:
We can see that the Copy method will re-arrange the data left-to-right. Try this:

Option Explicit

Public Sub CheckClipboard()

    Dim ws As Worksheet
    Dim rngToCopy As Range
    Dim objData As Object
    Dim varContents As Variant

    ' test data b,c,d,e,f,g in Sheet1!B1:G1
    Set ws = ThisWorkbook.Worksheets("Sheet1")
    ws.Range("B1:G1").Value = Array("b", "c", "d", "e", "f", "g")

    Set rngToCopy = ws.Range("E1:F1,G1,B1:C1") '<-- note not left-to-right order
    rngToCopy.Copy '<-- copy

    ' this is a late bound MSForms.DataObject
    Set objData = CreateObject("New:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")

    ' copy current cell formula to clipboard
    objData.GetFromClipboard
    varContents = objData.GetText

    Debug.Print varContents '<-- re-arranged left-to-right

    ' cancel copy
    Application.CutCopyMode = False

End Sub

I get this in the immediate window:

b   c   d   e   f   g

So, using Copy is not going to work for what you want to do.

In order to 'paste' the data in the order that you set it in the Range, you need to iterate each Area of the Range and then each cell (i.e. Range) in each Area. See the test code below which replicates your issue and presents a solution:

Option Explicit

Sub MixColumns()

    Dim ws As Worksheet
    Dim rngIn As Range
    Dim rngOut As Range
    Dim lng As Long
    Dim rngArea As Range
    Dim rngCell As Range

    Set ws = ThisWorkbook.Worksheets("Sheet1")

    ' example 1
    Set rngIn = ws.Range("B1:C1,E1:F1,G1") '<-- 5 cells, non-contiguous, forward order
    Set rngOut = ws.Range("B2:F2") '<-- 5 contiguous cells

    rngIn.Copy rngOut '<-- works

    ' example 2 - OP problem
    Set rngIn = ws.Range("E1:F1,G1,B1:C1") '<-- 5 cells, non-contiguous, odd order
    Set rngOut = ws.Range("B3:F3") '<-- 5 contiguous cells

    rngIn.Copy rngOut '<-- should be e,f,g,b,c but gets b,c,e,f,g

    ' example 3 - solution for OP problem
    Set rngIn = ws.Range("E1:F1,G1,B1:C1") '<-- 5 cells, non-contiguous, odd order
    Set rngOut = ws.Range("B4:F4") '<-- 5 contiguous cells

    lng = 1 '<-- rngOut cell counter
    ' iterate areas
    For Each rngArea In rngIn.Areas
        ' iterate cells in area
        For Each rngCell In rngArea.Cells
            rngOut.Cells(1, lng).Value = rngCell.Value '<-- copy single value
            lng = lng + 1 '<-- increment rngOut counter
        Next rngCell
    Next rngArea '<-- results in e,f,g,b,c

End Sub

Give this output: