问:
Cucumber Undefined Step, Though Defined Using IntelliJ
I'm trying to run a .feature file to test a simple RESTEasy web application: https://github.com/dashorst/jaxrs-quickstart-resteasy.

However, the IntelliJ keeps saying that:

```<code>Undefined step: Given  I am an invalid username

Undefined step: When  I perform a hello request with null username

Undefined step: Then  I receive a http response code of 400

Undefined step: When  I perform a hello request with empty username

Undefined step: Then  I receive a http response code of 400

You can implement missing steps with the snippets below:

@Given("^I am an invalid username$")
public void I_am_an_invalid_username() throws Throwable {
    // Express the Regexp above with the code you wish you had
    throw new PendingException();
}
// similar results...
</code>```

Below is my hello.feature file:

```<code>Feature: hello

#-------------------------------------
#next block is got the GET entry point
#-------------------------------------

#verify that with malformed input hello fails
Scenario: invalid username should fail
Given I am an invalid username
When I perform a hello request with null username
Then I receive a http response code of 400
When I perform a hello request with empty username
Then I receive a http response code of 400

#verify that you can get correct hello response with valid username. This is the 'everything works fine' path.
Scenario: User can get correct hello response with valid username
Given I am a valid username
When I perform a hello request with valid username
Then I receive a http response code of 200

import cucumber.annotation.en.Given;
import cucumber.annotation.en.Then;
import cucumber.annotation.en.When;
import cucumber.runtime.PendingException;
</code>```

I used IntelliJ option "generate steps" and got the MyStepdefs file.

```<code>/**
 * Created by z on 5/21/17.
 */
public class MyStepdefs {
    @Given("^I am a valid username$")
    public void iAmAValidUsername() throws Throwable {
        // Write code here that turns the phrase above into concrete actions
        throw new PendingException();
    }

    @Given("^I am an invalid username$")
    public void iAmAnInvalidUsername() throws Throwable {
        // Write code here that turns the phrase above into concrete actions
        throw new PendingException();
    }

    @When("^I perform a hello request with null username$")
    public void iPerformAHelloRequestWithNullUsername() throws Throwable {
        // Write code here that turns the phrase above into concrete actions
        throw new PendingException();
    }

    @Then("^I receive a http response code of (\\d+)$")
    public void iReceiveAHttpResponseCodeOf(int arg0) throws Throwable {
        // Write code here that turns the phrase above into concrete actions
        throw new PendingException();
    }

    @When("^I perform a hello request with empty username$")
    public void iPerformAHelloRequestWithEmptyUsername() throws Throwable {
        // Write code here that turns the phrase above into concrete actions
        throw new PendingException();
    }

    @When("^I perform a hello request with valid username$")
    public void iPerformAHelloRequestWithValidUsername() throws Throwable {
        // Write code here that turns the phrase above into concrete actions
        throw new PendingException();
    }
}
</code>```

I had tried to specify glue path for each scenario, but it doesn't work. I'm not sure what went run. Thanks for any advice!

I have looked into several existing questions but none of them helps:

Cucumber: undefined step, although step should be defined

Cucumber JVM undefined step

This is my project structure:

答:
Sometimes it happens when there are saved references to the old names of the packages. If the packages have been renamed you should check if there are references to the old names (Cucumber Run/Debug Configurations) and delete them.

Kind regards

Body:
I'm trying to run a .feature file to test a simple RESTEasy web application: https://github.com/dashorst/jaxrs-quickstart-resteasy.

However, the IntelliJ keeps saying that:

Undefined step: Given  I am an invalid username

Undefined step: When  I perform a hello request with null username

Undefined step: Then  I receive a http response code of 400

Undefined step: When  I perform a hello request with empty username

Undefined step: Then  I receive a http response code of 400

You can implement missing steps with the snippets below:

@Given("^I am an invalid username$")
public void I_am_an_invalid_username() throws Throwable {
    // Express the Regexp above with the code you wish you had
    throw new PendingException();
}
// similar results...

Below is my hello.feature file:

Feature: hello

#-------------------------------------
#next block is got the GET entry point
#-------------------------------------

#verify that with malformed input hello fails
Scenario: invalid username should fail
Given I am an invalid username
When I perform a hello request with null username
Then I receive a http response code of 400
When I perform a hello request with empty username
Then I receive a http response code of 400

#verify that you can get correct hello response with valid username. This is the 'everything works fine' path.
Scenario: User can get correct hello response with valid username
Given I am a valid username
When I perform a hello request with valid username
Then I receive a http response code of 200

import cucumber.annotation.en.Given;
import cucumber.annotation.en.Then;
import cucumber.annotation.en.When;
import cucumber.runtime.PendingException;

I used IntelliJ option "generate steps" and got the MyStepdefs file.

/**
 * Created by z on 5/21/17.
 */
public class MyStepdefs {
    @Given("^I am a valid username$")
    public void iAmAValidUsername() throws Throwable {
        // Write code here that turns the phrase above into concrete actions
        throw new PendingException();
    }

    @Given("^I am an invalid username$")
    public void iAmAnInvalidUsername() throws Throwable {
        // Write code here that turns the phrase above into concrete actions
        throw new PendingException();
    }

    @When("^I perform a hello request with null username$")
    public void iPerformAHelloRequestWithNullUsername() throws Throwable {
        // Write code here that turns the phrase above into concrete actions
        throw new PendingException();
    }

    @Then("^I receive a http response code of (\\d+)$")
    public void iReceiveAHttpResponseCodeOf(int arg0) throws Throwable {
        // Write code here that turns the phrase above into concrete actions
        throw new PendingException();
    }

    @When("^I perform a hello request with empty username$")
    public void iPerformAHelloRequestWithEmptyUsername() throws Throwable {
        // Write code here that turns the phrase above into concrete actions
        throw new PendingException();
    }

    @When("^I perform a hello request with valid username$")
    public void iPerformAHelloRequestWithValidUsername() throws Throwable {
        // Write code here that turns the phrase above into concrete actions
        throw new PendingException();
    }
}

I had tried to specify glue path for each scenario, but it doesn't work. I'm not sure what went run. Thanks for any advice!

I have looked into several existing questions but none of them helps:

Cucumber: undefined step, although step should be defined

Cucumber JVM undefined step

This is my project structure:


来源: stackexchange

问:
MS CRM 2011 CSV import (programatically)
How do I do that?

I need to import (and map) a CSV file to a custom entity in CRM 2011.

I am running an on-premise instance of CRM 2011 and need to use the late bound entities approach.

I have already tried following this example: Export and import a data map but failed miserably (ImportMap not found - what assembly is it in?).

答:
ImportMap is an entity in CRM rather than a class in the SDK Assemblies.  To get that example code to compile you'll need to have a class that represents the ImportMap entity, which is the early-bound model of CRM programming.

