问:
PL/SQL - XML clob error
I'm trying to test a PL/SQL procedure which takes an xml CLOB as a parameter

```<code>PROCEDURE example_proc(ex_xml CLOB) IS
BEGIN

/* Find the second < (skip over declaration) */
ln_position := instr(pc_shipment_xml, '<', 1, 2);
/* Find the space after the first tag */
ln_position := instr(pc_shipment_xml, ' ', ln_position, 1);
/* Set the first part of the XML clob */
lc_shipment_xml := substr(pc_shipment_xml, 1, ln_position - 1);
/* Skip the namespace */
ln_position     := instr(pc_shipment_xml, '>', ln_position, 1);
lc_shipment_xml := lc_shipment_xml || substr(pc_shipment_xml, ln_position);

/* Set the XML type */
lx_shipment_xml := xmltype(lc_shipment_xml); --RIGHT HERE IS WHERE IT ERRORS OUT
</code>```

Here is the xml that I am passing in (as the ex_xml clob parameter):

```<code>    xml :=
'<Shipment>
  <OrderNumber>00000</OrderNumber>
   <ShipmentLines>
    <ShipmentLine>
      <OrderDetailId>000000</OrderDetailId>
      <LineNumber>0</LineNumber>
      <ItemId>00000</ItemId>
      <UnitId>0000000</UnitId>
      <BaseUom>X</BaseUom>
      <Quantity1>000</Quantity1>
    </ShipmentLine>
  </ShipmentLines>
</Shipment>';
</code>```

and it errors out on that very last line with:

```<code>ORA-19202: Error occurred in XML processing
LPX-002255: end-element tag "ShipmentLines" does not match start-element tag "Shipment"
</code>```

Please pardon my ignorance but this is my first time working with XML in PL/SQ, am I missing something with the formatting? As far as I can see I'm opening and closing my tags correctly. Any input at all is appreciated.

答:
Running your code as

```<code>declare
  pc_shipment_xml CLOB := '<Shipment>
  <OrderNumber>00000</OrderNumber>
   <ShipmentLines>
    <ShipmentLine>
      <OrderDetailId>000000</OrderDetailId>
      <LineNumber>0</LineNumber>
      <ItemId>00000</ItemId>
      <UnitId>0000000</UnitId>
      <BaseUom>X</BaseUom>
      <Quantity1>000</Quantity1>
    </ShipmentLine>
  </ShipmentLines>
</Shipment>';
  lc_shipment_xml varchar2(2000);
  ln_position integer;
BEGIN
  /* Find the second < (skip over declaration) */
  ln_position := instr(pc_shipment_xml, '<', 1, 2);
  /* Find the space after the first tag */
  ln_position := instr(pc_shipment_xml, ' ', ln_position, 1);
  /* Set the first part of the XML clob */
  lc_shipment_xml := substr(pc_shipment_xml, 1, ln_position - 1);
  /* Skip the namespace */
  ln_position     := instr(pc_shipment_xml, '>', ln_position, 1) + 1;
  lc_shipment_xml := lc_shipment_xml || substr(pc_shipment_xml, ln_position);
  dbms_output.put_line(lc_shipment_xml);
end;
/
</code>```

gives the following output:

```<code><Shipment>
  <OrderNumber>00000</OrderNumber>

    <ShipmentLine>
      <OrderDetailId>000000</OrderDetailId>
      <LineNumber>0</LineNumber>
      <ItemId>00000</ItemId>
      <UnitId>0000000</UnitId>
      <BaseUom>X</BaseUom>
      <Quantity1>000</Quantity1>
    </ShipmentLine>
  </ShipmentLines>
</Shipment>
</code>```

so it looks like you are stripping out the start ShipmentLines tag, but not the end tag

if you know the name of the tag to remove you could more simply remove both with

```<code>lc_shipment_xml := regexp_replace(pc_shipment_xml, '</?ShipmentLines>');
</code>```

or getting the tag by position:

```<code>l_tag := regexp_substr(pc_shipment_xml, '<(\w+)>',1,3,'i',1);
lc_shipment_xml := regexp_replace(pc_shipment_xml, '</?' || l_tag || '>');
</code>```

A better approach would be to use the xml funtions, something like this:

```<code>declare
  pc_shipment_xml CLOB := '<Shipment>
  <OrderNumber>00000</OrderNumber>
  <ShipmentLines>
    <ShipmentLine>
      <OrderDetailId>000000</OrderDetailId>
      <LineNumber>0</LineNumber>
      <ItemId>00000</ItemId>
      <UnitId>0000000</UnitId>
      <BaseUom>X</BaseUom>
      <Quantity1>000</Quantity1>
    </ShipmentLine>
  </ShipmentLines>
</Shipment>';
  lx_shipment_xml xmltype := xmltype(pc_shipment_xml);
  lx_shipline_xml xmltype := xmltype(pc_shipment_xml);
  lc_shipment_xml varchar2(2000);
BEGIN
  /* Set the XML type */
    select extract(lx_shipment_xml, '/Shipment/ShipmentLines/ShipmentLine') into lx_shipline_xml from dual;
    select deletexml(lx_shipment_xml, '/Shipment/ShipmentLines') into lx_shipment_xml from dual;
    select insertxmlafter(lx_shipment_xml, '/Shipment/OrderNumber', lx_shipline_xml) into lx_shipment_xml from dual;
    select xmlserialize(content lx_shipment_xml) into lc_shipment_xml from dual;
    dbms_output.put_line(lc_shipment_xml);
end;
/
</code>```

Title: PL/SQL - XML clob error

Body:
I'm trying to test a PL/SQL procedure which takes an xml CLOB as a parameter

PROCEDURE example_proc(ex_xml CLOB) IS
BEGIN

/* Find the second < (skip over declaration) */
ln_position := instr(pc_shipment_xml, '<', 1, 2);
/* Find the space after the first tag */
ln_position := instr(pc_shipment_xml, ' ', ln_position, 1);
/* Set the first part of the XML clob */
lc_shipment_xml := substr(pc_shipment_xml, 1, ln_position - 1);
/* Skip the namespace */
ln_position     := instr(pc_shipment_xml, '>', ln_position, 1);
lc_shipment_xml := lc_shipment_xml || substr(pc_shipment_xml, ln_position);

/* Set the XML type */
lx_shipment_xml := xmltype(lc_shipment_xml); --RIGHT HERE IS WHERE IT ERRORS OUT

Here is the xml that I am passing in (as the ex_xml clob parameter):

    xml :=
'<Shipment>
  <OrderNumber>00000</OrderNumber>
   <ShipmentLines>
    <ShipmentLine>
      <OrderDetailId>000000</OrderDetailId>
      <LineNumber>0</LineNumber>
      <ItemId>00000</ItemId>
      <UnitId>0000000</UnitId>
      <BaseUom>X</BaseUom>
      <Quantity1>000</Quantity1>
    </ShipmentLine>
  </ShipmentLines>
</Shipment>';

and it errors out on that very last line with:

ORA-19202: Error occurred in XML processing
LPX-002255: end-element tag "ShipmentLines" does not match start-element tag "Shipment"

Please pardon my ignorance but this is my first time working with XML in PL/SQ, am I missing something with the formatting? As far as I can see I'm opening and closing my tags correctly. Any input at all is appreciated.

Body:
Running your code as

declare
  pc_shipment_xml CLOB := '<Shipment>
  <OrderNumber>00000</OrderNumber>
   <ShipmentLines>
    <ShipmentLine>
      <OrderDetailId>000000</OrderDetailId>
      <LineNumber>0</LineNumber>
      <ItemId>00000</ItemId>
      <UnitId>0000000</UnitId>
      <BaseUom>X</BaseUom>
      <Quantity1>000</Quantity1>
    </ShipmentLine>
  </ShipmentLines>
</Shipment>';
  lc_shipment_xml varchar2(2000);
  ln_position integer;
BEGIN
  /* Find the second < (skip over declaration) */
  ln_position := instr(pc_shipment_xml, '<', 1, 2);
  /* Find the space after the first tag */
  ln_position := instr(pc_shipment_xml, ' ', ln_position, 1);
  /* Set the first part of the XML clob */
  lc_shipment_xml := substr(pc_shipment_xml, 1, ln_position - 1);
  /* Skip the namespace */
  ln_position     := instr(pc_shipment_xml, '>', ln_position, 1) + 1;
  lc_shipment_xml := lc_shipment_xml || substr(pc_shipment_xml, ln_position);
  dbms_output.put_line(lc_shipment_xml);
end;
/

gives the following output:

<Shipment>
  <OrderNumber>00000</OrderNumber>

    <ShipmentLine>
      <OrderDetailId>000000</OrderDetailId>
      <LineNumber>0</LineNumber>
      <ItemId>00000</ItemId>
      <UnitId>0000000</UnitId>
      <BaseUom>X</BaseUom>
      <Quantity1>000</Quantity1>
    </ShipmentLine>
  </ShipmentLines>
</Shipment>

so it looks like you are stripping out the start ShipmentLines tag, but not the end tag

if you know the name of the tag to remove you could more simply remove both with

lc_shipment_xml := regexp_replace(pc_shipment_xml, '</?ShipmentLines>');

or getting the tag by position:

l_tag := regexp_substr(pc_shipment_xml, '<(\w+)>',1,3,'i',1);
lc_shipment_xml := regexp_replace(pc_shipment_xml, '</?' || l_tag || '>');

A better approach would be to use the xml funtions, something like this:

declare
  pc_shipment_xml CLOB := '<Shipment>
  <OrderNumber>00000</OrderNumber>
  <ShipmentLines>
    <ShipmentLine>
      <OrderDetailId>000000</OrderDetailId>
      <LineNumber>0</LineNumber>
      <ItemId>00000</ItemId>
      <UnitId>0000000</UnitId>
      <BaseUom>X</BaseUom>
      <Quantity1>000</Quantity1>
    </ShipmentLine>
  </ShipmentLines>
</Shipment>';
  lx_shipment_xml xmltype := xmltype(pc_shipment_xml);
  lx_shipline_xml xmltype := xmltype(pc_shipment_xml);
  lc_shipment_xml varchar2(2000);
BEGIN
  /* Set the XML type */
    select extract(lx_shipment_xml, '/Shipment/ShipmentLines/ShipmentLine') into lx_shipline_xml from dual;
    select deletexml(lx_shipment_xml, '/Shipment/ShipmentLines') into lx_shipment_xml from dual;
    select insertxmlafter(lx_shipment_xml, '/Shipment/OrderNumber', lx_shipline_xml) into lx_shipment_xml from dual;
    select xmlserialize(content lx_shipment_xml) into lc_shipment_xml from dual;
    dbms_output.put_line(lc_shipment_xml);
end;
/


来源: stackexchange

问:
Can I get multiple same enums?
For example, I have:

Action enum:

```<code>public enum Action{
    Pour, Mix, Shake, Add;

    public Ingredient ingredient;

    public String toString() {
        return super.toString() + " " + this.ingredient.toString();
    }
}
</code>```

Code example:

```<code>Ingredient [] ingredients1 = {
            new DrinkingIngredient("Vodka", 50, 20),
            new DrinkingIngredient("Tomato Juice", 120, 0),
            new DrinkingIngredient("lemon juice", 10, 0),
            new Component("Ice", 380),
            new Component("Celery", 15),

        };

        Action act1 = Action.Add;
        act1.ingredient = ingredients1[0];
        Action act2 = Action.Mix;
        act2.ingredient = ingredients1[1];
        Action act3 = Action.Mix;
        act3.ingredient = ingredients1[2];
        Action act4 = Action.Shake;
        Action act5 = Action.Add;
        act5.ingredient = ingredients1[3];
        Action act6 = Action.Add;
        act6.ingredient = ingredients1[4];
</code>```

I know this is not properly the best example I could do. Sorry about that, but I can explain that all Action enums have the same property value as the last one act6. So I can assume that the same enums in Java cannot live at once. Am I right? What should I do in that situation?

And yeah, after that:

```<code>System.out.print(act1);
</code>```

I get: "Add Celery" just like the last one act6 instead "Add Vodka" as I expected

答:
The direct answer to your question is "No, you cannot get multiple enums".  As you have discovered, it is the nature of enums that only one instance of a given enum constant ever exists.  So you have just one Action.Add, one Action.Mix, etc.  If you have an Ingredient as part of an Action, you can then only ever represent one combination of an action and ingredient.  So, you can have two "Add" steps, but they both have to add the same ingredient.  You can "Add Vodka" twice, or you can "Add Celery" twice, but you can't both "Add Vodka" and "Add Celery".

The solution to your problem is to separate the ingredient from the action.  You need an object that can represent a recipe step: a combination of an action and the ingredient to use in performing that action:

```<code>public class RecipeStep {
    public final Action action;
    public final Ingredient ingredient;
    public RecipeStep(Action a, Ingredient i){
        this.action = a;
        this.ingredient = i;
    }
    public String toString(){
        return Action.toString() +
            (ingredient != null
                ? (" " + ingredient.toString())
                : ""
             );
    }
}
</code>```

Then you make up your recipe as a list of RecipeStep instances:

```<code>RecipeStep step1 = new RecipeStep(Action.Add, ingredients1[0]);
RecipeStep step2 = new RecipeStep(Action.Mix, ingredients1[1]);
RecipeStep step3 = new RecipeStep(Action.Mix, ingredients1[2]);
RecipeStep step4 = new RecipeStep(Action.Shake, null);
RecipeStep step5 = new RecipeStep(Action.Add,ingredients1[3]);
RecipeStep step6 = new RecipeStep(Action.Add,ingredients1[4]);
</code>```

ContentLicense: CC BY-SA 3.0

Title: Can I get multiple same enums?

Body:
For example, I have:

Action enum:

public enum Action{
    Pour, Mix, Shake, Add;

    public Ingredient ingredient;

    public String toString() {
        return super.toString() + " " + this.ingredient.toString();
    }
}

Code example:

Ingredient [] ingredients1 = {
            new DrinkingIngredient("Vodka", 50, 20),
            new DrinkingIngredient("Tomato Juice", 120, 0),
            new DrinkingIngredient("lemon juice", 10, 0),
            new Component("Ice", 380),
            new Component("Celery", 15),

        };

        Action act1 = Action.Add;
        act1.ingredient = ingredients1[0];
        Action act2 = Action.Mix;
        act2.ingredient = ingredients1[1];
        Action act3 = Action.Mix;
        act3.ingredient = ingredients1[2];
        Action act4 = Action.Shake;
        Action act5 = Action.Add;
        act5.ingredient = ingredients1[3];
        Action act6 = Action.Add;
        act6.ingredient = ingredients1[4];

I know this is not properly the best example I could do. Sorry about that, but I can explain that all Action enums have the same property value as the last one act6. So I can assume that the same enums in Java cannot live at once. Am I right? What should I do in that situation?

And yeah, after that:

System.out.print(act1);

I get: "Add Celery" just like the last one act6 instead "Add Vodka" as I expected

Body:
The direct answer to your question is "No, you cannot get multiple enums".  As you have discovered, it is the nature of enums that only one instance of a given enum constant ever exists.  So you have just one Action.Add, one Action.Mix, etc.  If you have an Ingredient as part of an Action, you can then only ever represent one combination of an action and ingredient.  So, you can have two "Add" steps, but they both have to add the same ingredient.  You can "Add Vodka" twice, or you can "Add Celery" twice, but you can't both "Add Vodka" and "Add Celery".

The solution to your problem is to separate the ingredient from the action.  You need an object that can represent a recipe step: a combination of an action and the ingredient to use in performing that action:

public class RecipeStep {
    public final Action action;
    public final Ingredient ingredient;
    public RecipeStep(Action a, Ingredient i){
        this.action = a;
        this.ingredient = i;
    }
    public String toString(){
        return Action.toString() +
            (ingredient != null
                ? (" " + ingredient.toString())
                : ""
             );
    }
}

Then you make up your recipe as a list of RecipeStep instances:

RecipeStep step1 = new RecipeStep(Action.Add, ingredients1[0]);
RecipeStep step2 = new RecipeStep(Action.Mix, ingredients1[1]);
RecipeStep step3 = new RecipeStep(Action.Mix, ingredients1[2]);
RecipeStep step4 = new RecipeStep(Action.Shake, null);
RecipeStep step5 = new RecipeStep(Action.Add,ingredients1[3]);
RecipeStep step6 = new RecipeStep(Action.Add,ingredients1[4]);


问:
ReactVR how properly set pointer (raycaster)
I used code (installing it wasn't working for me) from simple-raycaster to display pointer on my VR screen, it works but with some problem - 'behind' me there is square space where this pointer disappears and didn't work. Any idea how can I fix that?</p>

答: I ran into an issue similar to what you describe.  I had several Text elements placed at various locations.  I had each wrapped in a VrButton with a onEnter and onExit calling functions to set timeouts gaze select an item.  I was seeing the raycaster disappear in a section of space directly behind me.  I eventually figured out that if I remove the VrButton wrapper and placed the onEnter and onExit directly on the Text element it solved the problem.  Hope this helps.</p>


问:
How to unmerge cells in a spreadsheet using apache POI java library
We can use sheet.addMergedRegion(rowFrom,rowTo,colFrom,colTo); for adding merged cells in the sheet But I already have a sheet with merged cells in it and I want to unmerge these cells.

Is there any way to unmerge cells of a sheet without creating new sheet using Apache POI ?

答:
For some reason the following code did not remove all the merged regions at once:

```<code>logger.info("Number of merged regions = " + sheet.getNumMergedRegions());
for (int i = 0; i < sheet.getNumMergedRegions(); i++) {
    logger.info("Removing merged region " + (i + 1));
    sheet.removeMergedRegion(i);
}
logger.info("\nNumber of merged regions = " + sheet.getNumMergedRegions());
</code>```

In the console I see this:

```<code>Number of merged regions = 7
Removing merged region 1
Removing merged region 2
Removing merged region 3
Removing merged region 4

Number of merged regions = 3
</code>```

Fix:

```<code>while (sheet.getNumMergedRegions() > 0) {
    logger.info("Number of merged regions = " + sheet.getNumMergedRegions());
    for (int i = 0; i < sheet.getNumMergedRegions(); i++) {
        logger.info("Removing merged region " + (i + 1));
        sheet.removeMergedRegion(i);
    }
}
</code>```

Body:
For some reason the following code did not remove all the merged regions at once:

logger.info("Number of merged regions = " + sheet.getNumMergedRegions());
for (int i = 0; i < sheet.getNumMergedRegions(); i++) {
    logger.info("Removing merged region " + (i + 1));
    sheet.removeMergedRegion(i);
}
logger.info("\nNumber of merged regions = " + sheet.getNumMergedRegions());

In the console I see this:

Number of merged regions = 7
Removing merged region 1
Removing merged region 2
Removing merged region 3
Removing merged region 4

Number of merged regions = 3

Fix:

while (sheet.getNumMergedRegions() > 0) {
    logger.info("Number of merged regions = " + sheet.getNumMergedRegions());
    for (int i = 0; i < sheet.getNumMergedRegions(); i++) {
        logger.info("Removing merged region " + (i + 1));
        sheet.removeMergedRegion(i);
    }
}


问:
JAVA - Drop down menu items based on another drop down menu
I am trying to make a world cup 2018 program that gives the percentages and choices for each team involved. I have figured out all the math and everything that goes with it, but i am having trouble finding out how to get the selection from one drop down menu change the choices for the next one and so on for the 4 groups. I have looked for information on this site and others, but because I am sorta new to java it isn't very easy for me to figure out what to do.

I have included my code below, with the four drop down menus, and would like to know how depending on the choice you make in the first group will give the proper choices in the 2nd group and so on...

```<code>import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.BoxLayout;
import java.awt.Component;

public class  Worldcup {

public static void main(String[] args) {

    JFrame frame = new JFrame("A Simple GUI");
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(500, 500);
    frame.setLocation(430, 100);

    JPanel panel = new JPanel();
    panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));

    frame.add(panel);

    //POT 1

    JLabel lbl = new JLabel("Select one of the possible choices and click OK");
    lbl.setAlignmentX(Component.CENTER_ALIGNMENT);
    panel.add(lbl);

    String[] choices = { "Russia", "Germany", "France", "Portugal",
                         "Belgium", "Poland","Brazil", "Argentina"};

    final JComboBox<String> cb = new JComboBox<String>(choices);

    cb.setMaximumSize(cb.getPreferredSize());
    cb.setAlignmentX(Component.CENTER_ALIGNMENT);
    panel.add(cb);

    JButton btn = new JButton("OK");
    btn.setAlignmentX(Component.CENTER_ALIGNMENT);
    panel.add(btn);
  frame.setVisible(true);

// POT 2

JLabel lbl2 = new JLabel("Select one of the possible choices and click OK");
    lbl2.setAlignmentX(Component.CENTER_ALIGNMENT);
    panel.add(lbl2);

    String[] choices2 = { "Spain", "Switzerland", "England", "Croatia",
                         "Peru", "Colombia","Uruguay", "Mexico"};

    final JComboBox<String> cb2 = new JComboBox<String>(choices2);

    cb2.setMaximumSize(cb2.getPreferredSize());
    cb2.setAlignmentX(Component.CENTER_ALIGNMENT);
    panel.add(cb2);

    JButton btn2 = new JButton("OK");
    btn2.setAlignmentX(Component.CENTER_ALIGNMENT);
    panel.add(btn2);
  frame.setVisible(true);

// POT 3

JLabel lbl3 = new JLabel("Select one of the possible choices and click OK");
    lbl3.setAlignmentX(Component.CENTER_ALIGNMENT);
    panel.add(lbl3);

    String[] choices3 = { "Denmark", "Iceland", "Sweden", "Costa Rica",
                         "Senegal", "Egypt","Tunisia", "IRAN"};

    final JComboBox<String> cb3 = new JComboBox<String>(choices3);

    cb3.setMaximumSize(cb3.getPreferredSize());
    cb3.setAlignmentX(Component.CENTER_ALIGNMENT);
    panel.add(cb3);

    JButton btn3 = new JButton("OK");
    btn3.setAlignmentX(Component.CENTER_ALIGNMENT);
    panel.add(btn3);
  frame.setVisible(true);

// POT 4

JLabel lbl4 = new JLabel("Select one of the possible choices and click OK");
    lbl4.setAlignmentX(Component.CENTER_ALIGNMENT);
    panel.add(lbl4);

    String[] choices4 = { "Serbia", "Nigeria", "Morocco", "Australia",
                         "Japan", "South Korea","Crappy Arabia", "Panama"};

    final JComboBox<String> cb4 = new JComboBox<String>(choices4);

    cb4.setMaximumSize(cb4.getPreferredSize());
    cb4.setAlignmentX(Component.CENTER_ALIGNMENT);
    panel.add(cb4);

    JButton btn4 = new JButton("OK");
    btn4.setAlignmentX(Component.CENTER_ALIGNMENT);
    panel.add(btn4);
  frame.setVisible(true);

    }
}
</code>```

答:
You'll need to use events and listeners.

Check this other post it might help.

Body:
I am trying to make a world cup 2018 program that gives the percentages and choices for each team involved. I have figured out all the math and everything that goes with it, but i am having trouble finding out how to get the selection from one drop down menu change the choices for the next one and so on for the 4 groups. I have looked for information on this site and others, but because I am sorta new to java it isn't very easy for me to figure out what to do.

I have included my code below, with the four drop down menus, and would like to know how depending on the choice you make in the first group will give the proper choices in the 2nd group and so on...

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.BoxLayout;
import java.awt.Component;

public class  Worldcup {

public static void main(String[] args) {

    JFrame frame = new JFrame("A Simple GUI");
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(500, 500);
    frame.setLocation(430, 100);

    JPanel panel = new JPanel();
    panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));

    frame.add(panel);

    //POT 1

    JLabel lbl = new JLabel("Select one of the possible choices and click OK");
    lbl.setAlignmentX(Component.CENTER_ALIGNMENT);
    panel.add(lbl);

    String[] choices = { "Russia", "Germany", "France", "Portugal",
                         "Belgium", "Poland","Brazil", "Argentina"};

    final JComboBox<String> cb = new JComboBox<String>(choices);

    cb.setMaximumSize(cb.getPreferredSize());
    cb.setAlignmentX(Component.CENTER_ALIGNMENT);
    panel.add(cb);

    JButton btn = new JButton("OK");
    btn.setAlignmentX(Component.CENTER_ALIGNMENT);
    panel.add(btn);
  frame.setVisible(true);

// POT 2

JLabel lbl2 = new JLabel("Select one of the possible choices and click OK");
    lbl2.setAlignmentX(Component.CENTER_ALIGNMENT);
    panel.add(lbl2);

    String[] choices2 = { "Spain", "Switzerland", "England", "Croatia",
                         "Peru", "Colombia","Uruguay", "Mexico"};

    final JComboBox<String> cb2 = new JComboBox<String>(choices2);

    cb2.setMaximumSize(cb2.getPreferredSize());
    cb2.setAlignmentX(Component.CENTER_ALIGNMENT);
    panel.add(cb2);

    JButton btn2 = new JButton("OK");
    btn2.setAlignmentX(Component.CENTER_ALIGNMENT);
    panel.add(btn2);
  frame.setVisible(true);

// POT 3

JLabel lbl3 = new JLabel("Select one of the possible choices and click OK");
    lbl3.setAlignmentX(Component.CENTER_ALIGNMENT);
    panel.add(lbl3);

    String[] choices3 = { "Denmark", "Iceland", "Sweden", "Costa Rica",
                         "Senegal", "Egypt","Tunisia", "IRAN"};

    final JComboBox<String> cb3 = new JComboBox<String>(choices3);

    cb3.setMaximumSize(cb3.getPreferredSize());
    cb3.setAlignmentX(Component.CENTER_ALIGNMENT);
    panel.add(cb3);

    JButton btn3 = new JButton("OK");
    btn3.setAlignmentX(Component.CENTER_ALIGNMENT);
    panel.add(btn3);
  frame.setVisible(true);

// POT 4

JLabel lbl4 = new JLabel("Select one of the possible choices and click OK");
    lbl4.setAlignmentX(Component.CENTER_ALIGNMENT);
    panel.add(lbl4);

    String[] choices4 = { "Serbia", "Nigeria", "Morocco", "Australia",
                         "Japan", "South Korea","Crappy Arabia", "Panama"};

    final JComboBox<String> cb4 = new JComboBox<String>(choices4);

    cb4.setMaximumSize(cb4.getPreferredSize());
    cb4.setAlignmentX(Component.CENTER_ALIGNMENT);
    panel.add(cb4);

    JButton btn4 = new JButton("OK");
    btn4.setAlignmentX(Component.CENTER_ALIGNMENT);
    panel.add(btn4);
  frame.setVisible(true);

    }
}


