问:
Android http post results in strange I/O error
I have an activity which has 2 edittext controls and a button. User fills in the edittexts and taps on the button.

Here is the button onclick event:

```<code>public void submitHelpRequest(View v)
{
    final Button submitButton = (Button)findViewById(R.id.submithelprequest);
    submitButton.setEnabled(false);
    EditText titleElm;
    EditText messageElm;
    titleElm = (EditText)findViewById(R.id.helprequestitle);
    messageElm = (EditText)findViewById(R.id.helprequestmessage);
    String titleValue = titleElm.getText().toString();
    String messageValue = messageElm.getText().toString();
    new NWThread().execute("snip", titleValue, messageValue);
}
</code>```

Here is my NWThread:

```<code>private class NWThread extends AsyncTask<String, Void, Void> {
    @Override
    protected Void doInBackground(String... values) {

        Post(values[0], values[1], values[2]);
        return null;
    }
}
</code>```

Here is Post()

```<code>public void Post(String webAddress, final String title, final String message)
{
    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(webAddress);

        String auth = new String(Base64.encode(( "snip" + ":" + "snip").getBytes(),Base64.URL_SAFE| Base64.NO_WRAP));
        httpPost.addHeader("Authorization", "Basic " + auth);

        String json = "";

        JSONObject object = new JSONObject();
        object.put("Title", title);
        object.put("Message", message);

        json = object.toString();

        StringEntity se = new StringEntity(json);

        httpPost.setEntity(se);
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");

        HttpResponse httpResponse = httpclient.execute(httpPost);

    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}
</code>```

I am getting some strange errors when i click on the button:

```<code>06-05 16:59:50.971 25135-2533 W/art: Failed to open zip archive '/system/framework/qcom.fmradio.jar': I/O Error
[ 06-05 16:59:50.971 25135:25332 W/] Unable to open '/system/framework/oem-services.jar': No such file or directory
06-05 16:59:50.971 25135-2533 W/art: Failed to open zip archive '/system/framework/oem-services.jar': I/O Error
</code>```

Also in Android Studio it says that HttpClient and HttpPost are deprecated, could this be why? And if so which classes in the SDK should I be using?

Edit: Here is the whole activity

```<code>package ui;

import android.content.Context;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;

import java.net.HttpURLConnection;
import java.net.URL;

public class ScreenSendHelpRequestActivity extends AppCompatActivity {

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

    public void submitHelpRequest(View v)
    {
        final Button submitButton = (Button)findViewById(R.id.submithelprequest);
        submitButton.setEnabled(false);
        EditText titleElm;
        EditText messageElm;
        titleElm = (EditText)findViewById(R.id.helprequestitle);
        messageElm = (EditText)findViewById(R.id.helprequestmessage);
        String titleValue = titleElm.getText().toString();
        String messageValue = messageElm.getText().toString();

        new NWThread().execute("snip", titleValue, messageValue);
    }

    private class NWThread extends AsyncTask<String, Void, Void> {
        @Override
        protected Void doInBackground(String... urls) {

            Post(urls[0], urls[1], urls[2]);
            return null;
        }
    }

    public void Post(String webAddress, final String title, final String message)
    {
        try {
            URL url1 = new URL(webAddress);
            HttpURLConnection cnx = (HttpURLConnection)url1.openConnection();
            cnx.setRequestMethod("POST");
            cnx.setRequestProperty("Content-type", "application/json");
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(webAddress);

            String auth = new String(Base64.encode(( "snip" + ":" + "snip").getBytes(),Base64.URL_SAFE| Base64.NO_WRAP));
            httpPost.addHeader("Authorization", "Basic " + auth);

            String json = "";

            JSONObject object = new JSONObject();
            object.put("Title", title);
            object.put("Message", message);

            json = object.toString();

            StringEntity se = new StringEntity(json);

            httpPost.setEntity(se);
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-type", "application/json");
            HttpResponse httpResponse = httpclient.execute(httpPost);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}
</code>```

答:
Also in Android Studio it says that HttpClient and HttpPost are deprecated, could this be why? And if so which classes in the SDK should I be using?

You should use Volley Library to do API REST and HTTP call.

I'll write down an example from you using the code from one of my activity app.
Please note that this example made a JSON request, is it possible also to do a StringRequest that returns a raw string (and also a JSONARRAYrequest).

```<code>    RequestQueue queue = Volley.newRequestQueue(this);
            String url = "https://www.google.it"; // your URI
            JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET,url, null, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    //Handle positive response
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
//Handle negative response
} {
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    Map<String,String> headers = new HashMap<>();
//put values headers
                    headers.put("user",username.getText().toString());
                    return headers;
                }
            };
            queue.add(request);
</code>```

Body:
I have an activity which has 2 edittext controls and a button. User fills in the edittexts and taps on the button.

Here is the button onclick event:

public void submitHelpRequest(View v)
{
    final Button submitButton = (Button)findViewById(R.id.submithelprequest);
    submitButton.setEnabled(false);
    EditText titleElm;
    EditText messageElm;
    titleElm = (EditText)findViewById(R.id.helprequestitle);
    messageElm = (EditText)findViewById(R.id.helprequestmessage);
    String titleValue = titleElm.getText().toString();
    String messageValue = messageElm.getText().toString();
    new NWThread().execute("snip", titleValue, messageValue);
}

Here is my NWThread:

private class NWThread extends AsyncTask<String, Void, Void> {
    @Override
    protected Void doInBackground(String... values) {

        Post(values[0], values[1], values[2]);
        return null;
    }
}

Here is Post()

public void Post(String webAddress, final String title, final String message)
{
    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(webAddress);

        String auth = new String(Base64.encode(( "snip" + ":" + "snip").getBytes(),Base64.URL_SAFE| Base64.NO_WRAP));
        httpPost.addHeader("Authorization", "Basic " + auth);

        String json = "";

        JSONObject object = new JSONObject();
        object.put("Title", title);
        object.put("Message", message);

        json = object.toString();

        StringEntity se = new StringEntity(json);

        httpPost.setEntity(se);
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");

        HttpResponse httpResponse = httpclient.execute(httpPost);

    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}

I am getting some strange errors when i click on the button:

06-05 16:59:50.971 25135-2533 W/art: Failed to open zip archive '/system/framework/qcom.fmradio.jar': I/O Error
[ 06-05 16:59:50.971 25135:25332 W/] Unable to open '/system/framework/oem-services.jar': No such file or directory
06-05 16:59:50.971 25135-2533 W/art: Failed to open zip archive '/system/framework/oem-services.jar': I/O Error

Also in Android Studio it says that HttpClient and HttpPost are deprecated, could this be why? And if so which classes in the SDK should I be using?

Edit: Here is the whole activity

package ui;

import android.content.Context;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;

import java.net.HttpURLConnection;
import java.net.URL;

public class ScreenSendHelpRequestActivity extends AppCompatActivity {

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

    public void submitHelpRequest(View v)
    {
        final Button submitButton = (Button)findViewById(R.id.submithelprequest);
        submitButton.setEnabled(false);
        EditText titleElm;
        EditText messageElm;
        titleElm = (EditText)findViewById(R.id.helprequestitle);
        messageElm = (EditText)findViewById(R.id.helprequestmessage);
        String titleValue = titleElm.getText().toString();
        String messageValue = messageElm.getText().toString();

        new NWThread().execute("snip", titleValue, messageValue);
    }

    private class NWThread extends AsyncTask<String, Void, Void> {
        @Override
        protected Void doInBackground(String... urls) {

            Post(urls[0], urls[1], urls[2]);
            return null;
        }
    }

    public void Post(String webAddress, final String title, final String message)
    {
        try {
            URL url1 = new URL(webAddress);
            HttpURLConnection cnx = (HttpURLConnection)url1.openConnection();
            cnx.setRequestMethod("POST");
            cnx.setRequestProperty("Content-type", "application/json");
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(webAddress);

            String auth = new String(Base64.encode(( "snip" + ":" + "snip").getBytes(),Base64.URL_SAFE| Base64.NO_WRAP));
            httpPost.addHeader("Authorization", "Basic " + auth);

            String json = "";

            JSONObject object = new JSONObject();
            object.put("Title", title);
            object.put("Message", message);

            json = object.toString();

            StringEntity se = new StringEntity(json);

            httpPost.setEntity(se);
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-type", "application/json");
            HttpResponse httpResponse = httpclient.execute(httpPost);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}

Body:
Also in Android Studio it says that HttpClient and HttpPost are deprecated, could this be why? And if so which classes in the SDK should I be using?

You should use Volley Library to do API REST and HTTP call.

I'll write down an example from you using the code from one of my activity app.
Please note that this example made a JSON request, is it possible also to do a StringRequest that returns a raw string (and also a JSONARRAYrequest).

    RequestQueue queue = Volley.newRequestQueue(this);
            String url = "https://www.google.it"; // your URI
            JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET,url, null, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    //Handle positive response
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
//Handle negative response
} {
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    Map<String,String> headers = new HashMap<>();
//put values headers
                    headers.put("user",username.getText().toString());
                    return headers;
                }
            };
            queue.add(request);


来源: stackexchange

问:
Prevent robots from coping images from a website
I have a website created in PHP technology and i want to prevent robots from coping images from the website.What is the best way to prevent robots from coping images from a website?

Please make sure it doesn't harm SEO.
Please make sure this does not influence spyders and crawlers from indexing the site.

答:
difficult, no fool proof way to do it, you can try to make it more difficult for the bots, though.

what comes to mind at the moment are:

create the image links using javascript (will force bots to execute the javascripts on the page)

use css sprites (i.e. pack several images together into one image), which might make it less useful for the bots (e.g. if they just wanna harvest and redisplay the images on their page, it will look a bit ugly on their site when several images are packed into one)

check http_referer and only serve proper images when http_referer is an allowed domain

put a water mark on top of the image with your domain name, makes it less useful for other sites

ContentLicense: CC BY-SA 2.5


问:
Access Printer to Print document in Salesforce using apex class
I am newbie to Sales force and I want to access my local printer to Print some document with apex class. I don't want use JavaScript.

Any help would be appreciated.

Thanks in Advance.

答:
Apex runs server side, on Salesforce servers.  It can't access your local printer.  Your browser can access your printer though.  In lightning or visualforce you can create a button to launch your browser's print function using</p>

