问:
Swing form clears but data is still retained
I have a swing form that I enter 4 values into and then a test file is generated based on 1 of the 4 available buttons being clicked.

The problem I am running into though is if I don't exit out after each use if I click a button twice the previous click's data is used to generate the 2nd file.

I thought clearing everything might fix it, and that made it so I could click 2 separate buttons and not have the 1st run's data in the 2nd's, but I'm not sure how to fix clicking the same button twice.

```<code>package GUI;
import Generators.*;

import javax.swing.*;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerConfigurationException;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Test_File_Generator implements  ActionListener {
JLabel intro;
JButton standard;
JButton ts;
JButton fa;
JButton fd;

JLabel name;
JButton testcaseFile;
JButton fullFile;

JLabel prefix;
JLabel sponsor;
JLabel email;
JLabel numRec;

JFrame frame;

public static JTextField prefixText;
public static JTextField sponsorText;
public static JTextField emailText;
public static JTextField numRecText;

JButton generate;
JButton clear;

Test_File_Generator() {
    JFrame jpn = new JFrame("Test File Generator");
    jpn.setLayout(new FlowLayout());
    jpn.setSize(400, 400);
    jpn.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    intro = new JLabel("               Select a PCI Data Feed Type               ");
    standard = new JButton("Standard");
    tsys = new JButton("TS");
    faps = new JButton("FA");
    fdc = new JButton("FD");

    name = new JLabel("          Select the type of Standard File to generate         ");
    testcaseFile = new JButton("TC File");
    fullFile = new JButton("Full File");

    //Create text fields and labels
    prefix = new JLabel("Enter a Prefix: ");
    prefixText = new JTextField(30);
    sponsor = new JLabel("Enter a Sponsor: ");
    sponsorText = new JTextField(30);
    email = new JLabel("Enter a Email: ");
    emailText = new JTextField(30);
    numRec = new JLabel("Enter the number of records needed: ");
    numRecText = new JTextField(30);
    generate = new JButton("Generate");
    clear = new JButton("Clear");

    //jpn.add(new JSplitPane(JSplitPane.HORIZONTAL_SPLIT));

    jpn.add(prefix);
    jpn.add(prefixText);
    jpn.add(sponsor);
    jpn.add(sponsorText);
    jpn.add(email);
    jpn.add(emailText);
    jpn.add(numRec);
    jpn.add(numRecText);
    //jpn.add(name);

   // jpn.add(testcaseFile);
    //jpn.add(fullFile);

    jpn.add(intro);
    jpn.add(standard);
    jpn.add(ts);
    jpn.add(fa);
    jpn.add(fd);

    standard.addActionListener(this);
    ts.addActionListener(this);
    fa.addActionListener(this);
    fd.addActionListener(this);

    jpn.setVisible(true);

}

public static void main(String[] args) {
    //Create the frame on the event dispatching thread
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            new Test_File_Generator();
        }
    });
}

public void clearText(){
    prefixText.setText("");
    sponsorText.setText("");
    emailText.setText("");
    numRecText.setText("");
}

public void actionPerformed(ActionEvent e) {
    if(e.getSource().equals(standard)) SwingUtilities.invokeLater(new Runnable() {

        @Override
        public void run() {
            if (prefixText.getText().equals("") || sponsorText.getText().equals("") || emailText.getText().equals("") || numRecText.getText().equals("")) {
                JOptionPane.showMessageDialog(frame, "All Fields Must Be Filled!");
            } else {
                new WFfgenerator().main();
                clearText();

            }
    }
    });

    else if(e.getSource().equals(ts)) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                if (prefixText.getText().equals("") || sponsorText.getText().equals("") || emailText.getText().equals("") || numRecText.getText().equals("")) {
                    JOptionPane.showMessageDialog(frame, "All Fields Must Be Filled!");
                } else {
                    try {
                        new TS_RecordCreator().main();
                    } catch (ParserConfigurationException e1) {
                        e1.printStackTrace();
                    }
                }
            }

        });
    } else if(e.getSource().equals(fa)) {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    if (prefixText.getText().equals("") || sponsorText.getText().equals("") || emailText.getText().equals("") || numRecText.getText().equals("")) {
                        JOptionPane.showMessageDialog(frame, "All Fields Must Be Filled!");
                    } else {
                        try {
                            new FA_generator().main();
                        } catch (TransformerConfigurationException e1) {
                            e1.printStackTrace();
                        }
                    }
                }
            });
} else {
        if(e.getSource().equals(fd)) {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    if (prefixText.getText().equals("") || sponsorText.getText().equals("") || emailText.getText().equals("") || numRecText.getText().equals("")) {
                        JOptionPane.showMessageDialog(frame, "All Fields Must Be Filled!");
                    } else {
                        new FDmerchant_generator().main();
                    }
                }
            });
        }
    }
}
</code>```

}

答:
I was looking at this issue wrong, but was able to solve it.  I was trying to have the text cleared at the base form level.  Where it needed to be cleared was when it called the method.

I fixed this by going into each method that was called by a button push, and at the end of it, putting in variables to clear out the values.

I also added that same code to be executed after each button push so that I start with a blank form each time.

I also looked through everyone's comments and got rid of the swingUtility Invoke later calls.

Body:
I have a swing form that I enter 4 values into and then a test file is generated based on 1 of the 4 available buttons being clicked.

The problem I am running into though is if I don't exit out after each use if I click a button twice the previous click's data is used to generate the 2nd file.

I thought clearing everything might fix it, and that made it so I could click 2 separate buttons and not have the 1st run's data in the 2nd's, but I'm not sure how to fix clicking the same button twice.

package GUI;
import Generators.*;

import javax.swing.*;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerConfigurationException;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Test_File_Generator implements  ActionListener {
JLabel intro;
JButton standard;
JButton ts;
JButton fa;
JButton fd;

JLabel name;
JButton testcaseFile;
JButton fullFile;

JLabel prefix;
JLabel sponsor;
JLabel email;
JLabel numRec;

JFrame frame;

public static JTextField prefixText;
public static JTextField sponsorText;
public static JTextField emailText;
public static JTextField numRecText;

JButton generate;
JButton clear;

Test_File_Generator() {
    JFrame jpn = new JFrame("Test File Generator");
    jpn.setLayout(new FlowLayout());
    jpn.setSize(400, 400);
    jpn.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    intro = new JLabel("               Select a PCI Data Feed Type               ");
    standard = new JButton("Standard");
    tsys = new JButton("TS");
    faps = new JButton("FA");
    fdc = new JButton("FD");

    name = new JLabel("          Select the type of Standard File to generate         ");
    testcaseFile = new JButton("TC File");
    fullFile = new JButton("Full File");

    //Create text fields and labels
    prefix = new JLabel("Enter a Prefix: ");
    prefixText = new JTextField(30);
    sponsor = new JLabel("Enter a Sponsor: ");
    sponsorText = new JTextField(30);
    email = new JLabel("Enter a Email: ");
    emailText = new JTextField(30);
    numRec = new JLabel("Enter the number of records needed: ");
    numRecText = new JTextField(30);
    generate = new JButton("Generate");
    clear = new JButton("Clear");

    //jpn.add(new JSplitPane(JSplitPane.HORIZONTAL_SPLIT));

    jpn.add(prefix);
    jpn.add(prefixText);
    jpn.add(sponsor);
    jpn.add(sponsorText);
    jpn.add(email);
    jpn.add(emailText);
    jpn.add(numRec);
    jpn.add(numRecText);
    //jpn.add(name);

   // jpn.add(testcaseFile);
    //jpn.add(fullFile);

    jpn.add(intro);
    jpn.add(standard);
    jpn.add(ts);
    jpn.add(fa);
    jpn.add(fd);

    standard.addActionListener(this);
    ts.addActionListener(this);
    fa.addActionListener(this);
    fd.addActionListener(this);

    jpn.setVisible(true);

}

public static void main(String[] args) {
    //Create the frame on the event dispatching thread
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            new Test_File_Generator();
        }
    });
}

public void clearText(){
    prefixText.setText("");
    sponsorText.setText("");
    emailText.setText("");
    numRecText.setText("");
}

public void actionPerformed(ActionEvent e) {
    if(e.getSource().equals(standard)) SwingUtilities.invokeLater(new Runnable() {

        @Override
        public void run() {
            if (prefixText.getText().equals("") || sponsorText.getText().equals("") || emailText.getText().equals("") || numRecText.getText().equals("")) {
                JOptionPane.showMessageDialog(frame, "All Fields Must Be Filled!");
            } else {
                new WFfgenerator().main();
                clearText();

            }
    }
    });

    else if(e.getSource().equals(ts)) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                if (prefixText.getText().equals("") || sponsorText.getText().equals("") || emailText.getText().equals("") || numRecText.getText().equals("")) {
                    JOptionPane.showMessageDialog(frame, "All Fields Must Be Filled!");
                } else {
                    try {
                        new TS_RecordCreator().main();
                    } catch (ParserConfigurationException e1) {
                        e1.printStackTrace();
                    }
                }
            }

        });
    } else if(e.getSource().equals(fa)) {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    if (prefixText.getText().equals("") || sponsorText.getText().equals("") || emailText.getText().equals("") || numRecText.getText().equals("")) {
                        JOptionPane.showMessageDialog(frame, "All Fields Must Be Filled!");
                    } else {
                        try {
                            new FA_generator().main();
                        } catch (TransformerConfigurationException e1) {
                            e1.printStackTrace();
                        }
                    }
                }
            });
} else {
        if(e.getSource().equals(fd)) {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    if (prefixText.getText().equals("") || sponsorText.getText().equals("") || emailText.getText().equals("") || numRecText.getText().equals("")) {
                        JOptionPane.showMessageDialog(frame, "All Fields Must Be Filled!");
                    } else {
                        new FDmerchant_generator().main();
                    }
                }
            });
        }
    }
}

}


来源: stackexchange

问:
Decrease the increase of value in database
My starting value is 18, for every +1 increase in that number the increase of value should decrease. Basically so it gets harder to inrease this value if you have more of it. The increase should be of 2% less that the previous increase as shown below.

Right now i only got a steady increase of 2 for every run.

```<code>$Strengthvalue = 2 + $row['strength'];
</code>```

18 = +2 (increase)

19 = +1.96 (increase)

20 = +1.92 (increase)

答:
If you want to be exact without rounding issues I suggest using a recursive approach:</p>

```<code><?php

function calculate_increase($current_strength) {
  if($current_strength == 18) {
      return 2;
  }

  return 0.98 * calculate_increase($current_strength-1);
}
//calculate_increase(20) == 1.9208
</code>```

ContentLicense: CC BY-SA 3.0

Body:
My starting value is 18, for every +1 increase in that number the increase of value should decrease. Basically so it gets harder to inrease this value if you have more of it. The increase should be of 2% less that the previous increase as shown below.

Right now i only got a steady increase of 2 for every run.

$Strengthvalue = 2 + $row['strength'];

18 = +2 (increase)

19 = +1.96 (increase)

20 = +1.92 (increase)

Body:
If you want to be exact without rounding issues I suggest using a recursive approach:

<?php

