问:
How to correctly handle 3rd party POD
I am using a 3rd party library that is for the most part consists of POD structures. Even more, those structures are shared pointed by a special library pointer, build with a special library factory, so they come and go around in the form of Ptr<APod>. Since PODs are by definition all public, this has led them to be modified all around the code base, scattering the code everywhere. I am trying to find a better approach. I would like to wrap them in order to make them become real classes, so that every operation regarding those data are forced to be inside the wrapper class:

```<code>class Wrapper
{
public:
    Wrapper( /* params to correcly build APod */ );

    /** required when it needs to be sent back to the library **/
    const Ptr<APod>& unwrap() const;
private:
    Ptr<APod> m_data;
};
</code>```

But even if this is fine for most of the library PODs, it is a little bit tricky when PODs have fields that consist of other POD, or when there is a collection of PODs (the library also have its own Vector of Ptr to PODs). Another tricky thing is that since the library accepts back only const Ptr<APod>&, which means constant pointer to non-constant object, my unwrap() method is still allowing programmers to have too much freedom on these PODs.
Can my approach be improved? Or is it entirely wrong, and should be replaced with another approach?

答:
If some of the PODs can be included in other PODs or in array/containers, it means that you should never try to build the POD yourself, but just assume that you build your wrapper from a pointer to POD or in the case of your specific library a Ptr<APod>.

Without knowing the semantics of Ptr (unique/shared/weak) I cannot say whether you should then keep a copy of the original Ptr<APod> or a reference to it.

Title: How to correctly handle 3rd party POD

Body:
I am using a 3rd party library that is for the most part consists of POD structures. Even more, those structures are shared pointed by a special library pointer, build with a special library factory, so they come and go around in the form of Ptr<APod>. Since PODs are by definition all public, this has led them to be modified all around the code base, scattering the code everywhere. I am trying to find a better approach. I would like to wrap them in order to make them become real classes, so that every operation regarding those data are forced to be inside the wrapper class:

class Wrapper
{
public:
    Wrapper( /* params to correcly build APod */ );

    /** required when it needs to be sent back to the library **/
    const Ptr<APod>& unwrap() const;
private:
    Ptr<APod> m_data;
};

But even if this is fine for most of the library PODs, it is a little bit tricky when PODs have fields that consist of other POD, or when there is a collection of PODs (the library also have its own Vector of Ptr to PODs). Another tricky thing is that since the library accepts back only const Ptr<APod>&, which means constant pointer to non-constant object, my unwrap() method is still allowing programmers to have too much freedom on these PODs.
Can my approach be improved? Or is it entirely wrong, and should be replaced with another approach?


来源: stackexchange

问:
Script to get Windows version and send it by email
I want to monitor version of Windows on all computers in a domain. So I want to create a .bat file that get the local Windows version and if possible send it via email using telnet command.

I never wrote a script in Windows. So it's difficult for me to start in this area. So any help will be appreciated.

答:
```<code> for /f "skip=3 delims=\" %%A in ('net view ^| findstr /v /C:"The command completed successfully"') do Echo %%A
</code>```

Will give you a list of computernames. Put it in a file.

```<code> for /f "skip=3 delims=\" %%A in ('net view ^| findstr /v /C:"The command completed successfully"') do Echo %%A >> Computername.txt
</code>```

Then type to do turned on computers

```<code> wmic /node:@"Computername.txt" os get version /format:csv
</code>```

ContentLicense: CC BY-SA 3.0

Body:
 for /f "skip=3 delims=\" %%A in ('net view ^| findstr /v /C:"The command completed successfully"') do Echo %%A

Will give you a list of computernames. Put it in a file.

 for /f "skip=3 delims=\" %%A in ('net view ^| findstr /v /C:"The command completed successfully"') do Echo %%A >> Computername.txt

Then type to do turned on computers

 wmic /node:@"Computername.txt" os get version /format:csv


问:
xcode timePicker returns wrong time
I am having an issue with a time picker and cannot figure out what my issue is.  Here is my code;

```<code>timePicker.timeZone = [NSTimeZone localTimeZone];
NSDate *selected = [timePicker date];

NSString *message = [[NSString alloc] initWithFormat:
                     @"The date and time you selected is: %@", selected];
UIAlertView *alert = [[UIAlertView alloc]
                      initWithTitle:@"Date and Time Selected"
                      message:message
                      delegate:nil
                      cancelButtonTitle:@"Yes, I did."
                      otherButtonTitles:nil];
[alert show];
</code>```

So for example if I select the time 2:55 pm the alert returns "2012-08-14 19:55:37 +0000"

It has to be something super simple just cannot see it

答:
You need to add time interval difference between UTC and your country time zone you can achieve it by this:</p>

```<code>(sender.date as NSDate).addingTimeInterval(TimeInterval(NSTimeZone.local.secondsFromGMT()))
</code>```

Title: xcode timePicker returns wrong time

Body:
I am having an issue with a time picker and cannot figure out what my issue is.  Here is my code;

timePicker.timeZone = [NSTimeZone localTimeZone];
NSDate *selected = [timePicker date];

NSString *message = [[NSString alloc] initWithFormat:
                     @"The date and time you selected is: %@", selected];
UIAlertView *alert = [[UIAlertView alloc]
                      initWithTitle:@"Date and Time Selected"
                      message:message
                      delegate:nil
                      cancelButtonTitle:@"Yes, I did."
                      otherButtonTitles:nil];
[alert show];

So for example if I select the time 2:55 pm the alert returns "2012-08-14 19:55:37 +0000"

It has to be something super simple just cannot see it

Body:
You need to add time interval difference between UTC and your country time zone you can achieve it by this:

(sender.date as NSDate).addingTimeInterval(TimeInterval(NSTimeZone.local.secondsFromGMT()))


问:
Generating URL for Controller action in Spring
How can I dynamically create an URL for a Controller action?

Consider the following case:

```<code>@Controller
@RequestMapping("controller")
public class Controller {
    @RequestMapping("url")
    public String method() {
        return "Whatever"
    }
}
</code>```

What I'd like to do is get the base URL and concat controller/url to it.
For this behavior, Laravel for example provides the URL helper (action() method). Is there something similar in Spring Boot?

答:
you can use UriComponentsBuilder to get the current url and concat the additional part to it</p>

```<code>@Controller
@RequestMapping("controller")
public class Controller {
    @RequestMapping("url")
    public String method(UriComponentBuilder ucb) {
        URI uri = ucb.path("/url").build().toUri();
        return "Whatever"
    }
}
</code>```

Body:
How can I dynamically create an URL for a Controller action?

Consider the following case:

@Controller
@RequestMapping("controller")
public class Controller {
    @RequestMapping("url")
    public String method() {
        return "Whatever"
    }
}

What I'd like to do is get the base URL and concat controller/url to it.
For this behavior, Laravel for example provides the URL helper (action() method). Is there something similar in Spring Boot?

Body:
you can use UriComponentsBuilder to get the current url and concat the additional part to it

@Controller
@RequestMapping("controller")
public class Controller {
    @RequestMapping("url")
    public String method(UriComponentBuilder ucb) {
        URI uri = ucb.path("/url").build().toUri();
        return "Whatever"
    }
}

ContentLicense: CC BY-SA 4.0


问:
Using oracle loop to concatanete strings
I have someting like this
id day descrition

```<code>1  1   hi
1  1   today
1  1   is a beautifull
1  1   day
1  2   exemplo
1  2   for
1  2   this case
</code>```

I need to do a funtion that for each day concatenate the descrtiomn colunm and return the result like this

```<code>id day descrition
1  1   hi today is a beautifull thay
1  2   exemplo for this case
</code>```

Anny ideia about how can i do this usisng a loop in a function in oracle

答:
You need a way of determining which order the values should be aggregated. The snippet below will rely on the implicit order in which Oracle reads the rows from the datafiles - if you have row movement enabled then you may get inconsistent results as the rows can be read in different orders as they are relocated in the underlying datafiles.

```<code>SELECT LISTAGG( description, ' ' ) WITHIN GROUP ( ORDER BY ROWNUM ) AS description
FROM   your_table
GROUP BY id, day
</code>```

It would be better to have another column that stores the order within each day.

Body:
I have someting like this
id day descrition

1  1   hi
1  1   today
1  1   is a beautifull
1  1   day
1  2   exemplo
1  2   for
1  2   this case

I need to do a funtion that for each day concatenate the descrtiomn colunm and return the result like this

id day descrition
1  1   hi today is a beautifull thay
1  2   exemplo for this case

Anny ideia about how can i do this usisng a loop in a function in oracle

Body:
You need a way of determining which order the values should be aggregated. The snippet below will rely on the implicit order in which Oracle reads the rows from the datafiles - if you have row movement enabled then you may get inconsistent results as the rows can be read in different orders as they are relocated in the underlying datafiles.

SELECT LISTAGG( description, ' ' ) WITHIN GROUP ( ORDER BY ROWNUM ) AS description
FROM   your_table
GROUP BY id, day

It would be better to have another column that stores the order within each day.


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

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

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

My template:

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

答:
If you will pass the values as an id array to ngModel

```<code>let idArrary = ["1"];

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

`

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

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

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

My template:

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

Body:
If you will pass the values as an id array to ngModel

let idArrary = ["1"];

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

`


问:
Increase wibox height depending on content
I have a wibox with vertical layout and two text widgets:

```<code>local w = wibox {
    width = 300,
    height = 80,
    ontop = true,
    screen = mouse.screen,
}

w:setup {
    {
        id = 'header',
        widget = wibox.widget.textbox
    },
    {
        id = 'body',
        widget = wibox.widget.textbox
    },
    id = 'text',
    layout = wibox.layout.flex.vertical,
}
</code>```

When string in 'body' textbox is short everything is ok, the widgets looks this way:

But if string is long, the size of the wibox is not enough to display it all so part of the string is cut out:

Is it possible to make wibox size change dynamically depending on size of the content?

答:
I'm not quit sure what you want. If you want to adjust the height of the wibox for the content:

After you change the text of the textboxes, run something like the following code:

```<code>local t1 = w:get_children_by_id("header")[1]
local t2 = w:get_children_by_id("body")[1]
local h1 = t1:get_height_for_width(w.width, w.screen)
local h2 = t2:get_height_for_width(w.width, w.screen)
w.height = h1 + h2
</code>```

If you want some extra empty space like in your first screenshot, you could add some number to the height. 42 is always a good answer. ;-)

Body:
I have a wibox with vertical layout and two text widgets:

local w = wibox {
    width = 300,
    height = 80,
    ontop = true,
    screen = mouse.screen,
}

w:setup {
    {
        id = 'header',
        widget = wibox.widget.textbox
    },
    {
        id = 'body',
        widget = wibox.widget.textbox
    },
    id = 'text',
    layout = wibox.layout.flex.vertical,
}

When string in 'body' textbox is short everything is ok, the widgets looks this way:

But if string is long, the size of the wibox is not enough to display it all so part of the string is cut out:

Is it possible to make wibox size change dynamically depending on size of the content?

Body:
I'm not quit sure what you want. If you want to adjust the height of the wibox for the content:

After you change the text of the textboxes, run something like the following code:

local t1 = w:get_children_by_id("header")[1]
local t2 = w:get_children_by_id("body")[1]
local h1 = t1:get_height_for_width(w.width, w.screen)
local h2 = t2:get_height_for_width(w.width, w.screen)
w.height = h1 + h2

If you want some extra empty space like in your first screenshot, you could add some number to the height. 42 is always a good answer. ;-)


问:
Editing row of one dataframe appears to affect another? Pandas Python
Having a bit of a strange issue, where I must be making some sort of mistake.

My script is as follows: Create one dataframe of 4 rows and 3 columns, full of random values. Then create a second dataframe which is equal to the first one, and then in the second df, change the values of the second row.

```<code>import pandas as pd
import numpy as np

