问:
anyway to optimize this multiple insert query?
So I have 3 tables given on the codes below
I don't know if there's any way to optimize this because I think it's not the proper way to insert data especially if you're dealing with normalization.</p>

```<code>string mySqlCon = "Server = localhost; port = 3306; database = rmsdb; Uid = root; pwd=''"; //connection string

private void loginbtn_Click(object sender, EventArgs e)
{
    MySqlConnection con = new MySqlConnection(mySqlCon);
    MySqlCommand cmd;

    try
    {
        if (firstnametb.Text.Length > 0 && lastnametb.Text.Length > 0 && gendercb.Text.Length > 0 && addresstb.Text.Length > 0 && birthdatetb.Text.Length > 0 && gradelevelcb.Text.Length > 0 && sectioncb.Text.Length > 0 && positioncb.Text.Length > 0 && empstatuscb.Text.Length > 0 && fiutb.Text.Length > 0 && oadtb.Text.Length > 0 && prctb.Text.Length > 0 && gsistb.Text.Length > 0 && csetb.Text.Length > 0 && contacttb.Text.Length > 0 && usernametb.Text.Length > 0 && passwordtb.Text.Length > 0 && questioncb.Text.Length > 0 && answertb.Text.Length > 0)
        {

            string CmdString = "INSERT INTO TeachersINFO('teachersid',firstname,lastname,gender,address,birthdate,position,empstatus,contactnumber,gradelevel,section,status) values (@teachersid,@firstname,@lastname,@gender,@address,@birthdate,@position,@empstatus,@contactnumber,@gradelevel,@section,@status);" +Environment.NewLine+
                               "INSERT INTO teacherslogin(teachersid,username,password,secretquestion,answer,status) values (@teachersid2,@username,@password,@secretquestion,@answer,@status2);" +Environment.NewLine+
                               "INSERT INTO teachersref(teachersid,FIU,oad,PrcNo,GSISBPNo,UMIDNo,TinNo,PhilHealthNo,CivilServiceE) values (@teachersid3,@FIU,@oad,@PrcNo,@GSISBPNo,@UMIDNo,@TinNo,@PhilHealthNo)";
            cmd = new MySqlCommand(CmdString, con);
            cmd.Parameters.AddWithValue("@teachersid", teacheridtb.Text);
            cmd.Parameters.AddWithValue("@firstname", firstnametb.Text);
            cmd.Parameters.AddWithValue("@lastname", lastnametb.Text);
            cmd.Parameters.AddWithValue("@gender", gendercb.Text);
            cmd.Parameters.AddWithValue("@address", addresstb.Text);
            cmd.Parameters.AddWithValue("@birthdate", birthdatetb.Text);
            cmd.Parameters.AddWithValue("@position", positioncb.Text);
            cmd.Parameters.AddWithValue("@empstatus", empstatuscb.Text);
            cmd.Parameters.AddWithValue("@contactnumber", contacttb.Text);
            cmd.Parameters.AddWithValue("@gradelevel", gradelevelcb.Text);
            cmd.Parameters.AddWithValue("@section", sectioncb.Text);
            cmd.Parameters.AddWithValue("@status", 1);
            //secondtable values p0ta kahit pandurugas to wala kong pake stored procedures parin tawag dito HAHAHA//
            cmd.Parameters.AddWithValue("@teachersid2", teacheridtb.Text);
            cmd.Parameters.AddWithValue("@username", usernametb.Text);
            cmd.Parameters.AddWithValue("@password", passwordtb.Text);
            cmd.Parameters.AddWithValue("@secretquestion", questioncb.Text);
            cmd.Parameters.AddWithValue("@answer", answertb.Text);
            cmd.Parameters.AddWithValue("@status2",1);
            //thirdtable values hahaha pota pandaraya so much

            con.Open();
            int RowsAffected = cmd.ExecuteNonQuery();
            if (RowsAffected > 0)
            {
                MessageBox.Show("Registered Successfully", "System Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
                firstnametb.Text = "";
                lastnametb.Text = "";
                gendercb.SelectedItem = null;
                lastnametb.Text = "";
                addresstb.Text = "";
                gradelevelcb.SelectedItem = null;
                sectioncb.SelectedItem = null;
                answertb.Text = "";
                usernametb.Text = "";
                passwordtb.Text = "";
                questioncb.Text = "";
                empstatuscb.Text = "";
                positioncb.Text = "";
                fiutb.Text = "";
                oadtb.Text = "";
                prctb.Text = "";
                gsistb.Text = "";
                csetb.Text = "";

                con.Close();
                //clearing textboxes fields.

            }
        }
        else
        {
            MessageBox.Show("Incomplete Data", "System Message", MessageBoxButtons.OK, MessageBoxIcon.Error);

        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
    finally
    {
        if (con.State == ConnectionState.Open)
        {
            con.Close();
        }
    }

}
</code>```

答:
I would advise using a stored procedure that takes in all these parameters and then does the insert.

Using a stored procedure can help optimise the code as the stored procedure has already been compiled before it is called in the C# code. That should help with optimisation.

You can also use something like EntityFramework to help you avoid writing SQL commands by yourself.

Body:
So I have 3 tables given on the codes below
I don't know if there's any way to optimize this because I think it's not the proper way to insert data especially if you're dealing with normalization.

string mySqlCon = "Server = localhost; port = 3306; database = rmsdb; Uid = root; pwd=''"; //connection string

