问:
Outer addition with Eigen
I am attempting to translate the following python function into C++:

import numpy as np
from scipy.linalg import blas
def scaled_dist(a, b, ls):
    al = a/ls
    bl = b/ls
    tmp1 = np.sum(al**2, axis=1)
    tmp2 = np.sum(bl**2, axis=1)
    tmp3 = np.add.outer(tmp1, tmp2, order='F')
    tau = blas.dgemm(a=al, b=bl, alpha=-2.0, c=tmp3, beta=1, trans_b=1)
    np.clip(tau, 0, np.inf, out=tau)
    return tau
```

<p>However I have hit a stumbling block with the line:</p>

<pre class="lang-py prettyprint-override"><code>tmp3 = np.add.outer(tmp1, tmp2)
</code>```

My c++ code compiles but encounters a runtime error when executed. The code (up to that line) is:

Eigen::MatrixXd test2(const Eigen::MatrixXd &x1, const Eigen::MatrixXd &x2,const Eigen::VectorXd &vec)
{
  Eigen::MatrixXd r = Eigen::MatrixXd::Zero(x1.rows(), x2.rows());
  Eigen::MatrixXd al = x1.array().rowwise() / vec.transpose().array();
  Eigen::VectorXd tmp1 = al.array().square().rowwise().sum();

  Eigen::MatrixXd bl = x2.array().rowwise() / vec.transpose().array();
  Eigen::VectorXd tmp2 = bl.array().square().rowwise().sum();

  r = tmp1.transpose().array() + tmp2.array();
  return r;
}
```

<p>I am able to make sense of the runtime error, which is (I believe) an assertion error, complaining that the left and right hand sides of the addition expression do not match in size. My approach was motivated by the fact that <code>tmp1.transpose() * tmp2</code> <em>does</em> appear to produce the expected result.</p>

<p><strong>My question is as follows:</strong></p>

<p>Given two vectors, <code>vec1</code> and <code>vec2</code>, what is the idiomatic way using Eigen of achieving the same functionality as <code>numpy.add.outer(vec1, vec2)</code>, namely an "outer" addition whereby a matrix is obtained by adding the (broadcast) rows of one vector to the (broadcast) columns of the other? i.e., if</p>

```vec1 = [1,2,3]
vec2 = [3,4,5]
```

<p>then</p>

```outer_add(vec1, vec2) =
[4, 5, 6]
[5, 6, 7]
[6, 7, 8]
```

答:
You can use replicate for that, e.g.:</p>

```<code>Vector3f v1(1,2,3), v2(3,4,5);
MatrixXf r = v1.rowwise().replicate(v2.size())
           + v2.transpose().colwise().replicate(v1.size());
</code>```

Title: Outer addition with Eigen

Body:
I am attempting to translate the following python function into C++:

import numpy as np
from scipy.linalg import blas
def scaled_dist(a, b, ls):
    al = a/ls
    bl = b/ls
    tmp1 = np.sum(al**2, axis=1)
    tmp2 = np.sum(bl**2, axis=1)
    tmp3 = np.add.outer(tmp1, tmp2, order='F')
    tau = blas.dgemm(a=al, b=bl, alpha=-2.0, c=tmp3, beta=1, trans_b=1)
    np.clip(tau, 0, np.inf, out=tau)
    return tau

However I have hit a stumbling block with the line:

tmp3 = np.add.outer(tmp1, tmp2)

My c++ code compiles but encounters a runtime error when executed. The code (up to that line) is:

Eigen::MatrixXd test2(const Eigen::MatrixXd &x1, const Eigen::MatrixXd &x2,const Eigen::VectorXd &vec)
{
  Eigen::MatrixXd r = Eigen::MatrixXd::Zero(x1.rows(), x2.rows());
  Eigen::MatrixXd al = x1.array().rowwise() / vec.transpose().array();
  Eigen::VectorXd tmp1 = al.array().square().rowwise().sum();

  Eigen::MatrixXd bl = x2.array().rowwise() / vec.transpose().array();
  Eigen::VectorXd tmp2 = bl.array().square().rowwise().sum();

  r = tmp1.transpose().array() + tmp2.array();
  return r;
}

I am able to make sense of the runtime error, which is (I believe) an assertion error, complaining that the left and right hand sides of the addition expression do not match in size. My approach was motivated by the fact that tmp1.transpose() * tmp2 does appear to produce the expected result.

My question is as follows:

Given two vectors, vec1 and vec2, what is the idiomatic way using Eigen of achieving the same functionality as numpy.add.outer(vec1, vec2), namely an "outer" addition whereby a matrix is obtained by adding the (broadcast) rows of one vector to the (broadcast) columns of the other? i.e., if

vec1 = [1,2,3]
vec2 = [3,4,5]

then

outer_add(vec1, vec2) =
[4, 5, 6]
[5, 6, 7]
[6, 7, 8]

Body:
You can use replicate for that, e.g.:

Vector3f v1(1,2,3), v2(3,4,5);
MatrixXf r = v1.rowwise().replicate(v2.size())
           + v2.transpose().colwise().replicate(v1.size());


来源: stackexchange

问:
Google spreadsheet api Request had insufficient authentication scopes
I'm making an script to read data from google spreadsheet using the following script on nodejs:

```<code>var url = oauth2Client.generateAuthUrl({
    access_type:     'offline',
    approval_prompt: 'force',
    scope: [
      'https://www.googleapis.com/auth/analytics.readonly',
      'https://www.googleapis.com/auth/drive',
      'https://www.googleapis.com/auth/spreadsheets'
    ]
});
global.googleapis = { expiry_date: 0 };
google.options({ auth: oauth2Client });
var sheets    = google.sheets('v4');
sheets.spreadsheets.get({ spreadsheetId: 'id'}, function(err, data) {
    res.send(err, data);
});
</code>```

But on every get request i'm getting this error:

```<code>Request had insufficient authentication scopes.
</code>```

I checked the Google developers console to enable the Google Drive API and it's enabled, so I dont really know what could it be.

答:
In my case a token.pickle file was created in the same working directory as my program, I also had my credentials.json file in the same directory, all I did was deleted the token.pickle file , then changed the scope, then ran it again, it will again ask for authentication in your browser and that's it , it works.

My code snippet is like below , I was creating a pickle file so I had to delete it before changing scope

```<code>    if os.path.exists('token.pickle'):
    with open('token.pickle', 'rb') as token:
        creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server()
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm making an script to read data from google spreadsheet using the following script on nodejs:

var url = oauth2Client.generateAuthUrl({
    access_type:     'offline',
    approval_prompt: 'force',
    scope: [
      'https://www.googleapis.com/auth/analytics.readonly',
      'https://www.googleapis.com/auth/drive',
      'https://www.googleapis.com/auth/spreadsheets'
    ]
});
global.googleapis = { expiry_date: 0 };
google.options({ auth: oauth2Client });
var sheets    = google.sheets('v4');
sheets.spreadsheets.get({ spreadsheetId: 'id'}, function(err, data) {
    res.send(err, data);
});

But on every get request i'm getting this error:

Request had insufficient authentication scopes.

I checked the Google developers console to enable the Google Drive API and it's enabled, so I dont really know what could it be.

Body:
In my case a token.pickle file was created in the same working directory as my program, I also had my credentials.json file in the same directory, all I did was deleted the token.pickle file , then changed the scope, then ran it again, it will again ask for authentication in your browser and that's it , it works.

My code snippet is like below , I was creating a pickle file so I had to delete it before changing scope

    if os.path.exists('token.pickle'):
    with open('token.pickle', 'rb') as token:
        creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server()
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

ContentLicense: CC BY-SA 4.0


问:
Passing value from onResponse to onPostExecute keep turning to null
I'm connecting to API with the async task. I need to pass two values from the API to the app, in onResponse I have logged the values and got them right. But in onPostExecute one of them keep turning into null

I have already tried to check different values from API and logs to see if the value that I'm looking for is there or if the connection is valid, everything went alright until it hits the onPostExecute where I'm getting only one value

```<code>public class ChooseLocationTask extends AsyncTask<String, Void, Void> {

    OkHttpClient client = new OkHttpClient.Builder()
            //default timeout for not annotated requests
            .readTimeout(15000, TimeUnit.MILLISECONDS)
            .connectTimeout(15000, TimeUnit.MILLISECONDS)
            .writeTimeout(15000, TimeUnit.MILLISECONDS)
            .build();
    Request request;

    private TextView location;
    private TextView value;
    String state;
    Number probability;
    String probablityString;

    public ChooseLocationTask(TextView location, int selected, TextView value){
        this.location = location;
        this.value = value;
    }

    @Override
    protected void onProgressUpdate(Void...values){
        super.onProgressUpdate(values);
    }
    @Override
    protected void onPreExecute(){
        super.onPreExecute();
    }
    @Override

    protected Void doInBackground(String... urls) {
        request = new Request.Builder().url(urls[0]).build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                Log.d("CallMsg", String.valueOf(call));
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d("Response", String.valueOf(response));
                try {
                    JSONObject jsonObject = new JSONObject(response.body().string());
                    JSONObject weather = jsonObject.getJSONObject("weather");
                    JSONObject location = weather.getJSONObject("location");
                    state = location.getString("state");

                    JSONObject percentage = jsonObject.getJSONObject("probability");
                    JSONObject calculated = percentage.getJSONObject("highest");
                    probability = calculated.getInt("value");
                    probablityString = probability.toString();
                    Log.d("percentage", probability.toString());
                    Log.d("String",probablityString);
                    Log.d("location",state);

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

        return null;
    }

    @Override
    protected void onPostExecute(Void voids){
        if(isCancelled()){
            voids= null;
        } else {
            location.setText(state);
            value.setText("your chance to see Northern lights today is" + probablityString);
            Log.d("value", "onPostExecute: " + probablityString);
        }
        Log.d("post", "onPostExecute: " + probability);
    }

}

</code>```

Basically, all I need is advice on how to get this value, I feel like maybe I made mistake when converting it into a string, but in logs, in onResponse it shows quite alright, so I don't know. Thank you for all the advice

答:
Retrofit has two techniques for performing requests, one synchronous (execute()) and another asynchronous (enqueue()). You are using the asynchronous technique, and as a result, when you go to execute your AsyncTask, your doInBackground() method immediately calls enqueue(), completes, and calls onPostExecute() before your request has completed.

You have two options. First, you can keep your current AsyncTask, but replace enqueue() for execute(). This will look a little like:

```<code>public class ChooseLocationTask extends AsyncTask<String, Void, Void> {

    private final OkHttpClient client = new OkHttpClient.Builder()
            //default timeout for not annotated requests
            .readTimeout(15000, TimeUnit.MILLISECONDS)
            .connectTimeout(15000, TimeUnit.MILLISECONDS)
            .writeTimeout(15000, TimeUnit.MILLISECONDS)
            .build();
    private final Request request;

    private final TextView location;
    private final TextView value;
    String state;
    Number probability;
    String probablityString;

    public ChooseLocationTask(TextView location, int selected, TextView value){
        this.location = location;
        this.value = value;
    }

    @Override
    protected Void doInBackground(String... urls) {
        request = new Request.Builder().url(urls[0]).build();

        try {
            final Response<?> response = client.newCall(request).execute();
            if(response.isSuccessful()) {
                final JSONObject jsonObject = new JsonObject(response.body().string());
                //etc...
            }
        } catch (IOException e) {
           //...
        }

        //I'd recommend you return values as well, rather than assigning them to
        //instance variables
        return null;
    }

    @Override
    protected void onPostExecute(Void voids){
        if(isCancelled()){
            voids= null;
        } else {
            location.setText(state);
            value.setText("your chance to see Northern lights today is" + probablityString);
            Log.d("value", "onPostExecute: " + probablityString);
        }
        Log.d("post", "onPostExecute: " + probability);
    }
</code>```

Or, you can get rid of your AsyncTask entirely, and just call enqueue()

Body:
I'm connecting to API with the async task. I need to pass two values from the API to the app, in onResponse I have logged the values and got them right. But in onPostExecute one of them keep turning into null

I have already tried to check different values from API and logs to see if the value that I'm looking for is there or if the connection is valid, everything went alright until it hits the onPostExecute where I'm getting only one value

public class ChooseLocationTask extends AsyncTask<String, Void, Void> {

    OkHttpClient client = new OkHttpClient.Builder()
            //default timeout for not annotated requests
            .readTimeout(15000, TimeUnit.MILLISECONDS)
            .connectTimeout(15000, TimeUnit.MILLISECONDS)
            .writeTimeout(15000, TimeUnit.MILLISECONDS)
            .build();
    Request request;

    private TextView location;
    private TextView value;
    String state;
    Number probability;
    String probablityString;

    public ChooseLocationTask(TextView location, int selected, TextView value){
        this.location = location;
        this.value = value;
    }

    @Override
    protected void onProgressUpdate(Void...values){
        super.onProgressUpdate(values);
    }
    @Override
    protected void onPreExecute(){
        super.onPreExecute();
    }
    @Override

    protected Void doInBackground(String... urls) {
        request = new Request.Builder().url(urls[0]).build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                Log.d("CallMsg", String.valueOf(call));
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d("Response", String.valueOf(response));
                try {
                    JSONObject jsonObject = new JSONObject(response.body().string());
                    JSONObject weather = jsonObject.getJSONObject("weather");
                    JSONObject location = weather.getJSONObject("location");
                    state = location.getString("state");

                    JSONObject percentage = jsonObject.getJSONObject("probability");
                    JSONObject calculated = percentage.getJSONObject("highest");
                    probability = calculated.getInt("value");
                    probablityString = probability.toString();
                    Log.d("percentage", probability.toString());
                    Log.d("String",probablityString);
                    Log.d("location",state);

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

        return null;
    }

    @Override
    protected void onPostExecute(Void voids){
        if(isCancelled()){
            voids= null;
        } else {
            location.setText(state);
            value.setText("your chance to see Northern lights today is" + probablityString);
            Log.d("value", "onPostExecute: " + probablityString);
        }
        Log.d("post", "onPostExecute: " + probability);
    }

}

Basically, all I need is advice on how to get this value, I feel like maybe I made mistake when converting it into a string, but in logs, in onResponse it shows quite alright, so I don't know. Thank you for all the advice

Body:
Retrofit has two techniques for performing requests, one synchronous (execute()) and another asynchronous (enqueue()). You are using the asynchronous technique, and as a result, when you go to execute your AsyncTask, your doInBackground() method immediately calls enqueue(), completes, and calls onPostExecute() before your request has completed.

You have two options. First, you can keep your current AsyncTask, but replace enqueue() for execute(). This will look a little like:

public class ChooseLocationTask extends AsyncTask<String, Void, Void> {

    private final OkHttpClient client = new OkHttpClient.Builder()
            //default timeout for not annotated requests
            .readTimeout(15000, TimeUnit.MILLISECONDS)
            .connectTimeout(15000, TimeUnit.MILLISECONDS)
            .writeTimeout(15000, TimeUnit.MILLISECONDS)
            .build();
    private final Request request;

    private final TextView location;
    private final TextView value;
    String state;
    Number probability;
    String probablityString;

    public ChooseLocationTask(TextView location, int selected, TextView value){
        this.location = location;
        this.value = value;
    }

    @Override
    protected Void doInBackground(String... urls) {
        request = new Request.Builder().url(urls[0]).build();

        try {
            final Response<?> response = client.newCall(request).execute();
            if(response.isSuccessful()) {
                final JSONObject jsonObject = new JsonObject(response.body().string());
                //etc...
            }
        } catch (IOException e) {
           //...
        }

        //I'd recommend you return values as well, rather than assigning them to
        //instance variables
        return null;
    }