#Create random df
df1 = pd.DataFrame(np.random.rand(4,3))

#Create a second df which is the same as df1
df2 = df1

#Viewing them both, the look the same
df1
df2

#Now edit row #1 of df2
df2.iloc[1:2] = [[0 , 0, 1]]

#Now viewing them both, both df1 and df2 have row #1 as 0, 0, 1
</code>```

I thought that df2 = df1 would be a one time assignment and the two dataframes would be entirely separate from then on?

答:
For new mutable object in python (here DataFrame) need copy:

```<code>df2 = df1.copy()
</code>```

Better explanation is here.

Body:
Having a bit of a strange issue, where I must be making some sort of mistake.

My script is as follows: Create one dataframe of 4 rows and 3 columns, full of random values. Then create a second dataframe which is equal to the first one, and then in the second df, change the values of the second row.

import pandas as pd
import numpy as np

#Create random df
df1 = pd.DataFrame(np.random.rand(4,3))

#Create a second df which is the same as df1
df2 = df1

#Viewing them both, the look the same
df1
df2

#Now edit row #1 of df2
df2.iloc[1:2] = [[0 , 0, 1]]

#Now viewing them both, both df1 and df2 have row #1 as 0, 0, 1

I thought that df2 = df1 would be a one time assignment and the two dataframes would be entirely separate from then on?

Body:
For new mutable object in python (here DataFrame) need copy:

df2 = df1.copy()

Better explanation is here.


问:
NEO4J MERGE is not working as expected
I am new in neo4j and I am having problems with the MERGE clause. I have a method to do queries like this:

```<code>def upsert (idValue, valueField1):
   query = "MERGE (n:Node {id: '" + idValue+ "'}) "
   query += "ON MATCH SET n.field1= n.field1+ " + str(valueField1) + " "
   query += "ON CREATE SET n = {id: '" + idValue + "', field1: 0} "
   return db.run(query)
</code>```

Then, I am calling the method like this:

```<code>upsert("1", 0)
upsert("2", 0)
upsert("3", 5)
upsert("1", 2)
upsert("1", 1)
</code>```

So, afterthat, I expected this:

```<code>node (id="1", field1=3)
node (id="2", field1=0)
node (id="3", field1=0)
</code>```

But, I am getting this:

```<code>node (id="1", field1=2)
node (id="2", field1=0)
node (id="3", field1=0)
</code>```

In addition, If I do the same calls again, I got this:

```<code>node (id="1", field1=4)
node (id="2", field1=0)
node (id="3", field1=5)
</code>```

Could anyone explain me what is happening and what am I doing wrong please? I was looking for on internet, but I couldn't find anything helpful for me.

答:
With this query, that is exactly the same as what you are doing, I have the good result :

```<code>WITH [
        {idValue:'1', valueField1:0},
        {idValue:'2', valueField1:0},
        {idValue:'3', valueField1:5},
        {idValue:'1', valueField1:2},
        {idValue:'1', valueField1:1}
    ] AS data
UNWIND data AS item
MERGE (n:Node {id:item.idValue})
  ON MATCH SET n.field1= n.field1 + item.valueField1
  ON CREATE SET n = {id:item.idValue, field1: 0}
</code>```

And then with MATCH (n:Node) RETURN n.id, n.field1 ORDER BY n.id LIMIT 25 :

```<code>n.id    n.field1
"1"     3
"2"     0
"3"     0
</code>```

So I don't think that the problem comes from the query itself, but from its construction.

You should consider to use a parameterized query. It will be easier to read the query, but also code it and it's more performant in Neo4j.
So your code should be :

```<code>def upsert (idValue, valueField1):
   query = "MERGE (n:Node {id:$id}) "
           " ON MATCH SET n.field1= n.field1 + $value"
           " ON CREATE SET n = {id:$id, field1: 0}"
   return db.run(query, id=idValue, value=valueField1)
</code>```

Title: NEO4J MERGE is not working as expected

Body:
I am new in neo4j and I am having problems with the MERGE clause. I have a method to do queries like this:

def upsert (idValue, valueField1):
   query = "MERGE (n:Node {id: '" + idValue+ "'}) "
   query += "ON MATCH SET n.field1= n.field1+ " + str(valueField1) + " "
   query += "ON CREATE SET n = {id: '" + idValue + "', field1: 0} "
   return db.run(query)

Then, I am calling the method like this:

upsert("1", 0)
upsert("2", 0)
upsert("3", 5)
upsert("1", 2)
upsert("1", 1)

So, afterthat, I expected this:

node (id="1", field1=3)
node (id="2", field1=0)
node (id="3", field1=0)

But, I am getting this:

node (id="1", field1=2)
node (id="2", field1=0)
node (id="3", field1=0)

In addition, If I do the same calls again, I got this:

node (id="1", field1=4)
node (id="2", field1=0)
node (id="3", field1=5)

Could anyone explain me what is happening and what am I doing wrong please? I was looking for on internet, but I couldn't find anything helpful for me.

Body:
With this query, that is exactly the same as what you are doing, I have the good result :

WITH [
        {idValue:'1', valueField1:0},
        {idValue:'2', valueField1:0},
        {idValue:'3', valueField1:5},
        {idValue:'1', valueField1:2},
        {idValue:'1', valueField1:1}
    ] AS data
UNWIND data AS item
MERGE (n:Node {id:item.idValue})
  ON MATCH SET n.field1= n.field1 + item.valueField1
  ON CREATE SET n = {id:item.idValue, field1: 0}

And then with MATCH (n:Node) RETURN n.id, n.field1 ORDER BY n.id LIMIT 25 :

n.id    n.field1
"1"     3
"2"     0
"3"     0

So I don't think that the problem comes from the query itself, but from its construction.

You should consider to use a parameterized query. It will be easier to read the query, but also code it and it's more performant in Neo4j.
So your code should be :

def upsert (idValue, valueField1):
   query = "MERGE (n:Node {id:$id}) "
           " ON MATCH SET n.field1= n.field1 + $value"
           " ON CREATE SET n = {id:$id, field1: 0}"
   return db.run(query, id=idValue, value=valueField1)


问:
How to fetch Kettle Trans execution results which are triggered by java application

I have successfully wrote a java program sending a ktr file to a remote Kettle platform to execute. The java program will load tasks in database and sending a related ktr to Kettle to execute. My problem is that I do not know how to get the Kettle Trans execution results for this task gracefully, cause I don't know how to filter out the trans logs by a certain task.

My current solution is to read the Ketlle Trans Log, one of the database log tables generate by Kettle itself.

The problem in this solution is since that all the fields and related data are provided by Kettle, I cannot tell which log is related to which task. So I have to rename transname in the transmeta with the task id, and then the task id will then be passed into the Trans Log table in the transname field. Through this way I can get the related log record by the task id.

```<code>private void startClusterTrans(String repoConnectStr, String transName, String taskId) throws PlatformException {
    Repository repository = null;
    TransMeta transMeta = null;
    try {
        repository = getKettleRepository(repoConnectStr);

        // 1: find the trans to execute by transName
        transMeta = findTransMeta(transName, repository);

        // 2: set the trans name with task id
        //    later the taksId will be passed to transname field in the trans log table
        transMeta.setName(taskId);
        TransExecutionConfiguration transExecutionConfiguration = new TransExecutionConfiguration();
        transExecutionConfiguration.setLogLevel(LogLevel.BASIC);
        transExecutionConfiguration.setExecutingClustered(true);
        ...
        transExecutionConfiguration.setVariables(transMeta);

        Trans.executeClustered(transMeta, transExecutionConfiguration);
    } catch (Throwable e) {
        throw new PlatformException(e);
    }
}
</code>```

I think this method is not gracefully. Firstly, I have to scan the database every some seconds and cause database pressure. Secondly The transname will be changed if the trans is executed in cluster mode.

Would anyone tell me if there is some other common way to filter the trans execution results?  I hope the way to fetch the results will be the same when trans is executed in local, remote and cluster mode.

To elaborate my problem, let's take cluster mode for example. I start a java task #1001 , which will execute a foo.ktr in a cluster mode. I have 1 master and 2 slaves in this situation. After the execution, there will be 3 records generated in trans log table. Sadly I don't know how to link the 3 trans logs to my task #1001.

Now my workaround is that before send foo.ktr to cluster, I change the transname of the transmeta to be task #1001, and after execution, the transname field for the 3 trans records in the trans log table will look like 1001 (my-cluster-sth) ; 1001 (my-cluster: slave1) ; 1001 (my-cluster: slave2) . So I have to use "LIKE" key word to link these 3 records to my task.  I don't think this is a good way. The 2 concerns are alread mentioned above.

答:
Please upvote http://jira.pentaho.com/browse/PDI-16549 and http://jira.pentaho.com/browse/PDI-10912.

If I do understand what you are aiming at, in a foreseeable future you 'll need to know the values of the parameters with which the transformation was run. So, upvote also http://jira.pentaho.com/browse/PDI-16550.

Body:
I have successfully wrote a java program sending a ktr file to a remote Kettle platform to execute. The java program will load tasks in database and sending a related ktr to Kettle to execute. My problem is that I do not know how to get the Kettle Trans execution results for this task gracefully, cause I don't know how to filter out the trans logs by a certain task.

My current solution is to read the Ketlle Trans Log, one of the database log tables generate by Kettle itself.

The problem in this solution is since that all the fields and related data are provided by Kettle, I cannot tell which log is related to which task. So I have to rename transname in the transmeta with the task id, and then the task id will then be passed into the Trans Log table in the transname field. Through this way I can get the related log record by the task id.

private void startClusterTrans(String repoConnectStr, String transName, String taskId) throws PlatformException {
    Repository repository = null;
    TransMeta transMeta = null;
    try {
        repository = getKettleRepository(repoConnectStr);

        // 1: find the trans to execute by transName
        transMeta = findTransMeta(transName, repository);

        // 2: set the trans name with task id
        //    later the taksId will be passed to transname field in the trans log table
        transMeta.setName(taskId);
        TransExecutionConfiguration transExecutionConfiguration = new TransExecutionConfiguration();
        transExecutionConfiguration.setLogLevel(LogLevel.BASIC);
        transExecutionConfiguration.setExecutingClustered(true);
        ...
        transExecutionConfiguration.setVariables(transMeta);

        Trans.executeClustered(transMeta, transExecutionConfiguration);
    } catch (Throwable e) {
        throw new PlatformException(e);
    }
}

I think this method is not gracefully. Firstly, I have to scan the database every some seconds and cause database pressure. Secondly The transname will be changed if the trans is executed in cluster mode.

Would anyone tell me if there is some other common way to filter the trans execution results?  I hope the way to fetch the results will be the same when trans is executed in local, remote and cluster mode.

To elaborate my problem, let's take cluster mode for example. I start a java task #1001 , which will execute a foo.ktr in a cluster mode. I have 1 master and 2 slaves in this situation. After the execution, there will be 3 records generated in trans log table. Sadly I don't know how to link the 3 trans logs to my task #1001.

Now my workaround is that before send foo.ktr to cluster, I change the transname of the transmeta to be task #1001, and after execution, the transname field for the 3 trans records in the trans log table will look like 1001 (my-cluster-sth) ; 1001 (my-cluster: slave1) ; 1001 (my-cluster: slave2) . So I have to use "LIKE" key word to link these 3 records to my task.  I don't think this is a good way. The 2 concerns are alread mentioned above.


问:
Ajax Jquery Function response
I am learning to use jQuery Ajax. What does function(response) mean and what is the meaning of response == 1 and response == 2?

jQuery.post(ajaxurl, data, function(response) {
  if (response == 1) {
    $saveAlert.addClass('is-success').delay(900).fadeOut(700);
    setTimeout(function() {
      $tieBody.removeClass('has-overlay');
    }, 1200);
  } else if (response == 2) {
    location.reload();
  } else {
    $saveAlert.addClass('is-failed').delay(900).fadeOut(700);
    setTimeout(function() {
      $tieBody.removeClass('has-overlay');
    }, 1200);
  }
});
```