private void loginbtn_Click(object sender, EventArgs e)
{
    MySqlConnection con = new MySqlConnection(mySqlCon);
    MySqlCommand cmd;

    try
    {
        if (firstnametb.Text.Length > 0 && lastnametb.Text.Length > 0 && gendercb.Text.Length > 0 && addresstb.Text.Length > 0 && birthdatetb.Text.Length > 0 && gradelevelcb.Text.Length > 0 && sectioncb.Text.Length > 0 && positioncb.Text.Length > 0 && empstatuscb.Text.Length > 0 && fiutb.Text.Length > 0 && oadtb.Text.Length > 0 && prctb.Text.Length > 0 && gsistb.Text.Length > 0 && csetb.Text.Length > 0 && contacttb.Text.Length > 0 && usernametb.Text.Length > 0 && passwordtb.Text.Length > 0 && questioncb.Text.Length > 0 && answertb.Text.Length > 0)
        {

            string CmdString = "INSERT INTO TeachersINFO('teachersid',firstname,lastname,gender,address,birthdate,position,empstatus,contactnumber,gradelevel,section,status) values (@teachersid,@firstname,@lastname,@gender,@address,@birthdate,@position,@empstatus,@contactnumber,@gradelevel,@section,@status);" +Environment.NewLine+
                               "INSERT INTO teacherslogin(teachersid,username,password,secretquestion,answer,status) values (@teachersid2,@username,@password,@secretquestion,@answer,@status2);" +Environment.NewLine+
                               "INSERT INTO teachersref(teachersid,FIU,oad,PrcNo,GSISBPNo,UMIDNo,TinNo,PhilHealthNo,CivilServiceE) values (@teachersid3,@FIU,@oad,@PrcNo,@GSISBPNo,@UMIDNo,@TinNo,@PhilHealthNo)";
            cmd = new MySqlCommand(CmdString, con);
            cmd.Parameters.AddWithValue("@teachersid", teacheridtb.Text);
            cmd.Parameters.AddWithValue("@firstname", firstnametb.Text);
            cmd.Parameters.AddWithValue("@lastname", lastnametb.Text);
            cmd.Parameters.AddWithValue("@gender", gendercb.Text);
            cmd.Parameters.AddWithValue("@address", addresstb.Text);
            cmd.Parameters.AddWithValue("@birthdate", birthdatetb.Text);
            cmd.Parameters.AddWithValue("@position", positioncb.Text);
            cmd.Parameters.AddWithValue("@empstatus", empstatuscb.Text);
            cmd.Parameters.AddWithValue("@contactnumber", contacttb.Text);
            cmd.Parameters.AddWithValue("@gradelevel", gradelevelcb.Text);
            cmd.Parameters.AddWithValue("@section", sectioncb.Text);
            cmd.Parameters.AddWithValue("@status", 1);
            //secondtable values p0ta kahit pandurugas to wala kong pake stored procedures parin tawag dito HAHAHA//
            cmd.Parameters.AddWithValue("@teachersid2", teacheridtb.Text);
            cmd.Parameters.AddWithValue("@username", usernametb.Text);
            cmd.Parameters.AddWithValue("@password", passwordtb.Text);
            cmd.Parameters.AddWithValue("@secretquestion", questioncb.Text);
            cmd.Parameters.AddWithValue("@answer", answertb.Text);
            cmd.Parameters.AddWithValue("@status2",1);
            //thirdtable values hahaha pota pandaraya so much

            con.Open();
            int RowsAffected = cmd.ExecuteNonQuery();
            if (RowsAffected > 0)
            {
                MessageBox.Show("Registered Successfully", "System Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
                firstnametb.Text = "";
                lastnametb.Text = "";
                gendercb.SelectedItem = null;
                lastnametb.Text = "";
                addresstb.Text = "";
                gradelevelcb.SelectedItem = null;
                sectioncb.SelectedItem = null;
                answertb.Text = "";
                usernametb.Text = "";
                passwordtb.Text = "";
                questioncb.Text = "";
                empstatuscb.Text = "";
                positioncb.Text = "";
                fiutb.Text = "";
                oadtb.Text = "";
                prctb.Text = "";
                gsistb.Text = "";
                csetb.Text = "";

                con.Close();
                //clearing textboxes fields.

            }
        }
        else
        {
            MessageBox.Show("Incomplete Data", "System Message", MessageBoxButtons.OK, MessageBoxIcon.Error);

        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
    finally
    {
        if (con.State == ConnectionState.Open)
        {
            con.Close();
        }
    }

}


来源: stackexchange

问:
Why can pointers be NULL
In C or C++, isn't NULL just the constant integer 0? Why are we allowed to assign some pointer to the value NULL if it a constant integer? Wouldn't a compiler say that the two types don't match? </p>

答:
6.3.2.3 Pointers

...

3     An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant.66) If a null pointer constant is converted to a pointer type, the resulting pointer, called a null pointer, is guaranteed to compare unequal to a pointer to any object or function.

66) The macro NULL is defined in <stddef.h> (and other headers) as a null pointer constant; see 7.19.

C 2011 online draft

A literal 0 in a pointer context is treated specially by the compiler, and is understood to be the null pointer constant.  In the context of your source code, it behaves like any other zero-valued expression.

However, once your code is translated to machine code, all occurrences of the null pointer constant will be replaced with whatever value the underlying platform uses to represent a well-defined invalid pointer value, whether that’s 0 or 0xFFFFFFFF or 0xDEADBEEF.

ContentLicense: CC BY-SA 3.0

Title: Why can pointers be NULL


问:
How to change color of button when clicked in WP7?
In WP7 whenever a button is clicked ,the background of button becomes white showing that button is clicked and becomes normal on releasing the mouse button.But I want to change the color of button selection from white to orange.How can i dot it?</p>

答:
You can do this by retemplating the button control in blend.

rclick the control

edit template

edit a copy

modify formatting of constituent components for chosen view states

ContentLicense: CC BY-SA 2.5


问:
How to parse String output of a tensorflow model
Created a model using the code here : https://gist.github.com/gaganmalhotra/1424bd3d0617e784976b29d5846b16b1

To get the predictions of the probabilites in java it can be done using below code:

```<code>  public static void main(String[] args) {
    Session session = SavedModelBundle.load("/Users/gagandeep.malhotra/Documents/SampleTF_projects/tf_iris_model/1510707746/", "serve").session();

    Tensor x =
        Tensor.create(
            new long[] {2, 4},
            FloatBuffer.wrap(
                new float[] {
                  6.4f, 3.2f, 4.5f, 1.5f,
                  5.8f, 3.1f, 5.0f, 1.7f
                }));

    final String xName = "Placeholder:0";
    final String scoresName = "dnn/head/predictions/probabilities:0";

    List<Tensor<?>> outputs = session.runner()
        .feed(xName, x)
        .fetch(scoresName)
        .run();

    // Outer dimension is batch size; inner dimension is number of classes
    float[][] scores = new float[2][3];

    outputs.get(0).copyTo(scores);
    System.out.println(Arrays.deepToString(scores));
  }
</code>```

However if we want to copy over the predicted classes (string type) for the code below:

```<code>final String xName = "Placeholder:0";
final String className = "dnn/head/predictions/str_classes:0";

List<Tensor<?>> outputs = session.runner()
    .feed(xName, x)
    .fetch(className)
    .run();

// Outer dimension is batch size; inner dimension is number of classes
String[][] classes = new String[2][1];

outputs.get(0).copyTo(classes);
System.out.println(Arrays.deepToString(classes));
</code>```

I end up with an error like this:

```<code>Exception in thread "main" java.lang.IllegalArgumentException: cannot copy Tensor with 2 dimensions into an object with 1
    at org.tensorflow.Tensor.throwExceptionIfTypeIsIncompatible(Tensor.java:739)
    at org.tensorflow.Tensor.copyTo(Tensor.java:450)
    at deeplearning.IrisTFLoad.main(IrisTFLoad.java:71)
</code>```

But the dimension is same as the output tensor: [STRING tensor with shape [2, 1]]

PS: The signature definition can be found as below -

```<code>The given SavedModel SignatureDef contains the following input(s):
    inputs['x'] tensor_info:
        dtype: DT_FLOAT
        shape: (-1, 4)
        name: Placeholder:0
    The given SavedModel SignatureDef contains the following output(s):
    outputs['class_ids'] tensor_info:
        dtype: DT_INT64
        shape: (-1, 1)
        name: dnn/head/predictions/ExpandDims:0
    outputs['classes'] tensor_info:
        dtype: DT_STRING
        shape: (-1, 1)
        name: dnn/head/predictions/str_classes:0
    outputs['logits'] tensor_info:
        dtype: DT_FLOAT
        shape: (-1, 3)
        name: dnn/head/logits:0
    outputs['probabilities'] tensor_info:
        dtype: DT_FLOAT
        shape: (-1, 3)
        name: dnn/head/predictions/probabilities:0
    Method name is: tensorflow/serving/predict
</code>```

Things tried :

Tensor tensor = (Tensor) outputs.get(0);
   byte[][][] result = tensor.copyTo(new byte[2][1][]);

but errors out as below:

```<code>Exception in thread "main" java.lang.IllegalStateException: invalid DataType(7)
    at org.tensorflow.Tensor.readNDArray(Native Method)
    at org.tensorflow.Tensor.copyTo(Tensor.java:451)
    at deeplearning.IrisTFLoad.main(IrisTFLoad.java:74)
</code>```

答:
The DT_STRING typed TensorFlow tensors contain arbitrary byte sequences as elements, not Java Strings (sequence of characters).

Thus, what you want is something like this:

```<code>byte[][][] classes = new byte[2][1][];
outputs.get(0).copyTo(classes);
</code>```

If you'd like to get Java String objects, then you'll need to know what encoding your model produces the classes in, and then could do something like (assuming UTF-8 encoding):

```<code>String[][] classesStrings = new String[2][1];
for (int i = 0; i < classes.length; ++i) {
  for (int j = 0; j < classes[i].length; ++j) {
    classesString[i][j] = new String(classes[i][j], UTF_8);
  }
}
</code>```

Hope that helps.
You might also find the unittest instructive.

Body:
Created a model using the code here : https://gist.github.com/gaganmalhotra/1424bd3d0617e784976b29d5846b16b1

To get the predictions of the probabilites in java it can be done using below code:

  public static void main(String[] args) {
    Session session = SavedModelBundle.load("/Users/gagandeep.malhotra/Documents/SampleTF_projects/tf_iris_model/1510707746/", "serve").session();

    Tensor x =
        Tensor.create(
            new long[] {2, 4},
            FloatBuffer.wrap(
                new float[] {
                  6.4f, 3.2f, 4.5f, 1.5f,
                  5.8f, 3.1f, 5.0f, 1.7f
                }));

    final String xName = "Placeholder:0";
    final String scoresName = "dnn/head/predictions/probabilities:0";

    List<Tensor<?>> outputs = session.runner()
        .feed(xName, x)
        .fetch(scoresName)
        .run();

    // Outer dimension is batch size; inner dimension is number of classes
    float[][] scores = new float[2][3];

    outputs.get(0).copyTo(scores);
    System.out.println(Arrays.deepToString(scores));
  }

However if we want to copy over the predicted classes (string type) for the code below:

final String xName = "Placeholder:0";
final String className = "dnn/head/predictions/str_classes:0";

List<Tensor<?>> outputs = session.runner()
    .feed(xName, x)
    .fetch(className)
    .run();

// Outer dimension is batch size; inner dimension is number of classes
String[][] classes = new String[2][1];

outputs.get(0).copyTo(classes);
System.out.println(Arrays.deepToString(classes));

I end up with an error like this:

Exception in thread "main" java.lang.IllegalArgumentException: cannot copy Tensor with 2 dimensions into an object with 1
    at org.tensorflow.Tensor.throwExceptionIfTypeIsIncompatible(Tensor.java:739)
    at org.tensorflow.Tensor.copyTo(Tensor.java:450)
    at deeplearning.IrisTFLoad.main(IrisTFLoad.java:71)

But the dimension is same as the output tensor: [STRING tensor with shape [2, 1]]

PS: The signature definition can be found as below -

The given SavedModel SignatureDef contains the following input(s):
    inputs['x'] tensor_info:
        dtype: DT_FLOAT
        shape: (-1, 4)
        name: Placeholder:0
    The given SavedModel SignatureDef contains the following output(s):
    outputs['class_ids'] tensor_info:
        dtype: DT_INT64
        shape: (-1, 1)
        name: dnn/head/predictions/ExpandDims:0
    outputs['classes'] tensor_info:
        dtype: DT_STRING
        shape: (-1, 1)
        name: dnn/head/predictions/str_classes:0
    outputs['logits'] tensor_info:
        dtype: DT_FLOAT
        shape: (-1, 3)
        name: dnn/head/logits:0
    outputs['probabilities'] tensor_info:
        dtype: DT_FLOAT
        shape: (-1, 3)
        name: dnn/head/predictions/probabilities:0
    Method name is: tensorflow/serving/predict

Things tried :

Tensor tensor = (Tensor) outputs.get(0);
   byte[][][] result = tensor.copyTo(new byte[2][1][]);

but errors out as below:

Exception in thread "main" java.lang.IllegalStateException: invalid DataType(7)
    at org.tensorflow.Tensor.readNDArray(Native Method)
    at org.tensorflow.Tensor.copyTo(Tensor.java:451)
    at deeplearning.IrisTFLoad.main(IrisTFLoad.java:74)

Body:
The DT_STRING typed TensorFlow tensors contain arbitrary byte sequences as elements, not Java Strings (sequence of characters).

Thus, what you want is something like this:

byte[][][] classes = new byte[2][1][];
outputs.get(0).copyTo(classes);

If you'd like to get Java String objects, then you'll need to know what encoding your model produces the classes in, and then could do something like (assuming UTF-8 encoding):

String[][] classesStrings = new String[2][1];
for (int i = 0; i < classes.length; ++i) {
  for (int j = 0; j < classes[i].length; ++j) {
    classesString[i][j] = new String(classes[i][j], UTF_8);
  }
}

Hope that helps.
You might also find the unittest instructive.


问:
How to run tslint using Angular Cli?
I am facing issue when I am trying to run tslint from Angular Cli.

> ng lint

Error

Failed to load E:\Projects\lsp-ui\node_modules\ng2-slimscroll\tslint.json: Could not find custom rule directory: E:\Projects\lsp-ui\node_modules\ng2-slimscroll\node_modules\codelyzer

[Error while running]

答:
Run npm install or npm install codelyzer first.

Also check the file path of tsconfig.json in the Angular Cli configuration lint section, the configuration of rules directory in tslint.json, such as:

```<code>"rulesDirectory": [
        "../node_modules/codelyzer"
    ]
</code>```

Title: How to run tslint using Angular Cli?

Body:
Run npm install or npm install codelyzer first.

Also check the file path of tsconfig.json in the Angular Cli configuration lint section, the configuration of rules directory in tslint.json, such as:

"rulesDirectory": [
        "../node_modules/codelyzer"
    ]

ContentLicense: CC BY-SA 4.0


问:
'conda list' shows package but anaconda navigator does not
When I type conda list into Windows command I can see

pyswarm    0.6      pip

but when I search for pyswarm in my root environment it doesn't show up. Assuming that only packages in my anaconda list can be imported in PyCharm (false, see comment), I want pyswarm to show up in my list in root (3.6)

I have tried (pip uninstall pyswarm after each failed attempt)

pip install -i https://pypi.anaconda.org/pypi/simple pyswarm (from here)

pip install --upgrade pyswarm (from here)

activate root (enter) --- pip install --upgrade swarm

My fix was to just use Jupyter copy the pso.py library into my PyCharm project

Thoughts:

The first install attempt is for a 2.7 package. My root is 3.6

There is a Git repo, but I believe this is a more appropriate platform for this Q

答:
It will only show anaconda site-packages folder where all libraries are installed. You can't directly see in program files like normal software.
Anaconda is listing because it found in site-packages. Use any IDE (ex:PyCharm or simple windows cmd ) to check whether you able to import or not.

Import package-name


问:
MySQL View: Union Query Fails
I'm trying to create a view based on the following query, which works fine as a query:

```<code>SELECT x_doc_status.Status, sort_order FROM x_doc_status WHERE sort_order IS NOT NULL
UNION
SELECT "[All]", -2
UNION
SELECT "[Open/App] (Trk/Pnd/App)", -1
UNION
SELECT "[Open] (Tracking & Pending)", 0
ORDER BY sort_order, STATUS;
</code>```

But it fails when I try to create the view from this. Any suggestions would be most appreciated!

答:
Use single quotes for literals

```<code>SELECT
      x_doc_status.Status
    , sort_order
FROM x_doc_status
WHERE sort_order IS NOT NULL
UNION
SELECT
      '[All]'
    , -2
UNION
SELECT
      '[Open/App] (Trk/Pnd/App)'
    , -1
UNION
SELECT
      '[Open] (Tracking & Pending)'
    , 0
ORDER BY
      sort_order
    , STATUS
;
</code>```

I suggest you also use UNION ALL instead of just UNION. The former is faster because it does not attempt to remove duplicate rows.

Title: MySQL View: Union Query Fails

Body:
I'm trying to create a view based on the following query, which works fine as a query:

SELECT x_doc_status.Status, sort_order FROM x_doc_status WHERE sort_order IS NOT NULL
UNION
SELECT "[All]", -2
UNION
SELECT "[Open/App] (Trk/Pnd/App)", -1
UNION
SELECT "[Open] (Tracking & Pending)", 0
ORDER BY sort_order, STATUS;

But it fails when I try to create the view from this. Any suggestions would be most appreciated!

Body:
Use single quotes for literals

SELECT
      x_doc_status.Status
    , sort_order
FROM x_doc_status
WHERE sort_order IS NOT NULL
UNION
SELECT
      '[All]'
    , -2
UNION
SELECT
      '[Open/App] (Trk/Pnd/App)'
    , -1
UNION
SELECT
      '[Open] (Tracking & Pending)'
    , 0
ORDER BY
      sort_order
    , STATUS
;

I suggest you also use UNION ALL instead of just UNION. The former is faster because it does not attempt to remove duplicate rows.


问:
tmux and macOS Clipboard
Is there a reliable way to make tmux 2.5 to work with macOS clipboard?

After upgrading to 2.5 everything went downhill. I have tried every solution I have found and nothing works. Could anybody please provide me with a working sample of tmux.conf that will make it work?

I can copy from neovim inside tmux just fine. I can't copy the text using tmux itself.

Here is what I have in .tmux.conf:

```<code>setw -g mode-keys vi
bind-key -T copy-mode-vi 'v' begin-selection
bind-key -T copy-mode-vi 'y' copy-pipe-and-cancel "reattach-to-user-namespace pbcopy" \; display-message "copied to system clipboard"
</code>```

These are the errors that appear every time the session is started:

```<code>.tmux.conf:95: unknown command: begin-selection
.tmux.conf:96: unknown command: copy-pipe-and-cancel
</code>```

I have tried the following:

```<code>set-window-option -g mode-keys vi
bind-key -Tcopy-mode-vi 'v' send -X begin-selection
bind-key -Tcopy-mode-vi 'y' send -X copy-pipe-and-cancel pbcopy
</code>```

I have also tried:

```<code>bind-key -Tcopy-mode-vi 'y' send -X copy-pipe-and-cancel
</code>```

Nothing.

答:
I made it work with tmux 2.6 like so:

Removed any references of reattach-to-user-namespace and now I have this in my .tmux.conf:

```<code>set-window-option -g mode-keys vi
bind-key -T copy-mode-vi v send -X begin-selection
bind-key -T copy-mode-vi y send-keys -X copy-pipe-and-cancel "pbcopy"
bind-key -T copy-mode-vi MouseDragEnd1Pane send-keys -X copy-pipe-and-cancel "pbcopy"
bind-key -T copy-mode-vi Enter send-keys -X copy-pipe-and-cancel "pbcopy"
</code>```

Title: tmux and macOS Clipboard

Body:
Is there a reliable way to make tmux 2.5 to work with macOS clipboard?

After upgrading to 2.5 everything went downhill. I have tried every solution I have found and nothing works. Could anybody please provide me with a working sample of tmux.conf that will make it work?

I can copy from neovim inside tmux just fine. I can't copy the text using tmux itself.

Here is what I have in .tmux.conf:

setw -g mode-keys vi
bind-key -T copy-mode-vi 'v' begin-selection
bind-key -T copy-mode-vi 'y' copy-pipe-and-cancel "reattach-to-user-namespace pbcopy" \; display-message "copied to system clipboard"

These are the errors that appear every time the session is started:

.tmux.conf:95: unknown command: begin-selection
.tmux.conf:96: unknown command: copy-pipe-and-cancel

I have tried the following:

set-window-option -g mode-keys vi
bind-key -Tcopy-mode-vi 'v' send -X begin-selection
bind-key -Tcopy-mode-vi 'y' send -X copy-pipe-and-cancel pbcopy

I have also tried:

bind-key -Tcopy-mode-vi 'y' send -X copy-pipe-and-cancel

Nothing.

Body:
I made it work with tmux 2.6 like so:

Removed any references of reattach-to-user-namespace and now I have this in my .tmux.conf:

set-window-option -g mode-keys vi
bind-key -T copy-mode-vi v send -X begin-selection
bind-key -T copy-mode-vi y send-keys -X copy-pipe-and-cancel "pbcopy"
bind-key -T copy-mode-vi MouseDragEnd1Pane send-keys -X copy-pipe-and-cancel "pbcopy"
bind-key -T copy-mode-vi Enter send-keys -X copy-pipe-and-cancel "pbcopy"


问:
C# + WPF : how should I do proper checks/guards/casts when accessing control values?
This is probably pretty basic, but I'm just picking up C# after many years working with other languages, and I've unfortunately grown used to loose and dynamic typing.  Now, in building a WPF form with a lot of checkboxes, I notice that my code to do simple things like determine whether a checkbox is checked is actually quite complicated due to the need to check for nulls and cast the results.  I end up with helper functions like:

```<code>    private bool isChecked(CheckBox control) {
        return control != null && control.IsChecked != null && control.IsChecked.HasValue && (bool)control.IsChecked;
    }
</code>```

so that in my logic code, I can just do

```<code>    if (isChecked(opticsCheckBox))
    {
        // whatever I need to do if opticsCheckBox is checked
    }
</code>```

Is this the normal way of doing things in C# (with WPF), or am I missing something simple?  Basically I'm finding the nested layers of conditionals to check every object for null all the time to be a warning sign of bad code (and the fact that I could forget a check).  Not sure what I should be doing though.

Should I be using try ... catch everywhere even though the control not being present or checked isn't really an exceptional condition?  That seems to me like it would end up being just as cluttered.

Another example to clarify:
When I would like to write something like:

```<code>    maxWeight = (int)maxWeightComboBox.SelectedItem;
</code>```

I find myself instead writing:

```<code>    if (maxWeightComboBox != null && maxWeightComboBox.SelectedItem != null)
    {
        ComboBoxItem item = (ComboBoxItem)maxWeightComboBox.SelectedItem;
        maxWeight = Int32.Parse(item.Content.ToString());
    }
</code>```

答:
In general, yes, C# is a bit more verbose than a dynamic / lossely typed language. The same is true of Java. Looking at your specific examples ...

```<code>private bool isChecked(CheckBox control) {
    return control != null && control.IsChecked != null && control.IsChecked.HasValue && (bool)control.IsChecked;
}
</code>```

A couple of points ... the following two checks are equivalent:

```<code>control.IsChecked != null
control.IsChecked.HasValue
</code>```

The IsChecked property is a Nullable type. As you are new to C# I would recommend reading up on value types vs. reference types. Once you have the hang of that, you can find out how the Nullable type can be used to wrap a value type in order to assign a null value to it. The page linked below explains why the twp statements above are equivalent:

http://msdn.microsoft.com/en-us/library/2cf62fcy%28VS.80%29.aspx

Secondly, why are you checking that control!=null ? In typical scenarious you create controls in XAML on your Window or UserControl, identifying via the x:Name attribute. In this case you can rely on the control being present in your UI and drop this check.

Your other two checks are necessary ;-)