You can find the class ImportMap in the file MyOrganizationCrmSdkTypes.cs in the SDK. Adding that file to your project will give you early bound classes for all the out-of-box entities. Alternatively, you could use CrmSvcUtil (included with the SDK), or a 3rd party tool (such as Daryl Labar's or XrmToolkit) to generate just the ImportMap early-bound class.

ContentLicense: CC BY-SA 3.0


问:
how to generically compare entire java beans?
I've been trying to grok the org.apache.commons.beanutils library for a method/idiom to evaluate for equality all properties between 2 instances i.e. a generic equals() method for beans.

Is there a simple way to do this usnig this library? Or am I going about this the wrong way?
Thanks.

答:
To answer your question directly, you could use reflection to do equality checking of beans. There are a few snags you need to be aware of.

There are rules regarding the behaviour of equals() and hashcode(). These rules talk about symmetry, consitency and reflexiveness which may be hard to do when your equals method behaves dynamically based on the other object you're passing in.

Interesting read:
http://www.geocities.com/technofundo/tech/java/equalhash.html

Generally speaking, I think you are better off creating your own hashcode and equals methods. There are a fwe good plugins which can automatically generate that code for you based on the class properties.

Having said all this, here are some (old style) methods for getting getters, setters and properties I wrote a long time ago:

```<code>private Map getPrivateFields(Class clazz, Map getters, Map setters) {
    Field[] fields = clazz.getDeclaredFields();
    Map m = new HashMap();
    for (int i = 0; i < fields.length; i++) {
        int modifiers = fields[i].getModifiers();
        if (Modifier.isPrivate(modifiers) && !Modifier.isStatic(modifiers) && !Modifier.isFinal(modifiers)) {
            String propName = fields[i].getName();
            if (getters.get(propName) != null && setters.get(propName) != null) {
                m.put(fields[i].getName(), fields[i]);
            }
        }
    }
    return m;
}
</code>```

The Getters:

```<code>private Map getGetters(Class clazz) {
    Method[] methods = clazz.getMethods();
    Map m = new HashMap();
    for (int i = 0; i < methods.length; i++) {
        if (methods[i].getName().startsWith("get")) {
            int modifiers = methods[i].getModifiers();
            if (validAccessMethod(modifiers)) {
                m.put(getPropertyName(methods[i].getName()), methods[i]);
            }
        }
    }
    return m;
}
</code>```

And the Setters:

```<code>private Map getSetters(Class clazz, Map getters) {
    Method[] methods = clazz.getMethods();
    Map m = new HashMap();
    for (int i = 0; i < methods.length; i++) {
        if (methods[i].getName().startsWith("set")) {
            int modifiers = methods[i].getModifiers();
            String propName = getPropertyName(methods[i].getName());
            Method getter = (Method) getters.get(propName);

            if (validAccessMethod(modifiers) && getter != null) {
                Class returnType = getter.getReturnType();
                Class setType = methods[i].getParameterTypes()[0];
                int numTypes = methods[i].getParameterTypes().length;

                if (returnType.equals(setType) && numTypes == 1) {
                    m.put(propName, methods[i]);
                }
            }
        }
    }
    return m;
}
</code>```

Maybe you can use this to roll your own.

Edit: Ofcourse the reflectionbuilder in Aaron Digulla's answer is much better than my handywork.

ContentLicense: CC BY-SA 2.5

Body:
To answer your question directly, you could use reflection to do equality checking of beans. There are a few snags you need to be aware of.

There are rules regarding the behaviour of equals() and hashcode(). These rules talk about symmetry, consitency and reflexiveness which may be hard to do when your equals method behaves dynamically based on the other object you're passing in.

Interesting read:
http://www.geocities.com/technofundo/tech/java/equalhash.html

Generally speaking, I think you are better off creating your own hashcode and equals methods. There are a fwe good plugins which can automatically generate that code for you based on the class properties.

Having said all this, here are some (old style) methods for getting getters, setters and properties I wrote a long time ago:

private Map getPrivateFields(Class clazz, Map getters, Map setters) {
    Field[] fields = clazz.getDeclaredFields();
    Map m = new HashMap();
    for (int i = 0; i < fields.length; i++) {
        int modifiers = fields[i].getModifiers();
        if (Modifier.isPrivate(modifiers) && !Modifier.isStatic(modifiers) && !Modifier.isFinal(modifiers)) {
            String propName = fields[i].getName();
            if (getters.get(propName) != null && setters.get(propName) != null) {
                m.put(fields[i].getName(), fields[i]);
            }
        }
    }
    return m;
}

The Getters:

private Map getGetters(Class clazz) {
    Method[] methods = clazz.getMethods();
    Map m = new HashMap();
    for (int i = 0; i < methods.length; i++) {
        if (methods[i].getName().startsWith("get")) {
            int modifiers = methods[i].getModifiers();
            if (validAccessMethod(modifiers)) {
                m.put(getPropertyName(methods[i].getName()), methods[i]);
            }
        }
    }
    return m;
}

And the Setters:

private Map getSetters(Class clazz, Map getters) {
    Method[] methods = clazz.getMethods();
    Map m = new HashMap();
    for (int i = 0; i < methods.length; i++) {
        if (methods[i].getName().startsWith("set")) {
            int modifiers = methods[i].getModifiers();
            String propName = getPropertyName(methods[i].getName());
            Method getter = (Method) getters.get(propName);

            if (validAccessMethod(modifiers) && getter != null) {
                Class returnType = getter.getReturnType();
                Class setType = methods[i].getParameterTypes()[0];
                int numTypes = methods[i].getParameterTypes().length;

                if (returnType.equals(setType) && numTypes == 1) {
                    m.put(propName, methods[i]);
                }
            }
        }
    }
    return m;
}

Maybe you can use this to roll your own.

Edit: Ofcourse the reflectionbuilder in Aaron Digulla's answer is much better than my handywork.

OwnerDisplayName: Rolf

LastEditorDisplayName: Rolf


问:
Getting 404 error while call oAuth2 api in the browser
I used ruby on rails to make RESTful api and also used doorkeeper to handle authentication and authorization. As you know the doorkeeper generate some OAuth2 api's and the two of the them that i need to use is /users which is the post request and /oauth/token that make token for me. The api that i make which are post, get, put works greate in postman and android studio and web browser.
But the post api /users and /oauth/token which generated by the doorkeeper doesn't work in web browser but works great on android studio and postman.
That was confused for me. The error that i take while calling this api is 404, I checked the ruby production log on the server and it says no route match. The string thing here is that the type of method and routes is correct.

This is the code that i used in the reactjs. i used axios:

```<code>var url="http://x.x.x.x/oauth/token";
    axios.post(url,{
        "username":"1",
        "password":"password",
        "grant_type":"password"
      },{headers:{"Content-Type":"application/json"}}).then( (response) => {
          console.log(response.data);
        })
        .catch( (error) => {
          console.log(JSON.stringify(error));
        });
</code>```

And also used raw jQuery to make request and get the same error. all my api works well execpt this two api:

```<code>var firstname = document.forms["registerForm"]["first_name"].value;
    var lastname = document.forms["registerForm"]["last_name"].value;
    var pass = document.forms["registerForm"]["password"].value;
    var passconfirm = document.forms["registerForm"]["password_confirmation"].value;

    var json_data = {
        "async": true,
        "crossDomain": true,
        "url": send,
        "method": "POST",
        "headers": {
            "content-type": "application/json",
        },
        "processData": false,
        "data":
        {
            "user": {
                "user_name": username,
                "password": pass,
                "password_confirmation": passconfirm,
                "user_type": "admin"
            },
            "profile": {
                "first_name": firstname,
                "last_name": lastname
            }
        }
    }

    $.ajax(json_data).done(function (response) {
        console.log(response);
    });
    console.log(json_data['data']);
    console.log(username);
</code>```

the output of this code console.log(JSON.stringify(error)); is this:

```<code>{"config":{"transformRequest":{},"transformResponse":{},"timeout":0,"xsrfCookieName":"XSRF-TOKEN","xsrfHeaderName":"X-XSRF-TOKEN","maxContentLength":-1,"headers":{"Accept":"application/json, text/plain, */*","Content-Type":"application/json;charset=utf-8"},"method":"post","url":"http://x.x.x.x/oauth/token.json","data":"{\"username\":\"1\",\"password\":\"password\",\"grant_type\":\"password\"}"},"request":{}}
</code>```

I find the request header and response header into the browser:

```<code>Response Header:

Content-Type
application/json; charset=UTF-8
Content-Length
34
Connection
keep-alive
Status
404 Not Found
X-Request-Id
d593b73f-eec8-41cd-95cd-e4459663358c
X-Runtime
0.002108
Date
Mon, 13 Nov 2017 11:19:26 GMT
X-Powered-By
Phusion Passenger 5.1.11
Server
nginx/1.12.1 + Phusion Passenger 5.1.11

Request headers (427 B)
Host
x.x.x.x
User-Agent
Mozilla/5.0 (X11; Ubuntu; Linu…) Gecko/20100101 Firefox/56.0
Accept
text/html,application/xhtml+xm…plication/xml;q=0.9,*/*;q=0.8
Accept-Language
en-US,en;q=0.5
Accept-Encoding
gzip, deflate
Access-Control-Request-Method
POST
Access-Control-Request-Headers
Origin
http://localhost:3000
Connection
keep-alive
</code>```

答: You need to configure in your OAuth settings to allow access to client web app. Check logs or error message which you get in api response.</p>

Body:
I used ruby on rails to make RESTful api and also used doorkeeper to handle authentication and authorization. As you know the doorkeeper generate some OAuth2 api's and the two of the them that i need to use is /users which is the post request and /oauth/token that make token for me. The api that i make which are post, get, put works greate in postman and android studio and web browser.
But the post api /users and /oauth/token which generated by the doorkeeper doesn't work in web browser but works great on android studio and postman.
That was confused for me. The error that i take while calling this api is 404, I checked the ruby production log on the server and it says no route match. The string thing here is that the type of method and routes is correct.

This is the code that i used in the reactjs. i used axios:

var url="http://x.x.x.x/oauth/token";
    axios.post(url,{
        "username":"1",
        "password":"password",
        "grant_type":"password"
      },{headers:{"Content-Type":"application/json"}}).then( (response) => {
          console.log(response.data);
        })
        .catch( (error) => {
          console.log(JSON.stringify(error));
        });

And also used raw jQuery to make request and get the same error. all my api works well execpt this two api:

var firstname = document.forms["registerForm"]["first_name"].value;
    var lastname = document.forms["registerForm"]["last_name"].value;
    var pass = document.forms["registerForm"]["password"].value;
    var passconfirm = document.forms["registerForm"]["password_confirmation"].value;

    var json_data = {
        "async": true,
        "crossDomain": true,
        "url": send,
        "method": "POST",
        "headers": {
            "content-type": "application/json",
        },
        "processData": false,
        "data":
        {
            "user": {
                "user_name": username,
                "password": pass,
                "password_confirmation": passconfirm,
                "user_type": "admin"
            },
            "profile": {
                "first_name": firstname,
                "last_name": lastname
            }
        }
    }

    $.ajax(json_data).done(function (response) {
        console.log(response);
    });
    console.log(json_data['data']);
    console.log(username);

the output of this code console.log(JSON.stringify(error)); is this:

{"config":{"transformRequest":{},"transformResponse":{},"timeout":0,"xsrfCookieName":"XSRF-TOKEN","xsrfHeaderName":"X-XSRF-TOKEN","maxContentLength":-1,"headers":{"Accept":"application/json, text/plain, */*","Content-Type":"application/json;charset=utf-8"},"method":"post","url":"http://x.x.x.x/oauth/token.json","data":"{\"username\":\"1\",\"password\":\"password\",\"grant_type\":\"password\"}"},"request":{}}

I find the request header and response header into the browser:

Response Header:

Content-Type
application/json; charset=UTF-8
Content-Length
34
Connection
keep-alive
Status
404 Not Found
X-Request-Id
d593b73f-eec8-41cd-95cd-e4459663358c
X-Runtime
0.002108
Date
Mon, 13 Nov 2017 11:19:26 GMT
X-Powered-By
Phusion Passenger 5.1.11
Server
nginx/1.12.1 + Phusion Passenger 5.1.11

Request headers (427 B)
Host
x.x.x.x
User-Agent
Mozilla/5.0 (X11; Ubuntu; Linu…) Gecko/20100101 Firefox/56.0
Accept
text/html,application/xhtml+xm…plication/xml;q=0.9,*/*;q=0.8
Accept-Language
en-US,en;q=0.5
Accept-Encoding
gzip, deflate
Access-Control-Request-Method
POST
Access-Control-Request-Headers
Origin
http://localhost:3000
Connection
keep-alive


问:
Chrome webdriver send keys does not send '3'
For some reason, I am unable to write character '3' into the input element on the page.

This code:

```<code>    chrome_options = Options()
    chrome_options.add_argument('--dns-prefetch-disable')
    chrome_options.add_argument('--no-proxy-server')
    chromeDriverPath = self.getChromeDriverPath()
    os.environ["webdriver.chrome.driver"] = chromeDriverPath
    self.driver = webdriver.Chrome(chromeDriverPath, chrome_options=chrome_options)

    self.driver.get(self.loginUrl)
    login = self.driver.find_element_by_id('login_credit')
    login.send_keys("12345")
</code>```

results in "1245" being written in the login input...
Can someone help please?
I use python 2.7, the latest chrome and the latest chromedriver

EDIT:

```<code>login.send_keys("3")

login.send_keys("\3")
</code>```

don't work either.

```<code>login.send_keys("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()")
</code>```

- only the "3" was missing in the string...

what worked was

```<code>login.send_keys(Keys.NUMPAD3)
</code>```

as Andersson suggested below, but this is not a solution.

I tried it in the google search box and I experienced the same behaviour.

答:
Instead of using send_keys("12345") you can use any of the alternatives mentioned below :

Use Keys.NUMPAD3 :

```<code>login.send_keys(Keys.NUMPAD3)
</code>```

Use JavascriptExecutor with getElementById :

```<code>self.driver.execute_script("document.getElementById('login_credit').value='12345'")
</code>```

Use JavascriptExecutor with getElementsById :

```<code>self.driver.execute_script("document.getElementsById('login_credit')[0].value='12345'")
</code>```

Body:
For some reason, I am unable to write character '3' into the input element on the page.

This code:

    chrome_options = Options()
    chrome_options.add_argument('--dns-prefetch-disable')
    chrome_options.add_argument('--no-proxy-server')
    chromeDriverPath = self.getChromeDriverPath()
    os.environ["webdriver.chrome.driver"] = chromeDriverPath
    self.driver = webdriver.Chrome(chromeDriverPath, chrome_options=chrome_options)

    self.driver.get(self.loginUrl)
    login = self.driver.find_element_by_id('login_credit')
    login.send_keys("12345")

results in "1245" being written in the login input...
Can someone help please?
I use python 2.7, the latest chrome and the latest chromedriver

EDIT:

login.send_keys("3")

login.send_keys("\3")

don't work either.

login.send_keys("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()")

- only the "3" was missing in the string...

what worked was

login.send_keys(Keys.NUMPAD3)

as Andersson suggested below, but this is not a solution.

I tried it in the google search box and I experienced the same behaviour.

Body:
Instead of using send_keys("12345") you can use any of the alternatives mentioned below :

Use Keys.NUMPAD3 :

login.send_keys(Keys.NUMPAD3)

Use JavascriptExecutor with getElementById :

self.driver.execute_script("document.getElementById('login_credit').value='12345'")

Use JavascriptExecutor with getElementsById :

self.driver.execute_script("document.getElementsById('login_credit')[0].value='12345'")


问:
How can i change the background color of my toast
I have added a toast in my project using the below code in my newrecord.ts

```<code>constructor(private toastCtrl: ToastController,
    private _listProduct : ListproductService,
    private _deleteProduct : DeleteProductService,
    public navCtrl: NavController,public navParams: NavParams,
    public loadingCtrl: LoadingController,
    private datePipe: DatePipe) {
        this.loading = this.loadingCtrl.create({
                            content: 'Please wait...'
                        });

        this.mytoast = this.toastCtrl.create({
                            message: 'Data loaded successfully',
                            duration: 3000,
                            position: 'top'
                        });

        this.initializeItems();
}
</code>```

and inside ngOnInit() I have called my toast like this this.mytoast.present();

It is working perfectly fine but instead of black can I use any other background color for my toast?

I have read cssClass property but I don't know how to use it

答:
You could define another background color by overriding a Ionic Sass Variables in your variables.scss

In case of toast background you could define for example white or #ffffff like following:

```<code>$toast-ios-background: #ffffff; // Apply for iOS
$toast-md-background: #ffffff; // Apply for Android
$toast-wp-background: white; // Apply for Windows
</code>```

You could find the all list of sass variables you could override in the documentation:

https://ionicframework.com/docs/theming/overriding-ionic-variables/

In case you would like even more flexibility or to set other styles, you could set a custom css property to your toast with the cssClass option

For example:

```<code> this.mytoast = this.toastCtrl.create({
                        message: 'Data loaded successfully',
                        duration: 3000,
                        position: 'top',
                        cssClass: 'myCustomCss'
                    });
</code>```

Then you could modify it in your stylesheets, like in app.component.scss

```<code>.myCustomCss {
    // The styles you would like to apply
 }
</code>```

See ToastController API documentation:

https://ionicframework.com/docs/api/components/toast/ToastController/

But when it goes to the background of the toast, first try with the variables ;)

Body:
I have added a toast in my project using the below code in my newrecord.ts

constructor(private toastCtrl: ToastController,
    private _listProduct : ListproductService,
    private _deleteProduct : DeleteProductService,
    public navCtrl: NavController,public navParams: NavParams,
    public loadingCtrl: LoadingController,
    private datePipe: DatePipe) {
        this.loading = this.loadingCtrl.create({
                            content: 'Please wait...'
                        });

        this.mytoast = this.toastCtrl.create({
                            message: 'Data loaded successfully',
                            duration: 3000,
                            position: 'top'
                        });

        this.initializeItems();
}

and inside ngOnInit() I have called my toast like this this.mytoast.present();

It is working perfectly fine but instead of black can I use any other background color for my toast?

I have read cssClass property but I don't know how to use it

Body:
You could define another background color by overriding a Ionic Sass Variables in your variables.scss

In case of toast background you could define for example white or #ffffff like following:

$toast-ios-background: #ffffff; // Apply for iOS
$toast-md-background: #ffffff; // Apply for Android
$toast-wp-background: white; // Apply for Windows

You could find the all list of sass variables you could override in the documentation:

https://ionicframework.com/docs/theming/overriding-ionic-variables/

In case you would like even more flexibility or to set other styles, you could set a custom css property to your toast with the cssClass option

For example:

 this.mytoast = this.toastCtrl.create({
                        message: 'Data loaded successfully',
                        duration: 3000,
                        position: 'top',
                        cssClass: 'myCustomCss'
                    });

Then you could modify it in your stylesheets, like in app.component.scss

.myCustomCss {
    // The styles you would like to apply
 }

See ToastController API documentation:

https://ionicframework.com/docs/api/components/toast/ToastController/

But when it goes to the background of the toast, first try with the variables ;)


问:
Can you help me with linear activation of my Simple Classifier Neural Network in pyBrain?
I'm trying a very simple case using a Python library called pyBrain
and I can't get it to work.  There is likely to be a very simple
reason, so, I hope someone can help!

1) A simple XOR works fine.

2) Classifying the led's displayed on a digital clock to the numerical
output value works fine.

e.g.

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

3) Classifying a numerical value to the led output to drive a digital display doesn't work.

e.g.

```<code>[ 0.] => [ 1.  1.  1.  0.  1.  1.  1.]
</code>```

etc etc (as above but reversed).

I'm using a simple linear activator with 10 inputs, 1 output and i've tried >12 neurons in the hidden layer.

My confusion is that, shouldn't the network be able to remember the pattern with 10 neurons in the hidden layer?

I'm sure there is something obvious I'm missing, so, please feel free to enlighten my stupidity!

答:
I think rather than SO, MetaOptimize might help you more.

I had taken only an introductory class in ML. But from what I remember, neural networks work for many problems, but they are like black boxes. If they do not work, it is difficult to determine why they are not working. Specifically, there are no specific rules as to the number of nodes in the hidden layer (there are rules of thumb for some problems).

Body:
I'm trying a very simple case using a Python library called pyBrain
and I can't get it to work.  There is likely to be a very simple
reason, so, I hope someone can help!

1) A simple XOR works fine.

2) Classifying the led's displayed on a digital clock to the numerical
output value works fine.

e.g.

[ 1.  1.  1.  0.  1.  1.  1.] => [ 0.]
[ 0.  0.  1.  0.  0.  1.  0.] => [ 1.]
[ 1.  0.  1.  1.  1.  0.  1.] => [ 2.]
[ 1.  0.  1.  1.  0.  1.  1.] => [ 3.]
[ 0.  1.  1.  1.  0.  1.  0.] => [ 4.]
[ 1.  1.  0.  1.  0.  1.  1.] => [ 5.]
[ 1.  1.  0.  1.  1.  1.  1.] => [ 6.]
[ 1.  0.  1.  0.  0.  1.  0.] => [ 7.]
[ 1.  1.  1.  1.  1.  1.  1.] => [ 8.]
[ 1.  1.  1.  1.  0.  1.  1.] => [ 9.]

3) Classifying a numerical value to the led output to drive a digital display doesn't work.

e.g.

[ 0.] => [ 1.  1.  1.  0.  1.  1.  1.]

etc etc (as above but reversed).

I'm using a simple linear activator with 10 inputs, 1 output and i've tried >12 neurons in the hidden layer.

My confusion is that, shouldn't the network be able to remember the pattern with 10 neurons in the hidden layer?

I'm sure there is something obvious I'm missing, so, please feel free to enlighten my stupidity!


问:
*.default is not a constructor, with a imported js plugin
I tried to create a simple form validation and registered this via yarn link in a example project to test the set up. But it absolutely doesn't work and I have no idea how to continue.

```<code>export default class Proofr {
  constructor() {
    console.log('test');
  }
}
</code>```

This "script" is then generated by webpack, with eslint-loader and babel-loader (presets env & stage-0).

So it shouldn't do much more than just for fun logging a message. But in when i try to call new Proofr() it tells me following:

```<code> form.js:25 Uncaught TypeError: _proofr2.default is not a constructor
</code>```

But if it is not a constructor what is ithen? It is a empty object, at least this is what the crome dev tools say.
I import proofr which is linked via yarn link with my project in a js file.

```<code>import Proofr from 'proofr';

import PinguComponent from '../../assets/js/helpers/PinguComponent';

class Form extends PinguComponent {
  constructor(el) {
    const defaultOpts = {
      classes: {
        dom: {},
        state: {},
      },
      customEvents: {},
    };

    const defaultData = {};

    super(el, defaultOpts, defaultData);

    new Proofr();

    this.log('Form loaded');
  }
}

export default Form;
</code>```

So am at the end of my knowledge, maybe someone sees the most possibly very small typo. Both repositories use the same babelrc so they use the same presets.

Here the by webpack and babel generated file for proofr

```<code>/******/ (function(modules) { // webpackBootstrap
/******/    // The module cache
/******/    var installedModules = {};
/******/
/******/    // The require function
/******/    function __webpack_require__(moduleId) {
/******/
/******/        // Check if module is in cache
/******/        if(installedModules[moduleId]) {
/******/            return installedModules[moduleId].exports;
/******/        }
/******/        // Create a new module (and put it into the cache)
/******/        var module = installedModules[moduleId] = {
/******/            i: moduleId,
/******/            l: false,
/******/            exports: {}
/******/        };
/******/
/******/        // Execute the module function
/******/        modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/        // Flag the module as loaded
/******/        module.l = true;
/******/
/******/        // Return the exports of the module
/******/        return module.exports;
/******/    }
/******/
/******/
/******/    // expose the modules object (__webpack_modules__)
/******/    __webpack_require__.m = modules;
/******/
/******/    // expose the module cache
/******/    __webpack_require__.c = installedModules;
/******/
/******/    // define getter function for harmony exports
/******/    __webpack_require__.d = function(exports, name, getter) {
/******/        if(!__webpack_require__.o(exports, name)) {
/******/            Object.defineProperty(exports, name, {
/******/                configurable: false,
/******/                enumerable: true,
/******/                get: getter
/******/            });
/******/        }
/******/    };
/******/
/******/    // getDefaultExport function for compatibility with non-harmony modules
/******/    __webpack_require__.n = function(module) {
/******/        var getter = module && module.__esModule ?
/******/            function getDefault() { return module['default']; } :
/******/            function getModuleExports() { return module; };
/******/        __webpack_require__.d(getter, 'a', getter);
/******/        return getter;
/******/    };
/******/
/******/    // Object.prototype.hasOwnProperty.call
/******/    __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/    // __webpack_public_path__
/******/    __webpack_require__.p = "";
/******/
/******/    // Load entry module and return exports
/******/    return __webpack_require__(__webpack_require__.s = 0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

/**
 * Proofr a lightweight js tool
 */

var Proofr = function Proofr() {
  _classCallCheck(this, Proofr);

  console.log('test');
};

exports.default = Proofr;

/***/ })
/******/ ]);
</code>```

If you want to see it by yourself you can add it via npm install proofr (or yarn proofr)

答:
Change the webpack build configuration of your proofr library by setting output.libraryTarget to umd:

```<code>output: {
  filename: '[name]',
  path: path.resolve(__dirname, '../dist'),
  libraryTarget: "umd"
},
</code>```

See https://webpack.js.org/configuration/output/#output-librarytarget for more options.

I tested this by rebuilding proofr with npm run start and imported it in a node.js script:

```<code>var proofr = require('proofr');
console.log(proofr);
</code>```

Without output.libraryTarget: "umd":

```<code>$ node index.js
{}
</code>```

With it:

```<code>$ node index.js
{ default: [Function: Proofr] }
</code>```

Body:
I tried to create a simple form validation and registered this via yarn link in a example project to test the set up. But it absolutely doesn't work and I have no idea how to continue.

export default class Proofr {
  constructor() {
    console.log('test');
  }
}

This "script" is then generated by webpack, with eslint-loader and babel-loader (presets env & stage-0).

So it shouldn't do much more than just for fun logging a message. But in when i try to call new Proofr() it tells me following:

 form.js:25 Uncaught TypeError: _proofr2.default is not a constructor

But if it is not a constructor what is ithen? It is a empty object, at least this is what the crome dev tools say.
I import proofr which is linked via yarn link with my project in a js file.

import Proofr from 'proofr';

import PinguComponent from '../../assets/js/helpers/PinguComponent';

class Form extends PinguComponent {
  constructor(el) {
    const defaultOpts = {
      classes: {
        dom: {},
        state: {},
      },
      customEvents: {},
    };

    const defaultData = {};

    super(el, defaultOpts, defaultData);

    new Proofr();

    this.log('Form loaded');
  }
}

export default Form;

So am at the end of my knowledge, maybe someone sees the most possibly very small typo. Both repositories use the same babelrc so they use the same presets.

Here the by webpack and babel generated file for proofr

/******/ (function(modules) { // webpackBootstrap
/******/    // The module cache
/******/    var installedModules = {};
/******/
/******/    // The require function
/******/    function __webpack_require__(moduleId) {
/******/
/******/        // Check if module is in cache
/******/        if(installedModules[moduleId]) {
/******/            return installedModules[moduleId].exports;
/******/        }
/******/        // Create a new module (and put it into the cache)
/******/        var module = installedModules[moduleId] = {
/******/            i: moduleId,
/******/            l: false,
/******/            exports: {}
/******/        };
/******/
/******/        // Execute the module function
/******/        modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/        // Flag the module as loaded
/******/        module.l = true;
/******/
/******/        // Return the exports of the module
/******/        return module.exports;
/******/    }
/******/
/******/
/******/    // expose the modules object (__webpack_modules__)
/******/    __webpack_require__.m = modules;
/******/
/******/    // expose the module cache
/******/    __webpack_require__.c = installedModules;
/******/
/******/    // define getter function for harmony exports
/******/    __webpack_require__.d = function(exports, name, getter) {
/******/        if(!__webpack_require__.o(exports, name)) {
/******/            Object.defineProperty(exports, name, {
/******/                configurable: false,
/******/                enumerable: true,
/******/                get: getter
/******/            });
/******/        }
/******/    };
/******/
/******/    // getDefaultExport function for compatibility with non-harmony modules
/******/    __webpack_require__.n = function(module) {
/******/        var getter = module && module.__esModule ?
/******/            function getDefault() { return module['default']; } :
/******/            function getModuleExports() { return module; };
/******/        __webpack_require__.d(getter, 'a', getter);
/******/        return getter;
/******/    };
/******/
/******/    // Object.prototype.hasOwnProperty.call
/******/    __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/    // __webpack_public_path__
/******/    __webpack_require__.p = "";
/******/
/******/    // Load entry module and return exports
/******/    return __webpack_require__(__webpack_require__.s = 0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

/**
 * Proofr a lightweight js tool
 */

var Proofr = function Proofr() {
  _classCallCheck(this, Proofr);

  console.log('test');
};

exports.default = Proofr;

/***/ })
/******/ ]);

If you want to see it by yourself you can add it via npm install proofr (or yarn proofr)

Body:
Change the webpack build configuration of your proofr library by setting output.libraryTarget to umd:

output: {
  filename: '[name]',
  path: path.resolve(__dirname, '../dist'),
  libraryTarget: "umd"
},

See https://webpack.js.org/configuration/output/#output-librarytarget for more options.

I tested this by rebuilding proofr with npm run start and imported it in a node.js script:

var proofr = require('proofr');
console.log(proofr);

Without output.libraryTarget: "umd":

$ node index.js
{}

With it:

$ node index.js
{ default: [Function: Proofr] }


问:
How to configure delay until condition is true in Jmeter
I have a question about Jmeter delay, I created a test plan and in one step I make a call to DB using JDBC, and store the results in actual_vertica_results parameter (counts number of employees in temp table).
I want to configure Jmeter to Waite until actual_vertica_results will be 0.
(the table in DB deletes itself)
Can someone please advise how can I perform such scenario in Jmeter, today I am using constant timer for delay, and increase it manually each iteration to make sure all the data deleted.
How can I ask Jmeter making call to DB every 5 seconds and check  the results and only after all temp data deleted from the table to progress to the next step?
if someone can provide step by step scenario with PIC it will be very helpful
regards

答:
Different solution:

add next steps in another Thread group

Check Run Thread group consequently checkbox in Test Plan

Add Test Action with Target Current Thread and Action Stop when count = 0

This way Thread group will execute until count = 0 and then continue to next steps in different Thread group

You can add Loop Count Forever in first Thread Group if you need


问:
invalidation of std::function objects
The following code does not work as per my understanding. When the Raise
 method of the handler object is called, random (I assume uninitialised variable) values are printed. My suspicion is that the map::insert calls made in CreateTests results in some sort of move that results in the invalidation of this parameters provides to the std::function objects provided to EventCoordinator::Register. The intended output of this program would be 2 lines printed in the console, with values 0 & 1 printed. Can somebody advise what the error here is?

```<code>#include <map>
#include <functional>
#include <vector>
#include <iostream>

