问:
Pandas read csv infer only bool
I would like to use pandas.read_csv to infer only boolean types in the data.

If I use dtypes=str, I do not have a simple way to convert my data back to boolean type as the following does not work well.

```<code>df['bool_column'].astype(bool).eq(False)
</code>```

I do not want to infer all dtypes as I do not want to lose any integer types in the data.

Is there a simple solution to this problem?

答:
For the Latest version, pandas read_csv could handle this without specifying the bool type. Other more clear ways as follow:

You can specify what datatype on what column

```<code>d = pandas.read_csv('foo.csv', dtype={'bool_column': 'bool'})
</code>```

or you can convert to bool for specific column by applying:

```<code>d = df['bool_column'].apply(bool)
or
d = df.bool_column.astype(bool)
</code>```

MaxU gives a better solution.
And Here is another solution:

```<code>df = pandas.read_csv('foo.csv', converters={"bool_column": bool})
</code>```

or

```<code>def convert_bool(col):
    if str(col) == "true":
       return True
    elif str(col) == "false":
       return False

df = pandas.read_csv('foo.csv', converters={"bool_column": lambda x:convert_bool(x)})
</code>```

Here is my test data:

```<code>#foo.csv
col1,col2,col3,col4
false,true,1,hah
true,false,0,haha
false,true,1,haaaaa
false,true,1,hah
true,false,0,haha
false,true,1,haaaaa
false,true,1,hah
true,false,0,haha
false,true,1,haaaaa
false,true,1,hah

pandas.read_csv('test.txt',converters={'col1':lambda x: convert_bool(x),'col2':str}).dtypes
#output
col1      bool
col2    object
col3     int64
col4    object
dtype: object

pandas.read_csv('test.txt',converters={'col1': bool}).dtypes
#output
col1      bool
col2      bool
col3      int64
col4      object
dtype: object
</code>```

Title: Pandas read csv infer only bool

Body:
I would like to use pandas.read_csv to infer only boolean types in the data.

If I use dtypes=str, I do not have a simple way to convert my data back to boolean type as the following does not work well.

df['bool_column'].astype(bool).eq(False)

I do not want to infer all dtypes as I do not want to lose any integer types in the data.

Is there a simple solution to this problem?

Body:
For the Latest version, pandas read_csv could handle this without specifying the bool type. Other more clear ways as follow:

You can specify what datatype on what column

d = pandas.read_csv('foo.csv', dtype={'bool_column': 'bool'})

or you can convert to bool for specific column by applying:

d = df['bool_column'].apply(bool)
or
d = df.bool_column.astype(bool)

MaxU gives a better solution.
And Here is another solution:

df = pandas.read_csv('foo.csv', converters={"bool_column": bool})

or

def convert_bool(col):
    if str(col) == "true":
       return True
    elif str(col) == "false":
       return False

df = pandas.read_csv('foo.csv', converters={"bool_column": lambda x:convert_bool(x)})

Here is my test data:

#foo.csv
col1,col2,col3,col4
false,true,1,hah
true,false,0,haha
false,true,1,haaaaa
false,true,1,hah
true,false,0,haha
false,true,1,haaaaa
false,true,1,hah
true,false,0,haha
false,true,1,haaaaa
false,true,1,hah

pandas.read_csv('test.txt',converters={'col1':lambda x: convert_bool(x),'col2':str}).dtypes
#output
col1      bool
col2    object
col3     int64
col4    object
dtype: object

pandas.read_csv('test.txt',converters={'col1': bool}).dtypes
#output
col1      bool
col2      bool
col3      int64
col4      object
dtype: object


来源: stackexchange

问:
Asp NetCore 2 Required validation - ModelState Valid is true when in error
I'm trying to get some required field validation working in AspNetCore 2, and what I expect to happen, isn't happening.

Model

```<code>[Required(ErrorMessage = "The game name cannot be blank")]
[StringLength(100,ErrorMessage = "The game name must be between 2 and 100 characters", MinimumLength = 2)]
[Display(Name = "Name")]
public string GameName { get; set; }
</code>```

Controller

```<code>[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult GameDetail(GameDetail model, IFormCollection form)
{
    if (!ModelState.IsValid)
    {
        return View(model);
    }

    // code removed for clarity
}
</code>```

View

```<code><div asp-validation-summary="ModelOnly" class="text-danger"></div>

<form class="form" method="post">
  <div class="form-group">
    <label class="form-label" asp-for="GameName"></label>
    <span asp-validation-for="GameName" class="text-danger"></span>
    <input class="form-control" asp-for="GameName" class="form-control" />
  </div>
  <div class="form-group">
    <input class="button" type="submit" value="Continue">
  </div>
</form>
</code>```

In MVC5, if this form was posted with no value entered, ModelState would be invalid and an error would be returned to the view.

However, in this instance, ModelState.IsValid is true, but the error count is 1 and the error list does show the field is required as an error.

I have tried a few things including adding [Bind("GameName")] on the post parameters against the model and also [BindRequired] on the model as well as this post: https://learn.microsoft.com/en-us/aspnet/core/mvc/models/validation

Yet, the form submits and redirects to the next page (code removed for clarity) without showing any errors.

I would expect to see the view returned with the field error message showing the required error message and an error summary showing the same error.

答:
I think you have to add AllowEmptyString=false on the required attribute.</p>

```<code>[Required (AllowEmptyStrings = false)]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to get some required field validation working in AspNetCore 2, and what I expect to happen, isn't happening.

Model

[Required(ErrorMessage = "The game name cannot be blank")]
[StringLength(100,ErrorMessage = "The game name must be between 2 and 100 characters", MinimumLength = 2)]
[Display(Name = "Name")]
public string GameName { get; set; }

Controller

[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult GameDetail(GameDetail model, IFormCollection form)
{
    if (!ModelState.IsValid)
    {
        return View(model);
    }

    // code removed for clarity
}

View

<form class="form" method="post">

    <input class="form-control" asp-for="GameName" class="form-control" />

    <input class="button" type="submit" value="Continue">

</form>

In MVC5, if this form was posted with no value entered, ModelState would be invalid and an error would be returned to the view.

However, in this instance, ModelState.IsValid is true, but the error count is 1 and the error list does show the field is required as an error.

I have tried a few things including adding [Bind("GameName")] on the post parameters against the model and also [BindRequired] on the model as well as this post: https://learn.microsoft.com/en-us/aspnet/core/mvc/models/validation

Yet, the form submits and redirects to the next page (code removed for clarity) without showing any errors.

I would expect to see the view returned with the field error message showing the required error message and an error summary showing the same error.

Body:
I think you have to add AllowEmptyString=false on the required attribute.

[Required (AllowEmptyStrings = false)]


问:
Assert seems to evaluate the return string even on a pass
I have an assert method which is checking to see if an array is empty or null. This check is working fine and when I expect it to be null or empty the test passes. The issue is that I have a string to show when the test fails that prints the to string of the array.

```<code>Assert.True(list == null || list.Count < 1, $"Printing array {list.ToString()}");
</code>```

This method is causing an exception to be thrown because the string is being evaluated for a null list even though the assert passes and the string should not be used. Why is the string still evaluated?

答:
Calling a method will evaluate all of its parameters before the call happens.

Before Assert.True() even runs, it will evaluate its string to pass the parameter.

Body:
I have an assert method which is checking to see if an array is empty or null. This check is working fine and when I expect it to be null or empty the test passes. The issue is that I have a string to show when the test fails that prints the to string of the array.

Assert.True(list == null || list.Count < 1, $"Printing array {list.ToString()}");

This method is causing an exception to be thrown because the string is being evaluated for a null list even though the assert passes and the string should not be used. Why is the string still evaluated?


问:
I am trying to join two tables I want null values to be equivalent to ALL
Lets say that I have two tables:

```<code>table 1 columns: A,B,C
table 2 columns: D,E,F

JOIN Conditions
table1.A = table2.D, table1.B=table2.E, table1.C = table2.F
</code>```

Any column can have a null value. I want null values to be treated as a match for any value. (i.e if A=D and B=E, but C is null. F has two values for A=D and B=E. Both rows should be included in the resultant table)

```<code>Table1:                                Table2:
A:         B:       C:                D:           E:          F:
a          b         c                 a           b           c
e          <null>    f                 e           a           f
o          <null>    q                 e           b           f
h          i         j                 h           i           k
l          <null>    m                 l           a           m
o          <null>    q                 o           <null>      q

results(show table 2 values...):
D:   E:     F:
a    b      c
e    a      f
e    b      f
o   <null>  q
l    a      m
</code>```

答:
You could just write out this condition. I feel like there may be some way to do this a bit more sneaky/less verbose, but this should get you in the ballpark:</p>

```<code>ON
(table1.A = table2.D AND table1.B = table2.E AND (table1.C = table2.F OR table1.C IS NULL))
OR (table1.A = table2.D AND (table1.B = table2.E OR table1.B IS NULL) AND table1.C = table2.F)
OR ((table1.A = table2.D OR table1.A IS NULL) AND table1.B = table2.E AND table1.C = table2.F)
</code>```

Body:
Lets say that I have two tables:

table 1 columns: A,B,C
table 2 columns: D,E,F

JOIN Conditions
table1.A = table2.D, table1.B=table2.E, table1.C = table2.F

Any column can have a null value. I want null values to be treated as a match for any value. (i.e if A=D and B=E, but C is null. F has two values for A=D and B=E. Both rows should be included in the resultant table)

Table1:                                Table2:
A:         B:       C:                D:           E:          F:
a          b         c                 a           b           c
e          <null>    f                 e           a           f
o          <null>    q                 e           b           f
h          i         j                 h           i           k
l          <null>    m                 l           a           m
o          <null>    q                 o           <null>      q

results(show table 2 values...):
D:   E:     F:
a    b      c
e    a      f
e    b      f
o   <null>  q
l    a      m

Body:
You could just write out this condition. I feel like there may be some way to do this a bit more sneaky/less verbose, but this should get you in the ballpark:

ON
(table1.A = table2.D AND table1.B = table2.E AND (table1.C = table2.F OR table1.C IS NULL))
OR (table1.A = table2.D AND (table1.B = table2.E OR table1.B IS NULL) AND table1.C = table2.F)
OR ((table1.A = table2.D OR table1.A IS NULL) AND table1.B = table2.E AND table1.C = table2.F)


问:
Shiny: unwanted space added by plotOutput() and/or renderPlot()
Either plotOutput or renderPlot seems to add a bunch of extra white space around a plot. I've added background colours to the plot and the layout column to illustrate this. Essentially, I would like to be completely rid of this white space, leaving only the area coloured in blue, which should then align itself to the left of the column.

I know that this can be adjusted using the width argument, but having it a either 100% or auto doesn't seem to work properly.

Thanks!

```<code>library(shiny)
library(ggplot2)

# Create sample data
animals <- as.data.frame(
  table(Species =
          c(rep("Moose", sample(1:100, 1)),
            rep("Frog", sample(1:100, 1)),
            rep("Dragonfly", sample(1:100, 1))
          )))

server <- function(input, output) {

  output$pieChart <- renderPlot({

    # Create pie chart
    ggplot(animals, aes(x = "", y = Freq, fill = Species)) +
      geom_bar(width = 1, stat = "identity") +
      coord_polar("y", start=0) +
      theme(plot.background = element_rect(fill = "lightblue"))
  })
}