    @Override
    protected void onPostExecute(Void voids){
        if(isCancelled()){
            voids= null;
        } else {
            location.setText(state);
            value.setText("your chance to see Northern lights today is" + probablityString);
            Log.d("value", "onPostExecute: " + probablityString);
        }
        Log.d("post", "onPostExecute: " + probability);
    }

Or, you can get rid of your AsyncTask entirely, and just call enqueue()


问:
Scripting file system object - fail to write text and create file object
I have most of the codes but cannot run it. Some basic info is that my username is nywongab, I want it as a text file and the text file placed on the desktop.
Thanks</p>

```<code>Sub createsth()
    Dim abbyFilesystem As filesystemobject
    Dim abbyfile As File

    Set abbyFilesystem = CreateObject("scripting.filesystemobject")
    Set abbyfile =_
        abbyFilesystem.createtextfile("C:\Users\nywongab\Desktop"_
        & ".txt")_

    Dim result As String
    result = "A"

    abbyfile.write (result)
End Sub
</code>```

答:
Not quite clear the question.. though from the subject you have a problem with writing to file. From the code is obviously not working, but you were close.

If you are trying to get the username or the desktop path more dynamically, you can use Environ like so:

Sub createsth()

Dim pathDesktop As String
pathDesktop = Environ("USERPROFILE") & "\Desktop\"

Dim pathSave As String
pathSave = pathDesktop & Environ("USERNAME") & ".txt"

Dim abbyFileSystem As Object
Set abbyFileSystem = CreateObject("Scripting.FileSystemObject")

Dim abbyFile As Object
Set abbyFile = abbyFileSystem.CreateTextFile(pathSave)

Dim result As String
result = "A"

abbyFile.Write result
abbyFile.Close

End Sub
```

Body:
I have most of the codes but cannot run it. Some basic info is that my username is nywongab, I want it as a text file and the text file placed on the desktop.
Thanks

Sub createsth()
    Dim abbyFilesystem As filesystemobject
    Dim abbyfile As File

    Set abbyFilesystem = CreateObject("scripting.filesystemobject")
    Set abbyfile =_
        abbyFilesystem.createtextfile("C:\Users\nywongab\Desktop"_
        & ".txt")_

    Dim result As String
    result = "A"

    abbyfile.write (result)
End Sub


问:
How apps like @macafee and other antivirus apps runs in background without enabling autostart in android
How these types of apps get location and perform other actions in Background without auto-start permission in phones like xiomi.</p>

答:
Few popular apps run in background without being killed during memory cleanup cycle (many of the polular OEMs customize the stack ROM for battery/memory optimization), because they are "White listed" by these manufactures.

For your app you can whitelist it either manually (via corresponding "settings" for the devices) or pragmatically by redirecting users to the corresponding settings page to white list the app. Pragmatically you can do like below:

Add below permissions in the App's manifest file:

```<code><uses-permission android:name="oppo.permission.OPPO_COMPONENT_SAFE"/>
<uses-permission android:name="com.huawei.permission.external_app_settings.USE_COMPONENT"/>
</code>```

Redirect your to the Auto Start setting:

```<code>if (Build.BRAND.equalsIgnoreCase("xiaomi")) {
            Intent intent = new Intent();
            intent.setComponent(new ComponentName("com.miui.securitycenter",
                    "com.miui.permcenter.autostart.AutoStartManagementActivity"));
            startActivity(intent);
        } else if (Build.BRAND.equalsIgnoreCase("Honor")) {
            Intent intent = new Intent();
            intent.setComponent(new ComponentName("com.huawei.systemmanager",
                    "com.huawei.systemmanager.optimize.process.ProtectActivity"));
            startActivity(intent);
        } else if (Build.MANUFACTURER.equalsIgnoreCase("oppo")) {
            try {
                Intent intent = new Intent();
                intent.setClassName("com.coloros.safecenter",
                        "com.coloros.safecenter.permission.startup.StartupAppListActivity");
                startActivity(intent);
            } catch (Exception e) {
                try {
                    Intent intent = new Intent();
                    intent.setClassName("com.oppo.safe",
                            "com.oppo.safe.permission.startup.StartupAppListActivity");
                    startActivity(intent);
                } catch (Exception ex) {
                    try {
                        Intent intent = new Intent();
                        intent.setClassName("com.coloros.safecenter",
                                "com.coloros.safecenter.startupapp.StartupAppListActivity");
                        startActivity(intent);
                    } catch (Exception exx) {

                    }
                }
            }
        }
.... //Like for other OEMs [Check details for the devices here][1]
</code>```

I have tested this method and it worked but the reliability is still a question.

But as an user we can prevent the app's background services as below :

Press Recent apps physical key (left side button).

Drag down the app once (select, hold & slide it down) which you require to be put in continuous operation.

The app will be put in lock condition (even if you clear the background app processes by clearing, the app will keep on running).

Same way, if you want to remove it from the lock condition, just drag down again once and the lock symbol will disappear (clearing the background process will clear the app from running too).

Body:
Few popular apps run in background without being killed during memory cleanup cycle (many of the polular OEMs customize the stack ROM for battery/memory optimization), because they are "White listed" by these manufactures.

For your app you can whitelist it either manually (via corresponding "settings" for the devices) or pragmatically by redirecting users to the corresponding settings page to white list the app. Pragmatically you can do like below:

Add below permissions in the App's manifest file:

<uses-permission android:name="oppo.permission.OPPO_COMPONENT_SAFE"/>
<uses-permission android:name="com.huawei.permission.external_app_settings.USE_COMPONENT"/>

Redirect your to the Auto Start setting:

if (Build.BRAND.equalsIgnoreCase("xiaomi")) {
            Intent intent = new Intent();
            intent.setComponent(new ComponentName("com.miui.securitycenter",
                    "com.miui.permcenter.autostart.AutoStartManagementActivity"));
            startActivity(intent);
        } else if (Build.BRAND.equalsIgnoreCase("Honor")) {
            Intent intent = new Intent();
            intent.setComponent(new ComponentName("com.huawei.systemmanager",
                    "com.huawei.systemmanager.optimize.process.ProtectActivity"));
            startActivity(intent);
        } else if (Build.MANUFACTURER.equalsIgnoreCase("oppo")) {
            try {
                Intent intent = new Intent();
                intent.setClassName("com.coloros.safecenter",
                        "com.coloros.safecenter.permission.startup.StartupAppListActivity");
                startActivity(intent);
            } catch (Exception e) {
                try {
                    Intent intent = new Intent();
                    intent.setClassName("com.oppo.safe",
                            "com.oppo.safe.permission.startup.StartupAppListActivity");
                    startActivity(intent);
                } catch (Exception ex) {
                    try {
                        Intent intent = new Intent();
                        intent.setClassName("com.coloros.safecenter",
                                "com.coloros.safecenter.startupapp.StartupAppListActivity");
                        startActivity(intent);
                    } catch (Exception exx) {

                    }
                }
            }
        }
.... //Like for other OEMs [Check details for the devices here][1]

I have tested this method and it worked but the reliability is still a question.

But as an user we can prevent the app's background services as below :

Press Recent apps physical key (left side button).

Drag down the app once (select, hold & slide it down) which you require to be put in continuous operation.

The app will be put in lock condition (even if you clear the background app processes by clearing, the app will keep on running).

Same way, if you want to remove it from the lock condition, just drag down again once and the lock symbol will disappear (clearing the background process will clear the app from running too).


问:
lib dependencies and their order
at times if we don't list libs in certain order inside a makefile, it fails.

The reason being - definition should come before its use.

How to determine the correct order?

答:
I found this to be annoying too. I remember searching for a tool to make the sorting for me, but didn't find anything to help.

Finally I decided to use the brute force approach: If you will list all your libs twice, e.g. -lA -lB -lA -lB, it will guarantee that every library is listed before (and after) every other library.

So given a $(LIST) of libraries, you can use $(addprefix -l,$(LIST) $(LIST)).

Not very elegant, and slows the linking stage somewhat, but works.

Title: lib dependencies and their order


问:
When writing an installer for my gtk app, how should I deal with gtk dependencies?
I have installed gtk on my centos 7 machine and developed a simple gui app that uses gtk. I would now like to write an installer that installs both my app and the required gtk dependencies so that it is easy for the end user to install and run. But I am unsure what is necessary for me to install. One thing that I'm unclear about are the dependencies needed by the client app and the dependencies needed by the display server. In my case both the client and the server are on the same machine. But this may not be the case for the end user. I believe my app dependencies include gtk, gdk, glib, cairo and more. How should my installer check that the end user has the gtk dependencies required to run my app and handle those cases where a dependency is missing?</p>

答:
Rather than putting effort into writing an installer, consider packaging your app for flatpak, which is shipped by default on CentOS 7.

Alternatively, package your app as an RPM.

Installers for individual apps are vanishingly uncommon on Linux due to the use of centralised package managers, which generally do a much better job of installing and uninstalling software correctly than custom installers do.


问:
String split of delimited values in 2 columns simultaneously - R
I'm looking for an elegant way to split and convert semicolon-separated values from two columns into rows. Data looks like as:

```<code>1        A0A024R442;E7ETB3;Q9ULA0;E7EMB6           443;465;447;382
2 A0A024R442;E7ETB3;Q9ULA0;E7EMB6;C9JBE1       323;345;327;262;309
</code>```

The required output is:

```<code>A0A024R442        443
    E7ETB3        465
    Q9ULA0        447
  ...................
    C9JBE1        309
</code>```

The number of elements in columns is always equal per row as depicted above. I have tried the strsplit() function but I think I can't split delimited values on multiple columns simultaneously (please correct me if I'm wrong).

I would appreciate any suggestion.

Body:
I'm looking for an elegant way to split and convert semicolon-separated values from two columns into rows. Data looks like as:

1        A0A024R442;E7ETB3;Q9ULA0;E7EMB6           443;465;447;382
2 A0A024R442;E7ETB3;Q9ULA0;E7EMB6;C9JBE1       323;345;327;262;309

The required output is:

A0A024R442        443
    E7ETB3        465
    Q9ULA0        447
  ...................
    C9JBE1        309

The number of elements in columns is always equal per row as depicted above. I have tried the strsplit() function but I think I can't split delimited values on multiple columns simultaneously (please correct me if I'm wrong).

I would appreciate any suggestion.

Body:
base R:

data.frame(matrix(unlist(strsplit(as.matrix(df),";")),ncol=2))

          X1  X2
1 A0A024R442 443
2     E7ETB3 465
3     Q9ULA0 447
4     E7EMB6 382
5 A0A024R442 323
6     E7ETB3 345
7     Q9ULA0 327
8     E7EMB6 262
9     C9JBE1 309


问:
How do I scale a Tensor column by a constant value?
I need to scale certain columns of a tensor by a constant value, but I've got no idea how to approach this with Keras/Tensorflow. I've got a (BatchSize, 6) matrix, and I need to multiply column 2 by one constant and column 5 by another constant.

I tried making a Lambda that multiplied the columns using sliced indexes, but TF returned an error about not being able to assign values to the result.

e.g.

x[:,2] *= constant
```

Any suggestions?

答:
Just multiply it by a tensor of ones and constants at the desired column locations. For example:

import tensorflow as tf
import numpy as np

x = tf.placeholder(tf.float32, (None, 6))

const1 = 5.
const2 = 3.
scaler = tf.constant([1, 1, const1, 1, 1, const2], dtype=tf.float32)
res = x*scaler

x_data = np.ones((3, 6))
with tf.Session() as sess:
    print(res.eval({x:x_data}))
# [[1. 1. 5. 1. 1. 3.]
#  [1. 1. 5. 1. 1. 3.]
#  [1. 1. 5. 1. 1. 3.]]
```

Body:
I need to scale certain columns of a tensor by a constant value, but I've got no idea how to approach this with Keras/Tensorflow. I've got a (BatchSize, 6) matrix, and I need to multiply column 2 by one constant and column 5 by another constant.

I tried making a Lambda that multiplied the columns using sliced indexes, but TF returned an error about not being able to assign values to the result.

e.g.

x[:,2] *= constant

Any suggestions?


问:
Ranking data with views
I have two tables that I'm working with.  FILMS and STUDIO.  I'm trying to make a view that sums the profit of films by studio.

Here are my tables:

```<code>**FILMS**
FILM_ID       NUMBER
FILM_NAME     VARCHAR2
FILM_DIRECTOR VARCHAR2

**STUDIO**
STUDIO_ID    NUMBER
STUDIO_NAME  VARCHAR2
PROFIT       NUMBER
</code>```

I have been trying to make a view with the following columns, STUDIO_ID,    STUDIO_NAME, TOTAL_PROFIT.
Where TOTAL_PROFIT holds the sum.

Here is what I have tried:

```<code>SELECT
        STUDIO.STUDIO_ID,
        FILMS.PROFIT
    FROM
        STUDIO,
        FILMS
    WHERE
        STUDIO.STUDIO_ID IS NOT NULL
</code>```

I'm not sure how to store the sum of profit by studio in another new column.

Any help would be appreciated.

答:
use sum aggregate funtionc</p>

```<code>    SELECT
    STUDIO.STUDIO_ID,STUDIO_NAME
    sum(FILMS.PROFIT) as totalprofit
FROM
    STUDIO,
    FILMS
WHERE
    STUDIO.STUDIO_ID IS NOT NULL
 group by STUDIO.STUDIO_ID,STUDIO_NAME
</code>```

Title: Ranking data with views

Body:
I have two tables that I'm working with.  FILMS and STUDIO.  I'm trying to make a view that sums the profit of films by studio.

Here are my tables:

**FILMS**
FILM_ID       NUMBER
FILM_NAME     VARCHAR2
FILM_DIRECTOR VARCHAR2

**STUDIO**
STUDIO_ID    NUMBER
STUDIO_NAME  VARCHAR2
PROFIT       NUMBER

I have been trying to make a view with the following columns, STUDIO_ID,    STUDIO_NAME, TOTAL_PROFIT.
Where TOTAL_PROFIT holds the sum.

Here is what I have tried:

SELECT
        STUDIO.STUDIO_ID,
        FILMS.PROFIT
    FROM
        STUDIO,
        FILMS
    WHERE
        STUDIO.STUDIO_ID IS NOT NULL

I'm not sure how to store the sum of profit by studio in another new column.

Any help would be appreciated.

Body:
use sum aggregate funtionc

    SELECT
    STUDIO.STUDIO_ID,STUDIO_NAME
    sum(FILMS.PROFIT) as totalprofit
FROM
    STUDIO,
    FILMS
WHERE
    STUDIO.STUDIO_ID IS NOT NULL
 group by STUDIO.STUDIO_ID,STUDIO_NAME


问:
Issue with Spring Webflux webclient , nothing happens when trying to send post request
Have the following implementation of webclient :

```<code>    public <T> WebClient.ResponseSpec sendRequest(HttpMethod method, String contentType, T body, String baseUrl, String path) {
    try {
        WebClient webClient = WebClient.builder().baseUrl(baseUrl).filter(logRequest()).build();
        WebClient.ResponseSpec responseSpec = webClient.method(method)
                .uri(path)
                .header(HttpHeaders.CONTENT_TYPE, contentType)
                .body(BodyInserters.fromObject(body))
                .retrieve();
        return responseSpec;
    } catch (Exception e) {
        throw new WebClientProcessingException("Exception when trying to execute request", e);

    }
}

// This method returns filter function which will log request data
private static ExchangeFilterFunction logRequest() {
    return ExchangeFilterFunction.ofRequestProcessor(clientRequest -> {
        LOGGER.info("Request: {} {} {}", clientRequest.method(), clientRequest.url(), clientRequest.body());
        clientRequest.headers().forEach((name, values) -> values.forEach(value -> LOGGER.info("{}={}", name, value)));
        return Mono.just(clientRequest);
    });
}
</code>```

Also have the following code , which is creating user object and command which contains user object , then calling webclient to send an request

```<code>@Autowired
private BaseWebClient baseWebClient;
@Override
public void saveOrUpdateUser() {
        UserPayload userPayload = new UserPayload();
        userPayload.setUserId(111L);
        userPayload.setCreatedAt(ZonedDateTime.now(DateTimeProps.systemTimeZone));
        UserCommand userCommand = new UserCommand();
        userCommand.setUser(userPayload);
        baseWebClient.sendRequest(HttpMethod.POST, "application/json",
            Stream.of(userCommand).collect(Collectors.toList()),
            "http://localhost:8080",
            "/users").onStatus(HttpStatus::isError, clientResponse -> {
        throw new WebClientUserSaveOrUpdateeFailedException("Exception when trying to update user state")
        .bodyToMono(String.class);
    });
}
</code>```

User payload :

```<code>@Data
@NoArgsConstructor
@AllArgsConstructor
public class UserPayload {
  Long userId;
  ZonedDateTime createdAt;
}
</code>```

User command :

```<code>@Data
@NoArgsConstructor
@AllArgsConstructor
public class UserCommand {
     @JsonProperty("user")
     UserPayload user;
}
</code>```

Json which is waiting for my other app (whom I am sending a request) :

```<code>[
  { "user":
            {
              "userId": 1,
              "createdAt": "2019-05-16T08:24:46.412Z"
            }
  }
]
</code>```

Using : Spring boot 2 , Lombok (for getter/setter) , gradle
When I'm trying to send a request nothing happens. No exception even.
I tried with very simple case as well the same issue.
One more note, is it possible to log body? I mean somehow see final json
I guess I am missing something general.

答:
In Reactor, nothing happens until you subscribe. retrive() does not actually start the request. As you can see in the example, you should use one of the method to convert the ResponseSpec to a Publisher and then eventually subscribe to that publisher.

Depending on how you're using this method, you might be able to let Spring subscribe to the publisher instead. WebFlux supports reactive types in the model which means you can directly return a Mono from your RestController methods, for example.

Body:
Have the following implementation of webclient :

    public <T> WebClient.ResponseSpec sendRequest(HttpMethod method, String contentType, T body, String baseUrl, String path) {
    try {
        WebClient webClient = WebClient.builder().baseUrl(baseUrl).filter(logRequest()).build();
        WebClient.ResponseSpec responseSpec = webClient.method(method)
                .uri(path)
                .header(HttpHeaders.CONTENT_TYPE, contentType)
                .body(BodyInserters.fromObject(body))
                .retrieve();
        return responseSpec;
    } catch (Exception e) {
        throw new WebClientProcessingException("Exception when trying to execute request", e);

    }
}

// This method returns filter function which will log request data
private static ExchangeFilterFunction logRequest() {
    return ExchangeFilterFunction.ofRequestProcessor(clientRequest -> {
        LOGGER.info("Request: {} {} {}", clientRequest.method(), clientRequest.url(), clientRequest.body());
        clientRequest.headers().forEach((name, values) -> values.forEach(value -> LOGGER.info("{}={}", name, value)));
        return Mono.just(clientRequest);
    });
}

Also have the following code , which is creating user object and command which contains user object , then calling webclient to send an request

@Autowired
private BaseWebClient baseWebClient;
@Override
public void saveOrUpdateUser() {
        UserPayload userPayload = new UserPayload();
        userPayload.setUserId(111L);
        userPayload.setCreatedAt(ZonedDateTime.now(DateTimeProps.systemTimeZone));
        UserCommand userCommand = new UserCommand();
        userCommand.setUser(userPayload);
        baseWebClient.sendRequest(HttpMethod.POST, "application/json",
            Stream.of(userCommand).collect(Collectors.toList()),
            "http://localhost:8080",
            "/users").onStatus(HttpStatus::isError, clientResponse -> {
        throw new WebClientUserSaveOrUpdateeFailedException("Exception when trying to update user state")
        .bodyToMono(String.class);
    });
}

User payload :

@Data
@NoArgsConstructor
@AllArgsConstructor
public class UserPayload {
  Long userId;
  ZonedDateTime createdAt;
}

User command :

@Data
@NoArgsConstructor
@AllArgsConstructor
public class UserCommand {
     @JsonProperty("user")
     UserPayload user;
}

Json which is waiting for my other app (whom I am sending a request) :

[
  { "user":
            {
              "userId": 1,
              "createdAt": "2019-05-16T08:24:46.412Z"
            }
  }
]

Using : Spring boot 2 , Lombok (for getter/setter) , gradle
When I'm trying to send a request nothing happens. No exception even.
I tried with very simple case as well the same issue.
One more note, is it possible to log body? I mean somehow see final json
I guess I am missing something general.


问:
What is the quickest way from a concept to a site?
I've got a bunch of website ideas and I was wondering what is the quickest way to get from a pretty thorough concept definition (idea mind-maps, use-cases, architecture diagrams ) to a working website. The only point is to get to something that's functional, not worrying about performance. The idea is to get something out to showcase a functional site, and after worry about fine-tuning or re-writing parts if necessary.

I am familiar with quite a few web frameworks from open-source and proprietary world, but I could not find so far a swiss-army-knife of web development environments that can get you fast from a concept to a working site.  I was kinda wondering if there is such a thing, free or non-free

Looking forward to your suggestions...

UPDATE: The question might get a bit too metaphoric for the kind readers of this site, but I'm at a moment where I feel that implementation details are killing my creativity ... maybe you'll laugh or you'll feel offended, I'm just wondering if anyone can give me a useful hint..

答:
First, select a dynamic scripting language. Static types and compilation will slow development. PHP is a good choice since you can download a LAMP package like xampp and start immediately.

Next, use a CMS if at all possible. If you require a flexible front end design, then choose a template focused CMS like Expression Engine. If your site can be relatively generic looking, then use something like Drupal.

If you require the flexibility of a framework, how much time can you spend learning it? You'll get up to speed with CodeIgniter or Kohana quickly. Other frameworks can save time with behind-the-scenes magic, but you can lose flexibility and the learning curve is steep expensive.

OwnerDisplayName: Cip

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: rick

LastEditorDisplayName: rick


问:
How can I collapse multiple columns and to generate new variables from the different levels/values that were collapsed?
I have a dataset (df) similar to this one:

```<code>df <- data.frame("ID"=c(1, 1, 1, 2, 2),
                 "Method of payment"=c("cash","liabilities",
                                       "shares", "cash", NA),
                 "USD"=c(110, 130, 200, 100, NA),
                 "var3"=c(1500, NA, NA, "ab", "bc"))
df
#   ID Method.of.payment USD var3
# 1  1              cash 110 1500
# 2  1       liabilities 130 <NA>
# 3  1            shares 200 <NA>
# 4  2              cash 100   ab
# 5  2              <NA>  NA   bc
</code>```

And I would like to have:

```<code>data.frame("ID"=c(1, 2),
           "Method of payment"=c("cash, liabilities, shares", "cash"),
           "Cash"=c(110, 100),
           "Liabilities"=c(130, 0),
           "Shares"=c(200, 0),
           "var3"=c(1500, "ab,bc"))

#   ID         Method.of.payment Cash Liabilities Shares  var3
# 1  1 cash, liabilities, shares  110         130    200  1500
# 2  2                      cash  100           0      0 ab,bc
</code>```

Therefore, I would like to

collapse the variables "method of payment" and "var3" in order to have only one row per ID, having all the levels/values linked to an ID pasted in one row;

generate new variables from existing levels of the factor variable method of payment ("cash", "liabilities", "shares") whose values should be the corresponding values of the variable USD or 0 if there is no corresponding value.

I am working with a very large dataset, so I am looking for something that works also on large data. I hope it is clear.

答:
Here is a solution via data.table that avoids replicating the collapsed fields over multiple rows. Performance bottleneck will be paste:

```<code>library(data.table)

df <- data.table(ID = c(1, 1, 1, 2, 2),
                 Method = c("cash","liabilities", "shares", "cash", NA),
                 USD = c(110, 130, 200, 100, NA),
                 var3 = c(1500, NA, NA, "ab", "bc"))

nice_paste <- function(z) {
  paste(z[!is.na(z)], collapse = ", ")
}

# Compress
part_1 <- df[, .(Method = .(nice_paste(Method)),
                 var3 = .(nice_paste(var3))), by = ID]

# Reshape "Method" to wide
part_2 <- dcast(df[!is.na(Method)],
                ID ~ Method,
                value.var = "USD",
                fill = 0,
                fun.aggregate = sum)

part_1[part_2, on = "ID"]
</code>```

Gives

```<code>   ID                    Method   var3 cash liabilities shares
1:  1 cash, liabilities, shares   1500  110         130    200
2:  2                      cash ab, bc  100           0      0
</code>```

Body:
I have a dataset (df) similar to this one:

df <- data.frame("ID"=c(1, 1, 1, 2, 2),
                 "Method of payment"=c("cash","liabilities",
                                       "shares", "cash", NA),
                 "USD"=c(110, 130, 200, 100, NA),
                 "var3"=c(1500, NA, NA, "ab", "bc"))
df
#   ID Method.of.payment USD var3
# 1  1              cash 110 1500
# 2  1       liabilities 130 <NA>
# 3  1            shares 200 <NA>
# 4  2              cash 100   ab
# 5  2              <NA>  NA   bc

And I would like to have:

data.frame("ID"=c(1, 2),
           "Method of payment"=c("cash, liabilities, shares", "cash"),
           "Cash"=c(110, 100),
           "Liabilities"=c(130, 0),
           "Shares"=c(200, 0),
           "var3"=c(1500, "ab,bc"))

#   ID         Method.of.payment Cash Liabilities Shares  var3
# 1  1 cash, liabilities, shares  110         130    200  1500
# 2  2                      cash  100           0      0 ab,bc

Therefore, I would like to

collapse the variables "method of payment" and "var3" in order to have only one row per ID, having all the levels/values linked to an ID pasted in one row;

generate new variables from existing levels of the factor variable method of payment ("cash", "liabilities", "shares") whose values should be the corresponding values of the variable USD or 0 if there is no corresponding value.

I am working with a very large dataset, so I am looking for something that works also on large data. I hope it is clear.

Body:
Here is a solution via data.table that avoids replicating the collapsed fields over multiple rows. Performance bottleneck will be paste:

library(data.table)

df <- data.table(ID = c(1, 1, 1, 2, 2),
                 Method = c("cash","liabilities", "shares", "cash", NA),
                 USD = c(110, 130, 200, 100, NA),
                 var3 = c(1500, NA, NA, "ab", "bc"))

nice_paste <- function(z) {
  paste(z[!is.na(z)], collapse = ", ")
}

# Compress
part_1 <- df[, .(Method = .(nice_paste(Method)),
                 var3 = .(nice_paste(var3))), by = ID]

# Reshape "Method" to wide
part_2 <- dcast(df[!is.na(Method)],
                ID ~ Method,
                value.var = "USD",
                fill = 0,
                fun.aggregate = sum)

part_1[part_2, on = "ID"]

Gives

   ID                    Method   var3 cash liabilities shares
1:  1 cash, liabilities, shares   1500  110         130    200
2:  2                      cash ab, bc  100           0      0


问:
Call more than one function 'onClick'
Here is my situation:

```<code><button onClick={this.changeTimerStatus.bind(this)}>makeTimerCliccable</button>

<button onClick={this.state.hasBeenFinished ? this.confirmHandler : (this.state.hasDest == false || this.state.hasDest == undefined ? this.takeTaskHandler : this.finishHandler)}>
</code>```

I have two buttons, but I'd like to have just the second one. Also, I'd like to execute this.changeTimerStatus.bind(this) (the function on the first button) together with this.confirmHandler or this.takeTaskHandler when they're running. How can I solve this?

答:
The answer that is accepted here will work, but that is not a good practice to use any logic inside your markup (in this case jsx). I would suggest to create one handler,</p>

```<code>class YourComponent extends React.Component {
    state = {
        // Whatever you store in the state
    };

    constructor(props) {
        super(props);

        this.clickHandler = this.clickHandler.bind(this);
    }

    clickHandler() {
        // this.state
        // ...logic can go here
        // it should be the same logic as it is in the accepted answer
    }

    render() {
         return (
              <button type="button" onClick={ this.clickHandler }>
                  BUTTON
              </button>
         );
    }
}
</code>```

Title: Call more than one function 'onClick'

Body:
Here is my situation:

<button onClick={this.changeTimerStatus.bind(this)}>makeTimerCliccable</button>

<button onClick={this.state.hasBeenFinished ? this.confirmHandler : (this.state.hasDest == false || this.state.hasDest == undefined ? this.takeTaskHandler : this.finishHandler)}>

I have two buttons, but I'd like to have just the second one. Also, I'd like to execute this.changeTimerStatus.bind(this) (the function on the first button) together with this.confirmHandler or this.takeTaskHandler when they're running. How can I solve this?

Body:
The answer that is accepted here will work, but that is not a good practice to use any logic inside your markup (in this case jsx). I would suggest to create one handler,

class YourComponent extends React.Component {
    state = {
        // Whatever you store in the state
    };

    constructor(props) {
        super(props);

        this.clickHandler = this.clickHandler.bind(this);
    }

    clickHandler() {
        // this.state
        // ...logic can go here
        // it should be the same logic as it is in the accepted answer
    }

    render() {
         return (
              <button type="button" onClick={ this.clickHandler }>
                  BUTTON
              </button>
         );
    }
}


问:
Convert Graphql to SQL?
We have existing SQL Server database and we are using C#. Lets say our mobile client send a graphql to server. How can I convert this SQL, so that my client get the data what he expect?</p>

答:
The most mature open source implementation I've found for doing this is https://join-monster.readthedocs.io/en/latest/

What Is It?
  Join Monster is a query planner between GraphQL and SQL for the Node.js graphql-js reference implementation. It's a function that takes a GraphQL query and dynamically translates GraphQL to SQL for efficient, batched data retrieval before resolution. It fetches only the data you need - nothing more, nothing less.

Why?
  It solves the problem of making too many database queries, i.e. the "round-trip" problem or "N+1" problem, where the round-trips are requests for data over the TCP/IP stack between your API server and your SQL database. Think of it as an alternative to Facebook's DataLoader, but with more specificity toward SQL, making it more powerful and simpler to use with SQL.

It is NOT a tool for automatically creating a schema for your GraphQL from your database or vice versa. You retain the freedom and power to define your schemas how you want. Join Monster simply "compiles" a GraphQL query to a SQL query based on the existing schemas. It fits into existing applications and can be seamlessly removed later or used to varying degree. It is a little opinionated, but not a full ORM.

It looks exactly like what you're looking for.

Also, https://github.com/graphile/postgraphile (which is mentioned as an answer here) is another possibility. It basically bring GraphQL capabilities to a Postgre DB.

Both solutions may fit your needs.

Title: Convert Graphql to SQL?


问:
Redis server refused to connect while using docker image
i am using docker to start using postgres, kibana, elasticsearch and redis.(using docker-compose up command). However redis failed to start  giving this error.

You can see read the last error line in the screenshot(showing bad file format). How can i resolve this?
Also i dont know how to run redis commands in terminal using docker such as ./redis-check-aof --fix  as given in screenshot?

答:
Like Uku mentions, the AOF file has become corrupted and you should run a command to fix it. The correct command for the official Redis redis:4.0.11-alpine image is:

```<code>docker-compose run redis redis-check-aof --fix appendonly.aof
</code>```

This assumes the name of your redis container is "redis". Hit "y" to confirm (it's not phrased like a question but it needs that input.

Body:
Like Uku mentions, the AOF file has become corrupted and you should run a command to fix it. The correct command for the official Redis redis:4.0.11-alpine image is:

docker-compose run redis redis-check-aof --fix appendonly.aof

This assumes the name of your redis container is "redis". Hit "y" to confirm (it's not phrased like a question but it needs that input.


问:
Accessing a single field in a foreach using Linq Dapper
I am using dapper and I want to use Linq to be able to update a single field called status in one table I am trying to use.

```<code>public async Task<Int32> ProcessUnprocessedTransactions(IEnumerable<BomComponentData> items)
{
    IEnumerable<BomComponentData> _itemstoBeProcesed = items.Where(w => w.Status == (int)BomStatus.Scanned);

    foreach (BomComponentData item in _itemstoBeProcesed)
    {
        item.Status = (int)BomStatus.Completed;
    }

    return await database.UpdateAsync(_itemstoBeProcesed);
}
</code>```

My class is as follows:

```<code>public class BomComponentData
{
    public int Sequence { get; set; }

    public string BOMShortName { get; set; }
    public string OperationName { get; set; }
    public long BomId { get; set; }
    public long BOMLineID { get; set; }
    public long StockItemID { get; set; }
    public string BomLineType { get; set; }
    public int Quantity { get; set; }
    public long UnitID { get; set; }
    public decimal? MultipleOfBaseUnit { get; set; }
    public string Code { get; set; }
    public string Name { get; set; }
    public string Barcode { get; set; }
    public long ProductGroupID { get; set; }
    public string ProductGroupCode { get; set; }
    public int Status { get; set; }

    public int BinLocation { get; set; }
    public string BinName { get; set; }

    public string UOM { get; set; }
    public int CalculatedValue { get; set; }
    public int BomPickedCount { get; set; }

    public int TotalLeftTopick
    {
        get { return Quantity - BomPickedCount; }
    }

    public enum BomStatus
    {
        Listed=1,
        Scanned=2,
        Confirmed=3,
        Processed=4,
        Completed=4,
        InVisible=5
    }

    public override string ToString()
    {
        return Code;
    }
}
</code>```

But it does not work if I use a foreach like above. I am sure it should update the items properly but I think that because I'm going through singular items in my foreach and my list in the update it's not updating correct.

All I want to do is mark the items as completed and ready for transfer, I am doing so by the status column and an int enum.

Maybe I am missing a declaration of what is my primary key?

Edit 2

When I use a key declaration of the primary key I get the following:

Unhandled Exception: System.AggregateException: One or more errors occurred. (Constraint

Edit 3

I have set key of my class but as you see I have auotincrement on my db and it still crashes. How should insert be handled?

Edit 4

For example I am inserting into the database as follows. Shouldn't this work?

```<code>List<BomComponentData> _bomList = new List<BomComponentData>();
_bomList.Add(new BomComponentData { Sequence = 1, Barcode = "0000000001498", BinLocation = 23, BinName = "A", BOMShortName = "GYNE-TXX", OperationName = "Example Product", Code = "TB9175CEA", Name = "Tiburon Peri/Gynae Pack-10", Quantity = 1, UOM = "Each" });

await database.InsertAllAsync(_bomList,true);
</code>```

I have placed the tag key for the update that works ok but when I attempt to do an insert with the key it doesn't it says constraint error but the update works. Does anybody no how i can solve both the insert and update in Dapper contrib.

答:
You are using Dapper.Contrib and this extension requires that you decorate your class with some attributes to help in the automatic handling of your data.

In particular for an Update method you need to define the Table attribute and the Key attribute to identify the primary key

```<code>[Table ("BomComps")]
public class BomComponentData
{
   // [ExplictKey]
   [Key]
   public int Sequence { get; set; }
   ....
</code>```

Here, for example, I have added the attribute Table to set a possible table name on the database, but if the name of the physical table matches the name of the class then you can omit the attribute. Also I have added the Key attribute to set the property that contains the primary key of your table (so the statement that updates your records could be formed with the proper WHERE condition).

Notice that the Key attribute should be used if the column has an Identity property set to yes while, if not, you use the ExplicitKey attribute to signal that the primary key is defined by your code.

Body:
I am using dapper and I want to use Linq to be able to update a single field called status in one table I am trying to use.

public async Task<Int32> ProcessUnprocessedTransactions(IEnumerable<BomComponentData> items)
{
    IEnumerable<BomComponentData> _itemstoBeProcesed = items.Where(w => w.Status == (int)BomStatus.Scanned);

    foreach (BomComponentData item in _itemstoBeProcesed)
    {
        item.Status = (int)BomStatus.Completed;
    }

    return await database.UpdateAsync(_itemstoBeProcesed);
}

My class is as follows:

public class BomComponentData
{
    public int Sequence { get; set; }

    public string BOMShortName { get; set; }
    public string OperationName { get; set; }
    public long BomId { get; set; }
    public long BOMLineID { get; set; }
    public long StockItemID { get; set; }
    public string BomLineType { get; set; }
    public int Quantity { get; set; }
    public long UnitID { get; set; }
    public decimal? MultipleOfBaseUnit { get; set; }
    public string Code { get; set; }
    public string Name { get; set; }
    public string Barcode { get; set; }
    public long ProductGroupID { get; set; }
    public string ProductGroupCode { get; set; }
    public int Status { get; set; }

    public int BinLocation { get; set; }
    public string BinName { get; set; }

    public string UOM { get; set; }
    public int CalculatedValue { get; set; }
    public int BomPickedCount { get; set; }

    public int TotalLeftTopick
    {
        get { return Quantity - BomPickedCount; }
    }

    public enum BomStatus
    {
        Listed=1,
        Scanned=2,
        Confirmed=3,
        Processed=4,
        Completed=4,
        InVisible=5
    }

    public override string ToString()
    {
        return Code;
    }
}

But it does not work if I use a foreach like above. I am sure it should update the items properly but I think that because I'm going through singular items in my foreach and my list in the update it's not updating correct.

All I want to do is mark the items as completed and ready for transfer, I am doing so by the status column and an int enum.

Maybe I am missing a declaration of what is my primary key?

Edit 2

When I use a key declaration of the primary key I get the following:

Unhandled Exception: System.AggregateException: One or more errors occurred. (Constraint

Edit 3

I have set key of my class but as you see I have auotincrement on my db and it still crashes. How should insert be handled?

Edit 4

For example I am inserting into the database as follows. Shouldn't this work?

List<BomComponentData> _bomList = new List<BomComponentData>();
_bomList.Add(new BomComponentData { Sequence = 1, Barcode = "0000000001498", BinLocation = 23, BinName = "A", BOMShortName = "GYNE-TXX", OperationName = "Example Product", Code = "TB9175CEA", Name = "Tiburon Peri/Gynae Pack-10", Quantity = 1, UOM = "Each" });

await database.InsertAllAsync(_bomList,true);

I have placed the tag key for the update that works ok but when I attempt to do an insert with the key it doesn't it says constraint error but the update works. Does anybody no how i can solve both the insert and update in Dapper contrib.

Body:
You are using Dapper.Contrib and this extension requires that you decorate your class with some attributes to help in the automatic handling of your data.

In particular for an Update method you need to define the Table attribute and the Key attribute to identify the primary key

[Table ("BomComps")]
public class BomComponentData
{
   // [ExplictKey]
   [Key]
   public int Sequence { get; set; }
   ....

Here, for example, I have added the attribute Table to set a possible table name on the database, but if the name of the physical table matches the name of the class then you can omit the attribute. Also I have added the Key attribute to set the property that contains the primary key of your table (so the statement that updates your records could be formed with the proper WHERE condition).

Notice that the Key attribute should be used if the column has an Identity property set to yes while, if not, you use the ExplicitKey attribute to signal that the primary key is defined by your code.


问:
Toggle DIV when Radio Buttons are checked
I am trying to make a DIV toggle visible and not visible when a group of radio buttons say yes or no.

For example I have a a list of stores in a DIV but I only want that list of stores visible when the radio button is checked as yes.

Edit Script View

```<code><div id="script_form_wrapper">
    <%= form_for(:script, :url => {:action => 'update', :id =>@script.id}) do |f| %>
        <div id="script_form_visibility">
            <div class="issue_section_header" align="center">Visibility</div>
            <div class="line-break"></div>
            <div class="standardText"><span class="boldText">All Stores:</span>
                <%=f.radio_button(:all_stores, true)%> Yes
                <%=f.radio_button(:all_stores, false)%> No
            </div>
            <br/>
            <div id="script_stores">
                <div class="issue_section_header" align="center">Stores</div>
                <div class="line-break"></div>
                <div class="standardText">
                    <%@stores.each do |store|%>
                        <%= check_box_tag 'script[store_ids][]', store.id, @script.store_ids.include?(store.id), :id => dom_id(store) %>
                        <%= label_tag dom_id(store), store.name, :class => "check_box_label" %><br/>
                    <%end%>
                </div>
            </div>
        </div>
        <div id="script_form">
            <div class="boldText"><%= f.label :name %></div>
            <div><%=f.text_field :name, :size => '94', :maxlength => '70'%></div>
            <div>
                <table width="100%" cellspacing="0">
                    <tr>
                        <td class="boldText"><%= f.label :category_id, "Category" %></td>
                        <td class="boldText" align="right">Show ID Required Field</td>
                    </tr>
                    <tr>
                        <td class="standardText"><%=f.select(:category_id, @categories.collect {|c| [c.name, c.id]}, :selected => session[:admin_category])%></td>
                        <td class="standardText" align="right"><%=f.radio_button(:require_id, true)%> Yes <%=f.radio_button(:require_id, false)%> No</td>
                    </tr>
                </table>
            </div>
            <div class="boldText"><%= f.label :task %></div>
            <div><%= f.text_area(:task, :size => "68x20") %></div>
            <div class="boldText"><%= f.label :expected_results, "Expected Results" %></div>
            <div><%= f.text_area(:expected_results, :size => "68x20") %></div>
            <div align="center"><%= f.submit "Update Script" %></div>
        </div>
    <% end %>
</div>
</code>```

Sad Attempt of Javascript

```<code><script type="text/javascript">
$(function() {
    $("[name=script[all_stores]]").click(function(){
            $('#script_stores').hide();
            $("#script_all_stores_"+$(this).val()).show('slow');
    });
 });
</script>
</code>```

Rendered HTML Source

```<code><div class="standardText"><span class="boldText">All Stores:</span>
                <input id="script_all_stores_true" name="script[all_stores]" type="radio" value="true" /> Yes
                <input checked="checked" id="script_all_stores_false" name="script[all_stores]" type="radio" value="false" /> No
            </div>
</code>```

Solution

```<code><script type="text/javascript">
$(function() {
    if($("#script_all_stores_false").is(":checked")){
       $('#script_stores').show();
         }else{
       $('#script_stores').hide();
         }
    $("input[name='script[all_stores]']").change(function(){
        if($("#script_all_stores_false").is(":checked")){
           $('#script_stores').show();
             }else{
           $('#script_stores').hide();
             }
    });
});
</script>
</code>```

Thank you for you help!!!

答:
```<code>  $("[name=script[all_stores]]").change(function(){
        $('#script_stores').toggle();
  });
</code>```

or

```<code>      $("[name=script[all_stores]]").change(function(){
         if($(this).is(":checked")){
           $('#script_stores').show();
         }else {
           $('#script_stores').hide();
         }

      });
</code>```

Body:
I am trying to make a DIV toggle visible and not visible when a group of radio buttons say yes or no.

For example I have a a list of stores in a DIV but I only want that list of stores visible when the radio button is checked as yes.

Edit Script View

    <%= form_for(:script, :url => {:action => 'update', :id =>@script.id}) do |f| %>

Visibility

All Stores:
                <%=f.radio_button(:all_stores, true)%> Yes
                <%=f.radio_button(:all_stores, false)%> No

Stores

                    <%@stores.each do |store|%>
                        <%= check_box_tag 'script[store_ids][]', store.id, @script.store_ids.include?(store.id), :id => dom_id(store) %>
                        <%= label_tag dom_id(store), store.name, :class => "check_box_label" %>

                    <%end%>

<%= f.label :name %>

<%=f.text_field :name, :size => '94', :maxlength => '70'%>

                        <%= f.label :category_id, "Category" %>
                        Show ID Required Field

                        <%=f.select(:category_id, @categories.collect {|c| [c.name, c.id]}, :selected => session[:admin_category])%>
                        <%=f.radio_button(:require_id, true)%> Yes <%=f.radio_button(:require_id, false)%> No

<%= f.label :task %>

<%= f.text_area(:task, :size => "68x20") %>

<%= f.label :expected_results, "Expected Results" %>

<%= f.text_area(:expected_results, :size => "68x20") %>

<%= f.submit "Update Script" %>

    <% end %>

Sad Attempt of Javascript

Rendered HTML Source

All Stores:
                <input id="script_all_stores_true" name="script[all_stores]" type="radio" value="true" /> Yes
                <input checked="checked" id="script_all_stores_false" name="script[all_stores]" type="radio" value="false" /> No

Solution

Thank you for you help!!!

Body:
  $("[name=script[all_stores]]").change(function(){
        $('#script_stores').toggle();
  });

or

      $("[name=script[all_stores]]").change(function(){
         if($(this).is(":checked")){
           $('#script_stores').show();
         }else {
           $('#script_stores').hide();
         }

      });


问:
Why is there an error comming up, that says a variable is undefined. (Unity)
I want to have an indicator of how fast you are moving as a UI element. however, I get an error that states: Cannot use local variable 'lastPosition' before it is declared. The declaration of the local variable hides the field 'scoreScript.lastPosition'.

Ive tried many different ways, getting a lot of errors (as i am pretty new to the unity coding language) and this one made the most sense to me, sadly there is still this one error.

```<code>Text shownScore;
public GameObject player;
Vector3 lastPosition;

// Start is called before the first frame update
void Start()
{
    lastPosition = player.transform.position;
    shownScore = GetComponent<Text>();
}

// Update is called once per frame
void Update()
{
    Vector3 offset =  player.transform.position - lastPosition;
    shownScore.text = offset.sqrMagnitude.ToString("#.00");
    Vector3 lastPosition = player.transform.position;
}
</code>```

答:
By using:

```<code>Vector3 lastPosition = player.transform.position;
</code>```

you are declaring a new local variable named lastPosition. This local variable overrides the lastPosition in your scoreScript and you'll get an error message when using it. Instead just use the same lastPosition:

```<code>lastPosition = player.transform.position;
</code>```

Body:
I want to have an indicator of how fast you are moving as a UI element. however, I get an error that states: Cannot use local variable 'lastPosition' before it is declared. The declaration of the local variable hides the field 'scoreScript.lastPosition'.

Ive tried many different ways, getting a lot of errors (as i am pretty new to the unity coding language) and this one made the most sense to me, sadly there is still this one error.

Text shownScore;
public GameObject player;
Vector3 lastPosition;

// Start is called before the first frame update
void Start()
{
    lastPosition = player.transform.position;
    shownScore = GetComponent<Text>();
}

// Update is called once per frame
void Update()
{
    Vector3 offset =  player.transform.position - lastPosition;
    shownScore.text = offset.sqrMagnitude.ToString("#.00");
    Vector3 lastPosition = player.transform.position;
}

Body:
By using:

Vector3 lastPosition = player.transform.position;

you are declaring a new local variable named lastPosition. This local variable overrides the lastPosition in your scoreScript and you'll get an error message when using it. Instead just use the same lastPosition:

lastPosition = player.transform.position;


问:
Convert from lowercase to uppercase all values in all character variables in dataframe
I have a mixed dataframe of character and numeric variables.

```<code>city,hs_cd,sl_no,col_01,col_02,col_03
Austin,1,2,,46,Female
Austin,1,3,,32,Male
Austin,1,4,,27,Male
Austin,1,5,,20,Female
Austin,2,2,,42,Female
Austin,2,1,,52,Male
Austin,2,3,,25,Male
Austin,2,4,,22,Female
Austin,3,3,,30,Female
Austin,3,1,,65,Female
</code>```

I want to convert all the lower-case characters in the dataframe to uppercase. Is there any way to do this in one shot without doing it repeatedly over each character-variable?

答:
Another alternative is to use a combination of mutate_if() and str_to_upper() function, both from the tidyverse package:

```<code>df %>% mutate_if(is.character, str_to_upper) -> df
</code>```

This will convert all string variables in the data frame to upper case.
str_to_lower() do the opposite.

Body:
I have a mixed dataframe of character and numeric variables.

city,hs_cd,sl_no,col_01,col_02,col_03
Austin,1,2,,46,Female
Austin,1,3,,32,Male
Austin,1,4,,27,Male
Austin,1,5,,20,Female
Austin,2,2,,42,Female
Austin,2,1,,52,Male
Austin,2,3,,25,Male
Austin,2,4,,22,Female
Austin,3,3,,30,Female
Austin,3,1,,65,Female

I want to convert all the lower-case characters in the dataframe to uppercase. Is there any way to do this in one shot without doing it repeatedly over each character-variable?

Body:
Another alternative is to use a combination of mutate_if() and str_to_upper() function, both from the tidyverse package:

df %>% mutate_if(is.character, str_to_upper) -> df

This will convert all string variables in the data frame to upper case.
str_to_lower() do the opposite.


问:
nAnt and nAntContrib
I'm having problems building the nAntContrib library using the instructions provided. When running the build I get the following feedback

```<code>C:\Code\trunk\tools\nAnt-Contrib>..\nant\nant-0.90\bin\nant.exe -D:nant.dir=C:\c
ode\trunk\tools\nAnt\nant-0.90 -f:NantContrib.build
NAnt 0.90 (Build 0.90.3780.0; release; 5/8/2010)
Copyright (C) 2001-2010 Gerry Shaw
http://nant.sourceforge.net

Buildfile: file:///C:/Code/trunk/tools/nAnt-Contrib/NantContrib.build
Target framework: Microsoft .NET Framework 2.0
Target(s) specified: test