class EventCoordinator
{
    using Handler = std::function<void()>;
    using Handlers = std::vector<Handler>;

    std::map<int, Handlers> HandlerMap;

public:

    void Register(const int id, std::function<void()> handler)
    {
        HandlerMap[id].emplace_back(handler);
    }

    void Raise(const int id)
    {
        try {
            auto handlers = HandlerMap.at(id);
            for (const auto& handler : handlers) {
                handler();
            }
        }
        catch (std::exception& e) {
            std::cout << e.what();
        }

    }
};

class test
{
public:
    test() : mId(-1)
    {
        std::cout << "test default constructor\n";
    }
    test(const int id, EventCoordinator& handler) : mId(id)
    {
        handler.Register(mId, std::bind(&test::func, *this));
    }

    void other()
    {
        std::cout << this << '\n';
    }

    void func() const
    {

        std::cout << this <<'\n';
        std::cout << mId << '\n';
    }
    ~test() = default;
    test(const test& other) = default;
    test(test&& other) noexcept = default;
    test& operator=(const test& other) = default;
    test& operator=(test&& other) noexcept = default;
    int mId;
};

std::map<int, test> CreateTests(EventCoordinator& handler)
{
    auto returnMap = std::map<int, test>();
    returnMap.emplace(std::make_pair(0, test(0, handler)));
    returnMap.emplace(std::make_pair(1, test(1, handler)));
    return returnMap;
}

