答:
```<code>JSONObject jsonObject= new JSONObject(all_data);

JSONArray jsonArray = jsonObject.getJSONArray("appointments");
 // To get elements from the array
for(int i=0;i<jsonArray.length;i++){
  JSONObject json = jsonArray.getJSONObject(i);
  String id = json.getString("id");
  String name=json.getString("cid");
}
</code>```

Title: Android JSON parsing error cannot be converted to JSONArray

Body:
I'm fairly new to Android dev, and am trying to write a programme to parse some JSON from a website and output it in a ListView. However, when I run my programme, I get the error: (There are more then 7 row same as this error)

03-31 05:25:14.296 3196-3196/nazilli.tenispark E/FAILED: Json parsing
error: Value
{"0":"2","id":"2","1":"0","cid":"0","2":"1","uid":"1","3":"2017-04-01","date":"2017-04-01","4":"20","hour":"20"}
of type org.json.JSONObject cannot be converted to JSONArray

03-31 05:25:14.297 3196-3196/nazilli.tenispark E/FAILED: Json parsing error:
Value
{"0":"3","id":"3","1":"0","cid":"0","2":"1","uid":"1","3":"2017-04-08","date":"2017-04-08","4":"20","hour":"20"}
of type org.json.JSONObject cannot be converted to JSONArray

The JSON I'm trying to parse is:

{"appointments":[{"0":"2","id":"2","1":"0","cid":"0","2":"1","uid":"1","3":"2017-04-01","date":"2017-04-01","4":"20","hour":"20"},{"0":"3","id":"3","1":"0","cid":"0","2":"1","uid":"1","3":"2017-04-08","date":"2017-04-08","4":"20","hour":"20"},{"0":"4","id":"4","1":"0","cid":"0","2":"1","uid":"1","3":"2017-04-15","date":"2017-04-15","4":"20","hour":"20"},{"0":"5","id":"5","1":"0","cid":"0","2":"1","uid":"1","3":"2017-04-22","date":"2017-04-22","4":"20","hour":"20"},{"0":"6","id":"6","1":"0","cid":"0","2":"1","uid":"1","3":"2017-03-24","date":"2017-03-24","4":"17","hour":"17"},{"0":"7","id":"7","1":"0","cid":"0","2":"1","uid":"1","3":"2017-03-26","date":"2017-03-26","4":"17","hour":"17"},{"0":"8","id":"8","1":"1","cid":"1","2":"1","uid":"1","3":"2017-03-26","date":"2017-03-26","4":"16","hour":"16"},{"0":"9","id":"9","1":"2","cid":"2","2":"1","uid":"1","3":"2017-03-26","date":"2017-03-26","4":"15","hour":"15"},{"0":"10","id":"10","1":"3","cid":"3","2":"1","uid":"1","3":"2017-03-26","date":"2017-03-26","4":"13","hour":"13"}]}

this my listview custom row java

public class adapter_appointment extends ArrayAdapter<String> {
    public adapter_appointment(Context context, String[] data){
        super(context, R.layout.row_layout, data);
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        LayoutInflater inflater = LayoutInflater.from(getContext());
        View customView = inflater.inflate(R.layout.row_layout, parent, false);
        String all_data = getItem(position);
        TextView title = (TextView) customView.findViewById(R.id.title);
        //title.setText(all_data.toString());
        try {
            JSONArray array = new JSONArray(all_data);
            JSONObject obj = array.getJSONObject(0);
            Log.d("SUCCESS", "JSON Object: " + obj.toString());
            if (obj.has("date") && !obj.isNull("date")) {
                title.setText(obj.getString("date").toString());
                Log.d("SUCCESS", "Date: " + obj.getString("date").toString());
            } else {
                // Do something
            }
        } catch (Exception e) {
            Log.e("FAILED", "Json parsing error: " + e.getMessage());
        }
        return customView;
    }
}

This is json.java

public class my_appointments extends AppCompatActivity {
    ListView lv;
    InputStream is = null;
    String line = null;
    String result = null;
    String[] data;

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