function calculate_increase($current_strength) {
  if($current_strength == 18) {
      return 2;
  }

  return 0.98 * calculate_increase($current_strength-1);
}
//calculate_increase(20) == 1.9208


问:
How do I calculate the date six months from the current date using the datetime Python module?
I am using the datetime Python module.  I am looking to calculate the date 6 months from the current date. Could someone give me a little help doing this?

The reason I want to generate a date 6 months from the current date is to produce a review date.  If the user enters data into the system it will have a review date of 6 months from the date they entered the data.

答:
Using below given function you can get date after/before x months.</p>

```
from datetime import date

def next_month(given_date, month):
    yyyy = int(((given_date.year * 12 + given_date.month) + month)/12)
    mm = int(((given_date.year * 12 + given_date.month) + month)%12)

    if mm == 0:
        yyyy -= 1
        mm = 12
    return given_date.replace(year=yyyy, month=mm)

if __name__ == "__main__":
    today = date.today()
    print(today)

    for mm in [-12, -1, 0, 1, 2, 12, 20 ]:
        next_date = next_month(today, mm)
        print(next_date)
```

OwnerDisplayName: Eef

ContentLicense: CC BY-SA 4.0

LastEditorDisplayName: Eef

Body:
Using below given function you can get date after/before x months.

from datetime import date

def next_month(given_date, month):
    yyyy = int(((given_date.year * 12 + given_date.month) + month)/12)
    mm = int(((given_date.year * 12 + given_date.month) + month)%12)

    if mm == 0:
        yyyy -= 1
        mm = 12
    return given_date.replace(year=yyyy, month=mm)

if __name__ == "__main__":
    today = date.today()
    print(today)

    for mm in [-12, -1, 0, 1, 2, 12, 20 ]:
        next_date = next_month(today, mm)
        print(next_date)


问:
How do i concat the Int or Long to a List in Scala?
I have this:

```<code>val vertexIdListPartitions: TrieMap[Long, List[Long]]
</code>```

I need to have something like this:

vertexIdListPartitions(0) -> List[2,3,4,5,etc..]

But when I add numbers in the list in this way:

```<code>for(c<- 0 to 10)
   vertexIdListPartitions.update(0,List(c))
</code>```

The result is List[10]

How can I concat them?

答:
If I understand your question right, you don't need a for loop:

```<code>import scala.collection.concurrent.TrieMap

val vertexIdListPartitions = TrieMap[Long, List[Long]]()

vertexIdListPartitions.update(0, (0L to 10L).toList)
// res1: scala.collection.concurrent.TrieMap[Long,List[Long]] =
// TrieMap(0 -> List(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10))
</code>```

[UPDATE]

Below is a method for adding or concatenating a key-value tuple to the TrieMap accordingly:

```<code>def concatTM( tm: TrieMap[Long, List[Long]], kv: Tuple2[Long, List[Long]] ) =
  tm += ( tm.get(kv._1) match {
    case Some(l: List[Long]) => (kv._1 -> (l ::: kv._2))
    case None => kv
  } )

concatTM( vertexIdListPartitions, (1L, List(1L, 2L, 3L)) )
// res2: scala.collection.concurrent.TrieMap[Long,List[Long]] =
// TrieMap(0 -> List(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10), 1 -> List(1, 2, 3))

concatTM( vertexIdListPartitions, (0L, List(11L, 12L)) )
// res61: scala.collection.concurrent.TrieMap[Long,List[Long]] =
// TrieMap(0 -> List(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12), 1 -> List(1, 2, 3))
</code>```

Body:
I have this:

val vertexIdListPartitions: TrieMap[Long, List[Long]]

I need to have something like this:

vertexIdListPartitions(0) -> List[2,3,4,5,etc..]

But when I add numbers in the list in this way:

for(c<- 0 to 10)
   vertexIdListPartitions.update(0,List(c))

The result is List[10]

How can I concat them?

Body:
If I understand your question right, you don't need a for loop:

import scala.collection.concurrent.TrieMap

val vertexIdListPartitions = TrieMap[Long, List[Long]]()

vertexIdListPartitions.update(0, (0L to 10L).toList)
// res1: scala.collection.concurrent.TrieMap[Long,List[Long]] =
// TrieMap(0 -> List(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10))

[UPDATE]

Below is a method for adding or concatenating a key-value tuple to the TrieMap accordingly:

def concatTM( tm: TrieMap[Long, List[Long]], kv: Tuple2[Long, List[Long]] ) =
  tm += ( tm.get(kv._1) match {
    case Some(l: List[Long]) => (kv._1 -> (l ::: kv._2))
    case None => kv
  } )

concatTM( vertexIdListPartitions, (1L, List(1L, 2L, 3L)) )
// res2: scala.collection.concurrent.TrieMap[Long,List[Long]] =
// TrieMap(0 -> List(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10), 1 -> List(1, 2, 3))

concatTM( vertexIdListPartitions, (0L, List(11L, 12L)) )
// res61: scala.collection.concurrent.TrieMap[Long,List[Long]] =
// TrieMap(0 -> List(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12), 1 -> List(1, 2, 3))


问:
C++ subclassing access modifier?
I'm C++ newbie, and I have many years of experience about OO languages such as C/C#/Objective-C. Now, I'm learning C++.

I saw this C++ code:

```<code>    class World : public State
    {
    };
</code>```

It seems class World inherits the class State publicly.
Public subclassing? It's hard to understand.

What's the concept of this feature?
And when is this useful or required?

答:
In case

```<code>class World: private State
{
};
</code>```

private inheritance means that all public and protected members of State would be inherited by World and would become private.  This seals State inside World.  No class that inherits from World will be able access any features of State.

Title: C++ subclassing access modifier?

Body:
I'm C++ newbie, and I have many years of experience about OO languages such as C/C#/Objective-C. Now, I'm learning C++.

I saw this C++ code:

    class World : public State
    {
    };

It seems class World inherits the class State publicly.
Public subclassing? It's hard to understand.

What's the concept of this feature?
And when is this useful or required?

Body:
In case

class World: private State
{
};

private inheritance means that all public and protected members of State would be inherited by World and would become private.  This seals State inside World.  No class that inherits from World will be able access any features of State.

ContentLicense: CC BY-SA 2.5


问:
Custom theme interferes with snackbar background color
Trying out the new Design Support Library, I added a snackbar; but unlike its main background, the text area is not colored with the default value of #323232. Instead, it looks like this. It seems to take its color from the android:background value defined in the custom theme in my styles.xml, which goes like this:

```<code><style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    ...
    <item name="android:background">#4f4f5e</item>
    ...
</style>
</code>```

If I try to forcefully color it with

```<code>View snackbarView = snackbar.getView();
snackbarView.setBackgroundColor(Color.YELLOW);
</code>```

it only impacts the main background, like this, and the text background still gets colored by the custom theme. Is there a way to both keep my custom theme, and have a standard snackbar? Thanks!

答:
I also faced similar issue & unfortunately no solution works for me Hence I write my own solution where I set background color for parent view too. </p>

```<code>    TextView snackbarTextView = snackbar.getView().findViewById(android.support.design.R.id.snackbar_text);
    snackbarTextView.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.colorPrimary));

    ViewParent parentView = snackbarTextView.getParent();
    if (parentView instanceof View) {
        ((View) parentView).setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.colorPrimary));
    }

    View snackbarView = snackbar.getView();
    snackbarView.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.colorPrimary));

    snackbar.show();
</code>```

Body:
Trying out the new Design Support Library, I added a snackbar; but unlike its main background, the text area is not colored with the default value of #323232. Instead, it looks like this. It seems to take its color from the android:background value defined in the custom theme in my styles.xml, which goes like this:

If I try to forcefully color it with

View snackbarView = snackbar.getView();
snackbarView.setBackgroundColor(Color.YELLOW);

it only impacts the main background, like this, and the text background still gets colored by the custom theme. Is there a way to both keep my custom theme, and have a standard snackbar? Thanks!

Body:
I also faced similar issue & unfortunately no solution works for me Hence I write my own solution where I set background color for parent view too.

    TextView snackbarTextView = snackbar.getView().findViewById(android.support.design.R.id.snackbar_text);
    snackbarTextView.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.colorPrimary));

    ViewParent parentView = snackbarTextView.getParent();
    if (parentView instanceof View) {
        ((View) parentView).setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.colorPrimary));
    }

    View snackbarView = snackbar.getView();
    snackbarView.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.colorPrimary));

    snackbar.show();


问:
I can't input text into my form that is inside a jQuery UI accordion
Like the title says, I have a form with a single input and button inside of a jQuery UI Accordion content div and I can't type any text into it when I test it out. I can also not click the button.

Here is the HTML:

```<code><button type="button" id="ic-open-report"><i class="fa fa-envelope"></i><p>Export Savings Report</p></buttOn>
                    <div id="ic-savings-report">
                        <h4>Export a PDF Savings Report</h4>
                            <div>
                            <form method="POST" class="savings-report">

                                        <input style="user-select: text;" type="email" id="ic-email"  placeholder="Email">
                                        <button type="submit" >Export</button>
                            </form>
                            </div>
                    </div>
</code>```

Here is the jQuery:

```<code>$('#ic-savings-report').accordion({
    collapsible: true,
    active: false,
    animate: 400
});
$('#ic-savings-report').hide();

$('#ic-open-report').click(function(){
    $('#ic-savings-report').toggle(700);
    setTimeout("$( '#ic-savings-report' ).accordion( 'option', 'active', 0       );", 1000);
});
</code>```

I'm not even sure why this would happen. Why would I be unable to edit the input?

Here is a link to the actual project:
http://lcstuff.000webhostapp.com/intellifrost-calculator/

答:
I came across this problem and jquery ui was setting the font-size: 1em on this element .ui-widget input and for some reason this made the text invisible. So it gave the impression that I couldn't input any text as no text was showing when I typed.

I just set it to the following to fix it:

```<code>font-size: 14px;
</code>```

Body:
Like the title says, I have a form with a single input and button inside of a jQuery UI Accordion content div and I can't type any text into it when I test it out. I can also not click the button.

Here is the HTML:

<button type="button" id="ic-open-report">
Export Savings Report
</buttOn>

Export a PDF Savings Report

                            <form method="POST" class="savings-report">

                                        <input style="user-select: text;" type="email" id="ic-email"  placeholder="Email">
                                        <button type="submit" >Export</button>
                            </form>

Here is the jQuery:

$('#ic-savings-report').accordion({
    collapsible: true,
    active: false,
    animate: 400
});
$('#ic-savings-report').hide();

$('#ic-open-report').click(function(){
    $('#ic-savings-report').toggle(700);
    setTimeout("$( '#ic-savings-report' ).accordion( 'option', 'active', 0       );", 1000);
});

I'm not even sure why this would happen. Why would I be unable to edit the input?

Here is a link to the actual project:
http://lcstuff.000webhostapp.com/intellifrost-calculator/

Body:
I came across this problem and jquery ui was setting the font-size: 1em on this element .ui-widget input and for some reason this made the text invisible. So it gave the impression that I couldn't input any text as no text was showing when I typed.