int main(int argc, char** args)
{
    EventCoordinator handler;
    auto ret = CreateTests(handler);
    handler.Raise(0);
    ret[0].other();
    handler.Raise(1);
    ret[1].other();
    std::cin.get();
}
</code>```

答:
As per the suggestion of @alain, the registration of the test object could not be carried out in the constructor of the test object. A register_test method was added to the test class. The following code takes the initialised std::map<int,test> object and calls test::register on the objects stored in the map.

```<code>#include <map>
#include <functional>
#include <vector>
#include <iostream>
#include <memory>

class EventCoordinator
{
    using Handler = std::function<void()>;
    using Handlers = std::vector<Handler>;
    std::map<int, Handlers> HandlerMap;

public:

    void Register(const int id, std::function<void()> handler)
    {
        HandlerMap[id].emplace_back(handler);
    }

    void Raise(const int id)
    {
        try {
            auto handlers = HandlerMap.at(id);
            for (const auto& handler : handlers) {
                handler();
            }
        }
        catch (std::exception& e) {
            std::cout << e.what();
        }
    }
};

class test
{
    int mId;
public:
    test() : mId(-1)
    {
        std::cout << "test default constructor\n";
    }

    test(const int id) : mId(id)
    {}

    void register_test(EventCoordinator& handler) {
        handler.Register(mId, std::bind(&test::func, this));
    }

    void func() const
    {
        std::cout << mId << '\n';
    }

    ~test() = default;
    test(const test& other) = default;
    test(test&& other) noexcept = default;
    test& operator=(const test& other) = default;
    test& operator=(test&& other) noexcept = default;
};

void RegisterTests(std::map<int,test>& testCollection,EventCoordinator& coordinator)
{
    for (auto& test: testCollection){
        test.second.register_test(coordinator);
    }
}

std::map<int, test> CreateTests(EventCoordinator& coordinator)
{
    auto returnMap = std::map<int, test>();
    returnMap.emplace(std::make_pair(0, test(0)));
    returnMap.emplace(std::make_pair(1, test(1)));
    RegisterTests(returnMap, coordinator);
    return returnMap;
}