```<code>window.print();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Apex runs server side, on Salesforce servers.  It can't access your local printer.  Your browser can access your printer though.  In lightning or visualforce you can create a button to launch your browser's print function using

window.print();


问:
Getting error "Action Error: Missing result from request body"
I'm running one of the examples in my own project and running into the error.

Action Error: Missing result from request body

Github Sample Project: dialogflow-silly-name-maker-webhook-nodejs

Hookbin:  Shows the webhook coming from the assistant.https://hookbin.com/bin/ZjPzJ1Yb

Might there be an error in the sample code or in my set-up?

答:
I was getting this error. In my case it was because the request object I was passing to ActionsSdkApp() constructor had a body property which was a JSON string as opposed to data structure.

Adding this in before instantiating ActionsSdkApp fixed it for me...

```<code>request.body = JSON.parse(request.body);
</code>```

Then I could carry on like this...

```<code>App = new ActionsSdkApp({'request': request, 'response': response});
</code>```

Body:
I was getting this error. In my case it was because the request object I was passing to ActionsSdkApp() constructor had a body property which was a JSON string as opposed to data structure.

Adding this in before instantiating ActionsSdkApp fixed it for me...

request.body = JSON.parse(request.body);

Then I could carry on like this...

App = new ActionsSdkApp({'request': request, 'response': response});


问:
Postgres view -- sum all values where dates are the same
I have a table that looks like the below

```<code>     project|issue|status   |story_points|sprint |date      |active_sprint
     ===============================================
     FB1    |abc  |In Review|     3      |Backlog|2017-06-05|True
     FB1    |acc  |In Review|     3      |Backlog|2017-06-05|True
     FB1    |adc  |In Review|     3      |Backlog|2017-06-04|True
     FB2    |xyz  |In Review|     3      |Backlog|2017-06-05|True
</code>```

Expected results

```<code>     open|project|date
     ===============================================
     6   |FB1    |2017-06-05
     3   |FB1    |2017-06-04
     3   |FB2    |2017-06-05
</code>```

I've tried for quite awhile and have looked all over but am still unable to figure this out.  I'm fairly new to postgres as well as views and was hoping to get some help.  I've tried a lot of different variations of what's below but am still unable to get this working.

```<code>    SELECT
    (SELECT COALESCE(SUM(story_points),0) AS "Open" from sample_table WHERE project = 'FB1' AND active_sprint='True' AND (status = 'In Review')) as "Open",
    (SELECT 'FB1'::text AS "Project") as "Project",
    (SELECT date as Date) as Date from sample_table WHERE project = 'FB1' group by 3
</code>```

答:
You could try something like this:</p>

```<code>select project, date1 , sum(story_points)
from asd1
group by project, date1
</code>```

Body:
I have a table that looks like the below

     project|issue|status   |story_points|sprint |date      |active_sprint
     ===============================================
     FB1    |abc  |In Review|     3      |Backlog|2017-06-05|True
     FB1    |acc  |In Review|     3      |Backlog|2017-06-05|True
     FB1    |adc  |In Review|     3      |Backlog|2017-06-04|True
     FB2    |xyz  |In Review|     3      |Backlog|2017-06-05|True

Expected results

     open|project|date
     ===============================================
     6   |FB1    |2017-06-05
     3   |FB1    |2017-06-04
     3   |FB2    |2017-06-05

I've tried for quite awhile and have looked all over but am still unable to figure this out.  I'm fairly new to postgres as well as views and was hoping to get some help.  I've tried a lot of different variations of what's below but am still unable to get this working.

    SELECT
    (SELECT COALESCE(SUM(story_points),0) AS "Open" from sample_table WHERE project = 'FB1' AND active_sprint='True' AND (status = 'In Review')) as "Open",
    (SELECT 'FB1'::text AS "Project") as "Project",
    (SELECT date as Date) as Date from sample_table WHERE project = 'FB1' group by 3

Body:
You could try something like this:

select project, date1 , sum(story_points)
from asd1
group by project, date1


问:
Read binary data and convert it into .wav or mp3 audio file
i am developing an web application in which i have to read binary from database base actually this is audio which is saved in the form or binary. how to convert this binary into wav or mp3 file </p>

答:
You do not need to 'convert' it, but if you want to allow a user to download an mp3 or wav file you need to set the correct headers.

You can set the headers for an mp3 download using the following code.

```<code>header('Expires: Sat, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate( 'D, d M Y H:i:s' ) . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header("Content-Type: audio/mpeg");
header("Content-Length: " . $len);
</code>```

Note, you will need to know the length of the mp3 data.

See http://php.net/manual/en/function.header.php for more information on setting headers.

Body:
You do not need to 'convert' it, but if you want to allow a user to download an mp3 or wav file you need to set the correct headers.

You can set the headers for an mp3 download using the following code.

header('Expires: Sat, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate( 'D, d M Y H:i:s' ) . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header("Content-Type: audio/mpeg");
header("Content-Length: " . $len);

Note, you will need to know the length of the mp3 data.

See http://php.net/manual/en/function.header.php for more information on setting headers.


问:
Oracle BMCS object store bandwidth cost
If my application that run in oracle bare metal compute nodes access oracle bare metal object storage service using the http apis provided, would it incur bandwidth cost? In other words, is there a way the compute nodes can route the traffic through an internal network rather than going through public IPs of the bare metal object storage service. </p>

答: There is no charge for network traffic between OBMCS compute and the object store.  </p>

Title: Oracle BMCS object store bandwidth cost


问:
Error "expression must have integral or enum type" in thats code:
Error "expression must have integral or enum type" in thats code:

```<code>__global__ void VectorKernel(float *a, float *b, float *c, int n)
{
    int i = threadIdx.x;
    float y = 0, z = 0;

if (i < n)

    y = (b-a) / n;

    for (float j = y; j <= n ; j++) {
        z = (((j+y) - j) / 6) * function(j) + 4 * (function((j + (y+j)) / 2)) + function(y+j);

        c = c + z;
    }
}
</code>```

the error happen in "z", in stretch:

```<code>c = c + z;
</code>```

(i'm beginner in CUDA programming)

答:
c is a pointer. Pointer arithmetic requires a pointer and an integer type expression.

If you want to to add z to the float pointed to by c you should change the expression to:

```<code>*c = *c + z;
</code>```

Body:
Error "expression must have integral or enum type" in thats code:

__global__ void VectorKernel(float *a, float *b, float *c, int n)
{
    int i = threadIdx.x;
    float y = 0, z = 0;

if (i < n)

    y = (b-a) / n;

    for (float j = y; j <= n ; j++) {
        z = (((j+y) - j) / 6) * function(j) + 4 * (function((j + (y+j)) / 2)) + function(y+j);

        c = c + z;
    }
}

the error happen in "z", in stretch:

c = c + z;

(i'm beginner in CUDA programming)

Body:
c is a pointer. Pointer arithmetic requires a pointer and an integer type expression.

If you want to to add z to the float pointed to by c you should change the expression to:

*c = *c + z;


问:
What's the meaning of 'origin' in 'git push origin master'
When I run:

```<code>git push origin master
</code>```

...what is the meaning of origin in this context?

答: "Origin" is the name of the remote repository where you want to publish your commits. By convention, the default remote repository is called "origin," but you can work with several remotes (with different names) at the same time.</p>

Body:
When I run:

git push origin master

...what is the meaning of origin in this context?


问:
Chrome -- CSS -- Extra spacing
Can anyone look at this template and explain why only in Chrome that it adds a whole lot of extra space at the top of the page?

https://html5up.net/uploads/demos/verti

Update:

Actually, I just discovered that when I'm logged into my work Google account (in the browser as a whole), it adds the extra spacing at the top. When I'm just generally using Chrome (guest mode), it does NOT add the extra space at the top. All on the same computer at my house. Different results depending on if I'm logged in or not. Is there an explanation for this?

答:
Padding for the #header-wrapper element, has the following CSS (main.css - line 1839). This equates to a padding-top: 66px in Chrome...

```<code>#header-wrapper {
    padding: 4.5em 0 1em 0;
    padding-top: 4.5em;
    padding-right: 0px;
    padding-bottom: 1em;
    padding-left: 0px;
}
</code>```

This would be simple to remove or override, if you needed to... e.g.

```<code>#header-wrapper {
    padding-top: 10px !important;
}
</code>```

Title: Chrome -- CSS -- Extra spacing

Body:
Padding for the #header-wrapper element, has the following CSS (main.css - line 1839). This equates to a padding-top: 66px in Chrome...

#header-wrapper {
    padding: 4.5em 0 1em 0;
    padding-top: 4.5em;
    padding-right: 0px;
    padding-bottom: 1em;
    padding-left: 0px;
}

This would be simple to remove or override, if you needed to... e.g.

#header-wrapper {
    padding-top: 10px !important;
}


问:
Combine Multiple Predicates
Is there any way in c# .NET 2.0! to combine multiple Predicates?

Let's say I have the following code.

```<code>List<string> names = new List<string>();
names.Add("Jacob");
names.Add("Emma");
names.Add("Michael");
names.Add("Isabella");
names.Add("Ethan");
names.Add("Emily");

List<string> filteredNames = names.FindAll(StartsWithE);