ui <- fluidPage(

  fluidRow(
    column(4,
           style = "background-color:lightgreen",
           align = "left",
           HTML("filler<br>"),
           plotOutput("pieChart")
    )
  )
)

shinyApp(ui = ui, server = server)
</code>```

答:
The space is added by the grid layout engine, not by anything in shiny. Grid adds the white space because ggplot has asked it to maintain the aspect ratio of the plot, to make sure the circle is round.

Here is how you can see this. First, let's draw the plot the regular way, but let's manually convert to a grob first.

```<code>g <- ggplot(animals, aes(x = "", y = Freq, fill = Species)) +
  geom_bar(width = 1, stat = "identity") +
  coord_polar("y", start=0) +
  theme(plot.background = element_rect(fill = "lightblue"))

library(grid)
grob <- ggplotGrob(g)
grid.newpage()
grid.draw(grob)
</code>```

This will generate plots with whitespace either on the sides or above/below, depending on the shape of the enclosing window:

Now let's turn off the aspect-ratio enforcement and plot again:

```<code>grob$respect <- FALSE # this switches of the fixed aspect ratio
grid.newpage()
grid.draw(grob)
</code>```

Now there is no white space, but also the circle isn't round.

You'll have to put the plot into an enclosing container that can provide necessary white space on the right and bottom. This is possible with grid if you're willing to give the plot a fixed size, by putting the plot into a table with empty space to the side and bottom:

```<code>library(grid)
library(gtable)
# need to play around to find numbers that work
plotwidth = unit(6.1, "inch")
plotheight = unit(5, "inch")

grob <- ggplotGrob(g)
mat <- matrix(list(grob, nullGrob(), nullGrob(), nullGrob()), nrow = 2)
widths <- unit(c(1, 1), "null")
widths[1] <- plotwidth
heights <- unit(c(1, 1), "null")
heights[1] <- plotheight
gm <- gtable_matrix(NULL, mat, widths, heights)
grid.newpage()
grid.draw(gm)
</code>```

The downside of this approach is that now, if the plot window is too small, the plot will not be resized but instead will be cut off:

I'm not sure how to get the plot to scale to the largest possible size that still fits within the window.

Body:
Either plotOutput or renderPlot seems to add a bunch of extra white space around a plot. I've added background colours to the plot and the layout column to illustrate this. Essentially, I would like to be completely rid of this white space, leaving only the area coloured in blue, which should then align itself to the left of the column.

I know that this can be adjusted using the width argument, but having it a either 100% or auto doesn't seem to work properly.

Thanks!

library(shiny)
library(ggplot2)

# Create sample data
animals <- as.data.frame(
  table(Species =
          c(rep("Moose", sample(1:100, 1)),
            rep("Frog", sample(1:100, 1)),
            rep("Dragonfly", sample(1:100, 1))
          )))

server <- function(input, output) {

  output$pieChart <- renderPlot({

    # Create pie chart
    ggplot(animals, aes(x = "", y = Freq, fill = Species)) +
      geom_bar(width = 1, stat = "identity") +
      coord_polar("y", start=0) +
      theme(plot.background = element_rect(fill = "lightblue"))
  })
}

ui <- fluidPage(

  fluidRow(
    column(4,
           style = "background-color:lightgreen",
           align = "left",
           HTML("filler
"),
           plotOutput("pieChart")
    )
  )
)

shinyApp(ui = ui, server = server)

Body:
The space is added by the grid layout engine, not by anything in shiny. Grid adds the white space because ggplot has asked it to maintain the aspect ratio of the plot, to make sure the circle is round.

Here is how you can see this. First, let's draw the plot the regular way, but let's manually convert to a grob first.

g <- ggplot(animals, aes(x = "", y = Freq, fill = Species)) +
  geom_bar(width = 1, stat = "identity") +
  coord_polar("y", start=0) +
  theme(plot.background = element_rect(fill = "lightblue"))

library(grid)
grob <- ggplotGrob(g)
grid.newpage()
grid.draw(grob)

This will generate plots with whitespace either on the sides or above/below, depending on the shape of the enclosing window:

Now let's turn off the aspect-ratio enforcement and plot again:

grob$respect <- FALSE # this switches of the fixed aspect ratio
grid.newpage()
grid.draw(grob)

Now there is no white space, but also the circle isn't round.

You'll have to put the plot into an enclosing container that can provide necessary white space on the right and bottom. This is possible with grid if you're willing to give the plot a fixed size, by putting the plot into a table with empty space to the side and bottom:

library(grid)
library(gtable)
# need to play around to find numbers that work
plotwidth = unit(6.1, "inch")
plotheight = unit(5, "inch")

grob <- ggplotGrob(g)
mat <- matrix(list(grob, nullGrob(), nullGrob(), nullGrob()), nrow = 2)
widths <- unit(c(1, 1), "null")
widths[1] <- plotwidth
heights <- unit(c(1, 1), "null")
heights[1] <- plotheight
gm <- gtable_matrix(NULL, mat, widths, heights)
grid.newpage()
grid.draw(gm)

The downside of this approach is that now, if the plot window is too small, the plot will not be resized but instead will be cut off:

I'm not sure how to get the plot to scale to the largest possible size that still fits within the window.


问:
Selenide and ChromeDriver (Java)
Can somebody help me, please?
I'm working with Selenide framework using Java. Selenide has method for opening browser. It look's like:
Selenide.open("http://www.google.com");

By default it uses FireFox. For use Chrome I need to set System property, like:

```<code>   @BeforeTest
    public void beforeTest() {
        Configuration.timeout=5000;
        System.setProperty("webdriver.chrome.driver", "chromedriver");
    }
</code>```

Chromedriver in my default project folder. What I'm doing wrong?

答:
you can use selenide configuration as below for the chrome browser

```<code>Configuration.browser = "chrome";
</code>```

You can see this post for more details

Title: Selenide and ChromeDriver (Java)

Body:
Can somebody help me, please?
I'm working with Selenide framework using Java. Selenide has method for opening browser. It look's like:
Selenide.open("http://www.google.com");

By default it uses FireFox. For use Chrome I need to set System property, like:

   @BeforeTest
    public void beforeTest() {
        Configuration.timeout=5000;
        System.setProperty("webdriver.chrome.driver", "chromedriver");
    }

Chromedriver in my default project folder. What I'm doing wrong?

Body:
you can use selenide configuration as below for the chrome browser

Configuration.browser = "chrome";

You can see this post for more details


问:
How to add URL query parameters to HTTP GET request?
I am trying to add a query parameter to a HTTP GET request but somehow methods pointed out on SO (e.g. here) don't work.

I have the following piece of code:

```<code>package main

import (
    "fmt"
    "log"
    "net/http"
)

func main() {
    req, err := http.NewRequest("GET", "/callback", nil)
    req.URL.Query().Add("code", "0xdead 0xbeef")
    req.URL.Query().Set("code", "0xdead 0xbeef")
    // this doesn't help
    //req.URL.RawQuery = req.URL.Query().Encode()

    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("URL      %+v\n", req.URL)
    fmt.Printf("RawQuery %+v\n", req.URL.RawQuery)
    fmt.Printf("Query    %+v\n", req.URL.Query())
}
</code>```

which prints:

```<code>URL      /callback
RawQuery
Query    map[]
</code>```

Any suggestions on how to achieve this?

Playground example: https://play.golang.org/p/SYN4yNbCmo

答:
Check the docs for req.URL.Query():

Query parses RawQuery and returns the corresponding values.

Since it "parses RawQuery and returns" the values what you get is just a copy of the URL query values, not a "live reference", so modifying that copy does nothing to the original query.  In order to modify the original query you must assign to the original RawQuery.

```<code>q := req.URL.Query() // Get a copy of the query values.
q.Add("code", "0xdead 0xbeef") // Add a new value to the set.
req.URL.RawQuery = q.Encode() // Encode and assign back to the original query.

// URL      /callback?code=0xdead+0xbeef
// RawQuery code=0xdead+0xbeef
// Query    map[code:[0xdead 0xbeef]]
</code>```

Note that your original attempt to do so didn't work because it simply parses the query values, encodes them, and assigns them right back to the URL:

```<code>req.URL.RawQuery = req.URL.Query().Encode()
// This is basically a noop!
</code>```

Body:
I am trying to add a query parameter to a HTTP GET request but somehow methods pointed out on SO (e.g. here) don't work.

I have the following piece of code:

package main

import (
    "fmt"
    "log"
    "net/http"
)

func main() {
    req, err := http.NewRequest("GET", "/callback", nil)
    req.URL.Query().Add("code", "0xdead 0xbeef")
    req.URL.Query().Set("code", "0xdead 0xbeef")
    // this doesn't help
    //req.URL.RawQuery = req.URL.Query().Encode()

    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("URL      %+v\n", req.URL)
    fmt.Printf("RawQuery %+v\n", req.URL.RawQuery)
    fmt.Printf("Query    %+v\n", req.URL.Query())
}

which prints:

URL      /callback
RawQuery
Query    map[]

Any suggestions on how to achieve this?

Playground example: https://play.golang.org/p/SYN4yNbCmo

Body:
Check the docs for req.URL.Query():

Query parses RawQuery and returns the corresponding values.

Since it "parses RawQuery and returns" the values what you get is just a copy of the URL query values, not a "live reference", so modifying that copy does nothing to the original query.  In order to modify the original query you must assign to the original RawQuery.

q := req.URL.Query() // Get a copy of the query values.
q.Add("code", "0xdead 0xbeef") // Add a new value to the set.
req.URL.RawQuery = q.Encode() // Encode and assign back to the original query.

// URL      /callback?code=0xdead+0xbeef
// RawQuery code=0xdead+0xbeef
// Query    map[code:[0xdead 0xbeef]]

Note that your original attempt to do so didn't work because it simply parses the query values, encodes them, and assigns them right back to the URL:

req.URL.RawQuery = req.URL.Query().Encode()
// This is basically a noop!


问:
Java JDBC - User registration & login
I have 3 questions regarding my code below used for user registration.

1) How can I prevent users from registering themselves providing empty value in the username and password area?

2) I wonder if it's a good practice to both dispose & run the form again in case user credentials already exist in database. Is there any other way to go back to the main screen?

3) My programs runs correctly but there is a warning message in a line like "The method getText() from the type JPasswordField is deprecated". What does that mean exactly?

Code:

```<code>public void actionPerformed(ActionEvent arg0) {

            try
                    {
              String userID = userIDinput.getText();
              String pass = passwordField.getText();
              String myDriver = "com.mysql.jdbc.Driver"; //jdbc driver loaded
              String myUrl = "jdbc:mysql://localhost:3306/masterdata_db?autoReconnect=true&useSSL=false";
              Class.forName(myDriver);
              Connection conn = DriverManager.getConnection(myUrl, "root", "");

              Statement st = conn.createStatement();
              ResultSet resultSet;

              String check = "SELECT Username FROM userregistration WHERE Username = '"+userID+"' ";
              resultSet = st.executeQuery(check);

              if(!resultSet.next()){

                  String sql = "INSERT INTO userregistration"
                            + "(Username, Password) VALUES"
                            + "(?,?)";
                  PreparedStatement pSt=conn.prepareStatement(sql);
                  pSt.setString(1, userID);
                  pSt.setString(2, pass);
                  pSt.executeUpdate();
                  conn.close();

              }

              else {

                  JOptionPane.showMessageDialog(frame, "USER ALREADY EXISTS. TRY ANOTHER ONE!", "Inane error",JOptionPane.ERROR_MESSAGE);
                  dispose();
                  new Login().setVisible(true);
              }

              }
            catch (Exception e)
                {

                  e.printStackTrace();
                }

            }
