问:
object 'new HttpResponseMessage()' is not disposed along all exception paths
I have tired using statement after going through the links in stackoverflow  but still couldnt figure the exact solution.

```<code> using (MemoryStream stream = new MemoryStream(textAsBytes))
            {
                using (HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new StreamContent(stream)
                })
                {
                    httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                    {
                        FileName = "main-theme.scss"
                    };
                    httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("text/css");

                    ResponseMessageResult responseMessageResult = ResponseMessage(httpResponseMessage);
                    return responseMessageResult;
                }
            }
</code>```

getting the following error

CA2000    In method 'GetStyleSheet()', object 'new HttpResponseMessage()' is not disposed along all exception paths. Call System.IDisposable.Dispose on object 'new HttpResponseMessage()' before all references to it are out of scope.

答:
The problem is that when creating the HttpResponseMessage you use a property initializer in addition to the constructor:

```<code>using (HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
{
  Content = new StreamContent(stream)
})
{
  // ...
}
</code>```

This leads to a code similar to the following is generated:

```<code>var httpRepsonseMessage = new HttpResponseMessage(HttpStatusCode.OK);
httpResponseMessage.Content = new StreamContent(stream);
try
{
   // ...
}
finally
{
  httpResponseMessage.Dispose();
}
</code>```

As you can see, httpResponseMessage will not be disposed if something goes wrong when creating the StreamContent and assigning it.

In order to solve this, move the assignment into the using block:

```<code>using (HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK))
{
  httpResponseMessage.Content = new StreamContent(stream);
  // ...
}
</code>```

This way, the disposal takes place even if there is a problem when assigning the content.

Body:
I have tired using statement after going through the links in stackoverflow  but still couldnt figure the exact solution.

 using (MemoryStream stream = new MemoryStream(textAsBytes))
            {
                using (HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new StreamContent(stream)
                })
                {
                    httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                    {
                        FileName = "main-theme.scss"
                    };
                    httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("text/css");

                    ResponseMessageResult responseMessageResult = ResponseMessage(httpResponseMessage);
                    return responseMessageResult;
                }
            }

getting the following error

CA2000    In method 'GetStyleSheet()', object 'new HttpResponseMessage()' is not disposed along all exception paths. Call System.IDisposable.Dispose on object 'new HttpResponseMessage()' before all references to it are out of scope.

Body:
The problem is that when creating the HttpResponseMessage you use a property initializer in addition to the constructor:

using (HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
{
  Content = new StreamContent(stream)
})
{
  // ...
}

This leads to a code similar to the following is generated:

var httpRepsonseMessage = new HttpResponseMessage(HttpStatusCode.OK);
httpResponseMessage.Content = new StreamContent(stream);
try
{
   // ...
}
finally
{
  httpResponseMessage.Dispose();
}

As you can see, httpResponseMessage will not be disposed if something goes wrong when creating the StreamContent and assigning it.

In order to solve this, move the assignment into the using block:

using (HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK))
{
  httpResponseMessage.Content = new StreamContent(stream);
  // ...
}

This way, the disposal takes place even if there is a problem when assigning the content.


来源: stackexchange

问:
Solution for Windows service failover system on MS Azure
We have a server environment with two different virtual machines each running a subset of our Windows services (about 50 in total split equally) created in .NET. What I'm looking for is the best way to automatically start the remaining services on the other VM should the one of them go down.

The reason we need this solution is that we're running these VMs on the cloud (MS Azure) which can get restarted semi-regularly. These services are also fairly hard to implement as actual horizontal scaling systems (especially the legacy services). So what we're after is essentially a form of redundancy system.

We've considered doing a custom solution ourselves using our centralized SQL database (also on Azure), but we'd rather prefer to use an existing solution if possible.
Google has yielded very little on the topic. So far the only tool we've found that allows this is using Docker with some extensions. But Docker also has many more features that we don't need and has a non-trivial barrier to entry (but is still an option obviously).

答:
You could use Azure Automation to poll the VM with the services and when a service is offline, do X on another VM. Azure recently released Task Watcher(subset to automation) that can poll with 1 minute granularity. note that it is in preview but it gives you sommething that you don't have today.

https://azure.microsoft.com/en-au/updates/azure-automation-watcher-tasks-public-preview-now-available/

ContentLicense: CC BY-SA 3.0


问:
iOS, Swift: How to save an array that contains custom objects so that I can be loaded for reuse?

I have an array that contains objects that I've created. I would like the manager class to load this array from the disk so that I can continue appending to the array.

---HERE IS THE CLASS I WOULD LIKE TO MANAGE LOADING THE ARRAY

```<code> class FoodManager{
    var foodList : [FoodItem]

    func addFood(name : String, carbs : Int, fat: Int, protein : Int) {
        let food = FoodItem(name: name, carbs: carbs, protein: protein,       fat: fat)
        foodList.append(food)
    }

    init(){
        foodList = [FoodItem]()
        //Here is where I would like to load the array to initialize foodList or if the file doesn't exist, create a new array

    }
}
</code>```

-----HERE IS THE CLASS THAT IS IN THE ARRAY----

```<code>class FoodItem{
    let name: String
    let carbs: Int
    let protein: Int
    let fat: Int

    init(name: String, carbs: Int, protein: Int, fat: Int){
        self.name = name
        self.carbs = carbs
        self.protein = protein
        self.fat = fat
    }
}
</code>```

I've found a lot of info on saving a class that has just primitive data types but have been having trouble finding examples where an array of user defined objects needs to be saved.

thanks!

答:
This would be the implementation of your custom class if you want to save it for reuse.

```<code>class FoodItem: NSCoding {
    let name: String?
    let carbs: Int?
    let protein: Int?
    let fat: Int?

required init(name: String, carbs: Int, protein: Int, fat: Int){
    self.name = name
    self.carbs = carbs
    self.protein = protein
    self.fat = fat
}

func encode(with aCoder: NSCoder) {
    aCoder.encode(name, forKey: "name")
    aCoder.encode(carbs, forKey: "carbs")
    aCoder.encode(protein, forKey: "protein")
    aCoder.encode(fat, forKey: "fat")
}

required init(coder aDecoder: NSCoder) {
    self.name = aDecoder.decodeObject(forKey : "name") as? String
    self.carbs = aDecoder.decodeObject(forKey : "carbs") as? Int
    self.protein = aDecoder.decodeObject(forKey : "protein") as? Int
    self.fat = aDecoder.decodeObject(forKey : "fat") as? Int
}
}
</code>```

For saving this class object into userdefaults you can use:

```<code>let userDefaults = UserDefaults.standard
                        let encodedData = NSKeyedArchiver.archivedData(withRootObject: YourObjectToSave)
                        userDefaults.set(encodedData, forKey: "DummyName")
                        userDefaults.synchronize()
</code>```

For getting the object back from userdefaults you can use:

```<code>let decoded  = UserDefaults.standard.object(forKey: "DummyName") as! NSData
let decodedClassObject = NSKeyedUnarchiver.unarchiveObject(with: decoded as Data) as! FoodItem
</code>```

EDIT:

Saving array of FoodItems:

Lets say I have an array of FoodItems:

```<code> let itemArray: [FoodItem] = [item1, item2, item3]
</code>```

You can now use the same code to save this array as well:

```<code> let userDefaults = UserDefaults.standard
                    let encodedData = NSKeyedArchiver.archivedData(withRootObject: YourObjectToSave)
                    userDefaults.set(encodedData, forKey: "itemArray")
                    userDefaults.synchronize()
</code>```

Now retrieve the array as:

```<code>let decoded  = UserDefaults.standard.object(forKey: "itemArray") as! NSData
let decodedClassObject = NSKeyedUnarchiver.unarchiveObject(with: decoded as Data) as! [FoodItem]
</code>```

Body:
I have an array that contains objects that I've created. I would like the manager class to load this array from the disk so that I can continue appending to the array.

---HERE IS THE CLASS I WOULD LIKE TO MANAGE LOADING THE ARRAY

 class FoodManager{
    var foodList : [FoodItem]

    func addFood(name : String, carbs : Int, fat: Int, protein : Int) {
        let food = FoodItem(name: name, carbs: carbs, protein: protein,       fat: fat)
        foodList.append(food)
    }

    init(){
        foodList = [FoodItem]()
        //Here is where I would like to load the array to initialize foodList or if the file doesn't exist, create a new array

    }
}

-----HERE IS THE CLASS THAT IS IN THE ARRAY----

class FoodItem{
    let name: String
    let carbs: Int
    let protein: Int
    let fat: Int

    init(name: String, carbs: Int, protein: Int, fat: Int){
        self.name = name
        self.carbs = carbs
        self.protein = protein
        self.fat = fat
    }
}

I've found a lot of info on saving a class that has just primitive data types but have been having trouble finding examples where an array of user defined objects needs to be saved.

thanks!

Body:
This would be the implementation of your custom class if you want to save it for reuse.

class FoodItem: NSCoding {
    let name: String?
    let carbs: Int?
    let protein: Int?
    let fat: Int?

required init(name: String, carbs: Int, protein: Int, fat: Int){
    self.name = name
    self.carbs = carbs
    self.protein = protein
    self.fat = fat
}

func encode(with aCoder: NSCoder) {
    aCoder.encode(name, forKey: "name")
    aCoder.encode(carbs, forKey: "carbs")
    aCoder.encode(protein, forKey: "protein")
    aCoder.encode(fat, forKey: "fat")
}

required init(coder aDecoder: NSCoder) {
    self.name = aDecoder.decodeObject(forKey : "name") as? String
    self.carbs = aDecoder.decodeObject(forKey : "carbs") as? Int
    self.protein = aDecoder.decodeObject(forKey : "protein") as? Int
    self.fat = aDecoder.decodeObject(forKey : "fat") as? Int
}
}

For saving this class object into userdefaults you can use:

let userDefaults = UserDefaults.standard
                        let encodedData = NSKeyedArchiver.archivedData(withRootObject: YourObjectToSave)
                        userDefaults.set(encodedData, forKey: "DummyName")
                        userDefaults.synchronize()

For getting the object back from userdefaults you can use:

let decoded  = UserDefaults.standard.object(forKey: "DummyName") as! NSData
let decodedClassObject = NSKeyedUnarchiver.unarchiveObject(with: decoded as Data) as! FoodItem

EDIT:

Saving array of FoodItems:

Lets say I have an array of FoodItems:

 let itemArray: [FoodItem] = [item1, item2, item3]

You can now use the same code to save this array as well:

 let userDefaults = UserDefaults.standard
                    let encodedData = NSKeyedArchiver.archivedData(withRootObject: YourObjectToSave)
                    userDefaults.set(encodedData, forKey: "itemArray")
                    userDefaults.synchronize()

Now retrieve the array as:

let decoded  = UserDefaults.standard.object(forKey: "itemArray") as! NSData
let decodedClassObject = NSKeyedUnarchiver.unarchiveObject(with: decoded as Data) as! [FoodItem]


答:
```<code>SELECT TIME_TO_SEC(TIMEDIFF(FROM_UNIXTIME('time 1'), FROM_UNIXTIME('time 2')) AS 'time_diff_in_sec' FROM 'your_table';
</code>```

This can help:
Mysql Get Time Diff

Title: query for time in mysql between hours