I just set it to the following to fix it:

font-size: 14px;


问:
Azure Container Instances stuck in "Creating" state
Whether I have the azure agent plugin for Jenkins make my container, or if I do it manually, it seems like either way it never enters a running state.

```<code>az container create \
    --os-type Windows \
    --location eastus \
    --registry-login-server SERVER.azurecr.io \
    --registry-password PASSWORD \
    --registry-username USERNAME \
    --image namespace/image \
    --name jenkins-permanent \
    --resource-group devops-aci \
    --cpu 2 \
    --memory 3.5 \
    --restart-policy Always \
    --command-line "-jnlpUrl http://host:8080/computer/NAME/slave-agent.jnlp -secret SECRET -workDir \"C:\\jenkins\""
</code>```

I've gone through all the troubleshooting steps that apply, tried a different region, but to no avail.

Here's a current event that I got which seems to be the most progress I've had yet:

```<code>          {
            "count": 1,
            "firstTimestamp": "2017-12-07T03:02:56+00:00",
            "lastTimestamp": "2017-12-07T03:02:56+00:00",
            "message": "Failed to pull image \"MYREPO.azurecr.io/my-company/windows-agent:latest\": Error response from da
emon: {\"message\":\"Get https://MYREPO.azurecr.io/v2/: net/http: request canceled while waiting for connection (Client.Timeout
exceeded while awaiting headers)\"}",
            "name": "Failed",
            "type": "Warning"
          }
</code>```

The funny thing is, this event happens before and after one case of the instance working (but unfortunately my entrypoint command was wrong, so it never started).

I really feel like Azure is punting on this and I just have no way to change the order I do anything.  It's simply one command.

答:
Alexander, here's a lead to actually check what could be causing the delay, or if the deployment has failed in the background, this information would be critical to narrow down what the issue is: https://learn.microsoft.com/en-us/azure/azure-resource-manager/resource-manager-troubleshoot-tips#determine-error-code

From the article above check on deployment logs:
Enable debug logging:
PowerShell
In PowerShell, set the DeploymentDebugLogLevel parameter to All, ResponseContent, or RequestContent.

```<code>New-AzureRmResourceGroupDeployment -ResourceGroupName examplegroup -TemplateFile c:\Azure\Templates\storage.json -DeploymentDebugLogLevel All
</code>```

or Azure CLI:

```<code>az group deployment operation list --resource-group ExampleGroup --name vmlinux
</code>```

Check Also Check deployment sequence:
Many deployment errors happen when resources are deployed in an unexpected sequence. These errors arise when dependencies are not correctly set. When you are missing a needed dependency, one resource attempts to use a value for another resource but the other does not yet exist.

The above link contains more details. Let me know if this helps.

Body:
Whether I have the azure agent plugin for Jenkins make my container, or if I do it manually, it seems like either way it never enters a running state.

az container create \
    --os-type Windows \
    --location eastus \
    --registry-login-server SERVER.azurecr.io \
    --registry-password PASSWORD \
    --registry-username USERNAME \
    --image namespace/image \
    --name jenkins-permanent \
    --resource-group devops-aci \
    --cpu 2 \
    --memory 3.5 \
    --restart-policy Always \
    --command-line "-jnlpUrl http://host:8080/computer/NAME/slave-agent.jnlp -secret SECRET -workDir \"C:\\jenkins\""

I've gone through all the troubleshooting steps that apply, tried a different region, but to no avail.

Here's a current event that I got which seems to be the most progress I've had yet:

          {
            "count": 1,
            "firstTimestamp": "2017-12-07T03:02:56+00:00",
            "lastTimestamp": "2017-12-07T03:02:56+00:00",
            "message": "Failed to pull image \"MYREPO.azurecr.io/my-company/windows-agent:latest\": Error response from da
emon: {\"message\":\"Get https://MYREPO.azurecr.io/v2/: net/http: request canceled while waiting for connection (Client.Timeout
exceeded while awaiting headers)\"}",
            "name": "Failed",
            "type": "Warning"
          }

The funny thing is, this event happens before and after one case of the instance working (but unfortunately my entrypoint command was wrong, so it never started).

I really feel like Azure is punting on this and I just have no way to change the order I do anything.  It's simply one command.

Body:
Alexander, here's a lead to actually check what could be causing the delay, or if the deployment has failed in the background, this information would be critical to narrow down what the issue is: https://learn.microsoft.com/en-us/azure/azure-resource-manager/resource-manager-troubleshoot-tips#determine-error-code

From the article above check on deployment logs:
Enable debug logging:
PowerShell
In PowerShell, set the DeploymentDebugLogLevel parameter to All, ResponseContent, or RequestContent.

New-AzureRmResourceGroupDeployment -ResourceGroupName examplegroup -TemplateFile c:\Azure\Templates\storage.json -DeploymentDebugLogLevel All

or Azure CLI:

az group deployment operation list --resource-group ExampleGroup --name vmlinux

Check Also Check deployment sequence:
Many deployment errors happen when resources are deployed in an unexpected sequence. These errors arise when dependencies are not correctly set. When you are missing a needed dependency, one resource attempts to use a value for another resource but the other does not yet exist.

The above link contains more details. Let me know if this helps.


问:
use JTA transaction or not?
I am developing a J2EE application which is deployed on JBoss application server.
The application is composed of an EJB 2.x component and a web component and is running on local computer or remote server. The database is either Oracle or SQL Server and is not in a distributed envrionment.

I am using Hibernate 3.6 (JPA 2.0 implementation) for the transactions. Should I use JTA which is container managed transaction or is it overkilled to use it?

Currently I am using JTA and it turns out it is running fine but with some small issues which I do not know whether it is related to the transaction management or not. Will it be easier or more reliable to use local transaction management?

答:
JTA transactions are always recommended above other kinds of transaction APIs, especially if you are referring to the native transactions that are still part of the JPA API. Note that you can't say 'JTA vs resource local transactions', as JTA actually manages resource local transactions among others.

Gavin King (creator of Hibernate) once indicated in an interview that this JPA specific API was a mistake and that the much more flexible JTA API should be preferred. Especially when using declarative transactions, JTA is very lightweight. The word overkill would actually apply more to using the JPA native transaction API, then to using JTA.

There is something to say about the choice between using XA or resource local transactions with JTA. See my answer here for some more details about that: JTA or LOCAL transactions in JPA2+Hibernate 3.6.0?

I do wonder why you are using EJB 2 in combination with JPA 2.0. EJB 3.1 would be a much more logical choice here. EJB 2 is completely deprecated (will be pruned in Java EE 7).

Title: use JTA transaction or not?


问:
Xamarin forms relative layout constraints top and bottom
I am new to Xamarin.Forms (Swift is my strong point). To make my App work across all screen sizes, I am using RelativeLayout. The only problem is, I can only find out how to set the width and height.

What I want to do is set the top and bottom constraints.

This is what I can do in Swift:

let redBox = UIView()
redBox.translatesAutoresizingMaskIntoConstraints = false
redBox.backgroundColor = .red

let blueBox = UIView()
blueBox.translatesAutoresizingMaskIntoConstraints = false
blueBox.backgroundColor = .blue

view.addSubview(redBox)
view.addSubview(blueBox)

redBox.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
redBox.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
redBox.heightAnchor.constraint(equalToConstant: 150).isActive = true

blueBox.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
blueBox.topAnchor.constraint(equalTo: redBox.bottomAnchor).isActive = true
blueBox.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
```

<p>This results in the following screen:</p>

<p><img src="https://i.stack.imgur.com/Rzgap.png" alt="enter image description here"></p>

<p>How would I achieve this in <code>Xamarin.Forms</code>?
I can only find out how to do width and height constraints. I also want to do it programatically instead of <code>XAML</code> or drag and drop.</p>

<p>Here is the <code>C#</code> <code>Xamarin.Forms</code> code that I have found out:</p>

<pre class="lang-cs prettyprint-override"><code>var layout = new RelativeLayout();
Content = layout;

var aquaBox = new BoxView()
{
    Color = Color.Aqua
};

var silverBox = new BoxView
{
    Color = Color.Silver
};

aquaBox.HeightRequest = 150;
layout.Children.Add(aquaBox,
    widthConstraint: Constraint.RelativeToParent(parent => parent.Width)
);

layout.Children.Add(silverBox,
    yConstraint: Constraint.RelativeToView(aquaBox, (RelativeLayout, element) => element.Height)
);
</code>```

XAML:

<?xml version="1.0" encoding="utf-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:Test"
             x:Class="Test.TestPage">

</ContentPage>
```

The result of this code is:

What C# Xamarin.Forms code is needed to get the same view as I have with Swift?

Note: I would like Xamarin.Forms code and not separate code for Android, Windows and iOS.

答:
RelativeLayout:

Find the height in the heightConstraint parameter. The VerticalOptions of RelativeLayout is default Fill and when the view (i.e. the RelativeLayout) is resized the parent.Height will be recalculated.

```<code>var layout = new RelativeLayout(); //VerticalOptions is default Fill

var aquaBox = new BoxView
{
    Color = Color.Aqua,
    HeightRequest = 150
};

var silverBox = new BoxView
{
    Color = Color.Silver
};

layout.Children.Add(aquaBox,
    widthConstraint: Constraint.RelativeToParent((parent) => parent.Width)
    );

layout.Children.Add(silverBox,
    widthConstraint: Constraint.RelativeToParent((parent) => parent.Width),
    yConstraint: Constraint.RelativeToView(aquaBox, (parent, sibling) => sibling.Height),
    heightConstraint: Constraint.RelativeToParent((parent) => parent.Height - aquaBox.HeightRequest)
    );