</code>```

答:
1)

```<code>if(userID.trim().isEmpty())//trim removes whitespaces
{
    throw new SomeKindOfException();
    //or just ...
    return;
}
</code>```

See this question.

2) Just remove the dispose and new Login(). JOptionPane will automatically "return to your main screen".

3) You should use password-fields like this:

```<code>JPasswordField passwordField = new JPasswordField();
char[] chars = passwordField.getPassword();
String pwd = new String(chars);
for (int i=0; i<chars.length; i++) chars[i] = ’x’; //overwrite password when done for more security
</code>```

See How to Use Password Fields for more information.

The JPasswordField uses char[] instead of String, because Strings are immutable.
For more information see this question.

Title: Java JDBC - User registration & login

Body:
I have 3 questions regarding my code below used for user registration.

1) How can I prevent users from registering themselves providing empty value in the username and password area?

2) I wonder if it's a good practice to both dispose & run the form again in case user credentials already exist in database. Is there any other way to go back to the main screen?

3) My programs runs correctly but there is a warning message in a line like "The method getText() from the type JPasswordField is deprecated". What does that mean exactly?

Code:

public void actionPerformed(ActionEvent arg0) {

            try
                    {
              String userID = userIDinput.getText();
              String pass = passwordField.getText();
              String myDriver = "com.mysql.jdbc.Driver"; //jdbc driver loaded
              String myUrl = "jdbc:mysql://localhost:3306/masterdata_db?autoReconnect=true&useSSL=false";
              Class.forName(myDriver);
              Connection conn = DriverManager.getConnection(myUrl, "root", "");

              Statement st = conn.createStatement();
              ResultSet resultSet;

              String check = "SELECT Username FROM userregistration WHERE Username = '"+userID+"' ";
              resultSet = st.executeQuery(check);

              if(!resultSet.next()){

                  String sql = "INSERT INTO userregistration"
                            + "(Username, Password) VALUES"
                            + "(?,?)";
                  PreparedStatement pSt=conn.prepareStatement(sql);
                  pSt.setString(1, userID);
                  pSt.setString(2, pass);
                  pSt.executeUpdate();
                  conn.close();

              }

              else {

                  JOptionPane.showMessageDialog(frame, "USER ALREADY EXISTS. TRY ANOTHER ONE!", "Inane error",JOptionPane.ERROR_MESSAGE);
                  dispose();
                  new Login().setVisible(true);
              }

              }
            catch (Exception e)
                {

                  e.printStackTrace();
                }

            }

Body:
1)

if(userID.trim().isEmpty())//trim removes whitespaces
{
    throw new SomeKindOfException();
    //or just ...
    return;
}

See this question.

2) Just remove the dispose and new Login(). JOptionPane will automatically "return to your main screen".

3) You should use password-fields like this:

JPasswordField passwordField = new JPasswordField();
char[] chars = passwordField.getPassword();
String pwd = new String(chars);
for (int i=0; i<chars.length; i++) chars[i] = ’x’; //overwrite password when done for more security

See How to Use Password Fields for more information.

The JPasswordField uses char[] instead of String, because Strings are immutable.
For more information see this question.


问:
New version of PHPMyAdmin has stopped me being able to edit data
PHPMyAdmin has just been upgraded by my server admin to v4.0.4.2.

Now I am unable to edit rows in the following table:

```<code>CREATE TABLE IF NOT EXISTS `product_options` (
  `product_id` int(10) NOT NULL,
  `option_id` int(10) NOT NULL,
  KEY `product_id` (`product_id`,`option_id`)
)
</code>```

PHPMyAdmin just returns this error message when I browse data in the table:

This table does not contain a unique column. Grid edit, checkbox, Edit, Copy and Delete features are not available.

I don't want a unique column in this table, so how can I edit data?  Is there a setting I can change?

Many thanks

MySQL v5.1.70

答:
I had the same issue. In my own case I already had an id column. I dropped the column and recreated it; this time I made it a primary key and ticked A_I (ie Auto-Increment). Everything went fine.

Note: You can only do this if changing your IDs does not affect your work.

Body:
PHPMyAdmin has just been upgraded by my server admin to v4.0.4.2.

Now I am unable to edit rows in the following table:

CREATE TABLE IF NOT EXISTS `product_options` (
  `product_id` int(10) NOT NULL,
  `option_id` int(10) NOT NULL,
  KEY `product_id` (`product_id`,`option_id`)
)

PHPMyAdmin just returns this error message when I browse data in the table:

This table does not contain a unique column. Grid edit, checkbox, Edit, Copy and Delete features are not available.

I don't want a unique column in this table, so how can I edit data?  Is there a setting I can change?

Many thanks

MySQL v5.1.70


问:
Attribute error problems with python hangman code
I have some trouble with my python hangman code and i cant seem to be able to fix it. Just to let everyone know I am new to coding and am still learning how to do stuff. It would be much appreciated if anyone could help me. I find that the same happens when I try to "append" at any other part of the code from the while loop from under the "print... dashes" part.Thank you!

Here is the code:

```<code>import random

name = input("Hello, my name is H.A.N.K.M.A.N! What is yours?: ")
print("Hello, "+name," do you wanna play Hangman? Yes? Well why didn't you say so? Lets Goooooooo!")

def extractwords(filename,number):
    myfile=open(filename+".txt","r")
    details=myfile.readlines()
    myfile.close()
    words=[]
    for i in details:
        for item in i.split():
            letter=True
            for j in item:
                if j.isalpha()==False:
                    letter = False
            item = item.lower()
            if len(item)==number and letter==True and item not in words:
                    words.append(item)
    return words
player = "y"
while player =="y":
    complete=0
    guessed=[]
    errors=""
    characters = random.randint(5,9)
    tries = characters+3

    wordlist=extractwords("wordlist",characters)
    word=random.choice(wordlist)
    print("Testing word:",word)
    print("You have "+ str(tries)+" tries left")

    letters=[]
    for i in word:
        letters.append(i)

    hword=[]
    for i in range(0,characters):
        hword.append("-")

    dashes=""
    for i in hword:
        dashes = dashes+i

    print("The word you need to guess is ",dashes)
    while complete < characters and tries > 0:
        guess = input("Please input your letter: ")
        if guess in word:
            guessed.append(dashes)
            print("Noice job! You guessed the right letter!")
            tries=tries-1
            print("You have "+ str(tries)+" tries left")
            print(dashes)
            if len(guessed) == len(word):
                print("What? How did this happen? Yuu must have been cheating!Just Kidding! You did a good job on finding the word, so a GOOD JOB is in order!")
                layer = input("Would you like to play again? y/n: ")
        elif guess.isalpha and guess not in word:
            tries=tries-1
            print("I am sorry, but your guess is a number / not part of the word that I am thinking off. Please have another go!")
            errors.append(guess)
            print("The letters you entered so far:", errors)
            print("You have "+ str(tries)+" tries left")
        elif len(guess)!=1 or "abcdefghiklmnoopqestuvwxyz":
            print("Please enter a valid/single letter.")
        elif guess in guessed:
            print("Please enter a letter that you havent entered previously. ")
        else:
            pass
    if tries==0:
        print("You lose!The word you were supposed to guess was ",word)
player = input("Would you like to play again? y/n: ")
</code>```

`

答:
Ok, so I reviewed your code and you've got more than one problem. THAT'S OKAY. You're new to this. Anyways, I'll go through piece by piece and describe them for you, as well as how to fix them. Ok, let's begin:

```<code>letters=[]
for i in word:
    letters.append(i)
</code>```

This code, while it works perfectly fine, is highly redundant. You could replace it simply with letters = list(word).

```<code>hword=[]
for i in range(0,characters):
    hword.append("-")

dashes=""
for i in hword:
    dashes = dashes+i
</code>```

These two go together. you could replace the first with ['-']*characters and the second with '-'*characters. Remember that when you multiply a list (and in this case, strings are lists of characters) by an integer, it returns a list made of that many repetitions of your original list. Even more space efficient... If you defined dashes first, you could follow that up with hword = list(dashes).

```<code>guessed.append(dashes)
</code>```

I already told you about this one in the comments, but here I go again. guessed should be taking your guess value, not your dashes value.

```<code>print(dashes)  #line 46
</code>```

Once again... You never change dashes, so you shouldn't print it.

```<code>elif guess.isalpha and guess not in word:
    tries=tries-1
    print("I am sorry, but your guess is a number / not part of the word that I am thinking off. Please have another go!")
    errors.append(guess)
    print("The letters you entered so far:", errors)
    print("You have "+ str(tries)+" tries left")
elif len(guess)!=1 or "abcdefghiklmnoopqestuvwxyz":
    print("Please enter a valid/single letter.")
elif guess in guessed:
    print("Please enter a letter that you havent entered previously. ")
else:
    pass
</code>```

Before you check if guess is in word, you should probably check it to see if it's even valid. This isn't just python, this is code security in general. The most basic hacking technique is sending input so large that it busts into another part of memory. This is bad. Check yourself before you wreck yourself. I, personally, would do something like this:

```<code>while ...
  #get input
  If not is_valid(your_input):
    continue
  #Do what you want with the input
</code>```

You'd have to define is_valid(), but that's the gist. The cool part of this code is the continue statement. continue loops the loop back to the start.

```<code>if guess in word:
    guessed.append(guess)
    print("Noice job! You guessed the right letter!")
    tries=tries-1
    print("You have "+ str(tries)+" tries left")
    print(dashes)
    if len(guessed) == len(word):
        print("What? How did this happen? Yuu must have been cheating!Just Kidding! You did a good job on finding the word, so a GOOD JOB is in order!")
        layer = input("Would you like to play again? y/n: ")
</code>```

Ok, for one, you misnamed player as layer. Tucking fypos. For another, you should probably move your statement beginning in tries=... and ending in ...dashes) (lines 44-46) to outside the if statement. Maybe set that at the very end of your loop so that it's encountered whenever there's a valid input?

Now, the biggest error I see in your code: dashes. You keep using it, but it's always got the same value. You need to add a section of code in your if guess in word: conditional that updates hword or dashes with your new guess. It's not a simple task, as if your word is bookkeeper, then you'd have to replace e not once, but three times.

```<code>elif len(guess)!=1 or "abcdefghiklmnoopqestuvwxyz":
    print("Please enter a valid/single letter.")
</code>```

This one... Ok, so I know I've already gone over this section of code, but this has an especially egregious error. You can't say your alphabet right. The section with the alphabet does less than nothing. I assume what you meant is not guess in 'abcdefghijklmnopqrstuvwxyz', but because you left the first part out, it always evaluates to True.

```<code>player = input("Would you like to play again? y/n: ")
</code>```

This is the one at the end. It's got a problem with indentation. When your game finishes, it'll never be called because it's outside the primary while loop.

That being said, your code isn't too bad. Here's my fixes:

```<code>import random

name = input("Hello, my name is H.A.N.K.M.A.N! What is yours?: ")
print("Hello, "+name," do you wanna play Hangman? Yes? Well why didn't you say so? Lets Goooooooo!")

def extractwords(filename,number):
    myfile=open(filename+".txt","r")
    details=myfile.readlines()
    myfile.close()
    words=[]
    for i in details:
        for item in i.split():
            letter=True
            for j in item:
                if j.isalpha()==False:
                    letter = False
            item = item.lower()
            if len(item)==number and letter==True and item not in words:
                    words.append(item)
    return words
player = "y"
while player =="y":
    complete=0
    guessed=""
    errors=""
    characters = random.randint(5,9)
    tries = characters+3

    wordlist=extractwords("wordlist",characters)
    word=random.choice(wordlist)
    print("Testing word:",word)
    print("You have "+ str(tries)+" tries left")

    letters = list(word)

    dashes = '-'*characters
    hword = list(dashes)
    print("The word you need to guess is ",dashes)
    while complete < characters and tries > 0:
        guess = input("Please input your letter: ")
        if not(guess.isalpha() or len(guess)==1):
          print('Error: invalid input.')
          continue
        if guess in word:
          if guess in guessed:
            print("Already guessed that!")
            continue
          guessed += guess
          print("Guess correct!")
          #code to update dashes
          else:
          print('Incorrect guess.')
          errors += guess
        tries -= 1
        print("The letters you entered so far:", errors+guessed)
        print("You have "+ str(tries)+" tries left")
    if tries==0:
        print('lose')
    else:
     print('win')
    player = input("Would you like to play again? y/n: ")
</code>```

Body:
I have some trouble with my python hangman code and i cant seem to be able to fix it. Just to let everyone know I am new to coding and am still learning how to do stuff. It would be much appreciated if anyone could help me. I find that the same happens when I try to "append" at any other part of the code from the while loop from under the "print... dashes" part.Thank you!

Here is the code:

import random

name = input("Hello, my name is H.A.N.K.M.A.N! What is yours?: ")
print("Hello, "+name," do you wanna play Hangman? Yes? Well why didn't you say so? Lets Goooooooo!")

def extractwords(filename,number):
    myfile=open(filename+".txt","r")
    details=myfile.readlines()
    myfile.close()
    words=[]
    for i in details:
        for item in i.split():
            letter=True
            for j in item:
                if j.isalpha()==False:
                    letter = False
            item = item.lower()
            if len(item)==number and letter==True and item not in words:
                    words.append(item)
    return words
player = "y"
while player =="y":
    complete=0
    guessed=[]
    errors=""
    characters = random.randint(5,9)
    tries = characters+3

    wordlist=extractwords("wordlist",characters)
    word=random.choice(wordlist)
    print("Testing word:",word)
    print("You have "+ str(tries)+" tries left")

    letters=[]
    for i in word:
        letters.append(i)

    hword=[]
    for i in range(0,characters):
        hword.append("-")

    dashes=""
    for i in hword:
        dashes = dashes+i

    print("The word you need to guess is ",dashes)
    while complete < characters and tries > 0:
        guess = input("Please input your letter: ")
        if guess in word:
            guessed.append(dashes)
            print("Noice job! You guessed the right letter!")
            tries=tries-1
            print("You have "+ str(tries)+" tries left")
            print(dashes)
            if len(guessed) == len(word):
                print("What? How did this happen? Yuu must have been cheating!Just Kidding! You did a good job on finding the word, so a GOOD JOB is in order!")
                layer = input("Would you like to play again? y/n: ")
        elif guess.isalpha and guess not in word:
            tries=tries-1
            print("I am sorry, but your guess is a number / not part of the word that I am thinking off. Please have another go!")
            errors.append(guess)
            print("The letters you entered so far:", errors)
            print("You have "+ str(tries)+" tries left")
        elif len(guess)!=1 or "abcdefghiklmnoopqestuvwxyz":
            print("Please enter a valid/single letter.")
        elif guess in guessed:
            print("Please enter a letter that you havent entered previously. ")
        else:
            pass
    if tries==0:
        print("You lose!The word you were supposed to guess was ",word)
player = input("Would you like to play again? y/n: ")

`

Body:
Ok, so I reviewed your code and you've got more than one problem. THAT'S OKAY. You're new to this. Anyways, I'll go through piece by piece and describe them for you, as well as how to fix them. Ok, let's begin:

letters=[]
for i in word:
    letters.append(i)

This code, while it works perfectly fine, is highly redundant. You could replace it simply with letters = list(word).

hword=[]
for i in range(0,characters):
    hword.append("-")

dashes=""
for i in hword:
    dashes = dashes+i

These two go together. you could replace the first with ['-']*characters and the second with '-'*characters. Remember that when you multiply a list (and in this case, strings are lists of characters) by an integer, it returns a list made of that many repetitions of your original list. Even more space efficient... If you defined dashes first, you could follow that up with hword = list(dashes).

guessed.append(dashes)

I already told you about this one in the comments, but here I go again. guessed should be taking your guess value, not your dashes value.

print(dashes)  #line 46

Once again... You never change dashes, so you shouldn't print it.

elif guess.isalpha and guess not in word:
    tries=tries-1
    print("I am sorry, but your guess is a number / not part of the word that I am thinking off. Please have another go!")
    errors.append(guess)
    print("The letters you entered so far:", errors)
    print("You have "+ str(tries)+" tries left")
elif len(guess)!=1 or "abcdefghiklmnoopqestuvwxyz":
    print("Please enter a valid/single letter.")
elif guess in guessed:
    print("Please enter a letter that you havent entered previously. ")
else:
    pass

Before you check if guess is in word, you should probably check it to see if it's even valid. This isn't just python, this is code security in general. The most basic hacking technique is sending input so large that it busts into another part of memory. This is bad. Check yourself before you wreck yourself. I, personally, would do something like this:

while ...
  #get input
  If not is_valid(your_input):
    continue
  #Do what you want with the input

You'd have to define is_valid(), but that's the gist. The cool part of this code is the continue statement. continue loops the loop back to the start.

if guess in word:
    guessed.append(guess)
    print("Noice job! You guessed the right letter!")
    tries=tries-1
    print("You have "+ str(tries)+" tries left")
    print(dashes)
    if len(guessed) == len(word):
        print("What? How did this happen? Yuu must have been cheating!Just Kidding! You did a good job on finding the word, so a GOOD JOB is in order!")
        layer = input("Would you like to play again? y/n: ")

Ok, for one, you misnamed player as layer. Tucking fypos. For another, you should probably move your statement beginning in tries=... and ending in ...dashes) (lines 44-46) to outside the if statement. Maybe set that at the very end of your loop so that it's encountered whenever there's a valid input?

Now, the biggest error I see in your code: dashes. You keep using it, but it's always got the same value. You need to add a section of code in your if guess in word: conditional that updates hword or dashes with your new guess. It's not a simple task, as if your word is bookkeeper, then you'd have to replace e not once, but three times.

elif len(guess)!=1 or "abcdefghiklmnoopqestuvwxyz":
    print("Please enter a valid/single letter.")

This one... Ok, so I know I've already gone over this section of code, but this has an especially egregious error. You can't say your alphabet right. The section with the alphabet does less than nothing. I assume what you meant is not guess in 'abcdefghijklmnopqrstuvwxyz', but because you left the first part out, it always evaluates to True.

player = input("Would you like to play again? y/n: ")

This is the one at the end. It's got a problem with indentation. When your game finishes, it'll never be called because it's outside the primary while loop.

That being said, your code isn't too bad. Here's my fixes:

import random

name = input("Hello, my name is H.A.N.K.M.A.N! What is yours?: ")
print("Hello, "+name," do you wanna play Hangman? Yes? Well why didn't you say so? Lets Goooooooo!")

def extractwords(filename,number):
    myfile=open(filename+".txt","r")
    details=myfile.readlines()
    myfile.close()
    words=[]
    for i in details:
        for item in i.split():
            letter=True
            for j in item:
                if j.isalpha()==False:
                    letter = False
            item = item.lower()
            if len(item)==number and letter==True and item not in words:
                    words.append(item)
    return words
player = "y"
while player =="y":
    complete=0
    guessed=""
    errors=""
    characters = random.randint(5,9)
    tries = characters+3

    wordlist=extractwords("wordlist",characters)
    word=random.choice(wordlist)
    print("Testing word:",word)
    print("You have "+ str(tries)+" tries left")

    letters = list(word)

    dashes = '-'*characters
    hword = list(dashes)
    print("The word you need to guess is ",dashes)
    while complete < characters and tries > 0:
        guess = input("Please input your letter: ")
        if not(guess.isalpha() or len(guess)==1):
          print('Error: invalid input.')
          continue
        if guess in word:
          if guess in guessed:
            print("Already guessed that!")
            continue
          guessed += guess
          print("Guess correct!")
          #code to update dashes
          else:
          print('Incorrect guess.')
          errors += guess
        tries -= 1
        print("The letters you entered so far:", errors+guessed)
        print("You have "+ str(tries)+" tries left")
    if tries==0:
        print('lose')
    else:
     print('win')
    player = input("Would you like to play again? y/n: ")


问:
Getting a "Can't resolve variable of class" error when trying to access header variable
I have a container

```<code>std::map<std::string, int> map;
</code>```

in an a6.hpp header file but when I try to access map in my source file, I get a "Can't resolve variable or class" error. I have a

```<code>#include "a6.hpp"
</code>```

line but it's still giving me this error. Could someone help?

答:
Don't call your std::map variable map or any other C++ keyword or else bad things will happen.  Also check your a6.hpp file and make sure it has both includes for map and string.

```<code>#include <map>
#include <string>
</code>```

Body:
I have a container

std::map<std::string, int> map;

in an a6.hpp header file but when I try to access map in my source file, I get a "Can't resolve variable or class" error. I have a

#include "a6.hpp"

line but it's still giving me this error. Could someone help?

Body:
Don't call your std::map variable map or any other C++ keyword or else bad things will happen.  Also check your a6.hpp file and make sure it has both includes for map and string.

#include <map>
#include <string>


问:
Building my own tf.Estimator, how did model_params overwrite model_dir? RuntimeWarning?
Recently I built a customized deep neural net model using TFLearn, which claims to bring deep learning to the scikit-learn estimator API.  I could train models and make predictions, but I couldn't get the scoring (evaluate) function to work, so I couldn't do cross-validation.  I tried to ask questions about TFLearn in various places, but I got no responses.

It appears that TensorFlow itself has an estimator class.  So I am putting TFLearn aside, and I'm trying to follow the guide at https://www.tensorflow.org/extend/estimators.  Somehow I'm managing to get variables where they don't belong.  Can anyone spot my problem?  I will post code and the output.

Note: Of course, I can see the RuntimeWarning at the top of the output. I have found references to this warning online, but so far everyone claims it's harmless. Maybe it is not...

CODE:

```<code>import tensorflow as tf
from my_library import Database, l2_angle_distance

def my_model_function(topology, params):

    # This function will eventually be a function factory.  This should
    # allow easy exploration of hyperparameters.  For now, this just
    # returns a single, fixed model_fn.

    def model_fn(features, labels, mode):

        # Input layer
        net = tf.layers.conv1d(features["x"], topology[0], 3, activation=tf.nn.relu)
        net = tf.layers.dropout(net, 0.25)
        # The core of the network is here (convolutional layers only for now).
        for nodes in topology[1:]:
            net = tf.layers.conv1d(net, nodes, 3, activation=tf.nn.relu)
            net = tf.layers.dropout(net, 0.25)
        sh = tf.shape(features["x"])
        net = tf.reshape(net, [sh[0], sh[1], 3, 2])
        predictions = tf.nn.l2_normalize(net, dim=3)

        # PREDICT EstimatorSpec
        if mode == tf.estimator.ModeKeys.PREDICT:
            return tf.estimator.EstimatorSpec(mode=mode,
                    predictions={"vectors": predictions})

        # TRAIN or EVAL EstimatorSpec
        loss = l2_angle_distance(labels, predictions)
        optimizer = tf.train.GradientDescentOptimizer(learning_rate=params["learning_rate"])
        train_op = optimizer.minimize(loss=loss, global_step=tf.train.get_global_step())
        return tf.estimator.EstimatorSpec(mode, predictions, loss, train_op)

    return model_fn