  [include] C:\Code\trunk\tools\nAnt-Contrib\NantContrib.build(3,6):
  [include] Build file 'C:\Code\trunk\tools\properties.xml' does not exist.

init:

debug:

Built-in property 'nant.project.basedir' is deprecated. Use the project::get-bas
e-directory() function instead.

set-runtime-configuration:

C:\Code\trunk\tools\nAnt-Contrib\NantContrib.build(331,10): Task <ifnot> is depr
ecated.  Use the <if> task instead.
    [ifnot] C:\Code\trunk\tools\nAnt-Contrib\NantContrib.build(331,10): Attribut
e 'propertyexists' for <ifnot ... /> is deprecated.  Use <if test="${property::e
xists('propertyname')}"> instead.
C:\Code\trunk\tools\nAnt-Contrib\NantContrib.build(332,14): Task <ifnot> is depr
ecated.  Use the <if> task instead.
    [ifnot] C:\Code\trunk\tools\nAnt-Contrib\NantContrib.build(332,14): Attribut
e 'propertyexists' for <ifnot ... /> is deprecated.  Use <if test="${property::e
xists('propertyname')}"> instead.
C:\Code\trunk\tools\nAnt-Contrib\NantContrib.build(335,14): Task <ifnot> is depr
ecated.  Use the <if> task instead.
    [ifnot] C:\Code\trunk\tools\nAnt-Contrib\NantContrib.build(335,14): Attribut
e 'targetexists' for <ifnot ... /> is deprecated.  Use <if test="${target::exist
s('targetname')}"> instead.

