问:
Make image inside div take the always the same amount of space
```<code><div id=“parent”>
    <div id = "child1">
       <img src="123"/>
   </div>
   <div id = "child2">
      <p> Some text1 </p>
      <p> Some text2 </p>
   </div>
</div>
</code>```

I have parent div with fixed height. Parent div always have 2 child containers:

1 clild - div with image

2 child - div with some data

The image inside the container can be different in size. Sometimes, when image is larger, it takes more space inside #child1 and my #child2 with text becoming only half-visible. I can see the "Some text1 " paragraph, but not "Some text2".

How can I make my image inside #child1 take always same % of space inside #parent? (Probably, by zooming it in)

答:
Fixing height of the children and using background image will help. overflow will make sure that the height of the child does not go beyond 250px

```<code>#parent {
  height:500px;
}
#child1, #child2 {
  height: 250px;
  overflow:auto;
  width:100%;
}
#child1 {
  background-size:contain;
  background-position: center;
}
</code>```

HTML

```<code><div id="parent">
    <div id="child1" style="background-image:url('path');"></div>
    <div id="child2">Text</div>
</div>
</code>```

Body:
 Some text1

 Some text2

I have parent div with fixed height. Parent div always have 2 child containers:

1 clild - div with image

2 child - div with some data

The image inside the container can be different in size. Sometimes, when image is larger, it takes more space inside #child1 and my #child2 with text becoming only half-visible. I can see the "Some text1 " paragraph, but not "Some text2".

How can I make my image inside #child1 take always same % of space inside #parent? (Probably, by zooming it in)

Body:
Fixing height of the children and using background image will help. overflow will make sure that the height of the child does not go beyond 250px

#parent {
  height:500px;
}
#child1, #child2 {
  height: 250px;
  overflow:auto;
  width:100%;
}
#child1 {
  background-size:contain;
  background-position: center;
}

HTML

<div id="parent">
    <div id="child1" style="background-image:url('path');"></div>
    <div id="child2">Text</div>
</div>


来源: stackexchange

问:
How to print exponential number "m³" using ESC/POS printer with C#?
I'm trying to print a ticket, and need to print out m³ as unit of measurement using a serial printer. And the following is what I have tried so far:

```<code>if (!printer.IsOpen)
    printer.Open();

printer.WriteLine(string.Format("{0} m{1}", "2.34", Convert.ToChar(0xB3)));

printer.Close();
</code>```

When I tried to debug and view the value using the text visualizer the text is correct which is "2.34 m³". But when it comes to printing, the text changed to "2.34 m?", where the expected output should be "2.34 m³".

I've been trying to figure this out for days. Please help. Thanks.

答: What font are you using?  I think the font you're using doesn't support that character, which is why it put a ?.  During debug it shows the right character because visual studio is using a font that does support that character.  Try choosing a different font and see if that helps.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to print a ticket, and need to print out m³ as unit of measurement using a serial printer. And the following is what I have tried so far:

if (!printer.IsOpen)
    printer.Open();

printer.WriteLine(string.Format("{0} m{1}", "2.34", Convert.ToChar(0xB3)));

printer.Close();

When I tried to debug and view the value using the text visualizer the text is correct which is "2.34 m³". But when it comes to printing, the text changed to "2.34 m?", where the expected output should be "2.34 m³".

I've been trying to figure this out for days. Please help. Thanks.


问:
How to output attributes of resources created?
I'm executing a GCP module to create a service account.

main.tf:

```<code>resource "google_service_account" "gsvc_account" {
    account_id   = "xxx"
    display_name = ""
    project      = "proj-yyy"
}

output "account_id" {
    value = "${google_service_account.gsvc_account.account_id}"
}
</code>```

Once the account is created, a terraform.tfstate file is created containing all details of the account.

terraform.tfstate

```<code>{
    "version": 4,
    "terraform_version": "0.12.0",
    "serial": 3,
    "lineage": "aaaa-bbbb-cccc",
    "outputs": {
        "xxx": {
            "value": "xxx",
            "type": "string"
        }
    },
    "resources": [
      {
            "module": "module.gsvc_tf",
            "mode": "managed",
            "type": "google_service_account",
            "name": "gsvc_account",
            "provider": "provider.google",
            "instances": [
                {
                    "schema_version": 0,
                    "attributes": {
                        "account_id": "xxx",
                        "display_name": "",
                        "email": "xxx@yyy.com",
                        "id": "projects/proj-yyy/serviceAccounts/xxx@yyy.com",
                        "name": "projects/proj-yyy/serviceAccounts/xxx@yyy.com",
                        "policy_data": null,
                        "project": "proj-xxx",
                        "unique_id": "10891885"
                    }
                }
            ]
        }
    ]
}
</code>```

As you can see above, in the module, I'm outputing the account_id input variable. Is there a way to output the attributes viz. id, name etc. so that they can be accessed by another module? The attributes are computed after the resource is created.

答:
If your other module is ran against a different state file (eg your Terraform code is in a separate directory) then you might be better off using the google_service_account data source instead of trying to output the values of the resource to your state file and using the terraform_remote_state data source to fetch them.

The documentation for the google_service_account data source shows a nice example of how you would use this:

```<code>data "google_service_account" "myaccount" {
  account_id = "myaccount-id"
}

resource "google_service_account_key" "mykey" {
  service_account_id = "${data.google_service_account.myaccount.name}"
}

resource "kubernetes_secret" "google-application-credentials" {
  metadata = {
    name = "google-application-credentials"
  }
  data {
    credentials.json = "${base64decode(google_service_account_key.mykey.private_key)}"
  }
}
</code>```

This avoids needing to configure your remote state data source and can be significantly simpler. In fact, this is the way I'd recommend accessing information about an existing resource in any case where the provider has a suitable data source. I'd even go so far as to recommend the external data source over the terraform_remote_state data source if there's another way to get at that information (eg through a cloud providers CLI) just because the terraform_remote_state data source is particularly clunky.

Body:
I'm executing a GCP module to create a service account.

main.tf:

resource "google_service_account" "gsvc_account" {
    account_id   = "xxx"
    display_name = ""
    project      = "proj-yyy"
}

output "account_id" {
    value = "${google_service_account.gsvc_account.account_id}"
}

Once the account is created, a terraform.tfstate file is created containing all details of the account.

terraform.tfstate

{
    "version": 4,
    "terraform_version": "0.12.0",
    "serial": 3,
    "lineage": "aaaa-bbbb-cccc",
    "outputs": {
        "xxx": {
            "value": "xxx",
            "type": "string"
        }
    },
    "resources": [
      {
            "module": "module.gsvc_tf",
            "mode": "managed",
            "type": "google_service_account",
            "name": "gsvc_account",
            "provider": "provider.google",
            "instances": [
                {
                    "schema_version": 0,
                    "attributes": {
                        "account_id": "xxx",
                        "display_name": "",
                        "email": "xxx@yyy.com",
                        "id": "projects/proj-yyy/serviceAccounts/xxx@yyy.com",
                        "name": "projects/proj-yyy/serviceAccounts/xxx@yyy.com",
                        "policy_data": null,
                        "project": "proj-xxx",
                        "unique_id": "10891885"
                    }
                }
            ]
        }
    ]
}

As you can see above, in the module, I'm outputing the account_id input variable. Is there a way to output the attributes viz. id, name etc. so that they can be accessed by another module? The attributes are computed after the resource is created.

Body:
If your other module is ran against a different state file (eg your Terraform code is in a separate directory) then you might be better off using the google_service_account data source instead of trying to output the values of the resource to your state file and using the terraform_remote_state data source to fetch them.

The documentation for the google_service_account data source shows a nice example of how you would use this:

data "google_service_account" "myaccount" {
  account_id = "myaccount-id"
}

resource "google_service_account_key" "mykey" {
  service_account_id = "${data.google_service_account.myaccount.name}"
}

resource "kubernetes_secret" "google-application-credentials" {
  metadata = {
    name = "google-application-credentials"
  }
  data {
    credentials.json = "${base64decode(google_service_account_key.mykey.private_key)}"
  }
}

This avoids needing to configure your remote state data source and can be significantly simpler. In fact, this is the way I'd recommend accessing information about an existing resource in any case where the provider has a suitable data source. I'd even go so far as to recommend the external data source over the terraform_remote_state data source if there's another way to get at that information (eg through a cloud providers CLI) just because the terraform_remote_state data source is particularly clunky.


问:
remove a contour from image using skimage
I want to remove some contour from an image but I don't know how to achieve it using skimage? I do something like this in OpenCV using drawContour but I can't find the equivalent in skimage.

Assume I have a simple image like:

```<code>0 0 0 0 0 0 0 0

0 0 1 1 1 1 0 0

0 0 1 0 0 1 0 0

0 0 1 1 1 1 0 0

0 0 0 0 0 0 0 0
</code>```

that has only one connected component.

I need to remove it by masking it.

The final result will be a 8 * 5 zero matrix!

```<code>a = '''0 0 0 0 0 0 0 0
0 0 1 1 1 1 0 0
0 0 1 0 0 1 0 0
0 0 1 1 1 1 0 0
0 0 0 0 0 0 0 0'''
np.array([int(i) for i in a.split()], dtype=bool).reshape(5, 8)
cc = measure.regionprops(measure.label(a))[0]
# here is what I do for removing cc
</code>```

What should I do to remove cc connected component using skimage?

答:
In this case, you need to turn the image to a binary image (as you have) and then follow these steps:

1 - Fill holes.

2 - recognize contour.

3 - create a black mask (false or 0) using the recognized contours.

```<code>from skimage import measure, draw
from scipy import ndimage as ndi

# I use this function "ndi.distance_transform_edt(thresh)" to turn my image to a binary image
def remove_contours(binary_image):
    binary_image = ndi.binary_fill_holes(binary_image)
    contours= measure.find_contours(binary_image, 0.9, fully_connected='high',
                                     positive_orientation='low')
    #Fill contours with False. (it could be 0 as well)
    for n, contour in enumerate(contours):
        draw.set_color(binary_image , draw.polygon(contour[:, 0], contour[:, 1]), False)
    return binary_image

</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to remove some contour from an image but I don't know how to achieve it using skimage? I do something like this in OpenCV using drawContour but I can't find the equivalent in skimage.

Assume I have a simple image like:

0 0 0 0 0 0 0 0

0 0 1 1 1 1 0 0

0 0 1 0 0 1 0 0

0 0 1 1 1 1 0 0

0 0 0 0 0 0 0 0

that has only one connected component.

I need to remove it by masking it.

The final result will be a 8 * 5 zero matrix!

a = '''0 0 0 0 0 0 0 0
0 0 1 1 1 1 0 0
0 0 1 0 0 1 0 0
0 0 1 1 1 1 0 0
0 0 0 0 0 0 0 0'''
np.array([int(i) for i in a.split()], dtype=bool).reshape(5, 8)
cc = measure.regionprops(measure.label(a))[0]
# here is what I do for removing cc

What should I do to remove cc connected component using skimage?

Body:
In this case, you need to turn the image to a binary image (as you have) and then follow these steps:

1 - Fill holes.

2 - recognize contour.

3 - create a black mask (false or 0) using the recognized contours.

from skimage import measure, draw
from scipy import ndimage as ndi

# I use this function "ndi.distance_transform_edt(thresh)" to turn my image to a binary image
def remove_contours(binary_image):
    binary_image = ndi.binary_fill_holes(binary_image)
    contours= measure.find_contours(binary_image, 0.9, fully_connected='high',
                                     positive_orientation='low')
    #Fill contours with False. (it could be 0 as well)
    for n, contour in enumerate(contours):
        draw.set_color(binary_image , draw.polygon(contour[:, 0], contour[:, 1]), False)
    return binary_image


问:
Java Applet Error Launching
I've created a small Java Applet to run for a company website. I'm currently using Eclipse for development and I've run into problems while trying to launch the application from the appropriate web page. My employee has placed the correct .JAR file in with the HTML file of the page itself, and is calling the applet with the following code:

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>

<applet code=OrderForm.class name=OrderForm archive=OrderForm.jar
    width=700 height=1100 >
    <param name="bgcolor" value="ffffff">
    <param name="fontcolor" value="000000">
    Your browser is not Java enabled.
</applet>

</body>
</html>
</code>```