##===================================================================

window = "whole"
encoding = "one_hot"
db = Database("/home/bwllc/Documents/Files for ML/compact")

traindb, testdb = db.train_test_split()
train_features, train_labels = traindb.values(window, encoding)
test_features, test_labels = testdb.values(window, encoding)

# Create the model.
tf.logging.set_verbosity(tf.logging.INFO)
LEARNING_RATE = 0.01
topology = (60,40,20)
model_params = {"learning_rate": LEARNING_RATE}
model_fn = my_model_function(topology, model_params)
model = tf.estimator.Estimator(model_fn, model_params)
print("\nmodel_dir?  No?  Why not? ", model.model_dir, "\n")  # This documents the error

# Input function.
my_input_fn = tf.estimator.inputs.numpy_input_fn({"x" : train_features}, train_labels, shuffle=True)

# Train the model.
model.train(input_fn=my_input_fn, steps=20)
</code>```

OUTPUT

```<code>/usr/lib/python3.6/importlib/_bootstrap.py:219: RuntimeWarning: compiletime version 3.5 of module 'tensorflow.python.framework.fast_tensor_util' does not match runtime version 3.6
  return f(*args, **kwds)
INFO:tensorflow:Using default config.
INFO:tensorflow:Using config: {'_model_dir': {'learning_rate': 0.01}, '_tf_random_seed': None, '_save_summary_steps': 100, '_save_checkpoints_steps': None, '_save_checkpoints_secs': 600, '_session_config': None, '_keep_checkpoint_max': 5, '_keep_checkpoint_every_n_hours': 10000, '_log_step_count_steps': 100, '_service': None, '_cluster_spec': <tensorflow.python.training.server_lib.ClusterSpec object at 0x7f0b55279048>, '_task_type': 'worker', '_task_id': 0, '_master': '', '_is_chief': True, '_num_ps_replicas': 0, '_num_worker_replicas': 1}

model_dir?  No?  Why not?  {'learning_rate': 0.01}

INFO:tensorflow:Create CheckpointSaverHook.
Traceback (most recent call last):
  File "minimal_estimator_bug_example.py", line 81, in <module>
    model.train(input_fn=my_input_fn, steps=20)
  File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/estimator/estimator.py", line 302, in train
    loss = self._train_model(input_fn, hooks, saving_listeners)
  File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/estimator/estimator.py", line 756, in _train_model
    scaffold=estimator_spec.scaffold)
  File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/training/basic_session_run_hooks.py", line 411, in __init__
    self._save_path = os.path.join(checkpoint_dir, checkpoint_basename)
  File "/usr/lib/python3.6/posixpath.py", line 78, in join
    a = os.fspath(a)
TypeError: expected str, bytes or os.PathLike object, not dict

------------------
(program exited with code: 1)
Press return to continue
</code>```

I can see exactly what went wrong, model_dir (which I left as the default) somehow bound to the value I intended for model_params. How did this happen in my code? I can't see it.

If anyone has advice or suggestions, I would greatly appreciate them. Thanks!

答:
Simply because you're feeding your model_param as a model_dir when you construct your Estimator.

From the tensorflow documentation :

Estimator __init__ function :

```<code>__init__(
    model_fn,
    model_dir=None,
    config=None,
    params=None
)
</code>```

Notice how the second argument is the model_dir one. If you want to specify only the params one, you need to pass it as a keyword argument.

```<code>model = tf.estimator.Estimator(model_fn, params=model_params)
</code>```

Or specify all the previous positional arguments :

```<code>model = tf.estimator.Estimator(model_fn, None, None, model_params)
</code>```

Body:
Recently I built a customized deep neural net model using TFLearn, which claims to bring deep learning to the scikit-learn estimator API.  I could train models and make predictions, but I couldn't get the scoring (evaluate) function to work, so I couldn't do cross-validation.  I tried to ask questions about TFLearn in various places, but I got no responses.

It appears that TensorFlow itself has an estimator class.  So I am putting TFLearn aside, and I'm trying to follow the guide at https://www.tensorflow.org/extend/estimators.  Somehow I'm managing to get variables where they don't belong.  Can anyone spot my problem?  I will post code and the output.

Note: Of course, I can see the RuntimeWarning at the top of the output. I have found references to this warning online, but so far everyone claims it's harmless. Maybe it is not...

CODE:

import tensorflow as tf
from my_library import Database, l2_angle_distance

def my_model_function(topology, params):

    # This function will eventually be a function factory.  This should
    # allow easy exploration of hyperparameters.  For now, this just
    # returns a single, fixed model_fn.

    def model_fn(features, labels, mode):

        # Input layer
        net = tf.layers.conv1d(features["x"], topology[0], 3, activation=tf.nn.relu)
        net = tf.layers.dropout(net, 0.25)
        # The core of the network is here (convolutional layers only for now).
        for nodes in topology[1:]:
            net = tf.layers.conv1d(net, nodes, 3, activation=tf.nn.relu)
            net = tf.layers.dropout(net, 0.25)
        sh = tf.shape(features["x"])
        net = tf.reshape(net, [sh[0], sh[1], 3, 2])
        predictions = tf.nn.l2_normalize(net, dim=3)

        # PREDICT EstimatorSpec
        if mode == tf.estimator.ModeKeys.PREDICT:
            return tf.estimator.EstimatorSpec(mode=mode,
                    predictions={"vectors": predictions})

        # TRAIN or EVAL EstimatorSpec
        loss = l2_angle_distance(labels, predictions)
        optimizer = tf.train.GradientDescentOptimizer(learning_rate=params["learning_rate"])
        train_op = optimizer.minimize(loss=loss, global_step=tf.train.get_global_step())
        return tf.estimator.EstimatorSpec(mode, predictions, loss, train_op)

    return model_fn

##===================================================================

window = "whole"
encoding = "one_hot"
db = Database("/home/bwllc/Documents/Files for ML/compact")

traindb, testdb = db.train_test_split()
train_features, train_labels = traindb.values(window, encoding)
test_features, test_labels = testdb.values(window, encoding)

# Create the model.
tf.logging.set_verbosity(tf.logging.INFO)
LEARNING_RATE = 0.01
topology = (60,40,20)
model_params = {"learning_rate": LEARNING_RATE}
model_fn = my_model_function(topology, model_params)
model = tf.estimator.Estimator(model_fn, model_params)
print("\nmodel_dir?  No?  Why not? ", model.model_dir, "\n")  # This documents the error

# Input function.
my_input_fn = tf.estimator.inputs.numpy_input_fn({"x" : train_features}, train_labels, shuffle=True)

# Train the model.
model.train(input_fn=my_input_fn, steps=20)

OUTPUT

/usr/lib/python3.6/importlib/_bootstrap.py:219: RuntimeWarning: compiletime version 3.5 of module 'tensorflow.python.framework.fast_tensor_util' does not match runtime version 3.6
  return f(*args, **kwds)
INFO:tensorflow:Using default config.
INFO:tensorflow:Using config: {'_model_dir': {'learning_rate': 0.01}, '_tf_random_seed': None, '_save_summary_steps': 100, '_save_checkpoints_steps': None, '_save_checkpoints_secs': 600, '_session_config': None, '_keep_checkpoint_max': 5, '_keep_checkpoint_every_n_hours': 10000, '_log_step_count_steps': 100, '_service': None, '_cluster_spec': <tensorflow.python.training.server_lib.ClusterSpec object at 0x7f0b55279048>, '_task_type': 'worker', '_task_id': 0, '_master': '', '_is_chief': True, '_num_ps_replicas': 0, '_num_worker_replicas': 1}

model_dir?  No?  Why not?  {'learning_rate': 0.01}

INFO:tensorflow:Create CheckpointSaverHook.
Traceback (most recent call last):
  File "minimal_estimator_bug_example.py", line 81, in <module>
    model.train(input_fn=my_input_fn, steps=20)
  File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/estimator/estimator.py", line 302, in train
    loss = self._train_model(input_fn, hooks, saving_listeners)
  File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/estimator/estimator.py", line 756, in _train_model
    scaffold=estimator_spec.scaffold)
  File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/training/basic_session_run_hooks.py", line 411, in __init__
    self._save_path = os.path.join(checkpoint_dir, checkpoint_basename)
  File "/usr/lib/python3.6/posixpath.py", line 78, in join
    a = os.fspath(a)
TypeError: expected str, bytes or os.PathLike object, not dict

------------------
(program exited with code: 1)
Press return to continue

I can see exactly what went wrong, model_dir (which I left as the default) somehow bound to the value I intended for model_params. How did this happen in my code? I can't see it.

If anyone has advice or suggestions, I would greatly appreciate them. Thanks!

Body:
Simply because you're feeding your model_param as a model_dir when you construct your Estimator.

From the tensorflow documentation :

Estimator __init__ function :

__init__(
    model_fn,
    model_dir=None,
    config=None,
    params=None
)

Notice how the second argument is the model_dir one. If you want to specify only the params one, you need to pass it as a keyword argument.

model = tf.estimator.Estimator(model_fn, params=model_params)

Or specify all the previous positional arguments :

model = tf.estimator.Estimator(model_fn, None, None, model_params)


问:
Specific regex not working in R
I'm trying to find whether a string pattern; (<double num><space><an operator><space><double num>) e.g. (14.0 + 46.0) exists in a given string using a regex in R. There can be 4 operators +,-,* and /.

There are two main patterns. Regex for the 1st pattern identifies that the pattern exists in the string "s"

```<code>#Pattern 1
s = "(14.0 + 46.0)"

#Regex
grep("^\\(-?\\d*\\.\\d{1}\\s[\\+\\-\\*\\/]\\s-?\\d*\\.\\d{1}\\)$", s)
</code>```

I'm trying to find the same pattern in a different string s1 and s2. I modified the first regex by adding .*  (any character) to the beginning and end of the string ("^.*   .*$"). I have checked the regex in this online checker and it works. But it doesn't work in R studio.

```<code>#Pattern 2
s1 = "((5.0 - 50.0) - 15.0)"
s2 = "(15.0 - (5.0 - 50.0))"

#Regex
grep("^.*\\(-?\\d*\\.\\d{1}\\s[\\+\\-\\*\\/]\\s-?\\d*\\.\\d{1}\\).*$", s1)
</code>```

答:
Note that adding .* at both ends of the regex is dangerous, since .* is greedy and will match any character. You can either attach ? (which makes .* lazy) or remove .* altogether since grep searches for any match in any parts of the string. To answer your question, it seems that you have to turn on perl to enable grep to match correctly:

```<code>#Pattern 2
s1 = "((5.0 - 50.0) - 15.0)"
s2 = "(15.0 - (5.0 - 50.0))"

grep("^.*?\\(-?\\d*\\.\\d{1}\\s[\\+\\-\\*\\/]\\s-?\\d*\\.\\d{1}\\).*?$", s1)
# integer(0)

grep("\\(-?\\d+\\.\\d\\s[\\+\\-\\*\\/]\\s-?\\d+\\.\\d\\)", s1)
# integer(0)