问:
Serving .cshtml files on IIS globally
I am trying to setup intranet IIS 8.5 (Win8.1) to globally serve .cshtml (Razor) files. The corresponding Application Pool is set to v4.0.

The files are simple Web Pages, not MVC. Here is an example of one:

```<code><html>
<body>
@foreach (var i = 0; i < 10; i++)
{
   <li>Item @i</li>
}
</body>
</html>
</code>```

By removing the mapping of .cshtml files to System.Web.ForbiddenHandler on the IIS server's Handler Mappings I was able to get past the initial hurdle of ASP.NET telling me that

This type of file is not served.

However, the .cshtml files are now served verbatim to the browser, instead of being run through the Razor rendering process.

One would think that it should be easy to serve Razor pages from IIS, but it isn't. I need to somehow convince IIS to interpret these pages as Razor views; I suspect I am missing some mapping to the appropriate handler (I don't want MVC though - just simple Web Pages).

Here are some additional constraints:

I would definitely like to avoid including a bin folder with the requisite Razor assemblies in each of the sites on the server. The server hosts many sites, and I don't want to have to copy the bin folder everywhere. It should be possible to configure it globally, once and for all.

Ideally, I would not even need a local web.config for each site. The sites that are being served are a patchwork of technologies, containing .html, .shtml, .php, .asp, .aspx, and - hopefully - .cshtml files and should not be dependent on a single technology or config.

Creating a Visual Studio project is expressly out of the question. I should be able to use any text editor to modify the .cshtml files.

.NET Core is not installed on the machine and is not an option. Must use full Framework up to 4.6.2.

I am aware of many other SO questions that are similar, but don't quite solve my problem.

This question for example, was closed as "unclear" before it could have been answered, yet it was pretty clear to me! I am having the exact same problem.

The accepted answer to this question simply resorts to copying the bin folder. This is something I specifically don't want to do.

This answer says you can run an MVC application without installing MVC on your server, again by copying a bin folder into the local root. I do want to install Razor (but not necessarily MVC) onto my server globally.

Essentially, what I am trying to do is to use Razor syntax in a way reminiscent of classic ASP, or ASPX, without the baggage of MVC.

Can it be done?

答: I believe what you're looking for is a feature called ASP.NET Web Pages. If you use ASP.NET Core 2.0, the most recent new project templates uses Pages, rather than controllers and views. I've never read this doco, but I guess it should help you get started (or just create an ASP.NET Core 2.0 project from the new project wizard)</p>

Title: Serving .cshtml files on IIS globally

Body:
I am trying to setup intranet IIS 8.5 (Win8.1) to globally serve .cshtml (Razor) files. The corresponding Application Pool is set to v4.0.

The files are simple Web Pages, not MVC. Here is an example of one:

@foreach (var i = 0; i < 10; i++)
{

Item @i

}

By removing the mapping of .cshtml files to System.Web.ForbiddenHandler on the IIS server's Handler Mappings I was able to get past the initial hurdle of ASP.NET telling me that

This type of file is not served.

However, the .cshtml files are now served verbatim to the browser, instead of being run through the Razor rendering process.

One would think that it should be easy to serve Razor pages from IIS, but it isn't. I need to somehow convince IIS to interpret these pages as Razor views; I suspect I am missing some mapping to the appropriate handler (I don't want MVC though - just simple Web Pages).

Here are some additional constraints:

I would definitely like to avoid including a bin folder with the requisite Razor assemblies in each of the sites on the server. The server hosts many sites, and I don't want to have to copy the bin folder everywhere. It should be possible to configure it globally, once and for all.

Ideally, I would not even need a local web.config for each site. The sites that are being served are a patchwork of technologies, containing .html, .shtml, .php, .asp, .aspx, and - hopefully - .cshtml files and should not be dependent on a single technology or config.

Creating a Visual Studio project is expressly out of the question. I should be able to use any text editor to modify the .cshtml files.

.NET Core is not installed on the machine and is not an option. Must use full Framework up to 4.6.2.

I am aware of many other SO questions that are similar, but don't quite solve my problem.

This question for example, was closed as "unclear" before it could have been answered, yet it was pretty clear to me! I am having the exact same problem.

The accepted answer to this question simply resorts to copying the bin folder. This is something I specifically don't want to do.

This answer says you can run an MVC application without installing MVC on your server, again by copying a bin folder into the local root. I do want to install Razor (but not necessarily MVC) onto my server globally.

Essentially, what I am trying to do is to use Razor syntax in a way reminiscent of classic ASP, or ASPX, without the baggage of MVC.

Can it be done?


问:
What will happen if variable is not declared in Javascript?
For example, I have code like this:

```<code>var Player = function(param){
    var self = {
    x:0,
    y:0,
    spdX:0,
    spdY:0,
    id:"",
    }
    self.hp = 24;
}
</code>```

Do I need to add hp inside var self = {}?

答:
No

It's completely alright. Relax. Your code isn't going to explode. Breathe. Breathe! Okay, now that you're settled down...

Performance wise, it's the same*: Performance test.

Syntax wise, they are both used in major documentation sites: developer.mozilla.org & W3Schools

*Well as close as it gets

Body:
For example, I have code like this:

var Player = function(param){
    var self = {
    x:0,
    y:0,
    spdX:0,
    spdY:0,
    id:"",
    }
    self.hp = 24;
}

Do I need to add hp inside var self = {}?


问:
Deserialize CSV with CustomHeaders using ServiceStack.Text: not working?
consider following class:

```<code>class Foo {
    public string bar { get; set; }
    public string rab { get; set; }

    public override string ToString()
    {
        return string.Format("[Foo bar={0}, rab={1}]", bar, rab);
    }
}
</code>```

And following code:

```<code>var csv1 =
    "bar,rab" + Environment.NewLine +
    "a,b" + Environment.NewLine +
    "c,d" + Environment.NewLine +
    "e,f" + Environment.NewLine;

var csv2 =
    "xbar,xrab" + Environment.NewLine +
    "a,b" + Environment.NewLine +
    "c,d" + Environment.NewLine +
    "e,f" + Environment.NewLine;

Console.WriteLine(CsvSerializer.DeserializeFromString<List<Foo>>(csv1).First());

CsvConfig<TMDBEntity>.CustomHeadersMap = new Dictionary<string, string> {
    {"bar", "xbar"},
    {"rab", "xrab"}
};

Console.WriteLine(CsvSerializer.DeserializeFromString<List<Foo>>(csv2).First());
</code>```

It is printing:

```<code>[Foo bar=a, rab=b]
[Foo bar=, rab=]
</code>```

while I would expect it to print

```<code>[Foo bar=a, rab=b]
[Foo bar=a, rab=b]
</code>```

Why is it not picking up the custom headers using xbar and xrab?

ServiceStack.Text version is 4.5.14.0

答:
This issue should be resolved from this commit which is available from ServiceStack v5.0.0 that's now available on MyGet.

Note you need to configure CsvConfig<Foo> in order to change how Foo is deserialized, e.g:

```<code>CsvConfig<Foo>.CustomHeadersMap = new Dictionary<string, string> {
    {"bar", "xbar"},
    {"rab", "xrab"}
};
</code>```