static bool StartsWithE(string s)
{
    if (s.StartsWith("E"))
    {
        return true;
    }
    else
    {
        return false;
    }
}
</code>```

This gives me:

```<code>Emma
Ethan
Emily
</code>```

So this is pretty cool stuff, but I know want to be able to filter using multiple predicates.

So I want to be able to say something like this:

```<code>List<string> filteredNames = names.FindAll(StartsWithE OR StartsWithI);
</code>```

In order to get:

```<code>Emma
Isabella
Ethan
Emily
</code>```

How can I achieve this?
Currently I am just filtering the complete list twice and combining the results afterwards. But unfortunately this is quite inefficent and even more importantly I lose the original sort order, which is not acceptable in my situation.

I also need to be able to iterate over any number of filters/predicates as there can be quite a lot.

Again it needs to be a .NET 2.0 solution unfortunately I can't use a newer version of the framework

Thanks a lot.

答:
I just recently came up with a solution similar to this problem, which could be also helpful. I expanded the FindAll method for lists, allowing me to stack predicates in lists as I needed:

```<code>public static class ExtensionMethods
{
    public static List<T> FindAll<T> (this List<T> list, List<Predicate<T>> predicates)
    {
        List<T> L = new List<T> ();
        foreach (T item in list)
        {
            bool pass = true;
            foreach (Predicate<T> p in predicates)
            {
                if (!(p (item)))
                {
                    pass = false;
                    break;
                }
            }
            if (pass) L.Add (item);
        }
        return L;
    }
}
</code>```

It returns a list with only the items matching all given predicates. Of course it can easily be altered to OR all predicates instead of AND. But with that alone one can assemble quite a good variety of logical combinations.

Usage:

```<code>{
    List<Predicate<int>> P = new List<Predicate<int>> ();
    P.Add (j => j > 100);
    P.Add (j => j % 5 == 0 || j % 7 == 0);
    P.Add (j => j < 1000);

    List<int> L = new List<int> () { 0, 1, 2, ... 999, 1000 }
    List<int> result = L.FindAll (P);

    // result will contain: 105, 110, 112, 115, 119, 120, ... 994, 995
}
</code>```

Title: Combine Multiple Predicates

Body:
Is there any way in c# .NET 2.0! to combine multiple Predicates?

Let's say I have the following code.

List<string> names = new List<string>();
names.Add("Jacob");
names.Add("Emma");
names.Add("Michael");
names.Add("Isabella");
names.Add("Ethan");
names.Add("Emily");

List<string> filteredNames = names.FindAll(StartsWithE);

static bool StartsWithE(string s)
{
    if (s.StartsWith("E"))
    {
        return true;
    }
    else
    {
        return false;
    }
}

This gives me:

Emma
Ethan
Emily

So this is pretty cool stuff, but I know want to be able to filter using multiple predicates.

So I want to be able to say something like this:

List<string> filteredNames = names.FindAll(StartsWithE OR StartsWithI);

In order to get:

Emma
Isabella
Ethan
Emily

How can I achieve this?
Currently I am just filtering the complete list twice and combining the results afterwards. But unfortunately this is quite inefficent and even more importantly I lose the original sort order, which is not acceptable in my situation.

I also need to be able to iterate over any number of filters/predicates as there can be quite a lot.

Again it needs to be a .NET 2.0 solution unfortunately I can't use a newer version of the framework

Thanks a lot.

Body:
I just recently came up with a solution similar to this problem, which could be also helpful. I expanded the FindAll method for lists, allowing me to stack predicates in lists as I needed:

public static class ExtensionMethods
{
    public static List<T> FindAll<T> (this List<T> list, List<Predicate<T>> predicates)
    {
        List<T> L = new List<T> ();
        foreach (T item in list)
        {
            bool pass = true;
            foreach (Predicate<T> p in predicates)
            {
                if (!(p (item)))
                {
                    pass = false;
                    break;
                }
            }
            if (pass) L.Add (item);
        }
        return L;
    }
}

It returns a list with only the items matching all given predicates. Of course it can easily be altered to OR all predicates instead of AND. But with that alone one can assemble quite a good variety of logical combinations.

Usage:

{
    List<Predicate<int>> P = new List<Predicate<int>> ();
    P.Add (j => j > 100);
    P.Add (j => j % 5 == 0 || j % 7 == 0);
    P.Add (j => j < 1000);

    List<int> L = new List<int> () { 0, 1, 2, ... 999, 1000 }
    List<int> result = L.FindAll (P);

    // result will contain: 105, 110, 112, 115, 119, 120, ... 994, 995
}

ContentLicense: CC BY-SA 4.0


问:
Ranking algorithm with multiples factors
So I'd like to rank items depending on multiples factors, however some are more important than others.

Concretely, I've a list of products which all have the following properties:

A price

A weight (in kilogrammes)

A time to build (in minutes)

A size (in centimetres)

Each property has a different scale, and I know the min & max range of them.

For example the price are between 10 and 200, while the weight are between 1.2 and 3.4, etc.

I'd like to apply a priority to the size, then to the time to build, weight and finally the price.

However, I'd like to ensure that no matter the time to build, the weight or the price values are, the size should be the first things that should matters.

For example:

```<code>[{
  price: 320,
  size: 10,
  weight: 0.4
  time: 4
},
{
  price: 230,
  size: 5,
  weight: 1.2
  time: 23
},
{
  price: 230,
  size: 10,
  weight: 1.2
  time: 23
}]
</code>```

should results in:

```<code>[{
  price: 230,
  size: 5,             // the lowest the better
  weight: 1.2
  time: 23
},
{
  price: 320,          // the higher the better
  size: 10,
  weight: 0.4
  time: 4
},
{
  price: 230,
  size: 10,
  weight: 1.2
  time: 23
}]
</code>```

I'm not very good at math and I don't really know where to start.

I'm thinking of something like scale each values on the same range (for example from 0 to 100) and them apply a factor the resulting range value and them add them all before to sort or something like that.

Any ideas.

答: Your sorting function should have the ability to pass a comparison function.  Pass a comparison function that tests each field in order, only moving to the next if everything so far is equal.  In most languages this is not too hard to do.  My guess (based on your posting history) is that you're using PHP so http://www.the-art-of-web.com/php/sortarray/ is likely to be the best guide to how to do that.</p>

Body:
So I'd like to rank items depending on multiples factors, however some are more important than others.

Concretely, I've a list of products which all have the following properties:

A price

A weight (in kilogrammes)

A time to build (in minutes)

A size (in centimetres)

Each property has a different scale, and I know the min & max range of them.

For example the price are between 10 and 200, while the weight are between 1.2 and 3.4, etc.

I'd like to apply a priority to the size, then to the time to build, weight and finally the price.

However, I'd like to ensure that no matter the time to build, the weight or the price values are, the size should be the first things that should matters.

For example:

[{
  price: 320,
  size: 10,
  weight: 0.4
  time: 4
},
{
  price: 230,
  size: 5,
  weight: 1.2
  time: 23
},
{
  price: 230,
  size: 10,
  weight: 1.2
  time: 23
}]

should results in:

[{
  price: 230,
  size: 5,             // the lowest the better
  weight: 1.2
  time: 23
},
{
  price: 320,          // the higher the better
  size: 10,
  weight: 0.4
  time: 4
},
{
  price: 230,
  size: 10,
  weight: 1.2
  time: 23
}]

I'm not very good at math and I don't really know where to start.

I'm thinking of something like scale each values on the same range (for example from 0 to 100) and them apply a factor the resulting range value and them add them all before to sort or something like that.

Any ideas.


问:
silverstripe dynamic backend for flexible frontend
I'm searching for a while, but didn't find a practical answer for the following problem:
An Articlepage in the Frontend can contain different types of sections. For example a block text section and than a text section with left photo an at the end an wallpaper photo.
Now I want to implement this in my backend dynamically, so that I can choose, which type of section and -even more important- how many sections my article should contain.

In my recent project I've solved the problem as an Articlesection with a Dropdown, wich contains the different section styles. And one article hat xy Artilesections as childpages. In the frontend I included all Childpages of the Article - so to speak the Articlesections, where I've checked with if conditions, which sectionsystyle I have in this Section and here I styled the section as I want.
For example Artilce1 has 2 Childpages: Articlesection1 and Artilcesection2.
In AS1 I have choose in the dropdown: right text with left photo and check with if conditions, to style the section. The same with AS2, that is for example a wallpaper photo.

This semiprofessional solution worked, but there are some bugs with displaying the Article correct in the backend, because I have to declare the Articlesections as Includes and not native childpages. And in generell this don't seems like the developers of silverstripe want the users to do it this way..

Are there better ways to implement a dynamically changing backend, so I can decide, which and how much sections I have in the frontend.

答: Take a look at https://github.com/sheadawson/silverstripe-blocks.  There's quite a few addons that offer similar functionality as Blocks such as Elemental.  The following blog post might also be useful too - https://www.silverstripe.org/blog/silverstripe-strips/.</p>


问:
Bug in my for-loop to iterate over data frame
I am working on a data frame and have extracted on the of the columns with hour data from 0 t0 23.  I am adding one more column as type of the day based on hour.  I had executed below for loop but getting error.  Can somebody help me what is wrong with below syntax and how to correct the same.</p>

```<code>for(i in data$Requesthours) {
   if(data$Requesthours>=0 & data$Requesthours<3) {
     data$Partoftheday <- "Midnight"
   } else if(data$Requesthours>=3 & data$Requesthours<6) {
     data$Partoftheday <- "Early Morning"
   } else if(data$Requesthours>=6 & data$Requesthours<12) {
     data$Partoftheday <- "Morning"
   } else if(data$Requesthours>=12 & data$Requesthours<16) {
     data$Partoftheday <- "Afternoon"
   } else if(data$Requesthours>=16 & data$Requesthours<20) {
     data$Partoftheday <- "Evening"
   } else if(data$Requesthours>=20 & data$Requesthours<=23) {
     data$Partoftheday <- "Night"
   }
}
</code>```

答:
Still waiting for you to post your bug, but here's an R coding tip which will reduce this to a one-liner (and bypass your bug). Also it'll be way faster (it's vectorized, unlike your for-loop and if-else-ladder).

```<code>data$Partoftheday <- as.character(
  cut(data$Requesthours,
      breaks=c(-1,3,6,12,16,20,24),
      labels=c('Midnight', 'Early Morning', 'Morning', 'Afternoon', 'Evening', 'Night')
  )
)
# see Notes on cut() at bottom to explain this
</code>```

Now back to your bug: You're confused about how to iterate over a column in R.  for(i in data$Requesthours) is trying to iterate over your df, but you're confusing indices with data values. Also you try to make i an iterator, but then you don't refer to the value i anywhere inside the loop, you refer back to data$Requesthours, which is an entire column not a single value (how do the loop contents known which value you're referring to? They don't. You could use an ugly explicit index-loop like for (i in 1:nrow(data) ... or for (i in seq_along(data) ... then access data[i,]$Requesthours, but please don't. Because...

One of the huge idiomatic things about learning R is generally when you write a for-loop to iterate over a dataframe or a df column, you should stop to think (or research) if there isn't a vectorized function in R that does what you want. cut, if, sum, mean, max, diff, stdev, ... fns are all vectorized, as are all the arithmetic and logical operators. 'vectorized' means you can feed them an entire (column) vector as an input, and they produce an entire (column) vector as output which you can directly assign to your new column. Very simple, very fast, very powerful. Generally beats the pants off for-loops. Please read R-intro.html, esp. Section 2 about vector assignment

And if you can't find or write a vectorized fn, there's also the *apply family of functions apply, sapply, lapply, ... to apply any arbitrary function you want to a list/vector/dataframe/df column.

Notes on cut()

cut(data, breaks, labels, ...) is a function where data is your input vector (e.g. your selected column data$Requesthours), breaks is a vector of integer or numeric, and labels is a vector to name the output. The length of labels is one more than breaks, since 5 breaks divides your data into 6 ranges.

We want the output vector to be string, not categorical, hence we apply as.character() to the output from cut()

Since your first if-else comparison is (hr>=0 & hr<3), we have to fiddle the lowest cutoff_hour 0 to -1, otherwise hr==0 would wrongly give NA. (There is a parameter include.lowest=TRUE/FALSE but it's not what you want, because it would also cause hr==3 to be 'Midnight', hr==6 to be 'Early Morning', etc.)

Body:
I am working on a data frame and have extracted on the of the columns with hour data from 0 t0 23.  I am adding one more column as type of the day based on hour.  I had executed below for loop but getting error.  Can somebody help me what is wrong with below syntax and how to correct the same.

for(i in data$Requesthours) {
   if(data$Requesthours>=0 & data$Requesthours<3) {
     data$Partoftheday <- "Midnight"
   } else if(data$Requesthours>=3 & data$Requesthours<6) {
     data$Partoftheday <- "Early Morning"
   } else if(data$Requesthours>=6 & data$Requesthours<12) {
     data$Partoftheday <- "Morning"
   } else if(data$Requesthours>=12 & data$Requesthours<16) {
     data$Partoftheday <- "Afternoon"
   } else if(data$Requesthours>=16 & data$Requesthours<20) {
     data$Partoftheday <- "Evening"
   } else if(data$Requesthours>=20 & data$Requesthours<=23) {
     data$Partoftheday <- "Night"
   }
}

Body:
Still waiting for you to post your bug, but here's an R coding tip which will reduce this to a one-liner (and bypass your bug). Also it'll be way faster (it's vectorized, unlike your for-loop and if-else-ladder).

data$Partoftheday <- as.character(
  cut(data$Requesthours,
      breaks=c(-1,3,6,12,16,20,24),
      labels=c('Midnight', 'Early Morning', 'Morning', 'Afternoon', 'Evening', 'Night')
  )
)
# see Notes on cut() at bottom to explain this

Now back to your bug: You're confused about how to iterate over a column in R.  for(i in data$Requesthours) is trying to iterate over your df, but you're confusing indices with data values. Also you try to make i an iterator, but then you don't refer to the value i anywhere inside the loop, you refer back to data$Requesthours, which is an entire column not a single value (how do the loop contents known which value you're referring to? They don't. You could use an ugly explicit index-loop like for (i in 1:nrow(data) ... or for (i in seq_along(data) ... then access data[i,]$Requesthours, but please don't. Because...

One of the huge idiomatic things about learning R is generally when you write a for-loop to iterate over a dataframe or a df column, you should stop to think (or research) if there isn't a vectorized function in R that does what you want. cut, if, sum, mean, max, diff, stdev, ... fns are all vectorized, as are all the arithmetic and logical operators. 'vectorized' means you can feed them an entire (column) vector as an input, and they produce an entire (column) vector as output which you can directly assign to your new column. Very simple, very fast, very powerful. Generally beats the pants off for-loops. Please read R-intro.html, esp. Section 2 about vector assignment

And if you can't find or write a vectorized fn, there's also the *apply family of functions apply, sapply, lapply, ... to apply any arbitrary function you want to a list/vector/dataframe/df column.

Notes on cut()

cut(data, breaks, labels, ...) is a function where data is your input vector (e.g. your selected column data$Requesthours), breaks is a vector of integer or numeric, and labels is a vector to name the output. The length of labels is one more than breaks, since 5 breaks divides your data into 6 ranges.

We want the output vector to be string, not categorical, hence we apply as.character() to the output from cut()

Since your first if-else comparison is (hr>=0 & hr<3), we have to fiddle the lowest cutoff_hour 0 to -1, otherwise hr==0 would wrongly give NA. (There is a parameter include.lowest=TRUE/FALSE but it's not what you want, because it would also cause hr==3 to be 'Midnight', hr==6 to be 'Early Morning', etc.)


问:
Merge strings in javascript
I want to merge two variable with stings alternately using javascript. What would be an algorithm to accomplish this task?

For example:

```<code>var a = "abc"
var b = "def"