Content = layout;
</code>```

Body:
I am new to Xamarin.Forms (Swift is my strong point). To make my App work across all screen sizes, I am using RelativeLayout. The only problem is, I can only find out how to set the width and height.

What I want to do is set the top and bottom constraints.

This is what I can do in Swift:

let redBox = UIView()
redBox.translatesAutoresizingMaskIntoConstraints = false
redBox.backgroundColor = .red

let blueBox = UIView()
blueBox.translatesAutoresizingMaskIntoConstraints = false
blueBox.backgroundColor = .blue

view.addSubview(redBox)
view.addSubview(blueBox)

redBox.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
redBox.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
redBox.heightAnchor.constraint(equalToConstant: 150).isActive = true

blueBox.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
blueBox.topAnchor.constraint(equalTo: redBox.bottomAnchor).isActive = true
blueBox.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true

This results in the following screen:

How would I achieve this in Xamarin.Forms?
I can only find out how to do width and height constraints. I also want to do it programatically instead of XAML or drag and drop.

Here is the C# Xamarin.Forms code that I have found out:

var layout = new RelativeLayout();
Content = layout;

var aquaBox = new BoxView()
{
    Color = Color.Aqua
};

var silverBox = new BoxView
{
    Color = Color.Silver
};

aquaBox.HeightRequest = 150;
layout.Children.Add(aquaBox,
    widthConstraint: Constraint.RelativeToParent(parent => parent.Width)
);

layout.Children.Add(silverBox,
    yConstraint: Constraint.RelativeToView(aquaBox, (RelativeLayout, element) => element.Height)
);

XAML:

<?xml version="1.0" encoding="utf-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:Test"
             x:Class="Test.TestPage">

</ContentPage>

The result of this code is:

What C# Xamarin.Forms code is needed to get the same view as I have with Swift?

Note: I would like Xamarin.Forms code and not separate code for Android, Windows and iOS.

Body:
RelativeLayout:

Find the height in the heightConstraint parameter. The VerticalOptions of RelativeLayout is default Fill and when the view (i.e. the RelativeLayout) is resized the parent.Height will be recalculated.

var layout = new RelativeLayout(); //VerticalOptions is default Fill

var aquaBox = new BoxView
{
    Color = Color.Aqua,
    HeightRequest = 150
};

var silverBox = new BoxView
{
    Color = Color.Silver
};

layout.Children.Add(aquaBox,
    widthConstraint: Constraint.RelativeToParent((parent) => parent.Width)
    );

layout.Children.Add(silverBox,
    widthConstraint: Constraint.RelativeToParent((parent) => parent.Width),
    yConstraint: Constraint.RelativeToView(aquaBox, (parent, sibling) => sibling.Height),
    heightConstraint: Constraint.RelativeToParent((parent) => parent.Height - aquaBox.HeightRequest)
    );

Content = layout;


问:
Plot the distance between every two points in 2 D
If I have a table with three columns where the first column represents the name of each point, the second column represent numerical data (mean) and the last column represent (second column + fixed number). The following an example how is the data looks like:

I want to plot this table so I have the following figure

If it is possible how I can plot it using either Microsoft Excel or python or R (Bokeh).

答:
Alright, I only know how to do it in ggplot2, I will answer regarding R here.

These method only works if the data-frame is in the format you provided above.

I rename your column to Name.of.Method, Mean, Mean.2.2

Preparation

Loading csv data into R

```<code>df <- read.csv('yourdata.csv', sep = ',')
</code>```

Change column name (Do this if you don't want to change the code below or else you will need to go through each parameter to match your column names.

```<code>names(df) <- c("Name.of.Method", "Mean", "Mean.2.2")
</code>```

Method 1 - Using geom_segment()

```<code>ggplot()  +
geom_segment(data=df,aes(x = Mean,
                         y = Name.of.Method,
                         xend = Mean.2.2,
                         yend = Name.of.Method))
</code>```

So as you can see, geom_segment allows us to specify the end position of the line (Hence, xend and  yend)

However, it does not look similar to the image you have above.

The line shape seems to represent error bar. Therefore, ggplot provides us with an error bar function.

Method 2 - Using geom_errorbarh()

```<code>ggplot(df, aes(y = Name.of.Method, x = Mean)) +
       geom_errorbarh(aes(xmin = Mean, xmax = Mean.2.2), linetype = 1, height = .2)
</code>```

Usually we don't use this method just to draw a line. However, its functionality fits your requirement. You can see that we use xmin and ymin to specify the head and the tail of the line.
The height input is to adjust the height of the bar at the end of the line in both ends.

Body:
Alright, I only know how to do it in ggplot2, I will answer regarding R here.

These method only works if the data-frame is in the format you provided above.

I rename your column to Name.of.Method, Mean, Mean.2.2

Preparation

Loading csv data into R

df <- read.csv('yourdata.csv', sep = ',')

Change column name (Do this if you don't want to change the code below or else you will need to go through each parameter to match your column names.

names(df) <- c("Name.of.Method", "Mean", "Mean.2.2")

Method 1 - Using geom_segment()

ggplot()  +
geom_segment(data=df,aes(x = Mean,
                         y = Name.of.Method,
                         xend = Mean.2.2,
                         yend = Name.of.Method))

So as you can see, geom_segment allows us to specify the end position of the line (Hence, xend and  yend)

However, it does not look similar to the image you have above.

The line shape seems to represent error bar. Therefore, ggplot provides us with an error bar function.

Method 2 - Using geom_errorbarh()

ggplot(df, aes(y = Name.of.Method, x = Mean)) +
       geom_errorbarh(aes(xmin = Mean, xmax = Mean.2.2), linetype = 1, height = .2)

Usually we don't use this method just to draw a line. However, its functionality fits your requirement. You can see that we use xmin and ymin to specify the head and the tail of the line.
The height input is to adjust the height of the bar at the end of the line in both ends.


问:
Two git repositories in one directory?
Is it possible to have 2 git repositories in one directory?  I'd think not, but thought I'd ask.  Basically, I'd like to check in my home directory config files (e.g. .emacs) which should be common across all of the machines I work on, but have a second repository for local files (e.g. .emacs.local), which contains machine-specific configurations.  The only way I can think of to do that is to have the local config in a subdirectory and ignore that subdirectory from the main git repository.  Any other ideas?</p>

答:
Disclaimer: This is not advertising. I'm the developer of the provided library.

I've created a git extension to handle cases where you want to mix multiple repositories into one folder. The advantage of the lib is, to keep track of the repositories and file conflicts. you can find it on github. There are also 2 example repositories to try it out.

OwnerDisplayName: Joe Casadonte

Title: Two git repositories in one directory?


问:
How not to use functions as parameters for other functions
I am trying to write a few functions that will determine the number of real roots and the roots of a quadratic equations, and I must do it using a main() function. What I am trying to avoid is using the final function with all the other functions as its parameters, like

```<code>def main():
    function4(function3(function2(function1())), function2(function1()))
</code>```

Instead, how can I make it look like:

```<code>def main():
    function1()
    function2()
    function3()
    function4()
</code>```

答:
This should be equivalent.</p>

```<code>def main():
    result1 = function1()
    result2 = function2(result1)
    result3 = function3(result2)
    final_result = function4(result3, result2)
</code>```

Body:
I am trying to write a few functions that will determine the number of real roots and the roots of a quadratic equations, and I must do it using a main() function. What I am trying to avoid is using the final function with all the other functions as its parameters, like

def main():
    function4(function3(function2(function1())), function2(function1()))

Instead, how can I make it look like:

def main():
    function1()
    function2()
    function3()
    function4()

Body:
This should be equivalent.

def main():
    result1 = function1()
    result2 = function2(result1)
    result3 = function3(result2)
    final_result = function4(result3, result2)


问:
Bash Shell Scripting: How to Sum the Values in a File With the Use of For Loop and bc Command
I'm currently trying to write a function in my bash script that does the following: Take in a file as an argument and calculate the sum of the numbers within that file. I must make use of a for loop and the bc command.

Example of values in the file (each value on their own line):

```<code>12
4
53
19
6
</code>```

So here's what I have so far:

```<code>function sum_values() {
  for line in $1; do
  #not sure how to sum the values using bc
  done
}
</code>```

Am I on the right track? I'm not sure how to implement the bc command  in this situation.

答:
You are not on track. Why?

You are passing the whole file content as a variable which requires to store the whole file in memory. Not a problem with a 1, 2, 3 example, big no go in real life.

You are iterating over the content of a file using a for in loop assuming that you are iterating over the lines of that file. That is not true, because word splitting will be performed which makes the for in loop literally iterate over words, not lines.

As others mentioned, the shell is not the right tool for it. That's because such kind of processing is very slow with the shell compared to awk for example. Furthermore the shell is not able to perform floating point operations, meaning you can only process integers. Use awk.

Correct would be (with bash, for educational purposes):

```<code># Expects a filename
sum() {
    filename=${1}
    s=0
    while read -r line ; do
        # Arithmetic expansion
        s=$((s+line))
        # Or with bc
        # s=$(bc <<< "${s}+${line}")
        # With floating point support
        # s=$(bc -l <<< "${s}+${line}")
    done < "${filename}"
    echo "${s}"
}

sum filename
</code>```

With awk:

```<code>awk '{s+=$0}END{print s}' filename
</code>```

Body:
I'm currently trying to write a function in my bash script that does the following: Take in a file as an argument and calculate the sum of the numbers within that file. I must make use of a for loop and the bc command.

Example of values in the file (each value on their own line):

12
4
53
19
6

So here's what I have so far:

function sum_values() {
  for line in $1; do
  #not sure how to sum the values using bc
  done
}

Am I on the right track? I'm not sure how to implement the bc command  in this situation.

Body:
You are not on track. Why?

You are passing the whole file content as a variable which requires to store the whole file in memory. Not a problem with a 1, 2, 3 example, big no go in real life.

You are iterating over the content of a file using a for in loop assuming that you are iterating over the lines of that file. That is not true, because word splitting will be performed which makes the for in loop literally iterate over words, not lines.

As others mentioned, the shell is not the right tool for it. That's because such kind of processing is very slow with the shell compared to awk for example. Furthermore the shell is not able to perform floating point operations, meaning you can only process integers. Use awk.

Correct would be (with bash, for educational purposes):

# Expects a filename
sum() {
    filename=${1}
    s=0
    while read -r line ; do
        # Arithmetic expansion
        s=$((s+line))
        # Or with bc
        # s=$(bc <<< "${s}+${line}")
        # With floating point support
        # s=$(bc -l <<< "${s}+${line}")
    done < "${filename}"
    echo "${s}"
}

sum filename

With awk:

awk '{s+=$0}END{print s}' filename


问:
How to deal with a variable that may be one of several types
I have a function like this

```<code>sqlQuery(query : string | Array, database = 'swdata') : Promise {
    let rest;
    if (Array.isArray(query)) {
        rest = query.splice(1);
        query = sqlString.format(query[0], rest);
    }

    const request = new Request('data', 'sqlQuery', {database, query, formatValues: true});
    return this.connection.sendRequest(request);

}
</code>```

My IDE complains that there is no method splice for a string. Is that just a quirk with my IDE, or is there a better way to write this code?

答:
Your IDE does not properly support TypeScript Language Service.

Array.isArray() is a Type Guard function that participates in the control flow analysis of TypeScript. That means in that block, TypeScript Language Service can determine that the type of query is of type array and you should not see the error.

For example, if your IDE is WebStorm, you need to go to setting and check using TypeScript language service.
Other IDE may have similar options or plugins.

You can use VSCode to test it out. It should be working just fine.

Body:
I have a function like this

sqlQuery(query : string | Array, database = 'swdata') : Promise {
    let rest;
    if (Array.isArray(query)) {
        rest = query.splice(1);
        query = sqlString.format(query[0], rest);
    }

    const request = new Request('data', 'sqlQuery', {database, query, formatValues: true});
    return this.connection.sendRequest(request);

}

My IDE complains that there is no method splice for a string. Is that just a quirk with my IDE, or is there a better way to write this code?


问:
Getting request attributes in freemarker
How do I check a value from the request attribute in freemarker?
I tried <#if *${RequestParameters['servicesettings']} ??> but getting errors ->

Encountered "*" at line

Can anyone help?

答:
According to the JavaDoc of the FreemarkerServlet:

It makes all request, request parameters, session, and servlet context attributes available to templates through Request, RequestParameters, Session, and Application variables.

The scope variables are also available via automatic scope discovery. That is, writing Application.attrName, Session.attrName, Request.attrName is not mandatory; it's enough to write attrName, and if no such variable was created in the template, it will search the variable in Request, and then in Session, and finally in Application.

You can simply write:

```<code>${attrName}
</code>```

to get the value of a request attribute (that you might have set in a servlet request filter using request.setAttribute('attrName', 'value')

Worked for me with Freemarker 2.3.27-incubating

Body:
According to the JavaDoc of the FreemarkerServlet:

It makes all request, request parameters, session, and servlet context attributes available to templates through Request, RequestParameters, Session, and Application variables.

The scope variables are also available via automatic scope discovery. That is, writing Application.attrName, Session.attrName, Request.attrName is not mandatory; it's enough to write attrName, and if no such variable was created in the template, it will search the variable in Request, and then in Session, and finally in Application.

You can simply write:

${attrName}

to get the value of a request attribute (that you might have set in a servlet request filter using request.setAttribute('attrName', 'value')

Worked for me with Freemarker 2.3.27-incubating


问:
Copula and simulation of binary and continuous variables
I am trying to simulate variables knowing their marginal distribution and their correlation matrix. I know we can use packages like copula but I am not familiar on how to go about it. Can someone help</p>

```<code>#mean(w1)=0.6, sd(w1)=0.38; w1 is normally distributed
#mean(w2)=0.31; w2 is binary
#mean(w3)=0.226; w3 is binary