Body:
consider following class:

class Foo {
    public string bar { get; set; }
    public string rab { get; set; }

    public override string ToString()
    {
        return string.Format("[Foo bar={0}, rab={1}]", bar, rab);
    }
}

And following code:

var csv1 =
    "bar,rab" + Environment.NewLine +
    "a,b" + Environment.NewLine +
    "c,d" + Environment.NewLine +
    "e,f" + Environment.NewLine;

var csv2 =
    "xbar,xrab" + Environment.NewLine +
    "a,b" + Environment.NewLine +
    "c,d" + Environment.NewLine +
    "e,f" + Environment.NewLine;

Console.WriteLine(CsvSerializer.DeserializeFromString<List<Foo>>(csv1).First());

CsvConfig<TMDBEntity>.CustomHeadersMap = new Dictionary<string, string> {
    {"bar", "xbar"},
    {"rab", "xrab"}
};

Console.WriteLine(CsvSerializer.DeserializeFromString<List<Foo>>(csv2).First());

It is printing:

[Foo bar=a, rab=b]
[Foo bar=, rab=]

while I would expect it to print

[Foo bar=a, rab=b]
[Foo bar=a, rab=b]

Why is it not picking up the custom headers using xbar and xrab?

ServiceStack.Text version is 4.5.14.0

Body:
This issue should be resolved from this commit which is available from ServiceStack v5.0.0 that's now available on MyGet.

Note you need to configure CsvConfig<Foo> in order to change how Foo is deserialized, e.g:

CsvConfig<Foo>.CustomHeadersMap = new Dictionary<string, string> {
    {"bar", "xbar"},
    {"rab", "xrab"}
};


问:
Keeping the formatting of the cut cells preserved
I have a sheet with some cells formatted (like borders, background colors).

User may cut/paste data.

The problem: when cutting/pasting, the formatting (borders) is gone.

How to keep the formatting of the cut cells preserved?

Thanks.

答:
I know this is almost 3 years late, but maybe someone still need an answer.

To avoid losing your format while cutting, you just have to format the original range or column with the "format cells option"

I hope someone find this useful.


问:
How Do You Remove Punctuation From A String? (Python)
I need some more help. Basically, I'm trying to return the user input with all non-space and non-alphanumeric characters removed. I made code for this much of the way, but I keep getting errors...

```<code>def remove_punctuation(s):
    '''(str) -> str
    Return s with all non-space or non-alphanumeric
    characters removed.
    >>> remove_punctuation('a, b, c, 3!!')
    'a b c 3'
    '''
    punctuation = '''''!()-[]{};:'"\,<>./?@#$%^&*_~'''
    my_str =  s
    no_punct = ""
    for char in my_str:
        if char not in punctuation:
            no_punct = no_punct + char
    return(no_punct)
</code>```

I'm not sure what I'm doing wrong. Any help is appreciated!

答:
I guess that's will work for you !</p>

```<code>def remove_punctuation(s):
    new_s = [i for i in s if i.isalnum() or i.isalpha() or i.isspace()]
    return ''.join(new_s)
</code>```

Body:
I need some more help. Basically, I'm trying to return the user input with all non-space and non-alphanumeric characters removed. I made code for this much of the way, but I keep getting errors...

def remove_punctuation(s):
    '''(str) -> str
    Return s with all non-space or non-alphanumeric
    characters removed.
    >>> remove_punctuation('a, b, c, 3!!')
    'a b c 3'
    '''
    punctuation = '''''!()-[]{};:'"\,<>./?@#$%^&*_~'''
    my_str =  s
    no_punct = ""
    for char in my_str:
        if char not in punctuation:
            no_punct = no_punct + char
    return(no_punct)

I'm not sure what I'm doing wrong. Any help is appreciated!

Body:
I guess that's will work for you !

def remove_punctuation(s):
    new_s = [i for i in s if i.isalnum() or i.isalpha() or i.isspace()]
    return ''.join(new_s)


问:
Get sum of array and callback a function inside another function
I am trying to solve a problem where I have to get the sum of an array using the .reduce() method inside a function and instead of returning the sum, I need to invoke the callback and pass the sum there.

I am pretty sure I am using the .reduce() correctly but I keep getting 'undefined' and, for the life of me, I cannot figure out how to get invoke a function inside a function.

Any help/explanations would be greatly appreciated!

Question: Sum up all of the integers in the numbers array.
Instead of returning the sum invoke cb and pass in the sum there.

My code:

```<code>function sumArray(numbers, cb) {
  //code here

  numbers.reduce(function(sum, currentValue) {
    return sum + currentValue;
  }, 0);

  cb([1, 2, 3, 4, 5], result);

}

function addTwo(num) {
  const result =  num + 2;
}
</code>```

答:
The question says

Instead of returning the sum invoke cb and pass in the sum there.

means cb(sum), nothing more. With this callback one could do other stuff.

Here is an example:

var numbers = [1, 2, 3, 4, 5];

function sumArray(numbers, cb) {
  var sum = numbers.reduce(function(sum, currentValue) {
    return sum + currentValue;
  }, 0);
  cb(sum);
}

function outputSum(sum) {
  console.log("The sum is " + sum);
}

function addTwo(sum) {
  console.log(sum + 2);
}

sumArray(numbers, outputSum);
sumArray(numbers, addTwo);```

Body:
I am trying to solve a problem where I have to get the sum of an array using the .reduce() method inside a function and instead of returning the sum, I need to invoke the callback and pass the sum there.

I am pretty sure I am using the .reduce() correctly but I keep getting 'undefined' and, for the life of me, I cannot figure out how to get invoke a function inside a function.

Any help/explanations would be greatly appreciated!

Question: Sum up all of the integers in the numbers array.
Instead of returning the sum invoke cb and pass in the sum there.

My code:

function sumArray(numbers, cb) {
  //code here

  numbers.reduce(function(sum, currentValue) {
    return sum + currentValue;
  }, 0);

  cb([1, 2, 3, 4, 5], result);

}

function addTwo(num) {
  const result =  num + 2;
}


问:
How to break a while true with keyboard interruption?
How can I break a while True if I press a key?, and if it is possible, how can I break a while True if a press an x key (e.g. intro)?.

```<code>while True:
    if something is pressed:
        print("STOP")
        break
    do_something()
</code>```

I tryied with inputs but you can't put:

```<code>while True:
    i = input() or None if program wait > 3 seconds. # > = more than
    if != None:
        print("STOP")
        break
    do_something()
</code>```

Input stop all the while waiting for answer, and i don't want that.

PD: I use win 10 64-bits, python 32-bits 3.6, terminal.

PD2: Before post this question I search more about it, i found:

```<code>while True:
    try:
        do_something()
    except KeyboardInterrupt:
        pass
</code>```

But this only stop with Ctrl + c, not other keys.

答:
This only works in Windows:

```<code>import msvcrt
while True:
    if msvcrt.kbhit():
        break
</code>```

The msvcrt provide a list of functions capables of process key inputs. msvcrt.kbhit() check if a key was pressed and it's waiting for been read and return true or false based on that.

Body:
How can I break a while True if I press a key?, and if it is possible, how can I break a while True if a press an x key (e.g. intro)?.

while True:
    if something is pressed:
        print("STOP")
        break
    do_something()

I tryied with inputs but you can't put:

while True:
    i = input() or None if program wait > 3 seconds. # > = more than
    if != None:
        print("STOP")
        break
    do_something()

Input stop all the while waiting for answer, and i don't want that.

PD: I use win 10 64-bits, python 32-bits 3.6, terminal.

PD2: Before post this question I search more about it, i found:

while True:
    try:
        do_something()
    except KeyboardInterrupt:
        pass

But this only stop with Ctrl + c, not other keys.

Body:
This only works in Windows:

import msvcrt
while True:
    if msvcrt.kbhit():
        break

The msvcrt provide a list of functions capables of process key inputs. msvcrt.kbhit() check if a key was pressed and it's waiting for been read and return true or false based on that.


问:
View with editable textviews (onClick)
I have a view with several textView. I want them to be editable on Click.
Following code seems not to do what is supposed to do:

```<code>    textView1 = (TextView) findViewById(R.id.tv1);
    textView1.setText(tv1);
    runEditListener(textView1);

    textView2 = (TextView) findViewById(R.id.tv2);
    textView2.setText(tv2);
    runEditListener(textView1);
</code>```

.......

```<code>    private void runEditListener(TextView textView) {

    dialog = new AlertDialog.Builder(this).create();
    editText = new EditText(this);
    dialog.setTitle("Edit");
    dialog.setView(editText);
    dialog.setButton(DialogInterface.BUTTON_POSITIVE, "Save", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) { textView.setText(editText.getText());

        }
    });

    textView.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View view){
            editText.setText(textView.getText());
            dialog.show();
        }
    });

}
</code>```

I probably should only run once the runEditListener() method and get on which TextView the user clicked but I don't really find how to do that.

答:
```<code>textView.setFocusable(true);
textView.setEnabled(true);
textView.setClickable(true);
textView.setFocusableInTouchMode(true);
</code>```

Title: View with editable textviews (onClick)

Body:
I have a view with several textView. I want them to be editable on Click.
Following code seems not to do what is supposed to do:

    textView1 = (TextView) findViewById(R.id.tv1);
    textView1.setText(tv1);
    runEditListener(textView1);

    textView2 = (TextView) findViewById(R.id.tv2);
    textView2.setText(tv2);
    runEditListener(textView1);

.......

    private void runEditListener(TextView textView) {

    dialog = new AlertDialog.Builder(this).create();
    editText = new EditText(this);
    dialog.setTitle("Edit");
    dialog.setView(editText);
    dialog.setButton(DialogInterface.BUTTON_POSITIVE, "Save", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) { textView.setText(editText.getText());

        }
    });

    textView.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View view){
            editText.setText(textView.getText());
            dialog.show();
        }
    });

}

I probably should only run once the runEditListener() method and get on which TextView the user clicked but I don't really find how to do that.


问:
Showing Div via CSS selector within a UL
I want to build CSS drop down menus.

I want to solve the problem of too long drop down items in UL. So I want to use DIV within a UL.

If you run this example, heading 3 will show you drop down UL items. I want the same for Heading 2 link. Because I put that UL in a DIV. So how can I do it?

CSS Code:

```<code>li{
    list-style: none;
    float: left;
}

li ul {
    display: none;
    background-color: #69f;
}

li:hover > div#mDiv {
    display: block;
}

.menuDiv{
    display: none;
}

li:hover > ul {
    display: block;
}
</code>```

Markup:

```<code><ul>
  <li><a href="#">Heading 1</a></li>
  <li><a href="#">Heading 2</a>
    <div class = "menuDiv" id = "mDiv">
        <ul>
          <li><a href="#">Subitem 1</a></li>
          <li><a href="#">Subitem 2</a></li>
          <li><a href="#">Subitem 3</a></li>
        </ul>
    </div>
  </li>
  <li><a href="#">Heading 3</a>
    <ul>
      <li><a href="#">Subitem 4</a></li>
      <li><a href="#">Subitem 5</a></li>
      <li><a href="#">Subitem 6</a></li>
    </ul>
  </li>
  </ul>