        lv=(ListView) findViewById(R.id.my_appointments);
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitNetwork().build());
        //Run
        getData();
        ArrayAdapter adapter = new adapter_appointment(this, data);
        lv.setAdapter(adapter);
    }

    private void getData()
    {
        try {
            URL url = new URL("MY URL");
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("GET");
            is=new BufferedInputStream(con.getInputStream());
            //
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            StringBuilder sb = new StringBuilder();
            while((line=br.readLine()) != null)
            {
                sb.append(line + "\n");
            }
            is.close();
            result=sb.toString();
            //
            JSONObject jo = new JSONObject(result);
            JSONArray ja = jo.getJSONArray("appointments");
            data = new String[ja.length()];
            for(int i=0;i<ja.length();i++)
            {
                jo=ja.getJSONObject(i);
                data[i]=jo.toString();
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}

If I don't parse:


来源: stackexchange

问:
"The resource cannot be found." error when there is a "dot" at the end of the url
I'm using ASP .NET MVC Beta and I get the HTTP 404 (The resource cannot be found) error when I use this url which has a "dot" at the end:

http://localhost:81/Title/Edit/Code1.

If I remove the dot at the end or the dot is somewhere in the middle I don't get the error.

I tried to debug but it I get the error from "System.Web.CachedPathData.GetConfigPathData(String configPath)" before ProcessRequest in MvcHandler.

Is "dot" not allowed at the end of a url? Or is there a way to fix the route definition to handle this url?

For an example: I have a table named Detail1 [Id(integer), Code(string), Description(string)] which has FK relationship with Master1 through it's Id column. Whenever I select a record of Master1, I also select it's Detail1 record to get it's Code field. In order to not to make this join everytime (since usually there isn't only one detail, there are more than one) I choose not to use Id column and I make Code PK of Detail1.

But when I get rid of Id and use Code as PK then my routes also start to work with Code field, like: Detail1\Edit\Code1

This Code can have anything in it or at the end, including DOT. There are cases where I can prohibit a DOT at the end but sometimes it's really meaningfull.

And I'have also seen this post that routes can be very flexible, so I didn't think mine is so weird.

So that's why I do something so non-standard. Any suggestions?

And also why it's so weird to have a DOT at the end of a url?

答:
Why can't you have a dot-terminated URI?

Because a URI is a resource request and a historical imperitive exists on all relevant operating systems that the dot character is the extension separator. The last dot is treated as denoting a file extension, hence dot-terminating will make no sense.

Also worth reading:

RFC1738

RFC3986

ContentLicense: CC BY-SA 3.0

LastEditorDisplayName: Fabian Steeg

OwnerDisplayName: annakata

ContentLicense: CC BY-SA 2.5


问:
IE8: "The system cannot find the path specified" error when acessing window.localStorage
I have some javascript code which accesses window.localStorage, and it's working fine on most machines, but in one of them (IE8 compat view, Windows 7 64) I get the error "The system cannot find the path specified" whenever I try to read window.localStorage. I've tried to find some discussions about it at SO and Google (no cigar) and didn't find any suspicious setting at the browser's options. Has anyone encountered this error, and a solution for it? I could put a try/catch around window.localStorage but I'd rather understand what is going on.</p>

答:
Take a look at Which browsers support html5 offline storage.

According to that list IE8's supported. If it's only on one pc where you have the problem then check if there are plugins for that browser that might interfere.


问:
Box constraint in libsvm package (compare MATLAB fitcsvm and libsvm options)
These are options of LIBSVM package:

```<code>   options:
    -s svm_type : set type of SVM (default 0)
        0 -- C-SVC
        1 -- nu-SVC
        2 -- one-class SVM
        3 -- epsilon-SVR
        4 -- nu-SVR
    -t kernel_type : set type of kernel function (default 2)
        0 -- linear: u'*v
        1 -- polynomial: (gamma*u'*v + coef0)^degree
        2 -- radial basis function: exp(-gamma*|u-v|^2)
        3 -- sigmoid: tanh(gamma*u'*v + coef0)
    -d degree : set degree in kernel function (default 3)
    -g gamma : set gamma in kernel function (default 1/num_features)
    -r coef0 : set coef0 in kernel function (default 0)
    -c cost : set the parameter C of C-SVC, epsilon-SVR, and nu-SVR (default 1)
    -n nu : set the parameter nu of nu-SVC, one-class SVM, and nu-SVR (default 0.5)
    -p epsilon : set the epsilon in loss function of epsilon-SVR (default 0.1)
    -m cachesize : set cache memory size in MB (default 100)
    -e epsilon : set tolerance of termination criterion (default 0.001)
    -h shrinking: whether to use the shrinking heuristics, 0 or 1 (default 1)
    -b probability_estimates: whether to train a SVC or SVR model for probability estimates, 0 or 1 (default 0)
    -wi weight: set the parameter C of class i to weight*C, for C-SVC (default 1)
</code>```

Which one is svm box-constraint? Is it -c? If not, How can I calculate that? Currently I'm converting my LIBSVM code to MATLAB fitcsvm function. We have these options in MATLAB:

```<code>    'Cost' — Misclassification cost
    square matrix | structure array
    Misclassification cost, specified as the comma-separated pair consisting of 'Cost' and a square matrix or structure. If you specify:

    The square matrix Cost, then Cost(i,j) is the cost of classifying a point into class j if its true class is i (i.e., the rows correspond to the true class and the columns correspond to the predicted class). To specify the class order for the corresponding rows and columns of Cost, additionally specify the ClassNames name-value pair argument.
    The structure S, then it must have two fields:
    S.ClassNames, which contains the class names as a variable of the same data type as Y
    S.ClassificationCosts, which contains the cost matrix with rows and columns ordered as in S.ClassNames
    For two-class learning, if you specify a cost matrix, then the software updates the prior probabilities by incorporating the penalties described in the cost matrix. Subsequently, the cost matrix resets to the default. For more details on the relationships and algorithmic behavior of BoxConstraint, Cost, Prior, Standardize, and Weights, see Algorithms.

    The defaults are:

    For one-class learning, Cost = 0.
    For two-class learning, Cost(i,j) = 1 if i ~= j, and Cost(i,j) = 0 if i = j.
    Example: 'Cost',[0,1;2,0]

    Data Types: double | single | struct
</code>```

///

```<code>'BoxConstraint' — Box constraint
1 (default) | positive scalar
Box constraint, specified as the comma-separated pair consisting of 'BoxConstraint' and a positive scalar.

For one-class learning, the software always sets the box constraint to 1.

For more details on the relationships and algorithmic behavior of BoxConstraint, Cost, Prior, Standardize, and Weights, see Algorithms.

Example: 'BoxConstraint',100

Data Types: double | single
</code>```

What are differences between cost and BoxConstraint comparing to above libsvm package options?

答:
google and found following:

-c  = BoxConstraint

-wi ≈ cost

-g = 1/(KernelScale^2) if RBF used

Body:
These are options of LIBSVM package:

   options:
    -s svm_type : set type of SVM (default 0)
        0 -- C-SVC
        1 -- nu-SVC
        2 -- one-class SVM
        3 -- epsilon-SVR
        4 -- nu-SVR
    -t kernel_type : set type of kernel function (default 2)
        0 -- linear: u'*v
        1 -- polynomial: (gamma*u'*v + coef0)^degree
        2 -- radial basis function: exp(-gamma*|u-v|^2)
        3 -- sigmoid: tanh(gamma*u'*v + coef0)
    -d degree : set degree in kernel function (default 3)
    -g gamma : set gamma in kernel function (default 1/num_features)
    -r coef0 : set coef0 in kernel function (default 0)
    -c cost : set the parameter C of C-SVC, epsilon-SVR, and nu-SVR (default 1)
    -n nu : set the parameter nu of nu-SVC, one-class SVM, and nu-SVR (default 0.5)
    -p epsilon : set the epsilon in loss function of epsilon-SVR (default 0.1)
    -m cachesize : set cache memory size in MB (default 100)
    -e epsilon : set tolerance of termination criterion (default 0.001)
    -h shrinking: whether to use the shrinking heuristics, 0 or 1 (default 1)
    -b probability_estimates: whether to train a SVC or SVR model for probability estimates, 0 or 1 (default 0)
    -wi weight: set the parameter C of class i to weight*C, for C-SVC (default 1)

Which one is svm box-constraint? Is it -c? If not, How can I calculate that? Currently I'm converting my LIBSVM code to MATLAB fitcsvm function. We have these options in MATLAB:

    'Cost' — Misclassification cost
    square matrix | structure array
    Misclassification cost, specified as the comma-separated pair consisting of 'Cost' and a square matrix or structure. If you specify:

    The square matrix Cost, then Cost(i,j) is the cost of classifying a point into class j if its true class is i (i.e., the rows correspond to the true class and the columns correspond to the predicted class). To specify the class order for the corresponding rows and columns of Cost, additionally specify the ClassNames name-value pair argument.
    The structure S, then it must have two fields:
    S.ClassNames, which contains the class names as a variable of the same data type as Y
    S.ClassificationCosts, which contains the cost matrix with rows and columns ordered as in S.ClassNames
    For two-class learning, if you specify a cost matrix, then the software updates the prior probabilities by incorporating the penalties described in the cost matrix. Subsequently, the cost matrix resets to the default. For more details on the relationships and algorithmic behavior of BoxConstraint, Cost, Prior, Standardize, and Weights, see Algorithms.

    The defaults are:

    For one-class learning, Cost = 0.
    For two-class learning, Cost(i,j) = 1 if i ~= j, and Cost(i,j) = 0 if i = j.
    Example: 'Cost',[0,1;2,0]

    Data Types: double | single | struct

///

'BoxConstraint' — Box constraint
1 (default) | positive scalar
Box constraint, specified as the comma-separated pair consisting of 'BoxConstraint' and a positive scalar.

For one-class learning, the software always sets the box constraint to 1.

For more details on the relationships and algorithmic behavior of BoxConstraint, Cost, Prior, Standardize, and Weights, see Algorithms.

Example: 'BoxConstraint',100

Data Types: double | single

What are differences between cost and BoxConstraint comparing to above libsvm package options?


问:
Invoking a rest api client
I have created a rest api in eclipse as a maven project.
MobileAnalyticsModel class for rest api is

```<code>package org.subhayya.amazonws.mobileanalytics;

import java.util.Date;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class MobileAnalyticsModel {

    private String name;
    private Date created;
    private String location;
    private String prize;
    private String requirement;

    public MobileAnalyticsModel() {

    }
    public MobileAnalyticsModel(String name, String location, String prize, String requirement) {

        this.name = name;
        this.location = location;
        this.prize = prize;
        this.requirement = requirement;
        this.created = new Date();
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Date getCreated() {
        return created;
    }

    public void setCreated(Date created) {
        this.created = created;
    }

    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }

    public String getPrize() {
        return prize;
    }

    public void setPrize(String prize) {
        this.prize = prize;
    }

    public String getRequirement() {
        return requirement;
    }

    public void setRequirement(String requirement) {
        this.requirement = requirement;
    }
}
</code>```

this is the json response of the created api:

and
this is my sample test code for invoking rest api:

```<code>package org.subhayya.example;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.core.MediaType;

public class SampleTestREstClient {

    public static void main(String[] args) {

        Client client = ClientBuilder.newClient( );
        String reponse = client.target("http://localhost:8080/AgentBasedCloudServiceCompositionFramework/webapi/mobileanalytics/mobileanalyticsjson")
                .request(MediaType.APPLICATION_JSON)
                .get(String.class);

        System.out.println(reponse);
    }}
</code>```

then i got full json response.. as

```<code> [{"created":"2017-03-30T14:36:58.56","location":"http://api.server.com","name":"Mobile Analytics","prize":"$1.00 per 1,000,000 Amazon Mobile Analytics events per month thereafter","requirement":"PutEvents"}]
</code>```

But I want to have the single parameter as my output, for e.g., name, location or requirement.I am creating client invoking code also in the same maven project. So I wrote my code as below

```<code>Client client = ClientBuilder.newClient( );
MobileAnalyticsModel reponse =
        client.target("http://localhost:8080/AgentBasedCloudServiceCompositionFramework/webapi/mobileanalytics/mobileanalyticsjson")
                    .request(MediaType.APPLICATION_JSON)
                    .get(MobileAnalyticsModel.class);

System.out.println(reponse.getName());
</code>```

But I am getting exception, So I changed it to System.out.println(reponse);
) get atleast JSON response, then also getting error.

how do I get single name parameter from the JSON response? I am new to this rest api..please help me to fix this as soon as possible.thanks in advance

答:
This code works for me..</p>

```<code> String url = "http://localhost:8080/AgentBasedCloudServiceCompositionFramework/webapi/mobileanalytics/";
            String city = "mobileanalyticsjson";
            Client client = ClientBuilder.newClient();
            WebTarget webTarget = client.register(JsonProcessingFeature.class).target(url);
            JsonArray jsonArray = webTarget.path(city)
                .request(MediaType.APPLICATION_JSON_TYPE).get(JsonArray.class);
            for (JsonObject jsonObject : jsonArray.getValuesAs(JsonObject.class)) {
                   System.out.println(jsonObject.getString("name"));
                   System.out.println(jsonObject.getString("location")); }
</code>```

Title: Invoking a rest api client

Body:
I have created a rest api in eclipse as a maven project.
MobileAnalyticsModel class for rest api is

package org.subhayya.amazonws.mobileanalytics;

import java.util.Date;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class MobileAnalyticsModel {

    private String name;
    private Date created;
    private String location;
    private String prize;
    private String requirement;

    public MobileAnalyticsModel() {

    }
    public MobileAnalyticsModel(String name, String location, String prize, String requirement) {

        this.name = name;
        this.location = location;
        this.prize = prize;
        this.requirement = requirement;
        this.created = new Date();
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Date getCreated() {
        return created;
    }

    public void setCreated(Date created) {
        this.created = created;
    }

    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }

    public String getPrize() {
        return prize;
    }

    public void setPrize(String prize) {
        this.prize = prize;
    }

    public String getRequirement() {
        return requirement;
    }

    public void setRequirement(String requirement) {
        this.requirement = requirement;
    }
}

this is the json response of the created api:

and
this is my sample test code for invoking rest api:

package org.subhayya.example;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.core.MediaType;

public class SampleTestREstClient {

    public static void main(String[] args) {

        Client client = ClientBuilder.newClient( );
        String reponse = client.target("http://localhost:8080/AgentBasedCloudServiceCompositionFramework/webapi/mobileanalytics/mobileanalyticsjson")
                .request(MediaType.APPLICATION_JSON)
                .get(String.class);

        System.out.println(reponse);
    }}

then i got full json response.. as

 [{"created":"2017-03-30T14:36:58.56","location":"http://api.server.com","name":"Mobile Analytics","prize":"$1.00 per 1,000,000 Amazon Mobile Analytics events per month thereafter","requirement":"PutEvents"}]

But I want to have the single parameter as my output, for e.g., name, location or requirement.I am creating client invoking code also in the same maven project. So I wrote my code as below

Client client = ClientBuilder.newClient( );
MobileAnalyticsModel reponse =
        client.target("http://localhost:8080/AgentBasedCloudServiceCompositionFramework/webapi/mobileanalytics/mobileanalyticsjson")
                    .request(MediaType.APPLICATION_JSON)
                    .get(MobileAnalyticsModel.class);

System.out.println(reponse.getName());

But I am getting exception, So I changed it to System.out.println(reponse);
) get atleast JSON response, then also getting error.

how do I get single name parameter from the JSON response? I am new to this rest api..please help me to fix this as soon as possible.thanks in advance

Body:
This code works for me..

 String url = "http://localhost:8080/AgentBasedCloudServiceCompositionFramework/webapi/mobileanalytics/";
            String city = "mobileanalyticsjson";
            Client client = ClientBuilder.newClient();
            WebTarget webTarget = client.register(JsonProcessingFeature.class).target(url);
            JsonArray jsonArray = webTarget.path(city)
                .request(MediaType.APPLICATION_JSON_TYPE).get(JsonArray.class);
            for (JsonObject jsonObject : jsonArray.getValuesAs(JsonObject.class)) {
                   System.out.println(jsonObject.getString("name"));
                   System.out.println(jsonObject.getString("location")); }


问:
how to put pictures in a row bootstrap
I'm trying to get these 3 pictures in a row with no or little spaces in between, but this code is causing them to stack on top of each other.  I also want them to be aligned to the center of the page.</p>

```<code><div class="container">
  <div class="row col-xs-2">
  <img style= "width: 25%; height: 25%" src="https://image.ibb.co/ckA7ka/mr_marbles.png" alt="Mister Marbles head tilt">
</div>
<div class="row col-xs-2">
  <img style= "width: 25%; height: 25%"  src="https://image.ibb.co/bTMKyv/kermit.png" alt="Kermit the Dog">
</div>
<div class="row col-xs-2">
  <img style= "width: 25%; height: 25%" src="https://image.ibb.co/ki8tQa/peach.png" alt="Peach posing magestically">
</div>
</div>
</code>```

答:
```<code><div class="row">

<div class="col-lg-4 col-md-4 col-xs-4 thumb">
    <a class="thumbnail" href="#">
        <img class="img-responsive" src="http://placehold.it/400x300" alt="">
    </a>
</div>
<div class="col-lg-4 col-md-4 col-xs-4 thumb">
    <a class="thumbnail" href="#">
        <img class="img-responsive" src="http://placehold.it/400x300" alt="">
    </a>
</div>
<div class="col-lg-4 col-md-4 col-xs-4 thumb">
    <a class="thumbnail" href="#">
        <img class="img-responsive" src="http://placehold.it/400x300" alt="">
    </a>
</div>
</code>```

Title: how to put pictures in a row bootstrap


问:
How to tackle this session problem in ASP.NET,VB.NET?
How to tackle this session problem in ASP.NET,VB.NET?

The following requirement are there:

When the authorized user logs into the system that user is not allowed to login from another computer or in different browser other than that user is using right at this time.

The remedy we applied was: We have kept "Is_Loggedin" as a column with data type "bit" in a mst_vendor as a table name. When a user logs in we set the flag, Is_Loggedin, to "1" and each time when someone tries to log in using this account, the system is showing the error "The user is already logged in.".

When the user logs out it turns to "0" as the logout procedure calls as soon as the user clicks the log out button.

Problem scenario:

When the user closes the browser the flag remains the same, that is, "1".

When power gets off, it remains the same as "1".

If the session timeouts after a predefined value it remains the same.

There may be different scenarios other than this.

Is there any way so that we can store this internal flagging for the user's login status using the application object?

It may improve efficiency of the system and also eliminates the above problematic scenarios.

答:
Store a datetime as another column next to the bit, and update it each and every time the user requests a page.

When a new user comes along with the same credentials and the bit is "1" you can check the datetime, and if it was a while ago you can be certain the user is no longer there.  So let the login go ahead.


问:
Azure Webjobs timing out, not receiving response from webapi
I have a Azure Webjob which hits a WebApi. The WebApi sends back an acknowledgement in 4 - 5mins. So, I have declared the TimeOut for the HttpClient to be at 10 mins.

Now, if the WebApi is returning the response in less than 4 mins, it works fine. But if the WebApi is returning the response for a request in 4 min 30 sec, the azure  webjob is not getting this acknowledgement. Instead, the HttpClient on the WebJob is waiting for 10 mins, and then timing out. Is there some kind of a time out on the Webjob that I'm missing?

答:
There is a 230 second timeout for requests that are not sending any data back. Please see the answer of @David Ebbo in following thread.

https://social.msdn.microsoft.com/Forums/en-US/17305ddc-07b2-436c-881b-286d1744c98f/503-errors-with-large-pdf-file?forum=windowsazurewebsitespreview

There is a 230 second (i.e. a little less than 4 mins) timeout for requests that are not sending any data back. After that, the client gets the 500 you saw, even though in reality the request is allowed to continue server side.

So the issue of not receiving response from Web API is related to the timeout limit of Azure Web App.  I also test it on my side. Though I set executionTimeout as 10min in web.config.

```<code><httpRuntime targetFramework="4.6" executionTimeout="600" />
</code>```

If the time of sending response from service side need more than 230s. I will get a 500 error on my client side.

```<code>public IEnumerable<string> Get()
{
    Thread.Sleep(270000);
    return new string[] { "value1", "value2" };
}
</code>```

I suggest you accept the suggestion of @Thomas.  Writing your response to a queue from your Web API and get the response  which you needed from the queue.

So, is there no method to bypass this timeout?

The 230 sec limit also could be proved in following article.

there is a general idle request timeout that will cause clients to get disconnected after 230 seconds.

https://github.com/projectkudu/kudu/wiki/Configurable-settings

I haven't found any ways to modify this timeout for Azure Web App. Please try the workarounds which I mentioned above.

Body:
There is a 230 second timeout for requests that are not sending any data back. Please see the answer of @David Ebbo in following thread.

https://social.msdn.microsoft.com/Forums/en-US/17305ddc-07b2-436c-881b-286d1744c98f/503-errors-with-large-pdf-file?forum=windowsazurewebsitespreview

There is a 230 second (i.e. a little less than 4 mins) timeout for requests that are not sending any data back. After that, the client gets the 500 you saw, even though in reality the request is allowed to continue server side.

So the issue of not receiving response from Web API is related to the timeout limit of Azure Web App.  I also test it on my side. Though I set executionTimeout as 10min in web.config.

<httpRuntime targetFramework="4.6" executionTimeout="600" />

If the time of sending response from service side need more than 230s. I will get a 500 error on my client side.

public IEnumerable<string> Get()
{
    Thread.Sleep(270000);
    return new string[] { "value1", "value2" };
}

I suggest you accept the suggestion of @Thomas.  Writing your response to a queue from your Web API and get the response  which you needed from the queue.

So, is there no method to bypass this timeout?

The 230 sec limit also could be proved in following article.

there is a general idle request timeout that will cause clients to get disconnected after 230 seconds.

https://github.com/projectkudu/kudu/wiki/Configurable-settings

I haven't found any ways to modify this timeout for Azure Web App. Please try the workarounds which I mentioned above.


问:
Why does process.argv[3] return something completely unexpected when it is '*'?
I've got a very simple calculator app:

```<code>if (process.argv[3]==='+') console.log(parseInt(process.argv[2]) + parseInt(process.argv[4]));
if (process.argv[3]==='-') console.log(parseInt(process.argv[2]) - parseInt(process.argv[4]));
if (process.argv[3]==='*') console.log(parseInt(process.argv[2]) * parseInt(process.argv[4]));
if (process.argv[3]==='/') console.log(parseInt(process.argv[2]) / parseInt(process.argv[4]));
console.log(process.argv[3])
</code>```

2 + 2, 2 - 2, 2 / 2 all work as expected, but 2 * 2 will log out the name of the script.

Why does this happen? What is it about the multiplication sign?

答:
It's because * is a shell wildcard, It has a special meaning to the shell, which expands it before passing it to the node.

You have to pass it with \* like this or "*" or like this '*'.

Body:
I've got a very simple calculator app:

if (process.argv[3]==='+') console.log(parseInt(process.argv[2]) + parseInt(process.argv[4]));
if (process.argv[3]==='-') console.log(parseInt(process.argv[2]) - parseInt(process.argv[4]));
if (process.argv[3]==='*') console.log(parseInt(process.argv[2]) * parseInt(process.argv[4]));
if (process.argv[3]==='/') console.log(parseInt(process.argv[2]) / parseInt(process.argv[4]));
console.log(process.argv[3])

2 + 2, 2 - 2, 2 / 2 all work as expected, but 2 * 2 will log out the name of the script.

Why does this happen? What is it about the multiplication sign?


问:
Deflating objects in specs2 (scala) and checking order of elements in sequence
Trying to write a small test case for already written code. Quiet new to Scala.

I have a service returning object like in result val

```<code>scala.util.Either[Error,Seq[Employee]]
</code>```

I want to write a test case using specs2 which can make sure that the order of Employee sequence is exactly in the same order as my test data.

Order of my test data is like this:

```<code>val fakeEmployee: Seq[Employee] = Seq(
      Employee("first", "Simon"),
      Employee("second", "Ajay"),
      Employee("third", "Xavior")
)
</code>```

What is the best way to deflate this object to get the Sequence object out and then check if sequence has objects in same order as fakeEmployee
something like this.

```<code>result.map {
   **Seq(Employee) must contain(allOf(".......").inOrder)**
}
</code>```

答:
This should work:</p>

```<code>val expected: Seq[Employee] = Seq(
  Employee("first", "Simon"),
  Employee("second", "Ajay"),
  Employee("third", "Xavior")
)

val result: Either[Error, Seq[Employee]] = ???

result must beRight(expected)
</code>```

Body:
Trying to write a small test case for already written code. Quiet new to Scala.

I have a service returning object like in result val

scala.util.Either[Error,Seq[Employee]]

I want to write a test case using specs2 which can make sure that the order of Employee sequence is exactly in the same order as my test data.

Order of my test data is like this:

val fakeEmployee: Seq[Employee] = Seq(
      Employee("first", "Simon"),
      Employee("second", "Ajay"),
      Employee("third", "Xavior")
)

What is the best way to deflate this object to get the Sequence object out and then check if sequence has objects in same order as fakeEmployee
something like this.

result.map {
   **Seq(Employee) must contain(allOf(".......").inOrder)**
}

Body:
This should work:

val expected: Seq[Employee] = Seq(
  Employee("first", "Simon"),
  Employee("second", "Ajay"),
  Employee("third", "Xavior")
)

val result: Either[Error, Seq[Employee]] = ???

result must beRight(expected)


问:
Get rid of strings containing a pattern within a file
Within a linux file with the following content I want to get rid of everything starting with a specific pattern, which is aws: in this particular case:

```<code>aws:cloudformation:logical-id="somestring" Name="abc" Product="xyz" Role="www" aws:autoscaling:groupName="strings-and-numbers-012345" aws:cloudformation:stack-id="strings-and-numbers-012345" aws:cloudformation:stack-name="strings-and-numbers-012345"
</code>```

The output I need is just: Name="abc" Product="xyz" Role="www"; how do I do it?

答:
In awk:

```<code>$ awk '{for(i=1;i<=NF;i++)if($i!~/^aws:/)b=b(b==""?"":OFS)$i;print b;b=""}' file
Name="abc" Product="xyz" Role="www"
</code>```

Explained:

```<code>{
    for(i=1;i<=NF;i++)             # iterate over every field
        if($i!~/^aws:/)            # if it doesn't start start with aws:
            b=b (b==""?"":OFS) $i  # buffer it to b with OFS
    print b                        # never stop iterating till the iterating is done and output
    b=""                           # reset buffer
}
</code>```

Downside is, it prints an empty line if every field starts with an aws:. Avoid that with if(b!="") before the print b.

Body:
Within a linux file with the following content I want to get rid of everything starting with a specific pattern, which is aws: in this particular case:

aws:cloudformation:logical-id="somestring" Name="abc" Product="xyz" Role="www" aws:autoscaling:groupName="strings-and-numbers-012345" aws:cloudformation:stack-id="strings-and-numbers-012345" aws:cloudformation:stack-name="strings-and-numbers-012345"

The output I need is just: Name="abc" Product="xyz" Role="www"; how do I do it?

Body:
In awk:

$ awk '{for(i=1;i<=NF;i++)if($i!~/^aws:/)b=b(b==""?"":OFS)$i;print b;b=""}' file
Name="abc" Product="xyz" Role="www"

Explained:

{
    for(i=1;i<=NF;i++)             # iterate over every field
        if($i!~/^aws:/)            # if it doesn't start start with aws:
            b=b (b==""?"":OFS) $i  # buffer it to b with OFS
    print b                        # never stop iterating till the iterating is done and output
    b=""                           # reset buffer
}

Downside is, it prints an empty line if every field starts with an aws:. Avoid that with if(b!="") before the print b.


问:
Python "with" statement can occur TOCTOU?
Assume that, file.txt is closed or deleted during the delay between open and write. (or it can ?)

Then, this situation can occur TOCTOU ?

with statement sure that atomic until with block or not?

```<code>with open("file.txt") as f :
    # ...delayed...
    f.write("something")
</code>```

答:
Can this occur?

Use case 1: Python itself deletes the file*

yes it can happen. I just tested like this:

```<code>In [1]: with open("file.txt", "w") as f :
   ...:     f.write("Something Old")
   ...:

In [2]: !cat ./file.txt
Something Old
In [3]: import os
   ...: with open("file.txt","w") as f:
   ...:     os.remove("./file.txt")
   ...:     print f.write("Something new")
   ...:
None

In [4]: !cat ./file.txt
cat: ./file.txt: No such file or directory
</code>```

Use Case 2: Other than python deletes the file.

Then also, found the behavior to be same.

```<code>In [1]: !cat ./file.txt
Something Old
In [2]: import os
   ...: import time
   ...:
   ...: with open("file.txt","w") as f:
   ...:     time.sleep(15)
   ...:     print f.write("Something new")
   ...:
None

In [3]: !cat ./file.txt
cat: ./file.txt: No such file or directory
</code>```

How to avoid it?

You can use exclusive lock from fcntl.lockf()

Edit: There is one more caveat here. Locking the file may not be straight forward and may be OS dependent like What is the best way to open a file for exclusive access in Python?

Body:
Assume that, file.txt is closed or deleted during the delay between open and write. (or it can ?)

Then, this situation can occur TOCTOU ?

with statement sure that atomic until with block or not?

with open("file.txt") as f :
    # ...delayed...
    f.write("something")

Body:
Can this occur?

Use case 1: Python itself deletes the file*

yes it can happen. I just tested like this:

In [1]: with open("file.txt", "w") as f :
   ...:     f.write("Something Old")
   ...:

In [2]: !cat ./file.txt
Something Old
In [3]: import os
   ...: with open("file.txt","w") as f:
   ...:     os.remove("./file.txt")
   ...:     print f.write("Something new")
   ...:
None

In [4]: !cat ./file.txt
cat: ./file.txt: No such file or directory

Use Case 2: Other than python deletes the file.

Then also, found the behavior to be same.

In [1]: !cat ./file.txt
Something Old
In [2]: import os
   ...: import time
   ...:
   ...: with open("file.txt","w") as f:
   ...:     time.sleep(15)
   ...:     print f.write("Something new")
   ...:
None

In [3]: !cat ./file.txt
cat: ./file.txt: No such file or directory

How to avoid it?

You can use exclusive lock from fcntl.lockf()

Edit: There is one more caveat here. Locking the file may not be straight forward and may be OS dependent like What is the best way to open a file for exclusive access in Python?


问:
How can I prevent a sticky footer + content editable div from having overlapping content
So I have a jsfiddle describing a contenteditable div with a sticky footer area representing: https://jsfiddle.net/xd5p1h7u/

CSS

```<code>.textarea {
  background: white;
  padding: 20px;
  min-height: 20px;
  width: 100%;
}
.footer {
  height: 20px;
  position: sticky;
  bottom: 0;
  background: blue;
}
</code>```

HTML

```<code><div class="textarea" contenteditable="true"></div>
<div class="footer"></div>
</code>```

If you type until you get to the bottom of the screen, you'll notice that the sticky footer covers up the bottom content. I've tried a variety of the typical techniques like adding bottom/top margins and paddings in various places to prevent the content from getting covered up.

Is there a purely css way to achieve this effect without overlapping content?

答:
By update your CSS like this, does that solve your issue?

Updated fiddle

Stack snippet

html, body {
  margin: 0;
}
.textarea {
  background: white;
  padding: 20px;
  min-height: 20px;
  width: 100%;
  max-height: calc(100vh - 20px);
  overflow: auto;
  box-sizing: border-box;
}
.footer {
  height: 20px;
  position: sticky;
  bottom: 0;
  background: blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="textarea" contenteditable="true">
content<br>
content<br>
content<br>
content<br>
content<br>
content<br>
content<br>
content<br>
content<br>
content<br>
content<br>
content<br>
content<br>
content<br>
content<br>
content<br>
content<br>
content<br>
content<br>
content<br>
content<br>
content<br>
</div>
<div class="footer">

</div></code>```

Body:
So I have a jsfiddle describing a contenteditable div with a sticky footer area representing: https://jsfiddle.net/xd5p1h7u/

CSS

.textarea {
  background: white;
  padding: 20px;
  min-height: 20px;
  width: 100%;
}
.footer {
  height: 20px;
  position: sticky;
  bottom: 0;
  background: blue;
}

HTML

If you type until you get to the bottom of the screen, you'll notice that the sticky footer covers up the bottom content. I've tried a variety of the typical techniques like adding bottom/top margins and paddings in various places to prevent the content from getting covered up.

Is there a purely css way to achieve this effect without overlapping content?

Body:
By update your CSS like this, does that solve your issue?

Updated fiddle

Stack snippet

html, body {
  margin: 0;
}
.textarea {
  background: white;
  padding: 20px;
  min-height: 20px;
  width: 100%;
  max-height: calc(100vh - 20px);
  overflow: auto;
  box-sizing: border-box;
}
.footer {
  height: 20px;
  position: sticky;
  bottom: 0;
  background: blue;
}

<div class="textarea" contenteditable="true">
content<br>
content<br>
content<br>
content<br>
content<br>
content<br>
content<br>
content<br>
content<br>
content<br>
content<br>
content<br>
content<br>
content<br>
content<br>
content<br>
content<br>
content<br>
content<br>
content<br>
content<br>
content<br>
</div>
<div class="footer">

</div>


问:
Get folder next to parent folder in either Path.GetDirectory or Server.MapPath
Consider the two paths, one in a solution and the other in IIS:

Solution Path:

C:\Users\userid\Desktop\File\Solution\RootName\ Folder1 \Folder1a\the.aspx

IIS path

C:\inetpub\wwwroot\RootName\webApplication\ Folder1 \Folder1a\the.aspx

Is there a way using Directory or Server or anything at all to get the FIRST folder name after the Parent Directory?

ie in the given above, Folder1 is the first folder after the parent folder.

I can get the opposite, which is the containing folder name from a filepath (in this example, Folder1a) and I can iterate it to get to the answer :

Path.GetFileName(Path.GetDirectoryName(file));

But the problem is, folders can be nested at any amount: (folder1a\folder1a1\folder1a1a...)

How can I get the first folder name after the Parent Directory given a file path?

as an aside,
If there is no foldername (ex. Folder1 does not exist) the answer should output "" (empty)

答:
Below is what I have tried that works.

Since I simply needed to output the first page after the word, I iterated Path.GetDirectoryName and Path.GetFileName until I could match the root folder.

Ex:

```<code>                baseFoldr = "";
                var curFile = Path.GetDirectoryName(file);
                string curName = Path.GetFileName(curFile);

                while (curName.ToLower() != "RootName")
                {
                        curFile = Path.GetDirectoryName(curFile);
                        baseFoldr = curName;
                        curName = Path.GetFileName(curFile);

                }

                return baseFoldr;
</code>```

I still believe there could be a better answer, though

Body:
Below is what I have tried that works.

Since I simply needed to output the first page after the word, I iterated Path.GetDirectoryName and Path.GetFileName until I could match the root folder.

Ex:

                baseFoldr = "";
                var curFile = Path.GetDirectoryName(file);
                string curName = Path.GetFileName(curFile);

                while (curName.ToLower() != "RootName")
                {
                        curFile = Path.GetDirectoryName(curFile);
                        baseFoldr = curName;
                        curName = Path.GetFileName(curFile);

                }

                return baseFoldr;

I still believe there could be a better answer, though


问:
how to use jwplatform api using python
I am going to create search api for Android and iOS developers.
Our client have setup a lambda function in AWS.
Now we need to fetch data using jwplatform Api based on search keyword passed as parameter. For this, I have to install jwplatform module in Lambda function or upload zip file of code with dependencies. So that i want to run python script locally and after getting appropriate result i will upload zip in AWS Lambda.
I want to use the videos/list (jwplatform Api) class to search the video library using python but i don't know much about Python. So i want to know how to run python script? and where should i put the pyhton script ?</p>

答:
I am succeed to install jwplatform module locally.
Steps are as follows:
1. Open command line
2. Type 'python' on command line
3. Type command 'pip install jwplatform'
4. Now, you can use jwplatform api.

Above command added module jwplatform in python locally
But my another challenge is to install jwplatform in AWS Lambda.

After research i am succeed to install module in AWS Lambda. I have bundled module and code in a directory then create zip of bundle and upload it in AWS Lambda. This will install module(jwplatform) in AWS Lambda.

Title: how to use jwplatform api using python


问:
error import android eclipse project in Android Studio
Error:Execution failed for task ':app:processDebugManifest'.

Manifest merger failed : uses-sdk:minSdkVersion 8 cannot be smaller than version 9 declared in library [com.google.android.gms:play-services:8.4.0] C:\Users\admin\Desktop\RingtoneApp2\app\build\intermediates\exploded-aar\com.google.android.gms\play-services\8.4.0\AndroidManifest.xml
      Suggestion: use tools:overrideLibrary="com.google.android.gms.all" to force usage

I used the site
http://developer.android.com/sdk/installing/migrate.html

答:
First Remove the google play library(in this case com.google.android.gms.play_services), then open manifests --> AndroidManifest.xml and change min sdk version to 9

This Line: android:minSdkVersion="9"

Also Change it in your build.gradle of app.. under the defaultConfig


问:
how to handle click function on ion-toggle
here is my .html file

```<code><ion-item no-lines (click)="update()" >
        <ion-label> Notification</ion-label>
        <ion-toggle [(ngModel)]="notify" ></ion-toggle>
    </ion-item>
</code>```

the above code works when i click on the Notification text but when i click on the ion-toggle i am not able to invoke the function what should i do to invoke the function.

here is my .ts file

```<code>update(){
 console.log("invoking notification");
}
</code>```

答:
If you use ngModel it's best to use ngModelChange

```<code><ion-toggle [(ngModel)]="notify" (ngModelChange)="update($event)" ></ion-toggle>
</code>```

otherwise you can use

```<code><ion-toggle (ionChange)="update($event)"></ion-toggle>
</code>```

See also https://ionicframework.com/docs/api/components/toggle/Toggle/

Body:
here is my .html file

<ion-item no-lines (click)="update()" >
        <ion-label> Notification</ion-label>
        <ion-toggle [(ngModel)]="notify" ></ion-toggle>
    </ion-item>

the above code works when i click on the Notification text but when i click on the ion-toggle i am not able to invoke the function what should i do to invoke the function.

here is my .ts file

update(){
 console.log("invoking notification");
}

Body:
If you use ngModel it's best to use ngModelChange

<ion-toggle [(ngModel)]="notify" (ngModelChange)="update($event)" ></ion-toggle>

otherwise you can use

<ion-toggle (ionChange)="update($event)"></ion-toggle>

See also https://ionicframework.com/docs/api/components/toggle/Toggle/


问:
Codeigniter - 403 Forbidden Access when sending array with 3000 entries via Ajax
I have a Controller which consumes Ajax requests and responds with the result of the database operation. The Ajax call is formed with a set of IDs (an array of ints) and a message.

When the set of IDs have a normal ammount of IDs (I tested with 20 IDs), the Ajax call returns normally. When trying to send 3000 IDs, I get an almost instant response with a 403 Forbidden Access error.

This is probably a Codeigniter or Apache server error. I looked for it, but didn't find any answer.

Thanks in advance.

答:
By default php.ini has 1000 max_input_vars variable.

Here you have the docs how to change

Change that and you will fix the issue. I had the same problem before.

Ex: placing following lines into .htaccess

```<code>php_value max_input_vars 3000
php_value suhosin.get.max_vars 3000
php_value suhosin.post.max_vars 3000
php_value suhosin.request.max_vars 3000
</code>```

Body:
By default php.ini has 1000 max_input_vars variable.

Here you have the docs how to change

Change that and you will fix the issue. I had the same problem before.

Ex: placing following lines into .htaccess

php_value max_input_vars 3000
php_value suhosin.get.max_vars 3000
php_value suhosin.post.max_vars 3000
php_value suhosin.request.max_vars 3000


问:
Spring Data JPA: Invalid object name if use more than one Config Class in jUnit test
I receive SQLServerException when run test:

```<code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {OlmeFtpConfig.class, OlmeCapConfig.class}, loader = AnnotationConfigContextLoader.class)
public class FirmsRepositoryTest {

    @Autowired
    FirmsRepository firmsRepository;
    @Autowired
    ExtraDAO extraDAO;

    @Test
    public void save() throws Exception {

        int extraID = extraDAO.getMaxExtraID();

        FirmsEntity firmsEntity = new FirmsEntity();
            firmsEntity.setBoCode(DataGenerator.getNumberText(5));
            firmsEntity.setextraID(extraID);
            firmsEntity.setFirmShortName(DataGenerator.getNumberText(10));
            firmsEntity.setId(DataGenerator.getNumberBetween(9999,99999));

        FirmsEntity save = firmsRepository.save(firmsEntity);
        assertNotNull(save);

    }
</code>```

The full stack trace is:

```<code>org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet

    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:261)
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:244)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:491)
    at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:59)
    at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:147)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:133)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:57)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
    at com.sun.proxy.$Proxy68.save(Unknown Source)
    at com.pivotal.olme.jpa.dao.FirmsRepositoryTest.save(FirmsRepositoryTest.java:41)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:237)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: org.hibernate.exception.SQLGrammarException: could not extract ResultSet
    at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:106)
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:97)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:79)
    at org.hibernate.loader.Loader.getResultSet(Loader.java:2123)
    at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1911)
    at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1887)
    at org.hibernate.loader.Loader.doQuery(Loader.java:932)
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:349)
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:319)
    at org.hibernate.loader.Loader.loadEntity(Loader.java:2205)
    at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:61)
    at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:51)
    at org.hibernate.persister.entity.AbstractEntityPersister.load(AbstractEntityPersister.java:4071)
    at org.hibernate.event.internal.DefaultLoadEventListener.loadFromDatasource(DefaultLoadEventListener.java:508)
    at org.hibernate.event.internal.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:478)
    at org.hibernate.event.internal.DefaultLoadEventListener.load(DefaultLoadEventListener.java:219)
    at org.hibernate.event.internal.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:278)
    at org.hibernate.event.internal.DefaultLoadEventListener.doOnLoad(DefaultLoadEventListener.java:121)
    at org.hibernate.event.internal.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:89)
    at org.hibernate.internal.SessionImpl.fireLoad(SessionImpl.java:1230)
    at org.hibernate.internal.SessionImpl.access$1900(SessionImpl.java:203)
    at org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.doLoad(SessionImpl.java:2787)
    at org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.load(SessionImpl.java:2761)
    at org.hibernate.internal.SessionImpl.get(SessionImpl.java:1071)
    at org.hibernate.event.internal.DefaultMergeEventListener.entityIsDetached(DefaultMergeEventListener.java:290)
    at org.hibernate.event.internal.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:170)
    at org.hibernate.event.internal.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:69)
    at org.hibernate.internal.SessionImpl.fireMerge(SessionImpl.java:874)
    at org.hibernate.internal.SessionImpl.merge(SessionImpl.java:860)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:298)
    at com.sun.proxy.$Proxy45.merge(Unknown Source)
    at org.springframework.data.jpa.repository.support.SimpleJpaRepository.save(SimpleJpaRepository.java:511)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:504)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:489)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:461)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:61)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
    ... 38 more
Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: Invalid object name 'stg.FIRMS'.
    at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:217)
    at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1635)
    at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(SQLServerPreparedStatement.java:426)
    at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute(SQLServerPreparedStatement.java:372)
    at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:6276)
    at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1793)
    at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:184)
    at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLServerStatement.java:159)
    at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.executeQuery(SQLServerPreparedStatement.java:284)
    at org.apache.commons.dbcp2.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:83)
    at org.apache.commons.dbcp2.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:83)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:70)
    ... 86 more