cor
           w1         w2         w3
w1  1.0000000 -0.3555066 -0.1986376
w2 -0.3555066  1.0000000  0.1030849
w3 -0.1986376  0.1030849  1.0000000
</code>```

答:
Drawing from the answer here: https://stackoverflow.com/a/10540234/6455166

```<code>library(copula)
set.seed(123)
myCop <- normalCopula(param = c(-0.46, -0.27, 0.18),
                      dim = 3, dispstr = "un")
out <- rCopula(1e5, myCop)
out[, 1] <- qnorm(out[, 1], mean = 0.6, sd = 0.38)
out[, 2] <- qbinom(out[, 2], size = 1, prob = 0.31)
out[, 3] <- qbinom(out[, 3], size = 1, prob = 0.226)

cor(out)
#            [,1]       [,2]       [,3]
# [1,]  1.0000000 -0.3548863 -0.1943631
# [2,] -0.3548863  1.0000000  0.1037638
# [3,] -0.1943631  0.1037638  1.0000000
colMeans(out)
# [1] 0.5992595 0.3118300 0.2256000
sd(out[, 1])
# [1] 0.3806173
</code>```

Explanation.  We draw correlated uniforms, and then convert each vector of uniforms to our desired distributions.  The values for the param argument in normalCopula were arrived at through trial and error: start with your desired correlations (i.e. c(-0.3555, -0.1986, 0.103)), then adjust them until cor(out) produces your target correlations.

Body:
I am trying to simulate variables knowing their marginal distribution and their correlation matrix. I know we can use packages like copula but I am not familiar on how to go about it. Can someone help

#mean(w1)=0.6, sd(w1)=0.38; w1 is normally distributed
#mean(w2)=0.31; w2 is binary
#mean(w3)=0.226; w3 is binary

cor
           w1         w2         w3
w1  1.0000000 -0.3555066 -0.1986376
w2 -0.3555066  1.0000000  0.1030849
w3 -0.1986376  0.1030849  1.0000000

Body:
Drawing from the answer here: https://stackoverflow.com/a/10540234/6455166

library(copula)
set.seed(123)
myCop <- normalCopula(param = c(-0.46, -0.27, 0.18),
                      dim = 3, dispstr = "un")
out <- rCopula(1e5, myCop)
out[, 1] <- qnorm(out[, 1], mean = 0.6, sd = 0.38)
out[, 2] <- qbinom(out[, 2], size = 1, prob = 0.31)
out[, 3] <- qbinom(out[, 3], size = 1, prob = 0.226)

cor(out)
#            [,1]       [,2]       [,3]
# [1,]  1.0000000 -0.3548863 -0.1943631
# [2,] -0.3548863  1.0000000  0.1037638
# [3,] -0.1943631  0.1037638  1.0000000
colMeans(out)
# [1] 0.5992595 0.3118300 0.2256000
sd(out[, 1])
# [1] 0.3806173

Explanation.  We draw correlated uniforms, and then convert each vector of uniforms to our desired distributions.  The values for the param argument in normalCopula were arrived at through trial and error: start with your desired correlations (i.e. c(-0.3555, -0.1986, 0.103)), then adjust them until cor(out) produces your target correlations.


问:
Backpropagating bias in a neural network
Following Andrew Traks's example, I want to implement a 3 layer neural network - 1 input, 1 hidden, 1 output - with a simple dropout, for binary classification.

If I include bias terms b1 and b2, then I would need to slightly modify Andrew's code as below.

```<code>X = np.array([ [0,0,1],[0,1,1],[1,0,1],[1,1,1] ])
y = np.array([[0,1,1,0]]).T
alpha,hidden_dim,dropout_percent = (0.5,4,0.2)
synapse_0 = 2*np.random.random((X.shape[1],hidden_dim)) - 1
synapse_1 = 2*np.random.random((hidden_dim,1)) - 1
b1 = np.zeros(hidden_dim)
b2 = np.zeros(1)
for j in range(60000):
    # sigmoid activation function
    layer_1 = (1/(1+np.exp(-(np.dot(X,synapse_0) + b1))))
    # dropout
    layer_1 *= np.random.binomial([np.ones((len(X),hidden_dim))],1-dropout_percent)[0] * (1.0/(1-dropout_percent))
    layer_2 = 1/(1+np.exp(-(np.dot(layer_1,synapse_1) + b2)))
    # sigmoid derivative = s(x)(1-s(x))
    layer_2_delta = (layer_2 - y)*(layer_2*(1-layer_2))
    layer_1_delta = layer_2_delta.dot(synapse_1.T) * (layer_1 * (1-layer_1))
    synapse_1 -= (alpha * layer_1.T.dot(layer_2_delta))
    synapse_0 -= (alpha * X.T.dot(layer_1_delta))
    b1 -= alpha*layer_1_delta
    b2 -= alpha*layer_2_delta
</code>```

The problem is, of course, with the code above the dimensions of b1 dont match with the dimensions of layer_1_delta, similarly with b2 and layer_2_delta.

I don't understand how the delta is calculated to update b1 and b2 - according to Michael Nielsen's example, b1 and b2 should be updated by a delta which in my code I believe to be layer_1_delta and layer_2_delta respectively.

What am I doing wrong here? Have I messed up the dimensionality of the deltas or of the biases? I feel it is the latter, because if I remove the biases from this code it works fine. Thanks in advance

答:
So first I would change X in bX to 0 and 1 to correspond to synapse_X, because this is where they belong and it makes it:

```<code>b1 -= alpha * 1.0 / m * np.sum(layer_2_delta)
b0 -= alpha * 1.0 / m * np.sum(layer_1_delta)
</code>```

Where m is the number of examples in the training set. Also, the drop rate is stupidly high and actually hurts convergence. So in all considered the whole code:

```<code>import numpy as np

X = np.array([ [0,0,1],[0,1,1],[1,0,1],[1,1,1] ])
m = X.shape[0]
y = np.array([[0,1,1,0]]).T
alpha,hidden_dim,dropout_percent = (0.5,4,0.02)
synapse_0 = 2*np.random.random((X.shape[1],hidden_dim)) - 1
synapse_1 = 2*np.random.random((hidden_dim,1)) - 1
b0 = np.zeros(hidden_dim)
b1 = np.zeros(1)
for j in range(10000):
    # sigmoid activation function
    layer_1 = (1/(1+np.exp(-(np.dot(X,synapse_0) + b0))))
    # dropout
    layer_1 *= np.random.binomial([np.ones((len(X),hidden_dim))],1-dropout_percent)[0] * (1.0/(1-dropout_percent))
    layer_2 = 1/(1+np.exp(-(np.dot(layer_1,synapse_1) + b1)))
    # sigmoid derivative = s(x)(1-s(x))
    layer_2_delta = (layer_2 - y)*(layer_2*(1-layer_2))
    layer_1_delta = layer_2_delta.dot(synapse_1.T) * (layer_1 * (1-layer_1))
    synapse_1 -= (alpha * layer_1.T.dot(layer_2_delta))
    synapse_0 -= (alpha * X.T.dot(layer_1_delta))
    b1 -= alpha * 1.0 / m * np.sum(layer_2_delta)
    b0 -= alpha * 1.0 / m * np.sum(layer_1_delta)

print layer_2
</code>```

Body:
Following Andrew Traks's example, I want to implement a 3 layer neural network - 1 input, 1 hidden, 1 output - with a simple dropout, for binary classification.

If I include bias terms b1 and b2, then I would need to slightly modify Andrew's code as below.

X = np.array([ [0,0,1],[0,1,1],[1,0,1],[1,1,1] ])
y = np.array([[0,1,1,0]]).T
alpha,hidden_dim,dropout_percent = (0.5,4,0.2)
synapse_0 = 2*np.random.random((X.shape[1],hidden_dim)) - 1
synapse_1 = 2*np.random.random((hidden_dim,1)) - 1
b1 = np.zeros(hidden_dim)
b2 = np.zeros(1)
for j in range(60000):
    # sigmoid activation function
    layer_1 = (1/(1+np.exp(-(np.dot(X,synapse_0) + b1))))
    # dropout
    layer_1 *= np.random.binomial([np.ones((len(X),hidden_dim))],1-dropout_percent)[0] * (1.0/(1-dropout_percent))
    layer_2 = 1/(1+np.exp(-(np.dot(layer_1,synapse_1) + b2)))
    # sigmoid derivative = s(x)(1-s(x))
    layer_2_delta = (layer_2 - y)*(layer_2*(1-layer_2))
    layer_1_delta = layer_2_delta.dot(synapse_1.T) * (layer_1 * (1-layer_1))
    synapse_1 -= (alpha * layer_1.T.dot(layer_2_delta))
    synapse_0 -= (alpha * X.T.dot(layer_1_delta))
    b1 -= alpha*layer_1_delta
    b2 -= alpha*layer_2_delta

The problem is, of course, with the code above the dimensions of b1 dont match with the dimensions of layer_1_delta, similarly with b2 and layer_2_delta.

I don't understand how the delta is calculated to update b1 and b2 - according to Michael Nielsen's example, b1 and b2 should be updated by a delta which in my code I believe to be layer_1_delta and layer_2_delta respectively.

What am I doing wrong here? Have I messed up the dimensionality of the deltas or of the biases? I feel it is the latter, because if I remove the biases from this code it works fine. Thanks in advance

Body:
So first I would change X in bX to 0 and 1 to correspond to synapse_X, because this is where they belong and it makes it:

b1 -= alpha * 1.0 / m * np.sum(layer_2_delta)
b0 -= alpha * 1.0 / m * np.sum(layer_1_delta)

Where m is the number of examples in the training set. Also, the drop rate is stupidly high and actually hurts convergence. So in all considered the whole code:

import numpy as np

X = np.array([ [0,0,1],[0,1,1],[1,0,1],[1,1,1] ])
m = X.shape[0]
y = np.array([[0,1,1,0]]).T
alpha,hidden_dim,dropout_percent = (0.5,4,0.02)
synapse_0 = 2*np.random.random((X.shape[1],hidden_dim)) - 1
synapse_1 = 2*np.random.random((hidden_dim,1)) - 1
b0 = np.zeros(hidden_dim)
b1 = np.zeros(1)
for j in range(10000):
    # sigmoid activation function
    layer_1 = (1/(1+np.exp(-(np.dot(X,synapse_0) + b0))))
    # dropout
    layer_1 *= np.random.binomial([np.ones((len(X),hidden_dim))],1-dropout_percent)[0] * (1.0/(1-dropout_percent))
    layer_2 = 1/(1+np.exp(-(np.dot(layer_1,synapse_1) + b1)))
    # sigmoid derivative = s(x)(1-s(x))
    layer_2_delta = (layer_2 - y)*(layer_2*(1-layer_2))
    layer_1_delta = layer_2_delta.dot(synapse_1.T) * (layer_1 * (1-layer_1))
    synapse_1 -= (alpha * layer_1.T.dot(layer_2_delta))
    synapse_0 -= (alpha * X.T.dot(layer_1_delta))
    b1 -= alpha * 1.0 / m * np.sum(layer_2_delta)
    b0 -= alpha * 1.0 / m * np.sum(layer_1_delta)

print layer_2


问:
Return datetime object of previous month
If only timedelta had a month argument in it's constructor.  So what's the simplest way to do this?

EDIT: I wasn't thinking too hard about this as was pointed out below.  Really what I wanted was any day in the last month because eventually I'm going to grab the year and month only.  So given a datetime object, what's the simplest way to return any datetime object that falls in the previous month?

答:
You can use below given function to get date before/after X month.</p>

```
from datetime import date

