问:
JavaFX How to add elements eg. Buttons dynamically created from items stored in the database Mysql?
There is this video in youtube https://www.youtube.com/watch?v=Idtm2Y6I23w
Whereby the person has dynamically populated buttons created from the items that are stored in the database.For instance in this picture

It has some categories that includes Tables,Stock,Reports and Users
When a user clicks on the Table category it displays Buttons dynamically created from items stored in the database mysql. For instance this is the result image:

How does one get to develop like that?
Is there a for loop statements that is going to be used?

EDIT

This is how i did it.This is the source code.

```<code>public class OrderController implements Initializable {

    @FXML
    private ListView<Button> listvieww;

    @FXML
    private HBox hboxx;

    List<String> listOfSomething = null;
//@FXML
//    private Pane panedynamic;
    private DBConnection database = new DBConnection();
    private Connection connection;
    private Statement statement;
    private ResultSet resultSet;

    private ObservableList<Button> buttons = FXCollections.observableArrayList();

    /**
     * Initializes the controller class.
     */
    @Override
    public void initialize(URL url, ResourceBundle rb) {
    hboxx.getChildren().add(buttons)
    }

    @FXML
    void acttable(ActionEvent event) {

        // TODO
        String sqlQuery = "SELECT * FROM restauranttables;";
        try {
            connection = database.getConnection();
            statement = connection.createStatement();
            resultSet = statement.executeQuery(sqlQuery);
            while (resultSet.next()) {
                String current = resultSet.getString("tablename");
                ObservableList<String> list = FXCollections.observableArrayList(current);
                Button b = new Button(list.toString());
                buttons.add(b);

            }

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

    }

    @FXML
    void actlogout(ActionEvent event) {

    }

    @FXML
    void actnew(ActionEvent event) {

    }

    @FXML
    void actorder(ActionEvent event) {

    }

    @FXML
    void actreports(ActionEvent event) {

    }

    @FXML
    void actstock(ActionEvent event) {

    }

    @FXML
    void actusers(ActionEvent event) {

    }

}
</code>```

this is how my scene builder looks like

```<code><?xml version="1.0" encoding="UTF-8"?>

<?import com.jfoenix.controls.JFXButton?>
<?import com.jfoenix.controls.JFXTextField?>
<?import javafx.scene.control.Menu?>
<?import javafx.scene.control.MenuBar?>
<?import javafx.scene.control.MenuItem?>
<?import javafx.scene.control.TableColumn?>
<?import javafx.scene.control.TableView?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.ColumnConstraints?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.layout.RowConstraints?>
<?import javafx.scene.layout.StackPane?>

<AnchorPane id="AnchorPane" prefHeight="600.0" prefWidth="1080.0" xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1" fx:controller="controllers.OrderController">
    <children>
        <AnchorPane layoutX="55.0" layoutY="29.0" prefHeight="600.0" prefWidth="1080.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
            <children>
                <TableView layoutX="21.0" layoutY="49.0" prefHeight="386.0" prefWidth="413.0">
                    <columns>
                        <TableColumn prefWidth="122.0" text="Description" />
                        <TableColumn prefWidth="57.0" text="Price" />
                        <TableColumn prefWidth="81.0" text="Sub Total" />
                        <TableColumn prefWidth="96.0" text="Table Id" />
                        <TableColumn prefWidth="57.0" text="Price" />
                    </columns>
                </TableView>
                <JFXTextField layoutX="53.0" layoutY="439.0" prefHeight="37.0" prefWidth="155.0" />
                <JFXTextField layoutX="253.0" layoutY="439.0" prefHeight="37.0" prefWidth="155.0" />
                <GridPane layoutX="63.0" layoutY="503.0" prefHeight="75.0" prefWidth="345.0">
                    <columnConstraints>
                        <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                        <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                    </columnConstraints>
                    <rowConstraints>
                        <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
                    </rowConstraints>
                    <children>
                        <AnchorPane prefHeight="200.0" prefWidth="200.0">
                            <children>
                                <JFXButton layoutX="25.0" layoutY="25.0" onAction="#actorder" prefHeight="75.0" prefWidth="173.0" text="Order" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0" />
                            </children>
                        </AnchorPane>
                        <AnchorPane prefHeight="200.0" prefWidth="200.0" GridPane.columnIndex="1">
                            <children>
                                <JFXButton layoutX="39.0" layoutY="14.0" onAction="#actnew" prefHeight="75.0" prefWidth="172.0" text="New" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0" />
                            </children>
                        </AnchorPane>
                    </children>
                </GridPane>
                <MenuBar layoutX="21.0" layoutY="14.0" prefHeight="29.0" prefWidth="413.0">
                    <menus>
                        <Menu mnemonicParsing="false" text="File">
                            <items>
                                <MenuItem mnemonicParsing="false" text="Close" />
                            </items>
                        </Menu>
                        <Menu mnemonicParsing="false" text="Edit">
                            <items>
                                <MenuItem mnemonicParsing="false" text="Delete" />
                            </items>
                        </Menu>
                        <Menu mnemonicParsing="false" text="Help">
                            <items>
                                <MenuItem mnemonicParsing="false" text="About" />
                            </items>
                        </Menu>
                    </menus>
                </MenuBar>
                <StackPane fx:id="acContent" layoutX="454.0" layoutY="49.0" prefHeight="525.0" prefWidth="605.0">
                    <children>
                        <AnchorPane fx:id="anchora" prefHeight="200.0" prefWidth="200.0">
                           <children>

                               <GridPane fx:id="sasa" layoutX="17.0" layoutY="7.0" prefHeight="90.0" prefWidth="571.0">
                                   <columnConstraints>
                                       <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                                       <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                                       <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                                       <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                                       <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                                   </columnConstraints>
                                   <rowConstraints>
                                       <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
                                   </rowConstraints>
                                   <children>
                                       <AnchorPane prefHeight="200.0" prefWidth="200.0">
                                           <children>
                                               <JFXButton fx:id="table" layoutX="37.0" layoutY="19.0" onAction="#acttable" prefHeight="90.0" prefWidth="135.0" text="TABLE" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0" />
                                           </children>
                                       </AnchorPane>
                                       <AnchorPane prefHeight="200.0" prefWidth="200.0" GridPane.columnIndex="1">
                                           <children>
                                               <JFXButton fx:id="stock" layoutX="43.0" layoutY="32.0" onAction="#actstock" prefHeight="90.0" prefWidth="134.0" text="STOCK" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0" />
                                           </children>
                                       </AnchorPane>
                                       <AnchorPane prefHeight="200.0" prefWidth="200.0" GridPane.columnIndex="2">
                                           <children>
                                               <JFXButton fx:id="reports" layoutX="26.0" layoutY="32.0" onAction="#actreports" prefHeight="90.0" prefWidth="134.0" text="REPORTS" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0" />
                                           </children>
                                       </AnchorPane>
                                       <AnchorPane prefHeight="200.0" prefWidth="200.0" GridPane.columnIndex="3">
                                           <children>
                                               <JFXButton fx:id="users" layoutX="26.0" layoutY="32.0" onAction="#actusers" prefHeight="90.0" prefWidth="134.0" text="USERS" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0" />
                                           </children>
                                       </AnchorPane>
                                       <AnchorPane prefHeight="200.0" prefWidth="200.0" GridPane.columnIndex="4">
                                           <children>
                                               <JFXButton fx:id="logout" layoutX="28.0" layoutY="32.0" onAction="#actlogout" prefHeight="90.0" prefWidth="134.0" text="LOGOUT" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0" />
                                           </children>
                                       </AnchorPane>
                                   </children>
                               </GridPane>
                        <HBox fx:id="hboxx" layoutX="17.0" layoutY="110.0" prefHeight="398.0" prefWidth="571.0" />
                           </children>
                        </AnchorPane>
                    </children>
                </StackPane>
            </children>
        </AnchorPane>
    </children>
</AnchorPane>
</code>```

i would want to align the buttons in a hbox but am getting an error here

```<code>@Override
    public void initialize(URL url, ResourceBundle rb) {
    hboxx.getChildren().add(buttons)
    }
</code>```

Any Help Thank you.

答:
You need a loop for that. Basically you can loop through your items and for each items you create a button and add it to a pane.

```<code>List<Element> databaseItems = getElementFromDataBase();
int i = 0;
int j = 0;
for(Element databaseItem : databaseItems) {
    Button tempButton = new Button(databaseItem.getName());
    tempButton.setOnAction(new MyClickListener()) //handle button click
    gridPane.add(i, j);
    i ++;
    if(i == GridPane.getRowIndex()) {
        j++; // get to the new row.
    }
}
</code>```

this code might not be accurate but it gives a general idea.

Body:
There is this video in youtube https://www.youtube.com/watch?v=Idtm2Y6I23w
Whereby the person has dynamically populated buttons created from the items that are stored in the database.For instance in this picture

It has some categories that includes Tables,Stock,Reports and Users
When a user clicks on the Table category it displays Buttons dynamically created from items stored in the database mysql. For instance this is the result image:

How does one get to develop like that?
Is there a for loop statements that is going to be used?

EDIT

This is how i did it.This is the source code.

public class OrderController implements Initializable {

    @FXML
    private ListView<Button> listvieww;

    @FXML
    private HBox hboxx;

    List<String> listOfSomething = null;
//@FXML
//    private Pane panedynamic;
    private DBConnection database = new DBConnection();
    private Connection connection;
    private Statement statement;
    private ResultSet resultSet;

    private ObservableList<Button> buttons = FXCollections.observableArrayList();

    /**
     * Initializes the controller class.
     */
    @Override
    public void initialize(URL url, ResourceBundle rb) {
    hboxx.getChildren().add(buttons)
    }