答:
I'll explain the basics:

jQuery.post = You want to post some data to your endpoint

ajaxurl = your endpoint address. Typically a API

data = the data you want to send to your endpoint along with the request.

function(response) is where you handle the response from the endpoint.

So lets go through the code. First you call post to your endpoint / API with the data you want to post. Then you provide a callback (in your case a function) to handle the response the endpoint / API provides you.

In your case it looks like if the endpoint responds with 1, you have successfully posted your data. If the endpoint responds with 2, you have posted data and want to reload the site. If the endpoint does NOT respond with either 1 or 2, it failed to post.

To help you understand the basics of jQuery post:

A well-written API / endpoint should respond with the correct HTTP status codes and status messages and it should be fairly easy to notice when data was posted correctly and when an error occurred.

I don't think your endpoint responds any good. response == 1 or response == 2is not by any means clear and easy to understand.

A better way of handling success and errors is to use the done and fail handlers of jquery post (more on this below).

```<code>$.post( "test.php" );
</code>```

This will completely ignore the response from calling the endpoint. I.e. you don't want to handle either success or error. PLEASE DO NOT USE THIS. You should handle success and error!

```<code>$.post( "test.php", function( data ) {
  //Do something now
});
</code>```

This will do whatever you provide in the function when the endpoint has sent its response.

```<code>$.post( "example.php", function() {
  //You successfully reached the endpoint
  console.log( "success" );
})
  .done(function() {
    //Handle success here!
  })
  .fail(function() {
    //Handle error here
  })
</code>```

This is probably the preferred way of handling both success and errors. It's pretty clear that if you reach the fail, it has failed. Both easy to read the code and easy to understand jquery post!

The examples above is copied from the jquery documentation.

Note that the previous handlers for done and fail was success and error, but success and error is deprecated and removed in jQuery 3.0!

So if you have jQuery version < 3.0 you need to find out if you need to use the new or old syntax, or if you need to update jQuery maybe?

Hope this explains enough to make you understand the basics, and to help you get further. I highly suggest you read the jQuery.post documentation here. I think you should also read the w3schools documentation here.

Title: Ajax Jquery Function response

Body:
I'll explain the basics:

jQuery.post = You want to post some data to your endpoint

ajaxurl = your endpoint address. Typically a API

data = the data you want to send to your endpoint along with the request.

function(response) is where you handle the response from the endpoint.

So lets go through the code. First you call post to your endpoint / API with the data you want to post. Then you provide a callback (in your case a function) to handle the response the endpoint / API provides you.

In your case it looks like if the endpoint responds with 1, you have successfully posted your data. If the endpoint responds with 2, you have posted data and want to reload the site. If the endpoint does NOT respond with either 1 or 2, it failed to post.

To help you understand the basics of jQuery post:

A well-written API / endpoint should respond with the correct HTTP status codes and status messages and it should be fairly easy to notice when data was posted correctly and when an error occurred.

I don't think your endpoint responds any good. response == 1 or response == 2is not by any means clear and easy to understand.

A better way of handling success and errors is to use the done and fail handlers of jquery post (more on this below).

$.post( "test.php" );

This will completely ignore the response from calling the endpoint. I.e. you don't want to handle either success or error. PLEASE DO NOT USE THIS. You should handle success and error!

$.post( "test.php", function( data ) {
  //Do something now
});

This will do whatever you provide in the function when the endpoint has sent its response.

$.post( "example.php", function() {
  //You successfully reached the endpoint
  console.log( "success" );
})
  .done(function() {
    //Handle success here!
  })
  .fail(function() {
    //Handle error here
  })

This is probably the preferred way of handling both success and errors. It's pretty clear that if you reach the fail, it has failed. Both easy to read the code and easy to understand jquery post!

The examples above is copied from the jquery documentation.

Note that the previous handlers for done and fail was success and error, but success and error is deprecated and removed in jQuery 3.0!

So if you have jQuery version < 3.0 you need to find out if you need to use the new or old syntax, or if you need to update jQuery maybe?

Hope this explains enough to make you understand the basics, and to help you get further. I highly suggest you read the jQuery.post documentation here. I think you should also read the w3schools documentation here.


问:
A simple Select taking too long
I have a table as follows:

```<code>    SELECT DrugID,
            DrugName,
            Method
     FROM DrugMaster_Names WITH (NOLOCK);
</code>```

A simple select query like above takes about 13 seconds for only 3585 records(rows) but if I remove DrugName from the query it takes just 1 sec. I'm trying to optimize this query and have tried a lot of things but nothing seems to work.
I need help optimizing this query. Any help will be highly appreciated.

Thanks

答:
If the data in that DrugName column is quite long - close to 2k per record - then it's a reasonable amount of data you're pulling with your query: ~6MB. Are you running this over the network or executing the query on the same machine as the DB? Are you running on a DB with very low throughput - e.g. on a Basic tier Azure DB?

If you truncate the DrugName does it make it much faster:

```<code>SELECT DrugID,
        left(DrugName, 20) as DrugName_Short,
        Method
 FROM DrugMaster_Names WITH (NOLOCK);
</code>```

Title: A simple Select taking too long

Body:
I have a table as follows:

    SELECT DrugID,
            DrugName,
            Method
     FROM DrugMaster_Names WITH (NOLOCK);

A simple select query like above takes about 13 seconds for only 3585 records(rows) but if I remove DrugName from the query it takes just 1 sec. I'm trying to optimize this query and have tried a lot of things but nothing seems to work.
I need help optimizing this query. Any help will be highly appreciated.

Thanks

Body:
If the data in that DrugName column is quite long - close to 2k per record - then it's a reasonable amount of data you're pulling with your query: ~6MB. Are you running this over the network or executing the query on the same machine as the DB? Are you running on a DB with very low throughput - e.g. on a Basic tier Azure DB?

If you truncate the DrugName does it make it much faster:

SELECT DrugID,
        left(DrugName, 20) as DrugName_Short,
        Method
 FROM DrugMaster_Names WITH (NOLOCK);


问:
Unable to expand MemberOf using Microsoft Graph .NET SDK using Delta Query
Expanding properties doesn't seem to work when using Delta queries. It works fine with regular user query.

Is this a limitation in Microsoft Graph API?

```<code>var usersInfo = graphServiceClientWithApplicationPermission.Users.Delta().Request().Expand("MemberOf").GetAsync();

// Add inital request users
foreach (var userInfo in usersInfo)
{

    // Member info doesn't seem to be expanded even if $expand=MemberOf is sent
    if (userInfo.MemberOf == null)
    {
        userInfo.MemberOf = await applicationPermissionsClient.Users[userInfo.Id].MemberOf.Request().GetAsync();
    }

    // MemberOf is now populated ??

}
</code>```

答:
Seems like this is another limitation of the Microsoft Graph and not supported.

Optional query parameters

If a client uses a query parameter, it must be specified in the
  initial request. Microsoft Graph automatically encodes the specified
  parameter into the nextLink or deltaLink provided in the response. The
  calling application only needs to specify their desired query
  parameters once upfront. Microsoft Graph adds the specified parameters
  automatically for all subsequent requests. For users and groups, t
  here are restrictions on using some query parameters:

If a $select query parameter is used, the parameter indicates that the
  client prefers to only track changes on the properties or
  relationships specified in the $select statement. If a change occurs
  to a property that is not selected, the resource for which that
  property changed does not appear in the delta response after a
  subsequent request. $expand is not supported.

For users and groups beta (preview) APIs, scoping filters allow you to
  track changes to one or more specific users or groups by objectId. For
  example, the following request:
  https://graph.microsoft.com/beta/groups/delta/?$filter= id eq
  '477e9fc6-5de7-4406-bb2a-7e5c83c9ae5f' or id eq
  '004d6a07-fe70-4b92-add5-e6e37b8acd8e' returns changes for the groups
  matching the ids specified in the query filter.

https://developer.microsoft.com/en-us/graph/docs/concepts/delta_query_overview

Body:
Expanding properties doesn't seem to work when using Delta queries. It works fine with regular user query.

Is this a limitation in Microsoft Graph API?

var usersInfo = graphServiceClientWithApplicationPermission.Users.Delta().Request().Expand("MemberOf").GetAsync();