def next_month(given_date, month):
    yyyy = int(((given_date.year * 12 + given_date.month) + month)/12)
    mm = int(((given_date.year * 12 + given_date.month) + month)%12)

    if mm == 0:
        yyyy -= 1
        mm = 12

    return given_date.replace(year=yyyy, month=mm)

if __name__ == "__main__":
    today = date.today()
    print(today)

    for mm in [-12, -1, 0, 1, 2, 12, 20 ]:
        next_date = next_month(today, mm)
        print(next_date)
```

Body:
You can use below given function to get date before/after X month.

from datetime import date

def next_month(given_date, month):
    yyyy = int(((given_date.year * 12 + given_date.month) + month)/12)
    mm = int(((given_date.year * 12 + given_date.month) + month)%12)

    if mm == 0:
        yyyy -= 1
        mm = 12

    return given_date.replace(year=yyyy, month=mm)

if __name__ == "__main__":
    today = date.today()
    print(today)

    for mm in [-12, -1, 0, 1, 2, 12, 20 ]:
        next_date = next_month(today, mm)
        print(next_date)


问:
python3: Unescape unicode escapes surrounded by unescaped characters
I received json data that has some unicode characters escaped, and others not.

```<code>>>> example = r'сло\u0301во'
</code>```

What is the best way to unescape those characters? In the example below, what would the function unescape look like? Is there a built-in function that does this?

```<code>>>> unescape(example)
сло́во
</code>```

答:
This solution assumes that every instance of \u in the original string is a unicode escape:

```<code>def unescape(in_str):
    """Unicode-unescape string with only some characters escaped."""
    in_str = in_str.encode('unicode-escape')   # bytes with all chars escaped (the original escapes have the backslash escaped)
    in_str = in_str.replace(b'\\\\u', b'\\u')  # unescape the \
    in_str = in_str.decode('unicode-escape')   # unescape unicode
    return in_str
</code>```

...or in one line...

```<code>def unescape(in_str):
    """Unicode-unescape string with only some characters escaped."""
    return in_str.encode('unicode-escape').replace(b'\\\\u', b'\\u').decode('unicode-escape')
</code>```

Body:
I received json data that has some unicode characters escaped, and others not.

>>> example = r'сло\u0301во'

What is the best way to unescape those characters? In the example below, what would the function unescape look like? Is there a built-in function that does this?

>>> unescape(example)
сло́во

Body:
This solution assumes that every instance of \u in the original string is a unicode escape:

def unescape(in_str):
    """Unicode-unescape string with only some characters escaped."""
    in_str = in_str.encode('unicode-escape')   # bytes with all chars escaped (the original escapes have the backslash escaped)
    in_str = in_str.replace(b'\\\\u', b'\\u')  # unescape the \
    in_str = in_str.decode('unicode-escape')   # unescape unicode
    return in_str

...or in one line...

def unescape(in_str):
    """Unicode-unescape string with only some characters escaped."""
    return in_str.encode('unicode-escape').replace(b'\\\\u', b'\\u').decode('unicode-escape')


问:
Laravel Parameter passing error from controller to view
I want to pass the parameter  $questions to view, but it gives the following error:

ErrorException (E_ERROR)
      Undefined variable: questions (View: C:\Users\Krishan\Documents\GitHub\GroupProject\lcurve\resources\views\quizz\questions\index.blade.php)

This is my controller index function part:

```<code>public function index()
{
    $questions = Question::all();
    return view('quizz/questions.index', compact('questions'));
}
</code>```

This is a part Of my view:

```<code><tbody>
    @if (count($questions_options) > 0)
        @foreach ($questions_options as $questions_option)
            <tr data-entry-id="{{ $questions_option->id }}">
                <td></td>
                <td>{{ $questions_option->question->question_text or '' }}</td>
                <td>{{ $questions_option->option }}</td>
                <td>{{ $questions_option->correct == 1 ? 'Yes' : 'No' }}</td>
                <td>
                    <a href="{{ route('quizz/questions_options.show',[$questions_option->id]) }}" class="btn btn-xs btn-primary">View</a>-->
                    <!--<a href="{{ route('questions_options.edit',[$questions_option->id]) }}" class="btn btn-xs btn-info">Edit</a>-->
                    {!! Form::open(array(
                                        'style' => 'display: inline-block;',
                                        'method' => 'DELETE',
                                        'onsubmit' => "return confirm('".trans("quickadmin.are_you_sure")."');",
                                        'route' => ['questions_options.destroy', $questions_option->id])) !!}
                                    {!! Form::submit(trans('quickadmin.delete'), array('class' => 'btn btn-xs btn-danger')) !!}
                                    {!! Form::close() !!}
                </td>
            </tr>
        @endforeach
    @else
        <tr>
            <td colspan="5">no_entries_in_table</td>
        </tr>
    @endif
</tbody>
</code>```

enter image description here

答:
Firstly, the error message you have mention should be shown. The error message should be:
Undefined variable: questions_options (View:C:\Users\Krishan\Do........

Because you are passing questions to view but you are accessing question_options in view. So, it should say question_options in undefined in view.

Besides, do you know you can avoid this count check? You can use laravel's forelse tag here a below:

```<code>@forelse($questions as $question)
     //Your table goes here
@empty
   <tr>
      <td colspan="5">no_entries_in_table</td>
   </tr>
@endforelse
</code>```

Body:
I want to pass the parameter  $questions to view, but it gives the following error:

ErrorException (E_ERROR)
      Undefined variable: questions (View: C:\Users\Krishan\Documents\GitHub\GroupProject\lcurve\resources\views\quizz\questions\index.blade.php)

This is my controller index function part:

public function index()
{
    $questions = Question::all();
    return view('quizz/questions.index', compact('questions'));
}

This is a part Of my view:

    @if (count($questions_options) > 0)
        @foreach ($questions_options as $questions_option)

id }}">

                {{ $questions_option->question->question_text or '' }}
                {{ $questions_option->option }}
                {{ $questions_option->correct == 1 ? 'Yes' : 'No' }}

                    id]) }}" class="btn btn-xs btn-primary">View-->

                    {!! Form::open(array(
                                        'style' => 'display: inline-block;',
                                        'method' => 'DELETE',
                                        'onsubmit' => "return confirm('".trans("quickadmin.are_you_sure")."');",
                                        'route' => ['questions_options.destroy', $questions_option->id])) !!}
                                    {!! Form::submit(trans('quickadmin.delete'), array('class' => 'btn btn-xs btn-danger')) !!}
                                    {!! Form::close() !!}

        @endforeach
    @else

            no_entries_in_table

    @endif

enter image description here

Body:
Firstly, the error message you have mention should be shown. The error message should be:
Undefined variable: questions_options (View:C:\Users\Krishan\Do........

Because you are passing questions to view but you are accessing question_options in view. So, it should say question_options in undefined in view.

Besides, do you know you can avoid this count check? You can use laravel's forelse tag here a below:

@forelse($questions as $question)
     //Your table goes here
@empty
   <tr>
      <td colspan="5">no_entries_in_table</td>
   </tr>
@endforelse


问:
Import complex types from XSD in different namespace
I have two XSD files in different namespaces like below

book_request.xsd

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsd:schema
    targetNamespace="book-request"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns="book-request"
    elementFormDefault="qualified">

    <xsd:element name="book-request" type="book-request"/>

    <xsd:complexType name="book-request">
        <xsd:sequence>
            <xsd:element name="booking-code" type="xsd:string"/>
            <xsd:element name="room-type-code" type="xsd:string"/>
            <xsd:element name="customer-ip-address" type="xsd:string"
                         minOccurs="0"/>
            <xsd:element name="booking-amount" type="xsd:double"/>
            <xsd:element name="customer" type="customer"/>
            <xsd:element name="payment" type="payment"/>
            <xsd:element name="provisional-book-id" type="xsd:string"
                         minOccurs="0"/>
        </xsd:sequence>
    </xsd:complexType>

    <xsd:complexType name="customer">
        <xsd:sequence>
            <xsd:element name="title" type="xsd:string"/>
            <xsd:element name="first-name" type="xsd:string"/>
            <xsd:element name="middle-name" type="xsd:string" minOccurs="0"/>
        </xsd:sequence>
    </xsd:complexType>
</xsd:schema>
</code>```

provisional_book_request.xsd

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsd:schema
    targetNamespace="provisional-book-request"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns:common="common"
    xmlns="provisional-book-request"
    elementFormDefault="qualified">

    <xsd:import schemaLocation="book_request.xsd" namespace="book-request"/>

    <xsd:element name="provisional-book-request" type="provisional-book-request"/>

    <xsd:complexType name="provisional-book-request">
        <xsd:sequence>
            <xsd:element name="nri" type="xsd:boolean"/>
            <xsd:element name="hotel-id" type="xsd:string"/>
            <xsd:element name="check-in-date" type="xsd:date"/>
            <xsd:element name="check-out-date" type="xsd:date"/>
            <xsd:element name="customer" type="customer:customer"/>
        </xsd:sequence>
    </xsd:complexType>