</code>```

FirmsRepossitory looks like:

```<code>@Repository
public interface FirmsRepository extends CrudRepository<FirmsEntity, FirmsEntityPK> {

    @Modifying
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    FirmsEntity save(FirmsEntity firmsEntity);

}
</code>```

If I use only OlmeFtpConfig.class in @ContextConfiguration(classes = {OlmeFtpConfig.class} the test executes without any exception.

But in some test (where application works with two databases) i need to use both config classes. There are different datasources in each config class.

How to run test without exception and use two config class in @ContextConfiguration annotation? So I need springframework can find stg.FIRMS.

答:
You mention that you have two DataSources in your configurations. It's hard to guess what exactly is going on, but it sounds like you are effectively accessing the wrong DataSource with your repository.

There is an example how to properly setup Spring Data in case of multiple DataSources, which should help.

To quote the readme:

To connect to two databases we need to manually configure a DataSource, EntityManagerFactory and JpaTransactionManager.

Below is the configuration for one of the sets of beans, which you have to adapt to the settings you need in your test and you need to duplicate it for the two DataSources with different bean names.

```<code>@Configuration
@EnableJpaRepositories(entityManagerFactoryRef = "customerEntityManagerFactory",
        transactionManagerRef = "customerTransactionManager")
class CustomerConfig {