// Add inital request users
foreach (var userInfo in usersInfo)
{

    // Member info doesn't seem to be expanded even if $expand=MemberOf is sent
    if (userInfo.MemberOf == null)
    {
        userInfo.MemberOf = await applicationPermissionsClient.Users[userInfo.Id].MemberOf.Request().GetAsync();
    }

    // MemberOf is now populated ??

}


问:
Corodva app icon wont change
I am having an issue with changing app icon in ios/android in cordova project.

I put icon src="icon.png" inside widget tag in config.xml.
Icon is inside my root folder. I got an error if i
execute following command:

```<code>cordova run ios
</code>```

error:

The following build commands failed:
          CompileAssetCatalog build/emulator/Survival\ Guide.app Survival\ Guide/Images.xcassets (1 failure) Error: Error code 65 for
  command: xcodebuild with args:
  -xcconfig,/Users/andreasplado/Desktop/work/studyinestoniaapp/platforms/ios/cordova/build-debug.xcconfig,-workspace,Survival
  Guide.xcworkspace,-scheme,Survival
  Guide,-configuration,Debug,-sdk,iphonesimulator,-destination,platform=iOS
  Simulator,name=iPhone
  X,build,CONFIGURATION_BUILD_DIR=/Users/andreasplado/Desktop/work/studyinestoniaapp/platforms/ios/build/emulator,SHARED_PRECOMPS_DIR=/Users/andreasplado/Desktop/work/studyinestoniaapp/platforms/ios/build/sharedpch

Please help me to change the icon of an app!
Looking forward to hear from you soon.

答: All latest cordova versions ideally expects (based on supported versions) the icons to have all 1x, 2x and 3x images with proper naming. You can refer Cordova App Icons  for better understanding. Please cross-check your code with this link.</p>

Title: Corodva app icon wont change

Body:
I am having an issue with changing app icon in ios/android in cordova project.

I put icon src="icon.png" inside widget tag in config.xml.
Icon is inside my root folder. I got an error if i
execute following command:

cordova run ios

error:

The following build commands failed:
          CompileAssetCatalog build/emulator/Survival\ Guide.app Survival\ Guide/Images.xcassets (1 failure) Error: Error code 65 for
  command: xcodebuild with args:
  -xcconfig,/Users/andreasplado/Desktop/work/studyinestoniaapp/platforms/ios/cordova/build-debug.xcconfig,-workspace,Survival
  Guide.xcworkspace,-scheme,Survival
  Guide,-configuration,Debug,-sdk,iphonesimulator,-destination,platform=iOS
  Simulator,name=iPhone
  X,build,CONFIGURATION_BUILD_DIR=/Users/andreasplado/Desktop/work/studyinestoniaapp/platforms/ios/build/emulator,SHARED_PRECOMPS_DIR=/Users/andreasplado/Desktop/work/studyinestoniaapp/platforms/ios/build/sharedpch

Please help me to change the icon of an app!
Looking forward to hear from you soon.


问:
parsing dictionary of objects in c# Dictionary<string,object> data
I am passing following json in request body

```<code>{
  "areaId": "1",
  "cat": "2",
  "subcat": "41",
  "location": "1100",
  "sublocation": "11001",
  "briefDescription": "thissss is brief description",
  "detailedDescription": "this is detailed obj",
  "images": {
    "image1": "base64 string",
    "image2": "base64 string"
  }
}
</code>```

and my handler looks like this

```<code>[HttpPost]
public HttpResponseMessage Post(Dictionary<string,object> data)
{
    int areaId = Int32.Parse(data["areaId"].ToString()); //this is how i am getting area from it

    return Request.CreateResponse(HttpStatusCode.OK, new { some objects to return });
}
</code>```

how can I extract the images from this json in a dictionary? and what will be the efficient way of doing this

答:
If you want to use the Linq to Json approach, you could do as follow:

```<code>JObject o = JObject.Parse(j);
Dictionary<string, string> images = new Dictionary<string, string>();
foreach(JProperty im in o["images"])
{
    images.Add(im.Name, (string)im.Value);
}
</code>```

where j is a string containing your JSON.

Body:
I am passing following json in request body

{
  "areaId": "1",
  "cat": "2",
  "subcat": "41",
  "location": "1100",
  "sublocation": "11001",
  "briefDescription": "thissss is brief description",
  "detailedDescription": "this is detailed obj",
  "images": {
    "image1": "base64 string",
    "image2": "base64 string"
  }
}

and my handler looks like this

[HttpPost]
public HttpResponseMessage Post(Dictionary<string,object> data)
{
    int areaId = Int32.Parse(data["areaId"].ToString()); //this is how i am getting area from it

    return Request.CreateResponse(HttpStatusCode.OK, new { some objects to return });
}

how can I extract the images from this json in a dictionary? and what will be the efficient way of doing this

Body:
If you want to use the Linq to Json approach, you could do as follow:

JObject o = JObject.Parse(j);
Dictionary<string, string> images = new Dictionary<string, string>();
foreach(JProperty im in o["images"])
{
    images.Add(im.Name, (string)im.Value);
}

where j is a string containing your JSON.


问:
Single Column Drop down instead of a two column drop down
Hi I am trying to make this two column drop down just a single column. I can't identify how to modify the code to do this. This is a custom them for open cart.</p>

```<code>public function drawMenuItem($children, $level = 0, $columChunk = 0, $lang_id = 1,$setting) {
        $lang_id = (int)$this->config->get('config_language_id');
        $this->load->model('catalog/category');

        $html = '<div class="itemMenu level' . $level . '">';

        $countChildren = 0;
        $ClassNoChildren = '';

        foreach ($children as $child) {
            $activeChildCat = $this->model_catalog_category->getCategories($child['category_id']);
            $activeChildCat = $this->getCategoryByLevelMax($activeChildCat,$setting);
            if ($activeChildCat) {
                $countChildren++;
            }
        }
        if ($countChildren == 0 && $columChunk == 1) {
            $ClassNoChildren = ' nochild';
        }

        foreach ($children as $child) {
             $info =  $this->model_catalog_category->getCategory($child['category_id']);
            $level = (int)  $this->getCategoryLevelByCateId($child['category_id']);
            $active = '';
            //$currentCate = $this->getCurrentCategoriesId($lang_id);
            $cate_id = (int) $child['category_id'];
          //  if (in_array($cate_id, $currentCate)) {
                if ($this->haveCateChildren($cate_id, $lang_id)) {
                    $active = ' actParent';
                } else {
                    $active = ' act';
                }
            //}
            // --- format category name ---
            $name = strip_tags($child['name']);
            if (count($child) > 0) {
                $parameters = null;
                $link = $this->url->link('product/category', "path=".$child['category_id']);

                $html.= '<a class="itemMenuName level' . $level . $active . $ClassNoChildren . '" href="' . $link . '"><span>' . $name .'</span></a>';

                if($setting['hlevel'] > 2 && $level <= $setting['hlevel'] ) {
                    $activeChildren = $this->model_catalog_category->getCategories($child['category_id']);
                    $activeChildren = $this->getCategoryByLevelMax($activeChildren,$setting);
                    if (count($activeChildren) > 0) {
                        $html.= '<div class="itemSubMenu level' . $level . '">';
                        //$html.= $this->drawMenuItem($activeChildren, $level + 1);
                        $html.= $this->drawMenuItem($activeChildren, $level ,$columChunk, $lang_id,$setting);
                        $html.= '</div>';
                    }
                }

            }
        }
        $html.= '</div>';
        return $html;
    }
</code>```

答:
The columns are s which are floated left (float: left;) with CSS which makes them appear next to each other.

If you remove the "float: left;" in custommenu.css around line 75, it will display as you desire.

Body:
Hi I am trying to make this two column drop down just a single column. I can't identify how to modify the code to do this. This is a custom them for open cart.

public function drawMenuItem($children, $level = 0, $columChunk = 0, $lang_id = 1,$setting) {
        $lang_id = (int)$this->config->get('config_language_id');
        $this->load->model('catalog/category');

        $html = '
';

        $countChildren = 0;
        $ClassNoChildren = '';

        foreach ($children as $child) {
            $activeChildCat = $this->model_catalog_category->getCategories($child['category_id']);
            $activeChildCat = $this->getCategoryByLevelMax($activeChildCat,$setting);
            if ($activeChildCat) {
                $countChildren++;
            }
        }
        if ($countChildren == 0 && $columChunk == 1) {
            $ClassNoChildren = ' nochild';
        }

        foreach ($children as $child) {
             $info =  $this->model_catalog_category->getCategory($child['category_id']);
            $level = (int)  $this->getCategoryLevelByCateId($child['category_id']);
            $active = '';
            //$currentCate = $this->getCurrentCategoriesId($lang_id);
            $cate_id = (int) $child['category_id'];
          //  if (in_array($cate_id, $currentCate)) {
                if ($this->haveCateChildren($cate_id, $lang_id)) {
                    $active = ' actParent';
                } else {
                    $active = ' act';
                }
            //}
            // --- format category name ---
            $name = strip_tags($child['name']);
            if (count($child) > 0) {
                $parameters = null;
                $link = $this->url->link('product/category', "path=".$child['category_id']);

                $html.= '' . $name .'';

                if($setting['hlevel'] > 2 && $level <= $setting['hlevel'] ) {
                    $activeChildren = $this->model_catalog_category->getCategories($child['category_id']);
                    $activeChildren = $this->getCategoryByLevelMax($activeChildren,$setting);
                    if (count($activeChildren) > 0) {
                        $html.= '
';
                        //$html.= $this->drawMenuItem($activeChildren, $level + 1);
                        $html.= $this->drawMenuItem($activeChildren, $level ,$columChunk, $lang_id,$setting);
                        $html.= '
';
                    }
                }

            }
        }
        $html.= '
';
        return $html;
    }


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

My array:

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

I need print:

Impresoras: Impresora 4, Impresora 8

Destructoras: Destructora 3, Destructora 5

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

    foreach ($options as $key => $value) {
        $data[$value['cat']][] = $value['nameProd'];
    };