</xsd:schema>
</code>```

I am trying to import the complex type customer from book_request.xsd to provisional_book_request.xsd and I try to achieve it by <xsd:element name="customer" type="customer:customer"/>

But I face the following error

"Invalid attribute value for 'ref' in element 'element'. Recorded
  reason: UndeclaredPrefix: Cannot resolve 'customer:customer' as a
  QName: the prefix 'customer' is not declared."

As I am very new to XSD, any help would be appreciated

答:
Declare a namespace prefix for the imported namespace in provisional_book_request.xsd,

```<code><xsd:schema

     xmlns:br="book-request"

>
</code>```

and use it to reference the imported type:

```<code><xsd:element name="customer" type="br:customer"/>
</code>```

then your error will go away.

Here is the full provisional_book_request.xsd, corrected as described:

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsd:schema
    targetNamespace="provisional-book-request"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns="provisional-book-request"
    xmlns:br="book-request"
    elementFormDefault="qualified">
  <xsd:import schemaLocation="book_request.xsd" namespace="book-request"/>
  <xsd:element name="provisional-book-request" type="provisional-book-request"/>
  <xsd:complexType name="provisional-book-request">
    <xsd:sequence>
      <xsd:element name="nri" type="xsd:boolean"/>
      <xsd:element name="hotel-id" type="xsd:string"/>
      <xsd:element name="check-in-date" type="xsd:date"/>
      <xsd:element name="check-out-date" type="xsd:date"/>
      <xsd:element name="customer" type="br:customer"/>
    </xsd:sequence>
  </xsd:complexType>
</xsd:schema>
</code>```

Body:
I have two XSD files in different namespaces like below

book_request.xsd

<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema
    targetNamespace="book-request"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns="book-request"
    elementFormDefault="qualified">

    <xsd:element name="book-request" type="book-request"/>

    <xsd:complexType name="book-request">
        <xsd:sequence>
            <xsd:element name="booking-code" type="xsd:string"/>
            <xsd:element name="room-type-code" type="xsd:string"/>
            <xsd:element name="customer-ip-address" type="xsd:string"
                         minOccurs="0"/>
            <xsd:element name="booking-amount" type="xsd:double"/>
            <xsd:element name="customer" type="customer"/>
            <xsd:element name="payment" type="payment"/>
            <xsd:element name="provisional-book-id" type="xsd:string"
                         minOccurs="0"/>
        </xsd:sequence>
    </xsd:complexType>

    <xsd:complexType name="customer">
        <xsd:sequence>
            <xsd:element name="title" type="xsd:string"/>
            <xsd:element name="first-name" type="xsd:string"/>
            <xsd:element name="middle-name" type="xsd:string" minOccurs="0"/>
        </xsd:sequence>
    </xsd:complexType>
</xsd:schema>

provisional_book_request.xsd

<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema
    targetNamespace="provisional-book-request"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns:common="common"
    xmlns="provisional-book-request"
    elementFormDefault="qualified">

    <xsd:import schemaLocation="book_request.xsd" namespace="book-request"/>

    <xsd:element name="provisional-book-request" type="provisional-book-request"/>

    <xsd:complexType name="provisional-book-request">
        <xsd:sequence>
            <xsd:element name="nri" type="xsd:boolean"/>
            <xsd:element name="hotel-id" type="xsd:string"/>
            <xsd:element name="check-in-date" type="xsd:date"/>
            <xsd:element name="check-out-date" type="xsd:date"/>
            <xsd:element name="customer" type="customer:customer"/>
        </xsd:sequence>
    </xsd:complexType>

</xsd:schema>

I am trying to import the complex type customer from book_request.xsd to provisional_book_request.xsd and I try to achieve it by <xsd:element name="customer" type="customer:customer"/>

But I face the following error

"Invalid attribute value for 'ref' in element 'element'. Recorded
  reason: UndeclaredPrefix: Cannot resolve 'customer:customer' as a
  QName: the prefix 'customer' is not declared."

As I am very new to XSD, any help would be appreciated

Body:
Declare a namespace prefix for the imported namespace in provisional_book_request.xsd,

<xsd:schema

     xmlns:br="book-request"

>

and use it to reference the imported type:

<xsd:element name="customer" type="br:customer"/>

then your error will go away.

Here is the full provisional_book_request.xsd, corrected as described:

<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema
    targetNamespace="provisional-book-request"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns="provisional-book-request"
    xmlns:br="book-request"
    elementFormDefault="qualified">
  <xsd:import schemaLocation="book_request.xsd" namespace="book-request"/>
  <xsd:element name="provisional-book-request" type="provisional-book-request"/>
  <xsd:complexType name="provisional-book-request">
    <xsd:sequence>
      <xsd:element name="nri" type="xsd:boolean"/>
      <xsd:element name="hotel-id" type="xsd:string"/>
      <xsd:element name="check-in-date" type="xsd:date"/>
      <xsd:element name="check-out-date" type="xsd:date"/>
      <xsd:element name="customer" type="br:customer"/>
    </xsd:sequence>
  </xsd:complexType>
</xsd:schema>


问:
Using Hashtable object as body/parameter for POST request (RestSharp in Xamarin Mono)
I'm having issues making POST requests with RestSharp. My Hashtable object 'param' contains key-value pairs that must be posted to the server. I've tried several combinations and have gotten weird output on the server-side.

Example 1:

```<code>var client = new RestClient();
var request = new RestRequest(url, Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddBody (param);
</code>```

Output:

```<code>Parameters: {"_json"=>[{"Key"=>"customer_subject_id", "Value"=>"300"}, {"Key"=>"client_code", "Value"=>"337"}, {"Key"=>"reservation_id", "Value"=>"9798"}, {"Key"=>"guid", "Value"=>"ODUUME4qhLmAcBVGlT4mrGbaHcbuXZID"}, {"Key"=>"customer_client_subject_id", "Value"=>"300"}, {"Key"=>"exam_code", "Value"=>"300"}, {"Key"=>"signature", "Value"=>"6bcbffb0c8ddcd89f159cf5ddd485d1eed76d1694ba329db5431f883bac3e982"}, {"Key"=>"customer_id", "Value"=>"lol"}, {"Key"=>"session_duration", "Value"=>60}]}
</code>```

Example 2:

```<code>var client = new RestClient();
var request = new RestRequest(url, Method.POST);
foreach(DictionaryEntry entry in param){
 request.RequestFormat = DataFormat.Json;
 request.AddParameter ((entry.Key.ToString()), entry.Value);
}
</code>```

Output:

```<code>Parameters: {"customer_subject_id"=>"300", "client_code"=>"337", "reservation_id"=>"9798", "guid"=>"o9LJ5e9t52xxFhxhAoHzmYd7AiQ3nu36", "customer_client_subject_id"=>"300", "exam_code"=>"300", "signature"=>"297cd7e871df885393ebe44b262cb40b8c03e55ae1f0567ff708e9811b2aedf8", "customer_id"=>"lol", "session_duration"=>"60"}
</code>```

The output for #2 seems correct, but I'm getting a 401 on the server-side. Weirdly, the GET output matches that of #2, but the request is made successfully. I think the problem may be that the request, in total, is posting 10 parameters yet it should be posting one JSON formatted string in the body. Typically, I would put a JSON formatted string in the body, but even when I use a standalone JSON serializer to obtain a JSON string of the Hashtable and put in AddBody, I get the following:

Example 3:

```<code>var client = new RestClient();
var request = new RestRequest(url, Method.POST);
String paramJson = SimpleJson.SerializeObject (param);
request.RequestFormat = DataFormat.Json;
request.AddBody (paramJson);
</code>```

Output:

```<code>  Parameters: {"_json"=>"[{\"Key\":\"customer_subject_id\",\"Value\":\"300\"},{\"Key\":\"client_code\",\"Value\":\"337\"},{\"Key\":\"reservation_id\",\"Value\":\"9798\"},{\"Key\":\"guid\",\"Value\":\"56ZAsFtBx7jhDmdconWTb40qGirNagxK\"},{\"Key\":\"customer_client_subject_id\",\"Value\":\"300\"},{\"Key\":\"exam_code\",\"Value\":\"300\"},{\"Key\":\"signature\",\"Value\":\"57d7c878dec24da98815071d1dc3730873285b3ae65f9d98591da94266b8f7d7\"},{\"Key\":\"customer_id\",\"Value\":\"lol\"},{\"Key\":\"session_duration\",\"Value\":60}]"}
</code>```

I'm mostly curious as to why the JSON string that RestSharp is creating contains "_json" at the beginning of it.

Thanks,
John

答:
Is your server running Rails? Maybe this is relevant https://groups.google.com/forum/#!topic/rubyonrails-core/ZYBI_XHYpak

If you have control of the server side, might be better to use AddParameter and pass a JSON string, which you can parse on the server side.

Body:
I'm having issues making POST requests with RestSharp. My Hashtable object 'param' contains key-value pairs that must be posted to the server. I've tried several combinations and have gotten weird output on the server-side.

Example 1:

var client = new RestClient();
var request = new RestRequest(url, Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddBody (param);

Output:

Parameters: {"_json"=>[{"Key"=>"customer_subject_id", "Value"=>"300"}, {"Key"=>"client_code", "Value"=>"337"}, {"Key"=>"reservation_id", "Value"=>"9798"}, {"Key"=>"guid", "Value"=>"ODUUME4qhLmAcBVGlT4mrGbaHcbuXZID"}, {"Key"=>"customer_client_subject_id", "Value"=>"300"}, {"Key"=>"exam_code", "Value"=>"300"}, {"Key"=>"signature", "Value"=>"6bcbffb0c8ddcd89f159cf5ddd485d1eed76d1694ba329db5431f883bac3e982"}, {"Key"=>"customer_id", "Value"=>"lol"}, {"Key"=>"session_duration", "Value"=>60}]}

Example 2:

var client = new RestClient();
var request = new RestRequest(url, Method.POST);
foreach(DictionaryEntry entry in param){
 request.RequestFormat = DataFormat.Json;
 request.AddParameter ((entry.Key.ToString()), entry.Value);
}

Output:

Parameters: {"customer_subject_id"=>"300", "client_code"=>"337", "reservation_id"=>"9798", "guid"=>"o9LJ5e9t52xxFhxhAoHzmYd7AiQ3nu36", "customer_client_subject_id"=>"300", "exam_code"=>"300", "signature"=>"297cd7e871df885393ebe44b262cb40b8c03e55ae1f0567ff708e9811b2aedf8", "customer_id"=>"lol", "session_duration"=>"60"}

The output for #2 seems correct, but I'm getting a 401 on the server-side. Weirdly, the GET output matches that of #2, but the request is made successfully. I think the problem may be that the request, in total, is posting 10 parameters yet it should be posting one JSON formatted string in the body. Typically, I would put a JSON formatted string in the body, but even when I use a standalone JSON serializer to obtain a JSON string of the Hashtable and put in AddBody, I get the following:

Example 3:

var client = new RestClient();
var request = new RestRequest(url, Method.POST);
String paramJson = SimpleJson.SerializeObject (param);
request.RequestFormat = DataFormat.Json;
request.AddBody (paramJson);

Output:

  Parameters: {"_json"=>"[{\"Key\":\"customer_subject_id\",\"Value\":\"300\"},{\"Key\":\"client_code\",\"Value\":\"337\"},{\"Key\":\"reservation_id\",\"Value\":\"9798\"},{\"Key\":\"guid\",\"Value\":\"56ZAsFtBx7jhDmdconWTb40qGirNagxK\"},{\"Key\":\"customer_client_subject_id\",\"Value\":\"300\"},{\"Key\":\"exam_code\",\"Value\":\"300\"},{\"Key\":\"signature\",\"Value\":\"57d7c878dec24da98815071d1dc3730873285b3ae65f9d98591da94266b8f7d7\"},{\"Key\":\"customer_id\",\"Value\":\"lol\"},{\"Key\":\"session_duration\",\"Value\":60}]"}

I'm mostly curious as to why the JSON string that RestSharp is creating contains "_json" at the beginning of it.

Thanks,
John


问:
What's the advantage of making an inner class as static with Java?
I have an inner class in my Java class.

When I run find bugs, it recommends(warns) to make it as static.

What's the point of this warning? What's the advantage of making a inner class as static?

答:
We already have good answers, here are my 5 cents:

Both static and non-static inner classes are used when we need to separate logical functionalities yet using the methods and variables of the outer class. Both of the inner classes have access to the private variables of the outer class.

Advantages of static inner class:
1) static classes can access the static variables from outer class
2) static classes can be treated like an independent class