All this seems correct to me, the JAR file is correctly labeled, and the .class file is correct. When the page opens, I get the message "Error. Click for Details", but when I click the 'X', the page freezes and doesn't show me any error details.

The JAR file was exported using Eclipse and I'm sure that I've included all the necessary files to compile (as it compiles perfectly with the Java Applet Viewer in Eclipse). Here's the applet below, it's simply a testing applet I created because of some past errors I was receiving when trying to run a larger applet on the company website, so this covers the basic functionality of the applet itself, thanks.

```<code>package OrderForm;

import javax.swing.JPanel;
import javax.swing.JApplet;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JLabel;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JCheckBox;
import javax.swing.SwingUtilities;

import java.awt.Rectangle;
import java.lang.reflect.InvocationTargetException;

import javax.swing.JButton;

@SuppressWarnings("serial")
public class OrderForm extends JApplet {

    private JPanel mainPanel = null;  //  @jve:decl-index=0:visual-constraint="10,10"
    private JLabel titleLabel = null;
    private JLabel customerInfoLabel = null;
    private JLabel distributorLabel = null;
    private JLabel customerNameLabel = null;
    private JLabel existingCustomerLabel = null;
    private JLabel industryLabel = null;
    private JLabel emailAddressLabel = null;
    private JButton testing = null;
    private JTextField text_customerName = null;
    private JTextField text_emailAddress = null;
    private JComboBox distributors = null;
    private JComboBox industries = null;
    private JCheckBox check_existingCustomer = null;
    /**
     * This is the xxx default constructor
     */
    public OrderForm() {
        super();
    }

    /**
     * This method initializes this
     *
     * @return void
     */
    public void init() {
        try
        {
            SwingUtilities.invokeAndWait(new Runnable()
            {
                public void run()
                {
                    setSize(645, 373);
                    setContentPane(getJContentPane());
                }
            });
        }
        catch (InterruptedException e) { e.printStackTrace(); }
        catch (InvocationTargetException e) { e.printStackTrace(); }
    }

    /**
     * This method initializes mainPanel
     *
     * @return javax.swing.JPanel
     */
    private JPanel getJContentPane() {
        if (mainPanel == null) {
            emailAddressLabel = new JLabel();
            emailAddressLabel.setBounds(new Rectangle(164, 226, 137, 16));
            emailAddressLabel.setText("Email Address:");
            industryLabel = new JLabel();
            industryLabel.setBounds(new Rectangle(165, 196, 136, 16));
            industryLabel.setText("Industry:");
            existingCustomerLabel = new JLabel();
            existingCustomerLabel.setBounds(new Rectangle(165, 165, 136, 16));
            existingCustomerLabel.setText("Existing Customer?:");
            customerNameLabel = new JLabel();
            customerNameLabel.setBounds(new Rectangle(166, 134, 135, 16));
            customerNameLabel.setText("Customer Name:");
            distributorLabel = new JLabel();
            distributorLabel.setBounds(new Rectangle(165, 105, 136, 16));
            distributorLabel.setText("Distributor:");
            customerInfoLabel = new JLabel();
            customerInfoLabel.setBounds(new Rectangle(30, 60, 166, 31));
            customerInfoLabel.setText("Customer Information");
            titleLabel = new JLabel();
            titleLabel.setBounds(new Rectangle(180, 15, 286, 40));
            titleLabel.setText("Order Form");
            mainPanel = new JPanel();
            mainPanel.setSize(new Dimension(624, 1055));
            mainPanel.setLayout(null);
            mainPanel.setBackground(Color.white);
            mainPanel.add(titleLabel, null);
            mainPanel.add(customerInfoLabel, null);
            mainPanel.add(distributorLabel, null);
            mainPanel.add(customerNameLabel, null);
            mainPanel.add(existingCustomerLabel, null);
            mainPanel.add(industryLabel, null);
            mainPanel.add(emailAddressLabel, null);
            mainPanel.add(getTesting(), null);
            mainPanel.add(getText_customerName(), null);
            mainPanel.add(getText_emailAddress(), null);
            mainPanel.add(getDistributors(), null);
            mainPanel.add(getIndustries(), null);
            mainPanel.add(getCheck_existingCustomer(), null);
        }
        return mainPanel;
    }

    /**
     * This method initializes testing
     *
     * @return javax.swing.JButton
     */
    private JButton getTesting() {
        if (testing == null) {
            testing = new JButton();
            testing.setBounds(new Rectangle(225, 285, 181, 61));
            testing.setText("TEST");
            testing.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent e) {
                    String distSelected = (String) distributors.getSelectedItem();
                    String industrySelected = (String) industries.getSelectedItem();

                    if(distSelected.equals("            "))
                        JOptionPane.showMessageDialog(null, "No Distributor Selected.", "Error", JOptionPane.INFORMATION_MESSAGE);
                    else if(industrySelected.equals("            "))
                        JOptionPane.showMessageDialog(null, "No Industry Selected.", "Error", JOptionPane.INFORMATION_MESSAGE);
                    else if(text_customerName.getText().length() == 0)
                        JOptionPane.showMessageDialog(null, "No Name Entered.", "Error", JOptionPane.INFORMATION_MESSAGE);
                    else if(text_emailAddress.getText().length() == 0)
                        JOptionPane.showMessageDialog(null, "No Email Entered.", "Error", JOptionPane.INFORMATION_MESSAGE);
                    else
                        JOptionPane.showMessageDialog(null, "Data Entered Successfully", "Success", JOptionPane.INFORMATION_MESSAGE);

                }
            });
        }
        return testing;
    }

    /**
     * This method initializes text_customerName
     *
     * @return javax.swing.JTextField
     */
    private JTextField getText_customerName() {
        if (text_customerName == null) {
            text_customerName = new JTextField();
            text_customerName.setBounds(new Rectangle(300, 135, 121, 16));
        }
        return text_customerName;
    }

    /**
     * This method initializes text_emailAddress
     *
     * @return javax.swing.JTextField
     */
    private JTextField getText_emailAddress() {
        if (text_emailAddress == null) {
            text_emailAddress = new JTextField();
            text_emailAddress.setBounds(new Rectangle(300, 225, 121, 16));
        }
        return text_emailAddress;
    }

    /**
     * This method initializes distributors
     *
     * @return javax.swing.JComboBox
     */
    private JComboBox getDistributors() {
        if (distributors == null) {
            distributors = new JComboBox();
            distributors.setBounds(new Rectangle(300, 105, 121, 16));

            String[] distributorList = getDistributorList();

            for(String d:distributorList)
                distributors.addItem(d);
        }
        return distributors;
    }

    /**
     * Initialize the list of distributors for the drop-down list
     * @return String[] containing the names of all distributors
     */
    private String[] getDistributorList()
    {
        String[] distributors =
        {
                "            ",
                "a1envirotech", "Beun-De Ronde B.V.", "Biolab A/S", "BRS", "Camlab Ltd.", "DKSH Australia Pty Ltd.", "DKSH New Zealand Ltd.",
                "DKSH - Malaysia", "DKSH - Philippines", "DKSH - Singapore", "DKSH - Vietnam", "E&C Technology Co., Ltd.", "FKV s.r.l.",
                "G&W Marketing", "LICA United Technology Ltd.", "Mandel Scientific Company Inc.", "Mansci (Aaron Gotway)", "Mansci (Chris Copeland)",
                "Mansci (Jake Bolotin)", "Mansci (Matt Grey)", "Mansci (Wes Floyd)", "Serlabo", "Southern Systems Ltd.", "TM - Autolab",
                "Wirsam Scientific"
        };
        return distributors;
    }

    /**
     * This method initializes industries
     *
     * @return javax.swing.JComboBox
     */
    private JComboBox getIndustries() {
        if (industries == null) {
            industries = new JComboBox();
            industries.setBounds(new Rectangle(300, 195, 121, 16));

            String[] industryList = getIndustryList();
            for(String i:industryList)
                industries.addItem(i);
        }
        return industries;
    }

    /**
     * Initialize the list of industries for the drop-down list
     */
    private String[] getIndustryList()
    {
        String[] industries =
        {
                "            ", "Commercial Lab", "Environmental", "Food / Wine", "Government", "Marine Lab",
                "Other", "Petro Chemical", "Power Generation", "Pulp & Paper", "University"
        };
        return industries;
    }

    /**
     * This method initializes check_existingCustomer
     *
     * @return javax.swing.JCheckBox
     */
    private JCheckBox getCheck_existingCustomer() {
        if (check_existingCustomer == null) {
            check_existingCustomer = new JCheckBox();
            check_existingCustomer.setBounds(new Rectangle(300, 165, 31, 16));
        }
        return check_existingCustomer;
    }

}  //  @jve:decl-index=0:visual-constraint="10,10"
</code>```

答: Your JApplet is in the (unconventionally named) package OrderForm, but your <applet> tag does not reflect this.

Title: Java Applet Error Launching

Body:
I've created a small Java Applet to run for a company website. I'm currently using Eclipse for development and I've run into problems while trying to launch the application from the appropriate web page. My employee has placed the correct .JAR file in with the HTML file of the page itself, and is calling the applet with the following code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

<applet code=OrderForm.class name=OrderForm archive=OrderForm.jar
    width=700 height=1100 >
    <param name="bgcolor" value="ffffff">
    <param name="fontcolor" value="000000">
    Your browser is not Java enabled.
</applet>

All this seems correct to me, the JAR file is correctly labeled, and the .class file is correct. When the page opens, I get the message "Error. Click for Details", but when I click the 'X', the page freezes and doesn't show me any error details.

The JAR file was exported using Eclipse and I'm sure that I've included all the necessary files to compile (as it compiles perfectly with the Java Applet Viewer in Eclipse). Here's the applet below, it's simply a testing applet I created because of some past errors I was receiving when trying to run a larger applet on the company website, so this covers the basic functionality of the applet itself, thanks.

package OrderForm;

import javax.swing.JPanel;
import javax.swing.JApplet;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JLabel;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JCheckBox;
import javax.swing.SwingUtilities;

import java.awt.Rectangle;
import java.lang.reflect.InvocationTargetException;

import javax.swing.JButton;

@SuppressWarnings("serial")
public class OrderForm extends JApplet {