</code>```

Title: Group array some values

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

My array:

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

I need print:

Impresoras: Impresora 4, Impresora 8

Destructoras: Destructora 3, Destructora 5


问:
Converting .exe to VS solution file / project
I've recently had an issue at work where I have lost my solution files to my projects, but I still have the executables that have been produced by the projects / solution.  It has been collection of 50+ webforms.

I have tried some de-compiler tools like ILSpy, JustComplie and .Net Reflector but everything gives source code in different format (not originally written by me) and also not designs of forms.

Is there any possibility to decompiling the executable back into a solution/project file?

答:
I don't think that you can actually decompile the executables to a solution structure as seen on VS.
Although you can decompile the executable files (there are decompilers on the net that can perofrm the operation for you - only the decompilation),
you need to re-create the solution manually and add the source files you have retrieved from the previous operation.
Furthermore, if your files were obfuscated this makes it harder for them to be decompiled.
Even if this works, be prepared to do some debugging and check references/dependencies.</p>


问:
How to analysis one row into several rows according to num of map.keys

I am trying to read a dataset and process it; dataset row type is (string,string,string,Map[String,String]), the num of Map.keys is from 1 to 3,so one row will become 1-3 rows like(string,string,string,k,v).
I actually realize it using code as follows:

```<code>var arr  = new ArrayBuffer[Array[String]]()
myDataset.collect.foreach{
f:(String,String,String,Map[String,String]) =>
    val ma = f._4
    for((k,v)<-ma) {
        arr += Array(f._1,f._2,f._3,k,v)
    }
}
</code>```

Orgdata like this(one row in mydataset:hundreds of millions ):

```<code>val a = ("111","222","333",Map("k1"->"v1","k2"->"v2"))
</code>```

expected output:

```<code>("111","222","333","k1","v1")
("111","222","333","k2","v2")
</code>```

But big data cause OOM problem,so is there other ways to accomplish this ? or how to optimize my code to avoid  OOM?

答:
You can just explode the map column and then select the exploded columns :

```<code>val df = sc.parallelize(Array(
    ("111","222","333",Map("k1"->"v1","k2"->"v2"))
)).toDF("a", "b", "c", "d")

df.select($"*", explode($"d") )
  .select("a", "b", "c" ,"key", "value")
  .as[(String, String, String, String, String)]
  .first
// (String, String, String, String, String) = (111,222,333,k1,v1)
</code>```

Body:
I am trying to read a dataset and process it; dataset row type is (string,string,string,Map[String,String]), the num of Map.keys is from 1 to 3,so one row will become 1-3 rows like(string,string,string,k,v).
I actually realize it using code as follows:

var arr  = new ArrayBuffer[Array[String]]()
myDataset.collect.foreach{
f:(String,String,String,Map[String,String]) =>
    val ma = f._4
    for((k,v)<-ma) {
        arr += Array(f._1,f._2,f._3,k,v)
    }
}

Orgdata like this(one row in mydataset:hundreds of millions ):

val a = ("111","222","333",Map("k1"->"v1","k2"->"v2"))

expected output:

("111","222","333","k1","v1")
("111","222","333","k2","v2")

But big data cause OOM problem,so is there other ways to accomplish this ? or how to optimize my code to avoid  OOM?

Body:
You can just explode the map column and then select the exploded columns :

val df = sc.parallelize(Array(
    ("111","222","333",Map("k1"->"v1","k2"->"v2"))
)).toDF("a", "b", "c", "d")

df.select($"*", explode($"d") )
  .select("a", "b", "c" ,"key", "value")
  .as[(String, String, String, String, String)]
  .first
// (String, String, String, String, String) = (111,222,333,k1,v1)


问:
Bash Sqlite3 Varrible
I have folder which has 500 database. I want get value from them. Inside the for loop ATTACH '$i' AS db2; not work. If i write to name of folder instead of $i code is work.

How can make a db_name as a varible

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

for i in $( ls ); do
    if [[ $i != test.sh ]]; then
            if [[ $i != abc.db3 ]]; then
            echo  "--------- " $i  " ---------"

            sqlite3  abc.db3 <<'EOF'
            ATTACH '$i' AS db2;
            INSERT INTO Test (userId, sender, date) SELECT user_id, sender, send_date FROM db2.mt;
EOF
        fi
     fi

done

echo "-------- Finish ----------"
</code>```

答:
You have disabled parameter substitution by quoting the heredoc label.

Use <<EOF instead.

Alternatively, open the database $i directly and attach abc.db3 to it.

Title: Bash Sqlite3 Varrible

Body:
I have folder which has 500 database. I want get value from them. Inside the for loop ATTACH '$i' AS db2; not work. If i write to name of folder instead of $i code is work.

How can make a db_name as a varible

#!/bin/bash
clear

for i in $( ls ); do
    if [[ $i != test.sh ]]; then
            if [[ $i != abc.db3 ]]; then
            echo  "--------- " $i  " ---------"

            sqlite3  abc.db3 <<'EOF'
            ATTACH '$i' AS db2;
            INSERT INTO Test (userId, sender, date) SELECT user_id, sender, send_date FROM db2.mt;
EOF
        fi
     fi

done

echo "-------- Finish ----------"


问:
Fetching all Mongo documents based on different combinations of values of same query parameters using Spring MongoRepository
I am writing a web service in which I need to provide in the response of a user's REST request a list of documents from MongoDb. The filter parameters are provided in the request payload of the request. I need to fetch all documents using Spring's MongoRepository interface which match a combination of parameters. The following query applied directly on the collection works the way I want:

```<code>db.getCollection('userCollection').find({ '$and' : [ { 'admin':'admin1', 'address':'add1'}, {'$or': [{ 'name' : { '$in':['Amy','Maya'] } }, {'school': 'S1', 'college': 'Col1', 'company': 'CompCop'}, {'school': 'S2', 'college': 'Col1', 'company': 'CompShop'}]} ]})
</code>```

So I need to do the following:

All documents must have "admin"="admin1" and "address"="add1"

Documents must either have "name" as one of ["Amy", "Maya"] or they must have one of the following of school-college-company combinations-

{'school': 'S1', 'college': 'Col1', 'company': 'CompCop'}, {'school': 'S2', 'college': 'Col1', 'company': 'CompShop'}

These values and the number of such combinations can differ based on what is provided in the web request coming dynamically.

This second point is what I am having trouble incorporating in my JSON based Query in java using the @Query annotation.

I want to provide this information as part of the following repository method:

```<code>@Query({'$and': [{'admin': ?0, 'address': ?1}, {'$or': [{'name': {'$in': ?2}}, <add solution here for adding list of school-college-company combinations> ]}]})
public List<Users> find(String admin, String address, List<String> names, <insert parameters for 'school-college-company' combinations>);
</code>```

I searched for a solution where I can provide a list of objects of a type which has the parameters as

```<code>class FilteringClass {
    String school;
    String college;
    String company;
}
</code>```

but without any luck.

I began by trying to collect each "school", "college" and "company" as separate lists and providing these as query parameters but obviously, this is not quite right since it will fetch documents with every possible permutation of the values and not as a unique combination of the three.

Do let me know if there is any solution the way I need it as mentioned above. Thanks in advance.

答:
Created a class exactly as mentioned in the question:

```<code>class SCCFilter {
String school;
String college;
String company;
}
</code>```

When the request comes from the user with these parameters, for each element in the request payload, I pick the school, college and company values and store them in a list of 'filters'.

(Of course, this can be optimized to avoid duplicates but as a solution to the problem above, it works alright)

Then I wrote the following query:

```<code>@Query("{ '$and' : [ { 'admin' : ?0 , 'address' : ?1 } , { '$or' : [{'name': {'$in': ?2 }}, {'$or': ?3 }] }]}")
public List<Users> find(String admin, String address List<String> names, List<SCCFilter> filters)
</code>```

And this is the final query I extracted from the logs at run-time to test (successfully) in the Mongo DB:

```<code>{ "$and" : [ { "admin" : "admin1" , "address" : "addr1"} , { "$or" : [ { "name" : { "$in" : [ "Amy" , "Maya"]}} , { "$or" : [ {'school': 'S1', 'college': 'Col1', 'company': 'CompCop'}, {'school': 'S2', 'college': 'Col1', 'company': 'CompShop'}]}]}]}
</code>```

Much more readable than using MongoTemplate!

Body:
I am writing a web service in which I need to provide in the response of a user's REST request a list of documents from MongoDb. The filter parameters are provided in the request payload of the request. I need to fetch all documents using Spring's MongoRepository interface which match a combination of parameters. The following query applied directly on the collection works the way I want:

db.getCollection('userCollection').find({ '$and' : [ { 'admin':'admin1', 'address':'add1'}, {'$or': [{ 'name' : { '$in':['Amy','Maya'] } }, {'school': 'S1', 'college': 'Col1', 'company': 'CompCop'}, {'school': 'S2', 'college': 'Col1', 'company': 'CompShop'}]} ]})

So I need to do the following:

All documents must have "admin"="admin1" and "address"="add1"

Documents must either have "name" as one of ["Amy", "Maya"] or they must have one of the following of school-college-company combinations-

{'school': 'S1', 'college': 'Col1', 'company': 'CompCop'}, {'school': 'S2', 'college': 'Col1', 'company': 'CompShop'}

These values and the number of such combinations can differ based on what is provided in the web request coming dynamically.

This second point is what I am having trouble incorporating in my JSON based Query in java using the @Query annotation.

I want to provide this information as part of the following repository method:

@Query({'$and': [{'admin': ?0, 'address': ?1}, {'$or': [{'name': {'$in': ?2}}, <add solution here for adding list of school-college-company combinations> ]}]})
public List<Users> find(String admin, String address, List<String> names, <insert parameters for 'school-college-company' combinations>);

I searched for a solution where I can provide a list of objects of a type which has the parameters as

class FilteringClass {
    String school;
    String college;
    String company;
}

but without any luck.

I began by trying to collect each "school", "college" and "company" as separate lists and providing these as query parameters but obviously, this is not quite right since it will fetch documents with every possible permutation of the values and not as a unique combination of the three.

Do let me know if there is any solution the way I need it as mentioned above. Thanks in advance.

Body:
Created a class exactly as mentioned in the question:

class SCCFilter {
String school;
String college;
String company;
}

When the request comes from the user with these parameters, for each element in the request payload, I pick the school, college and company values and store them in a list of 'filters'.

(Of course, this can be optimized to avoid duplicates but as a solution to the problem above, it works alright)

Then I wrote the following query:

@Query("{ '$and' : [ { 'admin' : ?0 , 'address' : ?1 } , { '$or' : [{'name': {'$in': ?2 }}, {'$or': ?3 }] }]}")
public List<Users> find(String admin, String address List<String> names, List<SCCFilter> filters)

And this is the final query I extracted from the logs at run-time to test (successfully) in the Mongo DB:

{ "$and" : [ { "admin" : "admin1" , "address" : "addr1"} , { "$or" : [ { "name" : { "$in" : [ "Amy" , "Maya"]}} , { "$or" : [ {'school': 'S1', 'college': 'Col1', 'company': 'CompCop'}, {'school': 'S2', 'college': 'Col1', 'company': 'CompShop'}]}]}]}

Much more readable than using MongoTemplate!


问:
Remove item from list if in another list (lists of list)
I have a list that looks like this

```<code>a = [('Eth1', 'desc', 'date'), ('Eth2', 'dest', 'date'), ('Eth3', 'dest', 'date')]
</code>```

I have another list that has this:

```<code>b = = ['Eth1', 'Eth2']
</code>```