Body:
how to get a list of rows that is between 17:30 till tomarrow 8:30.

--------------------------------------
| id | user_id | action |     time    |
--------------------------------------
| 1  |   25    | enter  | 1512459905
| 2  |   19    |  exit  | 1512125105
| 3  |   31    | enter  | 1514581905  |
--------------------------------------

mysql table have a time column with unix timestamp and i want get a list every day that between 17:30 till 8:30

Body:
SELECT TIME_TO_SEC(TIMEDIFF(FROM_UNIXTIME('time 1'), FROM_UNIXTIME('time 2')) AS 'time_diff_in_sec' FROM 'your_table';

This can help:
Mysql Get Time Diff


问:
Loop through an array of strings in Bash?
I want to write a script that loops through 15 strings (array possibly?) Is that possible?

Something like:

```<code>for databaseName in listOfNames
then
  # Do something
end
</code>```

答:
Implicit array for script or functions:

In addition to anubhava's correct answer: If basic syntax for loop is:

```<code>for var in "${arr[@]}" ;do ...$var... ;done
</code>```

there is a special case in bash:

When running a script or a function, arguments passed at command lines will be assigned to $@ array variable, you can access by $1, $2, $3, and so on.

This can be populated (for test) by

```<code>set -- arg1 arg2 arg3 ...
</code>```

A loop over this array could be written simply:

```<code>for item ;do
    echo "This is item: $item."
  done
</code>```

Note that the reserved work in is not present and no array name too!

Sample:

```<code>set -- arg1 arg2 arg3 ...
for item ;do
    echo "This is item: $item."
  done
This is item: arg1.
This is item: arg2.
This is item: arg3.
This is item: ....
</code>```

Note that this is same than

```<code>for item in "$@";do
    echo "This is item: $item."
  done
</code>```

Then into a script:

```<code>#!/bin/bash

for item ;do
    printf "Doing something with '%s'.\n" "$item"
  done
</code>```

Save this in a script myscript.sh, chmod +x myscript.sh, then

```<code>./myscript.sh arg1 arg2 arg3 ...
Doing something with 'arg1'.
Doing something with 'arg2'.
Doing something with 'arg3'.
Doing something with '...'.
</code>```

Same in a function:

```<code>myfunc() { for item;do cat <<<"Working about '$item'."; done ; }
</code>```

Then

```<code>myfunc item1 tiem2 time3
Working about 'item1'.
Working about 'tiem2'.
Working about 'time3'.
</code>```

Body:
I want to write a script that loops through 15 strings (array possibly?) Is that possible?

Something like:

for databaseName in listOfNames
then
  # Do something
end

Body:
Implicit array for script or functions:

In addition to anubhava's correct answer: If basic syntax for loop is:

for var in "${arr[@]}" ;do ...$var... ;done

there is a special case in bash:

When running a script or a function, arguments passed at command lines will be assigned to $@ array variable, you can access by $1, $2, $3, and so on.

This can be populated (for test) by

set -- arg1 arg2 arg3 ...

A loop over this array could be written simply:

for item ;do
    echo "This is item: $item."
  done

Note that the reserved work in is not present and no array name too!

Sample:

set -- arg1 arg2 arg3 ...
for item ;do
    echo "This is item: $item."
  done
This is item: arg1.
This is item: arg2.
This is item: arg3.
This is item: ....

Note that this is same than

for item in "$@";do
    echo "This is item: $item."
  done

Then into a script:

#!/bin/bash

for item ;do
    printf "Doing something with '%s'.\n" "$item"
  done

Save this in a script myscript.sh, chmod +x myscript.sh, then

./myscript.sh arg1 arg2 arg3 ...
Doing something with 'arg1'.
Doing something with 'arg2'.
Doing something with 'arg3'.
Doing something with '...'.

Same in a function:

myfunc() { for item;do cat <<<"Working about '$item'."; done ; }

Then

myfunc item1 tiem2 time3
Working about 'item1'.
Working about 'tiem2'.
Working about 'time3'.


问:
Converting Curl Sheel code to PHP
I want to convert Curl Shell code to PHP code, but i am getting a error that illegal charaters found in URL

```<code><?php
    $url = "https://www.unocoin.com/api/v1/general/prices";
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_URL, "Content-Type:application/json
    -H");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST
    -H");

    $result = curl_exec($ch);
    if (curl_errno($ch)) {
        echo 'Error:' . curl_error($ch);
    }
    curl_close ($ch);
?>
</code>```

I want the json format to be displayed on the screen

The Output of above code

答:
You are passing headers to CURLOPT_URL, headers should be set on CURLOPT_HTTPHEADER

Try this

```<code><?php

    $url = "https://www.unocoin.com/api/v1/general/prices";
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");

    $result = curl_exec($ch);
    if (curl_errno($ch)) {
        echo 'Error:' . curl_error($ch);
    } else {
        echo $result;
    }

    curl_close ($ch);
?>
</code>```

Title: Converting Curl Sheel code to PHP

Body:
I want to convert Curl Shell code to PHP code, but i am getting a error that illegal charaters found in URL

<?php
    $url = "https://www.unocoin.com/api/v1/general/prices";
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_URL, "Content-Type:application/json
    -H");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST
    -H");

    $result = curl_exec($ch);
    if (curl_errno($ch)) {
        echo 'Error:' . curl_error($ch);
    }
    curl_close ($ch);
?>

I want the json format to be displayed on the screen

The Output of above code

Body:
You are passing headers to CURLOPT_URL, headers should be set on CURLOPT_HTTPHEADER

Try this

<?php

    $url = "https://www.unocoin.com/api/v1/general/prices";
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");

    $result = curl_exec($ch);
    if (curl_errno($ch)) {
        echo 'Error:' . curl_error($ch);
    } else {
        echo $result;
    }

    curl_close ($ch);
?>


问:
Perl Debugger: DBD::mysql::db do failed: MySQL server has gone away at
I use MySQL with the DBI Module for my perl programming database connections.
I got the error message as below when using mysql :

```<code>Issuing rollback() due to DESTROY without explicit disconnect() of
DBD::mysql::db handle db=db;ip=X.X.X.X; at /code/save2db.plx line 104.
DBD::mysql::db DESTROY failed: MySQL server has gone away at
/code/save2db.plx line 104.
    (in cleanup) DBD::mysql::db DESTROY failed: MySQL server has gone away
at /code/save2db.plx line 104.
</code>```

the line 104 in my code is

```<code>103    $dbh->disconnect;
104    exit;
</code>```

Any idea why this happens?
I'd appreciate any feedback.

答:
The transaction behaviour of the disconnect method is, sadly,
  undefined. Some database systems (such as Oracle and Ingres) will
  automatically commit any outstanding changes, but others (such as
  Informix) will rollback any outstanding changes. Applications not
  using AutoCommit should explicitly call commit or rollback before
  calling disconnect.

See https://metacpan.org/pod/DBI#disconnect

Body:
I use MySQL with the DBI Module for my perl programming database connections.
I got the error message as below when using mysql :

Issuing rollback() due to DESTROY without explicit disconnect() of
DBD::mysql::db handle db=db;ip=X.X.X.X; at /code/save2db.plx line 104.
DBD::mysql::db DESTROY failed: MySQL server has gone away at
/code/save2db.plx line 104.
    (in cleanup) DBD::mysql::db DESTROY failed: MySQL server has gone away
at /code/save2db.plx line 104.

the line 104 in my code is

103    $dbh->disconnect;
104    exit;

Any idea why this happens?
I'd appreciate any feedback.


问:
foreach not recognized in C++
In my the cs106b book we use the expression "foreach" to go through a list of words in a Map. I implemented the code and banged my head against the wall facing mysterious errors. Here's the code:

```<code>   void DisplayWordCounts(Map<int> & wordsCount) {
     foreach (string word in wordsCount) {
        cout << left << setw(15) << word << right << setw(5)
        << wordsCount[word] << endl;
     }
}
</code>```

on the line starting with "foreach" I get the following errors:
lesson4-macbeth/life.cpp:58: error: expected primary-expression before 'word'
lesson4-macbeth/life.cpp:58: error: 'foreach' was not declared in this scope
lesson4-macbeth/life.cpp:58: error: expected `;' before '{' token

I guess foreach is not recognized. In that case, how can I go through a list of items from the Map class?

答:
Because the function name is for_each
P.S. I thought it was a c++ question, as the tag suggested, but the syntax all wrong for C++.

ContentLicense: CC BY-SA 2.5

Title: foreach not recognized in C++

Body:
In my the cs106b book we use the expression "foreach" to go through a list of words in a Map. I implemented the code and banged my head against the wall facing mysterious errors. Here's the code:

   void DisplayWordCounts(Map<int> & wordsCount) {
     foreach (string word in wordsCount) {
        cout << left << setw(15) << word << right << setw(5)
        << wordsCount[word] << endl;
     }
}

on the line starting with "foreach" I get the following errors:
lesson4-macbeth/life.cpp:58: error: expected primary-expression before 'word'
lesson4-macbeth/life.cpp:58: error: 'foreach' was not declared in this scope
lesson4-macbeth/life.cpp:58: error: expected `;' before '{' token

I guess foreach is not recognized. In that case, how can I go through a list of items from the Map class?


问:
How to edit specific fields of object in the array at the same time in setState
How do we create specific fields of object in the array?

Here is my state data that I want to partially update.

```<code>state.items = [
     {id:0, left: 100, right: 100, classified: true},
     {id:1, left: 200, right: 300, classified: false},
]
</code>```

And this is expected result after setState.

```<code>// Edit left, right, classified with given values,
// where the object's id is equal to 1.
state.items = [
     {id:0, left: 100, right: 100, classified: true},
     {id:1, left: 300, right: 200, classified: true},
]
</code>```

Here is code inside of function (Problem)

```<code>//console.log(id) <- prints 1. We are modifying the second object in the array with id 1.

// iterate items array
let { items } = this.state;
for (var index in items) {
  if(items[index].id === id) {
     // copy the whole object matching id is 1.
     var deep = _.cloneDeep(tag);

     //Assign new values (newLeft: 300, newRight:200, newCalssified: true)
     deep.left = newLeft
     deep.right = newRight
     deep.classified = newClassified

    this.setState({
      // HERE IS THE QUESTION
      taggedClothes // how do we modify the object with id 1??
    })
  }
}
</code>```

THANKS!!

答:
You need to modify the entire items array and then do a setState to update that entire items array.

```<code>const items = _.cloneDeep(this.state.items);

// Find index to modify
const index = items.findIndex(i => i.id === id);
items[index].left = newLeft;
items[index].right = newRight;
items[index].classified = newClassified;

this.setState({items});
</code>```

EDIT: as mentioned below, it is not always a good idea to mutate the state. I have added a _.cloneDeep at the beginning but have a look at this post for more info and other options: React: How do I update state.item[1] on setState? (with JSFiddle)

Body:
How do we create specific fields of object in the array?

Here is my state data that I want to partially update.

state.items = [
     {id:0, left: 100, right: 100, classified: true},
     {id:1, left: 200, right: 300, classified: false},
]

And this is expected result after setState.

// Edit left, right, classified with given values,
// where the object's id is equal to 1.
state.items = [
     {id:0, left: 100, right: 100, classified: true},
     {id:1, left: 300, right: 200, classified: true},
]

Here is code inside of function (Problem)

//console.log(id) <- prints 1. We are modifying the second object in the array with id 1.

// iterate items array
let { items } = this.state;
for (var index in items) {
  if(items[index].id === id) {
     // copy the whole object matching id is 1.
     var deep = _.cloneDeep(tag);

     //Assign new values (newLeft: 300, newRight:200, newCalssified: true)
     deep.left = newLeft
     deep.right = newRight
     deep.classified = newClassified

    this.setState({
      // HERE IS THE QUESTION
      taggedClothes // how do we modify the object with id 1??
    })
  }
}

THANKS!!

Body:
You need to modify the entire items array and then do a setState to update that entire items array.

const items = _.cloneDeep(this.state.items);

// Find index to modify
const index = items.findIndex(i => i.id === id);
items[index].left = newLeft;
items[index].right = newRight;
items[index].classified = newClassified;

this.setState({items});

EDIT: as mentioned below, it is not always a good idea to mutate the state. I have added a _.cloneDeep at the beginning but have a look at this post for more info and other options: React: How do I update state.item[1] on setState? (with JSFiddle)


问:
R Shiny actionButton to trim data limits
I am writing a R Shiny script to remove bad data points by clicking on the graph.  The flow goes like this:

Objective #1: The user clicks actionButton "Delete below", then clicks a point on the graph.  This point is the ymin, and R removes any y values less than that.  "Remove" = declares to be NA.

Objective #2: Conversely, user clicks actionButton "Delete above", then clicks a point on the graph.  This point is the ymax, and R removes any y values greater than that.

Here is a simplified version of the code:

```<code>library(shiny)
x = seq(0,10,length=50)
y = sin(x)
picked.style = "color: white; background-color: black"

ui = fluidPage(
  plotOutput("y.trimmed", click = "plot_click"),
  actionButton(inputId="b.above.pushed", label="Delete Above"),
  actionButton(inputId="b.below.pushed", label="Delete Below")
)

server = function(input, output) {
  v <- reactiveValues(
    ymin = min( y, na.rm=T),
    ymax = max(y, na.rm=T),
    pick.bottun = "none"
  )

  ############ push a button
  # pick above
  observeEvent(input$b.above.pushed, {
    v$pick.bottun <- "above"
    observeEvent(input$plot_click,
    {v$ymax = input$plot_click$y}, ignoreInit = TRUE)
  })
  # pick below
  observeEvent(input$b.below.pushed, {
    v$pick.bottun <- "below"
    observeEvent(input$plot_click,
    { v$ymin <- input$plot_click$y}, ignoreInit = TRUE)
  })

  ############# update and replot data
  output$y.trimmed <- renderPlot({
    # clean data
    print(paste("ymin=",round(v$ymin), "ymax=",round(v$ymax)) )
    cc = y <= v$ymin & is.na(y)==F; y[cc] = NA
    cc = y >= v$ymax & is.na(y)==F; y[cc] = NA
    plot(x, y)
  })
}

shinyApp(ui, server)
</code>```

Thus far it works fine for Objective #1 if that's all you run (even if you run it multiple times).  Likewise it works fine for Objective #2.

The problem occurs if you want to declare a ymin and then declare a ymax.  It will declare a min just fine (hypothetically let's say ymin=0.1), but then why you go to declare a ymax (hypothetically ymax=0.5), it sets BOTH ymin and ymax equal to 0.5.  This then deletes all the data, causing the code to crash.  The same thing happens if you declare ymax first and then try to set ymin.

Thank you in advance for your help.

答:
you don't want to put observeEvent in another. You are better off always placing them clean in the server function and the let them react to according to the what values have been previusly chosen. Like this.

```<code>library(shiny)
x = seq(0,10,length=50)
y = sin(x)
picked.style = "color: white; background-color: black"

ui = fluidPage(
  plotOutput("y.trimmed", click = "plot_click"),
  actionButton(inputId="b.above.pushed", label="Delete Above"),
  actionButton(inputId="b.below.pushed", label="Delete Below")
)

server = function(input, output) {
  v <- reactiveValues(
    ymin = min( y, na.rm=T),
    ymax = max(y, na.rm=T),
    pick.bottun = "none"
  )

  ############ push a button
  # pick above
  observeEvent(input$b.above.pushed, {
    v$pick.bottun <- "above"
  })

  observeEvent(input$plot_click,
               {
                 if(v$pick.bottun == "above"){
                    v$ymax = input$plot_click$y
                 } else if(v$pick.bottun == "below"){
                   v$ymin = input$plot_click$y
                 }

               }, ignoreInit = TRUE)
  # pick below
  observeEvent(input$b.below.pushed, {
    v$pick.bottun <- "below"
  })

  ############# update and replot data
  output$y.trimmed <- renderPlot({
    # clean data
    print(paste("ymin=",round(v$ymin), "ymax=",round(v$ymax)) )
    cc = y <= v$ymin & is.na(y)==F; y[cc] = NA
    cc = y >= v$ymax & is.na(y)==F; y[cc] = NA
    plot(x, y)
  })
}

shinyApp(ui, server)
</code>```

Hope this helps!

Body:
I am writing a R Shiny script to remove bad data points by clicking on the graph.  The flow goes like this:

Objective #1: The user clicks actionButton "Delete below", then clicks a point on the graph.  This point is the ymin, and R removes any y values less than that.  "Remove" = declares to be NA.

Objective #2: Conversely, user clicks actionButton "Delete above", then clicks a point on the graph.  This point is the ymax, and R removes any y values greater than that.

Here is a simplified version of the code:

library(shiny)
x = seq(0,10,length=50)
y = sin(x)
picked.style = "color: white; background-color: black"

ui = fluidPage(
  plotOutput("y.trimmed", click = "plot_click"),
  actionButton(inputId="b.above.pushed", label="Delete Above"),
  actionButton(inputId="b.below.pushed", label="Delete Below")
)

server = function(input, output) {
  v <- reactiveValues(
    ymin = min( y, na.rm=T),
    ymax = max(y, na.rm=T),
    pick.bottun = "none"
  )

  ############ push a button
  # pick above
  observeEvent(input$b.above.pushed, {
    v$pick.bottun <- "above"
    observeEvent(input$plot_click,
    {v$ymax = input$plot_click$y}, ignoreInit = TRUE)
  })
  # pick below
  observeEvent(input$b.below.pushed, {
    v$pick.bottun <- "below"
    observeEvent(input$plot_click,
    { v$ymin <- input$plot_click$y}, ignoreInit = TRUE)
  })

  ############# update and replot data
  output$y.trimmed <- renderPlot({
    # clean data
    print(paste("ymin=",round(v$ymin), "ymax=",round(v$ymax)) )
    cc = y <= v$ymin & is.na(y)==F; y[cc] = NA
    cc = y >= v$ymax & is.na(y)==F; y[cc] = NA
    plot(x, y)
  })
}

shinyApp(ui, server)

Thus far it works fine for Objective #1 if that's all you run (even if you run it multiple times).  Likewise it works fine for Objective #2.

The problem occurs if you want to declare a ymin and then declare a ymax.  It will declare a min just fine (hypothetically let's say ymin=0.1), but then why you go to declare a ymax (hypothetically ymax=0.5), it sets BOTH ymin and ymax equal to 0.5.  This then deletes all the data, causing the code to crash.  The same thing happens if you declare ymax first and then try to set ymin.

Thank you in advance for your help.

Body:
you don't want to put observeEvent in another. You are better off always placing them clean in the server function and the let them react to according to the what values have been previusly chosen. Like this.

library(shiny)
x = seq(0,10,length=50)
y = sin(x)
picked.style = "color: white; background-color: black"

ui = fluidPage(
  plotOutput("y.trimmed", click = "plot_click"),
  actionButton(inputId="b.above.pushed", label="Delete Above"),
  actionButton(inputId="b.below.pushed", label="Delete Below")
)

server = function(input, output) {
  v <- reactiveValues(
    ymin = min( y, na.rm=T),
    ymax = max(y, na.rm=T),
    pick.bottun = "none"
  )

  ############ push a button
  # pick above
  observeEvent(input$b.above.pushed, {
    v$pick.bottun <- "above"
  })

  observeEvent(input$plot_click,
               {
                 if(v$pick.bottun == "above"){
                    v$ymax = input$plot_click$y
                 } else if(v$pick.bottun == "below"){
                   v$ymin = input$plot_click$y
                 }

               }, ignoreInit = TRUE)
  # pick below
  observeEvent(input$b.below.pushed, {
    v$pick.bottun <- "below"
  })

  ############# update and replot data
  output$y.trimmed <- renderPlot({
    # clean data
    print(paste("ymin=",round(v$ymin), "ymax=",round(v$ymax)) )
    cc = y <= v$ymin & is.na(y)==F; y[cc] = NA
    cc = y >= v$ymax & is.na(y)==F; y[cc] = NA
    plot(x, y)
  })
}

shinyApp(ui, server)

Hope this helps!


问:
Usage of Parameters.Add not working
I have a C# program developed in VS 2010 that generates a report by reading parameters supplied from a stored procedure in SQL server. I have two ways of calling the parameters:

```<code>command.Parameters.AddWithValue("@SponsorID", strSponsorID);
</code>```

This works perfectly fine with no issue. However when I tried to use a different method like this:

```<code>paramFields.Add("SponsorID", (strSponsorID == "" ? "ALL" : strSponsorID));
</code>```

It throws an error claiming:

the parameters could not be supplied.

Note: Paramfields is a variable that I declared.

```<code>SortedList paramFields = new SortedList();
</code>```

May I know what is the possible issue?

答:
Why not try something like this with your AddWithValue?

```<code>command.Parameters.AddWithValue("@SponsorID", string.IsNullOrWhiteSpace(strSponsorID) ?
                                              "ALL" : strSponsorID);
</code>```

Or even simpler if just NULL checking enough:

```<code>command.Parameters.AddWithValue("@SponsorID", strSponsorID ?? "ALL");
</code>```

Although specify the type directly and use the Value property is more better than AddWithValue:

```<code>command.Parameters.Add("@SponsorID", SqlDbType.VarChar).Value
            = string.IsNullOrWhiteSpace(strSponsorID) ?
            "ALL" : strSponsorID;
</code>```

However you need to add using System.Data; to your using directives first.

Can we stop using AddWithValue() already?

Title: Usage of Parameters.Add not working

Body:
I have a C# program developed in VS 2010 that generates a report by reading parameters supplied from a stored procedure in SQL server. I have two ways of calling the parameters:

command.Parameters.AddWithValue("@SponsorID", strSponsorID);

This works perfectly fine with no issue. However when I tried to use a different method like this:

paramFields.Add("SponsorID", (strSponsorID == "" ? "ALL" : strSponsorID));

It throws an error claiming:

the parameters could not be supplied.

Note: Paramfields is a variable that I declared.

SortedList paramFields = new SortedList();

May I know what is the possible issue?

Body:
Why not try something like this with your AddWithValue?

command.Parameters.AddWithValue("@SponsorID", string.IsNullOrWhiteSpace(strSponsorID) ?
                                              "ALL" : strSponsorID);

Or even simpler if just NULL checking enough:

command.Parameters.AddWithValue("@SponsorID", strSponsorID ?? "ALL");

Although specify the type directly and use the Value property is more better than AddWithValue:

command.Parameters.Add("@SponsorID", SqlDbType.VarChar).Value
            = string.IsNullOrWhiteSpace(strSponsorID) ?
            "ALL" : strSponsorID;

However you need to add using System.Data; to your using directives first.

Can we stop using AddWithValue() already?


问:
Split one column to two columns depending one the content in pandas dataframe
I have a pandas DataFrame like this:

df = pd.DataFrame(['A',1,2,3,'B',4,5,'C',6,7,8,9])

```<code>    0
0   A
1   1
2   2
3   3
4   B
5   4
6   5
7   C
8   6
9   7
10  8
11  9
</code>```

It's mix of strings and numbers. I want to split this DF into tow columns like this:

```<code>   name value
0   A   1
1   A   2
2   A   3
3   B   4
4   B   5
5   C   6
6   C   7
7   C   8
8   C   9
</code>```

what's an efficient way to do this?

答:
You can use:

```<code>df = pd.DataFrame({0 :['A',1,2,3,'B',4,5,'C',6,7,8,9]})
#check strings
mask = df[0].astype(str).str.isalpha()
#check if mixed values - numeric with strings
#mask = df[0].apply(lambda x: isinstance(x, str))
#create column to first position, create NaNs filled by forward filling
df.insert(0, 'name', df[0].where(mask).ffill())
#remove rows with same values - with names, rename column
df = df[df['name'] != df[0]].rename(columns={0:'value'}).reset_index(drop=True)
print (df)
  name value
0    A     1
1    A     2
2    A     3
3    B     4
4    B     5
5    C     6
6    C     7
7    C     8
8    C     9
</code>```

Or:

```<code>out = []
acc = None
for x in df[0]:
    #check if strings
    if isinstance(x, str):
        #assign to variable for tuples
        acc = x
    else:
        #append tuple to out
        out.append((acc, x))
print (out)

df = pd.DataFrame(out, columns=['name','value'])
print (df)
  name  value
0    A      1
1    A      2
2    A      3
3    B      4
4    B      5
5    C      6
6    C      7
7    C      8
8    C      9
</code>```

Body:
I have a pandas DataFrame like this:

df = pd.DataFrame(['A',1,2,3,'B',4,5,'C',6,7,8,9])

    0
0   A
1   1
2   2
3   3
4   B
5   4
6   5
7   C
8   6
9   7
10  8
11  9

It's mix of strings and numbers. I want to split this DF into tow columns like this:

   name value
0   A   1
1   A   2
2   A   3
3   B   4
4   B   5
5   C   6
6   C   7
7   C   8
8   C   9

what's an efficient way to do this?

Body:
You can use:

df = pd.DataFrame({0 :['A',1,2,3,'B',4,5,'C',6,7,8,9]})
#check strings
mask = df[0].astype(str).str.isalpha()
#check if mixed values - numeric with strings
#mask = df[0].apply(lambda x: isinstance(x, str))
#create column to first position, create NaNs filled by forward filling
df.insert(0, 'name', df[0].where(mask).ffill())
#remove rows with same values - with names, rename column
df = df[df['name'] != df[0]].rename(columns={0:'value'}).reset_index(drop=True)
print (df)
  name value
0    A     1
1    A     2
2    A     3
3    B     4
4    B     5
5    C     6
6    C     7
7    C     8
8    C     9

Or:

out = []
acc = None
for x in df[0]:
    #check if strings
    if isinstance(x, str):
        #assign to variable for tuples
        acc = x
    else:
        #append tuple to out
        out.append((acc, x))
print (out)

df = pd.DataFrame(out, columns=['name','value'])
print (df)
  name  value
0    A      1
1    A      2
2    A      3
3    B      4
4    B      5
5    C      6
6    C      7
7    C      8
8    C      9


问:
Can I customize Jackson error messages?
I've got a JacksonMappingException that I'm using to produce errors for the user:

```<code>public Map<String, List<Map<String, String>>> getErrors(JsonMappingException e) {

    Map<String, List<Map<String, String>>> errors = new HashMap<>();

    List<Map<String, String>> badFields = new ArrayList<>();

    for (Reference ref: e.getPath()) {
        Map<String, String> badField = new HashMap<>();
        badField.put("field", ref.getFieldName());
        badField.put("description", e.getOriginalMessage());
        badFields.add(badField);
    }

    errors.put("errors", badFields);

    return errors;
}
</code>```

Which is great except for some classes of error, certain technical details leak out to the user, such as class structure, etc, that is totally unseemly:

```<code>{
  "errors" : [ {
    "field" : "id",
    "description" : "Unrecognized field \"id\" (class motif.web.resource.UserResource$PutUser), not marked as ignorable"
  } ]
}
</code>```

How can I can have description be more like Unrecognized field \"id\" without all the technical mumbo jumbo?

答: JsonMappingException has several subsclasses. You can do instanceof checks for the class of the exception, and then build your own description.</p>

Title: Can I customize Jackson error messages?

Body:
I've got a JacksonMappingException that I'm using to produce errors for the user:

public Map<String, List<Map<String, String>>> getErrors(JsonMappingException e) {

    Map<String, List<Map<String, String>>> errors = new HashMap<>();

    List<Map<String, String>> badFields = new ArrayList<>();

    for (Reference ref: e.getPath()) {
        Map<String, String> badField = new HashMap<>();
        badField.put("field", ref.getFieldName());
        badField.put("description", e.getOriginalMessage());
        badFields.add(badField);
    }

    errors.put("errors", badFields);

    return errors;
}

Which is great except for some classes of error, certain technical details leak out to the user, such as class structure, etc, that is totally unseemly:

{
  "errors" : [ {
    "field" : "id",
    "description" : "Unrecognized field \"id\" (class motif.web.resource.UserResource$PutUser), not marked as ignorable"
  } ]
}

How can I can have description be more like Unrecognized field \"id\" without all the technical mumbo jumbo?


问:
how to know if a $string ends with ','?

Possible Duplicate:

Find last character in a string in PHP

How can I know if the last char of a $string is ',' ?

答:
See the endsWith function here:

startsWith() and endsWith() functions in PHP

ContentLicense: CC BY-SA 4.0

Title: how to know if a $string ends with ','?


答:
```<code>$dateStart=strtotime(date("Y-m-d 17:30:00"));
$dateEnd=strtotime(date("Y-m-d 20:30:00"));
</code>```

This is how you can convert your date into unix timestamp in php.

Then in your query:

```<code>SELECT * FROM my_table WHERE time BETWEEN '$dateStart' AND '$dateEnd'
</code>```

If you don't want to execute your script manually every day you can set up a cronjob to do it for you.

Title: query for time in mysql between hours

Body:
how to get a list of rows that is between 17:30 till tomarrow 8:30.

--------------------------------------
| id | user_id | action |     time    |
--------------------------------------
| 1  |   25    | enter  | 1512459905
| 2  |   19    |  exit  | 1512125105
| 3  |   31    | enter  | 1514581905  |
--------------------------------------

mysql table have a time column with unix timestamp and i want get a list every day that between 17:30 till 8:30

Body:
$dateStart=strtotime(date("Y-m-d 17:30:00"));
$dateEnd=strtotime(date("Y-m-d 20:30:00"));

This is how you can convert your date into unix timestamp in php.

Then in your query:

SELECT * FROM my_table WHERE time BETWEEN '$dateStart' AND '$dateEnd'

If you don't want to execute your script manually every day you can set up a cronjob to do it for you.


问:
Stop body from getting focus
If I put the focus on the url edit in chrome and then press tab, then run document.activeElement in my console I get:

```<code><body tabindex="-1" aurelia-app="main">...</body>
</code>```

Is there a way I can stop the body from getting the tab focus?

答:
As this answer:

Between leaving the old element and entering the new element the active element is indeed the document/body itself.

I found if you don't want the body element to get focus do this

```<code><body onfocus="blur();">
</code>```

Title: Stop body from getting focus

Body:
If I put the focus on the url edit in chrome and then press tab, then run document.activeElement in my console I get:

...

Is there a way I can stop the body from getting the tab focus?

Body:
As this answer:

Between leaving the old element and entering the new element the active element is indeed the document/body itself.

I found if you don't want the body element to get focus do this

<body onfocus="blur();">


问:
Python, program that multiplies number by 2 til it's greater than 1000, having issue with syntax
When I put oursum outside of the loop it infinitely multiplies it by 2

```<code>usernum=float(input('Enter a number: '))
if usernum<=0 or usernum>1000:
    print('Your number is '+str(usernum))
else:
     oursum=usernum*2
     while oursum<=1000:
          print('Multiplied by 2 equals '+str(oursum))
</code>```

When inside, it's not defined.

```<code>usernum=float(input('Enter a number: '))
if usernum<=0 or usernum>1000:
   print('Your number is '+str(usernum))
else:

     while oursum<=1000:
          oursum=usernum*2
          print('Multiplied by 2 equals '+str(oursum))
</code>```

I understand the problems I'm making but I don't know how to rectify this without making it unnecessarily long and complicated. Thanks in advance.

答:
The condition in the if and while being pretty similar, you can combine both in a single test. It can also be a good idea to define a function in order to be able to reuse and test it more easily:

```<code>def transform(number):
    while 0 < number <= 1000:
        number *= 2
    return number

if __name__ == '__main__':
    user_num = float(input('Enter a number: '))
    print('After transformation, your number is', transform(user_num))
</code>```

Body:
When I put oursum outside of the loop it infinitely multiplies it by 2

usernum=float(input('Enter a number: '))
if usernum<=0 or usernum>1000:
    print('Your number is '+str(usernum))
else:
     oursum=usernum*2
     while oursum<=1000:
          print('Multiplied by 2 equals '+str(oursum))

When inside, it's not defined.

usernum=float(input('Enter a number: '))
if usernum<=0 or usernum>1000:
   print('Your number is '+str(usernum))
else:

     while oursum<=1000:
          oursum=usernum*2
          print('Multiplied by 2 equals '+str(oursum))

I understand the problems I'm making but I don't know how to rectify this without making it unnecessarily long and complicated. Thanks in advance.

Body:
The condition in the if and while being pretty similar, you can combine both in a single test. It can also be a good idea to define a function in order to be able to reuse and test it more easily:

def transform(number):
    while 0 < number <= 1000:
        number *= 2
    return number

if __name__ == '__main__':
    user_num = float(input('Enter a number: '))
    print('After transformation, your number is', transform(user_num))


问:
in Emacs, how to show current file in Finder?
In Emacs on Mac OSX, is there a function to reveal the current file in the Finder?</p>

答: On dired mode, instead of 'e' or 'f' to open the file within an emacs buffer, type '!' and then "open -R". A new Finder window is opened pointing to your file.</p>


问:
How to change Logo Company size
I want to change Logo company size in Sale Order and Custommer Invoice, I code with this but haven't changed that logo size.

here's my code:

```<code><?xml version="1.0" encoding="utf-8"?>
<odoo>
<template id="co_report_saleorder_document">
    <t t-call="report.external_layout">
        <t t-set="docs" t-value="docs.with_context({'lang':docs.partner_id.lang})" />

        <!-- Multicompany -->
        <t t-if="not o and doc">
            <t t-set="o" t-value="doc"/>
        </t>
        <t t-if="o and 'company_id' in o">
            <t t-set="company" t-value="o.company_id"></t>
        </t>
        <t t-if="not o or not 'company_id' in o">
            <t t-set="company" t-value="res_company"></t>
        </t>

        <div class="header">
            <div class="row">
                <div class="col-xs-3">
                    <img t-if="company.logo" t-att-src="'data:image/png;base64,%s' % company.logo" style="max-width: 200px; max-height: 150px;"/>
                </div>
                <div class="col-xs-9 text-right" style="margin-top:20px;" t-field="company.rml_header1"/>
            </div>
            <div class="row zero_min_height">
                <div class="col-xs-12">
                    <div style="border-bottom: 1px solid black;"></div>
                </div>
            </div>
        </div>

</template>

<template id="report_saleorder">
    <t t-call="report.html_container">
        <t t-foreach="docs" t-as="docs">
            <t t-call="sale.fal_report_saleorder_document" t-lang="docs.partner_id.lang"/>
        </t>
    </t>
</template>

<report
    string="Cetak Sales"
    id="co_view_sale"
    model="sale.order"
    report_type="qweb-pdf"
    name="co_sale_report.co_report_saleorder_document"
    file="co_sale_report.co_report_saleorder_document"
/>

</odoo>
</code>```

I have add code in style="max-width: 200px; max-height: 150px;" but haven't change. somebody can help me?

答:
You can not directly change into external layout. First you need to change header layout from the report module by inherit a template.

```<code><template id="external_layout_header_inherited" inherit_id="report.external_layout_header" primary="True">
<xpath expr="//img" position="replace">
    <img t-if="company.logo" t-att-src="'data:image/png;base64,%s' % company.logo" height='150' width='200' />
</xpath></template>
</code>```

hope this is help....

Title: How to change Logo Company size

Body:
I want to change Logo company size in Sale Order and Custommer Invoice, I code with this but haven't changed that logo size.

here's my code:

<?xml version="1.0" encoding="utf-8"?>
<odoo>
<template id="co_report_saleorder_document">
    <t t-call="report.external_layout">
        <t t-set="docs" t-value="docs.with_context({'lang':docs.partner_id.lang})" />

        <t t-if="not o and doc">
            <t t-set="o" t-value="doc"/>
        </t>
        <t t-if="o and 'company_id' in o">
            <t t-set="company" t-value="o.company_id"></t>
        </t>
        <t t-if="not o or not 'company_id' in o">
            <t t-set="company" t-value="res_company"></t>
        </t>

</template>

<template id="report_saleorder">
    <t t-call="report.html_container">
        <t t-foreach="docs" t-as="docs">
            <t t-call="sale.fal_report_saleorder_document" t-lang="docs.partner_id.lang"/>
        </t>
    </t>
</template>

<report
    string="Cetak Sales"
    id="co_view_sale"
    model="sale.order"
    report_type="qweb-pdf"
    name="co_sale_report.co_report_saleorder_document"
    file="co_sale_report.co_report_saleorder_document"
/>

</odoo>

I have add code in style="max-width: 200px; max-height: 150px;" but haven't change. somebody can help me?

Body:
You can not directly change into external layout. First you need to change header layout from the report module by inherit a template.

<template id="external_layout_header_inherited" inherit_id="report.external_layout_header" primary="True">
<xpath expr="//img" position="replace">
    <img t-if="company.logo" t-att-src="'data:image/png;base64,%s' % company.logo" height='150' width='200' />
</xpath></template>

hope this is help....


问:
Thymeleaf form send object with null fields to controller in weblogic server
I'm using thymeleaf for my web application. There is a problem about save and update functions. When I want to save a campaign from ui, the campaign object fields come null to rest controller class. This problem just occure in weblogic server(12.1.3). When I try it in tomcat server, do not occure any error.

my edit and create page as follow. There are a few fields for campaign, but I wrote some of them in here. Bytheway, I am sure that all fields ready in the html page. Some of them hidden, some of them visible.

```<code><div class="row">
    <form name="Form" class="col s8 offset-s2" id="upload-file-form"
          enctype="multipart/form-data" th:object="${campaign}"
          th:action="@{/admin/getCampaign}" onsubmit="return validateForm()"
          method="post">

        <div class="row">
            <input type="hidden" th:field="*{id}"/>
            <input type="hidden" th:field="*{version}"/>
        </div>
        <div class="row">
            <div class="input-field">
                <input id="brandname" type="text" class="validate" th:field="*{brandname}">
                <label for="brandname">Brand Name</label>
            </div>
        </div>
    </form>
</div>

@RequestMapping(value = "admin/getCampaign", method = RequestMethod.POST)
public String uploadingPost(@RequestParam("uploadingFiles") MultipartFile[] uploadingFiles,
                            @RequestParam("uploadingFiles1") MultipartFile[] uploadingFiles1,
                            @RequestParam("uploadingFiles2") MultipartFile[] uploadingFiles2,
                            @RequestParam("uploadingFiles3") MultipartFile[] uploadingFiles3,
                            Campaign campaign) throws IOException {

/** this is my controller method for save or update.
*/
}

in weblogic server campaign parameter fields come null (as a new object), but in tomcat server, everything is normal.
</code>```

UPDATE:

I changed my ui fields to value like this post. But the problem continue.

```<code><input type="hidden" th:value="*{id}"/>
</code>```

答:
Your form enctype is "multipart/form-data".
So you must add spring.http.encoding.enabled=false to application.properties.

Body:
I'm using thymeleaf for my web application. There is a problem about save and update functions. When I want to save a campaign from ui, the campaign object fields come null to rest controller class. This problem just occure in weblogic server(12.1.3). When I try it in tomcat server, do not occure any error.

my edit and create page as follow. There are a few fields for campaign, but I wrote some of them in here. Bytheway, I am sure that all fields ready in the html page. Some of them hidden, some of them visible.

    <form name="Form" class="col s8 offset-s2" id="upload-file-form"
          enctype="multipart/form-data" th:object="${campaign}"
          th:action="@{/admin/getCampaign}" onsubmit="return validateForm()"
          method="post">

            <input type="hidden" th:field="*{id}"/>
            <input type="hidden" th:field="*{version}"/>

                <input id="brandname" type="text" class="validate" th:field="*{brandname}">
                Brand Name

    </form>

@RequestMapping(value = "admin/getCampaign", method = RequestMethod.POST)
public String uploadingPost(@RequestParam("uploadingFiles") MultipartFile[] uploadingFiles,
                            @RequestParam("uploadingFiles1") MultipartFile[] uploadingFiles1,
                            @RequestParam("uploadingFiles2") MultipartFile[] uploadingFiles2,
                            @RequestParam("uploadingFiles3") MultipartFile[] uploadingFiles3,
                            Campaign campaign) throws IOException {

/** this is my controller method for save or update.
*/
}

in weblogic server campaign parameter fields come null (as a new object), but in tomcat server, everything is normal.

UPDATE:

I changed my ui fields to value like this post. But the problem continue.

<input type="hidden" th:value="*{id}"/>


问:
How to detect whether device support FaceID or not?
Its bit early to ask but I'm planning to add feature specially for FaceID, so before that I need to validate either device support FaceID or not?
Need suggestion and help.
Thanks in advance.</p>

答:
Objective-C version</p>

```<code>- (BOOL) isFaceIdSupported{
    if (@available(iOS 11.0, *)) {
        LAContext *context = [[LAContext alloc] init];
        if ([context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:nil]){
            return ( context.biometryType == LABiometryTypeFaceID);
        }
    }
    return NO;
}
</code>```

Body:
Objective-C version

- (BOOL) isFaceIdSupported{
    if (@available(iOS 11.0, *)) {
        LAContext *context = [[LAContext alloc] init];
        if ([context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:nil]){
            return ( context.biometryType == LABiometryTypeFaceID);
        }
    }
    return NO;
}


问:
create a tiff image
How to create a tiff image using HTML form data in java?
I have few text fields in my HTML page and I would like to generate a tiff file using that data

-PD

答: The Java(TM) Image I/O API will allow you to read and write TIFF files among other formats.</p>

Title: create a tiff image


问:
Removing the three dots from the end of the excerpt
So I am trying to remove the three dots from the end of my excerpt on my blog but without success. I have gone into the functions.php file and it seems to be blank:

```<code>add_filter('excerpt_more', 'new_excerpt_more');
function new_excerpt_more( $more ) {
return '[ ]';
</code>```

I have also had a look at another css file called blog-functions.php and can't seem to crack what is outputting the...

Thank you :-)

http://demo.boxofficeboxing.co.uk/news/

http://demo.boxofficeboxing.co.uk/?s=

答:
Hello you have to add one css for that in child theme style.css

you found css in modules.min.css file

```<code>.eltd-post-excerpt:after {
  position: relative;
  content: '...';
}
</code>```

so you have just override that css with this given css and dots are remove.

```<code>.eltd-post-excerpt:after {
    content: ' ';
}
</code>```

Hope this work as you want.

Thank You

Body:
So I am trying to remove the three dots from the end of my excerpt on my blog but without success. I have gone into the functions.php file and it seems to be blank:

add_filter('excerpt_more', 'new_excerpt_more');
function new_excerpt_more( $more ) {
return '[ ]';

I have also had a look at another css file called blog-functions.php and can't seem to crack what is outputting the...

Thank you :-)

http://demo.boxofficeboxing.co.uk/news/

http://demo.boxofficeboxing.co.uk/?s=

Body:
Hello you have to add one css for that in child theme style.css

you found css in modules.min.css file

.eltd-post-excerpt:after {
  position: relative;
  content: '...';
}

so you have just override that css with this given css and dots are remove.

.eltd-post-excerpt:after {
    content: ' ';
}

Hope this work as you want.

Thank You


问:
Creating a program that tests for palindrome without building the reversal (Java)
I am trying to create a Java program for my AP Computer Science class that asks the user for a string and tests whether or not the string is a palindrome or not. The teacher specifically told us to not do the project by building the reversal of the string and testing it to see if it matches. I know how to do it while building the reversal but I can't think of another way to do it. </p>

```<code>import java.util.*;

public class mondayassignment
{
    public static void main(String args[])
    {
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter a String: ");
        String s = scan.nextLine();

                while(s.indexOf(" ") >= 0)
                       {
                            s = s.substring(0, s.indexOf(" ")) +
s.substring(s.indexOf(" ") + 1);
                       }
                System.out.println("Spaces Removed:");
        System.out.println(s);
                String reverse="";
        for(int pos = 0; pos < s.length(); pos++)
                       {
                            reverse =  s.substring(pos, pos + 1) + reverse ;
                       }
                System.out.println("Reverse Of The String You Inputed Is:" );
                System.out.println(reverse);
                System.out.println("Testing For Palindrome:");

                if (reverse.equals(s))
                       {
                            System.out.println(s + " " + "is a palindrome" );
                       }
                else   {
                            System.out.println(s + " " + "is not a palindrome" );
                       }
    }
}
</code>```

<p>Can someone help me create a code that does it without building the reversal of the string? Many solutions I've found online uses boolean and char but the thing is, is that I haven't learn those yet. I've only learned double int and string. SO would there be a way without using boolean and char? I don't think my teacher wants us using boolean and char either because we have never discussed them. </p>

答:
```<code>package paintadvance;

import java.util.Scanner;

class  Palindrome_without_reverse{

public static void main(String[] ishan_vimukthi_is_my_name) {

    Scanner scan= new Scanner(System.in);
    String string="";

    /*while loop to keep running the programme unlit user need it to end*/
    while (true) {
        System.out.println("Enter string for palindrome check");
        string=scan.nextLine();

        /*this is for exiting the programme. If needed for user just type
         "exit".It's not casesensitive that means "EXIT" is also ok.*/

        if (string.equalsIgnoreCase("exit")) {System.out.println("Programme closed"); System.exit(0); }

       /*get the length of string to a int variable */
       int length=string.length();

        /*get mid point of string in eg:- "aasaa" midpoint is letter "s" that means 2 when count from 0 .
        We can get it from dividing string length from 2.Because we use int we will get 2 as the answer. */
        int midpoint=length/2;
        boolean ispalindrome=true;
        String x="";
        String y="";

        /*check length is odd or even eg:- "aasaa" is odd "aassaa" is even*/
        if (length%2==1) {

        /*if you want to see the method. uncomment this and understand it.
             System.out.println("odd string");
       System.out.println(string.substring(midpoint,string.length())+" X part");
        System.out.println(string.substring(0, midpoint+1)+" Y part");*/

       x =string.substring(midpoint,string.length());
       y=string.substring(0, midpoint+1);

        }else{
             /*if you want to see the method. uncomment this and understand it.
           System.out.println("even string");
       System.out.println(string.substring(midpoint,string.length())+" X part");
        System.out.println(string.substring(0, midpoint)+" Y part");*/

         x=string.substring(midpoint,string.length());
         y=string.substring(0, midpoint);
        }

        int ylength=y.length()-1;
        int ylength_end=y.length();

        aa: for (int i = 0; i < x.length(); i++) {

            /* by this code we compare each
            string part of both x and y strings
            in eg:- aasaa   x=saa y=aas

            we compair  0,1 of x and 2,3 of y
            and keep going.this is not a reversal but this is comparing x and y parts
            if its not equal we assign ispalindrome false if its equal it will be in true state
            */

            if (      !(x.substring(i, i+1).equals(  y.substring(ylength--, ylength_end--)))) {
               ispalindrome=false;
            }

        }

        /* after for loop  We check string is a palindrome or not */
        if (ispalindrome) {    System.out.println("This is a palindrome");}else{ System.out.println("Not a palindrome");}

        }
    }
 }
</code>```

Body:
I am trying to create a Java program for my AP Computer Science class that asks the user for a string and tests whether or not the string is a palindrome or not. The teacher specifically told us to not do the project by building the reversal of the string and testing it to see if it matches. I know how to do it while building the reversal but I can't think of another way to do it.

import java.util.*;

public class mondayassignment
{
    public static void main(String args[])
    {
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter a String: ");
        String s = scan.nextLine();

                while(s.indexOf(" ") >= 0)
                       {
                            s = s.substring(0, s.indexOf(" ")) +
s.substring(s.indexOf(" ") + 1);
                       }
                System.out.println("Spaces Removed:");
        System.out.println(s);
                String reverse="";
        for(int pos = 0; pos < s.length(); pos++)
                       {
                            reverse =  s.substring(pos, pos + 1) + reverse ;
                       }
                System.out.println("Reverse Of The String You Inputed Is:" );
                System.out.println(reverse);
                System.out.println("Testing For Palindrome:");

                if (reverse.equals(s))
                       {
                            System.out.println(s + " " + "is a palindrome" );
                       }
                else   {
                            System.out.println(s + " " + "is not a palindrome" );
                       }
    }
}

Can someone help me create a code that does it without building the reversal of the string? Many solutions I've found online uses boolean and char but the thing is, is that I haven't learn those yet. I've only learned double int and string. SO would there be a way without using boolean and char? I don't think my teacher wants us using boolean and char either because we have never discussed them.


问:
Combine multiple text rows with identical column
I need to combine rows with 1 column being the same and the rest is of type nvarchar.

TempTable

```<code>Id | Key          | Description1 | Description2
 1 | 60287F58-4631| Lorem Ipsum  | dolor sit amet
 2 | 60287F58-4631| consectetur  | adipiscing elit
 3 | 74553234-7543| Test test    | test test
</code>```

I need to get this result:

```<code>Key          | DescriptionCombined
60287F58-4631| Lorem Ipsum, dolor sit amet, consectetur, adipiscing elit
74553234-7543| Test test, test test
</code>```

I know that group by will not work because Description1 and Description2 are different between common rows. I started experimenting with for xml path(''), but this combines every row. I guess I need to first extract groups with the same key and then apply for xml path(''), but I cannot get this to work.

```<code>select ',' + t1.Description1, t1.Description2 from TempTable t1
for xml path('')
</code>```

答:
Just for fun - approach with recursive CTE:

```<code>;WITH cte AS (
    SELECT  TOP 1 WITH TIES id,
            [Key],
            CAST(CONCAT(Description1,', ',Description2)  as nvarchar(max))as DescriptionCombined,
            1 as lev
    FROM YourTable y
    ORDER BY ROW_NUMBER() OVER (PARTITION BY [Key] ORDER BY id ASC)
    UNION ALL
    SELECT  y.id,
            c.[Key],
            CAST(CONCAT(c.DescriptionCombined,', ',Description1,', ',Description2)  as nvarchar(max))as DescriptionCombined,
            lev+1
    FROM YourTable y
    INNER JOIN cte c
        ON y.[Key] = c.[key] AND y.[id] > c.[id]
)

SELECT TOP 1 WITH TIES  [Key],
                        DescriptionCombined
FROM cte
ORDER BY ROW_NUMBER() OVER (PARTITION BY [Key] ORDER BY lev DESC)
</code>```

Output:

```<code>Key             DescriptionCombined
60287F58-4631   Lorem Ipsum, dolor sit amet, consectetur, adipiscing elit
74553234-7543   Test test, test test
</code>```

Body:
I need to combine rows with 1 column being the same and the rest is of type nvarchar.

TempTable

Id | Key          | Description1 | Description2
 1 | 60287F58-4631| Lorem Ipsum  | dolor sit amet
 2 | 60287F58-4631| consectetur  | adipiscing elit
 3 | 74553234-7543| Test test    | test test

I need to get this result:

Key          | DescriptionCombined
60287F58-4631| Lorem Ipsum, dolor sit amet, consectetur, adipiscing elit
74553234-7543| Test test, test test

I know that group by will not work because Description1 and Description2 are different between common rows. I started experimenting with for xml path(''), but this combines every row. I guess I need to first extract groups with the same key and then apply for xml path(''), but I cannot get this to work.

select ',' + t1.Description1, t1.Description2 from TempTable t1
for xml path('')

Body:
Just for fun - approach with recursive CTE:

;WITH cte AS (
    SELECT  TOP 1 WITH TIES id,
            [Key],
            CAST(CONCAT(Description1,', ',Description2)  as nvarchar(max))as DescriptionCombined,
            1 as lev
    FROM YourTable y
    ORDER BY ROW_NUMBER() OVER (PARTITION BY [Key] ORDER BY id ASC)
    UNION ALL
    SELECT  y.id,
            c.[Key],
            CAST(CONCAT(c.DescriptionCombined,', ',Description1,', ',Description2)  as nvarchar(max))as DescriptionCombined,
            lev+1
    FROM YourTable y
    INNER JOIN cte c
        ON y.[Key] = c.[key] AND y.[id] > c.[id]
)

SELECT TOP 1 WITH TIES  [Key],
                        DescriptionCombined
FROM cte
ORDER BY ROW_NUMBER() OVER (PARTITION BY [Key] ORDER BY lev DESC)

Output:

Key             DescriptionCombined
60287F58-4631   Lorem Ipsum, dolor sit amet, consectetur, adipiscing elit
74553234-7543   Test test, test test


问:
Subsetting a Data Frame based on multiple wildcard criteria in R
i have a Data Frame called Test1 that contains 230k companies. what i need to do is to subset Tests1 into a new DF called FinalDS.

i have created a list called Customers that contains several name variations of the clients (about 100k) that i need put into my FinalDS DF.
What i am looking for is R to look at my Customers DF and look for the customer name in the Test1 DF but!.... what i need is R to scan the Customers DF and see if it can match any part of the customer name in the Customers DF to the Test1 DF

For example:

i have this customer on the Customers DF:
Centrica PLC

But on the Test1 DF i have Centrica so by difinition there will be no match. i know that i could just make all the customers match by deleting the PLC part from the Customers DF but i have a list of about 100k Customers.

this is the code that i have written:

```<code>Customers = c("Adidas","ADIDAS GROUP","ALIBABA GROUP","ALIBABA.COM (EUROPE) LTD"
              ,"Apple Asia Pacific Pte Ltd" ,"APPLE DISTRIBUTION INTERNATIONAL"
              ,"APPLE EUROPE LTD","Apple Sales International"
              ,"AVIVA-PLC","Aviva -Norwich Union"
              ,"Aviva -Norwich Union-MSP","AVIVA PLC"
              ,"AXA TECHNOLOGY SERVICES UK LTD","AXA UK PLC"
              ,"Bank of Baroda","Bank of Baroda"
              ,"BARCLAYS","BARCLAYS BANK PLC"
              ,"BARCLAYS PLC","BRAVURA SOLUTIONS LTD"
              ,"CENTRICA PLC","CISCO"
              ,"Cisco Systems LTD","CSC (NG)-MSP"
              ,"CSC COMPUTER SCIENCES LTD","EMC CORPORATION"
              ,"GE Infrastructure UK Limited","GE MEDICAL SYSTEMS INFORMATION TECHNOLOGIES GMBH")

FinalDS = subset(Test1, grepl(paste(Customers, collapse = "|"), Test1$Customer_Name))
</code>```

All this does is try to match word by word what i have on my Customer list against the Test1 DF

Help Please!

答:
How about this?</p>

```<code>FinalDS = subset(
    Test1,
    grepl(paste0("(", paste(Customers, collapse = "|"), ")"), Customer_Name))
</code>```

Body:
i have a Data Frame called Test1 that contains 230k companies. what i need to do is to subset Tests1 into a new DF called FinalDS.

i have created a list called Customers that contains several name variations of the clients (about 100k) that i need put into my FinalDS DF.
What i am looking for is R to look at my Customers DF and look for the customer name in the Test1 DF but!.... what i need is R to scan the Customers DF and see if it can match any part of the customer name in the Customers DF to the Test1 DF

For example:

i have this customer on the Customers DF:
Centrica PLC

But on the Test1 DF i have Centrica so by difinition there will be no match. i know that i could just make all the customers match by deleting the PLC part from the Customers DF but i have a list of about 100k Customers.

this is the code that i have written:

Customers = c("Adidas","ADIDAS GROUP","ALIBABA GROUP","ALIBABA.COM (EUROPE) LTD"
              ,"Apple Asia Pacific Pte Ltd" ,"APPLE DISTRIBUTION INTERNATIONAL"
              ,"APPLE EUROPE LTD","Apple Sales International"
              ,"AVIVA-PLC","Aviva -Norwich Union"
              ,"Aviva -Norwich Union-MSP","AVIVA PLC"
              ,"AXA TECHNOLOGY SERVICES UK LTD","AXA UK PLC"
              ,"Bank of Baroda","Bank of Baroda"
              ,"BARCLAYS","BARCLAYS BANK PLC"
              ,"BARCLAYS PLC","BRAVURA SOLUTIONS LTD"
              ,"CENTRICA PLC","CISCO"
              ,"Cisco Systems LTD","CSC (NG)-MSP"
              ,"CSC COMPUTER SCIENCES LTD","EMC CORPORATION"
              ,"GE Infrastructure UK Limited","GE MEDICAL SYSTEMS INFORMATION TECHNOLOGIES GMBH")

FinalDS = subset(Test1, grepl(paste(Customers, collapse = "|"), Test1$Customer_Name))

All this does is try to match word by word what i have on my Customer list against the Test1 DF

Help Please!

Body:
How about this?

FinalDS = subset(
    Test1,
    grepl(paste0("(", paste(Customers, collapse = "|"), ")"), Customer_Name))


问:
Rapidly iterating Silverlight development
My current default browser is Chrome (dev).  I'm using VS2010 and Silverlight4, with ASP.NET MVC3.  I don't seem to have the problems with debugging that I've seen others have.  My main complaint is that I regularly have to clear my browser cache to get the latest version of my app to show up.  Sometimes I have to clear it two or three times.  I've taken to changing the background color of certain elements just to be sure whether I've got the actual latest changes.

Are Firefox or IE better in this regard?  Is there are trick to make my latest version always appear?

答:
Like you, I use Chrome for my main browser, and I don't use IE for any regular browsing.  But I do use IE for Silverlight development, for this reason and others.  I rarely if ever have trouble with the IE cache holding onto outdated versions of my XAP file, but this happens pretty regularly with FireFox and Chrome.  In addition, depending on how I closed my previous debug session, when I start up a new one, FireFox and Chrome frequently open up my previous tab(s) in addition to the one that I'm actually trying to debug.  Consequently, IE is (for me) the cleanest browser to actually debug with.

This isn't really an answer -- just an observation.  Sorry :-).


问:
Elastic search: Run multiple analyzers on the same data
I am looking for a way to make ES search the data with multiple analyzers.
NGram analyzer and one or few language analyzers.

Possible solution will be to use multi-fields and explicitly declare which analyzer to use for each field.

For example, to set the following mappings:

```<code>  "mappings": {
    "my_entity": {
      "properties": {
        "my_field": {
          "type": "text",
          "fields": {
            "ngram": {
              "type": "string",
              "analyzer": "ngram_analyzer"
            },
            "spanish": {
              "type": "string",
              "analyzer": "spanish"
            },
            "english": {
              "type": "string",
              "analyzer": "english"
            }
          }
        }
      }
    }
  }
</code>```

The problem with that is that I have explicitly write every field and its analyzers to a search query.
And it will not allow to search with "_all" and use multiple analyzers.

Is there a way to make "_all" query use multiple analyzers?
Something like  "_all.ngram",  "_all.spanish" and without using copy_to do duplicate the data?

Is it possible to combine ngram analyzer with a spanish (or any other foreign language) and make a single custom analyzer?
I have tested the following settings but these did not work:

```<code>    PUT /ngrams_index
    {
       "settings": {
          "number_of_shards": 1,
          "analysis": {
            "tokenizer": {
              "ngram_tokenizer": {
                 "type": "nGram",
                 "min_gram": 3,
                 "max_gram": 3
              }
            },
            "filter": {
                "ngram_filter": {
                   "type": "nGram",
                   "min_gram": 3,
                   "max_gram": 3
              },

              "spanish_stop": {
                "type":       "stop",
                "stopwords":  "_spanish_"
              },
              "spanish_keywords": {
                "type":       "keyword_marker",
                "keywords":   ["ejemplo"]
              },
              "spanish_stemmer": {
                "type":       "stemmer",
                "language":   "light_spanish"
              }

            },
            "analyzer": {
              "ngram_analyzer": {
                 "type": "custom",
                 "tokenizer": "ngram_tokenizer",
                 "filter": [
                    "lowercase",
                    "spanish_stop",
                    "spanish_keywords",
                    "spanish_stemmer"
                 ]
              }
            }
          }
       },
       "mappings": {
          "my_entity": {
            "_all": {
                    "enabled": true,
                    "analyzer": "ngram_analyzer"
             },

             "properties": {
                "my_field": {
                    "type": "text",
                    "fields": {
                          "analyzer1": {
                            "type": "string",
                            "analyzer": "ngram_analyzer"
                          },
                          "analyzer2": {
                                  "type": "string",
                                 "analyzer": "spanish"
                          },
                          "analyzer3": {
                                  "type": "string",
                                 "analyzer": "english"
                          }
                    }
                }
             }
          }
       }
    }

    GET /ngrams_index/_analyze
    {
      "field": "_all",
      "text": "Hola, me llamo Juan."
    }
</code>```

returns: just ngram results, without Spanish analysis

where

```<code>    GET /ngrams_index/_analyze
    {
      "field": "my_field.analyzer2",
      "text": "Hola, me llamo Juan."
    }
</code>```

properly analyzes the search string.

Is it possible to build a custom analyzer which combine Spanish and ngram?

答:
There is a way to create a custom ngram+language analyzer:</p>

```<code>PUT /ngrams_index
{
  "settings": {
    "number_of_shards": 1,
    "analysis": {
      "filter": {
        "ngram_filter": {
          "type": "nGram",
          "min_gram": 3,
          "max_gram": 3
        },
        "spanish_stop": {
          "type": "stop",
          "stopwords": "_spanish_"
        },
        "spanish_keywords": {
          "type": "keyword_marker",
          "keywords": [
            "ejemplo"
          ]
        },
        "spanish_stemmer": {
          "type": "stemmer",
          "language": "light_spanish"
        }
      },
      "analyzer": {
        "ngram_analyzer": {
          "type": "custom",
          "tokenizer": "standard",
          "filter": [
            "lowercase",
            "spanish_stop",
            "spanish_keywords",
            "spanish_stemmer",
            "ngram_filter"
          ]
        }
      }
    }
  },
  "mappings": {
    "my_entity": {
      "_all": {
        "enabled": true,
        "analyzer": "ngram_analyzer"
      },

      "properties": {
        "my_field": {
          "type": "text",
          "analyzer": "ngram_analyzer"
        }
      }
    }
  }
}

GET /ngrams_index/_analyze
{
  "field": "my_field",
  "text": "Hola, me llamo Juan."
}
</code>```

Body:
I am looking for a way to make ES search the data with multiple analyzers.
NGram analyzer and one or few language analyzers.

Possible solution will be to use multi-fields and explicitly declare which analyzer to use for each field.

For example, to set the following mappings:

  "mappings": {
    "my_entity": {
      "properties": {
        "my_field": {
          "type": "text",
          "fields": {
            "ngram": {
              "type": "string",
              "analyzer": "ngram_analyzer"
            },
            "spanish": {
              "type": "string",
              "analyzer": "spanish"
            },
            "english": {
              "type": "string",
              "analyzer": "english"
            }
          }
        }
      }
    }
  }

The problem with that is that I have explicitly write every field and its analyzers to a search query.
And it will not allow to search with "_all" and use multiple analyzers.

Is there a way to make "_all" query use multiple analyzers?
Something like  "_all.ngram",  "_all.spanish" and without using copy_to do duplicate the data?

Is it possible to combine ngram analyzer with a spanish (or any other foreign language) and make a single custom analyzer?
I have tested the following settings but these did not work:

    PUT /ngrams_index
    {
       "settings": {
          "number_of_shards": 1,
          "analysis": {
            "tokenizer": {
              "ngram_tokenizer": {
                 "type": "nGram",
                 "min_gram": 3,
                 "max_gram": 3
              }
            },
            "filter": {
                "ngram_filter": {
                   "type": "nGram",
                   "min_gram": 3,
                   "max_gram": 3
              },

              "spanish_stop": {
                "type":       "stop",
                "stopwords":  "_spanish_"
              },
              "spanish_keywords": {
                "type":       "keyword_marker",
                "keywords":   ["ejemplo"]
              },
              "spanish_stemmer": {
                "type":       "stemmer",
                "language":   "light_spanish"
              }

            },
            "analyzer": {
              "ngram_analyzer": {
                 "type": "custom",
                 "tokenizer": "ngram_tokenizer",
                 "filter": [
                    "lowercase",
                    "spanish_stop",
                    "spanish_keywords",
                    "spanish_stemmer"
                 ]
              }
            }
          }
       },
       "mappings": {
          "my_entity": {
            "_all": {
                    "enabled": true,
                    "analyzer": "ngram_analyzer"
             },

             "properties": {
                "my_field": {
                    "type": "text",
                    "fields": {
                          "analyzer1": {
                            "type": "string",
                            "analyzer": "ngram_analyzer"
                          },
                          "analyzer2": {
                                  "type": "string",
                                 "analyzer": "spanish"
                          },
                          "analyzer3": {
                                  "type": "string",
                                 "analyzer": "english"
                          }
                    }
                }
             }
          }
       }
    }

    GET /ngrams_index/_analyze
    {
      "field": "_all",
      "text": "Hola, me llamo Juan."
    }

returns: just ngram results, without Spanish analysis

where

    GET /ngrams_index/_analyze
    {
      "field": "my_field.analyzer2",
      "text": "Hola, me llamo Juan."
    }

properly analyzes the search string.

Is it possible to build a custom analyzer which combine Spanish and ngram?

Body:
There is a way to create a custom ngram+language analyzer:

PUT /ngrams_index
{
  "settings": {
    "number_of_shards": 1,
    "analysis": {
      "filter": {
        "ngram_filter": {
          "type": "nGram",
          "min_gram": 3,
          "max_gram": 3
        },
        "spanish_stop": {
          "type": "stop",
          "stopwords": "_spanish_"
        },
        "spanish_keywords": {
          "type": "keyword_marker",
          "keywords": [
            "ejemplo"
          ]
        },
        "spanish_stemmer": {
          "type": "stemmer",
          "language": "light_spanish"
        }
      },
      "analyzer": {
        "ngram_analyzer": {
          "type": "custom",
          "tokenizer": "standard",
          "filter": [
            "lowercase",
            "spanish_stop",
            "spanish_keywords",
            "spanish_stemmer",
            "ngram_filter"
          ]
        }
      }
    }
  },
  "mappings": {
    "my_entity": {
      "_all": {
        "enabled": true,
        "analyzer": "ngram_analyzer"
      },

      "properties": {
        "my_field": {
          "type": "text",
          "analyzer": "ngram_analyzer"
        }
      }
    }
  }
}

GET /ngrams_index/_analyze
{
  "field": "my_field",
  "text": "Hola, me llamo Juan."
}


问:
How to edit specific fields of object in the array at the same time in setState
How do we create specific fields of object in the array?

Here is my state data that I want to partially update.

```<code>state.items = [
     {id:0, left: 100, right: 100, classified: true},
     {id:1, left: 200, right: 300, classified: false},
]
</code>```

And this is expected result after setState.

```<code>// Edit left, right, classified with given values,
// where the object's id is equal to 1.
state.items = [
     {id:0, left: 100, right: 100, classified: true},
     {id:1, left: 300, right: 200, classified: true},
]
</code>```

Here is code inside of function (Problem)

```<code>//console.log(id) <- prints 1. We are modifying the second object in the array with id 1.

// iterate items array
let { items } = this.state;
for (var index in items) {
  if(items[index].id === id) {
     // copy the whole object matching id is 1.
     var deep = _.cloneDeep(tag);

     //Assign new values (newLeft: 300, newRight:200, newCalssified: true)
     deep.left = newLeft
     deep.right = newRight
     deep.classified = newClassified

    this.setState({
      // HERE IS THE QUESTION
      taggedClothes // how do we modify the object with id 1??
    })
  }
}
</code>```

THANKS!!

答:
@klugjo's answer is correct but to change reference make a deep clone of current state to change state:</p>

```<code>const {items} = _.cloneDeep(this.state);

// Find index to modify
const index = items.findIndex(i => i.id === id);
items[index].left = newLeft;
items[index].right = newRight;
items[index].classified = newClassified;

this.setState({ items });
</code>```

Body:
How do we create specific fields of object in the array?

Here is my state data that I want to partially update.

state.items = [
     {id:0, left: 100, right: 100, classified: true},
     {id:1, left: 200, right: 300, classified: false},
]

And this is expected result after setState.

// Edit left, right, classified with given values,
// where the object's id is equal to 1.
state.items = [
     {id:0, left: 100, right: 100, classified: true},
     {id:1, left: 300, right: 200, classified: true},
]

Here is code inside of function (Problem)

//console.log(id) <- prints 1. We are modifying the second object in the array with id 1.

// iterate items array
let { items } = this.state;
for (var index in items) {
  if(items[index].id === id) {
     // copy the whole object matching id is 1.
     var deep = _.cloneDeep(tag);

     //Assign new values (newLeft: 300, newRight:200, newCalssified: true)
     deep.left = newLeft
     deep.right = newRight
     deep.classified = newClassified

    this.setState({
      // HERE IS THE QUESTION
      taggedClothes // how do we modify the object with id 1??
    })
  }
}

THANKS!!

Body:
@klugjo's answer is correct but to change reference make a deep clone of current state to change state:

const {items} = _.cloneDeep(this.state);

// Find index to modify
const index = items.findIndex(i => i.id === id);
items[index].left = newLeft;
items[index].right = newRight;
items[index].classified = newClassified;

this.setState({ items });


问:
json_decode expects parameter 1 to be string, says array is given. Why doesn't my string pass properly?
So, I've been struggling with this for the entire weekend and I still can't figure out what's wrong. I'm trying to pass some data through json_decode to be able to save it to a file and I keep getting the error it expects a string but an array is given. I'm using jQuery and PHP.

The data I send through the ajax call is, according to console.log(noBrack):

```<code>{"ID":2,"LLID":"LLID2","volNaam":"Test - 0","norm":"Zicht","instalDatum":"17-11-2017","endDate":"18-11-2017","serie":"0","klant":"Testklant","file":"data/Testklant (Heerenveen)/LLID2.json","gelDat":"27-10-2018"}
</code>```

My Ajax call is:

```<code>$.ajax({
  url: 'quickGrade.php',
  type: 'POST',
  data: noBrack,
  datatype: 'json',
  success:function(data){
    alert(data );
  }
});
</code>```

My PHP code is:

```<code>$testSave = 'data/gradeTest.json';
$decode = json_decode($_POST, true);
file_put_contents($testSave, $decode);
</code>```

Can anyone find out what I'm doing wrong? I've tested my string with an online json_decode tester and it said it was valid so I'm kinda hardstuck here.

答: The way you are sending data will give you $_POST array in php code. So actually you do not need to decode because the data is coming as $_POST array not a JSON string.</p>

Body:
So, I've been struggling with this for the entire weekend and I still can't figure out what's wrong. I'm trying to pass some data through json_decode to be able to save it to a file and I keep getting the error it expects a string but an array is given. I'm using jQuery and PHP.

The data I send through the ajax call is, according to console.log(noBrack):

{"ID":2,"LLID":"LLID2","volNaam":"Test - 0","norm":"Zicht","instalDatum":"17-11-2017","endDate":"18-11-2017","serie":"0","klant":"Testklant","file":"data/Testklant (Heerenveen)/LLID2.json","gelDat":"27-10-2018"}

My Ajax call is:

$.ajax({
  url: 'quickGrade.php',
  type: 'POST',
  data: noBrack,
  datatype: 'json',
  success:function(data){
    alert(data );
  }
});

My PHP code is:

$testSave = 'data/gradeTest.json';
$decode = json_decode($_POST, true);
file_put_contents($testSave, $decode);

Can anyone find out what I'm doing wrong? I've tested my string with an online json_decode tester and it said it was valid so I'm kinda hardstuck here.


问:
How word embeddings work for word similarity?
I am trying to apply word2vec/doc2vec to find similar sentences. First consider word2vec for word similarity. What I understand is, CBOW can be used to find most suitable word given a context, whereas Skip-gram is used to find the context given some word, so in both cases, I am getting words that co-occur frequently. But how does it work to find similar words? My intuition is, since similar words tend to occur in similar contexts, the words similarity is actually measured from the similarity among contextual/co-occuring words. In the neural net, when the vector representation for some word at the hidden layer is passed through to the output layer, it outputs probabilities of co-occuring words. So, the co-occuring words influence the vectors of some words, and since similar words have similar set of co-occuring words, their vector representations are also similar. To find the similarity, we need to extract the hidden layer weights (or vectors) for each word and measure their similarities. Do I understand it correctly?

Finally, what is a good way to find tweet text (full sentence) similarity using word2vec/doc2vec?

答:
I'm not certain this is a question for Stack Overflow but here goes my attempt at a reply...

You have the basic notions right, though you're mixing the definition of the goal with the implementation when you mention neural nets, there are other ways to get at word embedding for CBOW and skip-gram.

The word embedding can then be transferred (called transfer learning usually but in NLP they simply term it the embedding layer, which is standard practice to put as the first layer) to another domain and either kept frozen or tweaked for the more complex NLP task at hand, So...

As for your last question, it really depends on the specifics of the task

what are you using the tweet distance for?

Is it supervised or unsupervised?

What is the output space?

I think for unsupervised learning of doc2vec for something like clustering for topics a good bet would be to try autoencoders (see Hinton's dimensionality reduction paper) a language model (and taking the last hidden vector) wmd (I think its implemented in gensim) and many others (there are also other BOW like methods that don't use word embedding at all)


答:
As stated in previous answers you have to modify the entire items array. Here is another approach to do the same using reduce in a cleaner way.

```<code>this.setState({
  items: this.state.items.reduce(function(acc, item) {
    if (item.id === id) {
      item.left = newLeft;
      item.right = newRight;
      item.classified = newClassified;
    }
    acc.push(item);
    return acc;
  }, [])
});
</code>```

Title: How to edit specific fields of object in the array at the same time in setState

Body:
As stated in previous answers you have to modify the entire items array. Here is another approach to do the same using reduce in a cleaner way.

this.setState({
  items: this.state.items.reduce(function(acc, item) {
    if (item.id === id) {
      item.left = newLeft;
      item.right = newRight;
      item.classified = newClassified;
    }
    acc.push(item);
    return acc;
  }, [])
});


问:
how to get dynamic data using JSoup?
I'm  a beginner at android and I'm trying to make an app that get values from a html file hosted in a webserver that gets data from sensors of an arduino. But JSoup only gets the first value, i don't know how to get the values that changed.

Here is the MainAcivity.java code:

```<code>Public class MainActivity extends AppCompatActivity {
final String TAG = this.getClass().getSimpleName();
private AnimationDrawable creepyAnimation;
private ImageView creepyImage;
private TextView result;
RequestQueue requestQueue;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    creepyImage = (ImageView) findViewById(R.id.creepy);
    creepyImage.setBackgroundResource(R.drawable.animation);
    creepyAnimation = (AnimationDrawable) creepyImage.getBackground();
    requestQueue = Volley.newRequestQueue(this);
    result = (TextView) findViewById(R.id.textView);
    getWebSite();

}
private void getWebSite(){

    new  Thread(new Runnable() {
        @Override
        public void run() {
            final StringBuilder  builder = new StringBuilder();
            try {
                Document doc = (Document) Jsoup.connect("http://munhoz-unifei.000webhostapp.com/").get();
                Element valor1 = doc.getElementById("sala");
                Element valor2 = doc.getElementById("quarto");

                builder.append(valor1.attr("sala")).append("xxx: ").append(valor1.text()).append("\n");
                builder.append(valor2.attr("quarto")).append("lalala: ").append(valor2.text()).append("\n");

               /*
                for (Element element : valor){
                    builder.append(element.attr("sala"))
                            .append("\n").append("text: ").append(element.text());

                }
               */
            }catch (IOException e){
                builder.append("ERROR: ").append(e.getMessage()).append("\n");
            }
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    result.setText(builder.toString());

                }
            });
        }
    }).start();

}
</code>```

}

i just want to get the values to change on the app as it changes on the website. Could someone give me a hint or an example of how to do this work?

答:
Jsoup can only parse or process the html that is sent by the server.
Anything part of the DOM that is generated by the javascript on the client's end can't be parsed through Jsoup.

What you can try is selenium web automation to obtain the html rendered by the browser.

Title: how to get dynamic data using JSoup?

Body:
I'm  a beginner at android and I'm trying to make an app that get values from a html file hosted in a webserver that gets data from sensors of an arduino. But JSoup only gets the first value, i don't know how to get the values that changed.

Here is the MainAcivity.java code:

Public class MainActivity extends AppCompatActivity {
final String TAG = this.getClass().getSimpleName();
private AnimationDrawable creepyAnimation;
private ImageView creepyImage;
private TextView result;
RequestQueue requestQueue;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    creepyImage = (ImageView) findViewById(R.id.creepy);
    creepyImage.setBackgroundResource(R.drawable.animation);
    creepyAnimation = (AnimationDrawable) creepyImage.getBackground();
    requestQueue = Volley.newRequestQueue(this);
    result = (TextView) findViewById(R.id.textView);
    getWebSite();

}
private void getWebSite(){

    new  Thread(new Runnable() {
        @Override
        public void run() {
            final StringBuilder  builder = new StringBuilder();
            try {
                Document doc = (Document) Jsoup.connect("http://munhoz-unifei.000webhostapp.com/").get();
                Element valor1 = doc.getElementById("sala");
                Element valor2 = doc.getElementById("quarto");

                builder.append(valor1.attr("sala")).append("xxx: ").append(valor1.text()).append("\n");
                builder.append(valor2.attr("quarto")).append("lalala: ").append(valor2.text()).append("\n");

               /*
                for (Element element : valor){
                    builder.append(element.attr("sala"))
                            .append("\n").append("text: ").append(element.text());

                }
               */
            }catch (IOException e){
                builder.append("ERROR: ").append(e.getMessage()).append("\n");
            }
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    result.setText(builder.toString());

                }
            });
        }
    }).start();

}

}

i just want to get the values to change on the app as it changes on the website. Could someone give me a hint or an example of how to do this work?