问:
C# ExecuteNonQuery Error (Connecting My.ASP Web Form to an Access DB)
I'm trying to connect my ASP.NET online registration form to  MS Access backend database. The connection code I'm using is

```<code>String connString;
connString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Z\Desktop\Comp\MyWebsite\WorkDatabase.mdb";
OleDbConnection myConnection = new  OleDbConnection(connString);
myConnection.Open();
string myQuery = "INSERT INTO Parent([Username], [FirstName], [Surname], [Email], [Mobile], [Postcode], [Password]) values('" + Usernametb.Text + "','" + Firsttnametb.Text + "','" + Surnametb.Text + "','" + Emailtb.Text + "','" + Mobiletb.Text + "','" + Postcodetb.Text + "','" + Passwordtb.Text + "')";
OleDbCommand myCommand = new OleDbCommand(myQuery, myConnection);
myCommand.ExecuteNonQuery();
myConnection.Close();

try
{
    using (myConnection)
    {
        myConnection.Open();
        myCommand.ExecuteNonQuery();
        SuccReglbl.Text = "successful registration";
    }
}
catch (Exception ex)
{
    SuccReglbl.Text = "Exception in DBHandler" + ex;
}
finally
{

}

myCommand.ExecuteNonQuery();
OleDbDataReader myReader = myCommand.ExecuteReader();
while (myReader.Read())
{

}
myConnection.Close();
</code>```

I keep getting an error when I click on the "Register" button. The error is

"ExecuteNonQuery requires an open and available Connection. The connection's current state is closed."

I'm unsure how to fix this.

答:
After executing the first query, you are closing the database connection. However, after the following try-catch block, you execute another query. And at this point, the connection has been closed.

I'd suggest to only close the database connection after all queries have been executed. This way you don't need a new connection for every single query.

Update:

I removed all closes' except the last one and the unnecessary using statements. This code should work fine:

```<code>String connString;
connString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Z\Desktop\Comp\MyWebsite\WorkDatabase.mdb";
OleDbConnection myConnection = new  OleDbConnection(connString);
myConnection.Open();
string myQuery = "INSERT INTO Parent([Username], [FirstName], [Surname], [Email], [Mobile], [Postcode], [Password]) values('" + Usernametb.Text + "','" + Firsttnametb.Text + "','" + Surnametb.Text + "','" + Emailtb.Text + "','" + Mobiletb.Text + "','" + Postcodetb.Text + "','" + Passwordtb.Text + "')";
OleDbCommand myCommand = new OleDbCommand(myQuery, myConnection);
myCommand.ExecuteNonQuery();

try
{
    myCommand.ExecuteNonQuery();
    SuccReglbl.Text = "successful registration";
}
catch (Exception ex)
{
    SuccReglbl.Text = "Exception in DBHandler" + ex;
}
finally
{

}

myCommand.ExecuteNonQuery();
OleDbDataReader myReader = myCommand.ExecuteReader();
while (myReader.Read())
{

}
myConnection.Close();
</code>```

Body:
I'm trying to connect my ASP.NET online registration form to  MS Access backend database. The connection code I'm using is

String connString;
connString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Z\Desktop\Comp\MyWebsite\WorkDatabase.mdb";
OleDbConnection myConnection = new  OleDbConnection(connString);
myConnection.Open();
string myQuery = "INSERT INTO Parent([Username], [FirstName], [Surname], [Email], [Mobile], [Postcode], [Password]) values('" + Usernametb.Text + "','" + Firsttnametb.Text + "','" + Surnametb.Text + "','" + Emailtb.Text + "','" + Mobiletb.Text + "','" + Postcodetb.Text + "','" + Passwordtb.Text + "')";
OleDbCommand myCommand = new OleDbCommand(myQuery, myConnection);
myCommand.ExecuteNonQuery();
myConnection.Close();

try
{
    using (myConnection)
    {
        myConnection.Open();
        myCommand.ExecuteNonQuery();
        SuccReglbl.Text = "successful registration";
    }
}
catch (Exception ex)
{
    SuccReglbl.Text = "Exception in DBHandler" + ex;
}
finally
{

}

myCommand.ExecuteNonQuery();
OleDbDataReader myReader = myCommand.ExecuteReader();
while (myReader.Read())
{

}
myConnection.Close();

I keep getting an error when I click on the "Register" button. The error is

"ExecuteNonQuery requires an open and available Connection. The connection's current state is closed."

I'm unsure how to fix this.

Body:
After executing the first query, you are closing the database connection. However, after the following try-catch block, you execute another query. And at this point, the connection has been closed.

I'd suggest to only close the database connection after all queries have been executed. This way you don't need a new connection for every single query.

Update:

I removed all closes' except the last one and the unnecessary using statements. This code should work fine:

String connString;
connString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Z\Desktop\Comp\MyWebsite\WorkDatabase.mdb";
OleDbConnection myConnection = new  OleDbConnection(connString);
myConnection.Open();
string myQuery = "INSERT INTO Parent([Username], [FirstName], [Surname], [Email], [Mobile], [Postcode], [Password]) values('" + Usernametb.Text + "','" + Firsttnametb.Text + "','" + Surnametb.Text + "','" + Emailtb.Text + "','" + Mobiletb.Text + "','" + Postcodetb.Text + "','" + Passwordtb.Text + "')";
OleDbCommand myCommand = new OleDbCommand(myQuery, myConnection);
myCommand.ExecuteNonQuery();

try
{
    myCommand.ExecuteNonQuery();
    SuccReglbl.Text = "successful registration";
}
catch (Exception ex)
{
    SuccReglbl.Text = "Exception in DBHandler" + ex;
}
finally
{

}

myCommand.ExecuteNonQuery();
OleDbDataReader myReader = myCommand.ExecuteReader();
while (myReader.Read())
{

}
myConnection.Close();


来源: stackexchange

答:
YOu couold use a join on grouped  by result </p>

```<code>select a.id, b.min_time time, b.min_time Start, max_time Stop
from my_table a
inner join (
select date(time) date, hour(time) hour, min(time) min_time, max(time) max_time
from my_table
group by date(time), hour(time)
) b on date(a.time) = b.date and hour(a.time) = b.hour
</code>```

ContentLicense: CC BY-SA 3.0

Title: SQL query to reduce,delete unnecessary rows

Body:
I want to achieve this

ID      | NAME | CODE | TIME                  | Start               | Stop
--------|------|------|-----------------------|---------------------|------------
4B37B930| EV   | FI   | 2017-10-20 08:30:00   | 2017-10-20 08:30:00 | 2017-10-20 08:34:00
3333E8C4| HK   | FI   | 2017-10-20 12:33:00   | 2017-10-20 12:33:00 | 2017-10-20 12:36:00
EF84D06D| HK   | SE   | 2017-10-20 12:37:00   | 2017-10-20 12:37:00 | 2017-10-20 12:39:00

from these rows in the same table

ID      | NAME | CODE | TIME                  | Start     | Stop
--------|------|------|-----------------------|-----------|------------
4B37B930| EV   | FI   | 2017-10-20 08:30:00   |           |
7AA6E032| EV   | FI   | 2017-10-20 08:33:00   |           |
B59D4931| EV   | FI   | 2017-10-20 08:34:00   |           |
3333E8C4| HK   | FI   | 2017-10-20 12:33:00   |           |
1C4890A1| HK   | FI   | 2017-10-20 12:34:00   |           |
AA246243| HK   | FI   | 2017-10-20 12:35:00   |           |
A99DFF3C| HK   | FI   | 2017-10-20 12:36:00   |           |
EF84D06D| HK   | SE   | 2017-10-20 12:37:00   |           |
1D8C4963| HK   | SE   | 2017-10-20 12:38:00   |           |
0358656B| HK   | SE   | 2017-10-20 12:39:00   |           |

That is to delete rows if they are within 5 min and have same NAME and CODE value in the table. Please notice that it is ok for upto 5 consecutive rows to be missing, in this case rows with TIME value 08:31, 08:32 are missing but still I want the first three rows from table 2 to be replaced with one row as shown in table 1 row 1, and similarly, rows 4-7 from table 2 to be replaced with row 2 in table 1 and so on.

Here is a link so SQL fiddle
http://sqlfiddle.com/#!9/44af04/1/0

Body:
YOu couold use a join on grouped  by result

select a.id, b.min_time time, b.min_time Start, max_time Stop
from my_table a
inner join (
select date(time) date, hour(time) hour, min(time) min_time, max(time) max_time
from my_table
group by date(time), hour(time)
) b on date(a.time) = b.date and hour(a.time) = b.hour


问:
How to create region indicator variables from a state list in R
I have a variable that lists which states each company are active in. I am hoping to be able to create some kind of region (west, south, midwest etc.) variable. In this case, it is possible for each company to be in more than one region.

My approach so far has been to define region vectors, and then try to define indicator variables (dat$westYN, dat$southYN, etc) with 1 if that company operates in a state in that region and 0 otherwise.

I have used str_split to break apart the state character strings, but I am struggling with how to work with the resulting list.

In this case, it is working when dat$state is a single value, but not when there are multiple states.

Any help would be greatly appreciated!

```<code>id <- 1:20
state <- c("NJ, NY",
       "ID, OR",
       "CA",
       "FL, MO, NC, RI",
       "TX DE, KY, MD, MA, NH, NJ, PA, RI, WV",
       "FL, KY, TN",
       "DC, MD, VA",
       "NY",
       "AZ, NM",
       "FL, NJ, NY",
       "IN, MI",
       "GA, SC",
       "NV",
       "AR, CO, KY, MO, TN, TX",
       "OH",
       "NC",
       "FL",
       "IL",
       "AZ",
       "CA, CT, IL, MA, OH, PA, UT, WV"
       )

dat <- data.frame(id, state)

west <- c("WA", "OR", "CA", "NV", "AZ", "ID", "MT", "WY",
      "CO", "NM", "UT")
south <- c("TX", "OK", "AR", "LA", "MS", "AL", "TN", "KY",
       "GA", "FL", "SC", "NC", "VA", "WV")
midwest <- c("KS", "NE", "SD", "ND", "MN", "MO", "IA", "IL",
         "IN", "MI", "WI", "OH")
northeast <- c("ME", "NH", "NY", "MA", "RI", "VT", "PA",
           "NJ", "CT", "DE", "MD", "DC")

stateList <- stringr::str_split(dat$state, ",")

dat$westYN <- ifelse(is.element(stateList, west), 1, 0)
dat$southYN <- ifelse(is.element(stateList, south), 1, 0)
dat$midwestYN <- ifelse(is.element(stateList, midwest), 1, 0)
dat$northeastYN <- ifelse(is.element(stateList, northeast), 1, 0)
</code>```

答:
First, I think you are better off storing related information in a list rather than separate variables