I want to remove all occurrences of b in a with its corresponding data, so at the minute I have

```<code>c = list(set(a) - set(b))
print c
</code>```

I want c to look like this

```<code>c = ['Eth3', 'dest', 'date']
</code>```

But it just prints the list in a different order, like this

```<code>[('Eth2', 'dest', 'date'), ('Eth1', 'desc', 'date'), ('Eth3', 'dest', 'date')]
</code>```

What would the best way to do this be?

答:
You need a list comprehension:

```<code>In [4]: [tup for tup in a if tup[0] not in b]
Out[4]: [('Eth3', 'dest', 'date')]
</code>```

Note that you can't use set's operations here because you don't want to compare the tuples entirely but the first items (then removing the whole tuple based on it).

Also if you're lists are longer you better to use a set for preserving the b's items. The reason is that the membership checking is O(1) in sets.

For the sake of completeness here is a functional solution too (not recommended in this case, specially if you want the result to be a list):

```<code>In [7]: list(filter(lambda x: x[0] not in b, a))
Out[7]: [('Eth3', 'dest', 'date')]
</code>```

Body:
I have a list that looks like this

a = [('Eth1', 'desc', 'date'), ('Eth2', 'dest', 'date'), ('Eth3', 'dest', 'date')]

I have another list that has this:

b = = ['Eth1', 'Eth2']

I want to remove all occurrences of b in a with its corresponding data, so at the minute I have

c = list(set(a) - set(b))
print c

I want c to look like this

c = ['Eth3', 'dest', 'date']

But it just prints the list in a different order, like this

[('Eth2', 'dest', 'date'), ('Eth1', 'desc', 'date'), ('Eth3', 'dest', 'date')]

What would the best way to do this be?

Body:
You need a list comprehension:

In [4]: [tup for tup in a if tup[0] not in b]
Out[4]: [('Eth3', 'dest', 'date')]

Note that you can't use set's operations here because you don't want to compare the tuples entirely but the first items (then removing the whole tuple based on it).

Also if you're lists are longer you better to use a set for preserving the b's items. The reason is that the membership checking is O(1) in sets.

For the sake of completeness here is a functional solution too (not recommended in this case, specially if you want the result to be a list):

In [7]: list(filter(lambda x: x[0] not in b, a))
Out[7]: [('Eth3', 'dest', 'date')]


问:
Node.js mysql connection and transactions

Hi all,

I trying to change all my mysql inserts, update etc to transactions before going live with my app, I've had alot of trouble with connection already released before and to solve it I started using pool.query instead so that it handles the release itself.

```<code>    pool.query( 'INSERT INTO X SET ?', [ X ], ( error, results ) => {

            if(err){
                reject(err);
            }
            if ( error ) {
                reject( error );
            } else if ( results[ 0 ] !== 'undefined' ) {
                resolve( 'X added sucessfully' );
            } else {
                reject( error );
            }
                } );
</code>```

I've tried to google it but cant find it anywhere, even in docs of Mysql, when you do a transaction, where in the code do I release the connection when done, or even better, can I use pool.query when doing a transaction?

the code below works but it sometimes give a connection already released error

```<code>      connection.beginTransaction( function ( err ) {
            if ( err ) {
                reject( err);
            }

        connection.query( 'INSERT INTO X SET ?', [ X ], ( error, results ) => {

            if(err){
                reject(err);
            }
            if ( error ) {
                reject( error );
            } else if ( results[ 0 ] !== 'undefined' ) {
                resolve( 'X added sucessfully' );
            } else {
                reject( error );
            }
            connection.commit( function ( commitErr ) {
                if ( commitErr ) {
                    connection.rollback( function () {
                        reject(commitErr);
                    } );
                }
          connection.release();
            } );
                } );
        } );
</code>```

答:
You need to acquire a connection from the connection pool before beginning the transaction and release it wherever you decide to rollback.
You should also rollback and release the connection as soon as you face an error on your query/decide to roll back on any other condition. In your current code, you are rolling back only if you face an error while committing your transaction.</p>

```<code>pool.getConnection(function(err, connection) {
    connection.beginTransaction(function(err) {
        if (err) { //Transaction Error (Rollback and release connection)
            connection.rollback(function() {
                connection.release();
                reject( err);
            });
        }
        connection.query('INSERT INTO X SET ?', [X], (error, results) {
            if (err) {       //Why is this here?
                reject(err);
            }
            if (error) { //Query Error (Rollback and release connection)
                connection.rollback(function() {
                    connection.release();
                    reject( err);
                });
            } else if (results[0] !== 'undefined') {
                resolve('X added sucessfully');
            } else {
                reject(error);
            }
            connection.commit(function(commitErr) {
                if (commitErr) {
                    connection.rollback(function() {
                        connection.release();
                        reject(commitErr);
                    });
                }
                connection.release();
            });
        });
    });
});
</code>```

Body:
Hi all,

I trying to change all my mysql inserts, update etc to transactions before going live with my app, I've had alot of trouble with connection already released before and to solve it I started using pool.query instead so that it handles the release itself.

    pool.query( 'INSERT INTO X SET ?', [ X ], ( error, results ) => {

            if(err){
                reject(err);
            }
            if ( error ) {
                reject( error );
            } else if ( results[ 0 ] !== 'undefined' ) {
                resolve( 'X added sucessfully' );
            } else {
                reject( error );
            }
                } );

I've tried to google it but cant find it anywhere, even in docs of Mysql, when you do a transaction, where in the code do I release the connection when done, or even better, can I use pool.query when doing a transaction?

the code below works but it sometimes give a connection already released error

      connection.beginTransaction( function ( err ) {
            if ( err ) {
                reject( err);
            }

        connection.query( 'INSERT INTO X SET ?', [ X ], ( error, results ) => {

            if(err){
                reject(err);
            }
            if ( error ) {
                reject( error );
            } else if ( results[ 0 ] !== 'undefined' ) {
                resolve( 'X added sucessfully' );
            } else {
                reject( error );
            }
            connection.commit( function ( commitErr ) {
                if ( commitErr ) {
                    connection.rollback( function () {
                        reject(commitErr);
                    } );
                }
          connection.release();
            } );
                } );
        } );

Body:
You need to acquire a connection from the connection pool before beginning the transaction and release it wherever you decide to rollback.
You should also rollback and release the connection as soon as you face an error on your query/decide to roll back on any other condition. In your current code, you are rolling back only if you face an error while committing your transaction.

pool.getConnection(function(err, connection) {
    connection.beginTransaction(function(err) {
        if (err) { //Transaction Error (Rollback and release connection)
            connection.rollback(function() {
                connection.release();
                reject( err);
            });
        }
        connection.query('INSERT INTO X SET ?', [X], (error, results) {
            if (err) {       //Why is this here?
                reject(err);
            }
            if (error) { //Query Error (Rollback and release connection)
                connection.rollback(function() {
                    connection.release();
                    reject( err);
                });
            } else if (results[0] !== 'undefined') {
                resolve('X added sucessfully');
            } else {
                reject(error);
            }
            connection.commit(function(commitErr) {
                if (commitErr) {
                    connection.rollback(function() {
                        connection.release();
                        reject(commitErr);
                    });
                }
                connection.release();
            });
        });
    });
});


问:
#temp_table vs user.#temp_table sybase_iq
i wonder what is the difference between #temp_table and user.#temp_table

```<code> -- 1) #Tem_table

  create table #temp_table
   ( id integer null);

 select * from #temp_table  -- find

select * from sysobjects where name = '#temp_table'-- not found
</code>```

-- close my client

```<code> select * from #temp_table -- not found

--2) user.#temp_table
 create table user.#temp_table
   ( id integer null);

  select * from user.#temp_table  -- found

 select * from sysobjects where name = '#temp_table'  --  found
</code>```

-- close my client

```<code>  select * from sysobjects where name = '#temp_table'  -- still exist
</code>```

My Main question is, why

```<code> select * from sysobjects where name = '#temp_table'
</code>```

return nothing, and with user.

```<code>  select * from sysobjects where name = '#temp_table'
</code>```

returns the info.

答:
When you add user_name.#Table_name Sybase ignore automatically the #. What are you creating  is a normal user Table. In fact if you check it with

```<code> select * from sysobjects where name = '#temp_table'
</code>```

the type should be 'U' what means that you have created a user table = not temporary table at all.

Best Regards, Enrique

Body:
i wonder what is the difference between #temp_table and user.#temp_table

 -- 1) #Tem_table

  create table #temp_table
   ( id integer null);

 select * from #temp_table  -- find

select * from sysobjects where name = '#temp_table'-- not found

-- close my client

 select * from #temp_table -- not found

--2) user.#temp_table
 create table user.#temp_table
   ( id integer null);

  select * from user.#temp_table  -- found

 select * from sysobjects where name = '#temp_table'  --  found

-- close my client

  select * from sysobjects where name = '#temp_table'  -- still exist

My Main question is, why

 select * from sysobjects where name = '#temp_table'

return nothing, and with user.

  select * from sysobjects where name = '#temp_table'

returns the info.

Body:
When you add user_name.#Table_name Sybase ignore automatically the #. What are you creating  is a normal user Table. In fact if you check it with

 select * from sysobjects where name = '#temp_table'

the type should be 'U' what means that you have created a user table = not temporary table at all.

Best Regards, Enrique


问:
How will _Exit behave in a C++ program?
C99 offers the _Exit function, which exits "immediately", although it does may close file descriptors. Unix/POSIX extends this behavior by mandating the closing of all fd's without flushing (and offers the synonym _exit).

Will these functions call destructors for static objects when called from a C++ program? Does the C++ standard make any guarantees about _Exit?

(Inspired by this question; I suddenly wondered what happens in the typical fork-exec-_exit idiom in C++.)

答:
Calling of static destructors is defined in terms of atexit. _exit (or _Exit) is defined not to run atexit handlers. So static destructors should not be called by any implementation.

Automatic destructors are not even called when calling exit().

So any sane definition of _Exit semantics for C++ would not run destructors.

Title: How will _Exit behave in a C++ program?

ContentLicense: CC BY-SA 2.5


问:
Wrapping different versions of static library in dynamic libraries
In my project there is a dependency on a static library (just called libsomething from now on) from a 3rd party. Recently, libsomething has become available in another version. My task is to provide my software with support for the old and the new version. Only one version of libsomething is used at run-time at any given time, but which version this is should be configurable between program runs.

I am using MSVC2005 on WinXP, a secondary objective is to become prepared to switch over to Linux and GCC.

Since both versions of libsomething are using the same symbols, linking them both into my executable is out of the question as the symbols of both versions are going to clash all over at link-time.

While I could create two executables (one linking against the old version, the other one using the new version), I cannot implement a decision on which executable to call in the final deployment environment (legacy reasons).