result = "adbecf"
</code>```

答:
Regex or array processing and joining do the job:

let a = 'abc';
let b = 'def';
console.log(a.replace(/./g, (c, i) => c + b[i]));        // 'adbecf'
console.log(Array.from(a, (c, i) => c + b[i]).join('')); // 'adbecf'```

Title: Merge strings in javascript

Body:
I want to merge two variable with stings alternately using javascript. What would be an algorithm to accomplish this task?

For example:

var a = "abc"
var b = "def"

result = "adbecf"


问:
GridBagLayout in Java wont work
Ive been trying to make adjust my display the way i want it, but it doesnt seem to work. I want to use GridBagLayout to make something like this:

I want to sort panels like this

Ive found a piece of code, and edited it:

```<code>public class GBLPanel extends JPanel
{
    private static final long serialVersionUID = 1L;

    GridBagConstraints gbc = new GridBagConstraints();

    public GBLPanel(Dimension appdim)
    {
        GridBagConstraints c = new GridBagConstraints();

        setLayout(new GridBagLayout());
        add(gbcComponent(0,0,2,1,0,0), gbc);
        add(gbcComponent(0,1,1,1,0,50), gbc);
        add(gbcComponent(1,1,1,1,0,50), gbc);

    }

     private JPanel gbcComponent(int x, int y, int w, int h, int ipadyx, int ipadyy){

        gbc.gridx = x;
        gbc.gridy = y;
        gbc.gridwidth = w;
        gbc.gridheight = h;

        gbc.weightx = 1.0;
        gbc.weighty = 1.0;

        gbc.ipadx=ipadyx;
        gbc.ipady=ipadyy;

        gbc.fill = GridBagConstraints.BOTH;
        JPanel panel = new JPanel();
        JTextField text = new JTextField("(" + w + ", " + h + ")");
        panel.setBorder(new TitledBorder("(" + x + ", " + y + ")"));
        panel.add(text);
        return panel;

    }

}
</code>```

but it looks like this

and i cant figure out how to shape it as i want, anyone can help ? Thanks very much !

答:
A BorderLayout would probably be easier to do this for you.

But if you want/need to use a GridBagLayout, the current problem you are having is that you are setting the weight for both x and y for each panel to 1. Meaning they will all be distributed evenly.

Try changing them to reflect the values you want by doing something like this

```<code>public GBLPanel(Dimension appdim)
{
    GridBagConstraints c = new GridBagConstraints();

    setLayout(new GridBagLayout());
    // Pass in weights also
    add(gbcComponent(0,0,2,1,0,0, 1, 0.25), gbc);  // 100% x and 25% y
    add(gbcComponent(0,1,1,1,0,50, 0.25, 0.75), gbc); // 25% x and 75% y
    add(gbcComponent(1,1,1,1,0,50, 0.75, 0.75), gbc); // 75% x and 75% y

}

private JPanel gbcComponent(int x, int y, int w, int h, int ipadyx, int ipadyy, double wx, double wy)
{
    gbc.gridx = x;
    gbc.gridy = y;
    gbc.gridwidth = w;
    gbc.gridheight = h;

    gbc.weightx = wx;  // Set to passed in values here
    gbc.weighty = wy;

    gbc.ipadx=ipadyx;
    gbc.ipady=ipadyy;

    gbc.fill = GridBagConstraints.BOTH;
    JPanel panel = new JPanel();
    JTextField text = new JTextField("(" + w + ", " + h + ")");
    panel.setBorder(new TitledBorder("(" + x + ", " + y + ")"));
    panel.add(text);
    return panel;

}
</code>```

Title: GridBagLayout in Java wont work

Body:
Ive been trying to make adjust my display the way i want it, but it doesnt seem to work. I want to use GridBagLayout to make something like this:

I want to sort panels like this

Ive found a piece of code, and edited it:

public class GBLPanel extends JPanel
{
    private static final long serialVersionUID = 1L;

    GridBagConstraints gbc = new GridBagConstraints();

    public GBLPanel(Dimension appdim)
    {
        GridBagConstraints c = new GridBagConstraints();

        setLayout(new GridBagLayout());
        add(gbcComponent(0,0,2,1,0,0), gbc);
        add(gbcComponent(0,1,1,1,0,50), gbc);
        add(gbcComponent(1,1,1,1,0,50), gbc);

    }

     private JPanel gbcComponent(int x, int y, int w, int h, int ipadyx, int ipadyy){

        gbc.gridx = x;
        gbc.gridy = y;
        gbc.gridwidth = w;
        gbc.gridheight = h;

        gbc.weightx = 1.0;
        gbc.weighty = 1.0;

        gbc.ipadx=ipadyx;
        gbc.ipady=ipadyy;

        gbc.fill = GridBagConstraints.BOTH;
        JPanel panel = new JPanel();
        JTextField text = new JTextField("(" + w + ", " + h + ")");
        panel.setBorder(new TitledBorder("(" + x + ", " + y + ")"));
        panel.add(text);
        return panel;

    }

}

but it looks like this

and i cant figure out how to shape it as i want, anyone can help ? Thanks very much !

Body:
A BorderLayout would probably be easier to do this for you.

But if you want/need to use a GridBagLayout, the current problem you are having is that you are setting the weight for both x and y for each panel to 1. Meaning they will all be distributed evenly.

Try changing them to reflect the values you want by doing something like this

public GBLPanel(Dimension appdim)
{
    GridBagConstraints c = new GridBagConstraints();

    setLayout(new GridBagLayout());
    // Pass in weights also
    add(gbcComponent(0,0,2,1,0,0, 1, 0.25), gbc);  // 100% x and 25% y
    add(gbcComponent(0,1,1,1,0,50, 0.25, 0.75), gbc); // 25% x and 75% y
    add(gbcComponent(1,1,1,1,0,50, 0.75, 0.75), gbc); // 75% x and 75% y

}