    private JPanel mainPanel = null;  //  @jve:decl-index=0:visual-constraint="10,10"
    private JLabel titleLabel = null;
    private JLabel customerInfoLabel = null;
    private JLabel distributorLabel = null;
    private JLabel customerNameLabel = null;
    private JLabel existingCustomerLabel = null;
    private JLabel industryLabel = null;
    private JLabel emailAddressLabel = null;
    private JButton testing = null;
    private JTextField text_customerName = null;
    private JTextField text_emailAddress = null;
    private JComboBox distributors = null;
    private JComboBox industries = null;
    private JCheckBox check_existingCustomer = null;
    /**
     * This is the xxx default constructor
     */
    public OrderForm() {
        super();
    }

    /**
     * This method initializes this
     *
     * @return void
     */
    public void init() {
        try
        {
            SwingUtilities.invokeAndWait(new Runnable()
            {
                public void run()
                {
                    setSize(645, 373);
                    setContentPane(getJContentPane());
                }
            });
        }
        catch (InterruptedException e) { e.printStackTrace(); }
        catch (InvocationTargetException e) { e.printStackTrace(); }
    }

    /**
     * This method initializes mainPanel
     *
     * @return javax.swing.JPanel
     */
    private JPanel getJContentPane() {
        if (mainPanel == null) {
            emailAddressLabel = new JLabel();
            emailAddressLabel.setBounds(new Rectangle(164, 226, 137, 16));
            emailAddressLabel.setText("Email Address:");
            industryLabel = new JLabel();
            industryLabel.setBounds(new Rectangle(165, 196, 136, 16));
            industryLabel.setText("Industry:");
            existingCustomerLabel = new JLabel();
            existingCustomerLabel.setBounds(new Rectangle(165, 165, 136, 16));
            existingCustomerLabel.setText("Existing Customer?:");
            customerNameLabel = new JLabel();
            customerNameLabel.setBounds(new Rectangle(166, 134, 135, 16));
            customerNameLabel.setText("Customer Name:");
            distributorLabel = new JLabel();
            distributorLabel.setBounds(new Rectangle(165, 105, 136, 16));
            distributorLabel.setText("Distributor:");
            customerInfoLabel = new JLabel();
            customerInfoLabel.setBounds(new Rectangle(30, 60, 166, 31));
            customerInfoLabel.setText("Customer Information");
            titleLabel = new JLabel();
            titleLabel.setBounds(new Rectangle(180, 15, 286, 40));
            titleLabel.setText("Order Form");
            mainPanel = new JPanel();
            mainPanel.setSize(new Dimension(624, 1055));
            mainPanel.setLayout(null);
            mainPanel.setBackground(Color.white);
            mainPanel.add(titleLabel, null);
            mainPanel.add(customerInfoLabel, null);
            mainPanel.add(distributorLabel, null);
            mainPanel.add(customerNameLabel, null);
            mainPanel.add(existingCustomerLabel, null);
            mainPanel.add(industryLabel, null);
            mainPanel.add(emailAddressLabel, null);
            mainPanel.add(getTesting(), null);
            mainPanel.add(getText_customerName(), null);
            mainPanel.add(getText_emailAddress(), null);
            mainPanel.add(getDistributors(), null);
            mainPanel.add(getIndustries(), null);
            mainPanel.add(getCheck_existingCustomer(), null);
        }
        return mainPanel;
    }

    /**
     * This method initializes testing
     *
     * @return javax.swing.JButton
     */
    private JButton getTesting() {
        if (testing == null) {
            testing = new JButton();
            testing.setBounds(new Rectangle(225, 285, 181, 61));
            testing.setText("TEST");
            testing.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent e) {
                    String distSelected = (String) distributors.getSelectedItem();
                    String industrySelected = (String) industries.getSelectedItem();

                    if(distSelected.equals("            "))
                        JOptionPane.showMessageDialog(null, "No Distributor Selected.", "Error", JOptionPane.INFORMATION_MESSAGE);
                    else if(industrySelected.equals("            "))
                        JOptionPane.showMessageDialog(null, "No Industry Selected.", "Error", JOptionPane.INFORMATION_MESSAGE);
                    else if(text_customerName.getText().length() == 0)
                        JOptionPane.showMessageDialog(null, "No Name Entered.", "Error", JOptionPane.INFORMATION_MESSAGE);
                    else if(text_emailAddress.getText().length() == 0)
                        JOptionPane.showMessageDialog(null, "No Email Entered.", "Error", JOptionPane.INFORMATION_MESSAGE);
                    else
                        JOptionPane.showMessageDialog(null, "Data Entered Successfully", "Success", JOptionPane.INFORMATION_MESSAGE);

                }
            });
        }
        return testing;
    }

    /**
     * This method initializes text_customerName
     *
     * @return javax.swing.JTextField
     */
    private JTextField getText_customerName() {
        if (text_customerName == null) {
            text_customerName = new JTextField();
            text_customerName.setBounds(new Rectangle(300, 135, 121, 16));
        }
        return text_customerName;
    }

    /**
     * This method initializes text_emailAddress
     *
     * @return javax.swing.JTextField
     */
    private JTextField getText_emailAddress() {
        if (text_emailAddress == null) {
            text_emailAddress = new JTextField();
            text_emailAddress.setBounds(new Rectangle(300, 225, 121, 16));
        }
        return text_emailAddress;
    }

    /**
     * This method initializes distributors
     *
     * @return javax.swing.JComboBox
     */
    private JComboBox getDistributors() {
        if (distributors == null) {
            distributors = new JComboBox();
            distributors.setBounds(new Rectangle(300, 105, 121, 16));

            String[] distributorList = getDistributorList();

            for(String d:distributorList)
                distributors.addItem(d);
        }
        return distributors;
    }

    /**
     * Initialize the list of distributors for the drop-down list
     * @return String[] containing the names of all distributors
     */
    private String[] getDistributorList()
    {
        String[] distributors =
        {
                "            ",
                "a1envirotech", "Beun-De Ronde B.V.", "Biolab A/S", "BRS", "Camlab Ltd.", "DKSH Australia Pty Ltd.", "DKSH New Zealand Ltd.",
                "DKSH - Malaysia", "DKSH - Philippines", "DKSH - Singapore", "DKSH - Vietnam", "E&C Technology Co., Ltd.", "FKV s.r.l.",
                "G&W Marketing", "LICA United Technology Ltd.", "Mandel Scientific Company Inc.", "Mansci (Aaron Gotway)", "Mansci (Chris Copeland)",
                "Mansci (Jake Bolotin)", "Mansci (Matt Grey)", "Mansci (Wes Floyd)", "Serlabo", "Southern Systems Ltd.", "TM - Autolab",
                "Wirsam Scientific"
        };
        return distributors;
    }

    /**
     * This method initializes industries
     *
     * @return javax.swing.JComboBox
     */
    private JComboBox getIndustries() {
        if (industries == null) {
            industries = new JComboBox();
            industries.setBounds(new Rectangle(300, 195, 121, 16));

            String[] industryList = getIndustryList();
            for(String i:industryList)
                industries.addItem(i);
        }
        return industries;
    }

    /**
     * Initialize the list of industries for the drop-down list
     */
    private String[] getIndustryList()
    {
        String[] industries =
        {
                "            ", "Commercial Lab", "Environmental", "Food / Wine", "Government", "Marine Lab",
                "Other", "Petro Chemical", "Power Generation", "Pulp & Paper", "University"
        };
        return industries;
    }

    /**
     * This method initializes check_existingCustomer
     *
     * @return javax.swing.JCheckBox
     */
    private JCheckBox getCheck_existingCustomer() {
        if (check_existingCustomer == null) {
            check_existingCustomer = new JCheckBox();
            check_existingCustomer.setBounds(new Rectangle(300, 165, 31, 16));
        }
        return check_existingCustomer;
    }

}  //  @jve:decl-index=0:visual-constraint="10,10"


问:
Selecting person and their multiple letter ids?
Trying to use sql to grab all users from a location "E.g. Boston" and grab all their letter ids. For example it should return something similar to this:

```<code>username  | letterID
Sam Smith | 5278665, 674943, 6549343
Jane Lenna| 8759385, 439533
</code>```

In my Persons Table I have: userID, username, location, etc.

In my Letter Table I have: letterID, userID, title, description, etc.

答:
You should simply use a join:

```<code>select a.username, b.letterID from persons a, letter b where a.userID = b.userID and a.location = 'Boston';
</code>```

The result will be two columns with the username and the corresponding letter ID. A user would have as many rows in the result set as he has letters.

```<code>username  | letterID
Sam Smith | 5278665
Sam Smith | 674943
Sam Smith | 6549343
Jane Lenna| 8759385
Jane Lenna| 439533
</code>```

If you see the same user name and letter ID more than once in the result than simply use a distinct in the query.

Iterate over the resulting rows and process the data anyway you like, including inserting them into a data structure you deem reasonable for your task.

Body:
Trying to use sql to grab all users from a location "E.g. Boston" and grab all their letter ids. For example it should return something similar to this:

username  | letterID
Sam Smith | 5278665, 674943, 6549343
Jane Lenna| 8759385, 439533

In my Persons Table I have: userID, username, location, etc.

In my Letter Table I have: letterID, userID, title, description, etc.

Body:
You should simply use a join:

select a.username, b.letterID from persons a, letter b where a.userID = b.userID and a.location = 'Boston';

The result will be two columns with the username and the corresponding letter ID. A user would have as many rows in the result set as he has letters.

username  | letterID
Sam Smith | 5278665
Sam Smith | 674943
Sam Smith | 6549343
Jane Lenna| 8759385
Jane Lenna| 439533

If you see the same user name and letter ID more than once in the result than simply use a distinct in the query.

Iterate over the resulting rows and process the data anyway you like, including inserting them into a data structure you deem reasonable for your task.


问:
MS Bot framework emulator chang user id
Is there a way to change the default user id (which is 'default-user')  in bot emulator?

Or maybe it supports something about multi conversations in the same time?