BUILD FAILED - 1 non-fatal error(s), 7 warning(s)

C:\Code\trunk\tools\nAnt-Contrib\NantContrib.build(336,18):
No runtime configuration was specified and the current runtime (net-2.0) is not
supported by NAnt.

Total time: 0.3 seconds.
</code>```

I am running 32bit Windows 7 OS. If I try and use the dll that is included in the zip I get the following error.

```<code>C:\Code\trunk\build>call ..\tools\nant\nant-0.90\bin\nant.exe /f:build-database.
xml.build
NAnt 0.90 (Build 0.90.3780.0; release; 5/8/2010)
Copyright (C) 2001-2010 Gerry Shaw
http://nant.sourceforge.net

[loadtasks] Failure scanning "C:\Code\trunk\tools\nant\nant-0.90\bin\extensions\
common\2.0\CollectionGen.dll" for extensions. Could not load file or assembly 'M
icrosoft.VSDesigner, Version=7.0.3300.0, Culture=neutral, PublicKeyToken=b03f5f7
f11d50a3a' or one of its dependencies. The system cannot find the file specified
.
[loadtasks] Failure scanning "C:\Code\trunk\tools\nant\nant-0.90\bin\extensions\
common\2.0\NAnt.Contrib.Tasks.dll" for extensions. Unable to load one or more of
 the requested types. Retrieve the LoaderExceptions property for more informatio