I came up with the idea of creating a dynamic library wrapper for each version of libsomething and linking them at run-time depending on some config file. With MSCV, this would mean going down the road of using LoadLibrary(), GetProcAddress(), etc., while on Linux I would have to use dlopen() and dlsym().

I understand that using libtool (i.e., libtldl) is wrapping this platform-dependency for using shared libraries. Is this an appropriate path to follow? Are there better (or, at least, different) ways? Do alternatives for libtldl exist as open-source?

答:
It has been few years now but I'd like to mention another solution for completeness. Instead of manual dlopen and dlsym you could generate simple stubs for all necessary functions and on first call (or at program startup) decide which library version is needed, load it and resolve the addresses.

You could write a script specifically tailored for your project or use Implib.so tool:

```<code># This will generate mylib.so.init.c and mylib.so.tramp.S
# which implement stubs. These need to be linked to your
# executable.
$ implib-gen.py mylib.so
</code>```

Implib.so is Linux-only atm but should be easily adaptable to Windows.

Body:
It has been few years now but I'd like to mention another solution for completeness. Instead of manual dlopen and dlsym you could generate simple stubs for all necessary functions and on first call (or at program startup) decide which library version is needed, load it and resolve the addresses.

You could write a script specifically tailored for your project or use Implib.so tool:

# This will generate mylib.so.init.c and mylib.so.tramp.S
# which implement stubs. These need to be linked to your
# executable.
$ implib-gen.py mylib.so

Implib.so is Linux-only atm but should be easily adaptable to Windows.


问:
How do I select rows from a DataFrame based on column values?
How can I select rows from a DataFrame based on values in some column in Pandas?

In SQL, I would use:

SELECT *
FROM table
WHERE column_name = some_value
```

答:
For selecting only specific columns out of multiple columns for a given value in Pandas:

```<code>select col_name1, col_name2 from table where column_name = some_value.
</code>```

Options loc:

```<code>df.loc[df['column_name'] == some_value, [col_name1, col_name2]]
</code>```

or query:

```<code>df.query('column_name == some_value')[[col_name1, col_name2]]
</code>```

Body:
For selecting only specific columns out of multiple columns for a given value in Pandas:

select col_name1, col_name2 from table where column_name = some_value.

Options loc:

df.loc[df['column_name'] == some_value, [col_name1, col_name2]]

or query:

df.query('column_name == some_value')[[col_name1, col_name2]]


问:
How to responsively place links in a navbar
I'm having some issues with CSS at the moment. I'm working on a navbar with some horizontal links and a dropdown menu at the end.

The links collapse into a hamburger menu when on a small screen. What I'm trying to do is, when the links collapse, I want the last link that is next to the dropdown button to be placed after the dropdown button.

Here is what it looks like when uncollapsed and with the dropdown open:

This is what it looks like collapsed at the moment:

And this is how I would like it to look:

I'm not sure how to accomplish this. I have tried floating the "Profile name" to the right and it kinda works as it place itself to the right of the "IMG" but then all the way to the right. I would like it placed snug to the "IMG". Padding it to the right place screws up the responsiveness.

I'm using bootstrap for the responsiveness and dropdown menu. I assume that I will have to use media queries for this.

If anyone has any idea of how to do this I am more than grateful for any tip!

here is a code

Link 1

Link 2

Profile name

Link 3

Link 4

Link 5

```

Keeping the dropdown open while in hamburger-mode is a problem for another day.

答:
so simply write this way

 Profile name

.Profile-img {
  width: 20px;
  height: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li class="horizontal-align">LinkLink 1</li>
  <li class="horizontal-align">Link 2</li>
  <li class="horizontal-align"> <img class="Profile-img" src="https://www.w3schools.com/w3css/img_fjords.jpg" />Profile name
    <ul>
      <li class="dropdown-li">Link 3</li>
      <li class="dropdown-li">Link 4</li>
      <li class="dropdown-li">Link 5</li>
    </ul>
  </li>
</ul></code>```

Body:
I'm having some issues with CSS at the moment. I'm working on a navbar with some horizontal links and a dropdown menu at the end.

The links collapse into a hamburger menu when on a small screen. What I'm trying to do is, when the links collapse, I want the last link that is next to the dropdown button to be placed after the dropdown button.

Here is what it looks like when uncollapsed and with the dropdown open:

This is what it looks like collapsed at the moment:

And this is how I would like it to look:

I'm not sure how to accomplish this. I have tried floating the "Profile name" to the right and it kinda works as it place itself to the right of the "IMG" but then all the way to the right. I would like it placed snug to the "IMG". Padding it to the right place screws up the responsiveness.

I'm using bootstrap for the responsiveness and dropdown menu. I assume that I will have to use media queries for this.

If anyone has any idea of how to do this I am more than grateful for any tip!

here is a code

Link 1

Link 2

Profile name

Link 3

Link 4

Link 5

Keeping the dropdown open while in hamburger-mode is a problem for another day.

Body:
so simply write this way

<li class="horizontal-align"> <img class="Profile-img"  src="https://www.w3schools.com/w3css/img_fjords.jpg"/>Profile name

.Profile-img {
  width: 20px;
  height: 10px;
}

<ul>
  <li class="horizontal-align">LinkLink 1</li>
  <li class="horizontal-align">Link 2</li>
  <li class="horizontal-align"> <img class="Profile-img" src="https://www.w3schools.com/w3css/img_fjords.jpg" />Profile name
    <ul>
      <li class="dropdown-li">Link 3</li>
      <li class="dropdown-li">Link 4</li>
      <li class="dropdown-li">Link 5</li>
    </ul>
  </li>
</ul>


问:
Seamless video Loop with VideoView
I have the following code to take a video as a raw resource, start the video and loop it but I need the video to loop seamlessly as of now when it comes to an end of the clip and starts the clip again the transition between causes a flicker for a split second, which I really can't have for my app.

```<code>public class Example extends Activity {
    VideoView vv;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        vv = (VideoView)findViewById(R.id.VideoView01);

        //Video Loop
        vv.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            public void onCompletion(MediaPlayer mp) {
                vv.start(); //need to make transition seamless.
            }
        });

        Uri uri = Uri.parse("android.resource://com.example/"
                + R.raw.video);

        vv.setVideoURI(uri);
        vv.requestFocus();
        vv.start();
    }
}
</code>```

The clip is only 22 seconds long but was created to be seamless so it is possible to work without the delay.

答:
Not sure if this helps years later, but I used

```<code>vv.start();
vv.setOnCompletionListener ( new MediaPlayer.OnCompletionListener() {

 @Override
  public void onCompletion(MediaPlayer mediaPlayer) {
    vv.start();
  }
});
</code>```

and it has a seamless loop

Title: Seamless video Loop with VideoView

Body:
I have the following code to take a video as a raw resource, start the video and loop it but I need the video to loop seamlessly as of now when it comes to an end of the clip and starts the clip again the transition between causes a flicker for a split second, which I really can't have for my app.

public class Example extends Activity {
    VideoView vv;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        vv = (VideoView)findViewById(R.id.VideoView01);

        //Video Loop
        vv.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            public void onCompletion(MediaPlayer mp) {
                vv.start(); //need to make transition seamless.
            }
        });

        Uri uri = Uri.parse("android.resource://com.example/"
                + R.raw.video);

        vv.setVideoURI(uri);
        vv.requestFocus();
        vv.start();
    }
}

The clip is only 22 seconds long but was created to be seamless so it is possible to work without the delay.

Body:
Not sure if this helps years later, but I used

vv.start();
vv.setOnCompletionListener ( new MediaPlayer.OnCompletionListener() {

 @Override
  public void onCompletion(MediaPlayer mediaPlayer) {
    vv.start();
  }
});

and it has a seamless loop


问:
laravel Undefined variable when i post multiple value to view
In controller when i try to send multiple value to view such as this codes:

```<code>$content = Contents::find($contents);
$content_categories['categories'] = ContentCategories::all()->pluck('title', 'id');
$selected_categories['selected_categories'] = $content->categories()->pluck('title', 'id');