    @Bean
    PlatformTransactionManager customerTransactionManager() {
        return new JpaTransactionManager(customerEntityManagerFactory().getObject());
    }

    @Bean
    LocalContainerEntityManagerFactoryBean customerEntityManagerFactory() {

        HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
        jpaVendorAdapter.setGenerateDdl(true);

        LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();

        factoryBean.setDataSource(customerDataSource());
        factoryBean.setJpaVendorAdapter(jpaVendorAdapter);
        factoryBean.setPackagesToScan(CustomerConfig.class.getPackage().getName());

        return factoryBean;
    }

    @Bean
    DataSource customerDataSource() {

        return new EmbeddedDatabaseBuilder().//
                setType(EmbeddedDatabaseType.HSQL).//
                setName("customers").//
                build();
    }
}
</code>```

Body:
I receive SQLServerException when run test:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {OlmeFtpConfig.class, OlmeCapConfig.class}, loader = AnnotationConfigContextLoader.class)
public class FirmsRepositoryTest {

    @Autowired
    FirmsRepository firmsRepository;
    @Autowired
    ExtraDAO extraDAO;

    @Test
    public void save() throws Exception {

        int extraID = extraDAO.getMaxExtraID();

        FirmsEntity firmsEntity = new FirmsEntity();
            firmsEntity.setBoCode(DataGenerator.getNumberText(5));
            firmsEntity.setextraID(extraID);
            firmsEntity.setFirmShortName(DataGenerator.getNumberText(10));
            firmsEntity.setId(DataGenerator.getNumberBetween(9999,99999));

        FirmsEntity save = firmsRepository.save(firmsEntity);
        assertNotNull(save);

    }

The full stack trace is:

org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet

    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:261)
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:244)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:491)
    at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:59)
    at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:147)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:133)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:57)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
    at com.sun.proxy.$Proxy68.save(Unknown Source)
    at com.pivotal.olme.jpa.dao.FirmsRepositoryTest.save(FirmsRepositoryTest.java:41)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:237)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: org.hibernate.exception.SQLGrammarException: could not extract ResultSet
    at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:106)
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:97)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:79)
    at org.hibernate.loader.Loader.getResultSet(Loader.java:2123)
    at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1911)
    at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1887)
    at org.hibernate.loader.Loader.doQuery(Loader.java:932)
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:349)
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:319)
    at org.hibernate.loader.Loader.loadEntity(Loader.java:2205)
    at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:61)
    at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:51)
    at org.hibernate.persister.entity.AbstractEntityPersister.load(AbstractEntityPersister.java:4071)
    at org.hibernate.event.internal.DefaultLoadEventListener.loadFromDatasource(DefaultLoadEventListener.java:508)
    at org.hibernate.event.internal.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:478)
    at org.hibernate.event.internal.DefaultLoadEventListener.load(DefaultLoadEventListener.java:219)
    at org.hibernate.event.internal.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:278)
    at org.hibernate.event.internal.DefaultLoadEventListener.doOnLoad(DefaultLoadEventListener.java:121)
    at org.hibernate.event.internal.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:89)
    at org.hibernate.internal.SessionImpl.fireLoad(SessionImpl.java:1230)
    at org.hibernate.internal.SessionImpl.access$1900(SessionImpl.java:203)
    at org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.doLoad(SessionImpl.java:2787)
    at org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.load(SessionImpl.java:2761)
    at org.hibernate.internal.SessionImpl.get(SessionImpl.java:1071)
    at org.hibernate.event.internal.DefaultMergeEventListener.entityIsDetached(DefaultMergeEventListener.java:290)
    at org.hibernate.event.internal.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:170)
    at org.hibernate.event.internal.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:69)
    at org.hibernate.internal.SessionImpl.fireMerge(SessionImpl.java:874)
    at org.hibernate.internal.SessionImpl.merge(SessionImpl.java:860)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:298)
    at com.sun.proxy.$Proxy45.merge(Unknown Source)
    at org.springframework.data.jpa.repository.support.SimpleJpaRepository.save(SimpleJpaRepository.java:511)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:504)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:489)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:461)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:61)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
    ... 38 more
Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: Invalid object name 'stg.FIRMS'.
    at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:217)
    at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1635)
    at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(SQLServerPreparedStatement.java:426)
    at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute(SQLServerPreparedStatement.java:372)
    at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:6276)
    at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1793)
    at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:184)
    at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLServerStatement.java:159)
    at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.executeQuery(SQLServerPreparedStatement.java:284)
    at org.apache.commons.dbcp2.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:83)
    at org.apache.commons.dbcp2.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:83)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:70)
    ... 86 more

FirmsRepossitory looks like:

@Repository
public interface FirmsRepository extends CrudRepository<FirmsEntity, FirmsEntityPK> {

    @Modifying
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    FirmsEntity save(FirmsEntity firmsEntity);

}

If I use only OlmeFtpConfig.class in @ContextConfiguration(classes = {OlmeFtpConfig.class} the test executes without any exception.

But in some test (where application works with two databases) i need to use both config classes. There are different datasources in each config class.

How to run test without exception and use two config class in @ContextConfiguration annotation? So I need springframework can find stg.FIRMS.

Body:
You mention that you have two DataSources in your configurations. It's hard to guess what exactly is going on, but it sounds like you are effectively accessing the wrong DataSource with your repository.

There is an example how to properly setup Spring Data in case of multiple DataSources, which should help.

To quote the readme:

To connect to two databases we need to manually configure a DataSource, EntityManagerFactory and JpaTransactionManager.

Below is the configuration for one of the sets of beans, which you have to adapt to the settings you need in your test and you need to duplicate it for the two DataSources with different bean names.

@Configuration
@EnableJpaRepositories(entityManagerFactoryRef = "customerEntityManagerFactory",
        transactionManagerRef = "customerTransactionManager")
class CustomerConfig {

    @Bean
    PlatformTransactionManager customerTransactionManager() {
        return new JpaTransactionManager(customerEntityManagerFactory().getObject());
    }

    @Bean
    LocalContainerEntityManagerFactoryBean customerEntityManagerFactory() {

        HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
        jpaVendorAdapter.setGenerateDdl(true);

        LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();

        factoryBean.setDataSource(customerDataSource());
        factoryBean.setJpaVendorAdapter(jpaVendorAdapter);
        factoryBean.setPackagesToScan(CustomerConfig.class.getPackage().getName());

        return factoryBean;
    }

    @Bean
    DataSource customerDataSource() {

        return new EmbeddedDatabaseBuilder().//
                setType(EmbeddedDatabaseType.HSQL).//
                setName("customers").//
                build();
    }
}


问:
Multiple jquery ajax on page not working
I've got 2 ajax requests on one page. Both work fine on separate pages, but when they're both on the same page, one stops working after the first has been run.

I'm using the Colorbox plugin for one request and this works fine. The other I've put together myself (I'm new to jquery, so may well have errors) and works if I run it first. But once Colorbox has been activated it stops working.

The page is here: http://dev.thetram.net/times/test2.php and the code below.

Would really appreciate some pointers to where I'm going wrong, thanks!

```<code><script type="text/javascript">
<!--
$(document).ready(function(){

$(function() {
$('#parkride').change(function () {

$.ajax({
    type: "POST",
 url: "http://dev.thetram.net/inc/parkingfinder_script.asp",
 dataType: "application/x-www-form-urlencoded",
 data: "Action=GetPR&Val=" + $("#parkride").val(),
 async: false,
 success: function(msg) {
     $('#output').html("<li>" + msg + "</li>");
 }
 });
return false;
    });
  });

$(function() {
//if submit button is clicked
$('form#frm_journeyplanner #submit').click(function () {

//get form values
var str = $("form#frm_journeyplanner").serialize();

$.ajax({
    type: "POST",
    url: "http://dev.thetram.net/inc/journeyplanner/jp_testscript.asp",
 dataType: "application/x-www-form-urlencoded",
    data: str,
 async: false,
 success: function(msg) {
  $('#results').html(msg);
  $.colorbox({inline:true, href:"#results", opacity:0.6, innerWidth:620, innerHeight:580, title:"Find tram times",
  onOpen:function(){  $("#results").show(); }, //make sure results show in the modal window
  onClosed:function(){ $("#results").hide(); } //stop results from displaying on the main page
   });
 }
 });
return false;
    });
  });

}); // end of doc ready
-->
</script>
</code>```

答:
Try removing the

```<code>async: false
</code>```

line. This tells jQuery to run the request synchronously, which blocks the browser until the request comlpetes.

Body:
Try removing the

async: false

line. This tells jQuery to run the request synchronously, which blocks the browser until the request comlpetes.


问:
My version of Heroku doesn't offer pg:backups:download
I'm using Cloud9 IDE. According to the heroku version command, I'm running

```<code>heroku-toolbelt/3.43.13 (x86_64-linux) ruby/2.3.0
heroku-cli/5.4.8-eee5ec9 (linux-amd64) go1.7.1
</code>```

with no installed plugins.

I'm trying to download the database from one of my production apps to use in another. In doing so, I get the error,

```<code>`pg:backups:download` is not a heroku command
</code>```

When I run heroku help, my list shows "pgbackups" as a valid command, not "pg:backups", which is what I should see, according to the latest documentation.

When I run heroku help pgbackups, it lists options for capture, restore, destroy, transfer, and url.

Any ideas what's going on here? Thanks for any insight.

答:
Please install new verion of heroku Cli, ref link:
https://devcenter.heroku.com/articles/heroku-cli

Since in your list show 'pgbackups'
it means your are using older version which consists of pgbackups addon that got deprecated.
ref link: https://devcenter.heroku.com/changelog-items/623

You can create a publicly accessible backup URL with the pg:backups:url command. When the command is specified without a backup id, the latest available backup URL will be returned. This is useful for exporting your data outside of Heroku Postgres:

```<code>1) List you backups
   heroku pg:backups --app your_app_name