Good idea placng these in a method that you can re-use. You can also 'extend' the langauge by creating extension methods, e.g

```<code>private bool IsChecked(this CheckBox control) {
    return control.IsChecked.HasValue && (bool)control.IsChecked;
}

// calls the extension method above.
myCheckBox.IsChecked()
</code>```

Hoep that helps.

Body:
This is probably pretty basic, but I'm just picking up C# after many years working with other languages, and I've unfortunately grown used to loose and dynamic typing.  Now, in building a WPF form with a lot of checkboxes, I notice that my code to do simple things like determine whether a checkbox is checked is actually quite complicated due to the need to check for nulls and cast the results.  I end up with helper functions like:

    private bool isChecked(CheckBox control) {
        return control != null && control.IsChecked != null && control.IsChecked.HasValue && (bool)control.IsChecked;
    }

so that in my logic code, I can just do

    if (isChecked(opticsCheckBox))
    {
        // whatever I need to do if opticsCheckBox is checked
    }

Is this the normal way of doing things in C# (with WPF), or am I missing something simple?  Basically I'm finding the nested layers of conditionals to check every object for null all the time to be a warning sign of bad code (and the fact that I could forget a check).  Not sure what I should be doing though.

Should I be using try ... catch everywhere even though the control not being present or checked isn't really an exceptional condition?  That seems to me like it would end up being just as cluttered.

Another example to clarify:
When I would like to write something like:

    maxWeight = (int)maxWeightComboBox.SelectedItem;

I find myself instead writing:

    if (maxWeightComboBox != null && maxWeightComboBox.SelectedItem != null)
    {
        ComboBoxItem item = (ComboBoxItem)maxWeightComboBox.SelectedItem;
        maxWeight = Int32.Parse(item.Content.ToString());
    }

Body:
In general, yes, C# is a bit more verbose than a dynamic / lossely typed language. The same is true of Java. Looking at your specific examples ...

private bool isChecked(CheckBox control) {
    return control != null && control.IsChecked != null && control.IsChecked.HasValue && (bool)control.IsChecked;
}

A couple of points ... the following two checks are equivalent:

control.IsChecked != null
control.IsChecked.HasValue

The IsChecked property is a Nullable type. As you are new to C# I would recommend reading up on value types vs. reference types. Once you have the hang of that, you can find out how the Nullable type can be used to wrap a value type in order to assign a null value to it. The page linked below explains why the twp statements above are equivalent:

http://msdn.microsoft.com/en-us/library/2cf62fcy%28VS.80%29.aspx

Secondly, why are you checking that control!=null ? In typical scenarious you create controls in XAML on your Window or UserControl, identifying via the x:Name attribute. In this case you can rely on the control being present in your UI and drop this check.

Your other two checks are necessary ;-)

Good idea placng these in a method that you can re-use. You can also 'extend' the langauge by creating extension methods, e.g

private bool IsChecked(this CheckBox control) {
    return control.IsChecked.HasValue && (bool)control.IsChecked;
}

// calls the extension method above.
myCheckBox.IsChecked()

Hoep that helps.


问:
Deploying Maven project throws java.util.zip.ZipException: invalid LOC header (bad signature)
I am getting the below exception when I run my mvn install. I have even deleted the local repository and ran again getting same exception.