    @FXML
    void acttable(ActionEvent event) {

        // TODO
        String sqlQuery = "SELECT * FROM restauranttables;";
        try {
            connection = database.getConnection();
            statement = connection.createStatement();
            resultSet = statement.executeQuery(sqlQuery);
            while (resultSet.next()) {
                String current = resultSet.getString("tablename");
                ObservableList<String> list = FXCollections.observableArrayList(current);
                Button b = new Button(list.toString());
                buttons.add(b);

            }

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

    }

    @FXML
    void actlogout(ActionEvent event) {

    }

    @FXML
    void actnew(ActionEvent event) {

    }

    @FXML
    void actorder(ActionEvent event) {

    }

    @FXML
    void actreports(ActionEvent event) {

    }

    @FXML
    void actstock(ActionEvent event) {

    }

    @FXML
    void actusers(ActionEvent event) {

    }

}

this is how my scene builder looks like

<?xml version="1.0" encoding="UTF-8"?>

<?import com.jfoenix.controls.JFXButton?>
<?import com.jfoenix.controls.JFXTextField?>
<?import javafx.scene.control.Menu?>
<?import javafx.scene.control.MenuBar?>
<?import javafx.scene.control.MenuItem?>
<?import javafx.scene.control.TableColumn?>
<?import javafx.scene.control.TableView?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.ColumnConstraints?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.layout.RowConstraints?>
<?import javafx.scene.layout.StackPane?>

<AnchorPane id="AnchorPane" prefHeight="600.0" prefWidth="1080.0" xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1" fx:controller="controllers.OrderController">
    <children>
        <AnchorPane layoutX="55.0" layoutY="29.0" prefHeight="600.0" prefWidth="1080.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
            <children>
                <TableView layoutX="21.0" layoutY="49.0" prefHeight="386.0" prefWidth="413.0">
                    <columns>
                        <TableColumn prefWidth="122.0" text="Description" />
                        <TableColumn prefWidth="57.0" text="Price" />
                        <TableColumn prefWidth="81.0" text="Sub Total" />
                        <TableColumn prefWidth="96.0" text="Table Id" />
                        <TableColumn prefWidth="57.0" text="Price" />
                    </columns>
                </TableView>
                <JFXTextField layoutX="53.0" layoutY="439.0" prefHeight="37.0" prefWidth="155.0" />
                <JFXTextField layoutX="253.0" layoutY="439.0" prefHeight="37.0" prefWidth="155.0" />
                <GridPane layoutX="63.0" layoutY="503.0" prefHeight="75.0" prefWidth="345.0">
                    <columnConstraints>
                        <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                        <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                    </columnConstraints>
                    <rowConstraints>
                        <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
                    </rowConstraints>
                    <children>
                        <AnchorPane prefHeight="200.0" prefWidth="200.0">
                            <children>
                                <JFXButton layoutX="25.0" layoutY="25.0" onAction="#actorder" prefHeight="75.0" prefWidth="173.0" text="Order" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0" />
                            </children>
                        </AnchorPane>
                        <AnchorPane prefHeight="200.0" prefWidth="200.0" GridPane.columnIndex="1">
                            <children>
                                <JFXButton layoutX="39.0" layoutY="14.0" onAction="#actnew" prefHeight="75.0" prefWidth="172.0" text="New" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0" />
                            </children>
                        </AnchorPane>
                    </children>
                </GridPane>
                <MenuBar layoutX="21.0" layoutY="14.0" prefHeight="29.0" prefWidth="413.0">
                    <menus>
                        <Menu mnemonicParsing="false" text="File">
                            <items>
                                <MenuItem mnemonicParsing="false" text="Close" />
                            </items>
                        </Menu>
                        <Menu mnemonicParsing="false" text="Edit">
                            <items>
                                <MenuItem mnemonicParsing="false" text="Delete" />
                            </items>
                        </Menu>
                        <Menu mnemonicParsing="false" text="Help">
                            <items>
                                <MenuItem mnemonicParsing="false" text="About" />
                            </items>
                        </Menu>
                    </menus>
                </MenuBar>
                <StackPane fx:id="acContent" layoutX="454.0" layoutY="49.0" prefHeight="525.0" prefWidth="605.0">
                    <children>
                        <AnchorPane fx:id="anchora" prefHeight="200.0" prefWidth="200.0">
                           <children>