2) heroku pg:backups:url b001 --app your_app_name
</code>```

after this you will get this output which consist of url

The following URL will expire at 2015-04-07 18:35:50 +0000:
"http://s3.amazonaws.com/xkpgbackups/app1234567@heroku.com/b004.dump?AWSAccessKeyId=ABCD1234&Expires=1289261668&Signature=3mMBeKISewgEUDT%2FL5mRz4EYS4M%3D"

you can then download the dump by clicking on the url.

Body:
I'm using Cloud9 IDE. According to the heroku version command, I'm running

heroku-toolbelt/3.43.13 (x86_64-linux) ruby/2.3.0
heroku-cli/5.4.8-eee5ec9 (linux-amd64) go1.7.1

with no installed plugins.

I'm trying to download the database from one of my production apps to use in another. In doing so, I get the error,

`pg:backups:download` is not a heroku command

When I run heroku help, my list shows "pgbackups" as a valid command, not "pg:backups", which is what I should see, according to the latest documentation.

When I run heroku help pgbackups, it lists options for capture, restore, destroy, transfer, and url.

Any ideas what's going on here? Thanks for any insight.

Body:
Please install new verion of heroku Cli, ref link:
https://devcenter.heroku.com/articles/heroku-cli

Since in your list show 'pgbackups'
it means your are using older version which consists of pgbackups addon that got deprecated.
ref link: https://devcenter.heroku.com/changelog-items/623

You can create a publicly accessible backup URL with the pg:backups:url command. When the command is specified without a backup id, the latest available backup URL will be returned. This is useful for exporting your data outside of Heroku Postgres:

1) List you backups
   heroku pg:backups --app your_app_name

2) heroku pg:backups:url b001 --app your_app_name

after this you will get this output which consist of url

The following URL will expire at 2015-04-07 18:35:50 +0000:
"http://s3.amazonaws.com/xkpgbackups/app1234567@heroku.com/b004.dump?AWSAccessKeyId=ABCD1234&Expires=1289261668&Signature=3mMBeKISewgEUDT%2FL5mRz4EYS4M%3D"

you can then download the dump by clicking on the url.


问:
How do I close the panel when clicked on 'x' button and click on the screen using angularjs?(new to angular)
Here is my HTML code for my button

```<code>  <button class="btn btn-outlined  " ng-click="vm.showCommentBox1()">Notify All</button>
    <div class="comment-box custom saveAll" ng-if=""><div class="panel panel-default">
                  <div class="panel-heading">
                    <button type="button" class="close" aria-label="Close" ng-click="comment=true" title="Close comment box"><span aria-hidden="true">Ã—</span>
                      </button>
                    <h3 class="panel-title blue-30">Comment</h3>
                  </div>
                  <div class="panel-body">
                    <form>
                      <div class="form-group">
                        <textarea class="form-control bg-white" ng-model=""
                          placeholder="Add your description"></textarea>
                      </div>
                    </form>
                  </div>
                </div>
              </div>