private JPanel gbcComponent(int x, int y, int w, int h, int ipadyx, int ipadyy, double wx, double wy)
{
    gbc.gridx = x;
    gbc.gridy = y;
    gbc.gridwidth = w;
    gbc.gridheight = h;

    gbc.weightx = wx;  // Set to passed in values here
    gbc.weighty = wy;

    gbc.ipadx=ipadyx;
    gbc.ipady=ipadyy;

    gbc.fill = GridBagConstraints.BOTH;
    JPanel panel = new JPanel();
    JTextField text = new JTextField("(" + w + ", " + h + ")");
    panel.setBorder(new TitledBorder("(" + x + ", " + y + ")"));
    panel.add(text);
    return panel;

}


答:
When you write c = c + z and get an error like this, you should suspect your types are mismatched.
c is a float * and z is a float which are not assignable.

What you probably want to do is store the result of *c + z in the memory location pointed at by c, in which case you'd write:
*c = *c + z.

Title: Error "expression must have integral or enum type" in thats code:


问:
On typing a query, each alphabet is producing new single page. How it should be prevented?
I'm working, a project in which I have to create a search engine. I'm facing problem, whenever a user types a query for each and every alphabet typed a new page is being reproduced. For example if I type - 'fos' , 3 pages are being produced. If I type 'fossa' 5 pages are being produced.

I have used redux architecture and angular 2 in my project. How should I solve this problem ? Thanks in advance :)

```<code>onquery(event: any) {
   if (event.target.value.length > 2) {
     this.store.dispatch(new query.QueryAction(event.target.value));
     this.displayStatus = 'showbox';
     this.submit();
     this.hidebox(event);
    }
  }
submit() {
  this.router.navigate(['/search'], {queryParams: this.searchdata});
}
</code>```

HTML

```<code><input #input type="text" name="query" class="form-control" id="nav-input" (keyup)="onquery($event)"
           [(ngModel)]="searchdata.query" autocomplete="off">
</code>```

Reducer code -

```<code>export const CHANGE = 'CHANGE';

export interface State {
  searchresults: any;
  items: any;
}

const initialState: State = {
  searchresults: {},
  items: []
};

export function reducer(state: State = initialState, action: search.Actions): State {
  switch (action.type) {
    case search.ActionTypes.CHANGE: {
      const search = action.payload;
      return Object.assign({}, state, {
        searchresults: search,
        items: search.channels[0].items
      });
    }
    default: {
      return state;
    }
</code>```

答:
You are calling onquery on every keyup

onquery is calling submit

submit is calling router.navigate which is indeed navigating! (thus pushing to browser history as you show in your screenshot)

why do you want to navigate to search page while user is still typing?

you should call the submit function on ngSubmit placed on your form element like so

```<code><form (ngSubmit)="submit()">
    <input #input type="text" name="query" class="form-control" id="nav-input" (keyup)="onquery($event)"
           [(ngModel)]="searchdata.query" autocomplete="off">
</form>
</code>```

Body:
I'm working, a project in which I have to create a search engine. I'm facing problem, whenever a user types a query for each and every alphabet typed a new page is being reproduced. For example if I type - 'fos' , 3 pages are being produced. If I type 'fossa' 5 pages are being produced.

I have used redux architecture and angular 2 in my project. How should I solve this problem ? Thanks in advance :)

onquery(event: any) {
   if (event.target.value.length > 2) {
     this.store.dispatch(new query.QueryAction(event.target.value));
     this.displayStatus = 'showbox';
     this.submit();
     this.hidebox(event);
    }
  }
submit() {
  this.router.navigate(['/search'], {queryParams: this.searchdata});
}

HTML

<input #input type="text" name="query" class="form-control" id="nav-input" (keyup)="onquery($event)"
           [(ngModel)]="searchdata.query" autocomplete="off">

Reducer code -

export const CHANGE = 'CHANGE';

export interface State {
  searchresults: any;
  items: any;
}

const initialState: State = {
  searchresults: {},
  items: []
};

export function reducer(state: State = initialState, action: search.Actions): State {
  switch (action.type) {
    case search.ActionTypes.CHANGE: {
      const search = action.payload;
      return Object.assign({}, state, {
        searchresults: search,
        items: search.channels[0].items
      });
    }
    default: {
      return state;
    }

Body:
You are calling onquery on every keyup

onquery is calling submit

submit is calling router.navigate which is indeed navigating! (thus pushing to browser history as you show in your screenshot)

why do you want to navigate to search page while user is still typing?

you should call the submit function on ngSubmit placed on your form element like so

<form (ngSubmit)="submit()">
    <input #input type="text" name="query" class="form-control" id="nav-input" (keyup)="onquery($event)"
           [(ngModel)]="searchdata.query" autocomplete="off">
</form>


问:
How do I get the current MediaWiki version using the API?
Using the MediaWiki API how do I get the version number?</p>

答:
You need /w/api.php?action=query&format=json&prop=&meta=siteinfo. That will give you all you need (and a lot more). Here's what it returns from en.wikipedia.org:

```<code>{
    "batchcomplete": "",
    "query": {
        "general": {
            "mainpage": "Main Page",
            "base": "https://en.wikipedia.org/wiki/Main_Page",
            "sitename": "Wikipedia",
            "logo": "//en.wikipedia.org/static/images/project-logos/enwiki.png",
            "generator": "MediaWiki 1.30.0-wmf.2",
            "phpversion": "5.6.99-hhvm",
            "phpsapi": "srv",
            "hhvmversion": "3.18.2",
            "dbtype": "mysql",
            "dbversion": "10.0.29-MariaDB",
            "imagewhitelistenabled": "",
            "langconversion": "",
            "titleconversion": "",
            "linkprefixcharset": "",
            "linkprefix": "",
            "linktrail": "/^([a-z]+)(.*)$/sD",
            "legaltitlechars": " %!\"$&'()*,\\-.\\/0-9:;=?@A-Z\\\\^_`a-z~\\x80-\\xFF+",
            "invalidusernamechars": "@:",
            "fixarabicunicode": "",
            "fixmalayalamunicode": "",
            "git-hash": "b40805ff461884e48400adb3000fa06f9b6ff4c9",
            "git-branch": "wmf/1.30.0-wmf.2",
            "case": "first-letter",
            "lang": "en",
            "fallback": [],
            "fallback8bitEncoding": "windows-1252",
            "writeapi": "",
            "maxarticlesize": 2097152,
            "timezone": "UTC",
            "timeoffset": 0,
            "articlepath": "/wiki/$1",
            "scriptpath": "/w",
            "script": "/w/index.php",
            "variantarticlepath": false,
            "server": "//en.wikipedia.org",
            "servername": "en.wikipedia.org",
            "wikiid": "enwiki",
            "time": "2017-06-05T23:28:54Z",
            "misermode": "",
            "uploadsenabled": "",
            "maxuploadsize": 4294967296,
            "minuploadchunksize": 1024,
            "galleryoptions": {
                "imagesPerRow": 0,
                "imageWidth": 120,
                "imageHeight": 120,
                "captionLength": "",
                "showBytes": "",
                "mode": "traditional"
            },
            "thumblimits": [
                120,
                150,
                180,
                200,
                220,
                250,
                300,
                400
            ],
            "imagelimits": [
                {
                    "width": 320,
                    "height": 240
                },
                {
                    "width": 640,
                    "height": 480
                },
                {
                    "width": 800,
                    "height": 600
                },
                {
                    "width": 1024,
                    "height": 768
                },
                {
                    "width": 1280,
                    "height": 1024
                }
            ],
            "favicon": "//en.wikipedia.org/static/favicon/wikipedia.ico",
            "centralidlookupprovider": "CentralAuth",
            "allcentralidlookupproviders": [
                "CentralAuth",
                "local"
            ],
            "interwikimagic": "",
            "magiclinks": {
                "ISBN": "",
                "PMID": "",
                "RFC": ""
            },
            "wmf-config": {
                "wmfMasterDatacenter": "eqiad"
            },
            "pageviewservice-supported-metrics": {
                "pageviews": {
                    "pageviews": ""
                },
                "siteviews": {
                    "pageviews": "",
                    "uniques": ""
                },
                "mostviewed": {
                    "pageviews": ""
                }
            }
        }
    }
}
</code>```

I'm guessing you need the "generator" property there. If you like you can test it out in Wikipedia's API sandbox.

Body:
You need /w/api.php?action=query&format=json&prop=&meta=siteinfo. That will give you all you need (and a lot more). Here's what it returns from en.wikipedia.org:

{
    "batchcomplete": "",
    "query": {
        "general": {
            "mainpage": "Main Page",
            "base": "https://en.wikipedia.org/wiki/Main_Page",
            "sitename": "Wikipedia",
            "logo": "//en.wikipedia.org/static/images/project-logos/enwiki.png",
            "generator": "MediaWiki 1.30.0-wmf.2",
            "phpversion": "5.6.99-hhvm",
            "phpsapi": "srv",
            "hhvmversion": "3.18.2",
            "dbtype": "mysql",
            "dbversion": "10.0.29-MariaDB",
            "imagewhitelistenabled": "",
            "langconversion": "",
            "titleconversion": "",
            "linkprefixcharset": "",
            "linkprefix": "",
            "linktrail": "/^([a-z]+)(.*)$/sD",
            "legaltitlechars": " %!\"$&'()*,\\-.\\/0-9:;=?@A-Z\\\\^_`a-z~\\x80-\\xFF+",
            "invalidusernamechars": "@:",
            "fixarabicunicode": "",
            "fixmalayalamunicode": "",
            "git-hash": "b40805ff461884e48400adb3000fa06f9b6ff4c9",
            "git-branch": "wmf/1.30.0-wmf.2",
            "case": "first-letter",
            "lang": "en",
            "fallback": [],
            "fallback8bitEncoding": "windows-1252",
            "writeapi": "",
            "maxarticlesize": 2097152,
            "timezone": "UTC",
            "timeoffset": 0,
            "articlepath": "/wiki/$1",
            "scriptpath": "/w",
            "script": "/w/index.php",
            "variantarticlepath": false,
            "server": "//en.wikipedia.org",
            "servername": "en.wikipedia.org",
            "wikiid": "enwiki",
            "time": "2017-06-05T23:28:54Z",
            "misermode": "",
            "uploadsenabled": "",
            "maxuploadsize": 4294967296,
            "minuploadchunksize": 1024,
            "galleryoptions": {
                "imagesPerRow": 0,
                "imageWidth": 120,
                "imageHeight": 120,
                "captionLength": "",
                "showBytes": "",
                "mode": "traditional"
            },
            "thumblimits": [
                120,
                150,
                180,
                200,
                220,
                250,
                300,
                400
            ],
            "imagelimits": [
                {
                    "width": 320,
                    "height": 240
                },
                {
                    "width": 640,
                    "height": 480
                },
                {
                    "width": 800,
                    "height": 600
                },
                {
                    "width": 1024,
                    "height": 768
                },
                {
                    "width": 1280,
                    "height": 1024
                }
            ],
            "favicon": "//en.wikipedia.org/static/favicon/wikipedia.ico",
            "centralidlookupprovider": "CentralAuth",
            "allcentralidlookupproviders": [
                "CentralAuth",
                "local"
            ],
            "interwikimagic": "",
            "magiclinks": {
                "ISBN": "",
                "PMID": "",
                "RFC": ""
            },
            "wmf-config": {
                "wmfMasterDatacenter": "eqiad"
            },
            "pageviewservice-supported-metrics": {
                "pageviews": {
                    "pageviews": ""
                },
                "siteviews": {
                    "pageviews": "",
                    "uniques": ""
                },
                "mostviewed": {
                    "pageviews": ""
                }
            }
        }
    }
}