grep("^.*?\\(-?\\d*\\.\\d{1}\\s[\\+\\-\\*\\/]\\s-?\\d*\\.\\d{1}\\).*?$", s1, perl = TRUE)
# [1] 1

grep("\\(-?\\d+\\.\\d\\s[\\+\\-\\*\\/]\\s-?\\d+\\.\\d\\)", s1, perl = TRUE)
# [1] 1
</code>```

As pointed out by @ctwheels, this will match any string that has the pattern (<double num><space><an operator><space><double num>) in any position of the string. So this does not serve to validate whether the string contains only valid characters. See @ctwheels's answer for the latter case.

Title: Specific regex not working in R

Body:
I'm trying to find whether a string pattern; (<double num><space><an operator><space><double num>) e.g. (14.0 + 46.0) exists in a given string using a regex in R. There can be 4 operators +,-,* and /.

There are two main patterns. Regex for the 1st pattern identifies that the pattern exists in the string "s"

#Pattern 1
s = "(14.0 + 46.0)"

#Regex
grep("^\\(-?\\d*\\.\\d{1}\\s[\\+\\-\\*\\/]\\s-?\\d*\\.\\d{1}\\)$", s)

I'm trying to find the same pattern in a different string s1 and s2. I modified the first regex by adding .*  (any character) to the beginning and end of the string ("^.*   .*$"). I have checked the regex in this online checker and it works. But it doesn't work in R studio.

#Pattern 2
s1 = "((5.0 - 50.0) - 15.0)"
s2 = "(15.0 - (5.0 - 50.0))"

#Regex
grep("^.*\\(-?\\d*\\.\\d{1}\\s[\\+\\-\\*\\/]\\s-?\\d*\\.\\d{1}\\).*$", s1)

Body:
Note that adding .* at both ends of the regex is dangerous, since .* is greedy and will match any character. You can either attach ? (which makes .* lazy) or remove .* altogether since grep searches for any match in any parts of the string. To answer your question, it seems that you have to turn on perl to enable grep to match correctly:

#Pattern 2
s1 = "((5.0 - 50.0) - 15.0)"
s2 = "(15.0 - (5.0 - 50.0))"

grep("^.*?\\(-?\\d*\\.\\d{1}\\s[\\+\\-\\*\\/]\\s-?\\d*\\.\\d{1}\\).*?$", s1)
# integer(0)

grep("\\(-?\\d+\\.\\d\\s[\\+\\-\\*\\/]\\s-?\\d+\\.\\d\\)", s1)
# integer(0)

grep("^.*?\\(-?\\d*\\.\\d{1}\\s[\\+\\-\\*\\/]\\s-?\\d*\\.\\d{1}\\).*?$", s1, perl = TRUE)
# [1] 1

grep("\\(-?\\d+\\.\\d\\s[\\+\\-\\*\\/]\\s-?\\d+\\.\\d\\)", s1, perl = TRUE)
# [1] 1

As pointed out by @ctwheels, this will match any string that has the pattern (<double num><space><an operator><space><double num>) in any position of the string. So this does not serve to validate whether the string contains only valid characters. See @ctwheels's answer for the latter case.


问:
How to convert sysdate to UTC time in oracle
I am having a query to subtract a date from the sysdate. However the date object I have is in UTC but sysdate doesn't give me UTC time. How to I convert sysdate to give me date in UTC.

I have already tried using sys_extract_utc

```<code>select sys_extract_utc(systimestamp) from dual;
</code>```

This works fine and gives me the correct UTC time stamp. But the object returned by it is not the same as sysdate so when I subtract date from this object I get an INTERVAL DAY to SECOND but it should be a number.

答:
In case you do not want the "time" portion:</p>

```<code>SELECT TO_CHAR(SYS_EXTRACT_UTC(SYSTIMESTAMP), 'YYYY-MM-DD') FROM dual;
</code>```

Body:
I am having a query to subtract a date from the sysdate. However the date object I have is in UTC but sysdate doesn't give me UTC time. How to I convert sysdate to give me date in UTC.

I have already tried using sys_extract_utc

select sys_extract_utc(systimestamp) from dual;

This works fine and gives me the correct UTC time stamp. But the object returned by it is not the same as sysdate so when I subtract date from this object I get an INTERVAL DAY to SECOND but it should be a number.

Body:
In case you do not want the "time" portion:

SELECT TO_CHAR(SYS_EXTRACT_UTC(SYSTIMESTAMP), 'YYYY-MM-DD') FROM dual;


问:
Use erb partials, in Rails, to append the DOM using JavaScript - not hitting controller
I have a form that has a variable number of line items, each having the same inputs and icons and lots of other elements. I have a _line_item.html.erb partial that gets used in a loop in the view to show existing line items.

I also have a button, at the bottom, that when clicked will add a new, blank line item to the page. Doing so, however, doesn't hit the controller and happens completely client side. Currently, I just have a variable in my javascript that is a big string equal to the same HTML in the partial. I have to edit and maintain the erb partial and the javascript string separately, though.

This is all kind of ugly, and not at all DRY, so I was wondering - is there any way to leverage the HTML present in the erb partial for appending new line items, WITHOUT having to hit the controller first? Or, is there a better client-side way of handling appending reusable blocks of HTML?

Also, cloning is not an option since at some point the user could remove all their line items. I guess I could leave a hidden one in the DOM somewhere, rendered via the erb partial, but that also feels not great.

Body:
What you're doing is somewhat equivalent to what most implementations do.

Some implementations store the HTML in a <script type="text/html"> like tag, which may be a bit less painful for the updating of templates than maintaining a gigantic HTML string.


问:
How can I allow concurrent writes on different parts (with different keys) of a guava multimap
I'm using google guava multimap and would like to know if it's possible to allow concurrent writes to different parts of the map or do I have to synchronize all access? When I say different parts, I mean different key-value pairs in the multimap.

Is the following sample code correct?

```<code>  class Key {}
  class Value {}

  private Multimap<Key, Value> multimap = HashMultimap.create();

  private final Striped<Key> locks = Striped.readWriteLock(100);

  public void write(final Key key, final Collection<Value> values) {
     Lock writeLock = locks.get(key).writeLock();
     writeLock.lock();

     try {
        for (Value value : values) {
           multimap.put(key, value);
        }
     } finally {
       writeLock.unlock();
     }
  }

  public Collection<Value> read(final Key key) {
     Lock readLock = locks.get(key).readLock();
     readLock.lock();

     try {
      // Collect values
     } finally {
       readLock.unlock();
     }
  }
</code>```

答:
If you need this you may be better off using a ConcurrentHashMap<K, Set<V>> and manually replicating the multimap semantics.

You might be able to create a MultimapView type that extends Multimap and provides a view into a Map<K, Collection<V>> - I'm not sure if there's a reason Guava doesn't provide that (it might not be efficient?). All I see in Multimaps is copy factories.

Body:
I'm using google guava multimap and would like to know if it's possible to allow concurrent writes to different parts of the map or do I have to synchronize all access? When I say different parts, I mean different key-value pairs in the multimap.

Is the following sample code correct?

  class Key {}
  class Value {}

  private Multimap<Key, Value> multimap = HashMultimap.create();

  private final Striped<Key> locks = Striped.readWriteLock(100);

  public void write(final Key key, final Collection<Value> values) {
     Lock writeLock = locks.get(key).writeLock();
     writeLock.lock();

     try {
        for (Value value : values) {
           multimap.put(key, value);
        }
     } finally {
       writeLock.unlock();
     }
  }

  public Collection<Value> read(final Key key) {
     Lock readLock = locks.get(key).readLock();
     readLock.lock();

     try {
      // Collect values
     } finally {
       readLock.unlock();
     }
  }


问:
pandas group by and assign a group id then ungroup
I have a large data set in the following format:

```<code>id, socialmedia
1, facebook
2, facebook
3, google
4, google
5, google
6, twitter
7, google
8, twitter
9, snapchat
10, twitter
11, facebook
</code>```

I want to group by then and assign a group_id column and then ungroup (expand) back to individual records.

```<code>id, socialmedia, groupId
1, facebook, 1
2, facebook, 1
3, google, 2
4, google, 2
5, google, 2
6, twitter, 3
7, google, 2
8, twitter, 3
9, snapchat, 4
10, twitter, 3
11, facebook, 1
</code>```

I tried following but end up with 'DataFrameGroupBy' object does not support item assignment.

```<code>x['grpId'] = x.groupby('socialmedia')['socialmedia'].rank(method='dense').astype(int)
</code>```

答:
By using ngroup

```<code>df['grpId']=df.groupby(' socialmedia').ngroup().add(1)
df
Out[354]:
    id  socialmedia  grpId
0    1     facebook      1
1    2     facebook      1
2    3       google      2
3    4       google      2
4    5       google      2
5    6      twitter      4
6    7       google      2
7    8      twitter      4
8    9     snapchat      3
9   10      twitter      4
10  11     facebook      1
</code>```

Or pd.factorize and 'categroy'

```<code>df['grpId']=pd.factorize(df[' socialmedia'])[0]+1

df
Out[358]:
    id  socialmedia  grpId
0    1     facebook      1
1    2     facebook      1
2    3       google      2
3    4       google      2
4    5       google      2
5    6      twitter      3
6    7       google      2
7    8      twitter      3
8    9     snapchat      4
9   10      twitter      3
10  11     facebook      1
</code>```

```<code>df['grpId']=df[' socialmedia'].astype('category').cat.codes.add(1)
df
Out[356]:
    id  socialmedia  grpId
0    1     facebook      1
1    2     facebook      1
2    3       google      2
3    4       google      2
4    5       google      2
5    6      twitter      4
6    7       google      2
7    8      twitter      4
8    9     snapchat      3
9   10      twitter      4
10  11     facebook      1
</code>```

Body:
I have a large data set in the following format:

id, socialmedia
1, facebook
2, facebook
3, google
4, google
5, google
6, twitter
7, google
8, twitter
9, snapchat
10, twitter
11, facebook

I want to group by then and assign a group_id column and then ungroup (expand) back to individual records.

id, socialmedia, groupId
1, facebook, 1
2, facebook, 1
3, google, 2
4, google, 2
5, google, 2
6, twitter, 3
7, google, 2
8, twitter, 3
9, snapchat, 4
10, twitter, 3
11, facebook, 1

I tried following but end up with 'DataFrameGroupBy' object does not support item assignment.

x['grpId'] = x.groupby('socialmedia')['socialmedia'].rank(method='dense').astype(int)

Body:
By using ngroup

df['grpId']=df.groupby(' socialmedia').ngroup().add(1)
df
Out[354]:
    id  socialmedia  grpId
0    1     facebook      1
1    2     facebook      1
2    3       google      2
3    4       google      2
4    5       google      2
5    6      twitter      4
6    7       google      2
7    8      twitter      4
8    9     snapchat      3
9   10      twitter      4
10  11     facebook      1

Or pd.factorize and 'categroy'

df['grpId']=pd.factorize(df[' socialmedia'])[0]+1

df
Out[358]:
    id  socialmedia  grpId
0    1     facebook      1
1    2     facebook      1
2    3       google      2
3    4       google      2
4    5       google      2
5    6      twitter      3
6    7       google      2
7    8      twitter      3
8    9     snapchat      4
9   10      twitter      3
10  11     facebook      1

df['grpId']=df[' socialmedia'].astype('category').cat.codes.add(1)
df
Out[356]:
    id  socialmedia  grpId
0    1     facebook      1
1    2     facebook      1
2    3       google      2
3    4       google      2
4    5       google      2
5    6      twitter      4
6    7       google      2
7    8      twitter      4
8    9     snapchat      3
9   10      twitter      4
10  11     facebook      1


问:
Cannot increment variable in Python
I am learning how to code, would appreciate any inputs. This is a code I wrote to solve an easy problem on Leetcode.

The problem is that when the first time dict_ab[deck[-1]] == s[i+1], after executing deck.pop(), it'll then iterate i to i +=2. However this is not happening and i automatically only +=1. What is there that I did wrong? I have been working on this for a whole day, couldn't figure it out.

class Solution:
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        a = ('(','{','[')
        b = (')','}',']')
        dict_ab = dict(zip(a,b))

        import collections

        if (len(s) % 2 == 1) or (len(s) == 0):
            return False
        else:
            deck = collections.deque()
            #deck.append(s[0])
            #print(s[0])
            #print(len(s))
            for i in range(0, len(s), 1):
                #print(i)
                deck.append(s[i])
                #print(deck)

                if dict_ab[deck[-1]] == s[i+1]:
                    deck.pop()
                    #print(deck)
                    i +=2
                elif dict_ab[deck[-1]] != s[i+1]:
                    deck.append(s[i])
                    i +=1

            if len(deck) > 0:
                return False

        return True

    s = ('()[]')
    result = Solution().isValid(s)
    print(result)
```