[ERROR] Failed to execute goal
  org.apache.maven.plugins:maven-shade-plugin:2.1:shade (default) on
  project cores-batch: Error creating shaded jar: invalid LOC header
  (bad signature) -> [Help 1]

```<code><?xml version="1.0" encoding="UTF-8"?>
<plugin>
   <groupId>org.apache.maven.plugins</groupId>
   <artifactId>maven-shade-plugin</artifactId>
   <version>2.1</version>
   <configuration>
      <skipTests>true</skipTests>
   </configuration>
   <executions>
      <execution>
         <phase>package</phase>
         <goals>
            <goal>shade</goal>
         </goals>
         <configuration>
            <artifactSet>
               <excludes>
                  <exclude>commons-logging:commons-logging:jar:*</exclude>
               </excludes>
            </artifactSet>
            <filters>
               <filter>
                  <artifact>*:*</artifact>
                  <excludes>
                     <!-- workaround for a spring issues -->
                     <exclude>META-INF/*.SF</exclude>
                     <exclude>META-INF/*.DSA</exclude>
                     <exclude>META-INF/*.RSA</exclude>
                     <!-- don't want to pick up any other log4j.xml -->
                     <exclude>log4j.xml</exclude>
                  </excludes>
               </filter>
            </filters>
            <!-- May be needed to work around another issue in Spring -->
            <transformers>
               <transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
                  <resource>META-INF/spring.handlers</resource>
               </transformer>
               <transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
                  <resource>META-INF/spring.schemas</resource>
               </transformer>
            </transformers>
         </configuration>
      </execution>
   </executions>
</plugin>
</code>```

Error:

```<code>[ERROR] Failed to execute goal org.apache.maven.plugins:maven-shade-plugin:2.1:shade (default) on project cores-batch: Error creating shaded jar: invalid LOC header (bad signature) -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.maven.plugins:maven-shade-plugin:2.1:shade (default) on project cores-batch: Error creating shaded jar: invalid LOC header (bad signature)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:217)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:84)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:59)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.java:183)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:320)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:156)
    at org.apache.maven.cli.MavenCli.execute(MavenCli.java:537)
    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:196)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:141)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:290)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:230)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:409)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:352)
Caused by: org.apache.maven.plugin.MojoExecutionException: Error creating shaded jar: invalid LOC header (bad signature)
    at org.apache.maven.plugins.shade.mojo.ShadeMojo.execute(ShadeMojo.java:528)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:101)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:209)
    ... 19 more
Caused by: java.util.zip.ZipException: invalid LOC header (bad signature)
    at java.util.zip.ZipFile.read(Native Method)
    at java.util.zip.ZipFile.access$1400(ZipFile.java:56)
    at java.util.zip.ZipFile$ZipFileInputStream.read(ZipFile.java:679)
    at java.util.zip.ZipFile$ZipFileInflaterInputStream.fill(ZipFile.java:415)
    at java.util.zip.InflaterInputStream.read(InflaterInputStream.java:158)
    at java.io.FilterInputStream.read(FilterInputStream.java:107)
    at org.codehaus.plexus.util.IOUtil.copy(IOUtil.java:189)
    at org.codehaus.plexus.util.IOUtil.copy(IOUtil.java:175)
    at org.apache.maven.plugins.shade.DefaultShader.addResource(DefaultShader.java:427)
    at org.apache.maven.plugins.shade.DefaultShader.shade(DefaultShader.java:186)
    at org.apache.maven.plugins.shade.mojo.ShadeMojo.execute(ShadeMojo.java:458)
    ... 21 more
[ERROR]
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
</code>```

答: You need to check which jar is giving problem. It must be corrupted. Delete that jar and run mvn spring-boot:run command again. May be more that one jar has corrupted so every time you need to run that command to delete that jar. In my case mysql, jackson, aspect jars was corrupted mvn spring-boot:run command 3 times and I figure out this and deleted the jars from .m2 folder. Now the issue has resolved.

Body:
I am getting the below exception when I run my mvn install. I have even deleted the local repository and ran again getting same exception.

[ERROR] Failed to execute goal
  org.apache.maven.plugins:maven-shade-plugin:2.1:shade (default) on
  project cores-batch: Error creating shaded jar: invalid LOC header
  (bad signature) -> [Help 1]