n.
Buildfile: file:///C:/Code/trunk/build/build-database.xml.build
Target framework: Microsoft .NET Framework 2.0
Target(s) specified: go

 [property] Target framework changed to "Microsoft .NET Framework 3.5".

go:

     [echo] Building!

BUILD SUCCEEDED

Total time: 0.1 seconds.
</code>```

I am guessing there is a dependency missing ('Microsoft.VSDesigner') but was hoping the build script provided could shed some light on the problem.

Thanks in advance

答: Try using the latest versions (NAnt 0.91-alpha2 and NAntConrib 0.85).</p>

Title: nAnt and nAntContrib

Body:
I'm having problems building the nAntContrib library using the instructions provided. When running the build I get the following feedback

C:\Code\trunk\tools\nAnt-Contrib>..\nant\nant-0.90\bin\nant.exe -D:nant.dir=C:\c
ode\trunk\tools\nAnt\nant-0.90 -f:NantContrib.build
NAnt 0.90 (Build 0.90.3780.0; release; 5/8/2010)
Copyright (C) 2001-2010 Gerry Shaw
http://nant.sourceforge.net

Buildfile: file:///C:/Code/trunk/tools/nAnt-Contrib/NantContrib.build
Target framework: Microsoft .NET Framework 2.0
Target(s) specified: test

  [include] C:\Code\trunk\tools\nAnt-Contrib\NantContrib.build(3,6):
  [include] Build file 'C:\Code\trunk\tools\properties.xml' does not exist.

init:

debug:

Built-in property 'nant.project.basedir' is deprecated. Use the project::get-bas
e-directory() function instead.

set-runtime-configuration:

C:\Code\trunk\tools\nAnt-Contrib\NantContrib.build(331,10): Task <ifnot> is depr
ecated.  Use the <if> task instead.
    [ifnot] C:\Code\trunk\tools\nAnt-Contrib\NantContrib.build(331,10): Attribut
e 'propertyexists' for <ifnot ... /> is deprecated.  Use <if test="${property::e
xists('propertyname')}"> instead.
C:\Code\trunk\tools\nAnt-Contrib\NantContrib.build(332,14): Task <ifnot> is depr
ecated.  Use the <if> task instead.
    [ifnot] C:\Code\trunk\tools\nAnt-Contrib\NantContrib.build(332,14): Attribut
e 'propertyexists' for <ifnot ... /> is deprecated.  Use <if test="${property::e
xists('propertyname')}"> instead.
C:\Code\trunk\tools\nAnt-Contrib\NantContrib.build(335,14): Task <ifnot> is depr
ecated.  Use the <if> task instead.
    [ifnot] C:\Code\trunk\tools\nAnt-Contrib\NantContrib.build(335,14): Attribut
e 'targetexists' for <ifnot ... /> is deprecated.  Use <if test="${target::exist
s('targetname')}"> instead.

BUILD FAILED - 1 non-fatal error(s), 7 warning(s)

C:\Code\trunk\tools\nAnt-Contrib\NantContrib.build(336,18):
No runtime configuration was specified and the current runtime (net-2.0) is not
supported by NAnt.

Total time: 0.3 seconds.

I am running 32bit Windows 7 OS. If I try and use the dll that is included in the zip I get the following error.

C:\Code\trunk\build>call ..\tools\nant\nant-0.90\bin\nant.exe /f:build-database.
xml.build
NAnt 0.90 (Build 0.90.3780.0; release; 5/8/2010)
Copyright (C) 2001-2010 Gerry Shaw
http://nant.sourceforge.net

[loadtasks] Failure scanning "C:\Code\trunk\tools\nant\nant-0.90\bin\extensions\
common\2.0\CollectionGen.dll" for extensions. Could not load file or assembly 'M
icrosoft.VSDesigner, Version=7.0.3300.0, Culture=neutral, PublicKeyToken=b03f5f7
f11d50a3a' or one of its dependencies. The system cannot find the file specified
.
[loadtasks] Failure scanning "C:\Code\trunk\tools\nant\nant-0.90\bin\extensions\
common\2.0\NAnt.Contrib.Tasks.dll" for extensions. Unable to load one or more of
 the requested types. Retrieve the LoaderExceptions property for more informatio
n.
Buildfile: file:///C:/Code/trunk/build/build-database.xml.build
Target framework: Microsoft .NET Framework 2.0
Target(s) specified: go

 [property] Target framework changed to "Microsoft .NET Framework 3.5".

go:

     [echo] Building!

BUILD SUCCEEDED

Total time: 0.1 seconds.

I am guessing there is a dependency missing ('Microsoft.VSDesigner') but was hoping the build script provided could shed some light on the problem.

Thanks in advance


问:
Automation of different parts of a framework
I have a software framework consisting of multiple components which need to run sequentially. For example, I have a Python script which parses data, another Python script which POSTs the data through a REST API and persists it into a DB, and a Java program which retrieves the parsed data from the DB and performs some analysis on it. So one output is linked to the input of the other component.

I want to know how I can automate these tasks to run one after the other sequentially on a Windows platform. Is PowerShell a good tool to achieve this sort of sequential execution of programs with inter-related input/output flow?

If PowerShell is a suitable choice, it would be great if someone could give me an example of how to achieve this sort of sequential application execution. I have never used PowerShell before and the tutorials I looked up on PowerShell didn't specifically mention this sort of task.

答:
So what I gather is you need to pass data after each script is run to the next script

So we can do that using RedirectStandardOutput from ProcessStartInfo and StandardOutput.ReadToEnd() from Process

```<code>function Run-Process($Location, $Arguments = $Null){
    $info = New-Object System.Diagnostics.ProcessStartInfo
    $info.FileName = $Location
    $info.Arguments = $Arguments
    $info.RedirectStandardOutput = $True
    $info.UseShellExecute = $false
    $info.WindowStyle = [System.Diagnostics.ProcessWindowStyle]::Hidden

    $proc = New-Object System.Diagnostics.Process
    $proc.StartInfo = $info
    $proc.Start() | Out-Null
    $proc.WaitForExit()
    return $proc.StandardOutput.ReadToEnd()
}