```<code>regions <- list(
  west = c("WA", "OR", "CA", "NV", "AZ", "ID", "MT", "WY",
          "CO", "NM", "UT"),
  south = c("TX", "OK", "AR", "LA", "MS", "AL", "TN", "KY",
           "GA", "FL", "SC", "NC", "VA", "WV"),
  midwest = c("KS", "NE", "SD", "ND", "MN", "MO", "IA", "IL",
             "IN", "MI", "WI", "OH"),
  northeast = c("ME", "NH", "NY", "MA", "RI", "VT", "PA",
              "NJ", "CT", "DE", "MD", "DC")
)
</code>```

Then you can more easily do a loop to create your variables

```<code>for(region in names(regions)) {
  dat[[paste0(region, "YN")]] <-sapply(stateList, function(x) any(trimws(x) %in% regions[[region]]))
}
</code>```

Or using the regular vairables

```<code>dat$westYN <- sapply(stateList, function(x) any(x %in% west))
dat$southYN <- sapply(stateList, function(x) any(x %in% south))
dat$midwestYN <- sapply(stateList, function(x) any(x %in% midwest))
dat$northeastYN <- sapply(stateList, function(x) any(x %in% northeast))
</code>```

The trick is to use any() to see if any of the values match one of the states in each region.

Body:
I have a variable that lists which states each company are active in. I am hoping to be able to create some kind of region (west, south, midwest etc.) variable. In this case, it is possible for each company to be in more than one region.

My approach so far has been to define region vectors, and then try to define indicator variables (dat$westYN, dat$southYN, etc) with 1 if that company operates in a state in that region and 0 otherwise.

I have used str_split to break apart the state character strings, but I am struggling with how to work with the resulting list.

In this case, it is working when dat$state is a single value, but not when there are multiple states.

Any help would be greatly appreciated!

id <- 1:20
state <- c("NJ, NY",
       "ID, OR",
       "CA",
       "FL, MO, NC, RI",
       "TX DE, KY, MD, MA, NH, NJ, PA, RI, WV",
       "FL, KY, TN",
       "DC, MD, VA",
       "NY",
       "AZ, NM",
       "FL, NJ, NY",
       "IN, MI",
       "GA, SC",
       "NV",
       "AR, CO, KY, MO, TN, TX",
       "OH",
       "NC",
       "FL",
       "IL",
       "AZ",
       "CA, CT, IL, MA, OH, PA, UT, WV"
       )

dat <- data.frame(id, state)

west <- c("WA", "OR", "CA", "NV", "AZ", "ID", "MT", "WY",
      "CO", "NM", "UT")
south <- c("TX", "OK", "AR", "LA", "MS", "AL", "TN", "KY",
       "GA", "FL", "SC", "NC", "VA", "WV")
midwest <- c("KS", "NE", "SD", "ND", "MN", "MO", "IA", "IL",
         "IN", "MI", "WI", "OH")
northeast <- c("ME", "NH", "NY", "MA", "RI", "VT", "PA",
           "NJ", "CT", "DE", "MD", "DC")

stateList <- stringr::str_split(dat$state, ",")

dat$westYN <- ifelse(is.element(stateList, west), 1, 0)
dat$southYN <- ifelse(is.element(stateList, south), 1, 0)
dat$midwestYN <- ifelse(is.element(stateList, midwest), 1, 0)
dat$northeastYN <- ifelse(is.element(stateList, northeast), 1, 0)

Body:
First, I think you are better off storing related information in a list rather than separate variables

regions <- list(
  west = c("WA", "OR", "CA", "NV", "AZ", "ID", "MT", "WY",
          "CO", "NM", "UT"),
  south = c("TX", "OK", "AR", "LA", "MS", "AL", "TN", "KY",
           "GA", "FL", "SC", "NC", "VA", "WV"),
  midwest = c("KS", "NE", "SD", "ND", "MN", "MO", "IA", "IL",
             "IN", "MI", "WI", "OH"),
  northeast = c("ME", "NH", "NY", "MA", "RI", "VT", "PA",
              "NJ", "CT", "DE", "MD", "DC")
)

Then you can more easily do a loop to create your variables

for(region in names(regions)) {
  dat[[paste0(region, "YN")]] <-sapply(stateList, function(x) any(trimws(x) %in% regions[[region]]))
}

Or using the regular vairables

dat$westYN <- sapply(stateList, function(x) any(x %in% west))
dat$southYN <- sapply(stateList, function(x) any(x %in% south))
dat$midwestYN <- sapply(stateList, function(x) any(x %in% midwest))
dat$northeastYN <- sapply(stateList, function(x) any(x %in% northeast))

The trick is to use any() to see if any of the values match one of the states in each region.


问:
Parameter change with percentage
I have this assignment to make a class that creates product in a store.

One of the requirements is a method that changes the price according to a discount or increase percentage.

This is the method:

```<code>public void changePrice(double percent) {

    if ( percent > 0) {
        _price+= ((_price * percent) /100);
    }
    else if (percent < 0) {
        _price-= ((_price * percent) /100);

    }
    else {
    }
}
</code>```

for some reason it does not recognize negative numbers, and treats them like positive.
I tried a couple of variations of this with same results.

答:
The if, else if is negating the minus in percent

```<code>public void changePrice(double percent) {
    _price+= ((_price * percent) /100);
}
</code>```

If percent is +10% the price would increase by 10%
similarly if percent is -10% the price will reduce by 10%

Title: Parameter change with percentage

Body:
I have this assignment to make a class that creates product in a store.

One of the requirements is a method that changes the price according to a discount or increase percentage.

This is the method:

public void changePrice(double percent) {

    if ( percent > 0) {
        _price+= ((_price * percent) /100);
    }
    else if (percent < 0) {
        _price-= ((_price * percent) /100);

    }
    else {
    }
}

for some reason it does not recognize negative numbers, and treats them like positive.
I tried a couple of variations of this with same results.

Body:
The if, else if is negating the minus in percent

public void changePrice(double percent) {
    _price+= ((_price * percent) /100);
}

If percent is +10% the price would increase by 10%
similarly if percent is -10% the price will reduce by 10%


问:
How to check if template argument is a callable with a given signature
Basically, what I want to achieve is compile-time verification (with possibly nice error message) that registered callable (either a function, a lambda, a struct with call operator) has correct signature. Example (contents of the static_assert are to be filled):

```<code>struct A {
  using Signature = void(int, double);

  template <typename Callable>
  void Register(Callable &&callable) {
    static_assert(/* ... */);
    callback = callable;
  }

  std::function<Signature> callback;
};
</code>```

答:
You can use std::is_convertible (since C++11), e.g.

```<code>static_assert(std::is_convertible_v<Callable&&, std::function<Signature>>, "Wrong Signature!");
</code>```

or

```<code>static_assert(std::is_convertible_v<decltype(callable), decltype(callback)>, "Wrong Signature!");
</code>```

LIVE

Body:
Basically, what I want to achieve is compile-time verification (with possibly nice error message) that registered callable (either a function, a lambda, a struct with call operator) has correct signature. Example (contents of the static_assert are to be filled):

struct A {
  using Signature = void(int, double);

  template <typename Callable>
  void Register(Callable &&callable) {
    static_assert(/* ... */);
    callback = callable;
  }

  std::function<Signature> callback;
};

Body:
You can use std::is_convertible (since C++11), e.g.

static_assert(std::is_convertible_v<Callable&&, std::function<Signature>>, "Wrong Signature!");

or

static_assert(std::is_convertible_v<decltype(callable), decltype(callback)>, "Wrong Signature!");

LIVE


问:
Discovering Protractor / jasmine tests in Test explorer of Visual studio?
I have an application written in angular and i have developed my app with angular-cli.
I have unit tests written using jasmine and E2E tests in protractor.

Is there a way i can discover my tests in Test explorer of Visual studio?

Is there a way i can associate the unit tests and protractor tests with test cases / work item in visual studio?

This is needed for generating test reports and to trace back the unit tests and E2E tests to the backlog items/ requirements in VSTS.

Additional info:
I have added my protractor tests in nodejs project.
The unit test are part of the angular application created with angular-cli.

I am using Visual studio 2017. Please let me know if more information is needed.

Any help would be appreciated.

Thanks in advance!

答:
I will plus WebStorm as well. The big advantage they provide is Test runner window where you can visually see which tests failed/passed, easily navigate to the line of fail. All can be configured via GUI. They have predefined config for Protractor, Karma, etc

Visual Studio Code is very clean and fast but it misses some GUI tools. You can configure anything but you will have to do it from command line. It is free though.


问:
How to pass an object from one controller to another controller
I want to pass the object (that is placed in the model of a function in the first controller) to be received by a function of the second controller and place the received object in the function's model.

I understand that HTTP is stateless but is there a way to pass an object from one controller to another without using sessions in Spring MVC? Thanks.

Please see the sample code that I have given below.

FirstController.java

```<code>@RequestMapping(value="search-user",method=RequestMethod.POST)
public ModelAndView searchUser (HttpServletRequest request) {
    //Retrieve the search query by request.getParameter
    String searchQuery = request.getParameter("searchQuery");

    //Search for the user (this is the object that I want to pass)
    User user = userDao.searchUser(searchQuery);

    ModelAndView mav = new ModelAndView(new RedirectView("display-searched-user"));
    mav.addObject("user",user);

    return mav;
}
</code>```

SecondController.java

```<code>@RequestMapping(value="display-searched-user",method={RequestMethod.GET,RequestMethod.POST})
public ModelAndView displayResultUser (HttpServletRequest request) {
    ModelAndView mav = new ModelAndView();
    mav.setViewName("result");

    //I want to receive the object from the FirstController and set that object in this function's model.

    return mav;
}
</code>```

答:
You can achieve this with RedirectAttributes and ModelAttribute.

Normally I'd say just use flash attributes but since those are stored in the session and you wanted to do this without a session you'll have to do this with regular attributes.

Actually, after reading your code again I think what you really want to do is to use a session and flash attributes. Not using one is less secure (trusting the client to carry the user object) and/or error-prone.

Redirect attributes work by adding the redirect attributes as parameters on the redirect URL and to send anything more complex than simple strings, ints, doubles, etc. we need to serialize it first. Here I do this by turning the object into JSON and then Base64-encoding it.

Here's a complete, working example:

```<code>@Controller
@SpringBootApplication
public class RedirectController {

    @Autowired
    private ObjectMapper objectMapper;

    // Bean for converting from TestThing to base64 encoded string
    @Bean
    public Converter<TestThing, String> testThingToStringConverter() {
        return new Converter<TestThing, String>() {
            public String convert(TestThing thing) {
                try {
                    return Base64.getUrlEncoder().encodeToString(
                            objectMapper.writeValueAsString(thing)
                                    .getBytes(StandardCharsets.UTF_8));
                } catch (IOException e){
                    throw new RuntimeException(e);
                }
            }
        };
    }

    // Bean for converting from base64 encoded string to TestThing
    @Bean
    public Converter<String, TestThing> stringToTestThingConverter() {
        return new Converter<String, TestThing>() {
            public TestThing convert(String thing) {
                try {
                    return objectMapper.readValue(Base64.getUrlDecoder().decode(thing), TestThing.class);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        };
    }

    public static class TestThing implements Serializable {

        private String firstString;
        private String secondString;

        public String getFirstString() {
            return firstString;
        }

        public void setFirstString(String firstString) {
            this.firstString = firstString;
        }

        public String getSecondString() {
            return secondString;
        }

        public void setSecondString(String secondString) {
            this.secondString = secondString;
        }
    }

    @GetMapping("/test")
    public String testValidation(@RequestParam String firstString,
                                 @RequestParam String secondString,
                                 RedirectAttributes redirectAttributes) {
        TestThing redirectObject = new TestThing();
        redirectObject.firstString = firstString;
        redirectObject.secondString = secondString;

        redirectAttributes.addAttribute("redirectObject", redirectObject);

        return "redirect:/redirected";
    }

    @ResponseBody
    @GetMapping("/redirected")
    public TestThing redirected(@ModelAttribute("redirectObject") TestThing thing) {
        return thing;
    }
    public static void main(String[] args) {
        SpringApplication.run(RedirectController.class, args);
    }
}
</code>```