<?xml version="1.0" encoding="UTF-8"?>
<plugin>
   <groupId>org.apache.maven.plugins</groupId>
   <artifactId>maven-shade-plugin</artifactId>
   <version>2.1</version>
   <configuration>
      <skipTests>true</skipTests>
   </configuration>
   <executions>
      <execution>
         <phase>package</phase>
         <goals>
            <goal>shade</goal>
         </goals>
         <configuration>
            <artifactSet>
               <excludes>
                  <exclude>commons-logging:commons-logging:jar:*</exclude>
               </excludes>
            </artifactSet>
            <filters>
               <filter>
                  <artifact>*:*</artifact>
                  <excludes>

                     <exclude>META-INF/*.SF</exclude>
                     <exclude>META-INF/*.DSA</exclude>
                     <exclude>META-INF/*.RSA</exclude>

                     <exclude>log4j.xml</exclude>
                  </excludes>
               </filter>
            </filters>

            <transformers>
               <transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
                  <resource>META-INF/spring.handlers</resource>
               </transformer>
               <transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
                  <resource>META-INF/spring.schemas</resource>
               </transformer>
            </transformers>
         </configuration>
      </execution>
   </executions>
</plugin>

Error:

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-shade-plugin:2.1:shade (default) on project cores-batch: Error creating shaded jar: invalid LOC header (bad signature) -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.maven.plugins:maven-shade-plugin:2.1:shade (default) on project cores-batch: Error creating shaded jar: invalid LOC header (bad signature)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:217)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:84)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:59)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.java:183)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:320)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:156)
    at org.apache.maven.cli.MavenCli.execute(MavenCli.java:537)
    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:196)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:141)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:290)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:230)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:409)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:352)
Caused by: org.apache.maven.plugin.MojoExecutionException: Error creating shaded jar: invalid LOC header (bad signature)
    at org.apache.maven.plugins.shade.mojo.ShadeMojo.execute(ShadeMojo.java:528)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:101)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:209)
    ... 19 more
Caused by: java.util.zip.ZipException: invalid LOC header (bad signature)
    at java.util.zip.ZipFile.read(Native Method)
    at java.util.zip.ZipFile.access$1400(ZipFile.java:56)
    at java.util.zip.ZipFile$ZipFileInputStream.read(ZipFile.java:679)
    at java.util.zip.ZipFile$ZipFileInflaterInputStream.fill(ZipFile.java:415)
    at java.util.zip.InflaterInputStream.read(InflaterInputStream.java:158)
    at java.io.FilterInputStream.read(FilterInputStream.java:107)
    at org.codehaus.plexus.util.IOUtil.copy(IOUtil.java:189)
    at org.codehaus.plexus.util.IOUtil.copy(IOUtil.java:175)
    at org.apache.maven.plugins.shade.DefaultShader.addResource(DefaultShader.java:427)
    at org.apache.maven.plugins.shade.DefaultShader.shade(DefaultShader.java:186)
    at org.apache.maven.plugins.shade.mojo.ShadeMojo.execute(ShadeMojo.java:458)
    ... 21 more
[ERROR]
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException


问:
Action view::template::error (Unexpected token: operator (<))
im getting a problem with my deploy at heroku!
I just created an app Test with cedar stack, push my app and I have this problem (log)

```<code>←[32m2012-03-24T15:10:56+00:00 app[web.1]:←[0m ActionView::Template::Error (Unexpected token: operator (<)
←[32m2012-03-24T15:10:56+00:00 app[web.1]:←[0m   (in /app/app/assets/javascripts/application.js)):
←[32m2012-03-24T15:10:56+00:00 app[web.1]:←[0m     3: <head>
←[32m2012-03-24T15:10:56+00:00 app[web.1]:←[0m     4:   <title>Test</title>
←[32m2012-03-24T15:10:56+00:00 app[web.1]:←[0m     5:   <%= stylesheet_link_tag    "application" %>
←[32m2012-03-24T15:10:56+00:00 app[web.1]:←[0m     6:   <%= javascript_include_tag "application" %>
←[32m2012-03-24T15:10:56+00:00 app[web.1]:←[0m     7:   <%= csrf_meta_tags %>
←[32m2012-03-24T15:10:56+00:00 app[web.1]:←[0m     8: </head>
←[32m2012-03-24T15:10:56+00:00 app[web.1]:←[0m     9: <body>
</code>```

Any Idea??

Update:

My application.js file

```<code>// This is a manifest file that'll be compiled into including all the files listed below.
// Add new JavaScript/Coffee code in separate files in this directory and they'll automatically
// be included in the compiled file accessible from http://example.com/assets/application.js
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
//= require jquery
//= require jquery_ujs
//= require jquery-ui
//= require_tree .
</code>```

答:
I ran into this error and it took a while to figure out which file referenced in the manifest was the culprit. Once I figured out which file was causing the error, searching for '>' pulled up several lines but I got lucky and quickly zeroed in a map function which used the => operator:

.map(x => x.id);

Once I changed that to an anonymous function:

.map(function(x) { return x.id; });

the error went away.

Body:
im getting a problem with my deploy at heroku!
I just created an app Test with cedar stack, push my app and I have this problem (log)

←[32m2012-03-24T15:10:56+00:00 app[web.1]:←[0m ActionView::Template::Error (Unexpected token: operator (<)
←[32m2012-03-24T15:10:56+00:00 app[web.1]:←[0m   (in /app/app/assets/javascripts/application.js)):
←[32m2012-03-24T15:10:56+00:00 app[web.1]:←[0m     3:
←[32m2012-03-24T15:10:56+00:00 app[web.1]:←[0m     4:   <title>Test</title>
←[32m2012-03-24T15:10:56+00:00 app[web.1]:←[0m     5:   <%= stylesheet_link_tag    "application" %>
←[32m2012-03-24T15:10:56+00:00 app[web.1]:←[0m     6:   <%= javascript_include_tag "application" %>
←[32m2012-03-24T15:10:56+00:00 app[web.1]:←[0m     7:   <%= csrf_meta_tags %>
←[32m2012-03-24T15:10:56+00:00 app[web.1]:←[0m     8:
←[32m2012-03-24T15:10:56+00:00 app[web.1]:←[0m     9:

Any Idea??

Update:

My application.js file

// This is a manifest file that'll be compiled into including all the files listed below.
// Add new JavaScript/Coffee code in separate files in this directory and they'll automatically
// be included in the compiled file accessible from http://example.com/assets/application.js
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
//= require jquery
//= require jquery_ujs
//= require jquery-ui
//= require_tree .


问:
Unpack ... with missing arguments
I'm writing a function that accepts a variable number of arguments. Moreover, I would like the user to be able to leave some of these arguments as missing.

Consider just the task of turning the ... into a list of arguments. Here is my first attempt:

```<code>f <- function(...) list(...)
</code>```

This fails:

```<code>f(1,,2)
## Error in f(1, , 2) : argument is missing, with no default
</code>```

I would like the result to be list(1, NULL, 2). (I am not worried about distinguishing f(1,,2) from f(1,NULL,2).)

Here is my second attempt:

```<code>g <- function(...)
{
    args <- match.call()
    miss <- vapply(args, identical, NA, quote(expr=))
    args[miss] <- list(NULL)
    args[[1L]] <- quote(list)
    eval.parent(args)
}
</code>```

This works (sort of):

```<code>identical(g(1,,2), list(1, NULL, 2))
## [1] TRUE
</code>```

However, it fails when forwarding dots:

```<code>gg <- function(...) g(...)
identical(gg(1,,2), list(1,NULL,2))
## [1] FALSE
</code>```

Is there a way to achieve the same results as g, but in a way that allows forwarding dots and without using match.call()?

Edit: Issues with forwarding dots.

It's tempting to try the following:

```<code>h <- function(...)
{
    args <- substitute(list(...))
    miss <- vapply(args, identical, NA, quote(expr=))
    args[miss] <- list(NULL)
    eval.parent(args)
}
</code>```

However, as @lionel points out, there will be issues if you try to forward ... from another function:

```<code>hh <- function(...) h(letters, ...)
local({ a <- "foo"; h(a) })
## Error in eval(expr, p) : object 'a' not found
</code>```

It seems like you either need the expand.dots functionality of match.call, or you need to use a quosure (from the rlang package).

答:
@lionel gave me most of the information I needed, so I'm marking his answer as correct. The following seems to work:

```<code>h <- function(...)
{
    args <- substitute(list(...))
    miss <- vapply(args, identical, NA, quote(expr=))
    args[miss] <- list(NULL)
    eval.parent(args)
}
</code>```

However, there might be issues with forwarding ... from other functions.

Title: Unpack ... with missing arguments

Body:
I'm writing a function that accepts a variable number of arguments. Moreover, I would like the user to be able to leave some of these arguments as missing.

Consider just the task of turning the ... into a list of arguments. Here is my first attempt:

f <- function(...) list(...)

This fails:

f(1,,2)
## Error in f(1, , 2) : argument is missing, with no default

I would like the result to be list(1, NULL, 2). (I am not worried about distinguishing f(1,,2) from f(1,NULL,2).)

Here is my second attempt:

g <- function(...)
{
    args <- match.call()
    miss <- vapply(args, identical, NA, quote(expr=))
    args[miss] <- list(NULL)
    args[[1L]] <- quote(list)
    eval.parent(args)
}

This works (sort of):

identical(g(1,,2), list(1, NULL, 2))
## [1] TRUE

However, it fails when forwarding dots:

gg <- function(...) g(...)
identical(gg(1,,2), list(1,NULL,2))
## [1] FALSE

Is there a way to achieve the same results as g, but in a way that allows forwarding dots and without using match.call()?

Edit: Issues with forwarding dots.

It's tempting to try the following:

h <- function(...)
{
    args <- substitute(list(...))
    miss <- vapply(args, identical, NA, quote(expr=))
    args[miss] <- list(NULL)
    eval.parent(args)
}

However, as @lionel points out, there will be issues if you try to forward ... from another function:

hh <- function(...) h(letters, ...)
local({ a <- "foo"; h(a) })
## Error in eval(expr, p) : object 'a' not found

It seems like you either need the expand.dots functionality of match.call, or you need to use a quosure (from the rlang package).

Body:
@lionel gave me most of the information I needed, so I'm marking his answer as correct. The following seems to work:

h <- function(...)
{
    args <- substitute(list(...))
    miss <- vapply(args, identical, NA, quote(expr=))
    args[miss] <- list(NULL)
    eval.parent(args)
}

However, there might be issues with forwarding ... from other functions.


问:
How to log request data along with response data in http:outbound-gateway
Using spring integration, I am reading from a queue and then calling a REST service using http:outbound-gateway. The code works fine. But I want to relate the logs such that for a given request key field , so and so response is received. Otherwise, it is very difficult to pinpoint for which request the response is received, when there are thousands of messages flowing through the queue.

My JSON request for the service call is as follows:
{"ID":"123","status":"A"}

my JSON Response from the service call is as follows:
{"transactionStatus":"Success"}

I want to do logging such that "ID:123" has got a reponse transactionStatus as "Success".
Please help me with the code how I can achieve this. Please let me know if you need further details.
Thanks in advance.

```<code><int:object-to-json-transformer input-channel = "gcmRequestChannel" output-channel="RESTSrvcChannel"></int:object-to-json-transformer>

<int:header-enricher id = "restenricher" input-channel = "RESTSrvcChannel" output-channel = "RESTSrvcChannel2">
    <int:header name="contentType" value="application/json"/>
    <int:header name="SPApikey" value="${throttler.SPApikey}" />
</int:header-enricher>
 <http:outbound-gateway id="gcmrestHttpOutboundGateway" request-channel="RESTSrvcChannel2" reply-channel="nullChannel"
                       extract-request-payload="true"
                       url="${throttler.url}"
                       header-mapper="headerMapper"
                       http-method="POST"
                       expected-response-type="java.lang.String"
                       >

</http:outbound-gateway>
<beans:bean id="headerMapper"
    class="org.springframework.integration.http.support.DefaultHttpHeaderMapper">
    <beans:property name="inboundHeaderNames" value="*" />
    <beans:property name="outboundHeaderNames" value="HTTP_REQUEST_HEADERS,SPApikey" />
    <beans:property name="userDefinedHeaderPrefix" value="" />
</beans:bean>
</code>```

答:
I have coded as suggested by you. Thanks for your response.</p>

```<code><int:header-enricher id = "gcmrestenricher" input-channel = "gcmRESTSrvcChannel" output-channel = "gcmRESTSrvcChannel2">
    <int:header name="contentType" value="application/json"/>
    <int:header name="SPApikey" value="${throttler.SPApikey}" />
    <int:header name="JSONPayload" expression="payload"/>
</int:header-enricher>

<http:outbound-gateway id="gcmrestHttpOutboundGateway" request-channel="gcmRESTSrvcChannel2" reply-channel="gcmRESTSrvcOutputChannel"
                       extract-request-payload="true"
                       url="${throttler.gcmurl}"
                       header-mapper="gcmheaderMapper"
                       http-method="POST"
                       expected-response-type="java.lang.String"
                       >

</http:outbound-gateway>
<beans:bean id="gcmheaderMapper"
    class="org.springframework.integration.http.support.DefaultHttpHeaderMapper">
    <beans:property name="inboundHeaderNames" value="*" />
    <beans:property name="outboundHeaderNames" value="HTTP_REQUEST_HEADERS,SPApikey,JSONPayload" />
    <beans:property name="userDefinedHeaderPrefix" value="" />
</beans:bean>
<beans:bean id="logmsg" class = "com.MLAServiceActivator"></beans:bean>
<int:service-activator requires-reply="false" input-channel="gcmRESTSrvcOutputChannel" ref="logmsg" method="ResponseLogging"></int:service-activator>

@ServiceActivator
public void ResponseLogging(Message<String> message)
{
    logger.info("The response message is:"+message.getPayload()+ " for request message:"+message.getHeaders().get("JSONPayload"));
}
</code>```

Body:
Using spring integration, I am reading from a queue and then calling a REST service using http:outbound-gateway. The code works fine. But I want to relate the logs such that for a given request key field , so and so response is received. Otherwise, it is very difficult to pinpoint for which request the response is received, when there are thousands of messages flowing through the queue.

My JSON request for the service call is as follows:
{"ID":"123","status":"A"}

my JSON Response from the service call is as follows:
{"transactionStatus":"Success"}

I want to do logging such that "ID:123" has got a reponse transactionStatus as "Success".
Please help me with the code how I can achieve this. Please let me know if you need further details.
Thanks in advance.

<int:object-to-json-transformer input-channel = "gcmRequestChannel" output-channel="RESTSrvcChannel"></int:object-to-json-transformer>

<int:header-enricher id = "restenricher" input-channel = "RESTSrvcChannel" output-channel = "RESTSrvcChannel2">
    <int:header name="contentType" value="application/json"/>
    <int:header name="SPApikey" value="${throttler.SPApikey}" />
</int:header-enricher>
 <http:outbound-gateway id="gcmrestHttpOutboundGateway" request-channel="RESTSrvcChannel2" reply-channel="nullChannel"
                       extract-request-payload="true"
                       url="${throttler.url}"
                       header-mapper="headerMapper"
                       http-method="POST"
                       expected-response-type="java.lang.String"
                       >

</http:outbound-gateway>
<beans:bean id="headerMapper"
    class="org.springframework.integration.http.support.DefaultHttpHeaderMapper">
    <beans:property name="inboundHeaderNames" value="*" />
    <beans:property name="outboundHeaderNames" value="HTTP_REQUEST_HEADERS,SPApikey" />
    <beans:property name="userDefinedHeaderPrefix" value="" />
</beans:bean>

Body:
I have coded as suggested by you. Thanks for your response.

<int:header-enricher id = "gcmrestenricher" input-channel = "gcmRESTSrvcChannel" output-channel = "gcmRESTSrvcChannel2">
    <int:header name="contentType" value="application/json"/>
    <int:header name="SPApikey" value="${throttler.SPApikey}" />
    <int:header name="JSONPayload" expression="payload"/>
</int:header-enricher>

<http:outbound-gateway id="gcmrestHttpOutboundGateway" request-channel="gcmRESTSrvcChannel2" reply-channel="gcmRESTSrvcOutputChannel"
                       extract-request-payload="true"
                       url="${throttler.gcmurl}"
                       header-mapper="gcmheaderMapper"
                       http-method="POST"
                       expected-response-type="java.lang.String"
                       >

</http:outbound-gateway>
<beans:bean id="gcmheaderMapper"
    class="org.springframework.integration.http.support.DefaultHttpHeaderMapper">
    <beans:property name="inboundHeaderNames" value="*" />
    <beans:property name="outboundHeaderNames" value="HTTP_REQUEST_HEADERS,SPApikey,JSONPayload" />
    <beans:property name="userDefinedHeaderPrefix" value="" />
</beans:bean>
<beans:bean id="logmsg" class = "com.MLAServiceActivator"></beans:bean>
<int:service-activator requires-reply="false" input-channel="gcmRESTSrvcOutputChannel" ref="logmsg" method="ResponseLogging"></int:service-activator>

@ServiceActivator
public void ResponseLogging(Message<String> message)
{
    logger.info("The response message is:"+message.getPayload()+ " for request message:"+message.getHeaders().get("JSONPayload"));
}


问:
How do I update my Python Google Sheet API credentials code to avoid package depreciation?
The Google Sheets API Python Quickstart currently uses deprecated packages in its example code, where the use of oauth2client and httplib2 rather than google-auth and google-auth-oauthlib (or maybe google-auth?) is outdated or soon to be.

How do I rewrite this code to use these new libraries in a way that best anticipates their current state and the eventual move to google-auth, etc.? In particular, is there a simple reimplementation of retrieval, storage, and use of credentials in the quickstart (below) that brings it up to date?

```<code>from __future__ import print_function
import httplib2
import os

from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage

try:
    import argparse
    flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
    flags = None

SCOPES = 'https://www.googleapis.com/auth/spreadsheets.readonly'
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'Google Sheets API Python Quickstart'

def get_credentials():
    home_dir = os.path.expanduser('~')
    credential_dir = os.path.join(home_dir, '.credentials')
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir, 'sheets.googleapis.com-python-quickstart.json')

    store = Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
        flow.user_agent = APPLICATION_NAME
        if flags:
            credentials = tools.run_flow(flow, store, flags)
        else: # Needed only for compatibility with Python 2.6
            credentials = tools.run(flow, store)
        print('Storing credentials to ' + credential_path)
    return credentials

def main():
    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    discoveryUrl =  'https://sheets.googleapis.com/$discovery/rest?version=v4'
    service = discovery.build('sheets', 'v4', http=http, discoveryServiceUrl=discoveryUrl)
    # etc. ...
</code>```

答:
How about this answer? I prepared the sample script for the Quickstart of Sheets API.

In this sample, it supposes below.

Sheet API is enabled

You have a client_secret.json.

In this sample, at first, refresh token is retrieved using authorization code. The refresh token is saved to sheets.googleapis.com-python-quickstart.json. After 1st run, the access token is retrieved by the refresh token.

In this sample, cell values are retrieved from spreadsheet.

Sample script :

```<code>import copy
import json
import os
import pprint

import google.oauth2.credentials
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow

pp = pprint.PrettyPrinter(indent=2)

CLIENT_SECRETS_FILE = "client_secret.json"

SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly']
API_SERVICE_NAME = 'sheets'
API_VERSION = 'v4'

def get_authenticated_service():
    credential_path = os.path.join("./", 'sheets.googleapis.com-python-quickstart.json')
    if os.path.exists(credential_path):
        with open(credential_path, 'r') as f:
            credential_params = json.load(f)
        credentials = google.oauth2.credentials.Credentials(
            credential_params["access_token"],
            refresh_token=credential_params["refresh_token"],
            token_uri=credential_params["token_uri"],
            client_id=credential_params["client_id"],
            client_secret=credential_params["client_secret"]
        )
    else:
        flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRETS_FILE, SCOPES)
        credentials = flow.run_console()
        with open(credential_path, 'w') as f:
            p = copy.deepcopy(vars(credentials))
            del p["expiry"]
            json.dump(p, f, indent=4)
    return build(API_SERVICE_NAME, API_VERSION, credentials=credentials)

def spreadsheets_get(service):
    spreadsheetId = "### spreadsheet ID ###"
    rangeName = "Sheet1!a1:a10"
    results = service.spreadsheets().get(
        spreadsheetId=spreadsheetId,
        ranges=rangeName
    ).execute()
    pp.pprint(results)

if __name__ == '__main__':
    os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'
    service = get_authenticated_service()
    spreadsheets_get(service)
</code>```

Note :

In order to save credentials, it was required to use oauth2client.file. So I prepared the sample script without using oauth2client.file. If you want to use oauth2client.file, please modify it.

I think that Quickstart for Sheets API may be also updated in the near future.

References :

References I refered to prepare this sample script are as follows.

Using OAuth 2.0 for Installed Applications

There is a sample script for python.

User Guide

google.oauth2.credentials module

Using OAuth 2.0 for Web Server Applications

If I misunderstand your question, I'm sorry.

Body:
The Google Sheets API Python Quickstart currently uses deprecated packages in its example code, where the use of oauth2client and httplib2 rather than google-auth and google-auth-oauthlib (or maybe google-auth?) is outdated or soon to be.

How do I rewrite this code to use these new libraries in a way that best anticipates their current state and the eventual move to google-auth, etc.? In particular, is there a simple reimplementation of retrieval, storage, and use of credentials in the quickstart (below) that brings it up to date?

from __future__ import print_function
import httplib2
import os

from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage

try:
    import argparse
    flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
    flags = None

SCOPES = 'https://www.googleapis.com/auth/spreadsheets.readonly'
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'Google Sheets API Python Quickstart'

def get_credentials():
    home_dir = os.path.expanduser('~')
    credential_dir = os.path.join(home_dir, '.credentials')
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir, 'sheets.googleapis.com-python-quickstart.json')

    store = Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
        flow.user_agent = APPLICATION_NAME
        if flags:
            credentials = tools.run_flow(flow, store, flags)
        else: # Needed only for compatibility with Python 2.6
            credentials = tools.run(flow, store)
        print('Storing credentials to ' + credential_path)
    return credentials

def main():
    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    discoveryUrl =  'https://sheets.googleapis.com/$discovery/rest?version=v4'
    service = discovery.build('sheets', 'v4', http=http, discoveryServiceUrl=discoveryUrl)
    # etc. ...

Body:
How about this answer? I prepared the sample script for the Quickstart of Sheets API.

In this sample, it supposes below.

Sheet API is enabled

You have a client_secret.json.

In this sample, at first, refresh token is retrieved using authorization code. The refresh token is saved to sheets.googleapis.com-python-quickstart.json. After 1st run, the access token is retrieved by the refresh token.

In this sample, cell values are retrieved from spreadsheet.

Sample script :

import copy
import json
import os
import pprint

import google.oauth2.credentials
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow

pp = pprint.PrettyPrinter(indent=2)

CLIENT_SECRETS_FILE = "client_secret.json"

SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly']
API_SERVICE_NAME = 'sheets'
API_VERSION = 'v4'

def get_authenticated_service():
    credential_path = os.path.join("./", 'sheets.googleapis.com-python-quickstart.json')
    if os.path.exists(credential_path):
        with open(credential_path, 'r') as f:
            credential_params = json.load(f)
        credentials = google.oauth2.credentials.Credentials(
            credential_params["access_token"],
            refresh_token=credential_params["refresh_token"],
            token_uri=credential_params["token_uri"],
            client_id=credential_params["client_id"],
            client_secret=credential_params["client_secret"]
        )
    else:
        flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRETS_FILE, SCOPES)
        credentials = flow.run_console()
        with open(credential_path, 'w') as f:
            p = copy.deepcopy(vars(credentials))
            del p["expiry"]
            json.dump(p, f, indent=4)
    return build(API_SERVICE_NAME, API_VERSION, credentials=credentials)

def spreadsheets_get(service):
    spreadsheetId = "### spreadsheet ID ###"
    rangeName = "Sheet1!a1:a10"
    results = service.spreadsheets().get(
        spreadsheetId=spreadsheetId,
        ranges=rangeName
    ).execute()
    pp.pprint(results)

if __name__ == '__main__':
    os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'
    service = get_authenticated_service()
    spreadsheets_get(service)

Note :

In order to save credentials, it was required to use oauth2client.file. So I prepared the sample script without using oauth2client.file. If you want to use oauth2client.file, please modify it.

I think that Quickstart for Sheets API may be also updated in the near future.

References :

References I refered to prepare this sample script are as follows.

Using OAuth 2.0 for Installed Applications

There is a sample script for python.

User Guide

google.oauth2.credentials module

Using OAuth 2.0 for Web Server Applications

If I misunderstand your question, I'm sorry.


问:
Built in function for searching sorted array in C
Is there a built in function in C for searching an integer array that has been sorted?

I can easily implement it but it seems like such a common thing - would be weird if there is no library/built in C function.

答:
you need bsearch, this link will take you to the manual and an example provided in that manual. alternatively in a linux box you can type </p>

```<code>man -a bsearch
</code>```

Body:
you need bsearch, this link will take you to the manual and an example provided in that manual. alternatively in a linux box you can type

man -a bsearch


问:
Scala: How to multiply a List of Lists by value
Now studying Scala and working with list of lists. Want to multiply array by an element(for example, 1).

However I get the following error:

identifier expected but integer constant found

Current code:

```<code>def multiply[A](listOfLists:List[List[A]]):List[List[A]] =
if (listOfLists == Nil) Nil
else -1 * listOfLists.head :: multiply(listOfLists.tail)
val tt = multiply[List[3,4,5,6];List[4,5,6,7,8]]
print(tt);;
</code>```

答:
There are a few issues with your code:

In general, you can't perform arithmetic on unconstrained generic types; somehow, you have to communicate any supported arithmetic operations.

Multiplying by 1 will typically have no effect anyway.

As already pointed out, you don't declare List instances using square brackets (they're used for declaring generic type arguments).

The arguments you're passing to multiply are two separate lists (using an invalid semicolon separator instead of a comma), not a list of lists.

In the if clause the return value is Nil, which matches the stated return type of List[List[A]]. However the else clause is trying to perform a calculation which is multiplying List instances (not the contents of the lists) by an Int. Even if this made sense, the resulting type is clearly not a List[List[A]]. (This also makes it difficult for me to understand exactly what it is you're trying to accomplish.)

Here's a version of your code that corrects the above, assuming that you're trying to multiply each member of the inner lists by a particular factor:

```<code>// Multiply every element in a list of lists by the specified factor, returning the
// resulting list of lists.
//
// Should work for any primitive numeric type (Int, Double, etc.). For custom value types,
// you will need to declare an `implicit val` of type Numeric[YourCustomType] with an
// appropriate implementation of the `Numeric[T]` trait. If in scope, the appropriate
// num value will be identified by the compiler and passed to the function automatically.
def multiply[A](ll: List[List[A]], factor: A)(implicit num: Numeric[A]): List[List[A]] = {

  // Numeric[T] trait defines a times method that we use to perform the multiplication.
  ll.map(_.map(num.times(_, factor)))
}

// Sample use: Multiply every value in the list by 5.
val tt = multiply(List(List(3, 4, 5, 6), List(4, 5, 6, 7, 8)), 5)
println(tt)
</code>```

This should result in the following output:

```<code>List(List(15, 20, 25, 30), List(20, 25, 30, 35, 40))
</code>```

However, it might be that you're just trying to multiply together all of the values in the lists. This is actually a little more straightforward (note the different return type):

```<code>def multiply[A](ll: List[List[A]])(implicit num: Numeric[A]): A = ll.flatten.product

// Sample use: Multiply all values in all lists together.
val tt = multiply(List(List(3, 4, 5, 6), List(4, 5, 6, 7, 8)))
println(tt)
</code>```

This should result in the following output:

```<code>2419200
</code>```

I'd recommend you read a good book on Scala. There's a lot of pretty sophisticated stuff going on in these examples, and it would take too long to explain it all here. A good start would be Programming in Scala, Third Edition by Odersky, Spoon & Venners. That will cover List[A] operations such as map, flatten and product as well as implicit function arguments and implicit val declarations.

Body:
Now studying Scala and working with list of lists. Want to multiply array by an element(for example, 1).

However I get the following error:

identifier expected but integer constant found

Current code:

def multiply[A](listOfLists:List[List[A]]):List[List[A]] =
if (listOfLists == Nil) Nil
else -1 * listOfLists.head :: multiply(listOfLists.tail)
val tt = multiply[List[3,4,5,6];List[4,5,6,7,8]]
print(tt);;

Body:
There are a few issues with your code:

In general, you can't perform arithmetic on unconstrained generic types; somehow, you have to communicate any supported arithmetic operations.

Multiplying by 1 will typically have no effect anyway.

As already pointed out, you don't declare List instances using square brackets (they're used for declaring generic type arguments).

The arguments you're passing to multiply are two separate lists (using an invalid semicolon separator instead of a comma), not a list of lists.

In the if clause the return value is Nil, which matches the stated return type of List[List[A]]. However the else clause is trying to perform a calculation which is multiplying List instances (not the contents of the lists) by an Int. Even if this made sense, the resulting type is clearly not a List[List[A]]. (This also makes it difficult for me to understand exactly what it is you're trying to accomplish.)

Here's a version of your code that corrects the above, assuming that you're trying to multiply each member of the inner lists by a particular factor:

// Multiply every element in a list of lists by the specified factor, returning the
// resulting list of lists.
//
// Should work for any primitive numeric type (Int, Double, etc.). For custom value types,
// you will need to declare an `implicit val` of type Numeric[YourCustomType] with an
// appropriate implementation of the `Numeric[T]` trait. If in scope, the appropriate
// num value will be identified by the compiler and passed to the function automatically.
def multiply[A](ll: List[List[A]], factor: A)(implicit num: Numeric[A]): List[List[A]] = {

  // Numeric[T] trait defines a times method that we use to perform the multiplication.
  ll.map(_.map(num.times(_, factor)))
}

// Sample use: Multiply every value in the list by 5.
val tt = multiply(List(List(3, 4, 5, 6), List(4, 5, 6, 7, 8)), 5)
println(tt)

This should result in the following output:

List(List(15, 20, 25, 30), List(20, 25, 30, 35, 40))

However, it might be that you're just trying to multiply together all of the values in the lists. This is actually a little more straightforward (note the different return type):

def multiply[A](ll: List[List[A]])(implicit num: Numeric[A]): A = ll.flatten.product

// Sample use: Multiply all values in all lists together.
val tt = multiply(List(List(3, 4, 5, 6), List(4, 5, 6, 7, 8)))
println(tt)

This should result in the following output:

2419200

I'd recommend you read a good book on Scala. There's a lot of pretty sophisticated stuff going on in these examples, and it would take too long to explain it all here. A good start would be Programming in Scala, Third Edition by Odersky, Spoon & Venners. That will cover List[A] operations such as map, flatten and product as well as implicit function arguments and implicit val declarations.


问:
Converting x86 to Y86
I'm trying to figure out to convert this x86 assembly code to Y86 form:

Given the c program:

```<code>  int sum(int x) {
     if (x == 0 || x ==1) {
        return 1;
     } else {
        return x + sum(x-1);
     }
  }
</code>```

The following x86-64 assembly code is generated:

```<code>sum:
    cmpl $1, %rdi
    ja .L8
    movl $1, %eax
    ret
.L8:
    pushq %rbx
    movl %edi, %ebx
    leal -1(%rdi), %edi
    call sum
    addl %ebx, %eax
    popq %rbx
    ret
</code>```

How can I convert this to Y86-64 assembly code that does the same thing?

Thank you!

答:
In this case, you can convert by replacing each instruction with a short sequence of y86 instructions which does exactly the same thing.

y86 is Turing complete, but very crippled, so in general you can't always easily convert.  Some single x86 instructions might need an entire loop or very long function to implement, but that's not the case for any of your instructions.  Each of them can be transliterated to one or a few y86 instructions.  (Some might need a scratch register; I forget if y86 has compare with immediate or only mov-immediate to register.)

Your code doesn't have any multiplies, shifts, or bsf, or floating-point, or anything else that y86 doesn't have (and would need a loop to emulate).

Look up each x86 instruction in the instruction-set reference manual (like this online version, or this older one where not having AVX/AVX2 instructions means less to wade through.  See also the x86 tag wiki for links to Intel and AMD's PDF manuals.)  Look at the Operation section where pseudo-code describes the exact effect of the instruction on the architectural state.  That's the behaviour you want to implement using y86 instructions.

As an example, I forget if y86 has push / pop, but if not you can always manipulate rsp directly and load/store.  e.g. sub $8, %rsp ; movrm  %rbx, (rsp) is push (except it clobbers flags where x86's push doesn't).

Title: Converting x86 to Y86

Body:
I'm trying to figure out to convert this x86 assembly code to Y86 form:

Given the c program:

  int sum(int x) {
     if (x == 0 || x ==1) {
        return 1;
     } else {
        return x + sum(x-1);
     }
  }

The following x86-64 assembly code is generated:

sum:
    cmpl $1, %rdi
    ja .L8
    movl $1, %eax
    ret
.L8:
    pushq %rbx
    movl %edi, %ebx
    leal -1(%rdi), %edi
    call sum
    addl %ebx, %eax
    popq %rbx
    ret

How can I convert this to Y86-64 assembly code that does the same thing?

Thank you!


问:
Align buttons to line up with fieldset
Background:The website I am working on there are several different filters that people can use in order to show only the data they need; basic stuff. To make things look nice since I am not css inclined, I am using bootstrap to make things look clean.

Problem: I can't seem to get the buttons to line up with the right side of the fields. I can make them pull to the very edge of the field set, I can make push/pull them to the general area they should be in, but I can't get them to line up nicely and stay that way regardless of how you rearrange the size of the page window.

JSFiddle: https://jsfiddle.net/v3cugpx1/1/

```<code><div class="form-group col-md-12">
    <div class="input-group-btn">
        <div class="pull-right">
            <a class="btn btn-info" href="#" title="Clear"><i class="glyphicon glyphicon-arrow-left"></i> Clear</a>
            <button class="btn btn-primary" title="Filter" type="submit"><i class="glyphicon glyphicon-search"></i> Filter</button>
        </div>
    </div>
</div>
</code>```

Any help would be greatly appreciated.

Cheers!

答:
It's important to match the nesting of columns because of the gutters in the grid, which the other answers remark upon. If you start with the other two answers, it's easy enough to modify them to add the margin between the buttons you're looking for:

```<code><div class="form-group col-md-12">
  <div class="col-md-12">
    <div class="btn-toolbar col-md-12">
      <a class="btn btn-info pull-right" href="#" title="Clear"><i class="glyphicon glyphicon-arrow-left"></i> Clear</a>
      <button class="btn btn-primary pull-right" title="Filter" type="submit"><i class="glyphicon glyphicon-search"></i> Filter</button>
    </div>
  </div>
</div>
</code>```

The only really real addition is the btn-toolbar class to the inner-most div. And for posterity here's the Fiddle.

Title: Align buttons to line up with fieldset

Body:
Background:The website I am working on there are several different filters that people can use in order to show only the data they need; basic stuff. To make things look nice since I am not css inclined, I am using bootstrap to make things look clean.

Problem: I can't seem to get the buttons to line up with the right side of the fields. I can make them pull to the very edge of the field set, I can make push/pull them to the general area they should be in, but I can't get them to line up nicely and stay that way regardless of how you rearrange the size of the page window.

JSFiddle: https://jsfiddle.net/v3cugpx1/1/

             Clear
            <button class="btn btn-primary" title="Filter" type="submit"> Filter</button>

Any help would be greatly appreciated.

Cheers!

Body:
It's important to match the nesting of columns because of the gutters in the grid, which the other answers remark upon. If you start with the other two answers, it's easy enough to modify them to add the margin between the buttons you're looking for:

<div class="form-group col-md-12">
  <div class="col-md-12">
    <div class="btn-toolbar col-md-12">
      <a class="btn btn-info pull-right" href="#" title="Clear"><i class="glyphicon glyphicon-arrow-left"></i> Clear</a>
      <button class="btn btn-primary pull-right" title="Filter" type="submit"><i class="glyphicon glyphicon-search"></i> Filter</button>
    </div>
  </div>
</div>

The only really real addition is the btn-toolbar class to the inner-most div. And for posterity here's the Fiddle.


问:
socket undefined inside of socket.on
I have the current code;

```<code>socket.on('KeyPress', function(data){
    var ply = PLAYER_LIST[socket.id];
    /* ... */
 });