return view('layouts.backend.pages.manage_contents.edit', compact($selected_categories, $content_categories, ['content' => $content]));
</code>```

i get error for this variables into view:

```<code>$categories
$selected_categories
$content
</code>```

result of dd(['content' => $content], $content_categories, $selected_categories); is:

```<code>array:1 [▼
  "content" => Contents {#220 ▶}
]

array:1 [▼
  "categories" => Collection {#214 ▶}
]

array:1 [▼
  "selected_categories" => Collection {#227 ▶}
]
</code>```

whats problem of my code to parse them on view or send them with correct way

my view:

```<code>1) {{ Form::select('categories[]', $categories, $selected_categories, array('class' => 'multiselect-success','multiple'=>'multiple')) }}

2) action="{{ route('manage_contents.update' , ['id' => $content->id ]) }}"
</code>```

Errors:

```<code>"Undefined variable: categories (View: /Applications/XAMPP/xamppfiles/htdocs/alachiqServer/resources/views/layouts/backend/pages/manage_contents/edit.blade.php)"

"Undefined variable: selected_categories (View: /Applications/XAMPP/xamppfiles/htdocs/alachiqServer/resources/views/layouts/backend/pages/manage_contents/edit.blade.php)"

"Undefined variable: content (View: /Applications/XAMPP/xamppfiles/htdocs/alachiqServer/resources/views/layouts/backend/pages/manage_contents/edit.blade.php)"
</code>```

答:
You can try this:

```<code>$content_categories = ContentCategories::all()->pluck('title', 'id');
$selected_categories = $content->categories()->pluck('title', 'id');

return view('layouts.backend.pages.manage_contents.edit', compact('selected_categories', 'content_categories', 'content'));
</code>```

Hope this helps you!

Body:
In controller when i try to send multiple value to view such as this codes:

$content = Contents::find($contents);
$content_categories['categories'] = ContentCategories::all()->pluck('title', 'id');
$selected_categories['selected_categories'] = $content->categories()->pluck('title', 'id');

return view('layouts.backend.pages.manage_contents.edit', compact($selected_categories, $content_categories, ['content' => $content]));

i get error for this variables into view:

$categories
$selected_categories
$content

result of dd(['content' => $content], $content_categories, $selected_categories); is:

array:1 [▼
  "content" => Contents {#220 ▶}
]

array:1 [▼
  "categories" => Collection {#214 ▶}
]

array:1 [▼
  "selected_categories" => Collection {#227 ▶}
]

whats problem of my code to parse them on view or send them with correct way

my view:

1) {{ Form::select('categories[]', $categories, $selected_categories, array('class' => 'multiselect-success','multiple'=>'multiple')) }}

2) action="{{ route('manage_contents.update' , ['id' => $content->id ]) }}"

Errors:

"Undefined variable: categories (View: /Applications/XAMPP/xamppfiles/htdocs/alachiqServer/resources/views/layouts/backend/pages/manage_contents/edit.blade.php)"

"Undefined variable: selected_categories (View: /Applications/XAMPP/xamppfiles/htdocs/alachiqServer/resources/views/layouts/backend/pages/manage_contents/edit.blade.php)"

"Undefined variable: content (View: /Applications/XAMPP/xamppfiles/htdocs/alachiqServer/resources/views/layouts/backend/pages/manage_contents/edit.blade.php)"

Body:
You can try this:

$content_categories = ContentCategories::all()->pluck('title', 'id');
$selected_categories = $content->categories()->pluck('title', 'id');

return view('layouts.backend.pages.manage_contents.edit', compact('selected_categories', 'content_categories', 'content'));

Hope this helps you!


问:
Need string formation with space in php
```<code>$string='to kill a mocking bird';
</code>```

Need output like below format

Output:

'"To kill a mocking bird",
  "Tokill a mocking bird",
  "Tokilla mocking bird",
  "Tokillamocking bird",
  "Tokillamockingbird",
  ,"To kill a mockingbird"
  ,"To kill amockingbird"
  ,"To killamockingbird"';

I used below Script

```<code>$array = is_string($arg) ? str_split($arg) : $arg;

if(1 === count($array))
  return $array;

  $result = array();
    foreach($array as $key => $item)
        foreach(permute(array_diff_key($array, array($key => $item))) as $p)
            $result[] = $item .' '. $p;
    return $result;
</code>```

答:
I use explode to make it an array that I can loop through.

In the loop I use implode to add space and array_slice to select the corresponding words to join/add space between.

I loop once forward and once backwards to get all combinations.

```<code>$str='to kill a mocking bird';

$arr = explode(" ", $str);
Echo $str."\n";

For($i=1;$i<count($arr);$i++){
    Echo implode("", array_slice($arr, 0,$i)) . implode(" ", array_slice($arr, $i)) . "\n";
}

For($i=count($arr)-1;$i>1;$i--){
     Echo implode(" ", array_slice($arr, 0, $i)) . implode("", array_slice($arr,$i, count($arr))) . "\n";
}
</code>```

https://3v4l.org/QVIKG

Title: Need string formation with space in php

Body:
$string='to kill a mocking bird';

Need output like below format

Output:

'"To kill a mocking bird",
  "Tokill a mocking bird",
  "Tokilla mocking bird",
  "Tokillamocking bird",
  "Tokillamockingbird",
  ,"To kill a mockingbird"
  ,"To kill amockingbird"
  ,"To killamockingbird"';

I used below Script

$array = is_string($arg) ? str_split($arg) : $arg;

if(1 === count($array))
  return $array;

  $result = array();
    foreach($array as $key => $item)
        foreach(permute(array_diff_key($array, array($key => $item))) as $p)
            $result[] = $item .' '. $p;
    return $result;

Body:
I use explode to make it an array that I can loop through.

In the loop I use implode to add space and array_slice to select the corresponding words to join/add space between.

I loop once forward and once backwards to get all combinations.

$str='to kill a mocking bird';

$arr = explode(" ", $str);
Echo $str."\n";

For($i=1;$i<count($arr);$i++){
    Echo implode("", array_slice($arr, 0,$i)) . implode(" ", array_slice($arr, $i)) . "\n";
}

For($i=count($arr)-1;$i>1;$i--){
     Echo implode(" ", array_slice($arr, 0, $i)) . implode("", array_slice($arr,$i, count($arr))) . "\n";
}

https://3v4l.org/QVIKG


问:
Elasticsearch can't read ScriptedMetric from BucketScript?
I should work since the ScriptedMetric is a metric, and it does return a single numeric value, but I can't get it to work.

I'm using NEST (5.5.0 via NuGet, I'm targeting Elasticsearch 6.0.0) in C# to get it to work, I did however also try building the same query in Kibana to rule out an issue with NEST. And in Kibana I'm getting exactly the same error.

The error:

buckets_path must reference either a number value or a single value numeric metric aggregation, got: org.elasticsearch.search.aggregations.metrics.scripted.InternalScriptedMetric

My code:

```<code>ISearchResponse<LogItem> aggregationResponse = await client.SearchAsync<LogItem>(s => s
    .Size(0)
    .Type("errordoc")
    .Query(...)
    .Aggregations(a => a
    .Terms("Hash", st => st
        .Field(o => o.messageHash.Suffix("keyword")).OrderDescending("Avg-Score")
            .Aggregations(aa => aa
                .Terms("Friendly", ff => ff
                    .Field(oo => oo.friendly.Suffix("keyword"))
                )
                .Max("Max-DateTime", ff => ff
                    .Field(oo => oo.dateTimeStamp)
                )
                .Average("Avg-Score", sc => sc
                    .Script("_score")
                )
                .ScriptedMetric("Urgency-Level", sm => sm
                    .InitScript(i => i.Inline("params._agg.data = []").Lang("painless"))
                    .MapScript(i => i.Inline("params._agg.data.add(doc.urgency.value)").Lang("painless"))
                    .CombineScript(i => i.Inline("int urgency = 0; for (u in params._agg.data) { urgency += u } return urgency").Lang("painless"))
                    .ReduceScript(i =>i.Inline("int urgency = 0; for (a in params._aggs) { urgency += a } return urgency").Lang("painless"))
                )
                .BucketScript("finalScore", scb => scb
                    .BucketsPath(bp => bp
                        .Add("maxDateTime", "Max-DateTime")
                        .Add("avgScore", "Avg-Score")
                        .Add("urgencyLevel", "Urgency-Level")
                    )
                    .Script(i => i.Inline("params.avgScore").Lang("painless"))
                )
            )
       )
    )
);
</code>```

The ScriptedMetric aggregation is returning an 11 with my data set.

Am I doing something wrong? Or Is this not possible? If not possible, what would be an alternative?

Also, I know this ScriptedMetric does pretty much do what a Sum would do, but that's going to change of course...

Index mapping:

```<code>PUT /live
{
  "mappings": {
    "errordoc": {
      "properties": {
        "urgency": {
          "type": "integer"
        },
        "dateTimeStamp": {
          "type": "date",
          "format": "MM/dd/yyyy hh:mm:ss a"
        }      }
    }
  }
}
</code>```

Test data:

```<code>POST /live/errordoc
{ "messageID": "M111111", "messageHash": "1463454562\/-1210136287\/-1885530817\/-275007043\/-57589585", "friendly": "0", "urgency": "1", "organisation": "Organisation Name", "Environment": "ENV02", "Task": "TASK01", "Action": "A12", "dateTimeStamp": "11\/29\/2017 10:24:21 AM", "machineName": "DESKTOP-SMOM9R9", "parameters": "{ " }
</code>```

Copy this document a couple of times, maybe changing the urgency/dateTimeStamp, as long as the Hash stays the same it should reproduce my environment...

答:
Somebody on the Elasticsearch forums replied after I created 2 GitHub issues...
I did try everything, including this solution, but I must have done something else wrong during that try... Well whatever...

The solution

Change:

```<code>.Add("urgencyLevel", "Urgency-Level")
</code>```

to:

```<code>.Add("urgencyLevel", "Urgency-Level.value")
</code>```

Body:
I should work since the ScriptedMetric is a metric, and it does return a single numeric value, but I can't get it to work.

I'm using NEST (5.5.0 via NuGet, I'm targeting Elasticsearch 6.0.0) in C# to get it to work, I did however also try building the same query in Kibana to rule out an issue with NEST. And in Kibana I'm getting exactly the same error.

The error:

buckets_path must reference either a number value or a single value numeric metric aggregation, got: org.elasticsearch.search.aggregations.metrics.scripted.InternalScriptedMetric

My code:

ISearchResponse<LogItem> aggregationResponse = await client.SearchAsync<LogItem>(s => s
    .Size(0)
    .Type("errordoc")
    .Query(...)
    .Aggregations(a => a
    .Terms("Hash", st => st
        .Field(o => o.messageHash.Suffix("keyword")).OrderDescending("Avg-Score")
            .Aggregations(aa => aa
                .Terms("Friendly", ff => ff
                    .Field(oo => oo.friendly.Suffix("keyword"))
                )
                .Max("Max-DateTime", ff => ff
                    .Field(oo => oo.dateTimeStamp)
                )
                .Average("Avg-Score", sc => sc
                    .Script("_score")
                )
                .ScriptedMetric("Urgency-Level", sm => sm
                    .InitScript(i => i.Inline("params._agg.data = []").Lang("painless"))
                    .MapScript(i => i.Inline("params._agg.data.add(doc.urgency.value)").Lang("painless"))
                    .CombineScript(i => i.Inline("int urgency = 0; for (u in params._agg.data) { urgency += u } return urgency").Lang("painless"))
                    .ReduceScript(i =>i.Inline("int urgency = 0; for (a in params._aggs) { urgency += a } return urgency").Lang("painless"))
                )
                .BucketScript("finalScore", scb => scb
                    .BucketsPath(bp => bp
                        .Add("maxDateTime", "Max-DateTime")
                        .Add("avgScore", "Avg-Score")
                        .Add("urgencyLevel", "Urgency-Level")
                    )
                    .Script(i => i.Inline("params.avgScore").Lang("painless"))
                )
            )
       )
    )
);

The ScriptedMetric aggregation is returning an 11 with my data set.

Am I doing something wrong? Or Is this not possible? If not possible, what would be an alternative?

Also, I know this ScriptedMetric does pretty much do what a Sum would do, but that's going to change of course...

Index mapping:

PUT /live
{
  "mappings": {
    "errordoc": {
      "properties": {
        "urgency": {
          "type": "integer"
        },
        "dateTimeStamp": {
          "type": "date",
          "format": "MM/dd/yyyy hh:mm:ss a"
        }      }
    }
  }
}

Test data:

POST /live/errordoc
{ "messageID": "M111111", "messageHash": "1463454562\/-1210136287\/-1885530817\/-275007043\/-57589585", "friendly": "0", "urgency": "1", "organisation": "Organisation Name", "Environment": "ENV02", "Task": "TASK01", "Action": "A12", "dateTimeStamp": "11\/29\/2017 10:24:21 AM", "machineName": "DESKTOP-SMOM9R9", "parameters": "{ " }

Copy this document a couple of times, maybe changing the urgency/dateTimeStamp, as long as the Hash stays the same it should reproduce my environment...

Body:
Somebody on the Elasticsearch forums replied after I created 2 GitHub issues...
I did try everything, including this solution, but I must have done something else wrong during that try... Well whatever...

The solution

Change:

.Add("urgencyLevel", "Urgency-Level")

to:

.Add("urgencyLevel", "Urgency-Level.value")