If we talk to our controller with Curl we can see that it works:

```<code># -L follows redirects
$ curl -L "localhost:8080/test?firstString=first&secondString=second
{"firstString":"first","secondString":"second"}%

# Now let's do it manually
curl -v "localhost:8080/test?firstString=first&secondString=second"
*   Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 8080 (#0)
> GET /test?firstString=first&secondString=second HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.57.0
> Accept: */*
>
< HTTP/1.1 302
< Location: http://localhost:8080/redirected?redirectObject=eyJmaXJzdFN0cmluZyI6ImZpcnN0Iiwic2Vjb25kU3RyaW5nIjoic2Vjb25kIn0%3D
< Content-Language: en-GB
< Content-Length: 0
< Date: Thu, 07 Dec 2017 15:38:02 GMT
<
* Connection #0 to host localhost left intact

$ curl http://localhost:8080/redirected\?redirectObject\=eyJmaXJzdFN0cmluZyI6ImZpcnN0Iiwic2Vjb25kU3RyaW5nIjoic2Vjb25kIn0%3D
{"firstString":"first","secondString":"second"}
</code>```

If you use flash attributes instead, the example is the same but you don't need the two Converters and you use addFlashAttribute instead of addAttribute.

Body:
I want to pass the object (that is placed in the model of a function in the first controller) to be received by a function of the second controller and place the received object in the function's model.

I understand that HTTP is stateless but is there a way to pass an object from one controller to another without using sessions in Spring MVC? Thanks.

Please see the sample code that I have given below.

FirstController.java

@RequestMapping(value="search-user",method=RequestMethod.POST)
public ModelAndView searchUser (HttpServletRequest request) {
    //Retrieve the search query by request.getParameter
    String searchQuery = request.getParameter("searchQuery");

    //Search for the user (this is the object that I want to pass)
    User user = userDao.searchUser(searchQuery);

    ModelAndView mav = new ModelAndView(new RedirectView("display-searched-user"));
    mav.addObject("user",user);

    return mav;
}

SecondController.java

@RequestMapping(value="display-searched-user",method={RequestMethod.GET,RequestMethod.POST})
public ModelAndView displayResultUser (HttpServletRequest request) {
    ModelAndView mav = new ModelAndView();
    mav.setViewName("result");

    //I want to receive the object from the FirstController and set that object in this function's model.

    return mav;
}

Body:
You can achieve this with RedirectAttributes and ModelAttribute.

Normally I'd say just use flash attributes but since those are stored in the session and you wanted to do this without a session you'll have to do this with regular attributes.

Actually, after reading your code again I think what you really want to do is to use a session and flash attributes. Not using one is less secure (trusting the client to carry the user object) and/or error-prone.

Redirect attributes work by adding the redirect attributes as parameters on the redirect URL and to send anything more complex than simple strings, ints, doubles, etc. we need to serialize it first. Here I do this by turning the object into JSON and then Base64-encoding it.

Here's a complete, working example:

@Controller
@SpringBootApplication
public class RedirectController {

    @Autowired
    private ObjectMapper objectMapper;

    // Bean for converting from TestThing to base64 encoded string
    @Bean
    public Converter<TestThing, String> testThingToStringConverter() {
        return new Converter<TestThing, String>() {
            public String convert(TestThing thing) {
                try {
                    return Base64.getUrlEncoder().encodeToString(
                            objectMapper.writeValueAsString(thing)
                                    .getBytes(StandardCharsets.UTF_8));
                } catch (IOException e){
                    throw new RuntimeException(e);
                }
            }
        };
    }