</code>```

答:
Your problem is that because of your css, the div is shown on :hover, but the inner ul is not.

So you can use @BoltClock's solution or change:

```<code>li ul {
    display: none;
    background-color: #69f;
}
</code>```

to:

```<code>li ul {
    background-color: #69f;
}
li > ul {
    display: none;
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I want to build CSS drop down menus.

I want to solve the problem of too long drop down items in UL. So I want to use DIV within a UL.

If you run this example, heading 3 will show you drop down UL items. I want the same for Heading 2 link. Because I put that UL in a DIV. So how can I do it?

CSS Code:

li{
    list-style: none;
    float: left;
}

li ul {
    display: none;
    background-color: #69f;
}

li:hover > div#mDiv {
    display: block;
}

.menuDiv{
    display: none;
}

li:hover > ul {
    display: block;
}

Markup:

Heading 1

Heading 2

Subitem 1

Subitem 2

Subitem 3

Heading 3

Subitem 4

Subitem 5

Subitem 6

Body:
Your problem is that because of your css, the div is shown on :hover, but the inner ul is not.

So you can use @BoltClock's solution or change:

li ul {
    display: none;
    background-color: #69f;
}

to:

li ul {
    background-color: #69f;
}
li > ul {
    display: none;
}


问:
pandas python round timestamp to nearest second
I want to replace certain time stamp values in a spreadsheet using pandas in python.

Background Info

Spreadsheet A has time stamped values every 33 milliseconds (in the Time Stamp column). Also, it (in)conveniently skips every top of the second "S.000".

SPREADSHEET A

Time Stamp            | Location1

5/4/2017 10:00:00.000 | 0.005430355

5/4/2017 10:00:00.033 | 0.004475154

5/4/2017 10:00:00.066 | 0.004958829

5/4/2017 10:00:00.099 | 0.010678668

5/4/2017 10:00:00.133 | 0.014313085

5/4/2017 10:00:00.166 | 0.004182263

5/4/2017 10:00:00.199 | 0.00232128

5/4/2017 10:00:00.233 | 0.004263132

5/4/2017 10:00:00.266 | 0.007513777

.

.

5/4/2017 10:00:00.999 | 0.011229943 #always skips top of the second "S.000"

5/4/2017 10:00:01.033 | 0.016148495 #always skips top of the second "S.000"

5/4/2017 10:00:01.066 | 0.009239103

5/4/2017 10:00:01.099 | 0.015364848

5/4/2017 10:00:01.133 | 0.032139104

5/4/2017 10:00:01.166 | 0.023679454

5/4/2017 10:00:01.199 | 0.002503840

How can I use pandas to round every time stamp that has "X.999" to the nearest second? I want to

see if a value is "X.999" in the to "Time Stamp" column
 if it is "X.999":
     change it to "X+1.000" / or round it up
 else
     leave the time stamp as it is

Then keep repeating the above until I create a new set up time stamps for a new data frame. Or even better, replace the current dataframe time stamps with the new time stamps.

答:
Here is my solution so far...Took a long time, but it works for now.
Consider timestamps whose microseconds value were 9700000 (970 milliseconds) or higher, add whatever its difference was from 1 second to itself, then replace the time stamps with this new sum (always on the X.000 of a second).

Here is the code.

```<code>%matplotlib inline
import seaborn as sns
import matplotlib as mp
import pandas as pd
import numpy as np
import datetime
dfa=pd.read_excel("may2017.xlsx",sheetname=0)
dfb=pd.read_excel("logs.xlsx",sheetname=0, skip_rows=746243)
dfb = b.iloc[746244:754431] #got the index value range from trial and error
a = dfa
b = dfb
adummy = a
bdummy = b

for i in range(len(adummy.index)): #get the length of all rows
    #find the difference between each time stamp from 1 second
    dif = 1000000 - adummy.iloc[i]["Time Stamp"].microsecond
    #change microseconds to timedelta object for later
    tdelta = datetime.timedelta(microseconds=dif)
    #now check if this row timestamp is near a 1-second interval
    if adummy.iloc[i]["Time Stamp"].microsecond > 975000:
        #if near 1 second, 'round up' to the next second by adding tdelta
        tnew = tdelta + adummy.iloc[i]["Time Stamp"]
        #replace the time stamp in this row with the nearest second above
        adummy["Time Stamp"] = adummy["Time Stamp"].replace(adummy.iloc[i]["Time Stamp"], tnew)
        #print this new time to verify the dataframe got updated
        print(adummy.iloc[i]["Time Stamp"])
    else:
#else if the timestamp is not near 1 from the low side, do nothing
        pass
#Restart the loop
</code>```

Output:

```<code>2017-05-04 10:00:01
2017-05-04 10:00:02
2017-05-04 10:00:03
2017-05-04 10:00:04
2017-05-04 10:00:05
2017-05-04 10:00:06
2017-05-04 10:00:07
</code>```

Body:
Here is my solution so far...Took a long time, but it works for now.
Consider timestamps whose microseconds value were 9700000 (970 milliseconds) or higher, add whatever its difference was from 1 second to itself, then replace the time stamps with this new sum (always on the X.000 of a second).

Here is the code.

%matplotlib inline
import seaborn as sns
import matplotlib as mp
import pandas as pd
import numpy as np
import datetime
dfa=pd.read_excel("may2017.xlsx",sheetname=0)
dfb=pd.read_excel("logs.xlsx",sheetname=0, skip_rows=746243)
dfb = b.iloc[746244:754431] #got the index value range from trial and error
a = dfa
b = dfb
adummy = a
bdummy = b

for i in range(len(adummy.index)): #get the length of all rows
    #find the difference between each time stamp from 1 second
    dif = 1000000 - adummy.iloc[i]["Time Stamp"].microsecond
    #change microseconds to timedelta object for later
    tdelta = datetime.timedelta(microseconds=dif)
    #now check if this row timestamp is near a 1-second interval
    if adummy.iloc[i]["Time Stamp"].microsecond > 975000:
        #if near 1 second, 'round up' to the next second by adding tdelta
        tnew = tdelta + adummy.iloc[i]["Time Stamp"]
        #replace the time stamp in this row with the nearest second above
        adummy["Time Stamp"] = adummy["Time Stamp"].replace(adummy.iloc[i]["Time Stamp"], tnew)
        #print this new time to verify the dataframe got updated
        print(adummy.iloc[i]["Time Stamp"])
    else:
#else if the timestamp is not near 1 from the low side, do nothing
        pass
#Restart the loop

Output:

2017-05-04 10:00:01
2017-05-04 10:00:02
2017-05-04 10:00:03
2017-05-04 10:00:04
2017-05-04 10:00:05
2017-05-04 10:00:06
2017-05-04 10:00:07


问:
QIODevice::read: device not open Remote JSON File QT
This has driven me nuts. Been looking everywhere for a solution to this but amazingly there is very little out there about loading remote JSON files into QT.

I've got this code which works fine when I try to load a local file.

```<code>QFile jsonFile("/Users/blah/blah/myfile.json");

if (!jsonFile.open(QIODevice::ReadOnly | QIODevice::Text))
{
    qDebug() << "Unable to open file, exiting...";
    return;
}

QByteArray jsonData = jsonFile.readAll();
QJsonDocument doc = QJsonDocument::fromJson(jsonData);
QJsonObject jObject = doc.object();
QVariantMap json_map = jObject.toVariantMap();

QString getNow = json_map["now"].toString();
QString getImage = json_map["image"].toString();
QString getNext = json_map["next"].toString();

ui->live1->setText(getNow);
ui->live2->setText(getImage);
ui->live3->setText(getNext);
</code>```

But nothing I've tried for the past 5 hours will make it load a remote file and I can't find a straight up explanation showing how such a simple thing is achieved.

```<code> QFile jsonFile("https://myserver.com/myfile.json");
 QUrl jsonFile("https://myserver.com/myfile.json");
</code>```

And a whole bunch of other methods including QTextStream and anything else that I thought might do it like this which seemed way over the top for what I'm trying to do. But everything either returns...

```<code> QIODevice::read: device not open
</code>```

...Or a slew of other errors letting me know just how badly I screwed up.

Can somebody please put me out of my misery here?

** EDIT **

Using the QNetwork libs, but now throwing an expected expression error on the QObject::connect line?

```<code> QNetworkAccessManager manager;
    QNetworkRequest request(QUrl("https://myserver.com/myfile.json"));
    QNetworkReply *reply = manager.get(request);

    QObject::connect(reply, &QNetworkReply::finished, [&]() {
        QByteArray data = reply->readAll();

        QJsonDocument doc = QJsonDocument::fromJson(data);
        QJsonObject jObject = doc.object();
        QVariantMap json_map = jObject.toVariantMap();

        QString getNow = json_map["now"].toString();
        QString getImage = json_map["image"].toString();
        QString getNext = json_map["next"].toString();

        ui->live1->setText(getNow);
        ui->live2->setText(getImage);
        ui->live3->setText(getNext);

        reply->deleteLater();
    });
</code>```

** EDIT 2 **

I just realised that I need to include the C++11 compiler

```<code> CONFIG += c++11
</code>```

But now it's just gone mental throwing SSL errors

```<code> qt.network.ssl: QSslSocket: cannot resolve TLSv1_1_client_method
 qt.network.ssl: QSslSocket: cannot resolve TLSv1_2_client_method
 qt.network.ssl: QSslSocket: cannot resolve TLSv1_1_server_method
 qt.network.ssl: QSslSocket: cannot resolve TLSv1_2_server_method
 qt.network.ssl: QSslSocket: cannot resolve SSL_select_next_proto
 qt.network.ssl: QSslSocket: cannot resolve SSL_CTX_set_next_proto_select_cb
 qt.network.ssl: QSslSocket: cannot resolve SSL_get0_next_proto_negotiated
</code>```

** EDIT 3 **

Making some progress (I guess...)