$Data = Run-Process Parser.py -Arguments "<filepath>"

$Data = Run-Process POSTClient.py -Arguments $Data

Run-Process Analysis.java -Arguments $Data
</code>```

Body:
So what I gather is you need to pass data after each script is run to the next script

So we can do that using RedirectStandardOutput from ProcessStartInfo and StandardOutput.ReadToEnd() from Process

function Run-Process($Location, $Arguments = $Null){
    $info = New-Object System.Diagnostics.ProcessStartInfo
    $info.FileName = $Location
    $info.Arguments = $Arguments
    $info.RedirectStandardOutput = $True
    $info.UseShellExecute = $false
    $info.WindowStyle = [System.Diagnostics.ProcessWindowStyle]::Hidden

    $proc = New-Object System.Diagnostics.Process
    $proc.StartInfo = $info
    $proc.Start() | Out-Null
    $proc.WaitForExit()
    return $proc.StandardOutput.ReadToEnd()
}

$Data = Run-Process Parser.py -Arguments "<filepath>"

$Data = Run-Process POSTClient.py -Arguments $Data

Run-Process Analysis.java -Arguments $Data


问:
RegEx for capturing scientific citations
I am trying to capture brackets of text that have at least one digit in them (think citations). This is my regex now, and it works fine: https://regex101.com/r/oOHPvO/5

```<code>\((?=.*\d).+?\)
</code>```

So I wanted it to capture (Author 2000) and (2000) but not (Author).

I am trying to use python to capture all these brackets, but in python it also captures the text in the brackets even if they don't have digits.

```<code>import re

with open('text.txt') as f:
    f = f.read()

s = "\((?=.*\d).*?\)"

citations = re.findall(s, f)

citations = list(set(citations))

for c in citations:
    print (c)
</code>```

Any ideas what I am doing wrong?

答:
The most reliable way to possibly handle this expression might be to add boundaries as your expression would likely grow. For example, we could try creating char lists, where we wish to collect our desired data:

```<code>(?=\().([a-z]+)([\s,;]+?)([0-9]+)(?=\)).
</code>```

DEMO

Test

```<code># coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r"(?=\().([a-z]+)([\s,;]+?)([0-9]+)(?=\))."

test_str = "some text we wish before (Author) some text we wish after (Author 2000) some text we wish before (Author) some text we wish after (Author, 2000) some text we wish before (Author) some text we wish after (Author 2000) some text we wish before (Author) some text we wish after (Author; 2000)"

matches = re.finditer(regex, test_str, re.MULTILINE | re.IGNORECASE)

for matchNum, match in enumerate(matches, start=1):

    print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))

    for groupNum in range(0, len(match.groups())):
        groupNum = groupNum + 1

        print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.
</code>```

Demo

const regex = /(?=\().([a-z]+)([\s,;]+?)([0-9]+)(?=\))./mgi;
const str = `some text we wish before (Author) some text we wish after (Author 2000) some text we wish before (Author) some text we wish after (Author, 2000) some text we wish before (Author) some text we wish after (Author 2000) some text we wish before (Author) some text we wish after (Author; 2000)`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }

    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}```

RegEx Circuit

jex.im visualizes regular expressions:

Body:
I am trying to capture brackets of text that have at least one digit in them (think citations). This is my regex now, and it works fine: https://regex101.com/r/oOHPvO/5

\((?=.*\d).+?\)