</code>```

so when i click the 'x' button the panel should get closed

答: Simply use ng-if="comment===true" on the desired element in order to remove the element when you have set comment to true by pressing to 'x' button.

Body:
Here is my HTML code for my button

  <button class="btn btn-outlined  " ng-click="vm.showCommentBox1()">Notify All</button>

                    <button type="button" class="close" aria-label="Close" ng-click="comment=true" title="Close comment box">Ã—
                      </button>

Comment

                    <form>

                        <textarea class="form-control bg-white" ng-model=""
                          placeholder="Add your description"></textarea>

                    </form>

so when i click the 'x' button the panel should get closed


问:
Can PL/pgSQL return a function from a function? Or even a set of functions?
Can I declare a PL/pgSQL function where the return type is a function?  Or even a set of functions?  Is there even a function type in the language?

I was noodling with the idea of a library of PL/pgSQL functions that could handle function chaining to make using the library easier.  Syntax akin to method dispatch isn't possible, but returning a function from a function should allow for some basic syntax magic.  Unfortunately I don't have enough of a mastery of PL/pgSQL yet to try to describe what I'm asking in a code example, I hope the question is clear enough as stated.

A variant of this question, Is SQL a functional language was asked 8 years ago, but my question is a little more specific (besides, the #1 answer on that question is incorrect!).

答:
There is a datatype to represent function references: regprocedure.

What there isn't, as far as I'm aware, is a way to use such a reference to directly invoke the function. I think the best you could do is to construct a SELECT statement which calls the function, and run it via EXECUTE. At this point, it's not a whole lot different to simply passing function names around as strings (though using regprocedure does mean that case-folding and overload resolution are all handled for you).

There's probably not a lot you could do without knowing something about the function's inputs and outputs, so you would probably want to familiarise yourself with the pg_proc catalog.


问:
jQuery trigger("click") not working
Can someone please explain what is wrong with the pasted code. It shows alert on hover but does not perform click event like I expect, and click does not work on either  tag or <select> tag. My purpose is to expand the select element on hover by triggering click event

```<code><!DOCTYPE html>
<html>

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
</head>