I want to emulate two different users at the same time (because I have multiple user types in my project.

When I try to create new conversation like this

```<code>....
var connector = new ConnectorClient(new Uri(context.Activity.ServiceUrl));
var userAccount = new ChannelAccount("//here we need to provide user id which is always default-user", "Provider");
var botAccount = context.Activity.Recipient;

var conversation = await connector.Conversations.CreateDirectConversationAsync(botAccount, userAccount);
var message = context.MakeMessage();
message.Recipient = userAccount;
message.From = botAccount;
message.Conversation = new ConversationAccount(false, conversation.Id);
await connector.Conversations.SendToConversationAsync((Activity) message);
</code>```

My emulator opens new conversation in the same chat-window

答: I work on the Bot Framework Emulator. We've recently added the ability to override generated user ids to be used in conversations without the need of a tool like Fiddler. You can utilize this feature in our latest release. I hope you find this useful for your scenario.</p>

Title: MS Bot framework emulator chang user id

Body:
Is there a way to change the default user id (which is 'default-user')  in bot emulator?

Or maybe it supports something about multi conversations in the same time?

I want to emulate two different users at the same time (because I have multiple user types in my project.

When I try to create new conversation like this

....
var connector = new ConnectorClient(new Uri(context.Activity.ServiceUrl));
var userAccount = new ChannelAccount("//here we need to provide user id which is always default-user", "Provider");
var botAccount = context.Activity.Recipient;

var conversation = await connector.Conversations.CreateDirectConversationAsync(botAccount, userAccount);
var message = context.MakeMessage();
message.Recipient = userAccount;
message.From = botAccount;
message.Conversation = new ConversationAccount(false, conversation.Id);
await connector.Conversations.SendToConversationAsync((Activity) message);

My emulator opens new conversation in the same chat-window


问:
Are there built-in extension methods in the .NET framework that don't apply to LINQ?
For the purpose of a course I am developing, I am looking for some examples of where Microsoft has already implemented extension methods themselves. But since the students are not yet acquainted to LINQ, I would like to find some other example.

So, are there any methods defined in the .NET framework that are defined as an extension method, but do not refer to the LINQ framework or IEnumerable?

答:
.net uses them in GetCustomAttributes<T>for example.
See here.


答:
Try something like this:</p>

```<code>SELECT
  p.username,
  l.letterID
FROM
  Persons p
  Join Letter l on l.userID = p.userID
WHERE
  p.location = "Boston"
</code>```

Title: Selecting person and their multiple letter ids?

Body:
Try something like this:

SELECT
  p.username,
  l.letterID
FROM
  Persons p
  Join Letter l on l.userID = p.userID
WHERE
  p.location = "Boston"


问:
How to calculate pi in tkinter using Buffon’s needles?
I know there are many tutorials on how to calculate pi using Buffon's needles, but I didn't find any in tkinter.

I am a beginner, so sorry about the dirty code, but I will shortly walk you through it.

After drawing the setup it generates random x1 and y1 coordinates for the starting point of the line. Note that I want the lines to be 50 units long. So I generate x_rel which can be in a range -50 to 50. After that using Pythagorean's theorem, I calculate y_rel. Randomly it can be made negative or it can stay positive. To get the ending coordinates of the line, you just add up x_rel and x1, same for y.

To detect a collision with one of the starting lines on the board, I compare the first number of the y1 and y2. If they are the same, then there is no collision (this works because the gap between each starting line on the board is 100). After the counted collisions, I just calculate the pi and print it. But it usually returns ~2,6. But other programs like this which I have found online can calculate pi in this way fairly accurate. Where is my error?

```<code>import tkinter as tk
import random
import math

count = 0
class App:

    def __init__(self, root):

        self.root = root
        root.title("PI calculator")

        c = tk.Canvas(root, height=700, width=700)
        c.pack()
        c.create_line(100, 100, 600, 100)
        c.create_line(100, 200, 600, 200)
        c.create_line(100, 300, 600, 300)
        c.create_line(100, 400, 600, 400)
        c.create_line(100, 500, 600, 500)
        c.create_line(100, 600, 600, 600)
        for x in range(100000):
            c.create_line(self.generate_coords(), fill="red", width=1.5)

    def generate_coords(self):
        choices = [1, 0]
        x1 = random.randint(100, 600)
        y1 = random.randint(100, 600)
        x_rel = random.randint(-50, 50)
        y_rel = math.sqrt(50**2 - x_rel**2)
        if random.choice(choices) == 1:
            y_rel = -abs(y_rel)
        if random.choice(choices) == 0:
            y_rel = abs(y_rel)
        x2 = x1 + x_rel
        y2 = y1 + y_rel
        col = self.detect_collision(y1, y2)
        if col == True:
            global count
            count += 1
        return x1, y1, x2, y2

    def detect_collision(self, y1, y2):
        first_num_1 = math.floor(y1/100)
        first_num_2 = math.floor(y2 / 100)
        if first_num_1 != first_num_2:
            return True
        else:
            return False

root = tk.Tk()
window = App(root)
pi = (2*50*100000)/(100*count)
print(count)
print(pi)
root.mainloop()

38243
2.6148576210025363
</code>```

答:
I played around with your code and compared it with similar programs and the conclusion I came to is that your pin drops weren't as random as they should be and this was skewing your results.  Below I've reworked the pin dropping logic and the results seem to have improved:

```<code>import tkinter as tk
import random
import math

NUMBER_STICKS = 250
LINE_DISTANCE = 100
STICK_LENGTH = 83

class App:

    def __init__(self, root):

        self.root = root
        root.title("PI calculator")

        self.collisions = 0

        c = tk.Canvas(root, height=700, width=700)
        c.pack()

        for y in range(1, 7):
            c.create_line(100, y * LINE_DISTANCE, 600, y * LINE_DISTANCE)

        for _ in range(NUMBER_STICKS):
            collision, *coords = self.generate_coords()
            c.create_line(coords, fill="red" if collision else "green", width=1.5)

    def generate_coords(self):

        x1 = random.randint(100, 600)
        y1 = random.randint(100, 600)

        angle = random.randrange(360)
        x2 = x1 + STICK_LENGTH * math.cos(math.radians(angle))
        y2 = y1 + STICK_LENGTH * math.sin(math.radians(angle))

        collision = self.detect_collision(y1, y2)

        if collision:
            self.collisions += 1

        return collision, x1, y1, x2, y2

    def detect_collision(self, y1, y2):
        num_1 = y1 // LINE_DISTANCE
        num_2 = y2 // LINE_DISTANCE

        return num_1 != num_2

    def get_collisions(self):
        return self.collisions

root = tk.Tk()
application = App(root)

collisions = application.get_collisions()
print((2 * STICK_LENGTH * NUMBER_STICKS) / (LINE_DISTANCE * collisions))

root.mainloop()
</code>```

OUTPUT

```<code>% python3 test.py
3.516949152542373
%
</code>```

I also modified the program to color code the pins as crossing or not crossing the lines:

Body:
I know there are many tutorials on how to calculate pi using Buffon's needles, but I didn't find any in tkinter.

I am a beginner, so sorry about the dirty code, but I will shortly walk you through it.

After drawing the setup it generates random x1 and y1 coordinates for the starting point of the line. Note that I want the lines to be 50 units long. So I generate x_rel which can be in a range -50 to 50. After that using Pythagorean's theorem, I calculate y_rel. Randomly it can be made negative or it can stay positive. To get the ending coordinates of the line, you just add up x_rel and x1, same for y.

To detect a collision with one of the starting lines on the board, I compare the first number of the y1 and y2. If they are the same, then there is no collision (this works because the gap between each starting line on the board is 100). After the counted collisions, I just calculate the pi and print it. But it usually returns ~2,6. But other programs like this which I have found online can calculate pi in this way fairly accurate. Where is my error?

import tkinter as tk
import random
import math

count = 0
class App:

    def __init__(self, root):

        self.root = root
        root.title("PI calculator")

        c = tk.Canvas(root, height=700, width=700)
        c.pack()
        c.create_line(100, 100, 600, 100)
        c.create_line(100, 200, 600, 200)
        c.create_line(100, 300, 600, 300)
        c.create_line(100, 400, 600, 400)
        c.create_line(100, 500, 600, 500)
        c.create_line(100, 600, 600, 600)
        for x in range(100000):
            c.create_line(self.generate_coords(), fill="red", width=1.5)

    def generate_coords(self):
        choices = [1, 0]
        x1 = random.randint(100, 600)
        y1 = random.randint(100, 600)
        x_rel = random.randint(-50, 50)
        y_rel = math.sqrt(50**2 - x_rel**2)
        if random.choice(choices) == 1:
            y_rel = -abs(y_rel)
        if random.choice(choices) == 0:
            y_rel = abs(y_rel)
        x2 = x1 + x_rel
        y2 = y1 + y_rel
        col = self.detect_collision(y1, y2)
        if col == True:
            global count
            count += 1
        return x1, y1, x2, y2

    def detect_collision(self, y1, y2):
        first_num_1 = math.floor(y1/100)
        first_num_2 = math.floor(y2 / 100)
        if first_num_1 != first_num_2:
            return True
        else:
            return False

root = tk.Tk()
window = App(root)
pi = (2*50*100000)/(100*count)
print(count)
print(pi)
root.mainloop()

38243
2.6148576210025363

Body:
I played around with your code and compared it with similar programs and the conclusion I came to is that your pin drops weren't as random as they should be and this was skewing your results.  Below I've reworked the pin dropping logic and the results seem to have improved:

import tkinter as tk
import random
import math

NUMBER_STICKS = 250
LINE_DISTANCE = 100
STICK_LENGTH = 83

class App:

    def __init__(self, root):

        self.root = root
        root.title("PI calculator")

        self.collisions = 0

        c = tk.Canvas(root, height=700, width=700)
        c.pack()

        for y in range(1, 7):
            c.create_line(100, y * LINE_DISTANCE, 600, y * LINE_DISTANCE)

        for _ in range(NUMBER_STICKS):
            collision, *coords = self.generate_coords()
            c.create_line(coords, fill="red" if collision else "green", width=1.5)

    def generate_coords(self):

        x1 = random.randint(100, 600)
        y1 = random.randint(100, 600)

        angle = random.randrange(360)
        x2 = x1 + STICK_LENGTH * math.cos(math.radians(angle))
        y2 = y1 + STICK_LENGTH * math.sin(math.radians(angle))

        collision = self.detect_collision(y1, y2)

        if collision:
            self.collisions += 1

        return collision, x1, y1, x2, y2

    def detect_collision(self, y1, y2):
        num_1 = y1 // LINE_DISTANCE
        num_2 = y2 // LINE_DISTANCE

        return num_1 != num_2

    def get_collisions(self):
        return self.collisions

root = tk.Tk()
application = App(root)

collisions = application.get_collisions()
print((2 * STICK_LENGTH * NUMBER_STICKS) / (LINE_DISTANCE * collisions))

root.mainloop()

OUTPUT

% python3 test.py
3.516949152542373
%

I also modified the program to color code the pins as crossing or not crossing the lines:


问:
Assign negative value to char in Java
I want to assign a negative value to char in Java.
Example: char a='-1'
I tried the below example but an error occurs.

```<code> char[] temp=new char[10];
    for(int i=0;i<10;i++)
    {
        if(condition met)
        temp[i]='-1';
    }
</code>```

答: '-' and '1' are two separate chars, and they cannot be stored in a single char variable. Use a String instead. If you are using -1 as some sort of an exit case, use some alphabetical character instead like x.

Title: Assign negative value to char in Java

Body:
I want to assign a negative value to char in Java.
Example: char a='-1'
I tried the below example but an error occurs.

 char[] temp=new char[10];
    for(int i=0;i<10;i++)
    {
        if(condition met)
        temp[i]='-1';
    }


问:
Katalon UI recorder fails to run for date and radio buttons
I'm new to Katalon Studio.

I did UI web (chrome) recording for my application which has 14 entries.

When i run the test it lauches the browser and continues until it fails at the date selection object.

I deleted the date object and ran again but then it failed at a radio button.

I am using Katalon Suite version 6.1.5

Also, please suggest if I can use another tool for automated testing that simply runs this test without the need of workarounds for date or radio buttons ?

答:
You should detect elements by xpath or set correct xpath (You can get xpath of object with your browser.) for recorded elements under Object Repository. Please check this article: https://docs.katalon.com/katalon-studio/tutorials/detect_elements_xpath.html#issue-in-identifying-nested-elements

EDIT
You can use these identifiers to identify object in calendar.


问:
Using regexmatch & filter inside arrayformula (Google Sheets)
I have a functional Google Sheets formula, that I try to modify, in order to execute as array formula, so that I no longer need to copy-paste in every cell. Can you help?

I try the usual approach:

```<code>=arrayformula(if(len(A2:a)>0,iferror(transpose(filter(Dashboard!B:B, regexmatch(Dashboard!c:c, d2:d))),"-"),""))
</code>```

but is not working (i think is repeating the result from the first line on the whole column).

the simple version:

```<code>=if(len(A2)>0,iferror(transpose(filter(Dashboard!B:B, regexmatch(Dashboard!c:c, d2))),"-"),"")
</code>```

the array version:....?

答:
```<code>=ARRAYFORMULA(IF(LEN(A2:A), IFERROR(VLOOKUP(REGEXEXTRACT(D2:D, TRANSPOSE(SUBSTITUTE(
 TRIM(QUERY(TRANSPOSE(QUERY(TRANSPOSE(IFERROR(SPLIT(Dashboard!C2:C, ",")))
 ,,999^99)),,999^99)), " ", "|"))), TRIM(SPLIT(TRANSPOSE(SPLIT(QUERY(TRANSPOSE(QUERY(
 TRANSPOSE(IF(IFERROR(SPLIT(Dashboard!C2:C, ","))<>"", "♠"&IFERROR(
 SPLIT(Dashboard!C2:C, ","))&"♦"&Dashboard!B2:B, ))
 ,,999^99)),,999^99), "♠")), "♦")), 2, 0), "-"), ))
</code>```

Body:
I have a functional Google Sheets formula, that I try to modify, in order to execute as array formula, so that I no longer need to copy-paste in every cell. Can you help?

I try the usual approach:

=arrayformula(if(len(A2:a)>0,iferror(transpose(filter(Dashboard!B:B, regexmatch(Dashboard!c:c, d2:d))),"-"),""))

but is not working (i think is repeating the result from the first line on the whole column).

the simple version:

=if(len(A2)>0,iferror(transpose(filter(Dashboard!B:B, regexmatch(Dashboard!c:c, d2))),"-"),"")

the array version:....?


问:
How do I fix the syntax error at "TO" in \copy?
I'm trying to copy the results of a SQL query to a CSV file with \copy. However, I am getting a syntax error at TO and I can't quire figure out why.

Note that executing the SQL query works in psql, but I get an error when I try to export the query's results out of \copy into a CSV file.

```<code>\COPY
(SELECT
event_number,
event_type,
unit,
received,
split_part(entry::TEXT,' ',1)entry_year,
split_part(entry::TEXT,' ',2)entry_time,
split_part(dispatch::TEXT,' ',1)dispatch_year,
split_part(dispatch::TEXT,' ',2)dispatch_time,
split_part(ack::TEXT,' ',1)ack_year,
split_part(ack::TEXT,' ',2)ack_time,
enroute,
split_part(onscene::TEXT,' ',1)onscene_year,
split_part(onscene::TEXT,' ',2)onscene_time,
split_part(to_hospital::TEXT,' ',1)to_hospital_year,
split_part(to_hospital::TEXT,' ',2)to_hospital_time,
at_hospital,
return_to_qrtrs,
split_part(available_in_qrtrs::TEXT,' ',1)available_in_qrtrs_year,
split_part(available_in_qrtrs::TEXT,' ',2)available_in_qrtrs_time,
split_part(last_col::TEXT,' ',1)last_col_year,
split_part(last_col::TEXT,' ',2)last_col_time
FROM import.oems)
TO '/Users/ctoner/Desktop/oems/foia_190910/formatoems.csv' WITH CSV DELIMETER ',' HEADER;

ERROR:  syntax error at or near "TO"
LINE 24: TO '/Users/ctoner/Desktop/oems/foia_190910/formatoems.csv'
</code>```

答:
There's a Typo in your query

at line TO '/Users/ctoner/Desktop/oems/foia_190910/formatoems.csv' WITH CSV DELIMETER ',' HEADER;

Replace DELIMETER with DELIMITER

Also, the documentation says the file should be present on the server already.

Body:
I'm trying to copy the results of a SQL query to a CSV file with \copy. However, I am getting a syntax error at TO and I can't quire figure out why.

Note that executing the SQL query works in psql, but I get an error when I try to export the query's results out of \copy into a CSV file.

\COPY
(SELECT
event_number,
event_type,
unit,
received,
split_part(entry::TEXT,' ',1)entry_year,
split_part(entry::TEXT,' ',2)entry_time,
split_part(dispatch::TEXT,' ',1)dispatch_year,
split_part(dispatch::TEXT,' ',2)dispatch_time,
split_part(ack::TEXT,' ',1)ack_year,
split_part(ack::TEXT,' ',2)ack_time,
enroute,
split_part(onscene::TEXT,' ',1)onscene_year,
split_part(onscene::TEXT,' ',2)onscene_time,
split_part(to_hospital::TEXT,' ',1)to_hospital_year,
split_part(to_hospital::TEXT,' ',2)to_hospital_time,
at_hospital,
return_to_qrtrs,
split_part(available_in_qrtrs::TEXT,' ',1)available_in_qrtrs_year,
split_part(available_in_qrtrs::TEXT,' ',2)available_in_qrtrs_time,
split_part(last_col::TEXT,' ',1)last_col_year,
split_part(last_col::TEXT,' ',2)last_col_time
FROM import.oems)
TO '/Users/ctoner/Desktop/oems/foia_190910/formatoems.csv' WITH CSV DELIMETER ',' HEADER;

ERROR:  syntax error at or near "TO"
LINE 24: TO '/Users/ctoner/Desktop/oems/foia_190910/formatoems.csv'


问:
Program execution stops after catching runtime exception
I am executing a code that throws IllegalStateException. I want to catch that exception and continue the program execution but my program stops execution when this exception is encountered.

I have tried placing try{} catch{} block at multiple places. Also, tried using

```<code>Platform.runLater(new Runnable(){
                    @Override
                    public void run() { }
});
</code>```

to catch this exception.

```<code>try {
    List<ItemStandardFields> output = response.body().getContents();
    Platform.runLater(new Runnable(){
        @Override
        public void run() { }
    });
            // some code
}catch(Exception ex){
    log.error(ex.getLocalizedMessage());
}
</code>```

Actual - My program execution stops after getting exception at output = ...getContents();
Expected - I want my program to continue execution after catching exception.

答:
You can put your code in a new thread and use the Thread class's defaultUncaughtExceptionHandler. Please check the following code.</p>

```<code> public static void main(String[] args) {

      Thread thread = new Thread(new MyThread());

      thread.setDefaultUncaughtExceptionHandler(new Thread.
      UncaughtExceptionHandler() {
         public void uncaughtException(Thread t, Throwable e) {
            log.error(ex.getLocalizedMessage());
         }
      });
      thread.start();

    }
    }

    class MyThread implements Runnable {

       public void run() {
          List<ItemStandardFields> output = response.body().getContents();
       }
    }
</code>```

Body:
I am executing a code that throws IllegalStateException. I want to catch that exception and continue the program execution but my program stops execution when this exception is encountered.

I have tried placing try{} catch{} block at multiple places. Also, tried using

Platform.runLater(new Runnable(){
                    @Override
                    public void run() { }
});

to catch this exception.

try {
    List<ItemStandardFields> output = response.body().getContents();
    Platform.runLater(new Runnable(){
        @Override
        public void run() { }
    });
            // some code
}catch(Exception ex){
    log.error(ex.getLocalizedMessage());
}

Actual - My program execution stops after getting exception at output = ...getContents();
Expected - I want my program to continue execution after catching exception.

Body:
You can put your code in a new thread and use the Thread class's defaultUncaughtExceptionHandler. Please check the following code.

 public static void main(String[] args) {

      Thread thread = new Thread(new MyThread());

      thread.setDefaultUncaughtExceptionHandler(new Thread.
      UncaughtExceptionHandler() {
         public void uncaughtException(Thread t, Throwable e) {
            log.error(ex.getLocalizedMessage());
         }
      });
      thread.start();

    }
    }

    class MyThread implements Runnable {

       public void run() {
          List<ItemStandardFields> output = response.body().getContents();
       }
    }


问:
No token response returned when using Trusted Origin in Direct Line OAuth
I seem to be hitting an issue when using trusted origins with the OAuthPrompt (Generic Oauth2 w/ ADB2C) and a waterfall dialog. The first step is ensuring the user is authenticated, the next collects the token response from the step context result and continues. This all works fine w/ the magic code.

```<code>public async Task<DialogTurnResult> EnsureUserAuthenticated(WaterfallStepContext sc, CancellationToken cancellationToken)
{
     return await sc.BeginDialogAsync(nameof(OAuthPrompt), null, cancellationToken);
}

public async Task<DialogTurnResult> AskForDateTime(WaterfallStepContext sc, CancellationToken cancellationToken)

{
     var tokenResponse = sc.Result as TokenResponse;
     ...
}
</code>```

I've tried this locally and in Azure and after the auth browser window closes, nothing happens. You have to re-trigger the waterfall dialog to get the token response returned in the 2nd step.

This bot is being surfaced using CDN WebChat.

Any ideas what may be going wrong?

答:
This link helped me: https://blog.botframework.com/2018/09/25/enhanced-direct-line-authentication-features/

My understanding is that by default, WebChat is secured so that OAuthCard sign-in links do not result in a ‘verification code’ response.
The Emulator uses the WebChat control to display the conversation with the bot.

We could simulate the magic token experience inside emulator . For that ensure that ‘Use a sign-in verification code for OAuthCards’ is checked inside the settings of the emulator.If it works inside emulator ,the code is perfectly fine.

Body:
I seem to be hitting an issue when using trusted origins with the OAuthPrompt (Generic Oauth2 w/ ADB2C) and a waterfall dialog. The first step is ensuring the user is authenticated, the next collects the token response from the step context result and continues. This all works fine w/ the magic code.

public async Task<DialogTurnResult> EnsureUserAuthenticated(WaterfallStepContext sc, CancellationToken cancellationToken)
{
     return await sc.BeginDialogAsync(nameof(OAuthPrompt), null, cancellationToken);
}

public async Task<DialogTurnResult> AskForDateTime(WaterfallStepContext sc, CancellationToken cancellationToken)

{
     var tokenResponse = sc.Result as TokenResponse;
     ...
}

I've tried this locally and in Azure and after the auth browser window closes, nothing happens. You have to re-trigger the waterfall dialog to get the token response returned in the 2nd step.

This bot is being surfaced using CDN WebChat.

Any ideas what may be going wrong?


问:
How can i get Setup.rul file of an old InstallShield Installer from its exe file?
I have an old InstallShield installer which i believe was made using InstallShield 2012. I don't have the install script code for the same. I only have exe of the installer with me.

I need to create a new installer containing some of the same features from old installer, so is there any way by which i can get the setup.rul file of the installer from its exe?

I did some googling but got no help.

答:
Setup.exe Extraction: If you run an extraction of your setup.exe, do you get an *.ins file?

Programmatically extract contents of InstallShield setup.exe

Extract MSI from EXE

Decompiler: I believe there are some hacky solutions to decompile *.ins to *.rul. I do not have such a tool, nor have I ever tried one and I can't recall seeing any trace of them for a whole decade. Perhaps Installshield support can help?

Alternatives: Off the top of my head: Contact Installshield support, they might have better advice? Check with Installshield community? Check with Stefan Kruger - Installshield consultant? Check any source repositories you can find based on setup.exe timestamp? (search for *.rul, *.ism, or similar as relevant). Check backups? Check backups of setup developer PC? Check github.com even? (for samples of similar tasks). Check external media, email attachments, network shares, etc...


问:
asyncio: running task only if all other tasks are awaiting
I am currently running some endless tasks using asyncio.wait

I need a special function to run when all the others are on await

```<code>import asyncio

async def special_function():
    while True:
        # does some work,
        # Passes control back to controller to run main_tasks
        # if they are no longer waiting.
        await asyncio.sleep(0)

async def handler():
    tasks = [task() for task in main_tasks]

    # Adding the task that I want to run when all main_tasks are awaiting:
    tasks.append(special_function())

    await asyncio.wait(tasks)

asyncio.get_event_loop().run_until_complete(handler())
</code>```

How can I get  the special_function to only be run when all main_tasks are on await?

Edit:

What I mean by "all main_tasks are on await": all main_tasks are not ready to continue, e.g. are in asyncio.sleep(100) or I/O bound and still waiting for data.

Therefore the main_tasks cannot continue and the event loop runs the special_function while the tasks are in this state, NOT every iteration of the event loop.

Edit 2:

My use case:

The main_tasks are updating a data structure with new data from web-sockets.

The special_function transfers that data to another process upon an update signal from that process. (multiprocessing with shared variables and data structures)

It needs to be the most up to date data it can be when it transfers, there cannot be pending updates from main_tasks.

This is why I only want to run special_function when there are no main_tasks with new data available to be processed. (i.e. all waiting on await)

答:
Push both the input and output requests onto a PriorityQueue with the input prioritized over the output. Then just process tasks from the queue normally and it will always fulfill all outstanding input requests before any output ones.

So your main loop would consist of something like the following:

InputListener1 (queues each InputTask1 received at priority 0)

InputListener2 (queues each InputTask2 received at priority 0)

InputListener3 (queues each InputTask3 received at priority 0)

OutputListener (queues each OutputTask received at priority 1)

QueueWorker (processes the next task from the queue)

This likely means you'll have to split the logic for all of your existing tasks into separate socket listeners and the actual task processing, but that's not necessarily a bad thing.

Body:
I am currently running some endless tasks using asyncio.wait

I need a special function to run when all the others are on await

import asyncio

async def special_function():
    while True:
        # does some work,
        # Passes control back to controller to run main_tasks
        # if they are no longer waiting.
        await asyncio.sleep(0)

async def handler():
    tasks = [task() for task in main_tasks]

    # Adding the task that I want to run when all main_tasks are awaiting:
    tasks.append(special_function())

    await asyncio.wait(tasks)

asyncio.get_event_loop().run_until_complete(handler())

How can I get  the special_function to only be run when all main_tasks are on await?

Edit:

What I mean by "all main_tasks are on await": all main_tasks are not ready to continue, e.g. are in asyncio.sleep(100) or I/O bound and still waiting for data.

Therefore the main_tasks cannot continue and the event loop runs the special_function while the tasks are in this state, NOT every iteration of the event loop.

Edit 2:

My use case:

The main_tasks are updating a data structure with new data from web-sockets.

The special_function transfers that data to another process upon an update signal from that process. (multiprocessing with shared variables and data structures)

It needs to be the most up to date data it can be when it transfers, there cannot be pending updates from main_tasks.

This is why I only want to run special_function when there are no main_tasks with new data available to be processed. (i.e. all waiting on await)


问:
Need to mock a custom class for unit testing purposes
This question is in relation to a Previous question I posted.

As mentioned i was able to refactor the original code into two separate classes; I am now trying to test the portion (ParseDataTable) that is not reliant upon Office.Interop objects by mocking the portion (ExcelManager) that is.

When I run the tests my mocked object is only partially working, The GetColumnCount method is being properly mocked and returning my local variable within the ParseDataTable object.

However the GetData mocked method is not being called, the code instead goes into the GetData method on the ExcelManager class

The code used to create the mock:

```<code>MockExcel = new Mock<ExcelManager>("testfile.xls",0);
        MockExcel.Setup(x => x.GetColumnCount()).Returns(columnCount);
        MockExcel.Setup(x => x.GetData()).Returns(mockData);
        MockExcel.Setup(x => x.Initialize());
</code>```

columnCount and mockData are both local variables to the test with data that I am basing my tests on.

The class I am testing:

```<code>public class ParseDataTable
{
    private const string TableSortOrder = "1 asc, 4 asc, 6 asc";

    public DataTable GetRangeValue(ExcelManager excelManager)
    {
        var columnCount = excelManager.GetColumnCount();
        var sheetData = excelManager.GetData();

        var value = new DataTable();

        for (var j = 1; j <= columnCount; j++)
        {
            value.Columns.Add(j.ToString());
        }

        for (var i = 1; i <= sheetData.GetLength(0); i++)
        {
            var row = value.NewRow();
            var emptyCount = 0;
            for (var j = 1; j <= columnCount; j++)
            {
                row[j - 1] = sheetData[i, j] ?? "";
                if ((string)row[j-1] == "")
                {
                    emptyCount++;
                }
            }

            //if row is empty then no more data is expected
            if (emptyCount == value.Columns.Count) break;

            value.Rows.Add(row);
        }

        excelManager.Dispose();
        return sortDataTable(value);
    }

    private DataTable sortDataTable(DataTable table)
    {
        table.DefaultView.Sort = TableSortOrder;
        table = table.DefaultView.ToTable();
        return table;
    }
}
</code>```

Methods within the ExcelManager class that need to be mocked:

```<code>        public virtual int GetColumnCount()
    {
        var headerRng = _worksheet.get_Range(HeaderFirstCell, _miss);
        headerRng = headerRng.get_End(XlDirection.xlToRight);
        headerRng = _worksheet.get_Range(HeaderFirstCell, headerRng);
        var headerData = (object[,])headerRng.Value2;
        return headerData.GetLength(1);
    }

    public virtual object[,] GetData()
    {
        var last = _worksheet.Cells.SpecialCells(XlCellType.xlCellTypeLastCell, Type.Missing);
        var dataRng = _worksheet.get_Range(DataFirstCell, last);
        return (object[,])dataRng.Value2;
    }
</code>```

答: Wouldn't it be much easier if you extracted an interface from ExcelManager as an interface (you can call it IExcelManager, but tell everybody that i came up with the brilliant name :-) ? If you passed that instead your mocking difficulties should be less of a pain. </p>

ContentLicense: CC BY-SA 2.5

Body:
This question is in relation to a Previous question I posted.

As mentioned i was able to refactor the original code into two separate classes; I am now trying to test the portion (ParseDataTable) that is not reliant upon Office.Interop objects by mocking the portion (ExcelManager) that is.

When I run the tests my mocked object is only partially working, The GetColumnCount method is being properly mocked and returning my local variable within the ParseDataTable object.

However the GetData mocked method is not being called, the code instead goes into the GetData method on the ExcelManager class

The code used to create the mock:

MockExcel = new Mock<ExcelManager>("testfile.xls",0);
        MockExcel.Setup(x => x.GetColumnCount()).Returns(columnCount);
        MockExcel.Setup(x => x.GetData()).Returns(mockData);
        MockExcel.Setup(x => x.Initialize());

columnCount and mockData are both local variables to the test with data that I am basing my tests on.

The class I am testing:

public class ParseDataTable
{
    private const string TableSortOrder = "1 asc, 4 asc, 6 asc";

    public DataTable GetRangeValue(ExcelManager excelManager)
    {
        var columnCount = excelManager.GetColumnCount();
        var sheetData = excelManager.GetData();

        var value = new DataTable();

        for (var j = 1; j <= columnCount; j++)
        {
            value.Columns.Add(j.ToString());
        }

        for (var i = 1; i <= sheetData.GetLength(0); i++)
        {
            var row = value.NewRow();
            var emptyCount = 0;
            for (var j = 1; j <= columnCount; j++)
            {
                row[j - 1] = sheetData[i, j] ?? "";
                if ((string)row[j-1] == "")
                {
                    emptyCount++;
                }
            }

            //if row is empty then no more data is expected
            if (emptyCount == value.Columns.Count) break;

            value.Rows.Add(row);
        }

        excelManager.Dispose();
        return sortDataTable(value);
    }

    private DataTable sortDataTable(DataTable table)
    {
        table.DefaultView.Sort = TableSortOrder;
        table = table.DefaultView.ToTable();
        return table;
    }
}

Methods within the ExcelManager class that need to be mocked:

        public virtual int GetColumnCount()
    {
        var headerRng = _worksheet.get_Range(HeaderFirstCell, _miss);
        headerRng = headerRng.get_End(XlDirection.xlToRight);
        headerRng = _worksheet.get_Range(HeaderFirstCell, headerRng);
        var headerData = (object[,])headerRng.Value2;
        return headerData.GetLength(1);
    }

    public virtual object[,] GetData()
    {
        var last = _worksheet.Cells.SpecialCells(XlCellType.xlCellTypeLastCell, Type.Missing);
        var dataRng = _worksheet.get_Range(DataFirstCell, last);
        return (object[,])dataRng.Value2;
    }


问:
How to insert datetime value as dd-mmm-yyyy hh:mm:ss AM/PM format in SQL Server
I'm new to SQL Server, I want to insert a datetime value as in the following format dd-mmm-yyyy hh:mm:ss AM/PM (31-May-2019 11:06:37 PM).

To do so, I have used the following code:

```<code>REPLACE(CONVERT(NVARCHAR, (GETDATE()), 106), ' ', '-') + ' ' +
      LTRIM(RIGHT(CONVERT(VARCHAR(30), GETDATE(), 22), 11))
</code>```

Output : 31-May-2019 11:06:37 PM

Column datatype : datetime

When I execute the following query, I get the result as I expect, but while using this in an insert statement, it stores the value as follows

```<code>2019-05-31 23:02:47.000
</code>```

The format has changed.

Can anyone help me to fix this?

答:
It's good that you store it as datetime. Now you can display it in selects/reports as you want using convert(). Check this cheatsheet.

You can also use format():

```<code>SELECT FORMAT(cast('2019-05-31 23:02:47.000' as datetime), 'dd-MMM-yyyy hh:mm:ss tt') as datetime
</code>```

Body:
I'm new to SQL Server, I want to insert a datetime value as in the following format dd-mmm-yyyy hh:mm:ss AM/PM (31-May-2019 11:06:37 PM).

To do so, I have used the following code:

REPLACE(CONVERT(NVARCHAR, (GETDATE()), 106), ' ', '-') + ' ' +
      LTRIM(RIGHT(CONVERT(VARCHAR(30), GETDATE(), 22), 11))

Output : 31-May-2019 11:06:37 PM

Column datatype : datetime

When I execute the following query, I get the result as I expect, but while using this in an insert statement, it stores the value as follows

2019-05-31 23:02:47.000

The format has changed.

Can anyone help me to fix this?

Body:
It's good that you store it as datetime. Now you can display it in selects/reports as you want using convert(). Check this cheatsheet.

You can also use format():

SELECT FORMAT(cast('2019-05-31 23:02:47.000' as datetime), 'dd-MMM-yyyy hh:mm:ss tt') as datetime


问:
display notification Firebase in text view
I have implemented firebase cloud messaging in my app. I have been receiving messages I want to display that message in the textview of the app.

Here is the code to handle onMessageReceived..

```<code>public class FcmMessagingService extends FirebaseMessagingService {
    private Map<String, String> data;
    private static final String TAG="MyFirebaseMsgService";
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);
        data=remoteMessage.getData();
        String message=data.get("message");
        String titledata=data.get("title");
        ManualNotification(titledata , message);
    }
private void ManualNotification(String title , String messageBody){
        Intent intent = new Intent(this, MainActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("message", messageBody);
        intent.putExtras(bundle);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
        Bitmap bmp = BitmapFactory.decodeResource(this.getResources(),R.drawable.splash_img);
        Notification.BigPictureStyle bigpicture = new Notification.BigPictureStyle();
        bigpicture.bigPicture(bmp);
        NotificationCompat.Builder notificationBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.notifaction)
                .setContentTitle(title)
                //.setContentText(messageBody)
                .setLargeIcon(bmp)
                .setContentIntent(pendingIntent)
                .setStyle(new NotificationCompat.BigTextStyle().bigText(messageBody))
                .setContentText(messageBody).setLights(Color.YELLOW, 300, 300)
                .setVibrate(new long[] { 100, 250 })
                .setDefaults(Notification.DEFAULT_SOUND)
                .setAutoCancel(true);
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(0, notificationBuilder.build());
    }
}
</code>```

答: Manifest, how will look. Firebaserequired 2 service(instances and messages) another one we are using broadcast in it. so need to add anything for receiving option. </p>

Body:
I have implemented firebase cloud messaging in my app. I have been receiving messages I want to display that message in the textview of the app.

Here is the code to handle onMessageReceived..

public class FcmMessagingService extends FirebaseMessagingService {
    private Map<String, String> data;
    private static final String TAG="MyFirebaseMsgService";
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);
        data=remoteMessage.getData();
        String message=data.get("message");
        String titledata=data.get("title");
        ManualNotification(titledata , message);
    }