    // Bean for converting from base64 encoded string to TestThing
    @Bean
    public Converter<String, TestThing> stringToTestThingConverter() {
        return new Converter<String, TestThing>() {
            public TestThing convert(String thing) {
                try {
                    return objectMapper.readValue(Base64.getUrlDecoder().decode(thing), TestThing.class);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        };
    }

    public static class TestThing implements Serializable {

        private String firstString;
        private String secondString;

        public String getFirstString() {
            return firstString;
        }

        public void setFirstString(String firstString) {
            this.firstString = firstString;
        }

        public String getSecondString() {
            return secondString;
        }

        public void setSecondString(String secondString) {
            this.secondString = secondString;
        }
    }

    @GetMapping("/test")
    public String testValidation(@RequestParam String firstString,
                                 @RequestParam String secondString,
                                 RedirectAttributes redirectAttributes) {
        TestThing redirectObject = new TestThing();
        redirectObject.firstString = firstString;
        redirectObject.secondString = secondString;

        redirectAttributes.addAttribute("redirectObject", redirectObject);

        return "redirect:/redirected";
    }

    @ResponseBody
    @GetMapping("/redirected")
    public TestThing redirected(@ModelAttribute("redirectObject") TestThing thing) {
        return thing;
    }
    public static void main(String[] args) {
        SpringApplication.run(RedirectController.class, args);
    }
}

If we talk to our controller with Curl we can see that it works:

# -L follows redirects
$ curl -L "localhost:8080/test?firstString=first&secondString=second
{"firstString":"first","secondString":"second"}%

# Now let's do it manually
curl -v "localhost:8080/test?firstString=first&secondString=second"
*   Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 8080 (#0)
> GET /test?firstString=first&secondString=second HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.57.0
> Accept: */*
>
< HTTP/1.1 302
< Location: http://localhost:8080/redirected?redirectObject=eyJmaXJzdFN0cmluZyI6ImZpcnN0Iiwic2Vjb25kU3RyaW5nIjoic2Vjb25kIn0%3D
< Content-Language: en-GB
< Content-Length: 0
< Date: Thu, 07 Dec 2017 15:38:02 GMT
<
* Connection #0 to host localhost left intact

$ curl http://localhost:8080/redirected\?redirectObject\=eyJmaXJzdFN0cmluZyI6ImZpcnN0Iiwic2Vjb25kU3RyaW5nIjoic2Vjb25kIn0%3D
{"firstString":"first","secondString":"second"}

If you use flash attributes instead, the example is the same but you don't need the two Converters and you use addFlashAttribute instead of addAttribute.


问:
Why can't programs be proven?
Why can't a computer program be proven just as a mathematical statement can?  A mathematical proof is built up on other proofs, which are built up from yet more proofs and on down to axioms - those truths truths we hold as self evident.

Computer programs don't seem to have such a structure.  If you write a computer program, how is it that you can take previous proven works and use them to show the truth of your program?  You can't since none exist.  Further, what are the axioms of programming?  The very atomic truths of the field?

I don't have good answers to the above.  But it seems software can't be proven because it is art and not science.  How do you prove a Picasso?

答:
Some parts of programs can be proved. For example, the C# compiler that statically verify and guarantee type safety, if the the compilation succeeds.
But I suspect the core of your question is to prove that a program performs correctly. Many (I do not dare say most) algorithms can be proved to be correct, but a whole program probably cannot be proved statically due to the following:

Verification requires all possible branches (calls, ifs and interupts) to be traversed, which in advanced program code has super-cubic time complexity (hence it will never complete within reasonable time).

Some programming techniques, either through making components or using reflection, makes it impossible to statically predict execution of code (i.e. you don't know how another programmer will use your library, and the compiler has a hard time predict how reflection in a consumer will invoke functionality.

And those are just some...

ContentLicense: CC BY-SA 2.5

Title: Why can't programs be proven?

OwnerDisplayName: Scofield


问:
How to initialize a static variable in a multithreaded context?
I thought up a good use of the static keyword inside a function to be something like this:

```<code>void threadSafeWrite(int *array, int writeIndex, int writeData){
    static void *threadLock = Lock_create(); //in my code locks are void* to be cross-platform compatable
    Lock_aquire(threadLock);
    array[writeIndex] = writeData;
    Lock_release(threadLock);
}
</code>```

In short it seems like a good way to make a critical section. My question is though, how do I initialize the threadLock in a threadsafe manner? The problem with the example I fear is that the lock will get allocated multiple times and each thread will use a different lock. Any ideas on how to fix this? Seems like a chicken and egg problem. I want a solution (or solutions) which work with both pthreads and windows threads.

EDIT: the reason I want this functionality is because it provides a non-intrusive way to test whether there is a difference when running a piece of code single-threaded or multithreaded (meant for debug purposes).

答:
There are various options:

Manually call the initialization code at a safe time (e.g. before exposing the code to additional threads).

Use pthread_once() or equivalent, which will ensure the initialization code is called once and all subsequent callers see its effects.

Use a static initialization of the lock that does not involve calling any function. For example, using pthreads

```<code>static pthread_mutex_t mylock = PTHREAD_MUTEX_INITIALIZER;
</code>```

Body:
I thought up a good use of the static keyword inside a function to be something like this:

void threadSafeWrite(int *array, int writeIndex, int writeData){
    static void *threadLock = Lock_create(); //in my code locks are void* to be cross-platform compatable
    Lock_aquire(threadLock);
    array[writeIndex] = writeData;
    Lock_release(threadLock);
}

In short it seems like a good way to make a critical section. My question is though, how do I initialize the threadLock in a threadsafe manner? The problem with the example I fear is that the lock will get allocated multiple times and each thread will use a different lock. Any ideas on how to fix this? Seems like a chicken and egg problem. I want a solution (or solutions) which work with both pthreads and windows threads.

EDIT: the reason I want this functionality is because it provides a non-intrusive way to test whether there is a difference when running a piece of code single-threaded or multithreaded (meant for debug purposes).

Body:
There are various options:

Manually call the initialization code at a safe time (e.g. before exposing the code to additional threads).

Use pthread_once() or equivalent, which will ensure the initialization code is called once and all subsequent callers see its effects.

Use a static initialization of the lock that does not involve calling any function. For example, using pthreads

static pthread_mutex_t mylock = PTHREAD_MUTEX_INITIALIZER;


问:
Referring to a concept in a not-imported ontology
I want to refer to concepts defined in other ontologies, using only the respective concepts URI, without importing the outer ontology. I think that this is compatible with OWL semantics, using owl:equivalentTo property.

Can somebody confirm that this is correct? Furthermore, could someone provide me with an example on how to do it (preferably using Protege)?

答: The only way you can refer to concepts in an external ontology is by importing it. After you have imported it you can use owl:equivalentTo to assert that say the Identity concept in your ontology is equivalent to the external:ID concept of the external ontology.


问:
Unable to click Submit button using python-Selenium
I am trying to extract a value from google search using selenium web automation.

```<code>from selenium import webdriver
import time
import os

#open googole.com
driver = webdriver.Chrome()
time.sleep(2)
driver.get("https://www.google.co.in")

#search for bitcoin exchange rates
elem = driver.find_element_by_id("lst-ib")
elem.clear()
time.sleep(2)
elem.send_keys("bitcoin exchange rates")
time.sleep(2)
driver.find_element_by_name("btnK").click()

time.sleep(2)

#Store the value in a variable
rate = driver.find_element_by_xpath('//*[@id="rso"]/div[1]/div/div/div[2]/span[1]')

RateValue = rate.text
TodayDate = time.strftime("%x")
</code>```

This works perfectly with Firefox browser. However, I am getting the following error when I run it with Chrome:

self.error_handler.check_response(response)
    File "C:\Users\Alauddeen\AppData\Local\Programs\Python\Python36-32\Lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 194, in check_response
      raise exception_class(message, screen, stacktrace)
  selenium.common.exceptions.WebDriverException: Message: unknown error: Element  is not clickable at point (440, 411). Other element would receive the click: ...
    (Session info: chrome=62.0.3202.94)
    (Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 6.1.7601 SP1 x86)

Is there something I'm missing here? Any help is appreciated.

Thanks!

答:
There is probably a search suggestion box on top of the btnK, hiding it from sight so it can’t be clicked.

Use something like

```<code>elem.send_keys(Keys.ENTER)
</code>```

Or

```<code>elem.send_keys(Keys.ESCAPE)
</code>```

after sending your search text to the input to make the suggestion box go away.

Body:
I am trying to extract a value from google search using selenium web automation.

from selenium import webdriver
import time
import os

#open googole.com
driver = webdriver.Chrome()
time.sleep(2)
driver.get("https://www.google.co.in")

#search for bitcoin exchange rates
elem = driver.find_element_by_id("lst-ib")
elem.clear()
time.sleep(2)
elem.send_keys("bitcoin exchange rates")
time.sleep(2)
driver.find_element_by_name("btnK").click()

time.sleep(2)

#Store the value in a variable
rate = driver.find_element_by_xpath('//*[@id="rso"]/div[1]/div/div/div[2]/span[1]')

RateValue = rate.text
TodayDate = time.strftime("%x")

This works perfectly with Firefox browser. However, I am getting the following error when I run it with Chrome:

self.error_handler.check_response(response)
    File "C:\Users\Alauddeen\AppData\Local\Programs\Python\Python36-32\Lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 194, in check_response
      raise exception_class(message, screen, stacktrace)
  selenium.common.exceptions.WebDriverException: Message: unknown error: Element  is not clickable at point (440, 411). Other element would receive the click: ...
    (Session info: chrome=62.0.3202.94)
    (Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 6.1.7601 SP1 x86)

Is there something I'm missing here? Any help is appreciated.

Thanks!

Body:
There is probably a search suggestion box on top of the btnK, hiding it from sight so it can’t be clicked.

Use something like

elem.send_keys(Keys.ENTER)

Or

elem.send_keys(Keys.ESCAPE)

after sending your search text to the input to make the suggestion box go away.


问:
Printing at Dot Matrix printer from chrome
I made a A4 size pdf invoice using php and when I print this at dot matrix from chrome then page shrink. But when I print that pdf by downloading and opening through any pdf reader then it print in actual size. Again I tested by opening he downloaded pdf file in chrome then print, but problem is still not resolved. Is it problem of chrome browser or dot matrix printer. I am using TVS dot matrix printer.</p>

答:
this prolem is common on chrome browser, u can use mozilla instead.

chrome converts the document as image and send to printer.
dot matrix is not good on printing images and thats what happening to u.


问:
Hashed password in DB and plain password with Hash::check are not equal
I've created my accounts in CRM.

Most interesting thing is password and I've handled it creating like that:

```<code>$password = $faker->password();
$businessAccount->password = bcrypt($password);
</code>```

then I send email with this password.

and now I've created login page in my website when I want to make login using some number and password.

```<code>public function login(BusinessLoginRequest $request)
    {
        $orgNumber = $request->input('orgNumber');
        $password = $request->input('password');
        var_dump( $pass = BusinessAccounts::find('123456789')->password);
        var_dump(Hash::check($password, $pass));
        if(Auth::guard('business')->attempt(['orgNumber' => $orgNumber, 'password' => $password ])) {
                return 'Hello';
        }
        return 'no';

    }
</code>```

I'm sorry for that var_dumps, I've inserted it here to see what happen when I click "login"

Password was hashed through bcrypt and how I understand, Auth::attempt check plain password with hashed.

Okay, let's go deeper. First var_dump say me password which was stored in DB and they are equal.

Second var_dump say me "bool(false)" and last say me no, authentication failed, I think.

But when I put hashed password in my form then all is good and I see "Hello" but it's wrong.

And, of course, I've created guard and provider:

```<code>'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
        'api' => [
            'driver' => 'token',
            'provider' => 'users',
        ],
        'business' => [
            'driver' => 'session',
            'provider' => 'business'
        ]
    ],

    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\Models\Eloquent\Account::class,
        ],
        'business' => [
            'driver' => 'eloquent',
            'model'  => App\Models\Eloquent\BusinessAccounts::class
        ]
    ],
</code>```

and have changed my Model:

```<code>class BusinessAccounts extends Model implements Authenticatable
{
    use \Illuminate\Auth\Authenticatable;

    protected $table = 'business_accounts';

    protected $fillable =
        [
            'orgNumber', 'password'
        ];

    public $timestamps = false;

    protected $primaryKey = 'orgNumber';

}
</code>```

Question is: what I did wrong? How to check unhashed password? I don't want to put hashed password from my db.

答:
Try to hash in that way:

```<code>use Illuminate\Support\Facades\Hash;
</code>```

then:

```<code>'password' => Hash::make($request->newPassword)
</code>```

Body:
I've created my accounts in CRM.

Most interesting thing is password and I've handled it creating like that:

$password = $faker->password();
$businessAccount->password = bcrypt($password);

then I send email with this password.

and now I've created login page in my website when I want to make login using some number and password.

public function login(BusinessLoginRequest $request)
    {
        $orgNumber = $request->input('orgNumber');
        $password = $request->input('password');
        var_dump( $pass = BusinessAccounts::find('123456789')->password);
        var_dump(Hash::check($password, $pass));
        if(Auth::guard('business')->attempt(['orgNumber' => $orgNumber, 'password' => $password ])) {
                return 'Hello';
        }
        return 'no';

    }

I'm sorry for that var_dumps, I've inserted it here to see what happen when I click "login"

Password was hashed through bcrypt and how I understand, Auth::attempt check plain password with hashed.

Okay, let's go deeper. First var_dump say me password which was stored in DB and they are equal.

Second var_dump say me "bool(false)" and last say me no, authentication failed, I think.

But when I put hashed password in my form then all is good and I see "Hello" but it's wrong.

And, of course, I've created guard and provider:

'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
        'api' => [
            'driver' => 'token',
            'provider' => 'users',
        ],
        'business' => [
            'driver' => 'session',
            'provider' => 'business'
        ]
    ],

    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\Models\Eloquent\Account::class,
        ],
        'business' => [
            'driver' => 'eloquent',
            'model'  => App\Models\Eloquent\BusinessAccounts::class
        ]
    ],

and have changed my Model:

class BusinessAccounts extends Model implements Authenticatable
{
    use \Illuminate\Auth\Authenticatable;

    protected $table = 'business_accounts';

    protected $fillable =
        [
            'orgNumber', 'password'
        ];

    public $timestamps = false;

    protected $primaryKey = 'orgNumber';

}

Question is: what I did wrong? How to check unhashed password? I don't want to put hashed password from my db.

Body:
Try to hash in that way:

use Illuminate\Support\Facades\Hash;

then:

'password' => Hash::make($request->newPassword)


问:
Assign random letter to each variable
How can I cycle through variables and assign a random letter to each?

Without having to do:

```<code>var1 = RandomLetter();
var2 = RandomLetter();
var3 = RandomLetter();
var4 = RandomLetter();
var5 = RandomLetter();
</code>```

This will produce all having the same letter:

```<code>var1 = var2 = var3 = RandomLetter();
</code>```

I'm looking for a way to shorten the process, I need to do this to 50+ variables.

At first I though a foreach loop, but they are null and don't start out in a collection to loop through.

```<code>// Variables
public static char var1, var2, var3, var4, var5;

// Generate Random Letter
public static Random random = new Random();
public static char RandomLetter()
{
    const string text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    int index = random.Next(text.Length);
    return text[index];
}
</code>```

答:
Don't use separate variables, use a collection instead:</p>

```<code>List<char> letters =
    Enumerable.Range(1,50)
              .Select(i => RandomLetter())
              .ToList();
</code>```

Title: Assign random letter to each variable

Body:
How can I cycle through variables and assign a random letter to each?

Without having to do:

var1 = RandomLetter();
var2 = RandomLetter();
var3 = RandomLetter();
var4 = RandomLetter();
var5 = RandomLetter();

This will produce all having the same letter:

var1 = var2 = var3 = RandomLetter();

I'm looking for a way to shorten the process, I need to do this to 50+ variables.

At first I though a foreach loop, but they are null and don't start out in a collection to loop through.

// Variables
public static char var1, var2, var3, var4, var5;

// Generate Random Letter
public static Random random = new Random();
public static char RandomLetter()
{
    const string text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    int index = random.Next(text.Length);
    return text[index];
}

Body:
Don't use separate variables, use a collection instead:

List<char> letters =
    Enumerable.Range(1,50)
              .Select(i => RandomLetter())
              .ToList();


问:
how to use Google Cloud Memcach to save/update unique items
In my application I run a cron job to loop over all users (2500 user) to choose an item for every user out of 4k items, considering that:
- choosing the item is based on some user info,
- I need to make sure that each user take a unique item that wasn't taken by any one else, so relation is one-to-one

To achieve this I have to run this cron job and loop over the users one by one sequentially and pick up the item for each then remove it from the list (not to be chosen by next user(s)) then move to the next user

actually in my system the number of users/items is getting bigger and bigger every single day, this cron job now takes 2 hours to set items to all users.

I need to improve this, one of the things I've thought about is using Threads but I cant do that since Im using automatic scaling, so I start thinking about push Queues, so when the cron jobs run, will make a loop like this:

```<code>for(User user : users){
    getMyItem(user.getId());
}
</code>```

where getMyItem will push the task to a servlet to handle it and choose the best item for this person based on his data.

Let's say I'll start doing that so what will be the best/robust solution to avoid setting an item to more than one user ?

Since Im using basic scaling and 8 instances, can't rely on static variables.
one of the things that came across my mind is to create a table in the DB that accept only unique items then I insert into it the taken items so if the insertion is done successfully it means no body else took this item so i can just assign it to that person, but this will make the performance a bit lower cause I need to make write DB operation with every call (I want to avoid that)

Also I thought about MemCach, its really fast but not robust enough, if I save a Set of items into it which will accept only unique items, then if more than one thread was trying to access this Set at the same time to update it, only one thread will be able to save its data and all other threads data might be overwritten and lost.

I hope you guys can help to find a solution for this problem, thanks in advance :)

答:
If you are planning for push jobs inside a cron and you want the jobs to be updating key-value pairs as an addon to improvise the speed and performance, we can split the number of users and number of items into multiple key-(list of values) pairs so that our push jobs will pick the key random ( logic to write to pick a key out of 4 or 5 keys) and then remove an item from the list of items and update the key again, try to have a locking before working on the above part. Example of key value paris.
    Userlist1: ["vijay",...]
    Userlist2: ["ramana",...]</p>

Body:
In my application I run a cron job to loop over all users (2500 user) to choose an item for every user out of 4k items, considering that:
- choosing the item is based on some user info,
- I need to make sure that each user take a unique item that wasn't taken by any one else, so relation is one-to-one

To achieve this I have to run this cron job and loop over the users one by one sequentially and pick up the item for each then remove it from the list (not to be chosen by next user(s)) then move to the next user

actually in my system the number of users/items is getting bigger and bigger every single day, this cron job now takes 2 hours to set items to all users.

I need to improve this, one of the things I've thought about is using Threads but I cant do that since Im using automatic scaling, so I start thinking about push Queues, so when the cron jobs run, will make a loop like this:

for(User user : users){
    getMyItem(user.getId());
}

where getMyItem will push the task to a servlet to handle it and choose the best item for this person based on his data.

Let's say I'll start doing that so what will be the best/robust solution to avoid setting an item to more than one user ?

Since Im using basic scaling and 8 instances, can't rely on static variables.
one of the things that came across my mind is to create a table in the DB that accept only unique items then I insert into it the taken items so if the insertion is done successfully it means no body else took this item so i can just assign it to that person, but this will make the performance a bit lower cause I need to make write DB operation with every call (I want to avoid that)

Also I thought about MemCach, its really fast but not robust enough, if I save a Set of items into it which will accept only unique items, then if more than one thread was trying to access this Set at the same time to update it, only one thread will be able to save its data and all other threads data might be overwritten and lost.

I hope you guys can help to find a solution for this problem, thanks in advance :)


问:
Returning String from method in Java
I am trying to return the input from the user (inputname) from the method Dialog so that it can be printed in the method Print later, but I am getting the error message "exercise4.java:85: error:  expected</p>

```<code>public static String Dialog(inputname) //asks user about station and prints result"
    public static void main (String args [] )
    {
        Dialog(); // asks user about station and returns answer
        Print(); // prints station information

        System.exit(0);
    }
    // END Main method

    public static String Dialog(inputname) //asks user about station
    {
        String inputname = JOptionPane.showInputDialog("What station would you like information about?");

        return inputname;
    }

    public static void Print() //prints information
    {
        System.out.println("The name of the station is "+ inputname);
        return;
    }
}
</code>```

答:
Here:

```<code>public static String Dialog(inputname) //asks user about station
{
   String inputname = JOptionPane.showInputDialog("What station would
</code>```

...

And:

```<code>public static void Print() //prints information
{
  System.out.println("The name of the station is "+ inputname);
</code>```

The variable inputname is a local variable within the first method. It is simply not visible anywhere else - especially outside of that method. The simple solution:

```<code> public static void printName(String name) ...
</code>```

and then

```<code>   printName(getNameFromDialog())
</code>```

I took the freedom to rename your methods to be A) following Java conventions and B) tell the reader what they actually do.

Alternatively, you could declare a static field within your class, and have both methods using that field (instead of using local variables resp. parameters).

Title: Returning String from method in Java

Body:
I am trying to return the input from the user (inputname) from the method Dialog so that it can be printed in the method Print later, but I am getting the error message "exercise4.java:85: error:  expected

public static String Dialog(inputname) //asks user about station and prints result"
    public static void main (String args [] )
    {
        Dialog(); // asks user about station and returns answer
        Print(); // prints station information

        System.exit(0);
    }
    // END Main method

    public static String Dialog(inputname) //asks user about station
    {
        String inputname = JOptionPane.showInputDialog("What station would you like information about?");

        return inputname;
    }

    public static void Print() //prints information
    {
        System.out.println("The name of the station is "+ inputname);
        return;
    }
}

Body:
Here:

public static String Dialog(inputname) //asks user about station
{
   String inputname = JOptionPane.showInputDialog("What station would

...

And:

public static void Print() //prints information
{
  System.out.println("The name of the station is "+ inputname);

The variable inputname is a local variable within the first method. It is simply not visible anywhere else - especially outside of that method. The simple solution:

 public static void printName(String name) ...

and then

   printName(getNameFromDialog())

I took the freedom to rename your methods to be A) following Java conventions and B) tell the reader what they actually do.

Alternatively, you could declare a static field within your class, and have both methods using that field (instead of using local variables resp. parameters).


问:
Getting asynchronous data with AngularJS
I am designing a company page where some page elements are loaded based on the current logged user. For example, if a company logs into my application and wants to view their account details in the dashboard, the dashboard page will load the specific elements for that company(name, description etc.).
My problem is that my data does not get binded to my vm variable when I load the page. However, checking the console I see that my data is indeed being retrieved by the service, just a bit later on. Here's how I figured it out:

```<code>(function () {
'use strict';

angular.module('mainApp')
    .controller('currentCompanyCtrl',CurrentCompanyController);
CurrentCompanyController.$inject = ['CompanyService','AlertService', 'AuthService','$routeParams','$http'];
function CurrentCompanyController(CompanyService, AlertService, AuthService, $routeParams) {
    var vm = this;

    console.log(vm.company); //returns undefined
    vm.internships = getInternshipsByLoggedId();
    vm.company = getCompanyByLoggedId();
    console.log(vm); //returns two undefined objects
    for(var x in vm){
        console.log(x);
    }
    //todo find out why vm doesn't get filled earlier, probably has to do with asynchronous calls
    //do I need to return a Promise??

    //this returns the current company with the id provided by the current logged company
    //and binds it to the vm.company object
    function getCompanyByLoggedId() {
        AuthService.getCompany().then(
            function(response) {
                CompanyService.getCompanyById(response.data.id).then(
                        function success(response) {
                            vm.company = response.data;
                            console.log(response.data); //this returns the company
                        },
                        function error(response) {
                            vm.serverErrors = response.data;
                            AlertService.alertError(response.data);
                        });
            });
    }
....
</code>```

The bit that appears later is the console.log that I do inside my getCompanyByLoggedId function.

This means that the data retrieval is being handled asynchronously in the service and that I should return a Promise - from that I could read/gather from Google.
I tried using the $q from angular but to no avail. Do I need to modify my services? Currently they are as so:

```<code>(function () {
'use strict';

angular.module('mainApp')
    .factory('AuthService', AuthService);

AuthService.$inject = ['$http'];
function AuthService($http) {
    var service = {};

    service.getUser = getUser;
    service.getStudent = getStudent;
    service.getCompany = getCompany;

    return service;

    function getUser() {
        return $http.post('/api/user');
    }
    function getStudent() {
        return $http.post('/api/student');
    }
    function getCompany() {
        return $http.post('/api/company');
    }
}
})();
</code>```

And

```<code>(function () {
'use strict';

angular.module('mainApp')
    .factory('CompanyService', CompanyService);

CompanyService.$inject = ['$http'];
function CompanyService($http) {
    var service = {};

    service.getCompanyById = getCompanyById;
    service.getById = getById;
    return service;

    function getCompanyById(id) {
        return $http.get('api/companies/'+id);
    }

    function getById(id) {
        return $http.get('api/companies/'+id+'/internships');
    }
}
})();
</code>```

So basically I want to be able to bind data to my vm object so I can display it in my page. How do I do this if my data only arrives later on?

答:
You have few issues here. You are not returning the value

First you could do something like this, Return and maybe you will get values. (MAYBE? Cuz sometimes there is a delay of 2-3 seconds, At least I have seen it in my case)

```<code>getCompanyByLoggedId().then((data)=>{vm.company = data});

....
//Return your promises and make a chain of it
function getCompanyByLoggedId() {
    return AuthService.getCompany().then(
        function(response) {
            return CompanyService.getCompanyById(response.data.id).then(
                    function success(response) {
                        return response.data;
                    },
                    function error(response) {
                        AlertService.alertError(response.data);
                        return response.data;
                    });
        });
}
</code>```

What I do? I use $q.defer, You could read about it here https://docs.angularjs.org/api/ng/service/$q

```<code>getCompanyByLoggedId().then((data)=>{vm.company = data});
....

function getCompanyByLoggedId() {
    var defer = $q.defer();//Create a defer obj which will return when resolved or rejected
    AuthService.getCompany().then(
        function(response) {
            CompanyService.getCompanyById(response.data.id).then(
                    function success(response) {
                        defer.resolve(response.data);
                    },
                    function error(response) {
                        AlertService.alertError(response.data);
                        defer.reject(response.data);
                    });
        });
       return defer.promise;
}
</code>```

Body:
I am designing a company page where some page elements are loaded based on the current logged user. For example, if a company logs into my application and wants to view their account details in the dashboard, the dashboard page will load the specific elements for that company(name, description etc.).
My problem is that my data does not get binded to my vm variable when I load the page. However, checking the console I see that my data is indeed being retrieved by the service, just a bit later on. Here's how I figured it out:

(function () {
'use strict';

angular.module('mainApp')
    .controller('currentCompanyCtrl',CurrentCompanyController);
CurrentCompanyController.$inject = ['CompanyService','AlertService', 'AuthService','$routeParams','$http'];
function CurrentCompanyController(CompanyService, AlertService, AuthService, $routeParams) {
    var vm = this;

    console.log(vm.company); //returns undefined
    vm.internships = getInternshipsByLoggedId();
    vm.company = getCompanyByLoggedId();
    console.log(vm); //returns two undefined objects
    for(var x in vm){
        console.log(x);
    }
    //todo find out why vm doesn't get filled earlier, probably has to do with asynchronous calls
    //do I need to return a Promise??

    //this returns the current company with the id provided by the current logged company
    //and binds it to the vm.company object
    function getCompanyByLoggedId() {
        AuthService.getCompany().then(
            function(response) {
                CompanyService.getCompanyById(response.data.id).then(
                        function success(response) {
                            vm.company = response.data;
                            console.log(response.data); //this returns the company
                        },
                        function error(response) {
                            vm.serverErrors = response.data;
                            AlertService.alertError(response.data);
                        });
            });
    }
....

The bit that appears later is the console.log that I do inside my getCompanyByLoggedId function.

This means that the data retrieval is being handled asynchronously in the service and that I should return a Promise - from that I could read/gather from Google.
I tried using the $q from angular but to no avail. Do I need to modify my services? Currently they are as so:

(function () {
'use strict';

angular.module('mainApp')
    .factory('AuthService', AuthService);

AuthService.$inject = ['$http'];
function AuthService($http) {
    var service = {};

    service.getUser = getUser;
    service.getStudent = getStudent;
    service.getCompany = getCompany;

    return service;

    function getUser() {
        return $http.post('/api/user');
    }
    function getStudent() {
        return $http.post('/api/student');
    }
    function getCompany() {
        return $http.post('/api/company');
    }
}
})();

And

(function () {
'use strict';

angular.module('mainApp')
    .factory('CompanyService', CompanyService);

CompanyService.$inject = ['$http'];
function CompanyService($http) {
    var service = {};

    service.getCompanyById = getCompanyById;
    service.getById = getById;
    return service;

    function getCompanyById(id) {
        return $http.get('api/companies/'+id);
    }

    function getById(id) {
        return $http.get('api/companies/'+id+'/internships');
    }
}
})();

So basically I want to be able to bind data to my vm object so I can display it in my page. How do I do this if my data only arrives later on?

Body:
You have few issues here. You are not returning the value

First you could do something like this, Return and maybe you will get values. (MAYBE? Cuz sometimes there is a delay of 2-3 seconds, At least I have seen it in my case)

getCompanyByLoggedId().then((data)=>{vm.company = data});

....
//Return your promises and make a chain of it
function getCompanyByLoggedId() {
    return AuthService.getCompany().then(
        function(response) {
            return CompanyService.getCompanyById(response.data.id).then(
                    function success(response) {
                        return response.data;
                    },
                    function error(response) {
                        AlertService.alertError(response.data);
                        return response.data;
                    });
        });
}

What I do? I use $q.defer, You could read about it here https://docs.angularjs.org/api/ng/service/$q

getCompanyByLoggedId().then((data)=>{vm.company = data});
....

function getCompanyByLoggedId() {
    var defer = $q.defer();//Create a defer obj which will return when resolved or rejected
    AuthService.getCompany().then(
        function(response) {
            CompanyService.getCompanyById(response.data.id).then(
                    function success(response) {
                        defer.resolve(response.data);
                    },
                    function error(response) {
                        AlertService.alertError(response.data);
                        defer.reject(response.data);
                    });
        });
       return defer.promise;
}


问:
Walmart DVS API not returning products
I have been working with the walmart API for the marketplace and have everything working. Now on DVS it is not working for me. I am getting authenticated and everything but when I try to pull a list of my current listing it tells me nothing found. the same call to the marketplace works fine.
Any ideas what might be missing?

I'm using curl in PHP:

```<code>$curl = curl_init();
curl_setopt($curl, CURLOPT_HTTPHEADER, $apiheaders);
curl_setopt($curl, CURLOPT_URL,$url);
curl_setopt($curl, CURLOPT_VERBOSE, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "GET");
$response = curl_exec($curl);
</code>```

GET URL: https://api-gateway.walmart.com/v3/items?limit=10

HEADERS:

```<code>    [0] => WM_SVC.NAME: Drop Ship Vendor Services
    [1] => WM_QOS.CORRELATION_ID: xxxxxx
    [2] => WM_SEC.TIMESTAMP:xxxxxx
    [3] => WM_SEC.AUTH_SIGNATURE:xxxxxx
    [4] => WM_CONSUMER.CHANNEL.TYPE: xxxxxxx
    [5] => WM_CONSUMER.ID: xxxxxxxx
    [6] => Accept: application/xml
</code>```

I get back:

```<code>[error] => SimpleXMLElement Object
        (
            [code] => CONTENT_NOT_FOUND.GMP_ITEM_QUERY_API
            [description] => No item found
            [info] => Requested content could not be found.
            [severity] => INFO
            [category] => APPLICATION
        )
</code>```

答:
I reached out to Walmart support and apparently the V3 items AP/I is not yet up at all.
Their reply:

Thank you for the mail, Unfortunately GET Item API is currently
  unavailable to use hence you are getting Content Not Found response.

We are going to update developer portal soon with updated API detail

Title: Walmart DVS API not returning products

Body:
I have been working with the walmart API for the marketplace and have everything working. Now on DVS it is not working for me. I am getting authenticated and everything but when I try to pull a list of my current listing it tells me nothing found. the same call to the marketplace works fine.
Any ideas what might be missing?

I'm using curl in PHP:

$curl = curl_init();
curl_setopt($curl, CURLOPT_HTTPHEADER, $apiheaders);
curl_setopt($curl, CURLOPT_URL,$url);
curl_setopt($curl, CURLOPT_VERBOSE, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "GET");
$response = curl_exec($curl);

GET URL: https://api-gateway.walmart.com/v3/items?limit=10

HEADERS:

    [0] => WM_SVC.NAME: Drop Ship Vendor Services
    [1] => WM_QOS.CORRELATION_ID: xxxxxx
    [2] => WM_SEC.TIMESTAMP:xxxxxx
    [3] => WM_SEC.AUTH_SIGNATURE:xxxxxx
    [4] => WM_CONSUMER.CHANNEL.TYPE: xxxxxxx
    [5] => WM_CONSUMER.ID: xxxxxxxx
    [6] => Accept: application/xml

I get back:

[error] => SimpleXMLElement Object
        (
            [code] => CONTENT_NOT_FOUND.GMP_ITEM_QUERY_API
            [description] => No item found
            [info] => Requested content could not be found.
            [severity] => INFO
            [category] => APPLICATION
        )


问:
Connection timeout on query on large table
I have a problem with a script timing out while fetching data form a query on large table.

The table have 9,521,457 rows.

The query I'm trying to preform is:

```<code>SELECT *
FROM `dialhistory`
WHERE `customerId` IN (22606536, 22707251, 41598836);
</code>```

This query runs without problems on HeidiSQL and take about 171 seconds and returns 434 rows.

But when I run my C# script dose it timeout after 161 rows.

```<code>16:54:55: Row 1
...
16:54:55: Row 161
16:55:32: Error -> Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.
</code>```

Here is the code

```<code>public MySqlDatabase(string server, string database, string username, string password)
{
    ConnectionString = "SERVER=" + server + ";DATABASE=" + database + ";UID=" + username + ";PASSWORD=" + password + ";";

}

public IQueryable<DailHistory> GetHistory(IList<int> customerIds)
{
    IList<DailHistory> list = new List<DailHistory>();
    var connection = new MySqlConnection(ConnectionString);
    connection.Open();
    var command = connection.CreateCommand();
    command.CommandText = "SELECT * FROM `dialhistory` WHERE `customerId` in ("+string.Join(",", customerIds.ToArray())+")";
    var reader = command.ExecuteReader();
    int i = 1;
    while (reader.Read())
    {
        Console.WriteLine(DateTime.Now.ToLongTimeString() + ": Row " + i);
        i++;
        try
        {
            var d = new DailHistory();
            d.CustomerId = int.Parse((string) reader["customerId"]);
            d.Agent = ParseNullAbleString(reader["agent"].ToString());
            d.CallBackReason = ParseNullAbleString(reader["callBackReason"].ToString());
            d.CallState = ParseCallSate(reader["callState"].ToString());
            d.ContactResponse = ParseNullAbleString(reader["contactResponse"].ToString());
            d.DailTime = new DailTime(reader["dialStart"].ToString(), reader["dialEnd"].ToString());
            d.HistoryIndex = int.Parse(reader["historyIndex"].ToString());
            d.Note = ParseNullAbleString(reader["note"].ToString());
            d.OldDialNo = ParseNullAbleInt(reader["oldDialNo"].ToString());
            d.ProjectJob = ParseNullAbleString(reader["projectJob"].ToString());
            list.Add(d);
        }
        catch(Exception e)
        {
            Console.WriteLine(e.Message);
        }
    }
    reader.Close();
    return list.AsQueryable();
}
</code>```

答:
```<code>command.CommandTimeout = 2147483;
</code>```

The largest value for a MySQL command timeout is the largest value for a 32 bit integer, in milliseconds, 2147483647. But in C# the CommandTimeout property is in seconds, not milliseconds, so any higher than 2147483 will result in an exception.

Although this is not infinite, it is 24 days, 20 hours, 31 minutes, and 23 seconds, which would hopefully meet your need.

Setting the value to 0 did not work for me. The CommandTimeout property would not retain the value of 0 and kept auto-changing back to 30.

Setting the value to -1 did seem to work, but I didn't test it enough to be certain that a timeout would never occur.

Safest option: go with 2147483.

Body:
I have a problem with a script timing out while fetching data form a query on large table.

The table have 9,521,457 rows.

The query I'm trying to preform is:

SELECT *
FROM `dialhistory`
WHERE `customerId` IN (22606536, 22707251, 41598836);

This query runs without problems on HeidiSQL and take about 171 seconds and returns 434 rows.

But when I run my C# script dose it timeout after 161 rows.

16:54:55: Row 1
...
16:54:55: Row 161
16:55:32: Error -> Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.

Here is the code

public MySqlDatabase(string server, string database, string username, string password)
{
    ConnectionString = "SERVER=" + server + ";DATABASE=" + database + ";UID=" + username + ";PASSWORD=" + password + ";";

}

public IQueryable<DailHistory> GetHistory(IList<int> customerIds)
{
    IList<DailHistory> list = new List<DailHistory>();
    var connection = new MySqlConnection(ConnectionString);
    connection.Open();
    var command = connection.CreateCommand();
    command.CommandText = "SELECT * FROM `dialhistory` WHERE `customerId` in ("+string.Join(",", customerIds.ToArray())+")";
    var reader = command.ExecuteReader();
    int i = 1;
    while (reader.Read())
    {
        Console.WriteLine(DateTime.Now.ToLongTimeString() + ": Row " + i);
        i++;
        try
        {
            var d = new DailHistory();
            d.CustomerId = int.Parse((string) reader["customerId"]);
            d.Agent = ParseNullAbleString(reader["agent"].ToString());
            d.CallBackReason = ParseNullAbleString(reader["callBackReason"].ToString());
            d.CallState = ParseCallSate(reader["callState"].ToString());
            d.ContactResponse = ParseNullAbleString(reader["contactResponse"].ToString());
            d.DailTime = new DailTime(reader["dialStart"].ToString(), reader["dialEnd"].ToString());
            d.HistoryIndex = int.Parse(reader["historyIndex"].ToString());
            d.Note = ParseNullAbleString(reader["note"].ToString());
            d.OldDialNo = ParseNullAbleInt(reader["oldDialNo"].ToString());
            d.ProjectJob = ParseNullAbleString(reader["projectJob"].ToString());
            list.Add(d);
        }
        catch(Exception e)
        {
            Console.WriteLine(e.Message);
        }
    }
    reader.Close();
    return list.AsQueryable();
}

Body:
command.CommandTimeout = 2147483;

The largest value for a MySQL command timeout is the largest value for a 32 bit integer, in milliseconds, 2147483647. But in C# the CommandTimeout property is in seconds, not milliseconds, so any higher than 2147483 will result in an exception.

Although this is not infinite, it is 24 days, 20 hours, 31 minutes, and 23 seconds, which would hopefully meet your need.

Setting the value to 0 did not work for me. The CommandTimeout property would not retain the value of 0 and kept auto-changing back to 30.

Setting the value to -1 did seem to work, but I didn't test it enough to be certain that a timeout would never occur.

Safest option: go with 2147483.


问:
How to add pattern to For /F in batch to exclude files?
How can I add pattern to the following batch script in order to look for file (3) and not for all the files, after finding (3) then have to add [%DailyloadDateTime%] at the end of file.

```<code>1. ODS_ATI_NSource-[201712071636]-[201712071637].csv
2. ODS_ATI_NSource-[201712071637].csv
3. ODS_ATI_NSource.csv

for /F "delims=" %%j in ('dir /s /b *.csv') do (
    rename "%%j" "%%~nj-[%DailyloadDateTime%]%%~xj"
  )
</code>```

答:
```<code>for /F "delims=" %%j in ('dir /s /b *.csv^|findstr /L /V "["') do (
</code>```

which directs the dir output through findstr which looks for lines that /v do not contain /L the literal (whatever's in the quotes)

Body:
How can I add pattern to the following batch script in order to look for file (3) and not for all the files, after finding (3) then have to add [%DailyloadDateTime%] at the end of file.

1. ODS_ATI_NSource-[201712071636]-[201712071637].csv
2. ODS_ATI_NSource-[201712071637].csv
3. ODS_ATI_NSource.csv

for /F "delims=" %%j in ('dir /s /b *.csv') do (
    rename "%%j" "%%~nj-[%DailyloadDateTime%]%%~xj"
  )

Body:
for /F "delims=" %%j in ('dir /s /b *.csv^|findstr /L /V "["') do (

which directs the dir output through findstr which looks for lines that /v do not contain /L the literal (whatever's in the quotes)


问:
How to add swipe event on elements in angular4?
i'm trying to add a swipe event to elements on a page to trigger a class change but nothing i've tried so far works.
I'm working with Angular 4 .
Any idea of a library i could use ?
I've heard about Hammerjs but i don't know if that could do the job.

Thanks.

答: I believe adding hammerjs does provide gesture support.  Something like this article may help you get started: https://scotch.io/tutorials/using-hammerjs-touch-gesture-in-angular-2.  Even though it is for Angular 2 the concepts should still be valid for 4.</p>


问:
Query temp table in stored proc whilst debugging in SQL 2008 Management Studio
I have a really large stored procedure which calls other stored procedures and applies the results into temp tables.

I am debugging in SQL 2008 Management Studio and can use the watch window to query local parameters but how can I query a temp table on whilst debugging?

If its not possible is there an alternative approach? I have read about using table variables instead, would it be possible to query these? If so how would I do this?

答:
simply dont drop temp table or close transaction

eg

```<code>select * into #temp from myTable

select * from #temp
</code>```

Body:
simply dont drop temp table or close transaction

eg

select * into #temp from myTable

select * from #temp


问:
How do I change the order of columns in a Julia DataFrame?
Suppose I have a DataFrame like this:

```<code>julia> df = DataFrame(a = [1,2,3], b = [3,4,5])
3×2 DataFrames.DataFrame
│ Row │ a │ b │
├─────┼───┼───┤
│ 1   │ 1 │ 3 │
│ 2   │ 2 │ 4 │
│ 3   │ 3 │ 5 │
</code>```

How do I subsequently change the order of columns so that column :b comes before column :a?

答:
These are the recommendations for DataFrames.jl 0.21 or later.

If you want to be minimally faster you can write

```<code>df[!, [2, 1]]
</code>```

If you want to update df in place you can do it in two steps:

```<code>df[!, 1], df[!, 2] = df[!, 2], df[!, 1]
rename!(df, [:b, :a])
</code>```

which is yet faster.

Also you can use select! like this:

```<code>select!(df, [:b, :a])
</code>```

Body:
Suppose I have a DataFrame like this:

julia> df = DataFrame(a = [1,2,3], b = [3,4,5])
3×2 DataFrames.DataFrame
│ Row │ a │ b │
├─────┼───┼───┤
│ 1   │ 1 │ 3 │
│ 2   │ 2 │ 4 │
│ 3   │ 3 │ 5 │

How do I subsequently change the order of columns so that column :b comes before column :a?

Body:
These are the recommendations for DataFrames.jl 0.21 or later.

If you want to be minimally faster you can write

df[!, [2, 1]]

If you want to update df in place you can do it in two steps:

df[!, 1], df[!, 2] = df[!, 2], df[!, 1]
rename!(df, [:b, :a])

which is yet faster.

Also you can use select! like this:

select!(df, [:b, :a])

ContentLicense: CC BY-SA 4.0


答: You can convert your day/month format to day in year format and then compare each element in the list based on the year then the day</p>

Title: How can I sort date array

Body:
Please see my following code snippet

Input
list_x = ["11/1/2100", "5/12/1999", "19/1/2003", "11/9/2001"]

Output

['5/12/1999', '11/9/2001', '19/1/2003', '11/1/2100']


问:
Accessing a function/state of a component in a wrapping HOC
So I have a component A (extends React.component) and it is wrapped with a higher order component B.

In component B's methods, I need to setState for A, or call a function in A (so that it can do the setState) - how is this generally done?

I can paste actual code here, but I thought it may complicate matters if there are standard ways of handling this situation.

Edit: here's the code - isOpen needs to change for the Modal to close, and it needs to change in handleSubmit....

```<code>import React from 'react';
import Modal from 'react-modal';
import { withFormik, Form, Field } from 'formik';
import Yup from 'yup';

// first part of Formik integration
const formikEnhancer = withFormik({
  mapPropsToValues(props) {
    return {
      personName: props.email || '',
      personSurname: props.surname || '',
      personCongregation: props.congregation || ''
    }
  },
  validationSchema: Yup.object().shape({
    personName: Yup.string().required().min(1),
    personSurname: Yup.string().required().min(2),
    personCongregation: Yup.string().required().min(8)
  }),
  handleSubmit(values, {props, resetForm, setErrors, setSubmitting}) {
    submitNewPerson(values, {resetForm, setErrors, setSubmitting});
    props.testCall;
  }
});

function submitNewPerson(v, {resetForm, setErrors, setSubmitting}) {
  //e.preventDefault();

  congregations = [];
  congregations.push(v.personCongregation);

  const peep = {
    name: v.personName,
    surname: v.personSurname,
    congregations: congregations//,
    //startDate: Number(e.target.componentStartDate.value),
    //endDate: Number(e.target.componentEndDate.value)
  };
    // do the db insert here and check for errors
    setSubmitting(false);
  });
};

class AddPerson extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      error: undefined,
      isOpen: false
    }
  }

  componentWillMount() {
    Modal.setAppElement('body');
  }

  renderCong() {
    // this just maps out a list of select options
  }

  render() {
    return (
      <div>
        <button className="button" onClick={()=> this.setState({isOpen:true, error:undefined})}>+ Add Person</button>
        <Modal isOpen={this.state.isOpen} contentLabel="Add Person"
          className = "boxed-view__box" overlayClassName="boxed-view boxed-view--modal">
          <Form className="boxed-view__form">
            <div>
              <Field type="text" name="personName" placeholder="Name" />
            </div>
            <div>
                <Field type="text" name="personSurname" placeholder="Surname" />
            </div>
            <div>
             <Field component="select" name="personCongregation" value={this.state.cong}>
                <option key="0" value="">- Select Option -</option>
                {this.renderCong()}
              </Field>
            </div>
            <button disabled={this.props.isSubmitting} className="button">Add Person</button>
            <button disabled={this.props.isSubmitting} type="button" className="button button--secondary" onClick={
              ()=> {
                this.props.resetForm();
                this.setState({isOpen:false});
              }}>Cancel</button>
          </Form>

        </Modal>
      </div>
    )
  };
};
</code>```

答:
Unless you are in control of component B, this isn't really possible. Some popular HOCs (like connect in react-redux) have a mechanism that allows you to expose the wrapped component A, but this isn't true in general.

It's generally better not to do this at all. If the state of a component needs to be changed from the outside, it should be passed in as a prop and the "source of truth" should be your model or viewmodel. If you're using something like redux, try moving your component state into redux state, and instead of calling setState, use a redux action/reducer combo to update it.

Another way is to move the state up one level so that it's passed in as a prop from another component (the parent), and then have the logic in that parent, although this is much less flexible.

Body:
So I have a component A (extends React.component) and it is wrapped with a higher order component B.

In component B's methods, I need to setState for A, or call a function in A (so that it can do the setState) - how is this generally done?

I can paste actual code here, but I thought it may complicate matters if there are standard ways of handling this situation.

Edit: here's the code - isOpen needs to change for the Modal to close, and it needs to change in handleSubmit....

import React from 'react';
import Modal from 'react-modal';
import { withFormik, Form, Field } from 'formik';
import Yup from 'yup';

// first part of Formik integration
const formikEnhancer = withFormik({
  mapPropsToValues(props) {
    return {
      personName: props.email || '',
      personSurname: props.surname || '',
      personCongregation: props.congregation || ''
    }
  },
  validationSchema: Yup.object().shape({
    personName: Yup.string().required().min(1),
    personSurname: Yup.string().required().min(2),
    personCongregation: Yup.string().required().min(8)
  }),
  handleSubmit(values, {props, resetForm, setErrors, setSubmitting}) {
    submitNewPerson(values, {resetForm, setErrors, setSubmitting});
    props.testCall;
  }
});

function submitNewPerson(v, {resetForm, setErrors, setSubmitting}) {
  //e.preventDefault();

  congregations = [];
  congregations.push(v.personCongregation);

  const peep = {
    name: v.personName,
    surname: v.personSurname,
    congregations: congregations//,
    //startDate: Number(e.target.componentStartDate.value),
    //endDate: Number(e.target.componentEndDate.value)
  };
    // do the db insert here and check for errors
    setSubmitting(false);
  });
};

class AddPerson extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      error: undefined,
      isOpen: false
    }
  }

  componentWillMount() {
    Modal.setAppElement('body');
  }

  renderCong() {
    // this just maps out a list of select options
  }

  render() {
    return (

        <button className="button" onClick={()=> this.setState({isOpen:true, error:undefined})}>+ Add Person</button>
        <Modal isOpen={this.state.isOpen} contentLabel="Add Person"
          className = "boxed-view__box" overlayClassName="boxed-view boxed-view--modal">
          <Form className="boxed-view__form">

              <Field type="text" name="personName" placeholder="Name" />

                <Field type="text" name="personSurname" placeholder="Surname" />

             <Field component="select" name="personCongregation" value={this.state.cong}>
                <option key="0" value="">- Select Option -</option>
                {this.renderCong()}
              </Field>

            <button disabled={this.props.isSubmitting} className="button">Add Person</button>
            <button disabled={this.props.isSubmitting} type="button" className="button button--secondary" onClick={
              ()=> {
                this.props.resetForm();
                this.setState({isOpen:false});
              }}>Cancel</button>
          </Form>

        </Modal>

    )
  };
};


问:
Active transactions on a specific time every day using 'start date' and 'end date'
I'm trying to calculate the number of active transactions on the first of each month at a specific time. I can calculate that for a specific day for the time I want. For example I can run:

```<code>SELECT
A.country_code,
A.transaction_type,
COUNT (*)

FROM table A
JOIN table_history h ON h.listing_id = A.listing_id

WHERE h.start_date <= '2017-12-01 08:01:03' and NVL(h.end_date, '31-DEC-2099') >= '2017-12-01 08:01:03'

GROUP BY
A.country_code,
A.transaction_type
</code>```

That code works fine for the first of December. However, I want to expand that to get all active transactions at that specific time (08:01:03) for every first of the month.

Thank you

答:
Managed to sort it out by bringing in a Dim Date table and creating a complicated join:</p>

```<code>SELECT
A.country_code,
A.transaction_type,
COUNT (*)

FROM table A
JOIN table_history h ON h.listing_id = A.listing_id

JOIN dim_date dd  on h.start_date <= DATEADD(m,1,DATEADD(hour,8,dd.date)) and NVL(h.end_date, '31-DEC-2099') >= DATEADD(m,1,DATEADD(hour,8,dd.date))

WHERE dd.month_day_no = 1
--WHERE h.start_date <= '2017-12-01 08:01:03' and NVL(h.end_date, '31-DEC-2099') >= '2017-12-01 08:01:03'

GROUP BY
A.country_code,
A.transaction_type
</code>```

Body:
I'm trying to calculate the number of active transactions on the first of each month at a specific time. I can calculate that for a specific day for the time I want. For example I can run:

SELECT
A.country_code,
A.transaction_type,
COUNT (*)

FROM table A
JOIN table_history h ON h.listing_id = A.listing_id

WHERE h.start_date <= '2017-12-01 08:01:03' and NVL(h.end_date, '31-DEC-2099') >= '2017-12-01 08:01:03'

GROUP BY
A.country_code,
A.transaction_type

That code works fine for the first of December. However, I want to expand that to get all active transactions at that specific time (08:01:03) for every first of the month.

Thank you

Body:
Managed to sort it out by bringing in a Dim Date table and creating a complicated join:

SELECT
A.country_code,
A.transaction_type,
COUNT (*)

FROM table A
JOIN table_history h ON h.listing_id = A.listing_id

JOIN dim_date dd  on h.start_date <= DATEADD(m,1,DATEADD(hour,8,dd.date)) and NVL(h.end_date, '31-DEC-2099') >= DATEADD(m,1,DATEADD(hour,8,dd.date))

WHERE dd.month_day_no = 1
--WHERE h.start_date <= '2017-12-01 08:01:03' and NVL(h.end_date, '31-DEC-2099') >= '2017-12-01 08:01:03'

GROUP BY
A.country_code,
A.transaction_type


问:
Multiply list with binary
I am trying to create a powerset by multiplying binary counter with array to get

```<code>Value of Counter            Subset
    000                    -> Empty set
    001                    -> a
    010                    -> b
    011                    -> ab
    100                    -> c
    101                    -> ac
    110                    -> bc
    111                    -> abc
</code>```

My code:

```<code>A = ['a','b','c']
n = len(A)
for i in range(2**n):
    print format(i,'b') and A
</code>```

I get all the outputs as ['a','b','c'] . Is there a different way to do the print statement to get the required result.

答:
The expression format(i,'b') and A is not the same as "bitwise-and of the binary number i with the elements of list A". X and Y is logical-and and is interpreted as Y if X else X, thus you always get A as a result.

You can use a list comprehension, checking the bitwise & of 2**i (i being the current index) and the running number. Also, no explicit conversion to binary is needed.

```<code>>>> [[e for i, e in enumerate(A) if 2**i & x] for x in range(2**n)]
[[], ['a'], ['b'], ['a', 'b'], ['c'], ['a', 'c'], ['b', 'c'], ['a', 'b', 'c']]
</code>```

Title: Multiply list with binary

Body:
I am trying to create a powerset by multiplying binary counter with array to get

Value of Counter            Subset
    000                    -> Empty set
    001                    -> a
    010                    -> b
    011                    -> ab
    100                    -> c
    101                    -> ac
    110                    -> bc
    111                    -> abc

My code:

A = ['a','b','c']
n = len(A)
for i in range(2**n):
    print format(i,'b') and A

I get all the outputs as ['a','b','c'] . Is there a different way to do the print statement to get the required result.

Body:
The expression format(i,'b') and A is not the same as "bitwise-and of the binary number i with the elements of list A". X and Y is logical-and and is interpreted as Y if X else X, thus you always get A as a result.

You can use a list comprehension, checking the bitwise & of 2**i (i being the current index) and the running number. Also, no explicit conversion to binary is needed.

>>> [[e for i, e in enumerate(A) if 2**i & x] for x in range(2**n)]
[[], ['a'], ['b'], ['a', 'b'], ['c'], ['a', 'c'], ['b', 'c'], ['a', 'b', 'c']]


问:
Android: EditText cannot gain focus after being re-enabled
I have a TabHost with three tabs. The first tab's content is the Intent of a custom activity who's contentview is a relative layout containing two EditTexts and two CheckBoxes (and a button).

Each checkbox, when checked, enables/disables one EditText and the other checkbox. and I went about that like this:

```<code>chkPolaziste.setOnCheckedChangeListener(new OnCheckedChangeListener()
    {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
        {
            if ( isChecked )
            {
                entryPolaziste.setFocusable(false);
                entryPolaziste.setEnabled(false);
                chkOdrediste.setFocusable(false);
                chkOdrediste.setEnabled(false);
            }
            else
            {
                entryPolaziste.setEnabled(true);
                entryPolaziste.setFocusable(true);
                chkOdrediste.setEnabled(true);
                chkOdrediste.setFocusable(true);
            }
        }
    });
</code>```

And that works. When one checkbox is checked, it disables the other checkbox and his EditText, and when I uncheck it, EditText and the other checkbox are enabled. But, after it's enabled, I can't type anything into the EditText. It just flicks for a moment when I
click on it, and switches focus to another view. It looks to me as though the control is not fully enabled.

I've also tried to force the focus on the re-enabled EditText with requestFocus(), and tried to setFocusableInTouchMode(), but neither had worked.

I don't have an android device, so I only test this in the emulator (Min SDK is 1.6).

答:
Workaround:

Use setFocusableInTouchMode and setFocusable, both of them.

Body:
I have a TabHost with three tabs. The first tab's content is the Intent of a custom activity who's contentview is a relative layout containing two EditTexts and two CheckBoxes (and a button).

Each checkbox, when checked, enables/disables one EditText and the other checkbox. and I went about that like this:

chkPolaziste.setOnCheckedChangeListener(new OnCheckedChangeListener()
    {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
        {
            if ( isChecked )
            {
                entryPolaziste.setFocusable(false);
                entryPolaziste.setEnabled(false);
                chkOdrediste.setFocusable(false);
                chkOdrediste.setEnabled(false);
            }
            else
            {
                entryPolaziste.setEnabled(true);
                entryPolaziste.setFocusable(true);
                chkOdrediste.setEnabled(true);
                chkOdrediste.setFocusable(true);
            }
        }
    });

And that works. When one checkbox is checked, it disables the other checkbox and his EditText, and when I uncheck it, EditText and the other checkbox are enabled. But, after it's enabled, I can't type anything into the EditText. It just flicks for a moment when I
click on it, and switches focus to another view. It looks to me as though the control is not fully enabled.

I've also tried to force the focus on the re-enabled EditText with requestFocus(), and tried to setFocusableInTouchMode(), but neither had worked.

I don't have an android device, so I only test this in the emulator (Min SDK is 1.6).


问:
How do I properly format this table?

I'm trying to properly format a table so that it prints out values below each column, beginning with the first character of that column. I've had success formatting three columns, but I'm unable to figure out how to format the K Count and LM Count columns so that they are printed out in a neat fashion.

What are some corrections I can make to the while loop portion of the code so that the K count and LM count columns are printed out neatly?

```<code>void printTable(const vector<int>& z, const vector<long>& x, const
vector<long>& y,
const vector<int>& a, const vector<int>& b)
{
ostringstream ss;
ss << "\n\n\n" << setw(10) << left << "Digits" << "Input Numbers       "
    << setw(11) << right << "K Output   " << setw(6)
    << right << "K Count     " << setw(10) << right << "LM Output   " << setw(6)
    << right << "LM Count" << endl;

int i = 0, n = 0;
while (i < 5)
{
    string q = to_string(z[2*n]) + " x " + to_string(z[abs(2*n + 1)]);
    string r = to_string(x[i]);
    string s = to_string(a[i]);
    string t = to_string(y[i]);
    string u = to_string(b[i]);

    ss << setw(10) << left << (i+1) <<  q
        << setw(16) << right << r
        << setw(11) << right << s
        << setw(12) << right << t
        << setw(10) << right << u << endl;

    i++;
    n++;
}

string r = ss.str();
cout << r;
}
</code>```

答:
To fix K Count output, you should reset the cursor to align left after setting the width for the previous result, then shift back right.  Something like this should do what you want.</p>

```<code>ss << setw(10) << left  << (i+1) << right
    setw(16) << left << q << right <<
    setw(11) << left << r << right <<
    setw(12) << left << s << right <<
    setw(12) << left << t << right <<
    setw(10) << left << u << right << endl;
</code>```

Title: How do I properly format this table?

Body:
I'm trying to properly format a table so that it prints out values below each column, beginning with the first character of that column. I've had success formatting three columns, but I'm unable to figure out how to format the K Count and LM Count columns so that they are printed out in a neat fashion.

What are some corrections I can make to the while loop portion of the code so that the K count and LM count columns are printed out neatly?

void printTable(const vector<int>& z, const vector<long>& x, const
vector<long>& y,
const vector<int>& a, const vector<int>& b)
{
ostringstream ss;
ss << "\n\n\n" << setw(10) << left << "Digits" << "Input Numbers       "
    << setw(11) << right << "K Output   " << setw(6)
    << right << "K Count     " << setw(10) << right << "LM Output   " << setw(6)
    << right << "LM Count" << endl;

int i = 0, n = 0;
while (i < 5)
{
    string q = to_string(z[2*n]) + " x " + to_string(z[abs(2*n + 1)]);
    string r = to_string(x[i]);
    string s = to_string(a[i]);
    string t = to_string(y[i]);
    string u = to_string(b[i]);

    ss << setw(10) << left << (i+1) <<  q
        << setw(16) << right << r
        << setw(11) << right << s
        << setw(12) << right << t
        << setw(10) << right << u << endl;

    i++;
    n++;
}

string r = ss.str();
cout << r;
}

Body:
To fix K Count output, you should reset the cursor to align left after setting the width for the previous result, then shift back right.  Something like this should do what you want.

ss << setw(10) << left  << (i+1) << right
    setw(16) << left << q << right <<
    setw(11) << left << r << right <<
    setw(12) << left << s << right <<
    setw(12) << left << t << right <<
    setw(10) << left << u << right << endl;