<body>
    <a id="linkElement" href="www.google.co.uk">click</a>

    <select name="cars" id="selectElemet">
      <option value="volvo">Volvo</option>
      <option value="saab">Saab</option>
      <option value="fiat">Fiat</option>
      <option value="audi">Audi</option>
    </select>

    <script>
        $(document).ready(function () {
            $("#selectElement").mouseover(function () {
                $("#selectElement").trigger("click");
            });

            $("#linkElement").mouseover(function () {
                alert('here');
                $("#linkElement").trigger("click");
            });
        });
    </script>
</body>

</html>
</code>```

答: trigger('click') just happen where you have set 'click' event with element ,not physical 'click'.for example,trigger('click') even don't trigger '' tag if attach without 'click' </p>

Title: jQuery trigger("click") not working

Body:
Can someone please explain what is wrong with the pasted code. It shows alert on hover but does not perform click event like I expect, and click does not work on either  tag or <select> tag. My purpose is to expand the select element on hover by triggering click event

<!DOCTYPE html>

    click

    <select name="cars" id="selectElemet">
      <option value="volvo">Volvo</option>
      <option value="saab">Saab</option>
      <option value="fiat">Fiat</option>
      <option value="audi">Audi</option>
    </select>


问:
Sequence of images to video in OpenCV + range of reading
Already fighting with this problem for a whole day, maybe anyone can help? Have a basic knowledge at Mathlab, python and openCV
I am use python for make a video from images. And, as usually, found a problem with it. There is no sequence in reading image's for writing video. For example i have img_01,img_02,.....img_n. Each img - frame of video. And at final video it's looks like:

./img_155.jpg
./img_476.jpg
./img_282.jpg
and etc.

So, it's totally chaotic at the final video, as result...
Is anyone can help, please, with this problem? I found a lot of hints, but all of them with c++ only. There is code, what i am using now:

```<code>import cv2
import argparse
import os

# Construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-ext", "--extension", required=False, default='jpg', help="extension name. default is 'png'.")
ap.add_argument("-o", "--output", required=False, default='output.mp4', help="output video file")
args = vars(ap.parse_args())

# Arguments
dir_path = '.'
ext = args['extension']
output = args['output']

images = []
for f in os.listdir(dir_path):
    if f.endswith(ext):
        images.append(f)

# Determine the width and height from the first image
image_path = os.path.join(dir_path, images[0])
frame = cv2.imread(image_path)
cv2.imshow('video',frame)
height, width, channels = frame.shape

# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'mp4v') # Be sure to use lower case
out = cv2.VideoWriter(output, fourcc, 30.0, (width, height))

for image in images:

    image_path = os.path.join(dir_path, image)
    frame = cv2.imread(image_path)

    out.write(frame) # Write out frame to video

    cv2.imshow('video',frame)
    if (cv2.waitKey(1) & 0xFF) == ord('q'): # Hit `q` to exit
        break

# Release everything if job is finished
out.release()
cv2.destroyAllWindows()

print("The output video is {}".format(output))
</code>```

答:
I think your problem is : for f in os.listdir(dir_path): return file name in random sequence.

You should add follow line before '# Determine the width and height from the first image'

```<code>def name2num(name):
   m = re.search('img_(\d+)\.?.*', name)
   return int(m.group(1),10)

images.sort(key=name2num)
</code>```

Body:
Already fighting with this problem for a whole day, maybe anyone can help? Have a basic knowledge at Mathlab, python and openCV
I am use python for make a video from images. And, as usually, found a problem with it. There is no sequence in reading image's for writing video. For example i have img_01,img_02,.....img_n. Each img - frame of video. And at final video it's looks like:

./img_155.jpg
./img_476.jpg
./img_282.jpg
and etc.

So, it's totally chaotic at the final video, as result...
Is anyone can help, please, with this problem? I found a lot of hints, but all of them with c++ only. There is code, what i am using now:

import cv2
import argparse
import os

# Construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-ext", "--extension", required=False, default='jpg', help="extension name. default is 'png'.")
ap.add_argument("-o", "--output", required=False, default='output.mp4', help="output video file")
args = vars(ap.parse_args())

# Arguments
dir_path = '.'
ext = args['extension']
output = args['output']

images = []
for f in os.listdir(dir_path):
    if f.endswith(ext):
        images.append(f)

# Determine the width and height from the first image
image_path = os.path.join(dir_path, images[0])
frame = cv2.imread(image_path)
cv2.imshow('video',frame)
height, width, channels = frame.shape

# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'mp4v') # Be sure to use lower case
out = cv2.VideoWriter(output, fourcc, 30.0, (width, height))

for image in images:

    image_path = os.path.join(dir_path, image)
    frame = cv2.imread(image_path)

    out.write(frame) # Write out frame to video

    cv2.imshow('video',frame)
    if (cv2.waitKey(1) & 0xFF) == ord('q'): # Hit `q` to exit
        break

# Release everything if job is finished
out.release()
cv2.destroyAllWindows()

print("The output video is {}".format(output))

Body:
I think your problem is : for f in os.listdir(dir_path): return file name in random sequence.

You should add follow line before '# Determine the width and height from the first image'

def name2num(name):
   m = re.search('img_(\d+)\.?.*', name)
   return int(m.group(1),10)

images.sort(key=name2num)


问:
Failed to capture snapshot of output files for task
Error:Failed to capture snapshot of output files for task 'transformClassesWithDexForDebug' property 'streamOutputFolder' during up-to-date check.

Failed to create MD5 hash for file 'C:\Users\GauravZone\AndroidStudioProjects\ZopporoStore\app\build\intermediates\transforms\dex\debug\folders\1000\10000\instant-run_83dbc65f4e3a4cd278807c089695c6b352698791\classes.dex'.

I am getting these errors don't know why, all application working fine earlier but suddenly getting this error in my all applications when try to run projects

答: Disable your antivirus, and it will work.

ContentLicense: CC BY-SA 4.0


问:
How to delete login session of Digit?
I have installed Digit mobile verification in my app and when the user verifies his mobile number and comes back, the app works fine. Now if the user want to make a sign up process again, his session is automatically created. Since I'm using this to only verify user's mobile number and then continue with my own sign up process. How can I do that?

I want to just Remove all sessions.

答:
You need to call the method below before initialise.</p>

```<code>Digits.sharedInstance().logOut()

let digits = Digits.sharedInstance()
</code>```

Title: How to delete login session of Digit?

Body:
You need to call the method below before initialise.

Digits.sharedInstance().logOut()

let digits = Digits.sharedInstance()


问:
Changing connection string for different Users
My application used Code first approach & Entity Framework 6.0.

My requirement is that when a User A logs in connection string AppSchema should be used for whole application & when User B logs in connection string AppSchema1 should be used. My application is very big, i want to achieve this from a central location.

Below is the code :-

Connection String :-

```<code> <add name="AppSchema" connectionString="Data Source=Server1\MSSQLSERVER2014;Initial Catalog=MSchema;Integrated Security=True;Persist Security Info=True;" providerName="System.Data.SqlClient" />
</code>```

Connection String 2 :-

```<code><add name="AppSchema1" connectionString="Data Source=Server1\MSSQLSERVER2014;Initial Catalog=MSchema;Integrated Security=True;Persist Security Info=True;" providerName="System.Data.SqlClient" />
</code>```

ApplicationDbContext :-

```<code>public class ApplicationDbContext : IdentityDbContext<ApplicationUser>, IDbModelCacheKeyProvider, IDisposable
{
     public ApplicationDbContext(string schemaname)
                : base("AppSchema")
            {
                SchemaName = schemaname;
                ((IObjectContextAdapter)this).ObjectContext.CommandTimeout = 180;
            }
}
</code>```

Use :-

```<code> using (var ctx = new ApplicationDbContext(schemaName))
    {
        ....
        ctx.tblEmployee.Add(mod);
    }
</code>```

Can anyone suggest how to do this?

答:
Overload the DbContext's constructor with the name of a connection string.

```<code> public class ExampleDBContext : DbContext
    {
    public ExampleDBContext(string nameOrConnectionString) :
       base(nameOrConnectionString)
    {

    }
}
</code>```

pass the name of a configured connection string or a connection string when you instantiate your DbContext.

```<code>  var context = new ExampleDBContext ( "set name Or ConnectionString in run time");
</code>```

Body:
My application used Code first approach & Entity Framework 6.0.

My requirement is that when a User A logs in connection string AppSchema should be used for whole application & when User B logs in connection string AppSchema1 should be used. My application is very big, i want to achieve this from a central location.

Below is the code :-

Connection String :-

 <add name="AppSchema" connectionString="Data Source=Server1\MSSQLSERVER2014;Initial Catalog=MSchema;Integrated Security=True;Persist Security Info=True;" providerName="System.Data.SqlClient" />

Connection String 2 :-

<add name="AppSchema1" connectionString="Data Source=Server1\MSSQLSERVER2014;Initial Catalog=MSchema;Integrated Security=True;Persist Security Info=True;" providerName="System.Data.SqlClient" />

ApplicationDbContext :-

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>, IDbModelCacheKeyProvider, IDisposable
{
     public ApplicationDbContext(string schemaname)
                : base("AppSchema")
            {
                SchemaName = schemaname;
                ((IObjectContextAdapter)this).ObjectContext.CommandTimeout = 180;
            }
}

Use :-

 using (var ctx = new ApplicationDbContext(schemaName))
    {
        ....
        ctx.tblEmployee.Add(mod);
    }

Can anyone suggest how to do this?

Body:
Overload the DbContext's constructor with the name of a connection string.

 public class ExampleDBContext : DbContext
    {
    public ExampleDBContext(string nameOrConnectionString) :
       base(nameOrConnectionString)
    {

    }
}

pass the name of a configured connection string or a connection string when you instantiate your DbContext.

  var context = new ExampleDBContext ( "set name Or ConnectionString in run time");