Non-static inner class:
1) cannot use static members of the outer class
2) cannot be treated like an independent class

```<code>public class NestedClassDemo {
    private int a = 100;
    int b = 200;
    private static int c = 500;

    public NestedClassDemo() {
        TestInnerStatic teststat = new TestInnerStatic();
        System.out.println("const of NestedClassDemo, a is:"+a+", b is:"+b+".."+teststat.teststat_a);
    }

    public String getTask1(){
        return new TestInnerClass().getTask1();
    }

    public String getTask2(){
        return getTask1();
    }

    class TestInnerClass{
        int test_a = 10;

        TestInnerClass() {
            System.out.println("const of testinner private member of outerlcass"+a+"..."+c);
        }
        String getTask1(){
            return "task1 from inner:"+test_a+","+a;
        }
    }

    static class TestInnerStatic{
        int teststat_a = 20;

        public TestInnerStatic() {
            System.out.println("const of testinnerstat:"+teststat_a+" member of outer:"+c);
        }

        String getTask1stat(){
            return "task1 from inner stat:"+teststat_a+","+c;
        }
    }

    public static void main(String[] args){
        TestInnerStatic teststat = new TestInnerStatic();
        System.out.println(teststat.teststat_a);
        NestedClassDemo nestdemo = new NestedClassDemo();
        System.out.println(nestdemo.getTask1()+"...."+nestdemo.getTask2());
    }
}
</code>```

Accessing the static inner and non-static inner class from outside:

```<code>public class TestClass {
    public static void main(String[] args){
        NestedClassDemo.TestInnerClass a = new NestedClassDemo().new TestInnerClass();
        NestedClassDemo.TestInnerStatic b = new NestedClassDemo.TestInnerStatic();
    }
}
</code>```

The official java doc for static inner class can be found at https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html

Body:
We already have good answers, here are my 5 cents:

Both static and non-static inner classes are used when we need to separate logical functionalities yet using the methods and variables of the outer class. Both of the inner classes have access to the private variables of the outer class.

Advantages of static inner class:
1) static classes can access the static variables from outer class
2) static classes can be treated like an independent class

Non-static inner class:
1) cannot use static members of the outer class
2) cannot be treated like an independent class

public class NestedClassDemo {
    private int a = 100;
    int b = 200;
    private static int c = 500;

    public NestedClassDemo() {
        TestInnerStatic teststat = new TestInnerStatic();
        System.out.println("const of NestedClassDemo, a is:"+a+", b is:"+b+".."+teststat.teststat_a);
    }

    public String getTask1(){
        return new TestInnerClass().getTask1();
    }

    public String getTask2(){
        return getTask1();
    }

    class TestInnerClass{
        int test_a = 10;

        TestInnerClass() {
            System.out.println("const of testinner private member of outerlcass"+a+"..."+c);
        }
        String getTask1(){
            return "task1 from inner:"+test_a+","+a;
        }
    }

    static class TestInnerStatic{
        int teststat_a = 20;

        public TestInnerStatic() {
            System.out.println("const of testinnerstat:"+teststat_a+" member of outer:"+c);
        }

        String getTask1stat(){
            return "task1 from inner stat:"+teststat_a+","+c;
        }
    }

    public static void main(String[] args){
        TestInnerStatic teststat = new TestInnerStatic();
        System.out.println(teststat.teststat_a);
        NestedClassDemo nestdemo = new NestedClassDemo();
        System.out.println(nestdemo.getTask1()+"...."+nestdemo.getTask2());
    }
}

Accessing the static inner and non-static inner class from outside:

public class TestClass {
    public static void main(String[] args){
        NestedClassDemo.TestInnerClass a = new NestedClassDemo().new TestInnerClass();
        NestedClassDemo.TestInnerStatic b = new NestedClassDemo.TestInnerStatic();
    }
}

The official java doc for static inner class can be found at https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html


问:
VGAScreen does not work on the Cosmos
I have a VGAScreen of the cosmos (with it I can create operating systems with C #), and it does not work, a mixed colors appears and then VMware closes. I'm trying to use the size 640x480, and it does not work, it worked when the size was 320x200.
My code:

```<code>screen.SetGraphicsMode(VGAScreen.ScreenSize.Size640x480,
VGAScreen.ColorDepth.BitDepth4);
screen.Clear(0);
</code>```

The OS stop after this:

Note: I am using the cosmos for VS2013.
Sorry for my english. I speak portuguese.

答: only 320x200 works on that version of cosmos, you should update to a version that is not as old</p>

Title: VGAScreen does not work on the Cosmos

Body:
I have a VGAScreen of the cosmos (with it I can create operating systems with C #), and it does not work, a mixed colors appears and then VMware closes. I'm trying to use the size 640x480, and it does not work, it worked when the size was 320x200.
My code:

screen.SetGraphicsMode(VGAScreen.ScreenSize.Size640x480,
VGAScreen.ColorDepth.BitDepth4);
screen.Clear(0);

The OS stop after this:

Note: I am using the cosmos for VS2013.
Sorry for my english. I speak portuguese.


问:
Download generated XML with Google Apps Script
I have a Google Apps script bound to a Spreadsheet that convert the spreadsheet to XML.

Is there a way to download the generated XML file onto the user computer when the task is finished ?

I want it to behave just like the "file > Download to format" function of Spreadsheet.

Thanks

答:
How about this sample script? Please think of this as one of several answers.

In order to use this sample, at first, please set file ID of your generated XML file. For this, for example, it is considered the following methods.

When users click a download button, it creates XML file and retrieves the file ID.

Save the file ID of XML file using PropertiesService when the XML file is created, and when users click a download button, it retrieves the file ID.

FLow :

The flow of this sample script is as follows.

By opening spreadsheet, create a menu for downloading at menu bar.

Also you can directly run onOpen().

When users click a download button, retrieve file ID at GAS side.

Create download URL from the file ID. Download URL and filename are sent to download(obj) of Javascript.

Create a tag for downloading and click it at Javascript side.

By this, users can download the file of file ID.

Sample scripts :

Code.gs

```<code>function onOpen() {
  SpreadsheetApp.getUi()
                .createMenu('download')
                .addItem('download files', 'dialog')
                .addToUi();
}

function dialog() {
  var html = HtmlService.createHtmlOutputFromFile('download');
  SpreadsheetApp.getUi().showModalDialog(html, 'Sample dialog');
}

function getDownloadUrl() {
  var id = "### file id ###"; // Please put file ID of your generated XLM file.

  var file = DriveApp.getFileById(id);
  return {
    url: file.getDownloadUrl().replace("?e=download&gd=true",""),
    filename: file.getName()
  };
}
</code>```

download.html

```<code><input type="button" value="download" onclick="getUrl()" />
<script>
  function getUrl() {
    google.script.run.withSuccessHandler(download).getDownloadUrl();
  }

  function download(obj) {
    var d = document.createElement('a');
    d.href = obj.url;
    d.download = obj.filename;
    d.click();
  }
</script>
</code>```

Note :

This sample script is very simple. So please modify this for your environment.

If I misunderstand your question, I'm sorry.

Body:
How about this sample script? Please think of this as one of several answers.

In order to use this sample, at first, please set file ID of your generated XML file. For this, for example, it is considered the following methods.

When users click a download button, it creates XML file and retrieves the file ID.

Save the file ID of XML file using PropertiesService when the XML file is created, and when users click a download button, it retrieves the file ID.

FLow :

The flow of this sample script is as follows.

By opening spreadsheet, create a menu for downloading at menu bar.

Also you can directly run onOpen().

When users click a download button, retrieve file ID at GAS side.

Create download URL from the file ID. Download URL and filename are sent to download(obj) of Javascript.

Create a tag for downloading and click it at Javascript side.

By this, users can download the file of file ID.

Sample scripts :

Code.gs

function onOpen() {
  SpreadsheetApp.getUi()
                .createMenu('download')
                .addItem('download files', 'dialog')
                .addToUi();
}

function dialog() {
  var html = HtmlService.createHtmlOutputFromFile('download');
  SpreadsheetApp.getUi().showModalDialog(html, 'Sample dialog');
}

function getDownloadUrl() {
  var id = "### file id ###"; // Please put file ID of your generated XLM file.

  var file = DriveApp.getFileById(id);
  return {
    url: file.getDownloadUrl().replace("?e=download&gd=true",""),
    filename: file.getName()
  };
}

download.html

<input type="button" value="download" onclick="getUrl()" />
<script>
  function getUrl() {
    google.script.run.withSuccessHandler(download).getDownloadUrl();
  }

  function download(obj) {
    var d = document.createElement('a');
    d.href = obj.url;
    d.download = obj.filename;
    d.click();
  }
</script>

Note :

This sample script is very simple. So please modify this for your environment.

If I misunderstand your question, I'm sorry.


问:
N queen (algorithm) via array not understanding few lines
http://jeffe.cs.illinois.edu/teaching/algorithms/notes/03-backtracking.pdf

enter image description here

explain the highlighted texted of image

Q[i]=j  Q[i]=j+r-i  Q[i]=j-r+i

how these statements check if two queen attack in row column or diagonals?

答:
That's a better solution than I came up with many years ago when I beat the obvious algorithm by an order of magnitude.

Fundamentally, what this is doing is instead of maintaining a board and checking the three paths that a queen can move (you only need to look behind the queen--it's the only queen on the row so you know that direction is clear an the queens ahead haven't been placed yet) which requires checking (row - 1) * 3 cells (although some are off the board, it may be cheaper to test the diagonals for bounds first) it's maintaining a one dimensional array of queens and noting what they threaten.  This reduces each placement test to 3  squares.  (And uses only addition, no multiplication.  Irrelevant now, a considerable time savings when I was playing with this.)

I haven't looked over the whole thing to see how they are doing it with one array rather than the three I did it with (column threatened, / diagonal threatened, \ diagonal threatened.  The latter arrays are twice as big.)