I'm guessing you need the "generator" property there. If you like you can test it out in Wikipedia's API sandbox.


问:
What "private property" means on ES6 classes?
I am a bit lost with ES6 privacy on Classes. I have this Class:

```<code>class Whatever {

        constructor(value) {
            this._value = Number(value);
        }

        total() {
            return this._value * 2;
        }
    }

    let instance = new Whatever('1000');
    console.log(instance.total() );     // 2000
    console.log(instance._value  );     // 1000
</code>```

I am trying to learn how Symbol() works to keep data private (see link), and after reading the documentation I am trying to make a simple example about it, but does not seem to have any difference:

```<code>const _value = Symbol('value');

    class Whatever {

        constructor(value) {
            this[_value] = Number(value);
        }

        total() {
            return this[_value] * 2;
        }
    }

    let instance = new Whatever('1000');
    console.log(instance.total() );     // 2000
    console.log(instance[_value]  );    // 1000
</code>```

Could someone explain me on a comprehensive way, what does privacy mean on this case, and why my idea of privatizing data (making data unaccesible from outside the Class) is wrong? I have not much experience on OOP.

Thank you.

答:
There are a few subtle concepts at play here.

Symbols are globally unique; that is, if you call Symbol.create('somestring'); twice, it will produce two completely different symbols.

There is no way for "someone else" to access an object property whose key is a symbol** without access to that symbol in some other way. In your second example, code underneath the class still has lexical access to the symbol. However, this would not be the case were your class to be exported, whether through a module system or just returned to some other calling function without lexical access, even if they knew what string you used to label the symbol, because they can't re-create it (as mentioned above).

** edit 2: As others stated, including Dr. Rauschmayer, "others" can access the keys, including symbols, via Reflect.ownKeys(object). In this very deliberate case, one would hope that the other party knows what they're doing... so this whole paradigm of using symbols as keys is still good for ensuring non-clashing namespaces for keys (e.g., if someone else wanted to augment your object without accidentally overriding any of its important "internal" properties). However, it is not sufficient for 100% protection against deliberate access or modification. (There's a related ECMAScript proposal in the works, interesting read.)

Edit: here's an example

let Whatever = (function() {
      const _value = Symbol('value');

      class Whatever {

        constructor(value) {
          this[_value] = Number(value);
        }

        total() {
          return this[_value] * 2;
        }
      }

      return Whatever;
    })(); // IIFE

    let instance = new Whatever('1000');
    console.log(instance.total()); // 2000
    console.log(instance._value); // undefined
    console.log(instance[_value]); // ReferenceError: _value is not defined```

Body:
I am a bit lost with ES6 privacy on Classes. I have this Class:

class Whatever {

        constructor(value) {
            this._value = Number(value);
        }

        total() {
            return this._value * 2;
        }
    }

    let instance = new Whatever('1000');
    console.log(instance.total() );     // 2000
    console.log(instance._value  );     // 1000

I am trying to learn how Symbol() works to keep data private (see link), and after reading the documentation I am trying to make a simple example about it, but does not seem to have any difference:

const _value = Symbol('value');

    class Whatever {

        constructor(value) {
            this[_value] = Number(value);
        }

        total() {
            return this[_value] * 2;
        }
    }

    let instance = new Whatever('1000');
    console.log(instance.total() );     // 2000
    console.log(instance[_value]  );    // 1000

Could someone explain me on a comprehensive way, what does privacy mean on this case, and why my idea of privatizing data (making data unaccesible from outside the Class) is wrong? I have not much experience on OOP.

Thank you.


问:
HTML code indentation issues
i been doing a codecadmey course on html one of the task were to make the code so it follows the rules of the The World Wide Web Consortium by 2 space indents.I asked a few people where to put the indentations but every time i try i still cant proceed to the next task. here my code below can anyone help me to put the indentations.!!!

<!DOCTYPE html>

  <title>Animals Around the World</title>

 The Brown Bear

 The brown bear (Ursus arctos) is native to parts of northern Eurasia and North America. Its conservation status is currently "Least Concern." There are many subspecies within the brown bear species, including the Atlas bear and the Himalayan brown bear.

   Learn more

 The following are subspecies of bears:

 Arctos

 Collarus

 Horribilis

 Nelsoni (extinct)

 The following countries have the largest populations of brown bears:

 Russia

 United States

 Canada

```

答:
<!DOCTYPE html>

  <title>Animals Around the World</title>

 The Brown Bear

 The brown bear (Ursus arctos) is native to parts of northern Eurasia and North America. Its conservation status is currently "Least Concern." There are many subspecies within the brown bear species, including the Atlas bear and the Himalayan brown bear.

   Learn more

 The following are subspecies of bears:

 Arctos

 Collarus

 Horribilis

 Nelsoni (extinct)

 The following countries have the largest populations of brown bears:

 Russia

 United States

 Canada

```

The speediest solution is to use the HTML Tidy tool which you may find available online so that you may download and install it.  But, there are also websites that make that tool freely available for immediate use, such as codepen.io.  But, that is actually more effort than you need to expend, given that a tidy tool exists at StackOverflow as part of the functionality that the OP uses to display the HTML code in question.  If the OP were to click the option to edit the posed question, a link is provided ("edit the above snippet") that allows one to edit the code.  If you click that link, you will note on the left side a tidy tool that works on HTML, CSS or JavaScript.  So, you may choose to spend your time efficiently by utilizing this tool to have the desired indented code or else visually scan each line and character of the code to figure out for yourself where the spacing needs adjustment.

Title: HTML code indentation issues

Body:
<!DOCTYPE html>
<html>

<head>
  <title>Animals Around the World</title>
</head>

<body>
  <h1> The Brown Bear </h1>
  <p> The brown bear (Ursus arctos) is native to parts of northern Eurasia and North America. Its conservation status is currently "Least Concern." There are many subspecies within the brown bear species, including the Atlas bear and the Himalayan brown bear.
  </p>
  <a href="https://en.wikipedia.org/wiki/Brown_bear" target="_blank"> Learn more </a>
  <p> The following are subspecies of bears: </p>

  <ul>
    <li> Arctos </li>
    <li> Collarus </li>
    <li> Horribilis </li>
    <li> Nelsoni (extinct) </li>
  </ul>
  <p> The following countries have the largest populations of brown bears: </p>
  <ol>
    <li> Russia </li>
    <li> United States </li>
    <li> Canada </li>
  </ol>
  <a href="https://en.wikipedia.org/wiki/Brown_bear" target="_blank">
    <img src="https://s3.amazonaws.com/codecademy-content/courses/web-101/web101-image_brownbear.jpg" alt="bear photo" /></a>
</body>

</html>

The speediest solution is to use the HTML Tidy tool which you may find available online so that you may download and install it.  But, there are also websites that make that tool freely available for immediate use, such as codepen.io.  But, that is actually more effort than you need to expend, given that a tidy tool exists at StackOverflow as part of the functionality that the OP uses to display the HTML code in question.  If the OP were to click the option to edit the posed question, a link is provided ("edit the above snippet") that allows one to edit the code.  If you click that link, you will note on the left side a tidy tool that works on HTML, CSS or JavaScript.  So, you may choose to spend your time efficiently by utilizing this tool to have the desired indented code or else visually scan each line and character of the code to figure out for yourself where the spacing needs adjustment.