</code>```

WebStorm is informing me that socket.id may not be initialized, and then when this event is triggered it does cause the error

```<code>TypeError: Cannot read property 'id' of undefined
</code>```

The whole code is inside of

```<code>io.sockets.on('connection', function(socket){ /*...*/ });
</code>```

Here is two of the on method I'm using;

In the first block you can see I'm doing the same thing yet it works..

Also on that note how secure is it to use socket.id to auth a user? Is it possible to force-set your own id?

答:
You are a victim of a bad practice of defining variables with var within a loop and then getting bit by the influence of "variable hoisting" where a variable defined with var anywhere in the function is automatically declared at the start of the function and then initialized where your assignment was, meaning it's undefined everywhere in your function before that.

The problem is this line of code:

```<code>var socket = SOCKET_LIST[i];
</code>```

That is redefining a local variable named socket that hides the one you actually want.  Variables defined with var are function scoped.  That means they are defined at the top of the function (this is called variable hoisting) and thus hides the other parent scoped socket variable.

Think of your function as starting like this:

```<code>socket.on('KeyPress', function(data) {
    var socket;       // this is hoisted from deeper inside the function
                      // and creates a new undefined socket variable
    var ply = PLAYER_LIST[socket.id];

    // other code here
});
</code>```

This is essentially how Javascript sees your code.  You can do a search on "Javascript variable hoisting" and see LOTS of articles written on the topic if you want more info.

The smallest change you can make it to change the name of this local variable to something else to it doesn't interfere with the parent scoped variable, but really this code structure is not ideal in the first place.

```<code>var localSocket = SOCKET_LIST[i];
var ply = PLAYER_LIST[p];
localSocket.emit(...)
</code>```

In general it's a bad practice to define a variable with var inside a for loop.  It leads to the "assumption" that it is scoped only to that loop, but in reality, it's scoped to the whole function and can mess with things outside of the loop.

In ES6, you can use let or const instead of var to declare a variable that is actually scoped to only the block of the loop.

Of other note, you should NEVER be iterating arrays with for/in.  That iterates all array properties (including other enumerable object properties), not just array elements.  ES6 adds for/of for iterating arrays this way.  In ES5, you can use the more traditional for loop or .forEach().

Title: socket undefined inside of socket.on

Body:
I have the current code;

socket.on('KeyPress', function(data){
    var ply = PLAYER_LIST[socket.id];
    /* ... */
 });

WebStorm is informing me that socket.id may not be initialized, and then when this event is triggered it does cause the error

TypeError: Cannot read property 'id' of undefined

The whole code is inside of

io.sockets.on('connection', function(socket){ /*...*/ });

Here is two of the on method I'm using;

In the first block you can see I'm doing the same thing yet it works..

Also on that note how secure is it to use socket.id to auth a user? Is it possible to force-set your own id?

Body:
You are a victim of a bad practice of defining variables with var within a loop and then getting bit by the influence of "variable hoisting" where a variable defined with var anywhere in the function is automatically declared at the start of the function and then initialized where your assignment was, meaning it's undefined everywhere in your function before that.

The problem is this line of code:

var socket = SOCKET_LIST[i];

That is redefining a local variable named socket that hides the one you actually want.  Variables defined with var are function scoped.  That means they are defined at the top of the function (this is called variable hoisting) and thus hides the other parent scoped socket variable.

Think of your function as starting like this:

socket.on('KeyPress', function(data) {
    var socket;       // this is hoisted from deeper inside the function
                      // and creates a new undefined socket variable
    var ply = PLAYER_LIST[socket.id];

    // other code here
});

This is essentially how Javascript sees your code.  You can do a search on "Javascript variable hoisting" and see LOTS of articles written on the topic if you want more info.

The smallest change you can make it to change the name of this local variable to something else to it doesn't interfere with the parent scoped variable, but really this code structure is not ideal in the first place.

var localSocket = SOCKET_LIST[i];
var ply = PLAYER_LIST[p];
localSocket.emit(...)

In general it's a bad practice to define a variable with var inside a for loop.  It leads to the "assumption" that it is scoped only to that loop, but in reality, it's scoped to the whole function and can mess with things outside of the loop.

In ES6, you can use let or const instead of var to declare a variable that is actually scoped to only the block of the loop.

Of other note, you should NEVER be iterating arrays with for/in.  That iterates all array properties (including other enumerable object properties), not just array elements.  ES6 adds for/of for iterating arrays this way.  In ES5, you can use the more traditional for loop or .forEach().


问:
Actionscript - Obtain the name of the current function
I want to get the name of a function from inside that function. e.g.:

```<code>function blah() {
    //I want to get the string "blah" here, from the function's name
}
</code>```

Or at least the Function object?

答:
You probably wont be able to get the name of a function, because they don't really have a "name" as such. Just like your variables don't have names. They are just pointers to an object.

Getting the name doesn't make sense, partly due to the following example:

```<code>function foo():void
{
    //get function name.
}
var bar:Function = foo;
bar();
</code>```

A function is just like any other object/variable. What "name" would this function find? "foo"? or "bar"? Both foo and bar are referencing the same variable of type Function.

A better way to handle this would be to pass something in to the function as an argument:

```<code>function foo(myName:String):void
{
    trace(myName);
}
</code>```

You can however, get a reference to the current function using the arguments.callee :)

Body:
I want to get the name of a function from inside that function. e.g.:

function blah() {
    //I want to get the string "blah" here, from the function's name
}

Or at least the Function object?

Body:
You probably wont be able to get the name of a function, because they don't really have a "name" as such. Just like your variables don't have names. They are just pointers to an object.

Getting the name doesn't make sense, partly due to the following example:

function foo():void
{
    //get function name.
}
var bar:Function = foo;
bar();

A function is just like any other object/variable. What "name" would this function find? "foo"? or "bar"? Both foo and bar are referencing the same variable of type Function.

A better way to handle this would be to pass something in to the function as an argument:

function foo(myName:String):void
{
    trace(myName);
}

You can however, get a reference to the current function using the arguments.callee :)


问:
Excel multiple VBA run in different cells and sheets
my VBA code stoping when i run another VBA.
i create count timer with 3 buttons, start, stop, reset plus show current time(All VBA)
I need 15 colums with this repeat. The problem start when i click Button1(start count time) or another(no matther) it stops other my codes(Current time, and start,stop,reset buttons of count time) works only button which i click first after run code. How  can i run multiple VBA code that all worked together and did not interfere with each other.
Sorry for my English.enter image description here
My VBA for start, stop, reset.

```<code>Public StopIt As Boolean
Public ResetIt As Boolean
Public LastTime
Private Sub CommandButton1_Click()
Dim StartTime, FinishTime, TotalTime, PauseTime
StopIt = False
ResetIt = False
If Range("C2") = 0 Then
  StartTime = Timer
  PauseTime = 0
  LastTime = 0