                               <GridPane fx:id="sasa" layoutX="17.0" layoutY="7.0" prefHeight="90.0" prefWidth="571.0">
                                   <columnConstraints>
                                       <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                                       <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                                       <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                                       <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                                       <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                                   </columnConstraints>
                                   <rowConstraints>
                                       <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
                                   </rowConstraints>
                                   <children>
                                       <AnchorPane prefHeight="200.0" prefWidth="200.0">
                                           <children>
                                               <JFXButton fx:id="table" layoutX="37.0" layoutY="19.0" onAction="#acttable" prefHeight="90.0" prefWidth="135.0" text="TABLE" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0" />
                                           </children>
                                       </AnchorPane>
                                       <AnchorPane prefHeight="200.0" prefWidth="200.0" GridPane.columnIndex="1">
                                           <children>
                                               <JFXButton fx:id="stock" layoutX="43.0" layoutY="32.0" onAction="#actstock" prefHeight="90.0" prefWidth="134.0" text="STOCK" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0" />
                                           </children>
                                       </AnchorPane>
                                       <AnchorPane prefHeight="200.0" prefWidth="200.0" GridPane.columnIndex="2">
                                           <children>
                                               <JFXButton fx:id="reports" layoutX="26.0" layoutY="32.0" onAction="#actreports" prefHeight="90.0" prefWidth="134.0" text="REPORTS" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0" />
                                           </children>
                                       </AnchorPane>
                                       <AnchorPane prefHeight="200.0" prefWidth="200.0" GridPane.columnIndex="3">
                                           <children>
                                               <JFXButton fx:id="users" layoutX="26.0" layoutY="32.0" onAction="#actusers" prefHeight="90.0" prefWidth="134.0" text="USERS" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0" />
                                           </children>
                                       </AnchorPane>
                                       <AnchorPane prefHeight="200.0" prefWidth="200.0" GridPane.columnIndex="4">
                                           <children>
                                               <JFXButton fx:id="logout" layoutX="28.0" layoutY="32.0" onAction="#actlogout" prefHeight="90.0" prefWidth="134.0" text="LOGOUT" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0" />
                                           </children>
                                       </AnchorPane>
                                   </children>
                               </GridPane>
                        <HBox fx:id="hboxx" layoutX="17.0" layoutY="110.0" prefHeight="398.0" prefWidth="571.0" />
                           </children>
                        </AnchorPane>
                    </children>
                </StackPane>
            </children>
        </AnchorPane>
    </children>
</AnchorPane>

i would want to align the buttons in a hbox but am getting an error here

@Override
    public void initialize(URL url, ResourceBundle rb) {
    hboxx.getChildren().add(buttons)
    }

Any Help Thank you.

Body:
You need a loop for that. Basically you can loop through your items and for each items you create a button and add it to a pane.

List<Element> databaseItems = getElementFromDataBase();
int i = 0;
int j = 0;
for(Element databaseItem : databaseItems) {
    Button tempButton = new Button(databaseItem.getName());
    tempButton.setOnAction(new MyClickListener()) //handle button click
    gridPane.add(i, j);
    i ++;
    if(i == GridPane.getRowIndex()) {
        j++; // get to the new row.
    }
}

this code might not be accurate but it gives a general idea.


来源: stackexchange

问:
calculated field using if and or in ms-sql
```<code>IF(
    [dbo.tblx.Category] = 'WS' OR [dbo.tblx.Category] = 'SEM',
    0,
    [dbo.tblx.Tonnes] * [dbo.tblx.Grade] / 1000
)
</code>```

this returns the entire text and not the "calculation"

can someone help me...what am I doing wrong?

i tried

```<code>CASE WHEN dbo.tblx.Category = 'WS' OR dbo.tblx.Category = 'SEM' THEN 0
     ELSE  dbo.tblx.Tonnes * dbo.tblx.Grade / 1000
END AS Metal
</code>```

Do perhaps insert something before "CASE WHEN"? it is not running

答:
Update

```<code>DECLARE @myvar INT;
SET @myvar = CASE WHEN ([dbo.tblx.Category] = WS OR [dbo.tblPTx.Category] = SEM) THEN 0
                  ELSE  [dbo.tblx.Tonnes] * [dbo.tblx.Grade] / 1000
             END
</code>```

ContentLicense: CC BY-SA 3.0

Body:
IF(
    [dbo.tblx.Category] = 'WS' OR [dbo.tblx.Category] = 'SEM',
    0,
    [dbo.tblx.Tonnes] * [dbo.tblx.Grade] / 1000
)

this returns the entire text and not the "calculation"

can someone help me...what am I doing wrong?

i tried

CASE WHEN dbo.tblx.Category = 'WS' OR dbo.tblx.Category = 'SEM' THEN 0
     ELSE  dbo.tblx.Tonnes * dbo.tblx.Grade / 1000
END AS Metal

Do perhaps insert something before "CASE WHEN"? it is not running

Body:
Update

DECLARE @myvar INT;
SET @myvar = CASE WHEN ([dbo.tblx.Category] = WS OR [dbo.tblPTx.Category] = SEM) THEN 0
                  ELSE  [dbo.tblx.Tonnes] * [dbo.tblx.Grade] / 1000
             END


问:
How to identify a country from a normalized phone number?
I have a list of international phone numbers and a List of Country calling codes.

I would like to identify the Country from the numbers but I can't find a fast and elegant way to do it.

Any idea? The only I got is to have an hardcoded check (Eg. "look at the first number, look at the second number: if it's X then check for the third number. If the second number is Y then the Country is Foo", etc.).
I'm using PHP and a DB (MySQL) for the lists, but I think that any pseudocode will help.

答:
You can easily do a simple lookup starting with the first number, then the second, and so on until you find it. This will work correctly because no calling code is a prefix of another code, i.e. the international calling codes form a "prefix code" (the phone system relies on this property).

I'm not good any good at PHP so here is a simple python implementation; hopefully it is easy to follow:

```<code>>>> phone_numbers = ["+12345", "+23456", "+34567", "+45678"]
>>> country_codes = { "+1": "USA", "+234": "Nigeria", "+34" : "Spain" }
>>> for number in phone_numbers:
...     for i in [2, 3, 4]:
...         if number[:i] in country_codes:
...             print country_codes[number[:i]]
...             break
...     else:
...         print "Unknown"
...
USA
Nigeria
Spain
Unknown
</code>```

Essentially you have an associative array between prefixes and countries (which I assume you can easily generate from that Wikipedia article. You try looking up the first digit of the phone number in the associative array. If it's not in the array you try the first two digits, then the first three. If there is no match after three digits then this number doesn't start with a valid international calling code.

Body:
You can easily do a simple lookup starting with the first number, then the second, and so on until you find it. This will work correctly because no calling code is a prefix of another code, i.e. the international calling codes form a "prefix code" (the phone system relies on this property).

I'm not good any good at PHP so here is a simple python implementation; hopefully it is easy to follow:

>>> phone_numbers = ["+12345", "+23456", "+34567", "+45678"]
>>> country_codes = { "+1": "USA", "+234": "Nigeria", "+34" : "Spain" }
>>> for number in phone_numbers:
...     for i in [2, 3, 4]:
...         if number[:i] in country_codes:
...             print country_codes[number[:i]]
...             break
...     else:
...         print "Unknown"
...
USA
Nigeria
Spain
Unknown

Essentially you have an associative array between prefixes and countries (which I assume you can easily generate from that Wikipedia article. You try looking up the first digit of the phone number in the associative array. If it's not in the array you try the first two digits, then the first three. If there is no match after three digits then this number doesn't start with a valid international calling code.

ContentLicense: CC BY-SA 2.5


问:
Navigation between ionic pages 3
I'm having trouble with navCtrl.push. The flow is as follows:

n pages' 1.1, 1.2 and 1.3` I can go back and forth as many times as I want, but when I click the back button I need to return on page 1.

To go to the next page I use the button click event like this:

```<code>(Click) = "quickAccess ('Page1.1')"
</code>```

And to go back I add navPop to my navbar` button.

THE MISTAKE

When I click on the back, you are returning parts for the pastes of pages 1.2, 1.2 and 1.3 if I have navigated 10 times between these pastes it will return the 10 times.

ATTEMPTS

I'm trying to follow the following thinking when I navigate for example from page 1.1 to1.2 I should remove '1.1and so on, but I'm having this problem, how do I do this, already tried to index byView name` but none of them work.

PLEASE NOTE

It is important to know that there are other pages prior to PAGE 1 the flow with problem is only in this case, in the rest everything goes as expected.

答:
I found the problem!

According to this inssue no ionic team:

```<code>https://github.com/ionic-team/ionic/issues/12238
</code>```

An error is occurring in the structure, a solution for installing the fix via npm as reported in inssue:

```<code>npm install ionic-angular @ night
</code>```

So my .remove () works perfectly now.

Title: Navigation between ionic pages 3

Body:
I'm having trouble with navCtrl.push. The flow is as follows:

n pages' 1.1, 1.2 and 1.3` I can go back and forth as many times as I want, but when I click the back button I need to return on page 1.

To go to the next page I use the button click event like this:

(Click) = "quickAccess ('Page1.1')"

And to go back I add navPop to my navbar` button.

THE MISTAKE

When I click on the back, you are returning parts for the pastes of pages 1.2, 1.2 and 1.3 if I have navigated 10 times between these pastes it will return the 10 times.

ATTEMPTS

I'm trying to follow the following thinking when I navigate for example from page 1.1 to1.2 I should remove '1.1and so on, but I'm having this problem, how do I do this, already tried to index byView name` but none of them work.

PLEASE NOTE

It is important to know that there are other pages prior to PAGE 1 the flow with problem is only in this case, in the rest everything goes as expected.

Body:
I found the problem!

According to this inssue no ionic team:

https://github.com/ionic-team/ionic/issues/12238

An error is occurring in the structure, a solution for installing the fix via npm as reported in inssue:

npm install ionic-angular @ night

So my .remove () works perfectly now.


问:
removing and re-populating boostrapTable
I want basically to refresh the data held in a table. First instantiation works just fine, but no luck after removing and re-fetching of the data.

html

```<code><table id="tablePendByOrg" class="table table-bordered table-hover table-condensed table-striped">
                        <thead>
                            <tr>
                                <th data-field="Date">Time</th>
                                <th data-field="Organization">Org</th>
                                <th data-field="f24hs"><24Hs</th>
                                <th data-field="f48Hs"><48Hs</th>
                                <th data-field="f48Hs">>48Hs</th>
                                <th data-field="fTotal">Total</th>
                            </tr>
                        </thead>
                    </table>
</code>```

js to populate after ajax call.

```<code>$('#tablePendByOrg').bootstrapTable({
    data: d.Table
});
</code>```

js to remove data

```<code>$("#tablePendByOrg tbody tr").remove();
</code>```

And after a new call to the ajax code, I get the proper data in d.Table but no tbody are showing on the page, just the framed th that I set from the get go.

答:
As they describe:

```<code>$table = $('#tablePendByOrg');
$table.bootstrapTable('load', data); // removes old data, no need to remove it by yourself
</code>```

also the removal o all items is not to be done as you did:

<s>$("#tablePendByOrg tbody tr").remove();</s>

use:

```<code>$table.bootstrapTable('removeAll');
</code>```

Body:
I want basically to refresh the data held in a table. First instantiation works just fine, but no luck after removing and re-fetching of the data.

html

                                Time
                                Org
                                <24Hs
                                <48Hs
                                >48Hs
                                Total

js to populate after ajax call.

$('#tablePendByOrg').bootstrapTable({
    data: d.Table
});

js to remove data

$("#tablePendByOrg tbody tr").remove();

And after a new call to the ajax code, I get the proper data in d.Table but no tbody are showing on the page, just the framed th that I set from the get go.

Body:
As they describe:

$table = $('#tablePendByOrg');
$table.bootstrapTable('load', data); // removes old data, no need to remove it by yourself

also the removal o all items is not to be done as you did:

<s>$("#tablePendByOrg tbody tr").remove();</s>

use:

$table.bootstrapTable('removeAll');


问:
Exception in thread "main" java.sql.SQLException: Unable to open file
how to Solve this error and made load data query to open my file??

I get java.sql.SQLException: Unable to open file when trying to create statement from file. Code:

```<code>public class LoadData {

  public static void main(String[] args) throws Exception {

  File file=new File("C://Users//suriyan.s//Documents//suriyan//employees.csv");

  String filename = file.getAbsolutePath();

  System.out.println(filename);

  String tablename = "employee";

  Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/college", "root", "");

  // Load the data

  String qry = "LOAD DATA LOCAL INFILE '" + filename + "' INTO TABLE " + tablename + " FIELDS TERMINATED BY ','"
+ " LINES TERMINATED BY '\n';";

  Statement stmt = connection.createStatement();

  stmt.execute(qry);

  }
}
</code>```

答: The problem could be the string query 'qry'. Try removing the semi-colon ; from the end of the string.</p>

Body:
how to Solve this error and made load data query to open my file??

I get java.sql.SQLException: Unable to open file when trying to create statement from file. Code:

public class LoadData {

  public static void main(String[] args) throws Exception {

  File file=new File("C://Users//suriyan.s//Documents//suriyan//employees.csv");

  String filename = file.getAbsolutePath();

  System.out.println(filename);

  String tablename = "employee";

  Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/college", "root", "");

  // Load the data

  String qry = "LOAD DATA LOCAL INFILE '" + filename + "' INTO TABLE " + tablename + " FIELDS TERMINATED BY ','"
+ " LINES TERMINATED BY '\n';";

  Statement stmt = connection.createStatement();

  stmt.execute(qry);

  }
}


问:
PDFMerger with FPDI-PDF-PARSER
FPDI PDF Files merger is being used. However, I ran into the following issue while trying to merge PDF files versions 1.5 and higher. The following was the error I received:

This document (doc.pdf) probably uses a compression technique which is
  not supported by the free parser shipped with FPDI. (See
  https://www.setasign.com/fpdi-pdf-parser for more details)

I proceeded to visit the link, which advised to use the commercial addon fpdi-pdf-parser. This file is already included with the rest of the files. And in the installation steps, it is said that there are no other steps that are needed to be made, but I am still getting the same error.

It is worth noting that I am using the following PDF merger (which, in turn, uses the FPDI lib)

https://github.com/myokyawhtun/PDFMerger/blob/master/PDFMerger.php

I am not sure how I can use this "fpdi-pdf-parser addon", which is advertised to be a solution to my PDF 1.5 issue. What am I missing?

答:
You state that you are using PDFMerger, but looking at the project page shows:

Support of PDF 1.5 and PDF 1.6

FPDF and FPDI libraries replaced by TCPDF with TCPDI extension and parser.

So it would appear that, specifically because they don't support PDF versions >1.4, PDFMerger no longer uses FPDF and FPDI.

To test this I downloaded PDFMerger (note this includes a copy of TCPDF), slightly modified the example code, and ran it with a PDF that is marked as version 1.7:

```<code><?php

include 'PDFMerger.php';

$pdf = new PDFMerger;

$pdf->addPDF('43451941a.pdf', '1'); // page 1 from first file.
$pdf->addPDF('43451941b.pdf', '5'); // page 5 from second file.

$pdf->merge('browser'); // send the file to the browser.
</code>```

The result is that in my web browser I get a PDF file of two pages, as expected.

As far as I can tell FPDF/FPDI is not required at all!

Simply download and use PDFMerger.

ContentLicense: CC BY-SA 4.0

Title: PDFMerger with FPDI-PDF-PARSER

Body:
You state that you are using PDFMerger, but looking at the project page shows:

Support of PDF 1.5 and PDF 1.6

FPDF and FPDI libraries replaced by TCPDF with TCPDI extension and parser.

So it would appear that, specifically because they don't support PDF versions >1.4, PDFMerger no longer uses FPDF and FPDI.

To test this I downloaded PDFMerger (note this includes a copy of TCPDF), slightly modified the example code, and ran it with a PDF that is marked as version 1.7:

<?php

include 'PDFMerger.php';

$pdf = new PDFMerger;

$pdf->addPDF('43451941a.pdf', '1'); // page 1 from first file.
$pdf->addPDF('43451941b.pdf', '5'); // page 5 from second file.

$pdf->merge('browser'); // send the file to the browser.

The result is that in my web browser I get a PDF file of two pages, as expected.

As far as I can tell FPDF/FPDI is not required at all!

Simply download and use PDFMerger.


问:
How to add reverse IP record by using DNSPython
I try to add DNS record by using DNSPython;

it works well when I set dns like this:

```<code>import dns.resolver
import dns.query
import dns.reversename
import dns.update
import dns.rdatatype

update = dns.update.Update('test.com')
update.replace('a', 3600, dns.rdatatype.A, '10.10.10.10')
response = dns.query.tcp(update, '127.0.0.1')
</code>```

However it doesn't work when I set reverse dns by the same way:

```<code>update = dns.update.Update('10.in-addr.arpa')
update.replace('10.10.10.', 3600, dns.rdatatype.PTR, 'a.test.com')
response = dns.query.tcp(update, '127.0.0.1')
</code>```

I want to know how to set reverse dns successfully, Thx~

答:
Encountered this issue myself.

You're missing a dot at the end of you name:

```<code>update.replace('10.10.10', 3600, dns.rdatatype.PTR, 'a.test.com**.**')
</code>```

Body:
I try to add DNS record by using DNSPython;

it works well when I set dns like this:

import dns.resolver
import dns.query
import dns.reversename
import dns.update
import dns.rdatatype

update = dns.update.Update('test.com')
update.replace('a', 3600, dns.rdatatype.A, '10.10.10.10')
response = dns.query.tcp(update, '127.0.0.1')

However it doesn't work when I set reverse dns by the same way:

update = dns.update.Update('10.in-addr.arpa')
update.replace('10.10.10.', 3600, dns.rdatatype.PTR, 'a.test.com')
response = dns.query.tcp(update, '127.0.0.1')

I want to know how to set reverse dns successfully, Thx~

Body:
Encountered this issue myself.

You're missing a dot at the end of you name:

update.replace('10.10.10', 3600, dns.rdatatype.PTR, 'a.test.com**.**')


问:
How to create a byte[] image intent to share with Email
I am trying to create a byte[] image intent to share with the email app on my Xamarin.Android application. So far I have the following:

```<code>public void ShareAsync(byte[] image, string message)
{
    if (string.IsNullOrEmpty(message) || image == null)
        return;

    var sharingIntent = new Intent();
    sharingIntent.SetAction(Intent.ActionSend);
    sharingIntent.SetType("image/*");
    sharingIntent.PutExtra(Intent.ExtraStream, image);
    sharingIntent.AddFlags(ActivityFlags.GrantReadUriPermission);
    Plugin.CurrentActivity.CrossCurrentActivity.Current.Activity.StartActivity(Intent.CreateChooser(sharingIntent, message));
}
</code>```

This pops up the share dialog and I can click the email app but it returns a blank email.

Is it possible to share a byte[] with the email app so that the image appears as part of the body or an attachment?

答:
You can try converting by this

```<code>Bitmap bm = BitmapFactory.decodeFile("/path/to/image.jpg");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
</code>```

bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object

byte[] b = baos.toByteArray();

and convert back to image like this

```<code>Bitmap bmp = intent.getExtras().get("data");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
</code>```

I have't tested it so let me know if it works.

Body:
I am trying to create a byte[] image intent to share with the email app on my Xamarin.Android application. So far I have the following:

public void ShareAsync(byte[] image, string message)
{
    if (string.IsNullOrEmpty(message) || image == null)
        return;

    var sharingIntent = new Intent();
    sharingIntent.SetAction(Intent.ActionSend);
    sharingIntent.SetType("image/*");
    sharingIntent.PutExtra(Intent.ExtraStream, image);
    sharingIntent.AddFlags(ActivityFlags.GrantReadUriPermission);
    Plugin.CurrentActivity.CrossCurrentActivity.Current.Activity.StartActivity(Intent.CreateChooser(sharingIntent, message));
}

This pops up the share dialog and I can click the email app but it returns a blank email.

Is it possible to share a byte[] with the email app so that the image appears as part of the body or an attachment?

Body:
You can try converting by this

Bitmap bm = BitmapFactory.decodeFile("/path/to/image.jpg");
ByteArrayOutputStream baos = new ByteArrayOutputStream();

bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object

byte[] b = baos.toByteArray();

and convert back to image like this

Bitmap bmp = intent.getExtras().get("data");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();

I have't tested it so let me know if it works.


问:
Issue with Xamarin App and Web API Model Binding: Object passed to service is null only on iOS
I have been running into a very strange issue, and I am not even sure if this is an issue with my app or the web service I am calling.

I have a Web API Service with a Post method that accepts a complex parameter (it is my own custom object). In my Xamarin project I have some pretty straightforward code to call this service:

```<code>public async Task SubmitEReport(decimal amount, DateTime receivedDate,
byte[] image)
{
    try
    {
        HttpClient client = new HttpClient();

        var uri = new Uri("https://services.example.com/EPub/api/Expense/");

        var eReport = new eReport()
        {
            UserName = "EMPLOYEE\" + Application.Current.Properties["username"].ToString(),
            Cost = amount,
            ReceivedDate= receivedDate,
            ReceiptImageExtension = "jpg",
            SubmittalDate = DateTime.Now,
            Image = image
        };

        var json = JsonConvert.SerializeObject(eReport );

        var content = new System.Net.Http.StringContent(json, Encoding.UTF8, "application/json");

        content.Headers.Add("authorize-token", Application.Current.Properties["auth-token"] as string);

        HttpResponseMessage response = null;

        response = await client.PostAsync(uri, content);

        var eResult = new EResult()
        {
            Success = response.IsSuccessStatusCode,
            ErrorMessage = response.ReasonPhrase

        };

        return eResult ;
    }
    catch (Exception ex)
    {
        var errorResult = new eResult () { Success = false, ErrorMessage = ex.Message };
        return errorResult;
    }
}
</code>```

The issue that I am having is that, when I test this on an Android the code works as expected: the service is called, the object passed over is not null and has the data in it. In short, the parameter binding works as expected. The same is not so on iOS: when I call the service using the app on an iPhone, I can see that it is reaching the service and the Post method, but the parameter binding is not working correctly as the object I am passing over is always null.

答: The issue is resolved. The problem was actually the size of the request. I discovered this in my Web Api service after examining the contents of the request object, and received an exception that the request length was exceeded. My solution was to increase the value of the property maxrequestlength in the web.config. This still does not explain why the request is so much larger in iOS than Android. Will follow up on this.</p>

Body:
I have been running into a very strange issue, and I am not even sure if this is an issue with my app or the web service I am calling.

I have a Web API Service with a Post method that accepts a complex parameter (it is my own custom object). In my Xamarin project I have some pretty straightforward code to call this service:

public async Task SubmitEReport(decimal amount, DateTime receivedDate,
byte[] image)
{
    try
    {
        HttpClient client = new HttpClient();

        var uri = new Uri("https://services.example.com/EPub/api/Expense/");

        var eReport = new eReport()
        {
            UserName = "EMPLOYEE\" + Application.Current.Properties["username"].ToString(),
            Cost = amount,
            ReceivedDate= receivedDate,
            ReceiptImageExtension = "jpg",
            SubmittalDate = DateTime.Now,
            Image = image
        };

        var json = JsonConvert.SerializeObject(eReport );

        var content = new System.Net.Http.StringContent(json, Encoding.UTF8, "application/json");

        content.Headers.Add("authorize-token", Application.Current.Properties["auth-token"] as string);

        HttpResponseMessage response = null;

        response = await client.PostAsync(uri, content);

        var eResult = new EResult()
        {
            Success = response.IsSuccessStatusCode,
            ErrorMessage = response.ReasonPhrase

        };

        return eResult ;
    }
    catch (Exception ex)
    {
        var errorResult = new eResult () { Success = false, ErrorMessage = ex.Message };
        return errorResult;
    }
}

The issue that I am having is that, when I test this on an Android the code works as expected: the service is called, the object passed over is not null and has the data in it. In short, the parameter binding works as expected. The same is not so on iOS: when I call the service using the app on an iPhone, I can see that it is reaching the service and the Post method, but the parameter binding is not working correctly as the object I am passing over is always null.


问:
How redis work?
I am studying Redis, and I surprise how Redis works. I found that Redis, store recent data in cache in NoSQL format and have their own query for that. But I am curious about the following working:

How data store in persistence database. Do we need to fire same insert query in both the database?

If Redis uses NoSQL database is it compulsory that persistence database we are using is follow NoSQL structure?

How data synchronisation works between Redis database and persistence database?

答: Redis offers persistence. There are several options depending on what exactly do you need. Here is the official documentation.</p>

Title: How redis work?


问:
Send mail when Outlook is not already open
My situation:

I'm trying to send e-mails while Outlook is not open. This code will work if Outlook is running. If Outlook is closed the code will create a non-visible process that you can see running in Task Manager.

The code encounters an error during the .Send. It returns runtime error 287.

From my experience that are certain VBA methods that will only work when the object is either visible or active.

My work around is to use .Display(False) before calling .Send.

After calling .Send it immediately terminates the Outlook process. (Please point me to the right direction why.) Then the e-mail gets stuck in the Outbox.

I have to apply another work around by calling another CreateObject("Outlook.Application") and either looping through the Outbox While Outbox.Items.Count > 0

or

Looping through SyncObjects and manually calling .Start to run Send/Receive on the Outbox.

My question:

Is there a way to directly use the .Send method instead of using work arounds while also not having to open Outlook.

My code:

```<code>Sub emailer()

Dim OutApp As Object
Dim OutMail As Object

Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)

With OutMail
    .to = "f@r.com"
    .CC = ""
    .BCC = ""
    .Subject = "This is the Subject line"
    .Body = "Hi there"
    .Send   'or use .Display
End With

Set OutMail = Nothing
Set OutApp = Nothing

End Sub
</code>```

答:
A workaround for the .send issue with Outlook closing can possibly be resolved by changing the settings for Send/Receive.  Go to File -> Options -> Advanced -> find Send/Receive... and press it.  Under "Setting for group "All Accounts" is a checkbox for Perform an automatic send/receive when exiting. Check this, and it may resolve the "stuck in the outbox issue you are having".

Here is a screenshot:

Give this a try, hopefully it helps.

Body:
My situation:

I'm trying to send e-mails while Outlook is not open. This code will work if Outlook is running. If Outlook is closed the code will create a non-visible process that you can see running in Task Manager.

The code encounters an error during the .Send. It returns runtime error 287.

From my experience that are certain VBA methods that will only work when the object is either visible or active.

My work around is to use .Display(False) before calling .Send.

After calling .Send it immediately terminates the Outlook process. (Please point me to the right direction why.) Then the e-mail gets stuck in the Outbox.

I have to apply another work around by calling another CreateObject("Outlook.Application") and either looping through the Outbox While Outbox.Items.Count > 0

or

Looping through SyncObjects and manually calling .Start to run Send/Receive on the Outbox.

My question:

Is there a way to directly use the .Send method instead of using work arounds while also not having to open Outlook.

My code:

Sub emailer()

Dim OutApp As Object
Dim OutMail As Object

Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)

With OutMail
    .to = "f@r.com"
    .CC = ""
    .BCC = ""
    .Subject = "This is the Subject line"
    .Body = "Hi there"
    .Send   'or use .Display
End With

Set OutMail = Nothing
Set OutApp = Nothing

End Sub


问:
Using data from two separate geoJSON files in D3.js map visualization
I am making an interactive map visualization of the world, where the user should be able to zoom in on a country and then see more details of that country (for example states if the country is the US).

As of now, I have one geoJSON file for the data of the countries in the world and another one for the provinces of China. The problem is that I need to have the China province map placed where China is on the world map. And even though the shape of the Chinese border is the same for the both maps, the scaling is not and it is also a problem with the translation of the China map.

How can I make sure that the map over China gets placed in the same place as China is on the world map?

The end result should be something similar to this: http://techslides.com/demos/d3/us-zoom-county.html

But in that case all the data is in a single geoJSON file, containing both US states and counties for each state.

If there is some way to merge two or more geoJSON files that would be awesome and would probably work in my case.

Any ideas of how to use data from different geoJSON files in the same map visualization?

Thanks in advance!

答:
I managed to solve the problem and it was easier than I thought. The solution was to first calculate the bounding area of china then to draw the map there. Here are some code:

```<code>var projectionChina = d3.geoMercator();
var pathChina = d3.geoPath(projection);

g.append("g")
  .attr("class", "china")
  .attr("width", boundingArea.width)
  .attr("height", boundingArea.height)
  .selectAll("path")
    .data(data.geometries)
  .enter().append("path")
    .attr("d", pathChina);
</code>```

Where boundingArea is the rectangle that encapsulates the Chinese border.

Hope this helps some one with the same problem.

Body:
I managed to solve the problem and it was easier than I thought. The solution was to first calculate the bounding area of china then to draw the map there. Here are some code:

var projectionChina = d3.geoMercator();
var pathChina = d3.geoPath(projection);

g.append("g")
  .attr("class", "china")
  .attr("width", boundingArea.width)
  .attr("height", boundingArea.height)
  .selectAll("path")
    .data(data.geometries)
  .enter().append("path")
    .attr("d", pathChina);

Where boundingArea is the rectangle that encapsulates the Chinese border.

Hope this helps some one with the same problem.


问:
How to add a row to a pandas DataFrame without flattening the MultiIndex
I have trouble with adding a single row to a MultiIndexed DataFrame in an efficient way. By adding the row, the MultiIndex is flattened to a simple Index of Tuples. Strangely this is not a problem for MultiIndexed columns.

System info:

```<code>Python 3.6.1 |Continuum Analytics, Inc.| (default, Mar 22 2017, 19:25:17)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pandas as pd
>>> pd.__version__
'0.19.2'
</code>```

Example data: A DataFrame with both MultiIndex rows and columns

```<code>import numpy as np
import pandas as pd

index = pd.MultiIndex(levels=[['bar', 'foo'], ['one', 'two']],
                      labels=[[0, 0, 1, 1], [0, 1, 0, 1]],
                      names=['row_0', 'row_1'])
columns = pd.MultiIndex(levels=[['dull', 'shiny'], ['a', 'b']],
                      labels=[[0, 0, 1, 1], [0, 1, 0, 1]],
                      names=['col_0', 'col_1'])
df = pd.DataFrame(np.ones((4,4)),columns=columns, index=index)

print(df)

    col_0       dull      shiny
col_1          a    b     a    b
row_0 row_1
bar   one    1.0  1.0   1.0  1.0
      two    1.0  1.0   1.0  1.0
foo   one    1.0  1.0   1.0  1.0
      two    1.0  1.0   1.0  1.0
</code>```

It's no problem to add an additional column to the DataFrame:

```<code>df['last_col'] = 42 #define a new column and assign a value

print(df)

col_0       dull      shiny      last_col
col_1          a    b     a    b
row_0 row_1
bar   one    1.0  1.0   1.0  1.0       42
      two    1.0  1.0   1.0  1.0       42
foo   one    1.0  1.0   1.0  1.0       42
      two    1.0  1.0   1.0  1.0       42
</code>```

However, if i do the same for adding a row (by using loc), the MultiIndex is flattened to a
simple Index of Tuples:

```<code>df.loc['last_row'] = 43  #define a new row and assign a value

print(df)

col_0       dull       shiny       last_col
col_1          a     b     a     b
(bar, one)   1.0   1.0   1.0   1.0       42
(bar, two)   1.0   1.0   1.0   1.0       42
(foo, one)   1.0   1.0   1.0   1.0       42
(foo, two)   1.0   1.0   1.0   1.0       42
last_row    43.0  43.0  43.0  43.0       43
</code>```

Does anyone has an idea how to add a row without flattening the index in a both simple and efficient way? Thank you very much!!

答:
I think you need tuple with define both values of MultiIndex:

```<code>df.loc[('last_row', 'a'), :] = 43
print(df)
col_0           dull       shiny
col_1              a     b     a     b
row_0    row_1
bar      one     1.0   1.0   1.0   1.0
         two     1.0   1.0   1.0   1.0
foo      one     1.0   1.0   1.0   1.0
         two     1.0   1.0   1.0   1.0
last_row a      43.0  43.0  43.0  43.0
</code>```

For column it works similar:

```<code>df[('last_col', 'a')] = 43
print(df)
col_0       dull      shiny      last_col
col_1          a    b     a    b        a
row_0 row_1
bar   one    1.0  1.0   1.0  1.0       43
      two    1.0  1.0   1.0  1.0       43
foo   one    1.0  1.0   1.0  1.0       43
      two    1.0  1.0   1.0  1.0       43
</code>```

EDIT:

It seems you need define columns names, if need all use ::

```<code>df.loc['last_row',:] = 43
print(df)
col_0           dull       shiny
col_1              a     b     a     b
row_0    row_1
bar      one     1.0   1.0   1.0   1.0
         two     1.0   1.0   1.0   1.0
foo      one     1.0   1.0   1.0   1.0
         two     1.0   1.0   1.0   1.0
last_row        43.0  43.0  43.0  43.0
</code>```

If level is not defined is added empty string:

```<code>print(df.index)
MultiIndex(levels=[['bar', 'foo', 'last_row'], ['one', 'two', '']],
           labels=[[0, 0, 1, 1, 2], [0, 1, 0, 1, 2]],
           names=['row_0', 'row_1'])
</code>```

```<code>df.loc['last_row','dull'] = 43
print(df)
col_0           dull       shiny
col_1              a     b     a    b
row_0    row_1
bar      one     1.0   1.0   1.0  1.0
         two     1.0   1.0   1.0  1.0
foo      one     1.0   1.0   1.0  1.0
         two     1.0   1.0   1.0  1.0
last_row        43.0  43.0   NaN  NaN
</code>```

```<code>df.loc['last_row', ('dull', 'a')] = 43
print(df)
col_0           dull      shiny
col_1              a    b     a    b
row_0    row_1
bar      one     1.0  1.0   1.0  1.0
         two     1.0  1.0   1.0  1.0
foo      one     1.0  1.0   1.0  1.0
         two     1.0  1.0   1.0  1.0
last_row        43.0  NaN   NaN  NaN
</code>```

Body:
I have trouble with adding a single row to a MultiIndexed DataFrame in an efficient way. By adding the row, the MultiIndex is flattened to a simple Index of Tuples. Strangely this is not a problem for MultiIndexed columns.

System info:

Python 3.6.1 |Continuum Analytics, Inc.| (default, Mar 22 2017, 19:25:17)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pandas as pd
>>> pd.__version__
'0.19.2'

Example data: A DataFrame with both MultiIndex rows and columns

import numpy as np
import pandas as pd

index = pd.MultiIndex(levels=[['bar', 'foo'], ['one', 'two']],
                      labels=[[0, 0, 1, 1], [0, 1, 0, 1]],
                      names=['row_0', 'row_1'])
columns = pd.MultiIndex(levels=[['dull', 'shiny'], ['a', 'b']],
                      labels=[[0, 0, 1, 1], [0, 1, 0, 1]],
                      names=['col_0', 'col_1'])
df = pd.DataFrame(np.ones((4,4)),columns=columns, index=index)

print(df)

    col_0       dull      shiny
col_1          a    b     a    b
row_0 row_1
bar   one    1.0  1.0   1.0  1.0
      two    1.0  1.0   1.0  1.0
foo   one    1.0  1.0   1.0  1.0
      two    1.0  1.0   1.0  1.0

It's no problem to add an additional column to the DataFrame:

df['last_col'] = 42 #define a new column and assign a value

print(df)

col_0       dull      shiny      last_col
col_1          a    b     a    b
row_0 row_1
bar   one    1.0  1.0   1.0  1.0       42
      two    1.0  1.0   1.0  1.0       42
foo   one    1.0  1.0   1.0  1.0       42
      two    1.0  1.0   1.0  1.0       42

However, if i do the same for adding a row (by using loc), the MultiIndex is flattened to a
simple Index of Tuples:

df.loc['last_row'] = 43  #define a new row and assign a value

print(df)

col_0       dull       shiny       last_col
col_1          a     b     a     b
(bar, one)   1.0   1.0   1.0   1.0       42
(bar, two)   1.0   1.0   1.0   1.0       42
(foo, one)   1.0   1.0   1.0   1.0       42
(foo, two)   1.0   1.0   1.0   1.0       42
last_row    43.0  43.0  43.0  43.0       43

Does anyone has an idea how to add a row without flattening the index in a both simple and efficient way? Thank you very much!!

Body:
I think you need tuple with define both values of MultiIndex:

df.loc[('last_row', 'a'), :] = 43
print(df)
col_0           dull       shiny
col_1              a     b     a     b
row_0    row_1
bar      one     1.0   1.0   1.0   1.0
         two     1.0   1.0   1.0   1.0
foo      one     1.0   1.0   1.0   1.0
         two     1.0   1.0   1.0   1.0
last_row a      43.0  43.0  43.0  43.0

For column it works similar:

df[('last_col', 'a')] = 43
print(df)
col_0       dull      shiny      last_col
col_1          a    b     a    b        a
row_0 row_1
bar   one    1.0  1.0   1.0  1.0       43
      two    1.0  1.0   1.0  1.0       43
foo   one    1.0  1.0   1.0  1.0       43
      two    1.0  1.0   1.0  1.0       43

EDIT:

It seems you need define columns names, if need all use ::

df.loc['last_row',:] = 43
print(df)
col_0           dull       shiny
col_1              a     b     a     b
row_0    row_1
bar      one     1.0   1.0   1.0   1.0
         two     1.0   1.0   1.0   1.0
foo      one     1.0   1.0   1.0   1.0
         two     1.0   1.0   1.0   1.0
last_row        43.0  43.0  43.0  43.0

If level is not defined is added empty string:

print(df.index)
MultiIndex(levels=[['bar', 'foo', 'last_row'], ['one', 'two', '']],
           labels=[[0, 0, 1, 1, 2], [0, 1, 0, 1, 2]],
           names=['row_0', 'row_1'])

df.loc['last_row','dull'] = 43
print(df)
col_0           dull       shiny
col_1              a     b     a    b
row_0    row_1
bar      one     1.0   1.0   1.0  1.0
         two     1.0   1.0   1.0  1.0
foo      one     1.0   1.0   1.0  1.0
         two     1.0   1.0   1.0  1.0
last_row        43.0  43.0   NaN  NaN

df.loc['last_row', ('dull', 'a')] = 43
print(df)
col_0           dull      shiny
col_1              a    b     a    b
row_0    row_1
bar      one     1.0  1.0   1.0  1.0
         two     1.0  1.0   1.0  1.0
foo      one     1.0  1.0   1.0  1.0
         two     1.0  1.0   1.0  1.0
last_row        43.0  NaN   NaN  NaN


问:
How does evaluateJavascript work?
I'm trying to use the new evaluateJavascript method in Android 4.4, but all I ever get back is a null result:

```<code>webView1.evaluateJavascript("return \"test\";", new ValueCallback<String>() {
    @Override
    public void onReceiveValue(String s) {
        Log.d("LogName", s); // Log is written, but s is always null
    }
});
</code>```

How do I return a result to this method?

Update: Little bit more info:

I have the INTERNET permission set

I have setJavascriptEnabled(true);

Tried apostrophe string: return 'test';,

Tried JS object: return { test: 'this' }

console.log('test'); is being executed fine.

Set targetSdkVersion to 19 as per: If your app uses WebView

Devices: Both Nexus 7 and Nexus 5 (Stock)

答:
To summarize the answer of @GauntFace and provide an alternative solution without using JSON parser:

If your JS function returns just a String and you're wondering about why the string is mangled in Java, it's because it's JSON-escaped.

```<code>mWebView.evaluateJavascript("(function() { return 'Earvin \"Magic\" Johnson'; })();", new ValueCallback<String>() {
    @Override
    public void onReceiveValue(String s) {
        Log.d("LogName", s);
        // expected: s == Earvin "Magic" Johnson
        // actual:   s == "Earvin \"Magic\" Johnson"
    }
});
</code>```

(note that onReceiveValue always provides a String while JS function may return a null, a Number literal etc.)

To get the string value the same as in JS, if you're 100% sure you're expecting a proper String returned, you'd need to JSON-unescape it, for example like that:

```<code>String unescaped = s.substring(1, s.length() - 1)  // remove wrapping quotes
                     .replace("\\\\", "\\")        // unescape \\ -> \
                     .replace("\\\"", "\"");       // unescape \" -> "
</code>```

However, note that s might be a string "null" if JS returns proper null, so you obviously need to check that as the very first step.

```<code>if ("null".equals(s)) {
   ...
} else {
   // unescape JSON
}
</code>```

Title: How does evaluateJavascript work?

Body:
I'm trying to use the new evaluateJavascript method in Android 4.4, but all I ever get back is a null result:

webView1.evaluateJavascript("return \"test\";", new ValueCallback<String>() {
    @Override
    public void onReceiveValue(String s) {
        Log.d("LogName", s); // Log is written, but s is always null
    }
});

How do I return a result to this method?

Update: Little bit more info:

I have the INTERNET permission set

I have setJavascriptEnabled(true);

Tried apostrophe string: return 'test';,

Tried JS object: return { test: 'this' }

console.log('test'); is being executed fine.

Set targetSdkVersion to 19 as per: If your app uses WebView

Devices: Both Nexus 7 and Nexus 5 (Stock)

Body:
To summarize the answer of @GauntFace and provide an alternative solution without using JSON parser:

If your JS function returns just a String and you're wondering about why the string is mangled in Java, it's because it's JSON-escaped.

mWebView.evaluateJavascript("(function() { return 'Earvin \"Magic\" Johnson'; })();", new ValueCallback<String>() {
    @Override
    public void onReceiveValue(String s) {
        Log.d("LogName", s);
        // expected: s == Earvin "Magic" Johnson
        // actual:   s == "Earvin \"Magic\" Johnson"
    }
});

(note that onReceiveValue always provides a String while JS function may return a null, a Number literal etc.)

To get the string value the same as in JS, if you're 100% sure you're expecting a proper String returned, you'd need to JSON-unescape it, for example like that:

String unescaped = s.substring(1, s.length() - 1)  // remove wrapping quotes
                     .replace("\\\\", "\\")        // unescape \\ -> \
                     .replace("\\\"", "\"");       // unescape \" -> "

However, note that s might be a string "null" if JS returns proper null, so you obviously need to check that as the very first step.

if ("null".equals(s)) {
   ...
} else {
   // unescape JSON
}


问:
Generate classes with jaxb2-maven-plugin from WSDL
I am having trouble configuring the jaxb2-maven-plugin to generate Java classes from a WSDL and multiple XSD files that all exist in the same standard directory src/main/xsd.

how to use jaxb2 maven plugin with inline XSD? is related only in that the answers correctly suggest using the wsdl parameter in the plugin config but that question is really concerned with inline XSDs and my XSDs are external.

The plugin goal parameters are listed here.

My plugin configuration is:

```<code><plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>jaxb2-maven-plugin</artifactId>
    <version>1.5</version>
    <executions>
        <execution>
            <id>xjc</id>
            <goals>
                <goal>xjc</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <packageName>com.x.y.model</packageName>
        <wsdl>true</wsdl>
    </configuration>
</plugin>
</code>```

I am testing this with mvn -X clean jaxb2:xjc but the plugin is ignoring the .wsdl as seen in the debug output

```<code>[DEBUG] accept false for file c:\projects\foo\src\main\xsd\service.wsdl
[DEBUG] accept true for file c:\projects\foo\src\main\xsd\datatypes.xsd
[DEBUG] accept true for file c:\projects\foo\src\main\xsd\more-datatypes.xsd
</code>```

答:
You can use the follows code in the configuration:</p>

```<code>              <configuration>
                    <!-- Package to store the generated file -->
                    <packageName>com.example.demo.wsdl</packageName>
                    <!-- Treat the input as WSDL -->
                    <wsdl>true</wsdl>
                    <!-- Input is not XML schema -->
                    <xmlschema>false</xmlschema>
                    <!-- The WSDL file that you saved earlier -->
                    <schemaFiles>horarios.wsdl</schemaFiles>
                    <!-- The location of the WSDL file -->
                    <schemaDirectory>${project.basedir}/src/main/resources</schemaDirectory>
                    <!-- The output directory to store the generated Java files -->
                    <outputDirectory>${project.basedir}/src/main/java</outputDirectory>
                    <!-- Don't clear output directory on each run -->
                    <clearOutputDir>false</clearOutputDir>
                </configuration>
</code>```

Body:
I am having trouble configuring the jaxb2-maven-plugin to generate Java classes from a WSDL and multiple XSD files that all exist in the same standard directory src/main/xsd.

how to use jaxb2 maven plugin with inline XSD? is related only in that the answers correctly suggest using the wsdl parameter in the plugin config but that question is really concerned with inline XSDs and my XSDs are external.

The plugin goal parameters are listed here.

My plugin configuration is:

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>jaxb2-maven-plugin</artifactId>
    <version>1.5</version>
    <executions>
        <execution>
            <id>xjc</id>
            <goals>
                <goal>xjc</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <packageName>com.x.y.model</packageName>
        <wsdl>true</wsdl>
    </configuration>
</plugin>

I am testing this with mvn -X clean jaxb2:xjc but the plugin is ignoring the .wsdl as seen in the debug output

[DEBUG] accept false for file c:\projects\foo\src\main\xsd\service.wsdl
[DEBUG] accept true for file c:\projects\foo\src\main\xsd\datatypes.xsd
[DEBUG] accept true for file c:\projects\foo\src\main\xsd\more-datatypes.xsd

Body:
You can use the follows code in the configuration:

              <configuration>
                    <!-- Package to store the generated file -->
                    <packageName>com.example.demo.wsdl</packageName>
                    <!-- Treat the input as WSDL -->
                    <wsdl>true</wsdl>
                    <!-- Input is not XML schema -->
                    <xmlschema>false</xmlschema>
                    <!-- The WSDL file that you saved earlier -->
                    <schemaFiles>horarios.wsdl</schemaFiles>
                    <!-- The location of the WSDL file -->
                    <schemaDirectory>${project.basedir}/src/main/resources</schemaDirectory>
                    <!-- The output directory to store the generated Java files -->
                    <outputDirectory>${project.basedir}/src/main/java</outputDirectory>
                    <!-- Don't clear output directory on each run -->
                    <clearOutputDir>false</clearOutputDir>
                </configuration>


问:
Sorting data using array
This is my components.ts.
I want to write a fuction that sorts array by counts and i will use the sorted array datas in html to create a chart.</p>

```<code>import { Component } from '@angular/core';
@Component({
  selector: 'dashboard',
  styleUrls: ['./dashboard.scss'],
  templateUrl: './dashboard.html',
})
export class Dashboard {
  private data = [];
  constructor() {
    this.data = [{
      'maxTime': 30041,
      'minTime': 6453,
      'avgTime': 18949,
      'count': 4,
      'requestRouteTemplate': 'api/GetUserPostponesCountReport',
      'requestMethod': 'POST',
    },
  ...
  }
]
</code>```

答:
Implement this in your dashboard.html file where you want to show data order by count

Like this way:

```<code><tr  *ngFor="#friend in friends| orderBy : ['count']"">
      <td>{{friend.name}}</td>
      <td>{{friend.phone}}</td>
      <td>{{friend.count}}</td>
</tr>
</code>```

Title: Sorting data using array

Body:
This is my components.ts.
I want to write a fuction that sorts array by counts and i will use the sorted array datas in html to create a chart.

import { Component } from '@angular/core';
@Component({
  selector: 'dashboard',
  styleUrls: ['./dashboard.scss'],
  templateUrl: './dashboard.html',
})
export class Dashboard {
  private data = [];
  constructor() {
    this.data = [{
      'maxTime': 30041,
      'minTime': 6453,
      'avgTime': 18949,
      'count': 4,
      'requestRouteTemplate': 'api/GetUserPostponesCountReport',
      'requestMethod': 'POST',
    },
  ...
  }
]

Body:
Implement this in your dashboard.html file where you want to show data order by count

Like this way:

<tr  *ngFor="#friend in friends| orderBy : ['count']"">
      <td>{{friend.name}}</td>
      <td>{{friend.phone}}</td>
      <td>{{friend.count}}</td>
</tr>


问:
Performing migrations with multiple databases in Django
I have 2 databases in my Projects with multiple apps. All apps except for one are using default db, the other one has a separate db. After I ran makemigrations and ./manage.py migrate --database=separate_db_name I still have unapplied migration pending for default database.

The question is how can I make this migration only visible for my separate app and not others(that use default db). Thanks

Here is my router

```<code>class S3DatabaseRouter(object):
"""
Determine how to route calls for s3web_upload_dev database
"""

def db_for_read(self, model, **hints):
    """
    Attempts to read s3web_upload models to go to s3web_upload_dev
    """
    if model._meta.app_label == 's3web_upload':
        return 's3web_upload_dev'
    return None

def db_for_write(self, model, **hints):
    """
    Attempts to write s3web_upload models to go to s3web_upload_dev
    """
    if model._meta.app_label == 's3web_upload':
        return 's3web_upload_dev'
    return None

def allow_migrate(self, db, app_label, model_name=None, **hints):
    """
    Make sure the s3web_upload app only appears in the 's3web_upload_dev' database
    """
    if app_label == 's3web_upload':
        return db == 's3web_upload_dev'
    return None
</code>```

答:
For the app that uses default db also need to be routed in the router class, Try the following code it should work.  </p>

```<code>class S3DatabaseRouter(object):
    """
Determine how to route calls for s3web_upload_dev database
"""
def db_for_read(self, model, **hints):
    """
    Attempts to read s3web_upload models to go to s3web_upload_dev
    """
    if model._meta.app_label == 's3web_upload':
        return 's3web_upload_dev'
    if app_label == 'default': # if you using custome applable use it instead of 'default'
        return 'default' # it should be the db name from settings file
    return None

def db_for_write(self, model, **hints):
    """
    Attempts to write s3web_upload models to go to s3web_upload_dev
    """
    if model._meta.app_label == 's3web_upload':
        return 's3web_upload_dev'
    if app_label == 'default':
        return 'default'
    return None

def allow_migrate(self, db, app_label, model_name=None, **hints):
    """
    Make sure the s3web_upload app only appears in the 's3web_upload_dev' database
    """
    if app_label == 's3web_upload':
        return db == 's3web_upload_dev'

    if app_label == 'default':
        return db == 'default'
    return None
</code>```

Body:
I have 2 databases in my Projects with multiple apps. All apps except for one are using default db, the other one has a separate db. After I ran makemigrations and ./manage.py migrate --database=separate_db_name I still have unapplied migration pending for default database.

The question is how can I make this migration only visible for my separate app and not others(that use default db). Thanks

Here is my router

class S3DatabaseRouter(object):
"""
Determine how to route calls for s3web_upload_dev database
"""

def db_for_read(self, model, **hints):
    """
    Attempts to read s3web_upload models to go to s3web_upload_dev
    """
    if model._meta.app_label == 's3web_upload':
        return 's3web_upload_dev'
    return None

def db_for_write(self, model, **hints):
    """
    Attempts to write s3web_upload models to go to s3web_upload_dev
    """
    if model._meta.app_label == 's3web_upload':
        return 's3web_upload_dev'
    return None

def allow_migrate(self, db, app_label, model_name=None, **hints):
    """
    Make sure the s3web_upload app only appears in the 's3web_upload_dev' database
    """
    if app_label == 's3web_upload':
        return db == 's3web_upload_dev'
    return None

Body:
For the app that uses default db also need to be routed in the router class, Try the following code it should work.

class S3DatabaseRouter(object):
    """
Determine how to route calls for s3web_upload_dev database
"""
def db_for_read(self, model, **hints):
    """
    Attempts to read s3web_upload models to go to s3web_upload_dev
    """
    if model._meta.app_label == 's3web_upload':
        return 's3web_upload_dev'
    if app_label == 'default': # if you using custome applable use it instead of 'default'
        return 'default' # it should be the db name from settings file
    return None

def db_for_write(self, model, **hints):
    """
    Attempts to write s3web_upload models to go to s3web_upload_dev
    """
    if model._meta.app_label == 's3web_upload':
        return 's3web_upload_dev'
    if app_label == 'default':
        return 'default'
    return None

def allow_migrate(self, db, app_label, model_name=None, **hints):
    """
    Make sure the s3web_upload app only appears in the 's3web_upload_dev' database
    """
    if app_label == 's3web_upload':
        return db == 's3web_upload_dev'

    if app_label == 'default':
        return db == 'default'
    return None


问:
css module classes not there in production
I've been using css modules with sass in a react library that I want to be consumed by other libraries.

I have the following code for a component:

```<code>import React, { Component } from 'react';
import styles from './FormInput.scss';
import cs from 'classnames';
import { Input, Label } from '../..';

export const FormInput = ({ invalid, required }) =>
    <div
      className={styles['form-input']}
    >
      <Label htmlFor={this.id} invalid={invalid} required={required}>
        {label}
      </Label>
    </div>
</code>```

In development the css module classes are there in the rendered markup:

```<code><div class="form-group FormInput__form-input___2PK4N">
  <label for="ctrl1" class="">Form Input</label>
</div>
</code>```

But when I import the library, they are not there:

```<code><div class="form-group">
  <label for="ctrl1" class="">label</label>
</div>
</code>```

If I log the styles variable from import styles from './FormInput.scss';

It is /static/media/Banner.ee4182d1.scss which seems wrong.

I am using webpack and in my webpack.dev.config.js my loader looks like this:

```<code>  {
    test: /\.css$/,
    exclude: /node_modules/,
    use: ExtractTextPlugin.extract({
      fallback: 'style-loader',
      // Could also be write as follow:
      // use: 'css-loader?modules&localIdentName=[name]__[local]___[hash:base64:5]!postcss-loader'
      use: [
        {
          loader: 'css-loader',
          query: {
            modules: true,
            localIdentName: '[name]__[local]___[hash:base64:5]'
          }
        },
        'postcss-loader'
      ]
    })
  },
  {
    test: /\.scss$/,
    exclude: /node_modules/,
    use: ExtractTextPlugin.extract({
      fallback: 'style-loader',

      // Could also be write as follow:
      // use: 'css-loader?modules&importLoader=2&sourceMap&localIdentName=[name]__[local]___[hash:base64:5]!sass-loader'
      use: [
        {
          loader: 'css-loader',
          query: {
            modules: true,
            sourceMap: true,
            importLoaders: 2,
            localIdentName: '[name]__[local]___[hash:base64:5]'
          }
        },
        'sass-loader'
      ]
    })
  }
</code>```

And in webpack.prod.config.js looks like this:

```<code>  {
    test: /\.css$/,
    loader: ExtractTextPlugin.extract(
      Object.assign(
        {
          fallback: require.resolve('style-loader'),
          use: [
            {
              loader: require.resolve('css-loader'),
              options: {
                importLoaders: 1,
                minimize: true,
                sourceMap: true
              }
            },
            {
              loader: require.resolve('postcss-loader'),
              options: {
                ident: 'postcss', // https://webpack.js.org/guides/migrating/#complex-options
                plugins: () => [
                  require('postcss-flexbugs-fixes'),
                  autoprefixer({
                    browsers: [
                      '>1%',
                      'last 4 versions',
                      'Firefox ESR',
                      'not ie < 9' // React doesn't support IE8 anyway
                    ],
                    flexbox: 'no-2009'
                  })
                ]
              }
            }
          ]
        },
        extractTextPluginOptions
      )
    )
    // Note: this won't work without `new ExtractTextPlugin()` in `plugins`.
  },
  {
    test:/\.scss$/,
    use:ExtractTextPlugin.extract({
      fallback: 'style-loader',
      use: [
        {
          loader:'css-loader',
          options:{
            modules: true,
            importLoaders: 1,
            minimize: true,
            sourceMap: true
          }
        },
        {
          loader:  'sass-loader',
        },
        {
          loader:  'postcss-loader',
          options:{
            plugins:function(){
              return [autoprefixer]
            }
          }
        }
      ]
    })
  }
</code>```

I can see that there are scsss files generated as part of the output but why have the classes been stripped?

答:
You dont have modules enabled in your prod css-loader

```<code>        {
          loader: require.resolve('css-loader'),
          options: {
            importLoaders: 1,
            minimize: true,
            sourceMap: true,
            modules: true // NEED TO ADD THIS
          }
        },
</code>```

Body:
I've been using css modules with sass in a react library that I want to be consumed by other libraries.

I have the following code for a component:

import React, { Component } from 'react';
import styles from './FormInput.scss';
import cs from 'classnames';
import { Input, Label } from '../..';

export const FormInput = ({ invalid, required }) =>

        {label}

In development the css module classes are there in the rendered markup:

  Form Input

But when I import the library, they are not there:

  label

If I log the styles variable from import styles from './FormInput.scss';

It is /static/media/Banner.ee4182d1.scss which seems wrong.

I am using webpack and in my webpack.dev.config.js my loader looks like this:

  {
    test: /\.css$/,
    exclude: /node_modules/,
    use: ExtractTextPlugin.extract({
      fallback: 'style-loader',
      // Could also be write as follow:
      // use: 'css-loader?modules&localIdentName=[name]__[local]___[hash:base64:5]!postcss-loader'
      use: [
        {
          loader: 'css-loader',
          query: {
            modules: true,
            localIdentName: '[name]__[local]___[hash:base64:5]'
          }
        },
        'postcss-loader'
      ]
    })
  },
  {
    test: /\.scss$/,
    exclude: /node_modules/,
    use: ExtractTextPlugin.extract({
      fallback: 'style-loader',

      // Could also be write as follow:
      // use: 'css-loader?modules&importLoader=2&sourceMap&localIdentName=[name]__[local]___[hash:base64:5]!sass-loader'
      use: [
        {
          loader: 'css-loader',
          query: {
            modules: true,
            sourceMap: true,
            importLoaders: 2,
            localIdentName: '[name]__[local]___[hash:base64:5]'
          }
        },
        'sass-loader'
      ]
    })
  }

And in webpack.prod.config.js looks like this:

  {
    test: /\.css$/,
    loader: ExtractTextPlugin.extract(
      Object.assign(
        {
          fallback: require.resolve('style-loader'),
          use: [
            {
              loader: require.resolve('css-loader'),
              options: {
                importLoaders: 1,
                minimize: true,
                sourceMap: true
              }
            },
            {
              loader: require.resolve('postcss-loader'),
              options: {
                ident: 'postcss', // https://webpack.js.org/guides/migrating/#complex-options
                plugins: () => [
                  require('postcss-flexbugs-fixes'),
                  autoprefixer({
                    browsers: [
                      '>1%',
                      'last 4 versions',
                      'Firefox ESR',
                      'not ie < 9' // React doesn't support IE8 anyway
                    ],
                    flexbox: 'no-2009'
                  })
                ]
              }
            }
          ]
        },
        extractTextPluginOptions
      )
    )
    // Note: this won't work without `new ExtractTextPlugin()` in `plugins`.
  },
  {
    test:/\.scss$/,
    use:ExtractTextPlugin.extract({
      fallback: 'style-loader',
      use: [
        {
          loader:'css-loader',
          options:{
            modules: true,
            importLoaders: 1,
            minimize: true,
            sourceMap: true
          }
        },
        {
          loader:  'sass-loader',
        },
        {
          loader:  'postcss-loader',
          options:{
            plugins:function(){
              return [autoprefixer]
            }
          }
        }
      ]
    })
  }

I can see that there are scsss files generated as part of the output but why have the classes been stripped?

Body:
You dont have modules enabled in your prod css-loader

        {
          loader: require.resolve('css-loader'),
          options: {
            importLoaders: 1,
            minimize: true,
            sourceMap: true,
            modules: true // NEED TO ADD THIS
          }
        },


问:
Cast List<int> to List<string> in .NET 2.0
Can you cast a List<int> to List<string> somehow?

I know I could loop through and .ToString() the thing, but a cast would be awesome.

I'm in C# 2.0 (so no LINQ).

答:
You have to build a new list.  The underlying bit representations of List<int> and List<string> are completely incompatible -- on a 64-bit platform, for instance, the individual members aren't even the same size.

It is theoretically possible to treat a List<string> as a List<object> -- this gets you into the exciting worlds of covariance and contravariance, and is not currently supported by C# or VB.NET.

OwnerDisplayName: lomaxx

OwnerDisplayName: Curt Hagenlocher


问:
What do you call this functional language feature?
ok, embarrassing enough, I posted code that I need explained. Specifically, it first chains absolute value and subtraction together, then tacks on a sort, all the while not having to mention parameters and arguments at all, because of the presense of "adverbs" that can join these functions "verbs"

What (non-APL-type) languages support this kind of no-arguments function composition (I have the vague idea it ties in strongly to the concepts of monad/dyad and rank, but its hard to get a particularly easy-to-understand picture just from reading Wikipedia) and what do I call this concept?

答:
This is similar to pointfree style; this works though composition and currying. Functional languages such as Haskell and ML use this.

Concatenative programming languages like Joy, Factor, and Cat also have these "adverbs."

OwnerDisplayName: Jimmy

OwnerDisplayName: Doug Currie

LastEditorDisplayName: Doug Currie


问:
Creating a DataFrame from Row results in 'infer schema issue'
When I began learning PySpark, I used a list to create a dataframe. Now that inferring the schema from list has been deprecated, I got a warning and it suggested me to use pyspark.sql.Row instead. However, when I try to create one using Row, I get infer schema issue. This is my code:

>>> row = Row(name='Severin', age=33)
>>> df = spark.createDataFrame(row)
```

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

```Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/spark2-client/python/pyspark/sql/session.py", line 526, in createDataFrame
    rdd, schema = self._createFromLocal(map(prepare, data), schema)
  File "/spark2-client/python/pyspark/sql/session.py", line 390, in _createFromLocal
    struct = self._inferSchemaFromList(data)
  File "/spark2-client/python/pyspark/sql/session.py", line 322, in _inferSchemaFromList
    schema = reduce(_merge_type, map(_infer_schema, data))
  File "/spark2-client/python/pyspark/sql/types.py", line 992, in _infer_schema
    raise TypeError("Can not infer schema for type: %s" % type(row))
TypeError: Can not infer schema for type: <type 'int'>
```

<p>So I created a schema</p>

<pre class="lang-py prettyprint-override"><code>>>> schema = StructType([StructField('name', StringType()),
...                      StructField('age',IntegerType())])
>>> df = spark.createDataFrame(row, schema)
</code>```

but then, this error gets thrown.

```<code>Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/spark2-client/python/pyspark/sql/session.py", line 526, in createDataFrame
    rdd, schema = self._createFromLocal(map(prepare, data), schema)
  File "/spark2-client/python/pyspark/sql/session.py", line 387, in _createFromLocal
    data = list(data)
  File "/spark2-client/python/pyspark/sql/session.py", line 509, in prepare
    verify_func(obj, schema)
  File "/spark2-client/python/pyspark/sql/types.py", line 1366, in _verify_type
    raise TypeError("StructType can not accept object %r in type %s" % (obj, type(obj)))
TypeError: StructType can not accept object 33 in type <type 'int'>
</code>```

答:
The createDataFrame function takes a list of Rows (among other options) plus the schema, so the correct code would be something like:

from pyspark.sql.types import *
from pyspark.sql import Row

schema = StructType([StructField('name', StringType()), StructField('age',IntegerType())])
rows = [Row(name='Severin', age=33), Row(name='John', age=48)]
df = spark.createDataFrame(rows, schema)

df.printSchema()
df.show()
```
<p>Out:</p>
```root
 |-- name: string (nullable = true)
 |-- age: integer (nullable = true)

+-------+---+
|   name|age|
+-------+---+
|Severin| 33|
|   John| 48|
+-------+---+
```

In the pyspark docs (link) you can find more details about the createDataFrame function.

Body:
When I began learning PySpark, I used a list to create a dataframe. Now that inferring the schema from list has been deprecated, I got a warning and it suggested me to use pyspark.sql.Row instead. However, when I try to create one using Row, I get infer schema issue. This is my code:

>>> row = Row(name='Severin', age=33)
>>> df = spark.createDataFrame(row)

This results in the following error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/spark2-client/python/pyspark/sql/session.py", line 526, in createDataFrame
    rdd, schema = self._createFromLocal(map(prepare, data), schema)
  File "/spark2-client/python/pyspark/sql/session.py", line 390, in _createFromLocal
    struct = self._inferSchemaFromList(data)
  File "/spark2-client/python/pyspark/sql/session.py", line 322, in _inferSchemaFromList
    schema = reduce(_merge_type, map(_infer_schema, data))
  File "/spark2-client/python/pyspark/sql/types.py", line 992, in _infer_schema
    raise TypeError("Can not infer schema for type: %s" % type(row))
TypeError: Can not infer schema for type: <type 'int'>

So I created a schema

>>> schema = StructType([StructField('name', StringType()),
...                      StructField('age',IntegerType())])
>>> df = spark.createDataFrame(row, schema)

but then, this error gets thrown.

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/spark2-client/python/pyspark/sql/session.py", line 526, in createDataFrame
    rdd, schema = self._createFromLocal(map(prepare, data), schema)
  File "/spark2-client/python/pyspark/sql/session.py", line 387, in _createFromLocal
    data = list(data)
  File "/spark2-client/python/pyspark/sql/session.py", line 509, in prepare
    verify_func(obj, schema)
  File "/spark2-client/python/pyspark/sql/types.py", line 1366, in _verify_type
    raise TypeError("StructType can not accept object %r in type %s" % (obj, type(obj)))
TypeError: StructType can not accept object 33 in type <type 'int'>

Body:
The createDataFrame function takes a list of Rows (among other options) plus the schema, so the correct code would be something like:

from pyspark.sql.types import *
from pyspark.sql import Row

schema = StructType([StructField('name', StringType()), StructField('age',IntegerType())])
rows = [Row(name='Severin', age=33), Row(name='John', age=48)]
df = spark.createDataFrame(rows, schema)

df.printSchema()
df.show()

Out:

root
 |-- name: string (nullable = true)
 |-- age: integer (nullable = true)

+-------+---+
|   name|age|
+-------+---+
|Severin| 33|
|   John| 48|
+-------+---+

In the pyspark docs (link) you can find more details about the createDataFrame function.


问:
Use of unresolved indetifier jsonResult
I get this error everytime i tried to fix it. Please help</p>

```<code>do {
    if let jsonResult = try JSONSerialization.jsonObject(with: data, options: []) as? [String:AnyObject] {
        print(jsonResult)
    }
} catch let error as NSError {
    print(error.localizedDescription)
}

if (jsonResult != nil) {
    print(jsonResult)
} else {
    // couldn't load JSON, look at error
}
</code>```

答:
jsonResult was used outside the do-try-catch statement in which it was created, so that's why you can't access it. Here is the corrected code:

```<code>do {
    if let jsonResult = try JSONSerialization.jsonObject(with: data, options: []) as? [String:AnyObject] {
        print(jsonResult)
        //The following lines of code is commented out because you have used if let outside to make sure that jsonResult here is not nil.
        //So you do not need to check for it again
        //if (jsonResult != nil) {
        //   print(jsonResult)
        //} else {
        //    // couldn't load JSON, look at error
        //}
    }

} catch let error as NSError {
    print(error.localizedDescription)
}
</code>```

Title: Use of unresolved indetifier jsonResult

Body:
I get this error everytime i tried to fix it. Please help

do {
    if let jsonResult = try JSONSerialization.jsonObject(with: data, options: []) as? [String:AnyObject] {
        print(jsonResult)
    }
} catch let error as NSError {
    print(error.localizedDescription)
}

if (jsonResult != nil) {
    print(jsonResult)
} else {
    // couldn't load JSON, look at error
}

Body:
jsonResult was used outside the do-try-catch statement in which it was created, so that's why you can't access it. Here is the corrected code:

do {
    if let jsonResult = try JSONSerialization.jsonObject(with: data, options: []) as? [String:AnyObject] {
        print(jsonResult)
        //The following lines of code is commented out because you have used if let outside to make sure that jsonResult here is not nil.
        //So you do not need to check for it again
        //if (jsonResult != nil) {
        //   print(jsonResult)
        //} else {
        //    // couldn't load JSON, look at error
        //}
    }

} catch let error as NSError {
    print(error.localizedDescription)
}


问:
How to change Order Email Subject in Order.php Magento
I want to change order email subject in Magento for the order.php file.

Here is my code:

```<code>$mailSubject = "This is test subject";
Mage::getModel('core/email_template')->setTemplateSubject($mailSubject);
$translate = Mage::getSingleton('core/translate');
</code>```

It's not working. Is there any other way to set subject in order.php

I don't want to set from Transaction Emails option from back-end as there is a value generated by PHP I want to send in the subject line.

Any help would be appreciated.

Thanks

答:
Just refer the following URL for correct answer.

Magento - Custom subject of order email

And try to change customizations through custom magento module.Suppose you are going to update magento means it may cause some issues.

Create a new custom module and do the customizations in proper way.

Body:
I want to change order email subject in Magento for the order.php file.

Here is my code:

$mailSubject = "This is test subject";
Mage::getModel('core/email_template')->setTemplateSubject($mailSubject);
$translate = Mage::getSingleton('core/translate');

It's not working. Is there any other way to set subject in order.php

I don't want to set from Transaction Emails option from back-end as there is a value generated by PHP I want to send in the subject line.

Any help would be appreciated.

Thanks


问:
Build Mobile App for alexa?
Hi I have a custom skill running with alexa echo & is working fine. Now I need to build a mobile application (android native / Hybrid) that take input from my phone's mic, alexa processes this with my custom skill & return output that plays from my phone's speakers.

In short, I need an app doing all all echo is doing. Is it possible ? How ? And if yes, please provide me links that can be helpful. Any samples would be appreciated.

Thank you.

答:
you need to :

Registering Your Product and Creating a Security Profile

Generating Self-Signed Certificates

Building and Running the Android Mobile Apps

Running the Server

Running the Client

check this for full details

Title: Build Mobile App for alexa?


问:
Upload dSYM to crashlytics from window
I develop app by Xamarin.IOS and want to use crashlytics. I use CI by Jenkins based on Windows. How can I automatically upload dSYM files to crashlytics from windows machine? I try find any public API for that, but found nothing.

I have workaround: Upload dsym to mac and use fastlane

Is it only one way for this?

答: Mike from Fabric here and you're correct that using Fastlane as a workaround is the best solution. </p>

Title: Upload dSYM to crashlytics from window