问:
ASP.Net: How to control div-style in backend?
I will control the style from a div-container from the backend (c#, code behind).

I will not use the runat="server"-tag, because the div-id is much used in javaScript.

How to do?

答:
You have to make it runat=server if you want to access it from the code behind - simple as that.

If it's "much used" in JavaScript - set the ClientId in a literal control, and access it that way from JavaScript.

Or if your on .NET 4, set the ClientIdMode="Static".

EDIT

Here's how you can use a literal control to hold onto the client id (so you can use it in JavaScript):

ASPX:

```<code><asp:Literal id="DivClientId" runat="server"/>
</code>```

ASPX.CS:

```<code>DivClentId.Text = string.Format("<script type=\"text/javascript\">var divId = {0};</script>", ServerSideDiv.ClientId);
</code>```

JavaScript:

```<code>var div = document.getElementById(divId);
</code>```

Body:
You have to make it runat=server if you want to access it from the code behind - simple as that.

If it's "much used" in JavaScript - set the ClientId in a literal control, and access it that way from JavaScript.

Or if your on .NET 4, set the ClientIdMode="Static".

EDIT

Here's how you can use a literal control to hold onto the client id (so you can use it in JavaScript):

ASPX:

<asp:Literal id="DivClientId" runat="server"/>

ASPX.CS:

DivClentId.Text = string.Format("<script type=\"text/javascript\">var divId = {0};</script>", ServerSideDiv.ClientId);

JavaScript:

var div = document.getElementById(divId);


答:
It looks like you want to sort by size in increasing order, then if two objects have the same size then by time in increasing order, then by weight in increasing order, then by price in decreasing order (according to the comment in your example).

If you are using a language like Python, just put the four values into a tuple, with the items to be in decreasing order with their values replaced with their negatives. For each item your key is

```<code>(size, time, weight, -price)
</code>```

Then Python itself will sort those tuples appropriately--it is built into the language.  This is the easiest thing to do.

If you are using a language without sorted tuples, or for some reason you really want the key to be a floating point value, you can do this. For each factor, look at the known minimum and maximum. Use those to scale that factor to a number between 1 and 10, perhaps including 1 but not including 10. Make sure 1 goes with the value to be sorted first. This can be done with

```<code>scale1to10 = (value - min) / (max + 1 - min) * 9 + 1
</code>```

for increasing factors, and with

```<code>scale1to10 = (max - value) / (max + 1 - min) * 9 + 1
</code>```

for decreasing factors. Then combine all the factors into one "4-digit" number, as in

```<code>scale = scalesize * 1000 + scaletime * 100 + scaleweight * 10 + scaleprice
</code>```

Note that the most important factor is multiplied by the highest power of 10, while the lowest has no multiplier.

Title: Ranking algorithm with multiples factors

Body:
It looks like you want to sort by size in increasing order, then if two objects have the same size then by time in increasing order, then by weight in increasing order, then by price in decreasing order (according to the comment in your example).

If you are using a language like Python, just put the four values into a tuple, with the items to be in decreasing order with their values replaced with their negatives. For each item your key is

(size, time, weight, -price)

Then Python itself will sort those tuples appropriately--it is built into the language.  This is the easiest thing to do.

If you are using a language without sorted tuples, or for some reason you really want the key to be a floating point value, you can do this. For each factor, look at the known minimum and maximum. Use those to scale that factor to a number between 1 and 10, perhaps including 1 but not including 10. Make sure 1 goes with the value to be sorted first. This can be done with

scale1to10 = (value - min) / (max + 1 - min) * 9 + 1

for increasing factors, and with

scale1to10 = (max - value) / (max + 1 - min) * 9 + 1

for decreasing factors. Then combine all the factors into one "4-digit" number, as in

scale = scalesize * 1000 + scaletime * 100 + scaleweight * 10 + scaleprice

Note that the most important factor is multiplied by the highest power of 10, while the lowest has no multiplier.


问:
Modify Stored Procedure Without Executing
We have a stored procedure that fires off a thousand emails. It's auto-run at 1 AM every night. I have to edit the stored procedure in Management Studio: I know I have to choose "Modify" and then make the edits, but I don't want to click "Execute" to save it, or the emailing sequence will start. How can I save the new code without executing the stored procedure? Thank you</p>

答:
Clicking Execute won't actually run the procedure, it just applies your modifications.

Comment out the part that triggers the emails to be sent then execute, if you would prefer to see what it does first. Then when you are comfortable, uncomment and make your changes.


问:
Bash unexpected token near <<< here document
My terminal's character encoding is set to UTF-8. I went into the terminal program's Profile Preferences / Compatibility and clicked Reset Compatibility Options to Defaults.

I ssh'd to another machine using this terminal window.

I ran vi and typed in the following script in by hand (to avoid any unexpected hidden special characters) on that machine. Then I ran it and got syntax error near unexpected token <<<

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

cd "$1"

if [ $? -ne 0 ]; then
  printf 'cd fail'
  exit 1
fi

while read name
do
  printf 'item: [%s]\n' "$name"
done <<< "$(stat -t ./* | awk -F' ' '{print $13 " " $1}' | sort -r | awk -F' ' '{print $2}')"
</code>```

This  test machine has /bin/bash ... also /bin/sh is a link to /bin/bash. /bin/bash --version says GNU bash, version 2.05a.0(3)-release (i686-pc-linux-gnu)

I can disconnect from that test machine and in the same terminal window type the same script by hand on my machine and it runs fine. On my machine, /bin/bash --version says GNU bash, version 4.3.42(1)-release (x86_64-redhat-linux-gnu)

What's causing the syntax error on the test machine? Is <<< not supported in that earlier version of Bash?

答:
sure - that feature came in with 2.05b which git shows as July 2002, while 2.05a was November 2001.

bash's developer doesn't put dates in the changelog, but with some patience you can see the changes in git CHANGES

Body:
My terminal's character encoding is set to UTF-8. I went into the terminal program's Profile Preferences / Compatibility and clicked Reset Compatibility Options to Defaults.

I ssh'd to another machine using this terminal window.

I ran vi and typed in the following script in by hand (to avoid any unexpected hidden special characters) on that machine. Then I ran it and got syntax error near unexpected token <<<

#!/bin/bash

cd "$1"

if [ $? -ne 0 ]; then
  printf 'cd fail'
  exit 1
fi

while read name
do
  printf 'item: [%s]\n' "$name"
done <<< "$(stat -t ./* | awk -F' ' '{print $13 " " $1}' | sort -r | awk -F' ' '{print $2}')"

This  test machine has /bin/bash ... also /bin/sh is a link to /bin/bash. /bin/bash --version says GNU bash, version 2.05a.0(3)-release (i686-pc-linux-gnu)

I can disconnect from that test machine and in the same terminal window type the same script by hand on my machine and it runs fine. On my machine, /bin/bash --version says GNU bash, version 4.3.42(1)-release (x86_64-redhat-linux-gnu)

What's causing the syntax error on the test machine? Is <<< not supported in that earlier version of Bash?


问:
How to write an output of a grep from an openssl command?
Consider you have list of thousand IP addresses in a text file - one per line. I want to be able to grab all possible anomalies from each IP address using openssl s_client command. So far, anomalies are certificate expired, self signed certificate, and issuer CN to include emailAddress=root@localhost.localdomain.

Overall, I want to be able to obtain concise error message per IP address if there is any. My current bash script looks like:

```<code>for ip in `awk '{print $1}' < general_certs.txt`; do
# Print IP address currently checking
echo -e $ip;
    if timeout 30 openssl s_client -connect $ip:443| grep -i 'error' ; then
# Write error information and IP address to a file
        echo `openssl s_client -connect $ip:443| grep -i 'error'` $ip >> general_errors;
    else
# Write noerror information and IP address to another file
        echo "noerror" $ip >> general_noerror;
    fi;
done
</code>```

First issue I have with the code is that it is not optimized and that I am  skeptical if it returns accurate results. The end goal with the above script is to identify all untrusted certificate containing IPs.

Second issue I had with the above code that I could not echo $ip first because it would get truncated by the message itself. So, I ended up writing out $ip after the error message.

It is not necessary to use openssl if there is a more genuine solution to my question.

答:
If you're trying to get which ip's have a untrusted certificate, you could try, even if it's not the best option, with curl.

Something like:

```<code>for ip in `awk '{print $1}' < general_certs.txt`; do
  echo -e $ip

  curl https://${ip}:443 &> /dev/null

  if [ $? == 51 ]; then
    echo "upsis, https://${ip}:443 has a untrusted certificate" >> general_err
  else
    echo "yai, https://${ip}:443 doesn't have a untrusted certificate" >> general_noerr
  fi
done
</code>```

Notice that here you're only checking for unstrusted certificates ( error 51 in curl ), but the command could send any other error and it would go to general_noerror.

Body:
Consider you have list of thousand IP addresses in a text file - one per line. I want to be able to grab all possible anomalies from each IP address using openssl s_client command. So far, anomalies are certificate expired, self signed certificate, and issuer CN to include emailAddress=root@localhost.localdomain.

Overall, I want to be able to obtain concise error message per IP address if there is any. My current bash script looks like:

for ip in `awk '{print $1}' < general_certs.txt`; do
# Print IP address currently checking
echo -e $ip;
    if timeout 30 openssl s_client -connect $ip:443| grep -i 'error' ; then
# Write error information and IP address to a file
        echo `openssl s_client -connect $ip:443| grep -i 'error'` $ip >> general_errors;
    else
# Write noerror information and IP address to another file
        echo "noerror" $ip >> general_noerror;
    fi;
done

First issue I have with the code is that it is not optimized and that I am  skeptical if it returns accurate results. The end goal with the above script is to identify all untrusted certificate containing IPs.

Second issue I had with the above code that I could not echo $ip first because it would get truncated by the message itself. So, I ended up writing out $ip after the error message.

It is not necessary to use openssl if there is a more genuine solution to my question.

Body:
If you're trying to get which ip's have a untrusted certificate, you could try, even if it's not the best option, with curl.

Something like:

for ip in `awk '{print $1}' < general_certs.txt`; do
  echo -e $ip

  curl https://${ip}:443 &> /dev/null

  if [ $? == 51 ]; then
    echo "upsis, https://${ip}:443 has a untrusted certificate" >> general_err
  else
    echo "yai, https://${ip}:443 doesn't have a untrusted certificate" >> general_noerr
  fi
done

Notice that here you're only checking for unstrusted certificates ( error 51 in curl ), but the command could send any other error and it would go to general_noerror.


答:
Clicking Execute doesn't execute the procedure itself, it executes only SQL command altering the procedure.

You can check it by creating some mock stored procedure that is meant to just add some data to table and check if it adds that data when you click Execute in Modify window.

Title: Modify Stored Procedure Without Executing

Body: We have a stored procedure that fires off a thousand emails. It's auto-run at 1 AM every night. I have to edit the stored procedure in Management Studio: I know I have to choose "Modify" and then make the edits, but I don't want to click "Execute" to save it, or the emailing sequence will start. How can I save the new code without executing the stored procedure? Thank you


问:
How can I convert this for loop pseudocode into Python code without inducing infinite recursion?
I would like to turn the following pseudocode into Python code without inducing infinite recursion.

```<code>u(x) = x^2

for i = 0 to 5
v(x) = u(x)^2
u(x) = v(x)

print(u(x))
</code>```

Here is my attempt, which produces the error "maximum recursion depth exceeded":

```<code>import sympy as sym

u = lambda a: a**2

for i in range(0,5):
  print('Starting loop',i)
  v = lambda b: u(b)**2
  u = lambda c: v(c)
  print('Ending loop',i)

x = sym.symbols('x')
print(u(x))
</code>```

答:
Python variables are bound by name, and a for loop does not actually create a new scope. So when you do lambda c: v(c), you are actually creating a function that will look up v from its surrounding scope when its being executed. This means that updates to v are all applied when the function is executed.

In particular, it means that the following two definition already create an infinite loop:

```<code>v = lambda b: u(b)**2
u = lambda c: v(c)
</code>```

Because v calls u, and u calls v. It does not matter that the values are updated later, since the value will be looked up when the function is called.

You can visualize this easily using the following:

```<code>>>> x = lambda: y
>>> y = 2
>>> x()
2
>>> y = 5
>>> x()
5
</code>```

Even though the function x is never updated, it will still use the updated value for y.

What you need here is a closure to put get references to the original functions in a separate scope so that later changes do not affect the function. A simple way is to add another function where the function you want to call is passed as an argument. Since functions create new variable scopes, these will be then independent of the original definitions:

```<code>for i in range(0, 5):
    print('Starting loop', i)
    v = (lambda u: lambda b: u(b)**2)(u)
    u = (lambda v: lambda c: v(c))(v)
    print('Ending loop', i)
</code>```

See also this question on how binding works and how closures help there.

Body:
I would like to turn the following pseudocode into Python code without inducing infinite recursion.

u(x) = x^2

for i = 0 to 5
v(x) = u(x)^2
u(x) = v(x)

print(u(x))

Here is my attempt, which produces the error "maximum recursion depth exceeded":

import sympy as sym

u = lambda a: a**2

for i in range(0,5):
  print('Starting loop',i)
  v = lambda b: u(b)**2
  u = lambda c: v(c)
  print('Ending loop',i)

x = sym.symbols('x')
print(u(x))

Body:
Python variables are bound by name, and a for loop does not actually create a new scope. So when you do lambda c: v(c), you are actually creating a function that will look up v from its surrounding scope when its being executed. This means that updates to v are all applied when the function is executed.

In particular, it means that the following two definition already create an infinite loop:

v = lambda b: u(b)**2
u = lambda c: v(c)

Because v calls u, and u calls v. It does not matter that the values are updated later, since the value will be looked up when the function is called.

You can visualize this easily using the following:

>>> x = lambda: y
>>> y = 2
>>> x()
2
>>> y = 5
>>> x()
5

Even though the function x is never updated, it will still use the updated value for y.

What you need here is a closure to put get references to the original functions in a separate scope so that later changes do not affect the function. A simple way is to add another function where the function you want to call is passed as an argument. Since functions create new variable scopes, these will be then independent of the original definitions:

for i in range(0, 5):
    print('Starting loop', i)
    v = (lambda u: lambda b: u(b)**2)(u)
    u = (lambda v: lambda c: v(c))(v)
    print('Ending loop', i)

See also this question on how binding works and how closures help there.


问:
jquery attribute. jquery js

$(".dum").click(function() {
    document.getElementById("ev").value=$(this).attr("data-name");

    $("#test-form").dialog("open");
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code>// this is just the test

cell2.innerHTML = '<span  class="dum" style="color:'+testvalues[i]+'; font-size:20px;">'+testvalues[i + 2] || ''+'data-name=" '+testvalues[i+2] +'">'+ '</span>';

<div id="test-form" title="Event Information">
 <p>Event:</p>
 <input id= "ev" type="text"  name="fullname" disabled />
</div></code>```

I have a  where I have values from db. And I am trying to get those value to a input box using jquery attr but I am getting undefined. The attr name is "data-name". I do not know what I am doing wrong here. I will be very thankful for any help.

答: Please check the spans you are inserting. I don't think the problem is related to jQuery, rather that you are not actually writing the data-name attribute. What is the || on the innerHTML for? Because of that || you are only writing the first part of the string (everything to its left) and nothing to its right (the data-name attribute).

Title: jquery attribute. jquery js

Body:
$(".dum").click(function() {
    document.getElementById("ev").value=$(this).attr("data-name");

    $("#test-form").dialog("open");
});

// this is just the test

cell2.innerHTML = ''+testvalues[i + 2] || ''+'data-name=" '+testvalues[i+2] +'">'+ '';

Event:

 <input id= "ev" type="text"  name="fullname" disabled />

I have a  where I have values from db. And I am trying to get those value to a input box using jquery attr but I am getting undefined. The attr name is "data-name". I do not know what I am doing wrong here. I will be very thankful for any help.


问:
idempotency_key must be set error using Square API
Trying to use Square e-commerce API. When running a test charge, I recieve the following response:

```<code>object(stdClass)#14 (1) {
  ["errors"]=>
  array(1) {
    [0]=>
     object(stdClass)#13 (4) {
      ["category"]=>
      string(21) "INVALID_REQUEST_ERROR"
      ["code"]=>
      string(26) "MISSING_REQUIRED_PARAMETER"
      ["detail"]=>
      string(17) "Field must be set"
      ["field"]=>
      string(15) "idempotency_key"
    }
  }
}
</code>```

I cant quite work out why it has failed to set the idempotenct_key. I thought this was being dealt with by the uniqid() function. Please advise. My code is as follows:

```<code><?php
require 'vendor/autoload.php';
# Replace these values. You probably want to start with your Sandbox credentials
# to start: https://docs.connect.squareup.com/articles/using-sandbox/
# The ID of the business location to associate processed payments with.
# If you're testing things out, use a sandbox location ID.
#
# See [Retrieve your business's locations](https://docs.connect.squareup.com/articles/getting-started/#retrievemerchantprofile)
# for an easy way to get your business's location IDs.

# The access token to use in all Connect API requests. Use your *sandbox* access
# token if you're just testing things out.
$access_token = 'REPLACE_ME';

    SquareConnect\Configuration::getDefaultConfiguration()->setAccessToken($access_token);

$locations_api = new \SquareConnect\Api\LocationsApi();

$location_id = $locations_api->listLocations($access_token);
# Helps ensure this code has been reached via form submission
if ($_SERVER['REQUEST_METHOD'] != 'POST') {
  error_log("Received a non-POST request");
  echo "Request not allowed";
  http_response_code(405);
  return;
}
# Fail if the card form didn't send a value for `nonce` to the server
$nonce = $_POST['nonce'];
if (is_null($nonce)) {
  echo "Invalid card data";
  http_response_code(422);
  return;
}
$transactions_api = new \SquareConnect\Api\TransactionsApi();
$request_body = array (
  "card_nonce" => $nonce,
  # Monetary amounts are specified in the smallest unit of the applicable currency.
  # This amount is in cents. It's also hard-coded for $1.00, which isn't very useful.
  "amount_money" => array (
    "amount" => 100,
    "currency" => "USD"
  ),
  # Every payment you process with the SDK must have a unique idempotency key.
  # If you're unsure whether a particular payment succeeded, you can reattempt
  # it with the same idempotency key without worrying about double charging
  # the buyer.
  "idempotency_key" => uniqid()
);
# The SDK throws an exception if a Connect endpoint responds with anything besides
# a 200-level HTTP code. This block catches any exceptions that occur from the request.
try {
  $result = $transactions_api->charge($access_token, $location_id, $request_body);
  echo "```";
  print_r($result);
  echo "```";
} catch (\SquareConnect\ApiException $e) {
  echo "Caught exception!<br/>";
  print_r("<strong>Response body:</strong><br/>");
  echo "```"; var_dump($e->getResponseBody()); echo "```";
  echo "<br/><strong>Response headers:</strong><br/>";
  echo "```"; var_dump($e->getResponseHeaders()); echo "```";
}