Else
  StartTime = 0
  PauseTime = Timer
End If
StartIt:
  DoEvents
  If StopIt = True Then
    LastTime = TotalTime
    Exit Sub
  Else
    FinishTime = Timer
    TotalTime = FinishTime - StartTime + LastTime - PauseTime
    TTime = TotalTime * 100
    HM = TTime Mod 100
    TTime = TTime \ 100
    hh = TTime \ 3600
    TTime = TTime Mod 3600
    MM = TTime \ 60
    SS = TTime Mod 60
    Range("C2").Value = Format(hh, "00") & ":" & Format(MM, "00") & ":" & Format(SS, "00") & "." & Format(HM, "00")
    If ResetIt = True Then
      Range("C2") = Format(0, "00") & ":" & Format(0, "00") & ":" & Format(0, "00") & "." & Format(0, "00")
      LastTime = 0
      PauseTime = 0
      End
    End If
    GoTo StartIt
  End If
End Sub
Private Sub CommandButton2_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
  StopIt = True
End Sub
Private Sub CommandButton3_Click()
  Range("C2").Value = Format(0, "00") & ":" & Format(0, "00") & ":" & Format(0, "00") & "." & Format(0, "00")
  LastTime = 0
  ResetIt = True
End Sub
</code>```

Current time:

```<code>Private sub workbook
dim hour as boolean
hour = not (hour)
do while hour = true
doevents
range ("A1") = timevalue(now)
loop
end sub
</code>```

答:
here is a simple demo code that runs a main loop and services button presses without stopping the main loop ( it still takes away from main loop though )

you have to add code to do other functions

speed up the code by letting cell formulas do all the calculations

on a worksheet, place 1 button and three toggle-buttons

put this code into worksheet also

```<code>Option Explicit