int main(int argc, char** args)
{
    EventCoordinator handler;
    auto ret = CreateTests(handler);
    handler.Raise(0);
    handler.Raise(1);
    std::cin.get();
}
</code>```

Title: invalidation of std::function objects

Body:
The following code does not work as per my understanding. When the Raise
 method of the handler object is called, random (I assume uninitialised variable) values are printed. My suspicion is that the map::insert calls made in CreateTests results in some sort of move that results in the invalidation of this parameters provides to the std::function objects provided to EventCoordinator::Register. The intended output of this program would be 2 lines printed in the console, with values 0 & 1 printed. Can somebody advise what the error here is?

#include <map>
#include <functional>
#include <vector>
#include <iostream>

class EventCoordinator
{
    using Handler = std::function<void()>;
    using Handlers = std::vector<Handler>;

    std::map<int, Handlers> HandlerMap;

public:

    void Register(const int id, std::function<void()> handler)
    {
        HandlerMap[id].emplace_back(handler);
    }

    void Raise(const int id)
    {
        try {
            auto handlers = HandlerMap.at(id);
            for (const auto& handler : handlers) {
                handler();
            }
        }
        catch (std::exception& e) {
            std::cout << e.what();
        }

    }
};

class test
{
public:
    test() : mId(-1)
    {
        std::cout << "test default constructor\n";
    }
    test(const int id, EventCoordinator& handler) : mId(id)
    {
        handler.Register(mId, std::bind(&test::func, *this));
    }

    void other()
    {
        std::cout << this << '\n';
    }

    void func() const
    {

        std::cout << this <<'\n';
        std::cout << mId << '\n';
    }
    ~test() = default;
    test(const test& other) = default;
    test(test&& other) noexcept = default;
    test& operator=(const test& other) = default;
    test& operator=(test&& other) noexcept = default;
    int mId;
};

std::map<int, test> CreateTests(EventCoordinator& handler)
{
    auto returnMap = std::map<int, test>();
    returnMap.emplace(std::make_pair(0, test(0, handler)));
    returnMap.emplace(std::make_pair(1, test(1, handler)));
    return returnMap;
}

int main(int argc, char** args)
{
    EventCoordinator handler;
    auto ret = CreateTests(handler);
    handler.Raise(0);
    ret[0].other();
    handler.Raise(1);
    ret[1].other();
    std::cin.get();
}

Body:
As per the suggestion of @alain, the registration of the test object could not be carried out in the constructor of the test object. A register_test method was added to the test class. The following code takes the initialised std::map<int,test> object and calls test::register on the objects stored in the map.

#include <map>
#include <functional>
#include <vector>
#include <iostream>
#include <memory>

class EventCoordinator
{
    using Handler = std::function<void()>;
    using Handlers = std::vector<Handler>;
    std::map<int, Handlers> HandlerMap;

public:

    void Register(const int id, std::function<void()> handler)
    {
        HandlerMap[id].emplace_back(handler);
    }

    void Raise(const int id)
    {
        try {
            auto handlers = HandlerMap.at(id);
            for (const auto& handler : handlers) {
                handler();
            }
        }
        catch (std::exception& e) {
            std::cout << e.what();
        }
    }
};

class test
{
    int mId;
public:
    test() : mId(-1)
    {
        std::cout << "test default constructor\n";
    }

    test(const int id) : mId(id)
    {}

    void register_test(EventCoordinator& handler) {
        handler.Register(mId, std::bind(&test::func, this));
    }

    void func() const
    {
        std::cout << mId << '\n';
    }

    ~test() = default;
    test(const test& other) = default;
    test(test&& other) noexcept = default;
    test& operator=(const test& other) = default;
    test& operator=(test&& other) noexcept = default;
};

void RegisterTests(std::map<int,test>& testCollection,EventCoordinator& coordinator)
{
    for (auto& test: testCollection){
        test.second.register_test(coordinator);
    }
}

std::map<int, test> CreateTests(EventCoordinator& coordinator)
{
    auto returnMap = std::map<int, test>();
    returnMap.emplace(std::make_pair(0, test(0)));
    returnMap.emplace(std::make_pair(1, test(1)));
    RegisterTests(returnMap, coordinator);
    return returnMap;
}

int main(int argc, char** args)
{
    EventCoordinator handler;
    auto ret = CreateTests(handler);
    handler.Raise(0);
    handler.Raise(1);
    std::cin.get();
}


问:
Get the median from 6 tables
I know how to calculate the median from 1 table but Im trying to do it on 6 tables comparing the price.   My code so far, can you help?

```<code>    select avg(price) as median from
     (select row_id, price from (
     (select @counter:=@counter+1 as row_id, t1.priceInt as price
     from Table1 t1, (select @counter:=0) tx1
     )
     union all (select @counter:=@counter+1 as row_id, t2.priceInt as price
     from Table2 t2, (select @counter:=0) tx2
     )
     union all (select @counter:=@counter+1 as row_id, t3.priceInt as price
     from Table3 t3, (select @counter:=0) tx3
     )
     union all (select @counter:=@counter+1 as row_id, t4.priceInt as price
     from Table4 t4, (select @counter:=0) tx4
     )
     union all (select @counter:=@counter+1 as row_id, t5.priceInt as price
     from Table5 t5, (select @counter:=0) tx5
     )
     union all (select @counter:=@counter+1 as row_id, t6.priceInt as price
     from Table6 t6, (select @counter:=0) tx6
     )
     ) xx order by price) o1 join
     (
     select sum(x) AS total_rows from
     (
     select count(*) x from Table1 union all select count(*) x from
     Table2
     union all select count(*) x from Table3 union all select count(*) x
     from Table4
     union all select count(*) x from Table5 union all (select count(*) x
     from Table6
     )
     ) o2 where o1.row_id in (floor((o2.total_rows + 1)/2),
    floor((o2.total_rows + 2)/2)))
</code>```

My error is that o1.row_id is not recognised!

Here is an example of Table 1, each table has identical columns!

***EDIT

Desired results:  250, 275, 300, 400, 500   I want the 300k
(Note the numbers have to be ordered and if there are 2 middle numbers the average has to be found of the 2 numbers)

答:
Just "stack" the data from each of the tables together, and treat that as one list from then on, Do the counter "up one level". Layout your query so it is easy to read and so that aliases are easy to find.

```<code>select
     avg(price) as median
from (
        select
               row_id
             , price
        from (
            select
                   @counter:=@counter+1 as row_id
                 , price
            from (
                 select t1.priceInt as price from Table1 t1 union all
                 select t2.priceInt as price from Table2 t2 union all
                 select t3.priceInt as price from Table3 t3 union all
                 select t4.priceInt as price from Table4 t4 union all
                 select t5.priceInt as price from Table5 t5 union all
                 select t6.priceInt as price from Table6 t6
                 ) u
            cross join (select @counter:=0) vars
            ORDER BY u.price
            ) o1
        cross join (
                     select sum(x) AS total_rows
                     from (
                         select count(*) x from Table1 union all
                         select count(*) x from Table2 union all
                         select count(*) x from Table3 union all
                         select count(*) x from Table4 union all
                         select count(*) x from Table5 union all
                         select count(*) x from Table6
                        ) c
                  ) o2
        where o1.row_id in (floor((o2.total_rows + 1)/2),floor((o2.total_rows + 2)/2)))
    ) d
</code>```

Placing repetitive sql as a "list" is very helpful in my experience. I just realized I had the table names wrong just before i saved this. It's untested of course but it should help you get going.

Oh, and please avoid using commas between tables or subqueries in the from clause. You will see lots of samples like this:

```<code>from table_x, (select @counter:=0) vars
</code>```

Don't! It isn't an explicit join (it is an implied cross join) make it explicit:

```<code>from table_x
cross join (select @counter:=0) vars
</code>```

Now everyone know that cross join exsts and is deliberate.

Title: Get the median from 6 tables

Body:
I know how to calculate the median from 1 table but Im trying to do it on 6 tables comparing the price.   My code so far, can you help?

    select avg(price) as median from
     (select row_id, price from (
     (select @counter:=@counter+1 as row_id, t1.priceInt as price
     from Table1 t1, (select @counter:=0) tx1
     )
     union all (select @counter:=@counter+1 as row_id, t2.priceInt as price
     from Table2 t2, (select @counter:=0) tx2
     )
     union all (select @counter:=@counter+1 as row_id, t3.priceInt as price
     from Table3 t3, (select @counter:=0) tx3
     )
     union all (select @counter:=@counter+1 as row_id, t4.priceInt as price
     from Table4 t4, (select @counter:=0) tx4
     )
     union all (select @counter:=@counter+1 as row_id, t5.priceInt as price
     from Table5 t5, (select @counter:=0) tx5
     )
     union all (select @counter:=@counter+1 as row_id, t6.priceInt as price
     from Table6 t6, (select @counter:=0) tx6
     )
     ) xx order by price) o1 join
     (
     select sum(x) AS total_rows from
     (
     select count(*) x from Table1 union all select count(*) x from
     Table2
     union all select count(*) x from Table3 union all select count(*) x
     from Table4
     union all select count(*) x from Table5 union all (select count(*) x
     from Table6
     )
     ) o2 where o1.row_id in (floor((o2.total_rows + 1)/2),
    floor((o2.total_rows + 2)/2)))

My error is that o1.row_id is not recognised!

Here is an example of Table 1, each table has identical columns!

***EDIT

Desired results:  250, 275, 300, 400, 500   I want the 300k
(Note the numbers have to be ordered and if there are 2 middle numbers the average has to be found of the 2 numbers)

Body:
Just "stack" the data from each of the tables together, and treat that as one list from then on, Do the counter "up one level". Layout your query so it is easy to read and so that aliases are easy to find.

select
     avg(price) as median
from (
        select
               row_id
             , price
        from (
            select
                   @counter:=@counter+1 as row_id
                 , price
            from (
                 select t1.priceInt as price from Table1 t1 union all
                 select t2.priceInt as price from Table2 t2 union all
                 select t3.priceInt as price from Table3 t3 union all
                 select t4.priceInt as price from Table4 t4 union all
                 select t5.priceInt as price from Table5 t5 union all
                 select t6.priceInt as price from Table6 t6
                 ) u
            cross join (select @counter:=0) vars
            ORDER BY u.price
            ) o1
        cross join (
                     select sum(x) AS total_rows
                     from (
                         select count(*) x from Table1 union all
                         select count(*) x from Table2 union all
                         select count(*) x from Table3 union all
                         select count(*) x from Table4 union all
                         select count(*) x from Table5 union all
                         select count(*) x from Table6
                        ) c
                  ) o2
        where o1.row_id in (floor((o2.total_rows + 1)/2),floor((o2.total_rows + 2)/2)))
    ) d

Placing repetitive sql as a "list" is very helpful in my experience. I just realized I had the table names wrong just before i saved this. It's untested of course but it should help you get going.

Oh, and please avoid using commas between tables or subqueries in the from clause. You will see lots of samples like this:

from table_x, (select @counter:=0) vars

Don't! It isn't an explicit join (it is an implied cross join) make it explicit:

from table_x
cross join (select @counter:=0) vars

Now everyone know that cross join exsts and is deliberate.


答:
Ansible runs the loop and:

for items 4, 5, and 6 executes the echo command - shows changed status,

for remaining items it does not execute it - shows skipped status,

You have achieved what you wanted.

The only thing you can improve is getting rid of the warning by fixing the conditional:

```<code>- hosts: localhost
  tasks:
    - shell: echo {{ item }}
      register: result
      with_sequence: start=4 end=16
      when: "item|int < 7"