?>
</code>```

答:
It looks like you are using some outdated sample code. Try the code here: https://github.com/square/connect-api-examples/blob/master/connect-examples/v2/php_payment/process-card.php

The main difference is the lack of an authorization parameter in the request.

Body:
Trying to use Square e-commerce API. When running a test charge, I recieve the following response:

object(stdClass)#14 (1) {
  ["errors"]=>
  array(1) {
    [0]=>
     object(stdClass)#13 (4) {
      ["category"]=>
      string(21) "INVALID_REQUEST_ERROR"
      ["code"]=>
      string(26) "MISSING_REQUIRED_PARAMETER"
      ["detail"]=>
      string(17) "Field must be set"
      ["field"]=>
      string(15) "idempotency_key"
    }
  }
}

I cant quite work out why it has failed to set the idempotenct_key. I thought this was being dealt with by the uniqid() function. Please advise. My code is as follows:

<?php
require 'vendor/autoload.php';
# Replace these values. You probably want to start with your Sandbox credentials
# to start: https://docs.connect.squareup.com/articles/using-sandbox/
# The ID of the business location to associate processed payments with.
# If you're testing things out, use a sandbox location ID.
#
# See [Retrieve your business's locations](https://docs.connect.squareup.com/articles/getting-started/#retrievemerchantprofile)
# for an easy way to get your business's location IDs.

# The access token to use in all Connect API requests. Use your *sandbox* access
# token if you're just testing things out.
$access_token = 'REPLACE_ME';

    SquareConnect\Configuration::getDefaultConfiguration()->setAccessToken($access_token);

$locations_api = new \SquareConnect\Api\LocationsApi();

$location_id = $locations_api->listLocations($access_token);
# Helps ensure this code has been reached via form submission
if ($_SERVER['REQUEST_METHOD'] != 'POST') {
  error_log("Received a non-POST request");
  echo "Request not allowed";
  http_response_code(405);
  return;
}
# Fail if the card form didn't send a value for `nonce` to the server
$nonce = $_POST['nonce'];
if (is_null($nonce)) {
  echo "Invalid card data";
  http_response_code(422);
  return;
}
$transactions_api = new \SquareConnect\Api\TransactionsApi();
$request_body = array (
  "card_nonce" => $nonce,
  # Monetary amounts are specified in the smallest unit of the applicable currency.
  # This amount is in cents. It's also hard-coded for $1.00, which isn't very useful.
  "amount_money" => array (
    "amount" => 100,
    "currency" => "USD"
  ),
  # Every payment you process with the SDK must have a unique idempotency key.
  # If you're unsure whether a particular payment succeeded, you can reattempt
  # it with the same idempotency key without worrying about double charging
  # the buyer.
  "idempotency_key" => uniqid()
);
# The SDK throws an exception if a Connect endpoint responds with anything besides
# a 200-level HTTP code. This block catches any exceptions that occur from the request.
try {
  $result = $transactions_api->charge($access_token, $location_id, $request_body);
  echo "
";
  print_r($result);
  echo "
";
} catch (\SquareConnect\ApiException $e) {
  echo "Caught exception!
";
  print_r("Response body:
");
  echo "
"; var_dump($e->getResponseBody()); echo "
";
  echo "
Response headers:
";
  echo "
"; var_dump($e->getResponseHeaders()); echo "
";
}

?>