Dim doFive As Boolean
Dim doSix As Boolean
Dim doSeven As Boolean

Private Sub CommandButton1_Click()      ' could be started other ways

    doFive = ToggleButton1              ' this one affects cell G5
    doSix = ToggleButton2               ' G6
    doSeven = ToggleButton3             ' G7

    While True                          ' main demo service loop

        DoEvents                        ' this allows other events to be serviced (like button presses)

        If doFive Then Range("g5") = Range("g5") + 1
        If doSix Then Range("g6") = Range("g6") + 1
        If ToggleButton3 Then Range("g7") = Range("g7") + 1
    Wend

End Sub

Private Sub ToggleButton1_Click()

    doFive = ToggleButton1

End Sub

Private Sub ToggleButton2_Click()

    doSix = ToggleButton2

End Sub
</code>```

Body:
my VBA code stoping when i run another VBA.
i create count timer with 3 buttons, start, stop, reset plus show current time(All VBA)
I need 15 colums with this repeat. The problem start when i click Button1(start count time) or another(no matther) it stops other my codes(Current time, and start,stop,reset buttons of count time) works only button which i click first after run code. How  can i run multiple VBA code that all worked together and did not interfere with each other.
Sorry for my English.enter image description here
My VBA for start, stop, reset.

Public StopIt As Boolean
Public ResetIt As Boolean
Public LastTime
Private Sub CommandButton1_Click()
Dim StartTime, FinishTime, TotalTime, PauseTime
StopIt = False
ResetIt = False
If Range("C2") = 0 Then
  StartTime = Timer
  PauseTime = 0
  LastTime = 0
Else
  StartTime = 0
  PauseTime = Timer
End If
StartIt:
  DoEvents
  If StopIt = True Then
    LastTime = TotalTime
    Exit Sub
  Else
    FinishTime = Timer
    TotalTime = FinishTime - StartTime + LastTime - PauseTime
    TTime = TotalTime * 100
    HM = TTime Mod 100
    TTime = TTime \ 100
    hh = TTime \ 3600
    TTime = TTime Mod 3600
    MM = TTime \ 60
    SS = TTime Mod 60
    Range("C2").Value = Format(hh, "00") & ":" & Format(MM, "00") & ":" & Format(SS, "00") & "." & Format(HM, "00")
    If ResetIt = True Then
      Range("C2") = Format(0, "00") & ":" & Format(0, "00") & ":" & Format(0, "00") & "." & Format(0, "00")
      LastTime = 0
      PauseTime = 0
      End
    End If
    GoTo StartIt
  End If
End Sub
Private Sub CommandButton2_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
  StopIt = True
End Sub
Private Sub CommandButton3_Click()
  Range("C2").Value = Format(0, "00") & ":" & Format(0, "00") & ":" & Format(0, "00") & "." & Format(0, "00")
  LastTime = 0
  ResetIt = True
End Sub

Current time:

Private sub workbook
dim hour as boolean
hour = not (hour)
do while hour = true
doevents
range ("A1") = timevalue(now)
loop
end sub

Body:
here is a simple demo code that runs a main loop and services button presses without stopping the main loop ( it still takes away from main loop though )

you have to add code to do other functions

speed up the code by letting cell formulas do all the calculations

on a worksheet, place 1 button and three toggle-buttons

put this code into worksheet also

Option Explicit

Dim doFive As Boolean
Dim doSix As Boolean
Dim doSeven As Boolean

Private Sub CommandButton1_Click()      ' could be started other ways

    doFive = ToggleButton1              ' this one affects cell G5
    doSix = ToggleButton2               ' G6
    doSeven = ToggleButton3             ' G7

    While True                          ' main demo service loop

        DoEvents                        ' this allows other events to be serviced (like button presses)

        If doFive Then Range("g5") = Range("g5") + 1
        If doSix Then Range("g6") = Range("g6") + 1
        If ToggleButton3 Then Range("g7") = Range("g7") + 1
    Wend

End Sub

Private Sub ToggleButton1_Click()

    doFive = ToggleButton1

End Sub

Private Sub ToggleButton2_Click()

    doSix = ToggleButton2

End Sub


问:
How do I convert a string in JavaScript to a sequence of bytes?
In Python 3, to convert a string to sequence of bytes, one uses String.encode(ENCODING) where ENCODING is the name of the encoding to use. If I have a character in my string that has a code point greater than 255, then it will still be converted to an array of bytes. This is useful if one needs to operate on the stringfor something like a demo of a cipher. The text can reconstructed by using ByteArray.decode(ENCODING).

I haven't seen anything similar for JavaScript. There is String.charCodeAt(), but this would convert a character like Ā to 256. That's not what I want.

答:
"operate on the string for … a cipher": Probably not.

Ciphers are mathematical transformations of byte arrays. The result of encryption is not text so it can't be directly stored in a string.

A JavaScript string is a counted sequence of UTF-16 code units. (Also applies to VB4/5/6, VB, VBA, VBScript, C#, Java….) UTF-16 is one of several encoding of the Unicode character set. UTF-8 is another. Neither encodes to/decodes from arbitrary binary data.

You mentioned String.charCodeAt(). This just gives you one of the UTF-16 code units from the string.

Common ways of carrying and displaying binary data in strings are Base64 and hexadecimal. It's a bit weightier that way—and sender and receiver have to agree on both the character encoding of the string and the binary-to-text transformation—but many systems would rather pass text than binary.