It seems that QT is using an old version of SSL (which probably isn't supported according to the docs).

QDebug spat out this when asked about the SSL...

```<code> Support SSL:   true
 Lib Version Number:  9470431
 Lib Version String:  "OpenSSL 0.9.8zh 14 Jan 2016"
 Lib Build Version Number:  268439727
 Lib Build Version String:  "OpenSSL 1.0.1j 15 Oct 2014"
</code>```

So now I need to figure out how to make QT use the newer version that's on my machine.

答:
QFile does not support remote URIs. You need to use QtNetwork for this.

The following C++11 example demonstrates how to retrieve JSON from a remote URI:

```<code>QNetworkAccessManager manager;
QNetworkRequest request(QUrl("http://example.com/file.json"));
QNetworkReply *reply = manager.get(request);

QObject::connect(reply, &QNetworkReply::finished, [&]() {
    QByteArray data = reply->readAll();
    // do stuff with data
    reply->deleteLater();
});
</code>```

Body:
This has driven me nuts. Been looking everywhere for a solution to this but amazingly there is very little out there about loading remote JSON files into QT.

I've got this code which works fine when I try to load a local file.

QFile jsonFile("/Users/blah/blah/myfile.json");

if (!jsonFile.open(QIODevice::ReadOnly | QIODevice::Text))
{
    qDebug() << "Unable to open file, exiting...";
    return;
}

QByteArray jsonData = jsonFile.readAll();
QJsonDocument doc = QJsonDocument::fromJson(jsonData);
QJsonObject jObject = doc.object();
QVariantMap json_map = jObject.toVariantMap();

QString getNow = json_map["now"].toString();
QString getImage = json_map["image"].toString();
QString getNext = json_map["next"].toString();

ui->live1->setText(getNow);
ui->live2->setText(getImage);
ui->live3->setText(getNext);

But nothing I've tried for the past 5 hours will make it load a remote file and I can't find a straight up explanation showing how such a simple thing is achieved.

 QFile jsonFile("https://myserver.com/myfile.json");
 QUrl jsonFile("https://myserver.com/myfile.json");

And a whole bunch of other methods including QTextStream and anything else that I thought might do it like this which seemed way over the top for what I'm trying to do. But everything either returns...

 QIODevice::read: device not open

...Or a slew of other errors letting me know just how badly I screwed up.

Can somebody please put me out of my misery here?

** EDIT **

Using the QNetwork libs, but now throwing an expected expression error on the QObject::connect line?

 QNetworkAccessManager manager;
    QNetworkRequest request(QUrl("https://myserver.com/myfile.json"));
    QNetworkReply *reply = manager.get(request);

    QObject::connect(reply, &QNetworkReply::finished, [&]() {
        QByteArray data = reply->readAll();

        QJsonDocument doc = QJsonDocument::fromJson(data);
        QJsonObject jObject = doc.object();
        QVariantMap json_map = jObject.toVariantMap();

        QString getNow = json_map["now"].toString();
        QString getImage = json_map["image"].toString();
        QString getNext = json_map["next"].toString();

        ui->live1->setText(getNow);
        ui->live2->setText(getImage);
        ui->live3->setText(getNext);

        reply->deleteLater();
    });

** EDIT 2 **

I just realised that I need to include the C++11 compiler

 CONFIG += c++11

But now it's just gone mental throwing SSL errors

 qt.network.ssl: QSslSocket: cannot resolve TLSv1_1_client_method
 qt.network.ssl: QSslSocket: cannot resolve TLSv1_2_client_method
 qt.network.ssl: QSslSocket: cannot resolve TLSv1_1_server_method
 qt.network.ssl: QSslSocket: cannot resolve TLSv1_2_server_method
 qt.network.ssl: QSslSocket: cannot resolve SSL_select_next_proto
 qt.network.ssl: QSslSocket: cannot resolve SSL_CTX_set_next_proto_select_cb
 qt.network.ssl: QSslSocket: cannot resolve SSL_get0_next_proto_negotiated

** EDIT 3 **

Making some progress (I guess...)

It seems that QT is using an old version of SSL (which probably isn't supported according to the docs).

QDebug spat out this when asked about the SSL...

 Support SSL:   true
 Lib Version Number:  9470431
 Lib Version String:  "OpenSSL 0.9.8zh 14 Jan 2016"
 Lib Build Version Number:  268439727
 Lib Build Version String:  "OpenSSL 1.0.1j 15 Oct 2014"

So now I need to figure out how to make QT use the newer version that's on my machine.

Body:
QFile does not support remote URIs. You need to use QtNetwork for this.

The following C++11 example demonstrates how to retrieve JSON from a remote URI:

QNetworkAccessManager manager;
QNetworkRequest request(QUrl("http://example.com/file.json"));
QNetworkReply *reply = manager.get(request);

QObject::connect(reply, &QNetworkReply::finished, [&]() {
    QByteArray data = reply->readAll();
    // do stuff with data
    reply->deleteLater();
});


问:
Can't get object key in firebase
Problem: I am making an app with Firebase and React Native where users can post, and then other users can comment on posts. To do the comments, I need to grab the key of the content of a post. I tried using the child.getKey() function, but that gave me an error.

```<code>child.getKey is not a function. (In 'child.getKey()', 'child.getKey' is undefined)
</code>```

I would really love some help getting the key. Thank you!

Code

```<code>  getItems(){
    var items = [];
    var query = ref.orderByKey();
    query.once ('value', (snap) => {
      snap.forEach ( (child) => {
       items.push({
         content: child.val().content,
         key: child.getKey()
     });
     });
    items.reverse();
    }).then(() => {
        this.setState({firebaseItems: items});
    });
 }
</code>```

Firebase layout

```<code>Posts:
    -Kier498dma39md:
        content: 'This is an example post. The numbers above me are an example of the random key I am trying to get.'
</code>```

答: So, I did some research, and eventually found out all I needed to do was use key: child.key

Title: Can't get object key in firebase

Body:
Problem: I am making an app with Firebase and React Native where users can post, and then other users can comment on posts. To do the comments, I need to grab the key of the content of a post. I tried using the child.getKey() function, but that gave me an error.

child.getKey is not a function. (In 'child.getKey()', 'child.getKey' is undefined)

I would really love some help getting the key. Thank you!

Code

  getItems(){
    var items = [];
    var query = ref.orderByKey();
    query.once ('value', (snap) => {
      snap.forEach ( (child) => {
       items.push({
         content: child.val().content,
         key: child.getKey()
     });
     });
    items.reverse();
    }).then(() => {
        this.setState({firebaseItems: items});
    });
 }

Firebase layout

Posts:
    -Kier498dma39md:
        content: 'This is an example post. The numbers above me are an example of the random key I am trying to get.'


问:
mysql select * from table where column a value = column b value laravel
Im trying to query a table with column called completed and column called follow_ups among other columns - using laravel im trying to

```<code> select * from table where completed > follow_ups
 select * from table where completed = follow_ups
</code>```

using laravel model im running the following

```<code> $followUps = TestFollowups::where('follow_ups', '>', 'completed')->get();
</code>```

I dont have to use laravels model system i can write a manual query as well but unsure what the query should look like. Can anyone help please

答:
You can use:</p>

```<code>whereRaw(select * from table where completed > follow_ups)
</code>```

Body:
Im trying to query a table with column called completed and column called follow_ups among other columns - using laravel im trying to

 select * from table where completed > follow_ups
 select * from table where completed = follow_ups

using laravel model im running the following

 $followUps = TestFollowups::where('follow_ups', '>', 'completed')->get();

I dont have to use laravels model system i can write a manual query as well but unsure what the query should look like. Can anyone help please

Body:
You can use:

whereRaw(select * from table where completed > follow_ups)


问:
How long since last time app was opened in iOS?
How can I tell the time from the last time my app was open?  Can this still be monitored even my app is not running in the background?

Thanks.

答:
Put something like

```<code>[[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:@"kLastCloseDate"];
</code>```

in both

```<code>- (void)applicationWillTerminate:(UIApplication *)application
- (void)applicationDidEnterBackground:(UIApplication *)application
</code>```

Then check the difference at startup:

```<code>NSDate *lastDate = [[NSUserDefaults standardUserDefaults] objectForKey:@"kLastCloseDate"];
NSTimeInterval timeDiff = [[NSDate date] timeIntervalSinceDate:lastDate];
// your stuff
</code>```

in both

```<code>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
- (void)applicationWillEnterForeground:(UIApplication *)application
</code>```

Body:
Put something like

[[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:@"kLastCloseDate"];

in both

- (void)applicationWillTerminate:(UIApplication *)application
- (void)applicationDidEnterBackground:(UIApplication *)application

Then check the difference at startup:

NSDate *lastDate = [[NSUserDefaults standardUserDefaults] objectForKey:@"kLastCloseDate"];
NSTimeInterval timeDiff = [[NSDate date] timeIntervalSinceDate:lastDate];
// your stuff

in both

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
- (void)applicationWillEnterForeground:(UIApplication *)application


答:
Can you use the regular expression module? If so, you can do:</p>

```<code>import re

def remove_punctuation(s)
    return re.sub(r'[^\w 0-9]|_', '', s)
</code>```

Title: How Do You Remove Punctuation From A String? (Python)

Body:
Can you use the regular expression module? If so, you can do:

import re

def remove_punctuation(s)
    return re.sub(r'[^\w 0-9]|_', '', s)


问:
relative and absolute html path?
The code snippet in html format is showing as below.
there are three requirements listed below for reference as well.</p>

```<code>   <!DOCTYPE html>
    <html lang="en">
    <head>
        <title>Images and Links - Fast Broccoli!</title>
    </head>
    <body>
        <div class="content">
            <h1>Fast Broccoli! - About Us</h1>
            <!--
                Use images and links to build an "About Us" page for Fast Broccoli!,
                the world's first one-hour organic produce delivery service.

            You'll need:
            1. A main image with source: https://upload.wikimedia.org/wikipedia/commons/0/03/Broccoli_and_cross_section_edit.jpg
                  and alt description: Fast Broccoli!'s Logo
            2. A link to the relative path: index.html
                with the text: Return Home
            3. A second link to the absolute path: https://shop.fastbrocolli.com
                The link should target a new browser window.
                The link should contain an image
                    with source: images/cabbage.png
                   -->
        </div>
    </body>
    </html>
</code>```

答:
i m getting this error "I can't find your main image with src="https://upload.wikimedia.org/wikipedia/commons/0/03/Broccoli_and_cross_section_edit.jpg". Please add it."

```<code>    <h1>Fast Broccoli! - About Us</h1>

  <img src="Broccoli_and_cross_section_edit.jpg" alt="Fast Broccoli!'s Logo"
       style="width: 60px;"/>

  <a href="index.html">Return Home</a>

  <a href="https://shop.fastbrocolli.com">
  <img src="images/cabbage.png" />
  </a>
</code>```

Title: relative and absolute html path?

Body:
The code snippet in html format is showing as below.
there are three requirements listed below for reference as well.

   <!DOCTYPE html>

        <title>Images and Links - Fast Broccoli!</title>

Fast Broccoli! - About Us

Body:
i m getting this error "I can't find your main image with src="https://upload.wikimedia.org/wikipedia/commons/0/03/Broccoli_and_cross_section_edit.jpg". Please add it."

    <h1>Fast Broccoli! - About Us</h1>

  <img src="Broccoli_and_cross_section_edit.jpg" alt="Fast Broccoli!'s Logo"
       style="width: 60px;"/>

  <a href="index.html">Return Home</a>

  <a href="https://shop.fastbrocolli.com">
  <img src="images/cabbage.png" />
  </a>


问:
How to call my function in another function
I am getting an value from the user in getInteger.

I need to get the output from sqInteger in getInteger.

No matter how I set up the parameters or indent the sqInteger function, variable x is undefined.

I added a return line to try and pass the x variable, but that's definitely not helping.

Please help me understand what I'm missing!

```<code>def getInteger():
   while True:
      try:
          x = int(input('Enter an integer: '))
      except ValueError:
          print()
          print('That\'s not an integer.  Try again.')
          continue
      else:
          return x
          print(x)
          break

def sqInteger(getInteger, x):
   y = x**2
   print(y)
</code>```

答:
Is this the entire code?  You need to call the getInteger() function at some point in the code before that loop will begin.  You're also not calling function sqInteger() at any point.

Your exception handler will immediately stop evaluating the try block and move down to the except block upon a non-integer being typed into the input.  Therefore, you can place a call to the sqInteger() function after the input() function.  If the user types a non-integer into the terminal, it will move down to your Exception handler and prompt the user to retry.  If they enter an integer, the code will continue to evaluate and run the function sqInteger.

For this, you also do not need to pass getInteger into the sqInteger() function.  You are technically allowed to pass functions as parameters in Python but it's not necessary for this and probably out of the scope of this program.

So the following code would be suitable:

```<code>def getInteger():
   while True:
      try:
          x = int(input('Enter an integer: '))
          # variable 'squared' now receives the return value from the function
          squared = sqInteger(x) # call to function sqInteger necessary for this function to be executed
      except ValueError:
          print('That\'s not an integer.  Try again.')
          continue
      else:
          print(x) # if user entered 2, prints 2, not 4
          return x # this value is still only what the user input, not the result of sqInteger()
          break

def sqInteger(x):
   y = x**2
   print(y)
   return y #you need to return values from functions in order to access it from outside the function
</code>```

The reason you pass a variable into a function (as a parameter) is to give that function access to that variable.  Creating a function creates a local scope for that function so that variables named within that function are in a separate namespace from variables outside that function.  This is useful in large programs where many variables might exist and you need to keep them separate.

Because you've separately defined a sqrt function, it does not have access to variables outside of its scope.  You need to pass in variables that you'd like it to have access to.

You also need to call functions before they will run.  Defining a function only serves to set up the function so that it can be called as one functional unit.  It's useful for separating concerns within a program.  The ability to call a function is useful because it allows you to separate your code out and only mention a single call to a function rather than having the entire functionality jumbled in with the rest of the code.  It also allows for reusability of code.

You can also have access to the result of the squared integer by returning a value and assigning this value to a function call, like such:

```<code># lets say x = 4
squared = sqInteger(x)

def sqInteger(x):
   y = x**2
   return y
</code>```

This would NOT work:

```<code>x = input("Enter integer") #lets say you enter 3
squared = sqInteger()
print(squared)

def sqInteger():
    print(x) # error: x is not defined
    return x**2 # error: x is not defined
</code>```

The function does not have access to outside variables like x.  It must be passed these variables as parameters so that you can call this function and set the parameters at will.  This is for the sake of modularity in a program.  You can pass it all sorts of different integers as parameters and it allows you to have a resuable function for anytime you need to square an integer.

Edit:  Sorry this was a mess, I finally fixed all the errors in my explanation though...

Body:
I am getting an value from the user in getInteger.

I need to get the output from sqInteger in getInteger.

No matter how I set up the parameters or indent the sqInteger function, variable x is undefined.

I added a return line to try and pass the x variable, but that's definitely not helping.

Please help me understand what I'm missing!

def getInteger():
   while True:
      try:
          x = int(input('Enter an integer: '))
      except ValueError:
          print()
          print('That\'s not an integer.  Try again.')
          continue
      else:
          return x
          print(x)
          break

def sqInteger(getInteger, x):
   y = x**2
   print(y)

Body:
Is this the entire code?  You need to call the getInteger() function at some point in the code before that loop will begin.  You're also not calling function sqInteger() at any point.

Your exception handler will immediately stop evaluating the try block and move down to the except block upon a non-integer being typed into the input.  Therefore, you can place a call to the sqInteger() function after the input() function.  If the user types a non-integer into the terminal, it will move down to your Exception handler and prompt the user to retry.  If they enter an integer, the code will continue to evaluate and run the function sqInteger.

For this, you also do not need to pass getInteger into the sqInteger() function.  You are technically allowed to pass functions as parameters in Python but it's not necessary for this and probably out of the scope of this program.

So the following code would be suitable:

def getInteger():
   while True:
      try:
          x = int(input('Enter an integer: '))
          # variable 'squared' now receives the return value from the function
          squared = sqInteger(x) # call to function sqInteger necessary for this function to be executed
      except ValueError:
          print('That\'s not an integer.  Try again.')
          continue
      else:
          print(x) # if user entered 2, prints 2, not 4
          return x # this value is still only what the user input, not the result of sqInteger()
          break

def sqInteger(x):
   y = x**2
   print(y)
   return y #you need to return values from functions in order to access it from outside the function

The reason you pass a variable into a function (as a parameter) is to give that function access to that variable.  Creating a function creates a local scope for that function so that variables named within that function are in a separate namespace from variables outside that function.  This is useful in large programs where many variables might exist and you need to keep them separate.

Because you've separately defined a sqrt function, it does not have access to variables outside of its scope.  You need to pass in variables that you'd like it to have access to.

You also need to call functions before they will run.  Defining a function only serves to set up the function so that it can be called as one functional unit.  It's useful for separating concerns within a program.  The ability to call a function is useful because it allows you to separate your code out and only mention a single call to a function rather than having the entire functionality jumbled in with the rest of the code.  It also allows for reusability of code.

You can also have access to the result of the squared integer by returning a value and assigning this value to a function call, like such:

# lets say x = 4
squared = sqInteger(x)

def sqInteger(x):
   y = x**2
   return y

This would NOT work:

x = input("Enter integer") #lets say you enter 3
squared = sqInteger()
print(squared)

def sqInteger():
    print(x) # error: x is not defined
    return x**2 # error: x is not defined

The function does not have access to outside variables like x.  It must be passed these variables as parameters so that you can call this function and set the parameters at will.  This is for the sake of modularity in a program.  You can pass it all sorts of different integers as parameters and it allows you to have a resuable function for anytime you need to square an integer.

Edit:  Sorry this was a mess, I finally fixed all the errors in my explanation though...


问:
When to use getX method
Coming from a C# background we use properties for something that would not take long to retrieve and a getX method if something would take long (msdn link). In Java, since there are no properties, do you use getX for both cases or is there some other convention to indicate a quick access from a not so quick access (other than documenting it)?

Edit:
For example would you use a different naming convention for a time consuming get operation like database access or also use the getX naming convention?

答: It depends on the situation and exactly what you're doing - for example, you might use loadX, fetchX, computeX - or sometimes just getX as for normal "cheap" properties.

Title: When to use getX method


答:
There is an inbuilt function to get the punctuations...

```<code>    s="This is a String with Punctuations !!!!@@$##%"
    import string
    punctuations = set(string.punctuations)
    withot_punctuations = ''.join(ch for ch in s if ch not in punctuations)
</code>```

You will get the string without punctuations

```<code>output:
This is a String with Punctuations
</code>```

You can find more about string functions here

Body:
I need some more help. Basically, I'm trying to return the user input with all non-space and non-alphanumeric characters removed. I made code for this much of the way, but I keep getting errors...

def remove_punctuation(s):
    '''(str) -> str
    Return s with all non-space or non-alphanumeric
    characters removed.
    >>> remove_punctuation('a, b, c, 3!!')
    'a b c 3'
    '''
    punctuation = '''''!()-[]{};:'"\,<>./?@#$%^&*_~'''
    my_str =  s
    no_punct = ""
    for char in my_str:
        if char not in punctuation:
            no_punct = no_punct + char
    return(no_punct)

I'm not sure what I'm doing wrong. Any help is appreciated!

Body:
There is an inbuilt function to get the punctuations...

    s="This is a String with Punctuations !!!!@@$##%"
    import string
    punctuations = set(string.punctuations)
    withot_punctuations = ''.join(ch for ch in s if ch not in punctuations)

You will get the string without punctuations

output:
This is a String with Punctuations

You can find more about string functions here


问:
I am trying to create a function based on user input. What am I doing with my Code?
My goal is to get user input for different variables and then use the input to create an equation.  The equation should read like this U1= 2*((DM/2)(D2)) ; U2= D1/ (DS/2); U3= (U1-U2) ; U4 = (D2-D1); U= (U3/U4).

Do I have to do document.getelementbyId tag or is there an another way.

```<code>       <html>
       <head>

       <script>
        var DM
        DM = prompt ("Moon's Diameter");
        var DE
        DE = prompt ("Earth's Diameter");
           var DS
        DS = prompt ("Sun's Diameter");
        var D1
         D1 = prompt ("Distance from Earth to the Moon");
        var D2
         D2= prompt ("Distance from Sun to the Moon");

       function umbra() {
       var U1 = (2*((DM/2) * (D2));
      return (U1);
      var U2 = (D1)*(DS/2);
          return (U2);
      var U3= U1-U2;
        return (U3);
       var U4 = (D2-D1);
     return (U4)
    var U = (U3/U4)
    return (U)
     }
    document.write(umbra)
    </script>
    </head>
    <body>

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

答:
Creat a little Web page, Use HTML input fields, let the user type their numbers, create a "Calculate" button, and display the result on click in a read-only input field.

Consider using jQuery. It makes things easier.

There's a bizillion calculators on the net that work like this. Google "volume calc" "mortgage calc" "auto calc" etc for examples.


问:
Find Item.index after using Items.find
How do you look up the index of a contact item that was set using the items.find method?  After finding the item, I want to be able to move to the next item, but my code sends me to the first item in the collection.  A condensed version of my plan is below...

```<code>dim ColItms as items
dim CI as contactItem
Dim CIindex as integer

set CI= ColItms.find("[CompanyName] = ""IBM""")
CIindex = CI.????  '''''  This shows what I'm wanting to do, but don't know how

' now advance to next item in collection
set ci = ColItms.item(CIindex +1) ' i think this would work if I could find CIindex

set ci = ColItms.GetNext ' this fails as it returns the 1st item in the collection
</code>```

Right now all that seems to work is to loop through each item in the collection to see if it matches the found contact,

答:
Items have no intrinsic index, only an entry id.
To find the next match, use Items.FindNext.

Title: Find Item.index after using Items.find

Body:
How do you look up the index of a contact item that was set using the items.find method?  After finding the item, I want to be able to move to the next item, but my code sends me to the first item in the collection.  A condensed version of my plan is below...

dim ColItms as items
dim CI as contactItem
Dim CIindex as integer

set CI= ColItms.find("[CompanyName] = ""IBM""")
CIindex = CI.????  '''''  This shows what I'm wanting to do, but don't know how

' now advance to next item in collection
set ci = ColItms.item(CIindex +1) ' i think this would work if I could find CIindex

set ci = ColItms.GetNext ' this fails as it returns the 1st item in the collection

Right now all that seems to work is to loop through each item in the collection to see if it matches the found contact,


问:
R - replacing values in a column with those of another column when other column is not missing
I have the following dataframe:

```<code>    IID sex longitude latitude longitude.1 latitude.1 longitude.2 latitude.2
1234587   0    351500   383500          NA         NA          NA         NA
5145633   1    431340   265505          NA         NA          NA         NA
1305430   1    449500   244900      262500     265500          NA         NA
5012044   0    445600   514300          NA         NA          NA         NA
1234059   1        NA       NA      514300     514300      445500     445520
3087662   0    444500   425200          NA         NA          NA         NA
....
....etc
</code>```

I want to replace the values of longitude with the values of longitude.1 whenever longitude.1 is not missing, and do the same for latitude and latitude.1. I thought this should be easy and tried the following:

```<code>MyData$longitude[!is.na(MyData$longitude.1)] <- MyData$longitude.1
MyData$latitude[!is.na(MyData$latitude.1)] <- MyData$latitude.1
</code>```

However, I get the following error:

```<code>Warning message:
In MyData$longitude[!is.na(MyData$longitude.1)] <- MyData$longitude.1 :
  number of items to replace is not a multiple of replacement length
</code>```

What did I do wrong?

The outcome should be this:

```<code>    IID sex longitude latitude longitude.1 latitude.1 longitude.2 latitude.2
1234587   0    351500   383500          NA         NA          NA         NA
5145633   1    431340   265505          NA         NA          NA         NA
1305430   1    262500   265500      262500     265500          NA         NA
5012044   0    445600   514300          NA         NA          NA         NA
1234059   1    514300   514300      514300     514300      445500     445520
3087662   0    444500   425200          NA         NA          NA         NA
....
....etc
</code>```

答:
MyData$longitude[!is.na(MyData$longitude.1)] yields 2 NA whereas MyData$longitude.1 is all the 6 values. So assignment fails. Get the longitude.1 that is not NA as well:

```<code>MyData$longitude[!is.na(MyData$longitude.1)] <- MyData$longitude.1[!is.na(MyData$longitude.1)]

MyData$latitude[!is.na(MyData$latitude.1)] <- MyData$latitude.1[!is.na(MyData$latitude.1)]
</code>```

Body:
I have the following dataframe:

    IID sex longitude latitude longitude.1 latitude.1 longitude.2 latitude.2
1234587   0    351500   383500          NA         NA          NA         NA
5145633   1    431340   265505          NA         NA          NA         NA
1305430   1    449500   244900      262500     265500          NA         NA
5012044   0    445600   514300          NA         NA          NA         NA
1234059   1        NA       NA      514300     514300      445500     445520
3087662   0    444500   425200          NA         NA          NA         NA
....
....etc

I want to replace the values of longitude with the values of longitude.1 whenever longitude.1 is not missing, and do the same for latitude and latitude.1. I thought this should be easy and tried the following:

MyData$longitude[!is.na(MyData$longitude.1)] <- MyData$longitude.1
MyData$latitude[!is.na(MyData$latitude.1)] <- MyData$latitude.1

However, I get the following error:

Warning message:
In MyData$longitude[!is.na(MyData$longitude.1)] <- MyData$longitude.1 :
  number of items to replace is not a multiple of replacement length

What did I do wrong?

The outcome should be this:

    IID sex longitude latitude longitude.1 latitude.1 longitude.2 latitude.2
1234587   0    351500   383500          NA         NA          NA         NA
5145633   1    431340   265505          NA         NA          NA         NA
1305430   1    262500   265500      262500     265500          NA         NA
5012044   0    445600   514300          NA         NA          NA         NA
1234059   1    514300   514300      514300     514300      445500     445520
3087662   0    444500   425200          NA         NA          NA         NA
....
....etc

Body:
MyData$longitude[!is.na(MyData$longitude.1)] yields 2 NA whereas MyData$longitude.1 is all the 6 values. So assignment fails. Get the longitude.1 that is not NA as well:

MyData$longitude[!is.na(MyData$longitude.1)] <- MyData$longitude.1[!is.na(MyData$longitude.1)]

MyData$latitude[!is.na(MyData$latitude.1)] <- MyData$latitude.1[!is.na(MyData$latitude.1)]


问:
How to create a file upload button in Racket?
So I'm writing a small Racket application that will parse a (very poorly formatted) .txt file and output a .csv that can be worked with in Excel.  The first thing I want to do is open up a small window with a button that opens a file dialog so the user can select the file to be converted (just like any program that launches an open file selection dialog).  I've looked around online and can't find anything on this.  This is going to be a native application, so the stuff I have found on POSTing to webservers isn't relevant.  How can you do this in Racket?</p>

答:
The procedures get-file and put-file exist in #lang racket/gui. Both can be used to obtain file pathnames from users via a dialog. get-file is styled towards selecting existing files, while put-file is directed towards creating new ones.

Consider the following example that does the following:

It creates a window containing a "Select File" button.

When button is clicked, a dialog will appear to select a file (can be the .txt file for conversion).

Once the text file is selected, it will open another dialog to select a file to save converted data on (can be the .csv file).

```<code>#lang racket/gui

;; Prints file's contents line by line
(define (print-each-line input-file)
  (define line (read-line input-file))
  (unless (eof-object? line)
    ;; 'line' here represents a line of txt file's contents
    ;; The line can be processed/modified to any desired output, but
    ;; for the purposes of this example, the line will simply be
    ;; printed the way it is without any "processing".
    (println line)
    (print-each-line input-file)))

;; Convert txt to csv by printing each line of txt
;; to the csv file using print-each-line (above)
(define (convert txt csv)
  (define in (open-input-file txt))
  (with-output-to-file csv
    (lambda () (print-each-line in)))
  (close-input-port in))

;; Make a frame by instantiating the frame% class
(define frame (new frame% [label "Example"]))

;; Make a button in the frame
(new button% [parent frame]
             [label "Select File"]
             ;; Callback procedure for a button click:
             [callback
              (lambda (button event)
                (define txt (get-file))
                (define csv (put-file))
                (convert txt csv))])

;; Show the frame by calling its show method
(send frame show #t)
</code>```

Body:
The procedures get-file and put-file exist in #lang racket/gui. Both can be used to obtain file pathnames from users via a dialog. get-file is styled towards selecting existing files, while put-file is directed towards creating new ones.

Consider the following example that does the following:

It creates a window containing a "Select File" button.

When button is clicked, a dialog will appear to select a file (can be the .txt file for conversion).

Once the text file is selected, it will open another dialog to select a file to save converted data on (can be the .csv file).

#lang racket/gui

;; Prints file's contents line by line
(define (print-each-line input-file)
  (define line (read-line input-file))
  (unless (eof-object? line)
    ;; 'line' here represents a line of txt file's contents
    ;; The line can be processed/modified to any desired output, but
    ;; for the purposes of this example, the line will simply be
    ;; printed the way it is without any "processing".
    (println line)
    (print-each-line input-file)))

;; Convert txt to csv by printing each line of txt
;; to the csv file using print-each-line (above)
(define (convert txt csv)
  (define in (open-input-file txt))
  (with-output-to-file csv
    (lambda () (print-each-line in)))
  (close-input-port in))

;; Make a frame by instantiating the frame% class
(define frame (new frame% [label "Example"]))

;; Make a button in the frame
(new button% [parent frame]
             [label "Select File"]
             ;; Callback procedure for a button click:
             [callback
              (lambda (button event)
                (define txt (get-file))
                (define csv (put-file))
                (convert txt csv))])

;; Show the frame by calling its show method
(send frame show #t)


问:
How Do You Remove Punctuation From A String? (Python)
I need some more help. Basically, I'm trying to return the user input with all non-space and non-alphanumeric characters removed. I made code for this much of the way, but I keep getting errors...

```<code>def remove_punctuation(s):
    '''(str) -> str
    Return s with all non-space or non-alphanumeric
    characters removed.
    >>> remove_punctuation('a, b, c, 3!!')
    'a b c 3'
    '''
    punctuation = '''''!()-[]{};:'"\,<>./?@#$%^&*_~'''
    my_str =  s
    no_punct = ""
    for char in my_str:
        if char not in punctuation:
            no_punct = no_punct + char
    return(no_punct)
</code>```

I'm not sure what I'm doing wrong. Any help is appreciated!

答:
I added the space character to your punctuation string and cleanup up your use of quotes in the punctuation string. Then I cleaned up the code in my own style so that can see the small differences.</p>

```<code>def remove_punctuation(str):
    '''(str) -> str
    Return s with all non-space or non-alphanumeric
    characters removed.
    >>> remove_punctuation('a, b, c, 3!!')
    'a b c 3'
    '''
    punctuation = "! ()-[]{};:'\"\,<>./?@#$%^&*_~"
    no_punct = ""
    for c in str:
        if c not in punctuation:
            no_punct += c
    return(no_punct)

result = remove_punctuation('a, b, c, 3!!')
print("Result 1: ", result)
result = remove_punctuation("! ()-[]{};:'\"\,<>./?@#$%^&*_~")
print("Result 2: ", result)
</code>```

Body:
I added the space character to your punctuation string and cleanup up your use of quotes in the punctuation string. Then I cleaned up the code in my own style so that can see the small differences.

def remove_punctuation(str):
    '''(str) -> str
    Return s with all non-space or non-alphanumeric
    characters removed.
    >>> remove_punctuation('a, b, c, 3!!')
    'a b c 3'
    '''
    punctuation = "! ()-[]{};:'\"\,<>./?@#$%^&*_~"
    no_punct = ""
    for c in str:
        if c not in punctuation:
            no_punct += c
    return(no_punct)

result = remove_punctuation('a, b, c, 3!!')
print("Result 1: ", result)
result = remove_punctuation("! ()-[]{};:'\"\,<>./?@#$%^&*_~")
print("Result 2: ", result)


问:
Selecting an element with different value but similar id
How can you select an  element with value 2 using jQuery, if they all have same name and id?

```<code> <input type="radio" id="store" name="store" value="1">
    <input type="radio" id="store" name="store" value="2">
     <input type="radio" id="store" name="store" value="3">
</code>```

jQuery that didn't work:

```<code>$('#store:input[type="radio", value="2"]').html();
</code>```

答: You can't—there should only be one instance of any given #id on the page. </p>

Body:
How can you select an  element with value 2 using jQuery, if they all have same name and id?

 <input type="radio" id="store" name="store" value="1">
    <input type="radio" id="store" name="store" value="2">
     <input type="radio" id="store" name="store" value="3">

jQuery that didn't work:

$('#store:input[type="radio", value="2"]').html();


答:
Read about multiple attribute selector.

This should work:
$('#store:input[type="radio"][value="2"]').html();

Title: Selecting an element with different value but similar id


问:
How do I convert struct System.Byte byte[] to a System.IO.Stream object in C#?
How do I convert struct System.Byte byte[] to a System.IO.Stream object in C#?

答:
You're looking for the MemoryStream.Write method.

For example, the following code will write the contents of a byte[] array into a memory stream:

```<code>byte[] myByteArray = new byte[10];
MemoryStream stream = new MemoryStream();
stream.Write(myByteArray, 0, myByteArray.Length);
</code>```

Alternatively, you could create a new, non-resizable MemoryStream object based on the byte array:

```<code>byte[] myByteArray = new byte[10];
MemoryStream stream = new MemoryStream(myByteArray);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
You're looking for the MemoryStream.Write method.

For example, the following code will write the contents of a byte[] array into a memory stream:

byte[] myByteArray = new byte[10];
MemoryStream stream = new MemoryStream();
stream.Write(myByteArray, 0, myByteArray.Length);

Alternatively, you could create a new, non-resizable MemoryStream object based on the byte array:

byte[] myByteArray = new byte[10];
MemoryStream stream = new MemoryStream(myByteArray);


问:
DAO as Service vs DAO as Library
I have 3 different services which needs to access same database. Each of these service will serve different purpose and different queries. I can generalize them in following way

Service 1 -> Customer Inquires

Service 2 -> Order Processor (e.g.workflow for placed orders)

Service 3 -> Reporting

I have written a DAO to expose data. I am evaluating two system designs for scalability and maintenance.

Option 1:  Write one more service to expose DAO functionality as Data Service.

Pros:

Load on database will be controlled and easy to scale-in/out as needed

Easy to maintain for future updates

Access control for various actions

clients doesn't have full access on underlying database

Cons:

Single point of failure

management of extra service

Need to enforce backward compatibility rules

In case of DataService downtime every service is affected (factors other than database downtime)

And

Option 2: Create a storage library out of DAO and use these library in above mentioned three services.

Pros:

distributed, impact radius is very small

Cons:

Every service get full access on database

Needs to update all three services for new features

Which option is good and why?

Any other ideas/architecture designs to consider?

What are the things I need to consider when choosing architecture?

答:
Thank you Rob and Maksym for your inputs.

I separated queries based on bounded context and created library and service for different context.

Service

Inquiry and Order Service access data using data service. This helped me control noisy neighbor and resource allocation.

Library

I replicated data from main database to reporting database and built a library for Reporting service to access reporting database.

Title: DAO as Service vs DAO as Library