private void ManualNotification(String title , String messageBody){
        Intent intent = new Intent(this, MainActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("message", messageBody);
        intent.putExtras(bundle);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
        Bitmap bmp = BitmapFactory.decodeResource(this.getResources(),R.drawable.splash_img);
        Notification.BigPictureStyle bigpicture = new Notification.BigPictureStyle();
        bigpicture.bigPicture(bmp);
        NotificationCompat.Builder notificationBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.notifaction)
                .setContentTitle(title)
                //.setContentText(messageBody)
                .setLargeIcon(bmp)
                .setContentIntent(pendingIntent)
                .setStyle(new NotificationCompat.BigTextStyle().bigText(messageBody))
                .setContentText(messageBody).setLights(Color.YELLOW, 300, 300)
                .setVibrate(new long[] { 100, 250 })
                .setDefaults(Notification.DEFAULT_SOUND)
                .setAutoCancel(true);
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(0, notificationBuilder.build());
    }
}


问:
Find and print num of solutions to x1+x2+x3=num
I need to write a recusive function that recive an integer num and returns the number of solutions to the equation :x1 + x2 + x3 = num, where x1,x2,x3 are numbers between 1-10, the method should print all solutions.

For example if num=3 then the method will print 1+1+1 and will return 1.

if num=5 the method will return 6 and will print:

```<code>1 + 1 + 3
1 + 2 + 2
1 + 3 + 1
2 + 1 + 2
2 + 2 + 1
3 + 1 + 1
</code>```

if num<3 or num>30 the method will return 0.

The method should be recursive without using loops. Global variables are not allowed. Lists are also not allowed.

Here my code, it works fine but it also prints duplicates, for num=5 it prints:

```<code>3 + 1 + 1
2 + 2 + 1
2 + 1 + 2
2 + 2 + 1
1 + 3 + 1
1 + 2 + 2
2 + 1 + 2
1 + 2 + 2
1 + 1 + 3
</code>```

Here is my code:

```<code>public static void main(String[] args) {
    System.out.println("num of solutions: "+solutions(5));

}

public static int solutions(int num)
{

    if (num < 3 || num > 30)
        return 0;

    return solutions(num, 1, 1, 1);
}
private static int solutions(int num, int x1, int x2, int x3)
{
    if (x1 < 1 || x1 > 10 || x2 < 1 || x2 > 10||x3 < 1 || x3 > 10)
        return 0;
    if (x1 + x2 + x3 > num)
        return 0;
    if (x1 + x2 + x3 == num)
    {
        System.out.println(x1 + " + " + x2 + " + " + x3);
        return 1;
    }
    return solutions(num, x1 + 1, x2, x3) + solutions(num, x1, x2 + 1, x3) + solutions(num, x1, x2, x3 + 1);

}
</code>```