</code>```

Title: How to break loop in Ansible?

Body:
Want to break the task after the value for item became 7, here is the sample task

   - hosts: localhost
     tasks:
       - shell: echo {{ item }}
         register: result
         with_sequence: start=4 end=16
         when: "{{ item }} < 7"

On the above code it's iterating the task from 4 to 16 as below

PLAY [localhost] ***********************************************************************************************************************************************

TASK [Gathering Facts] *****************************************************************************************************************************************
ok: [localhost]

TASK [command] *************************************************************************************************************************************************
 [WARNING]: when statements should not include jinja2 templating delimiters such as {{ }} or {% %}. Found: {{ item }} < 7

changed: [localhost] => (item=4)
changed: [localhost] => (item=5)
changed: [localhost] => (item=6)
skipping: [localhost] => (item=7)
skipping: [localhost] => (item=8)
skipping: [localhost] => (item=9)
skipping: [localhost] => (item=10)
skipping: [localhost] => (item=11)
skipping: [localhost] => (item=12)
skipping: [localhost] => (item=13)
skipping: [localhost] => (item=14)
skipping: [localhost] => (item=15)
skipping: [localhost] => (item=16)

PLAY RECAP *****************************************************************************************************************************************************
localhost                  : ok=2    changed=1    unreachable=0    failed=0

Body:
Ansible runs the loop and:

for items 4, 5, and 6 executes the echo command - shows changed status,

for remaining items it does not execute it - shows skipped status,

You have achieved what you wanted.

The only thing you can improve is getting rid of the warning by fixing the conditional:

- hosts: localhost
  tasks:
    - shell: echo {{ item }}
      register: result
      with_sequence: start=4 end=16
      when: "item|int < 7"


问:
How can I install Magento themes on localhost?
I have downloaded a Magento 2 theme and I want to install that theme to my Magento store. currently I am doing it on my local host.

I am new in Magento and want to install the theme. When I extract the downloaded theme file it gave me 4 directories: app, js, lib, skin and 2 files: .htaccess and robots.txt

Tell me how I can add this theme to my store.

答:
For installing theme on  magento 2 you need to implemeint your theme package to the current magento directory with all the files in designed folder please consider its doc for its file structure first.

Then open cmd using win + R >  type cmd

navigate to your project directory

and run following commands

1- php bin/magento setup:upgrade

2- php bin/magento setup:static-content:deploy

3- php bin/magentocache:flush

4- open admin and select theme from admin>CMS>Theme- Configuration> Your store

ContentLicense: CC BY-SA 4.0


问:
Avoiding comma separator for the last value
I am generating an output on a webpage in a format like this

({"1":"Jeff","2":"Tom","3":"Michael",})

For this, basically this is the code I am using

```<code>Response.Write("(" + "{");
//
for (Int32 i = 0; i < k.Length; i++)
{
  Response.Write(Convert.ToString(k.GetValue(i)) + ",");
}
//
Response.Write("}" + ")");
</code>```

Notice my output, after Michael" there is a comma which I do not want since this is the last vaue but this is appearing since , is in the for loop. How to prevent this/remove this last comma from appearing?

My output should be ({"1":"Jeff","2":"Tom","3":"Michael"}) (There's no comma after last value here)

答:
```<code>Response.Write("(" + "{");
//
for (Int32 i = 0; i < k.Length; i++)
{
  Response.Write(Convert.ToString(k.GetValue(i)) + (i == k.Length - 1 ? "" : ","));
}
//
Response.Write("}" + ")");
</code>```

Body:
I am generating an output on a webpage in a format like this

({"1":"Jeff","2":"Tom","3":"Michael",})

For this, basically this is the code I am using

Response.Write("(" + "{");
//
for (Int32 i = 0; i < k.Length; i++)
{
  Response.Write(Convert.ToString(k.GetValue(i)) + ",");
}
//
Response.Write("}" + ")");

Notice my output, after Michael" there is a comma which I do not want since this is the last vaue but this is appearing since , is in the for loop. How to prevent this/remove this last comma from appearing?

My output should be ({"1":"Jeff","2":"Tom","3":"Michael"}) (There's no comma after last value here)


问:
Longest sequence of number in two arrays
I have two array that initialize in random number between 0-9

I need to find the longest same sequence that exist in both of them.

For example

```<code>var arrFirst = [8,5,3,0,3,1,8,2,8,7,3,5,4,0,8,5,7,3,1]
var arrSecond = [8,5,4,0,2,9,4,3,6,9,2,3,1,8,2,8,7,3,3]
</code>```

The result array need to contain the longest sequence that appear in both array

```<code>var arrResult = [3,1,8,2,8,7,3]
</code>```

In this example we have sequence right on start [8, 5] but it's not the longest one.

Could you please provide some code that would help me?

Thanx

答:
You could check ech element of array1 with every element of array2 and go on with checking the elements with a while loop with a counter and for each array an offset for the index.

Later check if the length of the found same elements is greater or equal to the last found array and either replace the result set with the new longer one or append, if equal to the result set.

var array1 = [8, 5, 3, 0, 3, 1, 8, 2, 8, 7, 3, 5, 4, 0, 8, 5, 7, 3, 1],
    array2 = [1, 8, 4, 0, 2, 9, 4, 3, 6, 9, 2, 3, 1, 8, 2, 8, 7, 3, 3],
    result = array1.reduce(function (r, _, i, a) {
        array2.forEach(function (__, j, b) {
            var k = 0,
                temp = [];

            while ((i + k) in a && (j + k) in b && a[i + k] === b[j + k]) {
                temp.push(a[i + k]);
                k++;
            }
            if (!r.length || temp.length > r[0].length) {
                r = [temp];
                return;
            }
            if (temp.length === r[0].length) {
                r.push(temp);
            }
        });
        return r;
    }, []);

console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
I have two array that initialize in random number between 0-9

I need to find the longest same sequence that exist in both of them.

For example

var arrFirst = [8,5,3,0,3,1,8,2,8,7,3,5,4,0,8,5,7,3,1]
var arrSecond = [8,5,4,0,2,9,4,3,6,9,2,3,1,8,2,8,7,3,3]

The result array need to contain the longest sequence that appear in both array

var arrResult = [3,1,8,2,8,7,3]

In this example we have sequence right on start [8, 5] but it's not the longest one.

Could you please provide some code that would help me?

Thanx

Body:
You could check ech element of array1 with every element of array2 and go on with checking the elements with a while loop with a counter and for each array an offset for the index.

Later check if the length of the found same elements is greater or equal to the last found array and either replace the result set with the new longer one or append, if equal to the result set.

var array1 = [8, 5, 3, 0, 3, 1, 8, 2, 8, 7, 3, 5, 4, 0, 8, 5, 7, 3, 1],
    array2 = [1, 8, 4, 0, 2, 9, 4, 3, 6, 9, 2, 3, 1, 8, 2, 8, 7, 3, 3],
    result = array1.reduce(function (r, _, i, a) {
        array2.forEach(function (__, j, b) {
            var k = 0,
                temp = [];

            while ((i + k) in a && (j + k) in b && a[i + k] === b[j + k]) {
                temp.push(a[i + k]);
                k++;
            }
            if (!r.length || temp.length > r[0].length) {
                r = [temp];
                return;
            }
            if (temp.length === r[0].length) {
                r.push(temp);
            }
        });
        return r;
    }, []);

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
how to represent distance information from 3d camera with RGB
I have got a distance matrix from a 3D-sensor, how can I represent the distance information with different colors(RGB). For example, red means short range, green means medium range and blue means long range.</p>

答:
In MATLAB use colour maps. Assuming your depth data are stored in a 16-bits single channel image, use the code below. </p>

```<code>im=imread(‘pathtoyourimage’)
clrd=ind2rgb(im, jet(2^13))
</code>```

Body:
In MATLAB use colour maps. Assuming your depth data are stored in a 16-bits single channel image, use the code below.

im=imread(‘pathtoyourimage’)
clrd=ind2rgb(im, jet(2^13))


问:
Map throw error on duplicate insertion
I am creating a Map with stores some data and i want the map to throw an exception if a duplicate value is tried to insert.

```<code>Map <Integer, String> temp;
temp.put(1, "hi");
temp.put(1, "hello");
</code>```

Here this map should throw an error since a key '1' is already present.
It can throw an error or does not compile.
Is there any map which has said functionality?

答:
Map doesn't throw any error or exception while trying to add new value with a key that is present in the map. In that case old value is simply being replaced with a new value. </p>

<p>If you want to add a functionality that will throw an error in that situation, you can use </p>

```<code>if(map.containsKey(yourKey)) // here your error action
</code>```

Title: Map throw error on duplicate insertion

Body:
I am creating a Map with stores some data and i want the map to throw an exception if a duplicate value is tried to insert.

Map <Integer, String> temp;
temp.put(1, "hi");
temp.put(1, "hello");

Here this map should throw an error since a key '1' is already present.
It can throw an error or does not compile.
Is there any map which has said functionality?

Body:
Map doesn't throw any error or exception while trying to add new value with a key that is present in the map. In that case old value is simply being replaced with a new value.

If you want to add a functionality that will throw an error in that situation, you can use

if(map.containsKey(yourKey)) // here your error action


问:
capistrano does not bundle install into specified gemset
I have a Rails application configured to deploy via Capistrano and RVM. When I run a cap my_stage deploy (this applies for all my stages), Capistrano bundle installs to /var/www/my_app/shared/bundle, even though I have specified in my config/deploy.rb file that I want it to use the 1.9.2@my_app gemset.

This is contrary to my expectations - I expect Capistrano to deploy into my user's home directory: ~/.rvm/gems/ruby-1.9.2-p290@my_gemset/gems.

Am I doing something wrong? Or is this expected behaviour.

Here is my deploy file:

```<code>require 'capistrano/ext/multistage'
require 'bundler/capistrano'

set :stages, %w(local development staging production)
set :default_stage, "local"

set :application, "My Rails App"
set :repository,  "git@github.com:MyApp/my_app.git"

set :scm, :git
set :deploy_to, "/var/www/my_app"
set :use_sudo, false
ssh_options[:keys] = [File.join(ENV["HOME"], ".ssh", "my_key.pem")]