<p>The result I see is as below:</p>

<blockquote>
  <pre class="lang-py prettyprint-override"><code>    KeyError                                  Traceback (most recent call last)
    <ipython-input-9-56d864c71658> in <module>()
     37         return True
     38 s = ('()[]')
    ---> 39 result = Solution().isValid(s)
     40 print(result)

    <ipython-input-9-56d864c71658> in isValid(self, s)
     23                 print(deck)
     24
    ---> 25                 if dict_ab[deck[-1]] == s[i+1]:
     26                     deck.pop()
     27                     print(deck)

    KeyError: ')'
</code>```

答:
This is a leetcode question. Rated as "Easy".

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

== below is the solution so if you don't want to read it, stop here ==

```<code>class Solution:
def isValid(self, s):
    """
    :type s: str
    :rtype: bool
    """
    a = ('(','{','[')
    b = (')','}',']')
    dict_ab = dict(zip(a,b))

    import collections

    if (len(s) % 2 == 1) or (len(s) == 0):
        return False
    else:
        deck = collections.deque()
        for i in range(0, len(s), 1):
            if s[i] in a:
                deck.append(s[i])
            else:
                if s[i] in b:
                    if len(deck) == 0:
                        return False
                    else:
                        if s[i] == dict_ab[deck[-1]]:
                            deck.pop()
                        else:
                            return False

        if len(deck) > 0:
            return False

    return True
</code>```

ContentLicense: CC BY-SA 4.0

Title: Cannot increment variable in Python

Body:
I am learning how to code, would appreciate any inputs. This is a code I wrote to solve an easy problem on Leetcode.

The problem is that when the first time dict_ab[deck[-1]] == s[i+1], after executing deck.pop(), it'll then iterate i to i +=2. However this is not happening and i automatically only +=1. What is there that I did wrong? I have been working on this for a whole day, couldn't figure it out.

class Solution:
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        a = ('(','{','[')
        b = (')','}',']')
        dict_ab = dict(zip(a,b))

        import collections

        if (len(s) % 2 == 1) or (len(s) == 0):
            return False
        else:
            deck = collections.deque()
            #deck.append(s[0])
            #print(s[0])
            #print(len(s))
            for i in range(0, len(s), 1):
                #print(i)
                deck.append(s[i])
                #print(deck)

                if dict_ab[deck[-1]] == s[i+1]:
                    deck.pop()
                    #print(deck)
                    i +=2
                elif dict_ab[deck[-1]] != s[i+1]:
                    deck.append(s[i])
                    i +=1

            if len(deck) > 0:
                return False

        return True

    s = ('()[]')
    result = Solution().isValid(s)
    print(result)

The result I see is as below:

    KeyError                                  Traceback (most recent call last)
    <ipython-input-9-56d864c71658> in <module>()
     37         return True
     38 s = ('()[]')
    ---> 39 result = Solution().isValid(s)
     40 print(result)

    <ipython-input-9-56d864c71658> in isValid(self, s)
     23                 print(deck)
     24
    ---> 25                 if dict_ab[deck[-1]] == s[i+1]:
     26                     deck.pop()
     27                     print(deck)

    KeyError: ')'

Body:
This is a leetcode question. Rated as "Easy".

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

== below is the solution so if you don't want to read it, stop here ==

class Solution:
def isValid(self, s):
    """
    :type s: str
    :rtype: bool
    """
    a = ('(','{','[')
    b = (')','}',']')
    dict_ab = dict(zip(a,b))

    import collections

    if (len(s) % 2 == 1) or (len(s) == 0):
        return False
    else:
        deck = collections.deque()
        for i in range(0, len(s), 1):
            if s[i] in a:
                deck.append(s[i])
            else:
                if s[i] in b:
                    if len(deck) == 0:
                        return False
                    else:
                        if s[i] == dict_ab[deck[-1]]:
                            deck.pop()
                        else:
                            return False

        if len(deck) > 0:
            return False

    return True


问:
Compiling a specific boost library
I only require a single .lib and .dll but I don't want to go through compiling process of all using bjam.exe How can i do that?

答: You can use the bcp tool to create just the subset of Boost that you need.</p>

ContentLicense: CC BY-SA 2.5

Title: Compiling a specific boost library


问:
Lazy Loading ngModules with own routes
I have this scenario.

I have two Angular Modules: AuthModule and DashModule. Each of these modules have their own .routing.tsfiles.

Then, each of the modules are imported into the AppModule at the appwide level.

In code, here:

auth.module.ts is at src/app/auth/auth.module.ts

auth.module.ts

```<code>import { NgModule } from '@angular/core';
... // all necessary imports
import { AuthRoutingModule } from './auth-module.routing';

@NgModule({
  imports: [
    CommonModule,
    AuthRoutingModule
  ],
  declarations: [
    // all declarations
  ],
  providers: []
})

export class AuthModule { }
</code>```

src/app/auth/auth-module.routing.ts

```<code>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
// all necessary imports

const routes: Routes = [
    { path: 'not-verified', component: NotVerifiedComponent },
    { path: 'login', component: LoginRegisterComponent },
    { path: 'register', component: LoginRegisterComponent },
    { path: 'verify-email/:token', component: VerifyEmailComponent },
    { path: 'reset-password/:token', component: ResetPasswordComponenet },
    { path: 'forgot', component: ForgotComponent },
  ];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule],
  providers: []
})
export class AuthRoutingModule { }
</code>```

The DashModule also follow a similar pattern as the AuthModule

My src/app/app.routing.ts looks like this:

```<code>import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { NotfoundComponent } from './pages/notfound/notfound.component';

const appRoutes: Routes = [
  // this is more like a catchall route. if all routes fail
  {path: '**', component: NotfoundComponent },
];