How do I get the desired output without duplicates?

答:
Try this :

public static void main(String... args) {
    System.out.println(solutions(5));
}
public static int solutions(int n) {

    if (n < 3 || n > 30) return 0;
    return solutions(n, n-2, 1, 1, 0);

}

public static int solutions(int n, int x1, int x2, int x3, int solutions) {

    ++solutions;
    System.out.println("Solution found : "+x1 +"+" + x2 + "+" + x3);

    if(x3 == n-2) return solutions;

    if(x2 > 1) {
        return solutions(n, x1, x2-1, x3+1, solutions);
    }

    if(x1 > 1) {
        return solutions(n, x1-1, n-x1, 1, solutions);
    }
    return solutions;
}
```

Output : 6

The idea is the following :

You start with x1 the greatest as possible.

Then you follow these two rules :

if x2 > 1 THEN x2 = x2 - 1 and x3 = x3 + 1

if not, and if x1 > 1 THEN x1 = x1 - 1, x3 = 1 and x2 = the number required to have the correct total.

If none of these two conditions are true, there is no more solutions.

Result :

3 + 1 + 1

First condition false, second true :
We remove 1 to x1, x3 becomes 1 and x2 becomes logically 2

2 + 2 + 1

First condition is true.
We remove 1 to x2 and add 1 to x3

2 + 1 + 2

First condition is false

Second condition is true

1 + 3 + 1

First condition is true

1 + 2 + 2

First condition is true

1 + 1 + 3

First condition is false, second is false.

We have our 6 solutions, so there it is.

Hope that helped !

Body:
I need to write a recusive function that recive an integer num and returns the number of solutions to the equation :x1 + x2 + x3 = num, where x1,x2,x3 are numbers between 1-10, the method should print all solutions.

For example if num=3 then the method will print 1+1+1 and will return 1.

if num=5 the method will return 6 and will print:

1 + 1 + 3
1 + 2 + 2
1 + 3 + 1
2 + 1 + 2
2 + 2 + 1
3 + 1 + 1

if num<3 or num>30 the method will return 0.

The method should be recursive without using loops. Global variables are not allowed. Lists are also not allowed.

Here my code, it works fine but it also prints duplicates, for num=5 it prints:

3 + 1 + 1
2 + 2 + 1
2 + 1 + 2
2 + 2 + 1
1 + 3 + 1
1 + 2 + 2
2 + 1 + 2
1 + 2 + 2
1 + 1 + 3

Here is my code:

public static void main(String[] args) {
    System.out.println("num of solutions: "+solutions(5));

}

public static int solutions(int num)
{

    if (num < 3 || num > 30)
        return 0;

    return solutions(num, 1, 1, 1);
}
private static int solutions(int num, int x1, int x2, int x3)
{
    if (x1 < 1 || x1 > 10 || x2 < 1 || x2 > 10||x3 < 1 || x3 > 10)
        return 0;
    if (x1 + x2 + x3 > num)
        return 0;
    if (x1 + x2 + x3 == num)
    {
        System.out.println(x1 + " + " + x2 + " + " + x3);
        return 1;
    }
    return solutions(num, x1 + 1, x2, x3) + solutions(num, x1, x2 + 1, x3) + solutions(num, x1, x2, x3 + 1);

}

How do I get the desired output without duplicates?

Body:
Try this :

public static void main(String... args) {
    System.out.println(solutions(5));
}
public static int solutions(int n) {

    if (n < 3 || n > 30) return 0;
    return solutions(n, n-2, 1, 1, 0);

}

public static int solutions(int n, int x1, int x2, int x3, int solutions) {

    ++solutions;
    System.out.println("Solution found : "+x1 +"+" + x2 + "+" + x3);

    if(x3 == n-2) return solutions;

    if(x2 > 1) {
        return solutions(n, x1, x2-1, x3+1, solutions);
    }

    if(x1 > 1) {
        return solutions(n, x1-1, n-x1, 1, solutions);
    }
    return solutions;
}

Output : 6

The idea is the following :

You start with x1 the greatest as possible.

Then you follow these two rules :

if x2 > 1 THEN x2 = x2 - 1 and x3 = x3 + 1

if not, and if x1 > 1 THEN x1 = x1 - 1, x3 = 1 and x2 = the number required to have the correct total.

If none of these two conditions are true, there is no more solutions.

Result :

3 + 1 + 1

First condition false, second true :
We remove 1 to x1, x3 becomes 1 and x2 becomes logically 2

2 + 2 + 1

First condition is true.
We remove 1 to x2 and add 1 to x3

2 + 1 + 2

First condition is false

Second condition is true

1 + 3 + 1

First condition is true

1 + 2 + 2

First condition is true

1 + 1 + 3

First condition is false, second is false.

We have our 6 solutions, so there it is.

Hope that helped !


问:
How to fix facebook links preview for vue js links?
When I try (for testing) to post a link from my vue.js project in my facebook page, the link preview section does not work as expected although I've added the needed <meta /> facebook tags.

Here is an example of the result:

How could it be fixed? Thanks.

答:
Facebook's crawler doesn't execute JavaScript. As such, it only sees what you'd see if you hit "view source" on the page - in the case of a Vue app, that's very little.

You'll need to dig into server-side rendering of your components.


问:
How can I fix this batch file so that it does not error out on the IF statement?
I am pulling my hair out getting an error on this IF statement

```<code>IF %resultis%=="true" (
</code>```

The batch file hits the pause right before it but right after that gets some error that goes by to fast for me to see what it is.

Here is the full script:

```<code>@Echo off
Echo "Adding Chrysaliser user to Users group and removing from Administrators"
REM net localgroup Users Chrysaliser /add
REM net localgroup Administrators Chrysaliser /delete

REM SET /P password= Enter ladmin user password:
REM net user ladmin %password% /ADD
REM net localgroup Administrators ladmin /add

SET /P alaptop= Is this a laptop? (Y/N):
echo %alaptop%
IF %alaptop%=="Y" (SET resultis="true")
IF %alaptop%=="y" (SET resultis="true")
pause
IF %resultis%=="true" (
    pause
    SET /P password= Enter Lockedout user password:
    pause
    net user Lockedout %password% /ADD
    net localgroup Users Lockedout /add
    net localgroup Administrators Chrysaliser /delete

)
Echo Getting install files
mkdir %SYSTEMDRIVE%\files
SET /P username= Enter your domain admin username:
SET/P password= Enter your domain admin password:
net use \\server /user:%username% $password%
pause
</code>```

答:
If your target Opertaing Systems are Windows Vista or later, I would suggest you use choice.exe for user input consisting of one of a small pre-defined set of known responses.

In the example below, I've included some code to try to pre-determine if the chassis is a laptop/notebook. If that cannot be determined the prompt for input will be invoked.

```<code>@Echo Off

For /F "EOL=C Delims={}" %%A In ('
    ""%__AppDir__%wbem\WMIC.exe" SystemEnclosure Get ChassisTypes 2>Nul"'
) Do For %%B In (%%A) Do If %%B GEq 9 If %%B LEq 10 Set "ResultIs=T"
If Not "%ResultIs%"=="T" ("%__AppDir__%choice.exe" /M "Is this a laptop"
    If ErrorLevel 2 GoTo :Continue)

Rem Laptop specific code goes here
Echo You are using a laptop

:Continue
Rem The rest of your code goes here
Echo Continuing . . .
Pause
</code>```

Body:
I am pulling my hair out getting an error on this IF statement

IF %resultis%=="true" (

The batch file hits the pause right before it but right after that gets some error that goes by to fast for me to see what it is.

Here is the full script:

@Echo off
Echo "Adding Chrysaliser user to Users group and removing from Administrators"
REM net localgroup Users Chrysaliser /add
REM net localgroup Administrators Chrysaliser /delete

REM SET /P password= Enter ladmin user password:
REM net user ladmin %password% /ADD
REM net localgroup Administrators ladmin /add

SET /P alaptop= Is this a laptop? (Y/N):
echo %alaptop%
IF %alaptop%=="Y" (SET resultis="true")
IF %alaptop%=="y" (SET resultis="true")
pause
IF %resultis%=="true" (
    pause
    SET /P password= Enter Lockedout user password:
    pause
    net user Lockedout %password% /ADD
    net localgroup Users Lockedout /add
    net localgroup Administrators Chrysaliser /delete

)
Echo Getting install files
mkdir %SYSTEMDRIVE%\files
SET /P username= Enter your domain admin username:
SET/P password= Enter your domain admin password:
net use \\server /user:%username% $password%
pause

Body:
If your target Opertaing Systems are Windows Vista or later, I would suggest you use choice.exe for user input consisting of one of a small pre-defined set of known responses.

In the example below, I've included some code to try to pre-determine if the chassis is a laptop/notebook. If that cannot be determined the prompt for input will be invoked.

@Echo Off

For /F "EOL=C Delims={}" %%A In ('
    ""%__AppDir__%wbem\WMIC.exe" SystemEnclosure Get ChassisTypes 2>Nul"'
) Do For %%B In (%%A) Do If %%B GEq 9 If %%B LEq 10 Set "ResultIs=T"
If Not "%ResultIs%"=="T" ("%__AppDir__%choice.exe" /M "Is this a laptop"
    If ErrorLevel 2 GoTo :Continue)

Rem Laptop specific code goes here
Echo You are using a laptop

:Continue
Rem The rest of your code goes here
Echo Continuing . . .
Pause


问:
How to find middle of a curve drawn by p5.js?
We have:

p1: beginning control point

p2: first point

p3: second point

p4: ending control point

Is there any formula to find the middle of the curve?

Here is the reference for the curve() function: https://p5js.org/reference/#/p5/curve

答: It sounds like you're looking for the curvePoint() function. You can find more info in the reference.


问:
Set last day of month in date
how can I set a month date to appear with last day of month. Currently I have

```<code> 2008-01-01 for January
</code>```

but I want it

```<code> 2008-01-31.
</code>```

Thanks in advance

答:
Use replace of datetime module</p>

```<code>import datetime
datetime.datetime.strptime('2008-01-01','%Y-%d-%m').replace(day=31)
</code>```

Title: Set last day of month in date

Body:
how can I set a month date to appear with last day of month. Currently I have

 2008-01-01 for January

but I want it

 2008-01-31.

Thanks in advance

Body:
Use replace of datetime module

import datetime
datetime.datetime.strptime('2008-01-01','%Y-%d-%m').replace(day=31)


问:
XML layout in tab android (tabhost)
I'm trying to get a tabbed layout working on android. Using an example I managed to get the tabs working but my different tabs are in different activities. Each tab is similar, it's almost the same so I want them in the same activity.

I want an xml file in the layout folder as content.

This works, seperate classes:

```<code>tabSpec1.setIndicator("tabName1").setContent(new Intent(this, FirstTab.class));
</code>```

This doesn't work:

```<code>tabSpec2.setIndicator("tabName2").setContent(R.layout.tab);
</code>```

The setContent function accepts id's like that. The reference to tab is also in my R class. This is the XML in my tab:

```<code><?xml version="1.0" encoding="UTF-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="This is the tab from XML"/> </LinearLayout>
</code>```

答:
Check this: unable to add views in TabHost by IDs, crashing

If you want to set content of each tab by View ids, you have to make sure that there is some layout xml that defines TabHost, TabWidget, and FrameLayout tags properly. Then the views that you want to be set by ids can be put as child tags in FrameLayout. Without any one of the tags mentioned above, the app will crash due to "cannot find view id xxxxxx".

You can get what you want by combining this and the <include> tag.

Title: XML layout in tab android (tabhost)

Body:
I'm trying to get a tabbed layout working on android. Using an example I managed to get the tabs working but my different tabs are in different activities. Each tab is similar, it's almost the same so I want them in the same activity.

I want an xml file in the layout folder as content.

This works, seperate classes:

tabSpec1.setIndicator("tabName1").setContent(new Intent(this, FirstTab.class));

This doesn't work:

tabSpec2.setIndicator("tabName2").setContent(R.layout.tab);

The setContent function accepts id's like that. The reference to tab is also in my R class. This is the XML in my tab:

<?xml version="1.0" encoding="UTF-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="This is the tab from XML"/> </LinearLayout>


问:
Does TypeScript support events on classes?
I am just wondering if in TypeScript you can define custom events on your classes or interfaces?

What would this look like?

答:
Here's a simple example of adding custom-type events to your class, using sub-events:

```<code>class MyClass {

    readonly onMessage: SubEvent<string> = new SubEvent();
    readonly onData: SubEvent<MyCustomType> = new SubEvent();

    sendMessage(msg: string) {
        this.onMessage.emit(msg);
    }

    sendData(data: MyCustomType) {
        this.onData.emit(data);
    }
}
</code>```

And then any client can subscribe to receive those events:

```<code>const a = new MyClass();

const sub1 = a.onMessage.subscribe(msg => {
    // msg here is strongly-typed
});

const sub2 = a.onData.subscribe(data => {
    // data here is strongly-typed
});
</code>```

And when you no longer need the events, you can cancel the subscriptions:

```<code>sub1.cancel();

sub2.cancel();
</code>```

Body:
Here's a simple example of adding custom-type events to your class, using sub-events:

class MyClass {

    readonly onMessage: SubEvent<string> = new SubEvent();
    readonly onData: SubEvent<MyCustomType> = new SubEvent();

    sendMessage(msg: string) {
        this.onMessage.emit(msg);
    }

    sendData(data: MyCustomType) {
        this.onData.emit(data);
    }
}

And then any client can subscribe to receive those events:

const a = new MyClass();

const sub1 = a.onMessage.subscribe(msg => {
    // msg here is strongly-typed
});

const sub2 = a.onData.subscribe(data => {
    // data here is strongly-typed
});

And when you no longer need the events, you can cancel the subscriptions:

sub1.cancel();

sub2.cancel();


问:
Filter array that doesn't have specific object
I've a document that have a key that is a array, how can i search on all documents where the array doesn't have a specific object?

Some of my documents are:

```<code>{
    "sku": "x",
    "datas": [{a: 1, b: 2}, {a: 1, b:2}]
}
</code>```

and some others:

```<code>{
    "sku": "y",
    "datas": [{c: 0}, {a: 1, b: 2}, {a: 1, b:2}]
}
</code>```

The result that i want is sku "x" because it does not have {c: 0}

答:
perhaps use the $not operator to negate an $elemMatch term:

```<code>db.my_data.find({
    datas: {
        $not: {
            $elemMatch: {c: 0}
        }
    }
})
</code>```

Body:
I've a document that have a key that is a array, how can i search on all documents where the array doesn't have a specific object?

Some of my documents are:

{
    "sku": "x",
    "datas": [{a: 1, b: 2}, {a: 1, b:2}]
}

and some others:

{
    "sku": "y",
    "datas": [{c: 0}, {a: 1, b: 2}, {a: 1, b:2}]
}

The result that i want is sku "x" because it does not have {c: 0}

Body:
perhaps use the $not operator to negate an $elemMatch term:

db.my_data.find({
    datas: {
        $not: {
            $elemMatch: {c: 0}
        }
    }
})


问:
updateOptions and strokeWidth
Updating a dygraphs like: g1.updateOptions({series:1, strokeWidth:2 }); updates all series with a strokeWidth of 2.  Is it possible to use updateOptions to update just one series with a wider strokeWidth?

答:
Yes, strokeWidth can be set on a per-series basis:

g1.updateOptions({
  series: {
    'y1': {
      strokeWidth: 2
    }
  }
});
```

"y1" is the name of your series. This shows up when you mouse over the chart and usually comes from the first row of your CSV file.

Title: updateOptions and strokeWidth

Body:
Yes, strokeWidth can be set on a per-series basis:

g1.updateOptions({
  series: {
    'y1': {
      strokeWidth: 2
    }
  }
});

"y1" is the name of your series. This shows up when you mouse over the chart and usually comes from the first row of your CSV file.


问:
Ignoring newlines with regex in xml
This is for a project for a very specific use.

I am trying to find how to find any empty text from the xml and replace it with a message.

```<code>regex = re.compile(r'>\s*</')

replaced = re.sub(regex, ">[!] JSON value does not exist, Check your Json!</", temp)
</code>```

For example filename is blank

```<code>        <file>
            <fileType>Mezza</fileType>
            <fileName></fileName>
            <segments>0000</segments>
        </file>
</code>```

and the output would be:

```<code>         <file>
            <fileType>Mezza</fileType>
            <fileName>[!] value does not exist!</fileName>
            <segments>0000</segments>
        </file>
</code>```

However I am getting for other parts where there is white space and newline I dont want to have this message, both tag names are different there is a new line and they are closing tags how do I implement this in regex?:

```<code></fileName>[!] value does not exist!</file>
</code>```

答:
Use [ \t]* instead of \s*. This will match spaces and tabs, but not newlines. So the code should be:

```<code>regex = re.compile(r'>[ \t]*</')
</code>```

DEMO

Title: Ignoring newlines with regex in xml

Body:
This is for a project for a very specific use.

I am trying to find how to find any empty text from the xml and replace it with a message.

regex = re.compile(r'>\s*</')

replaced = re.sub(regex, ">[!] JSON value does not exist, Check your Json!</", temp)

For example filename is blank

        <file>
            <fileType>Mezza</fileType>
            <fileName></fileName>
            <segments>0000</segments>
        </file>

and the output would be:

         <file>
            <fileType>Mezza</fileType>
            <fileName>[!] value does not exist!</fileName>
            <segments>0000</segments>
        </file>

However I am getting for other parts where there is white space and newline I dont want to have this message, both tag names are different there is a new line and they are closing tags how do I implement this in regex?:

</fileName>[!] value does not exist!</file>

Body:
Use [ \t]* instead of \s*. This will match spaces and tabs, but not newlines. So the code should be:

regex = re.compile(r'>[ \t]*</')

DEMO