# RVM
$:.unshift(File.expand_path('./lib', ENV['rvm_path']))
require 'rvm/capistrano'
set :rvm_ruby_string, '1.9.2@my_app'
set :rvm_type, :user
set :user, 'my_user'
</code>```

Here is my .rvmrc file in my Rails app:

```<code>rvm_trust_rvmrc_flags=1
rvm use 1.9.2@my_app
</code>```

Thanks,
Max

答:
Adding capistrano/rvm and setting my ruby version inside production.rb did a trick.

```<code>set :rvm_ruby_version, 'ruby-2.4.1'
</code>```

Body:
I have a Rails application configured to deploy via Capistrano and RVM. When I run a cap my_stage deploy (this applies for all my stages), Capistrano bundle installs to /var/www/my_app/shared/bundle, even though I have specified in my config/deploy.rb file that I want it to use the 1.9.2@my_app gemset.

This is contrary to my expectations - I expect Capistrano to deploy into my user's home directory: ~/.rvm/gems/ruby-1.9.2-p290@my_gemset/gems.

Am I doing something wrong? Or is this expected behaviour.

Here is my deploy file:

require 'capistrano/ext/multistage'
require 'bundler/capistrano'

set :stages, %w(local development staging production)
set :default_stage, "local"

set :application, "My Rails App"
set :repository,  "git@github.com:MyApp/my_app.git"

set :scm, :git
set :deploy_to, "/var/www/my_app"
set :use_sudo, false
ssh_options[:keys] = [File.join(ENV["HOME"], ".ssh", "my_key.pem")]

# RVM
$:.unshift(File.expand_path('./lib', ENV['rvm_path']))
require 'rvm/capistrano'
set :rvm_ruby_string, '1.9.2@my_app'
set :rvm_type, :user
set :user, 'my_user'

Here is my .rvmrc file in my Rails app:

rvm_trust_rvmrc_flags=1
rvm use 1.9.2@my_app

Thanks,
Max

Body:
Adding capistrano/rvm and setting my ruby version inside production.rb did a trick.

set :rvm_ruby_version, 'ruby-2.4.1'


问:
Bootstrap Container centered vertically
My page is made of a navbar and a container containing two panels.

I want to vertically center my container. The navbar has to stay on top.

Right now I have this :

I want to achieve this :

Here's my code :

HTML

```<code><body>

  <nav class="navbar transparent navbar-static-top">

    <div class="navbar-header">
      <p>Welcome</p>
    </div>

  </nav>

  <div class="container d-flex h-100">

    <div class="row justify-content-center align-self-center">

      <!-- 1st panel -->
      <div class="col-md-4 mb-4" id="panel">

        <div class="panel panel-default1">

          <div class="panel-body">

            <p>Blablabla</p>

          </div>
          <!-- panel body -->
        </div>
        <!-- panel-default1-->
      </div>
      <!-- col md 4 -->

      <!-- 2nd panel -->

      <div class="col-md-8 col-md-8" id="panel2">

        <div class="panel panel-default2">

          <div class="panel-body">

            <p>Blablabla</p>

          </div>
          <!-- panel-body -->

        </div>
        <!-- panel-default2-->

      </div>
      <!-- col md 8 -->

    </div>
    <!-- row -->

  </div>
  <!-- container-->

</body>
</code>```

CSS

```<code>html {
  overflow: hidden;
  height: 100%;
}

body {
  overflow: hidden;
  width: 100%;
  height: 100%;
  margin: 0px;
  padding: 0px;
}

.panel-default1 {
  padding-top: 8px;
  border-radius: 20px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.10);
  height: 400px;
  width: 100%;
  overflow: hidden;
  margin: 0 auto;
  position: relative;
}

.panel-default2 {
  padding-top: 10px;
  padding-right: -15px;
  border-radius: 20px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.10);
  height: 400px;
  width: 100%;
  margin: 0 auto;
  position: relative;
}
</code>```

I haven't been successful in center the container vertically.

Please advise a clean and working solution.

答:
I tried doing something similar not long ago and found it easier to be solved through simple CSS than through Bootstrap classes, even because it was a CSS limitation that was going on ( wasn't getting 100% height because there wasn't enough content filling it).

I'm adapting my stylesheet so only your .container element gets its content centered.

```<code>html, body, .container {
    height: 100%;
    overflow-x: hidden;
}

body, .container {
    display: flex;
}

.container {
    align-items: center;
}
</code>```

Title: Bootstrap Container centered vertically

Body:
My page is made of a navbar and a container containing two panels.

I want to vertically center my container. The navbar has to stay on top.

Right now I have this :

I want to achieve this :

Here's my code :

HTML

Welcome

Blablabla

Blablabla

CSS

html {
  overflow: hidden;
  height: 100%;
}

body {
  overflow: hidden;
  width: 100%;
  height: 100%;
  margin: 0px;
  padding: 0px;
}

.panel-default1 {
  padding-top: 8px;
  border-radius: 20px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.10);
  height: 400px;
  width: 100%;
  overflow: hidden;
  margin: 0 auto;
  position: relative;
}

.panel-default2 {
  padding-top: 10px;
  padding-right: -15px;
  border-radius: 20px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.10);
  height: 400px;
  width: 100%;
  margin: 0 auto;
  position: relative;
}

I haven't been successful in center the container vertically.

Please advise a clean and working solution.

Body:
I tried doing something similar not long ago and found it easier to be solved through simple CSS than through Bootstrap classes, even because it was a CSS limitation that was going on (<body> wasn't getting 100% height because there wasn't enough content filling it).

I'm adapting my stylesheet so only your .container element gets its content centered.

html, body, .container {
    height: 100%;
    overflow-x: hidden;
}

body, .container {
    display: flex;
}

.container {
    align-items: center;
}


问:
Nested attributes saving with empty values rails 5
I have two models. order and order has many order_products.
i am using angularjs post request to create an order.
angular controller:

```<code>return $scope.submitForm = function() {
    var order_products_attributes;
    if ($scope.buyer.selected_item) {
        $scope.order.company_id = $scope.buyer.selected_item.id;
    }
    order_products_attributes = [];
    var qtt = 0
    $scope.op.forEach(function(obj) {
        var newObj;
        var total = parseInt(obj.quantity) * parseInt(obj.batch.selected_item[0].pack_size);
        qtt= qtt+total;
        newObj = {
            product_id: parseInt(obj.product.selected_item[0].id),
            product_batch_id: parseInt(obj.batch.selected_item[0].id),
            price: parseInt(obj.price),
            quantity: parseInt(obj.quantity),
            free_quantity: parseInt(obj.free_quantity),
            total_quantity:total ,
            total_amount: parseInt(obj.total_amount)
        };
        return order_products_attributes.push(newObj);
    });
    $scope.order.order_products_attributes = order_products_attributes;
    $scope.order.price = $scope.amount;
    $scope.order.discount = $scope.discount;
    $scope.order.quantity = qtt;
    $scope.order.status = 'Booked'
    // $scope.order.dc_date = $("#orderDate").find("input").val()
    $scope.order.order_date = $("#orderDate").find("input").val()
    // $scope.order.delivery_date = $("#orderDate").find("input").val()
    $scope.order.delivery_date = $("#deliveryDate").find("input").val()

    var st = $("#orderDate").find("input").val().split("/");
    var dd = new Date(st[2],st[1]-1,st[0]);
    dd.setDate(dd.getDate()+30);
    $scope.order.due_date = dd;

    $scope.order.authenticity_token = $scope.authenticity_token;
    $scope.order.type = type;
    // if($scope.p_type.selected_item)
    //     $scope.order.payment_type = $scope.p_type.selected_item.value;
    console.log($scope.order)

    return $http.post('/orders', $scope.order).then(function(response) {
        response.data;

        $window.location.href = '/orders/invoice_print/'+response.data.id;
    });
};
</code>```

following is the request.

```<code>Parameters: {"company_id"=>13, "order_products_attributes"=>[{"product_id"=>6, "product_batch_id"=>26, "price"=>1100, "quantity"=>1, "free_quantity"=>nil, "total_quantity"=>10, "total_amount"=>11000}], "price"=>11000, "discount"=>0, "quantity"=>10, "status"=>"Booked", "order_date"=>"13/11/2017", "delivery_date"=>"13/11/2017", "due_date"=>"2017-12-12T19:00:00.000Z", "authenticity_token"=>"OJx5FtSx6+e0FEhlRdUIqzfW7OhA18/Y3B3ETAqye8en3WC49QhR0smmz3MGoqRfsqmckMFLhVsz2ldRnmDXXA==", "type"=>"RegisteredOrder", "order"=>{"company_id"=>13, "price"=>11000, "quantity"=>10, "order_date"=>"13/11/2017", "delivery_date"=>"13/11/2017", "discount"=>0, "type"=>"RegisteredOrder", "due_date"=>"2017-12-12T19:00:00.000Z"}}
</code>```

My models are

```<code>class Order < ApplicationRecord
    has_many :order_products, inverse_of: :order, :dependent => :destroy
    accepts_nested_attributes_for :order_products
end
class OrderProduct < ApplicationRecord
    belongs_to :product
    belongs_to :order
end
</code>```

Controller:

```<code>@order = Order.new(order_params)
status_value_id = StatusValue.where(:status_val=> 'Booked').where(:status_type => 'sale-order').first.id
@order.order_products_attributes = params["order_products_attributes"]
@order.save

params.require(:order).permit(:status,:company_id, :type, :price,:quantity,:discount, :order_date, :delivery_date ,:due_date, :dc_date, :dc_number, :order_number, :invoice_number,  :special_instruction,order_products_attributes: [:id,:product_id, :description, :product_batch_id, :quantity,:pack_size,:total_quantity, :price, :discount, :discount_percentage, :total_amount])
</code>```

It creates order products but all attributes are set to null. following is the output. it works perfectly fine in rails 4 but not working in rails 5.

```<code>INSERT INTO "orders" ("company_id", "price", "quantity", "order_date", "delivery_date", "created_at", "updated_at", "discount", "order_number", "invoice_number", "type", "dc_number", "user_id", "due_date", "status_value_id") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15) RETURNING "id"  [["company_id", 13], ["price", 11000.0], ["quantity", 10], ["order_date", 2017-11-12 19:00:00 UTC], ["delivery_date", 2017-11-12 19:00:00 UTC], ["created_at", 2017-11-13 06:06:52 UTC], ["updated_at", 2017-11-13 06:06:52 UTC], ["discount", 0.0], ["order_number", 26], ["invoice_number", 26], ["type", "RegisteredOrder"], ["dc_number", "10"], ["user_id", 1], ["due_date", 2017-12-12 19:00:00 UTC], ["status_value_id", 9]]
SQL (16.0ms)  INSERT INTO "order_products" ("order_id", "created_at", "updated_at") VALUES ($1, $2, $3) RETURNING "id"  [["order_id", 90], ["created_at", 2017-11-13 06:06:52 UTC], ["updated_at", 2017-11-13 06:06:52 UTC]]
</code>```

答:
params["order_products_attributes"] is not permitted by default. so you have to permit it like:

```<code>private