export const AppRouting: ModuleWithProviders = RouterModule.forRoot(appRoutes);
</code>```

My src/app/app.module.ts looks like this:

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { AppRouting } from './app.routing';

import { AuthModule } from './auth/auth.module';
import { DashModule } from './dash/dash.module';
// Providers
// some providers

@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    ...
    AuthModule,
    DashModule,
    AppRouting
  ],
  exports: [  ],
  providers: [
   // providers here
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

Now, can I make both the DashModule and AuthModule lazy load? How?

答:
Lazily loaded modules are not imported into the app.module. Remove them from there, otherwise, they will not be lazy loaded. In your app.routing.ts you need to define the routes and lazy load the modules there using something like:

```<code>const appRoutes: Routes = [
  { path: 'dashbobard', loadChildren: 'src/app/dash/dashmodule.module#DashModule' },
  // or use relative paths.
  { path: 'auth', loadChildren: './auth/auth.module#AuthModule },
];
</code>```

If you're switching your application to lazily load modules, you might have to fix some of your routes, eg [routerLink]='[/some/route]'

Title: Lazy Loading ngModules with own routes

Body:
I have this scenario.

I have two Angular Modules: AuthModule and DashModule. Each of these modules have their own .routing.tsfiles.

Then, each of the modules are imported into the AppModule at the appwide level.

In code, here:

auth.module.ts is at src/app/auth/auth.module.ts

auth.module.ts

import { NgModule } from '@angular/core';
... // all necessary imports
import { AuthRoutingModule } from './auth-module.routing';

@NgModule({
  imports: [
    CommonModule,
    AuthRoutingModule
  ],
  declarations: [
    // all declarations
  ],
  providers: []
})

export class AuthModule { }

src/app/auth/auth-module.routing.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
// all necessary imports

const routes: Routes = [
    { path: 'not-verified', component: NotVerifiedComponent },
    { path: 'login', component: LoginRegisterComponent },
    { path: 'register', component: LoginRegisterComponent },
    { path: 'verify-email/:token', component: VerifyEmailComponent },
    { path: 'reset-password/:token', component: ResetPasswordComponenet },
    { path: 'forgot', component: ForgotComponent },
  ];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule],
  providers: []
})
export class AuthRoutingModule { }

The DashModule also follow a similar pattern as the AuthModule

My src/app/app.routing.ts looks like this:

import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { NotfoundComponent } from './pages/notfound/notfound.component';

const appRoutes: Routes = [
  // this is more like a catchall route. if all routes fail
  {path: '**', component: NotfoundComponent },
];

export const AppRouting: ModuleWithProviders = RouterModule.forRoot(appRoutes);

My src/app/app.module.ts looks like this:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { AppRouting } from './app.routing';

import { AuthModule } from './auth/auth.module';
import { DashModule } from './dash/dash.module';
// Providers
// some providers

@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    ...
    AuthModule,
    DashModule,
    AppRouting
  ],
  exports: [  ],
  providers: [
   // providers here
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Now, can I make both the DashModule and AuthModule lazy load? How?

Body:
Lazily loaded modules are not imported into the app.module. Remove them from there, otherwise, they will not be lazy loaded. In your app.routing.ts you need to define the routes and lazy load the modules there using something like:

const appRoutes: Routes = [
  { path: 'dashbobard', loadChildren: 'src/app/dash/dashmodule.module#DashModule' },
  // or use relative paths.
  { path: 'auth', loadChildren: './auth/auth.module#AuthModule },
];

If you're switching your application to lazily load modules, you might have to fix some of your routes, eg [routerLink]='[/some/route]'


问:
Add Two Fields That May Contain NULL - SSRS
I'm trying to add two fields that may contain a NULL value in an SSRS expression.  On records that contain a NULL, I am getting an #Error on the report interface.

I have tried to handle the NULLs with the following:

```<code>=SUM( IIF(IsNothing(Fields!TotalSale.Value),0,Fields!TotalSale.Value) + IIF(IsNothing(Fields!TotalVoidedSale.Value),0,Fields!TotalVoidedSale.Value) )
</code>```

and:

```<code>=SUM( IIF(IsNothing(Fields!TotalSale.Value),Nothing,Fields!TotalSale.Value) + IIF(IsNothing(Fields!TotalVoidedSale.Value),Nothing,Fields!TotalVoidedSale.Value) )
</code>```

And neither works.  Could someone point out what I might be doing wrong here?

答:
If this is for detail-level data, then you would want to simply remove the SUM and go with this:

```<code>=IIF(IsNothing(Fields!TotalSale.Value),0,Fields!TotalSale.Value) + IIF(IsNothing(Fields!TotalVoidedSale.Value),0,Fields!TotalVoidedSale.Value)
</code>```

If you need this expression as an aggregate, then you would need two add the two separate sums together:

```<code>=SUM(IIF(IsNothing(Fields!TotalSale.Value),0,Fields!TotalSale.Value)) + SUM(IIF(IsNothing(Fields!TotalVoidedSale.Value),0,Fields!TotalVoidedSale.Value))
</code>```

Body:
I'm trying to add two fields that may contain a NULL value in an SSRS expression.  On records that contain a NULL, I am getting an #Error on the report interface.

I have tried to handle the NULLs with the following:

=SUM( IIF(IsNothing(Fields!TotalSale.Value),0,Fields!TotalSale.Value) + IIF(IsNothing(Fields!TotalVoidedSale.Value),0,Fields!TotalVoidedSale.Value) )

and:

=SUM( IIF(IsNothing(Fields!TotalSale.Value),Nothing,Fields!TotalSale.Value) + IIF(IsNothing(Fields!TotalVoidedSale.Value),Nothing,Fields!TotalVoidedSale.Value) )

And neither works.  Could someone point out what I might be doing wrong here?

Body:
If this is for detail-level data, then you would want to simply remove the SUM and go with this:

=IIF(IsNothing(Fields!TotalSale.Value),0,Fields!TotalSale.Value) + IIF(IsNothing(Fields!TotalVoidedSale.Value),0,Fields!TotalVoidedSale.Value)

If you need this expression as an aggregate, then you would need two add the two separate sums together:

=SUM(IIF(IsNothing(Fields!TotalSale.Value),0,Fields!TotalSale.Value)) + SUM(IIF(IsNothing(Fields!TotalVoidedSale.Value),0,Fields!TotalVoidedSale.Value))


问:
Way to save type of each item
I am reading records from Excel to a POJO

I have created an enum to hold the order of each column

My question is Is it possible to save the column type as well?

so later I will pass this enum to some method it will know how to process the value based on its type...

for example:

```<code>public enum StudentInfo{
 name(0,String),
 age(1,Integer),
 height(2,Float),
 eyeColor(5,Color);
</code>```

答:
You can save the class of the expected type as a field in the enum instances. You would construct them similarly to what you have now but like:

```<code>name(0, String.class),
</code>```

Then you can have a

```<code>private Class<?> columnType;
</code>```

as a field and use that.

As an aside, by convention (see here and here), enum values are usually named in all upper case.

Title: Way to save type of each item

Body:
I am reading records from Excel to a POJO

I have created an enum to hold the order of each column

My question is Is it possible to save the column type as well?

so later I will pass this enum to some method it will know how to process the value based on its type...

for example:

public enum StudentInfo{
 name(0,String),
 age(1,Integer),
 height(2,Float),
 eyeColor(5,Color);

Body:
You can save the class of the expected type as a field in the enum instances. You would construct them similarly to what you have now but like:

name(0, String.class),

Then you can have a

private Class<?> columnType;

as a field and use that.

As an aside, by convention (see here and here), enum values are usually named in all upper case.


问:
Bootstrap 3 Collapse - changing the glyphicon in the panel heading depending on collapse state
I know that this has been asked several times but I cannot get any of the answers to work in my code.

I am using Bootstrap 3 panels and collapse to show adverts. In the basic view, only the advert heading is shown together with a chevron down glyph to indicate that there is more information.

When the user clicks on the chevron-down, the main panel body containing the advert text is shown. At this point, I would like the chevron-down glyph to change to a chevron-up glyp.

I am using the following code:

```<code><script language="JavaScript" type="text/javascript">
  $('#Advert').on('show.bs.collapse', function(){
    $('#Glyp-Advert').removeclass('glyphicon glyphicon-chevron-down').addclass('glyphicon glyphicon-chevron-up');
  });
  $('#Advert').on('hide.bs.collapse', function() {
    $('#Glyp-Advert').removeclass('glyphicon glyphicon-chevron-up').addclass('glyphicon glyphicon-chevron-down');
  });
</script>

<div class="panel panel-default">
  <div class="panel-heading">
    <h4 class="panel-title">
      <a id="Heading-Advert" data-toggle="collapse" data-parent="#accordion" href="#Advert">
        Heading
        <span class="pull-right"><span id="Glyp-Advert" class="glyphicon glyphicon-chevron-down"></span></span>
      </a>
    </h4>
  </div>
  <div id="Advert" class="panel-collapse collapse">
    <div class="panel-body">
      Advert text<br />
    </div>
  </div>
</div>
</code>```

This succeeds in displaying the main advert panel but will not change the glyph.

Any help would be appreciated. Note that the page will contain several adverts; so I intend to repeat the above code several times on the page but change the id's to contain the word 'Advert1' or 'Advert2' etc instead of just 'Advert'.

答:
You don't necessarily need Javascript.  You can do this with a few CSS styles.  Here's how I've done it.

Make sure all your panel-title a links have this class:  accordion-toggle

Add this CSS to your style sheet:

.

```<code>/* symbol for open panels */
.panel-heading .accordion-toggle:after {
    font-family: 'FontAwesome';
    content: "\f068";
    float: right;
    color: #474747;
}

/* symbol for closed panels */
.panel-heading .accordion-toggle.collapsed:after {
    content: "\f067";
}
</code>```

Note, I've used FontAwesome here, but you can change the font and characters to whatever you need, such as up and down chevrons.

Body:
I know that this has been asked several times but I cannot get any of the answers to work in my code.

I am using Bootstrap 3 panels and collapse to show adverts. In the basic view, only the advert heading is shown together with a chevron down glyph to indicate that there is more information.

When the user clicks on the chevron-down, the main panel body containing the advert text is shown. At this point, I would like the chevron-down glyph to change to a chevron-up glyp.

I am using the following code:

        Heading

      Advert text

This succeeds in displaying the main advert panel but will not change the glyph.

Any help would be appreciated. Note that the page will contain several adverts; so I intend to repeat the above code several times on the page but change the id's to contain the word 'Advert1' or 'Advert2' etc instead of just 'Advert'.

Body:
You don't necessarily need Javascript.  You can do this with a few CSS styles.  Here's how I've done it.

Make sure all your panel-title a links have this class:  accordion-toggle

Add this CSS to your style sheet:

.

/* symbol for open panels */
.panel-heading .accordion-toggle:after {
    font-family: 'FontAwesome';
    content: "\f068";
    float: right;
    color: #474747;
}

/* symbol for closed panels */
.panel-heading .accordion-toggle.collapsed:after {
    content: "\f067";
}

Note, I've used FontAwesome here, but you can change the font and characters to whatever you need, such as up and down chevrons.


Title: pandas groupby: TOP 3 values for each group

Body:
A new and more generic question has been posted in pandas groupby: TOP 3 values in each group and store in DataFrame and a working solution has been answered there.

In this example I create a dataframe df with some random data spaced 5 minutes.
I want to create a dataframe gdf (grouped df) where the 3 highest values for each hour are listed.

I.e.: from this series of values

                     VAL
TIME
2017-12-08 00:00:00   29
2017-12-08 00:05:00   56
2017-12-08 00:10:00   82
2017-12-08 00:15:00   13
2017-12-08 00:20:00   35
2017-12-08 00:25:00   53
2017-12-08 00:30:00   25
2017-12-08 00:35:00   23
2017-12-08 00:40:00   21
2017-12-08 00:45:00   12
2017-12-08 00:50:00   15
2017-12-08 00:55:00    9
2017-12-08 01:00:00   13
2017-12-08 01:05:00   87
2017-12-08 01:10:00    9
2017-12-08 01:15:00   63
2017-12-08 01:20:00   62
2017-12-08 01:25:00   52
2017-12-08 01:30:00   43
2017-12-08 01:35:00   77
2017-12-08 01:40:00   95
2017-12-08 01:45:00   79
2017-12-08 01:50:00   77
2017-12-08 01:55:00    5
2017-12-08 02:00:00   78
2017-12-08 02:05:00   41
2017-12-08 02:10:00   10
2017-12-08 02:15:00   10
2017-12-08 02:20:00   88

I am very close to the solution but I cannot find the correct syntax for the last step. What I get up to now (largest3) is:

                                           VAL
TIME                  TIME
2017-12-08 00:00:00   2017-12-08 00:10:00   82
                      2017-12-08 00:05:00   56
                      2017-12-08 00:25:00   53
2017-12-08 01:00:00   2017-12-08 01:40:00   95
                      2017-12-08 01:05:00   87
                      2017-12-08 01:45:00   79
2017-12-08 02:00:00   2017-12-08 02:20:00   88
                      2017-12-08 02:00:00   78
                      2017-12-08 02:05:00   41

from which I would like to obtain this gdf (the time when each maximum was reached is not important):

                    VAL1  VAL2  VAL3
 TIME
2017-12-08 00:00:00   82    56    53
2017-12-08 01:00:00   95    87    79
2017-12-08 02:00:00   88    78    41

This is the code:

import pandas as pd
from datetime import *
import numpy as np

# test data
df = pd.DataFrame()
date_ref = datetime(2017,12,8,0,0,0)
days = pd.date_range(date_ref, date_ref + timedelta(0.1), freq='5min')
np.random.seed(seed=1111)
data1 = np.random.randint(1, high=100, size=len(days))
df = pd.DataFrame({'TIME': days, 'VAL': data1})
df = df.set_index('TIME')
print(df)
print("----")

# groupby
group1 = df.groupby(pd.Grouper(freq='1H'))
largest3 = pd.DataFrame(group1['VAL'].nlargest(3))
print(largest3)

gdf = pd.DataFrame()
# ???? <-------------------

Thank you in advance.

Body:
NOTE: This solution works only if each group has at least 3 rows

Try the following approach:

In [59]: x = (df.groupby(pd.Grouper(freq='H'))['VAL']
                .apply(lambda x: x.nlargest(3))
                .reset_index(level=1, drop=True)
                .to_frame('VAL'))

In [60]: x
Out[60]:
                     VAL
TIME
2017-12-08 00:00:00   82
2017-12-08 00:00:00   56
2017-12-08 00:00:00   53
2017-12-08 01:00:00   95
2017-12-08 01:00:00   87
2017-12-08 01:00:00   79
2017-12-08 02:00:00   88
2017-12-08 02:00:00   78
2017-12-08 02:00:00   41

In [61]: x.set_index(np.arange(len(x)) % 3, append=True)['VAL'].unstack().add_prefix('VAL')
Out[61]:
                     VAL0  VAL1  VAL2
TIME
2017-12-08 00:00:00    82    56    53
2017-12-08 01:00:00    95    87    79
2017-12-08 02:00:00    88    78    41

Some explanation:

In [94]: x.set_index(np.arange(len(x)) % 3, append=True)
Out[94]:
                       VAL
TIME
2017-12-08 00:00:00 0   82
                    1   56
                    2   53
2017-12-08 01:00:00 0   95
                    1   87
                    2   79
2017-12-08 02:00:00 0   88
                    1   78
                    2   41

In [95]: x.set_index(np.arange(len(x)) % 3, append=True)['VAL'].unstack()
Out[95]:
                      0   1   2
TIME
2017-12-08 00:00:00  82  56  53
2017-12-08 01:00:00  95  87  79
2017-12-08 02:00:00  88  78  41