So I wanted it to capture (Author 2000) and (2000) but not (Author).

I am trying to use python to capture all these brackets, but in python it also captures the text in the brackets even if they don't have digits.

import re

with open('text.txt') as f:
    f = f.read()

s = "\((?=.*\d).*?\)"

citations = re.findall(s, f)

citations = list(set(citations))

for c in citations:
    print (c)

Any ideas what I am doing wrong?

Body:
The most reliable way to possibly handle this expression might be to add boundaries as your expression would likely grow. For example, we could try creating char lists, where we wish to collect our desired data:

(?=\().([a-z]+)([\s,;]+?)([0-9]+)(?=\)).

DEMO

Test

# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r"(?=\().([a-z]+)([\s,;]+?)([0-9]+)(?=\))."

test_str = "some text we wish before (Author) some text we wish after (Author 2000) some text we wish before (Author) some text we wish after (Author, 2000) some text we wish before (Author) some text we wish after (Author 2000) some text we wish before (Author) some text we wish after (Author; 2000)"

matches = re.finditer(regex, test_str, re.MULTILINE | re.IGNORECASE)

for matchNum, match in enumerate(matches, start=1):

    print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))

    for groupNum in range(0, len(match.groups())):
        groupNum = groupNum + 1

        print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.

Demo

const regex = /(?=\().([a-z]+)([\s,;]+?)([0-9]+)(?=\))./mgi;
const str = `some text we wish before (Author) some text we wish after (Author 2000) some text we wish before (Author) some text we wish after (Author, 2000) some text we wish before (Author) some text we wish after (Author 2000) some text we wish before (Author) some text we wish after (Author; 2000)`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }

    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}

RegEx Circuit

jex.im visualizes regular expressions:


问:
'adb' is not recognized as an internal or external command, operable program or batch file
I am trying to run google map v2 on emulator, I am following this tutorial.
When I was trying to install required apk file on emulator, I am getting below error.

I tried to solve this using this tutorial.Followed all steps, added the path to paltform-tools to  environment path. Also after modifying the PATH variable started a new CommandPrompt window.

But getting the same error. I need to check my google map application on emulator.
Kindly suggest me.

```<code>'adb' is not recognized as an internal or external command,
operable program or batch file.
</code>```

答:
If your OS is Windows, then it is very simple.
When you install Android Studio, adb.exe is located in the following folder:

```<code>C:\Users\**your-user-name**\AppData\Local\Android\Sdk\platform-tools
</code>```

Copy the path and paste in your environment variables.

Open your terminal and type: adb it's done!

Body:
I am trying to run google map v2 on emulator, I am following this tutorial.
When I was trying to install required apk file on emulator, I am getting below error.

I tried to solve this using this tutorial.Followed all steps, added the path to paltform-tools to  environment path. Also after modifying the PATH variable started a new CommandPrompt window.

But getting the same error. I need to check my google map application on emulator.
Kindly suggest me.

'adb' is not recognized as an internal or external command,
operable program or batch file.

Body:
If your OS is Windows, then it is very simple.
When you install Android Studio, adb.exe is located in the following folder:

C:\Users\**your-user-name**\AppData\Local\Android\Sdk\platform-tools

Copy the path and paste in your environment variables.

Open your terminal and type: adb it's done!


问:
ReactJs and NodeJs JSON parser issue. app.use(bodyParser.json) seems not working
I'm a beginner of ReactJs, NodeJs, express, etc and all the Javascript things. I'm trying the following code sample to learn the basics.

My issue is when I commented out the following line

```<code>app.use(bodyParser.json);
</code>```

I can see the returning data. But if uncomment it back data will not appear. Anyway, the returning data is coming as an object array as below.

```<code>[object Object],[object Object],[object Object],[object Object]
</code>```

How can parse the JSON to see the actual data?
Do I really need to specify following two lines to get JSON data? if so, how to do it?

```<code>app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json);
</code>```

Following is the full code

```<code>const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');

var Client = require('node-rest-client').Client;

var client = new Client();

const app = express();

app.use(bodyParser.urlencoded({extended:true}));
app.use(cors());
app.use(bodyParser.json);

app.post('/api',(req,res)=>{

client.get("https://url", function (data, response) {
    // parsed response body as js object
    console.log("DATA : "+data);
    res.json({msg:true,data:data});

    // raw response
    //console.log("RESPONSE: "+response);
 });

 });

app.listen(3001,()=>{
console.log("listning to port 3001");
 })
</code>```

Here is the dependency versions as in the package.json file

```<code>"dependencies": {
"body-parser": "^1.18.2",
"cors": "^2.8.4",
"express": "^4.16.2",
"node-rest-client": "^3.1.0"
</code>```

}

Highly appreciate your feedback

答:
As it says in the documentation

You need to use it like this

```<code>// parse application/json
app.use(bodyParser.json())
</code>```

You are using

```<code>app.use(bodyParser.json)
</code>```

Where you have missed ()

Body:
I'm a beginner of ReactJs, NodeJs, express, etc and all the Javascript things. I'm trying the following code sample to learn the basics.

My issue is when I commented out the following line

app.use(bodyParser.json);

I can see the returning data. But if uncomment it back data will not appear. Anyway, the returning data is coming as an object array as below.

[object Object],[object Object],[object Object],[object Object]

How can parse the JSON to see the actual data?
Do I really need to specify following two lines to get JSON data? if so, how to do it?

app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json);

Following is the full code

const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');

var Client = require('node-rest-client').Client;

var client = new Client();

const app = express();

app.use(bodyParser.urlencoded({extended:true}));
app.use(cors());
app.use(bodyParser.json);

app.post('/api',(req,res)=>{

client.get("https://url", function (data, response) {
    // parsed response body as js object
    console.log("DATA : "+data);
    res.json({msg:true,data:data});

    // raw response
    //console.log("RESPONSE: "+response);
 });

 });

app.listen(3001,()=>{
console.log("listning to port 3001");
 })

Here is the dependency versions as in the package.json file

"dependencies": {
"body-parser": "^1.18.2",
"cors": "^2.8.4",
"express": "^4.16.2",
"node-rest-client": "^3.1.0"

}

Highly appreciate your feedback

Body:
As it says in the documentation

You need to use it like this

// parse application/json
app.use(bodyParser.json())

You are using

app.use(bodyParser.json)

Where you have missed ()


问:
Constructor overload in TypeScript
Has anybody done constructor overloading in TypeScript. On page 64 of the language specification (v 0.8), there are statements describing constructor overloads, but there wasn't any sample code given.

I'm trying out a really basic class declaration right now; it looks like this,

```<code>interface IBox {
    x : number;
    y : number;
    height : number;
    width : number;
}

class Box {
    public x: number;
    public y: number;
    public height: number;
    public width: number;

    constructor(obj: IBox) {
        this.x = obj.x;
        this.y = obj.y;
        this.height = obj.height;
        this.width = obj.width;
    }

    constructor() {
        this.x = 0;
        this.y = 0;
        this.width = 0;
        this.height = 0;
    }
}
</code>```

When ran with tsc BoxSample.ts, it throws out a duplicate constructor definition -- which is obvious. Any help is appreciated.

答:
Actually it might be too late for this answer but you can now do this:

```<code>class Box {
    public x: number;
    public y: number;
    public height: number;
    public width: number;

    constructor();
    constructor(obj: IBox);
    constructor(obj?: IBox) {
        this.x = !obj ? 0 : obj.x;
        this.y = !obj ? 0 : obj.y;
        this.height = !obj ? 0 : obj.height;
        this.width = !obj ? 0 : obj.width;
    }
}
</code>```

so instead of static methods you can do the above. I hope it will help you!!!

Title: Constructor overload in TypeScript

Body:
Has anybody done constructor overloading in TypeScript. On page 64 of the language specification (v 0.8), there are statements describing constructor overloads, but there wasn't any sample code given.

I'm trying out a really basic class declaration right now; it looks like this,

interface IBox {
    x : number;
    y : number;
    height : number;
    width : number;
}

class Box {
    public x: number;
    public y: number;
    public height: number;
    public width: number;

    constructor(obj: IBox) {
        this.x = obj.x;
        this.y = obj.y;
        this.height = obj.height;
        this.width = obj.width;
    }

    constructor() {
        this.x = 0;
        this.y = 0;
        this.width = 0;
        this.height = 0;
    }
}

When ran with tsc BoxSample.ts, it throws out a duplicate constructor definition -- which is obvious. Any help is appreciated.

Body:
Actually it might be too late for this answer but you can now do this:

class Box {
    public x: number;
    public y: number;
    public height: number;
    public width: number;

    constructor();
    constructor(obj: IBox);
    constructor(obj?: IBox) {
        this.x = !obj ? 0 : obj.x;
        this.y = !obj ? 0 : obj.y;
        this.height = !obj ? 0 : obj.height;
        this.width = !obj ? 0 : obj.width;
    }
}

so instead of static methods you can do the above. I hope it will help you!!!


问:
.Net Core - AWS Lambda Project enabling DI
I have a Lambda project in .net core and would like to enable Dependency Injection. I have created a Startup class in which I added ConfigureService and ConfigureContainer

```<code>public class Startup
{
        public void ConfigureServices(IServiceCollection services)
        {
            void ConfigureContainer()
            {
                services.AddTransient<IProfileEventHandler, ProfileEventHandler>();
                services.AddTransient<IRepository, ESRepository>();
                services.AddTransient<IDataKeyDecryption, KmsDataKeyDecryption>();
                services.AddTransient<IDecryptionProvider, DecryptionProvider>();
            }

            ConfigureContainer();
        }

}
</code>```

Usually a typical .net core project have a Program Class and we will invoke the start up class in CreateWebHost method, when we run the WebHost, it will just resolve the dependency. But how can I do the same in AWS Lambda project.

答:
You can actually use Asp.NET Core in Lambdas and this makes for easier web development of course.
If you download the dotnet project templates, you can create a project from a template that already has a serverless template as well as the lambda entrypoint, all configured for lambda!

Using this will provide you with the DI and IoC that Asp.Net Core provides out of the box.

If you are using VS you can download the AWS Toolkit for Visual Studio:
https://aws.amazon.com/visualstudio/

Alternatively, you can download the templates to be used via the dotnet cli
https://aws.amazon.com/blogs/developer/creating-net-core-aws-lambda-projects-without-visual-studio/

Body:
I have a Lambda project in .net core and would like to enable Dependency Injection. I have created a Startup class in which I added ConfigureService and ConfigureContainer

public class Startup
{
        public void ConfigureServices(IServiceCollection services)
        {
            void ConfigureContainer()
            {
                services.AddTransient<IProfileEventHandler, ProfileEventHandler>();
                services.AddTransient<IRepository, ESRepository>();
                services.AddTransient<IDataKeyDecryption, KmsDataKeyDecryption>();
                services.AddTransient<IDecryptionProvider, DecryptionProvider>();
            }

            ConfigureContainer();
        }

}

Usually a typical .net core project have a Program Class and we will invoke the start up class in CreateWebHost method, when we run the WebHost, it will just resolve the dependency. But how can I do the same in AWS Lambda project.