def order_products_attributes_params
  params.permit(order_products_attributes: [:product_id, :product_batch_id, :price, :quantity, :free_quantity, :total_quantity, :total_amount])
end
</code>```

and use it while assigning to @order and save it like:

```<code>@order.order_products_attributes = order_products_attributes_params[:order_products_attributes]
@order.save
</code>```

Btw the above solution does not act in rails way. It may work anyway. To make it standard, it should look like:

```<code>@order = Order.new(order_params)
@order.save # this should create the new :order along with a nested :order_product

# the following should not be needed if you pass the parameters from angular in correct way
# @order.order_products_attributes = order_products_attributes_params[:order_products_attributes]
</code>```

So you should better take care of sending the parameters from angular that would look like:

```<code>Parameters:
{
  "authenticity_token": "OJx5FtSx6+e0FEhlRdUIqzfW7OhA18/Y3B3ETAqye8en3WC49QhR0smmz3MGoqRfsqmckMFLhVsz2ldRnmDXXA==",
  "order": {
    "company_id": 13,
    "price": 11000,
    "discount": 0,
    "quantity": 10,
    "status": "Booked",
    "order_date": "13/11/2017",
    "delivery_date": "13/11/2017",
    "due_date": "2017-12-12T19:00:00.000Z",
    "type": "RegisteredOrder",
    "order_products_attributes": [
      {
        "product_id": 6,
        "product_batch_id": 26,
        "price": 1100,
        "quantity": 1,
        "free_quantity": nil,
        "total_quantity": 10,
        "total_amount": 11000
      }
    ]
  }
}
</code>```

order_params would look like:

```<code>private

def order_params
  params.require(:order).permit(:company_id, :price, :discount, :quantity,
     :status, :order_date, :delivery_date, :due_date, :type,
     :order_products_attributes: [
       :product_id, :product_batch_id, :price, :quantity, :free_quantity,
       :total_quantity, :total_amount
     ]
  )
end
</code>```

Body:
I have two models. order and order has many order_products.
i am using angularjs post request to create an order.
angular controller:

return $scope.submitForm = function() {
    var order_products_attributes;
    if ($scope.buyer.selected_item) {
        $scope.order.company_id = $scope.buyer.selected_item.id;
    }
    order_products_attributes = [];
    var qtt = 0
    $scope.op.forEach(function(obj) {
        var newObj;
        var total = parseInt(obj.quantity) * parseInt(obj.batch.selected_item[0].pack_size);
        qtt= qtt+total;
        newObj = {
            product_id: parseInt(obj.product.selected_item[0].id),
            product_batch_id: parseInt(obj.batch.selected_item[0].id),
            price: parseInt(obj.price),
            quantity: parseInt(obj.quantity),
            free_quantity: parseInt(obj.free_quantity),
            total_quantity:total ,
            total_amount: parseInt(obj.total_amount)
        };
        return order_products_attributes.push(newObj);
    });
    $scope.order.order_products_attributes = order_products_attributes;
    $scope.order.price = $scope.amount;
    $scope.order.discount = $scope.discount;
    $scope.order.quantity = qtt;
    $scope.order.status = 'Booked'
    // $scope.order.dc_date = $("#orderDate").find("input").val()
    $scope.order.order_date = $("#orderDate").find("input").val()
    // $scope.order.delivery_date = $("#orderDate").find("input").val()
    $scope.order.delivery_date = $("#deliveryDate").find("input").val()

    var st = $("#orderDate").find("input").val().split("/");
    var dd = new Date(st[2],st[1]-1,st[0]);
    dd.setDate(dd.getDate()+30);
    $scope.order.due_date = dd;

    $scope.order.authenticity_token = $scope.authenticity_token;
    $scope.order.type = type;
    // if($scope.p_type.selected_item)
    //     $scope.order.payment_type = $scope.p_type.selected_item.value;
    console.log($scope.order)

    return $http.post('/orders', $scope.order).then(function(response) {
        response.data;

        $window.location.href = '/orders/invoice_print/'+response.data.id;
    });
};

following is the request.

Parameters: {"company_id"=>13, "order_products_attributes"=>[{"product_id"=>6, "product_batch_id"=>26, "price"=>1100, "quantity"=>1, "free_quantity"=>nil, "total_quantity"=>10, "total_amount"=>11000}], "price"=>11000, "discount"=>0, "quantity"=>10, "status"=>"Booked", "order_date"=>"13/11/2017", "delivery_date"=>"13/11/2017", "due_date"=>"2017-12-12T19:00:00.000Z", "authenticity_token"=>"OJx5FtSx6+e0FEhlRdUIqzfW7OhA18/Y3B3ETAqye8en3WC49QhR0smmz3MGoqRfsqmckMFLhVsz2ldRnmDXXA==", "type"=>"RegisteredOrder", "order"=>{"company_id"=>13, "price"=>11000, "quantity"=>10, "order_date"=>"13/11/2017", "delivery_date"=>"13/11/2017", "discount"=>0, "type"=>"RegisteredOrder", "due_date"=>"2017-12-12T19:00:00.000Z"}}

My models are

class Order < ApplicationRecord
    has_many :order_products, inverse_of: :order, :dependent => :destroy
    accepts_nested_attributes_for :order_products
end
class OrderProduct < ApplicationRecord
    belongs_to :product
    belongs_to :order
end

Controller:

@order = Order.new(order_params)
status_value_id = StatusValue.where(:status_val=> 'Booked').where(:status_type => 'sale-order').first.id
@order.order_products_attributes = params["order_products_attributes"]
@order.save

params.require(:order).permit(:status,:company_id, :type, :price,:quantity,:discount, :order_date, :delivery_date ,:due_date, :dc_date, :dc_number, :order_number, :invoice_number,  :special_instruction,order_products_attributes: [:id,:product_id, :description, :product_batch_id, :quantity,:pack_size,:total_quantity, :price, :discount, :discount_percentage, :total_amount])

It creates order products but all attributes are set to null. following is the output. it works perfectly fine in rails 4 but not working in rails 5.

INSERT INTO "orders" ("company_id", "price", "quantity", "order_date", "delivery_date", "created_at", "updated_at", "discount", "order_number", "invoice_number", "type", "dc_number", "user_id", "due_date", "status_value_id") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15) RETURNING "id"  [["company_id", 13], ["price", 11000.0], ["quantity", 10], ["order_date", 2017-11-12 19:00:00 UTC], ["delivery_date", 2017-11-12 19:00:00 UTC], ["created_at", 2017-11-13 06:06:52 UTC], ["updated_at", 2017-11-13 06:06:52 UTC], ["discount", 0.0], ["order_number", 26], ["invoice_number", 26], ["type", "RegisteredOrder"], ["dc_number", "10"], ["user_id", 1], ["due_date", 2017-12-12 19:00:00 UTC], ["status_value_id", 9]]
SQL (16.0ms)  INSERT INTO "order_products" ("order_id", "created_at", "updated_at") VALUES ($1, $2, $3) RETURNING "id"  [["order_id", 90], ["created_at", 2017-11-13 06:06:52 UTC], ["updated_at", 2017-11-13 06:06:52 UTC]]

Body:
params["order_products_attributes"] is not permitted by default. so you have to permit it like:

private

def order_products_attributes_params
  params.permit(order_products_attributes: [:product_id, :product_batch_id, :price, :quantity, :free_quantity, :total_quantity, :total_amount])
end

and use it while assigning to @order and save it like:

@order.order_products_attributes = order_products_attributes_params[:order_products_attributes]
@order.save

Btw the above solution does not act in rails way. It may work anyway. To make it standard, it should look like:

@order = Order.new(order_params)
@order.save # this should create the new :order along with a nested :order_product

# the following should not be needed if you pass the parameters from angular in correct way
# @order.order_products_attributes = order_products_attributes_params[:order_products_attributes]

So you should better take care of sending the parameters from angular that would look like:

Parameters:
{
  "authenticity_token": "OJx5FtSx6+e0FEhlRdUIqzfW7OhA18/Y3B3ETAqye8en3WC49QhR0smmz3MGoqRfsqmckMFLhVsz2ldRnmDXXA==",
  "order": {
    "company_id": 13,
    "price": 11000,
    "discount": 0,
    "quantity": 10,
    "status": "Booked",
    "order_date": "13/11/2017",
    "delivery_date": "13/11/2017",
    "due_date": "2017-12-12T19:00:00.000Z",
    "type": "RegisteredOrder",
    "order_products_attributes": [
      {
        "product_id": 6,
        "product_batch_id": 26,
        "price": 1100,
        "quantity": 1,
        "free_quantity": nil,
        "total_quantity": 10,
        "total_amount": 11000
      }
    ]
  }
}

order_params would look like:

private

def order_params
  params.require(:order).permit(:company_id, :price, :discount, :quantity,
     :status, :order_date, :delivery_date, :due_date, :type,
     :order_products_attributes: [
       :product_id, :product_batch_id, :price, :quantity, :free_quantity,
       :total_quantity, :total_amount
     ]
  )
end


问:
Exclude integer values from list that have difference less than 80
I have a list that contains many values like

```<code>mylist = [4361, 4868,4878, 5395, 5940, 6539, 6544, 7164 ]
</code>```

In case I have values that have difference less than 80,  like 4868,4878 I want to exclude the second one and keep only 4868 and get the indexes of the those that are deleted.

The new resulted list will be

```<code>my_list = [4361, 4868, 5395, 5940, 6539, 7164]
</code>```

Is there an easy way to achieve this?

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

```<code>mylist = [4361, 4868, 4878, 5395, 5940, 6539, 7164]

new = [x for x, y in zip(mylist, mylist[1:]) if y - x >= 80]
if mylist[-1] - new[-2] >= 80:
    new.append(mylist[-1])
</code>```

Body:
I have a list that contains many values like

mylist = [4361, 4868,4878, 5395, 5940, 6539, 6544, 7164 ]

In case I have values that have difference less than 80,  like 4868,4878 I want to exclude the second one and keep only 4868 and get the indexes of the those that are deleted.

The new resulted list will be

my_list = [4361, 4868, 5395, 5940, 6539, 7164]

Is there an easy way to achieve this?

Body:
This should do the trick:

mylist = [4361, 4868, 4878, 5395, 5940, 6539, 7164]

new = [x for x, y in zip(mylist, mylist[1:]) if y - x >= 80]
if mylist[-1] - new[-2] >= 80:
    new.append(mylist[-1])