问:
how to write java 8 Comparator for Map values inside Map.Entry
Here is what I have, I want to sort in descending a the value in the entry.

```<code>Map<String, Outer> outer = Input
                          .entrySet()
                          .stream
                          .collect(toMap(Map.Entry::getKey, entry->{
                           List<Outer> inner = entry
                                    .getValue()
                                    .stream()
                                    .sorted(Comparator.comparingDouble(???))
                              })) ... (more lines of code.)
</code>```

How to write a Comparator with sorted.
If want to do the following inside sorted

```<code>if (o1.getSomething() > o2.getSomething())
     return -1;
if (o1.getSomething() < o2.getSomething())
     return 1;
return 0;
</code>```

After getting the List and sorting it works for me.

```<code>inner.sort((Outer o1, Outer o2) -> {
if (o1.getSomething() > o2.getSomething())
         return -1;
    if (o1.getSomething() < o2.getSomething())
         return 1;
    return 0;
});
</code>```

But is there a way to use stream.sorted( " use the same comparator logic here") inside entry.

Entry is an ArrayList, with bunch of values.

```<code>entry:[{w:1},{w:2},{w:3},{w:4}];
</code>```

So I want to reverse sort this, to be as follows:

```<code>entry:[{w:4},{w:3},{w:2},{w:1}];
</code>```

so the final list I get is a sorted in reverse order one.

sry for the confusion.

答:
As far as I can tell your question is really just how to create a sorted list as the value in your map, with sorting based on the return of getSomething.

```<code>entry.getValue().stream()
    .sorted(Comparator.comparing(Outer::getSomething))
    .collect(toList())
</code>```

will return the list sorted according to getSomething. If that method returns a double then you could use comparingDouble(Outer::getSomething) to avoid boxing the value.

Body:
Here is what I have, I want to sort in descending a the value in the entry.

Map<String, Outer> outer = Input
                          .entrySet()
                          .stream
                          .collect(toMap(Map.Entry::getKey, entry->{
                           List<Outer> inner = entry
                                    .getValue()
                                    .stream()
                                    .sorted(Comparator.comparingDouble(???))
                              })) ... (more lines of code.)

How to write a Comparator with sorted.
If want to do the following inside sorted

if (o1.getSomething() > o2.getSomething())
     return -1;
if (o1.getSomething() < o2.getSomething())
     return 1;
return 0;

After getting the List and sorting it works for me.

inner.sort((Outer o1, Outer o2) -> {
if (o1.getSomething() > o2.getSomething())
         return -1;
    if (o1.getSomething() < o2.getSomething())
         return 1;
    return 0;
});

But is there a way to use stream.sorted( " use the same comparator logic here") inside entry.

Entry is an ArrayList, with bunch of values.

entry:[{w:1},{w:2},{w:3},{w:4}];

So I want to reverse sort this, to be as follows:

entry:[{w:4},{w:3},{w:2},{w:1}];

so the final list I get is a sorted in reverse order one.

sry for the confusion.

Body:
As far as I can tell your question is really just how to create a sorted list as the value in your map, with sorting based on the return of getSomething.

entry.getValue().stream()
    .sorted(Comparator.comparing(Outer::getSomething))
    .collect(toList())

will return the list sorted according to getSomething. If that method returns a double then you could use comparingDouble(Outer::getSomething) to avoid boxing the value.


来源: stackexchange

问:
Arduino yun Stops working after a few hours
I am trying to use the arduino yun to output the number of parts a machine has produced to a google spreadsheet. With the setup I have, I am able to output data to the spreadsheet temporarily. However, after some time, the yun stops working. The red LED I have on to indicate the code is running turns off, and I can no longer see the arduino in the port list. A reset of the 32u4 chip causes the LED to turn back on, indicating the code is running, but the board still does not appear in the port menu.

I have tested it at our workshop and it has run for 7-12 hours with no problems at all. It is only when we take it on to the production floor that we start experiencing these problems. Does anyone have any idea what the issue could be? Here is the most relevant part of the code:

```<code>#include <elapsedMillis.h>
#include <Process.h>
#include <Bridge.h>
#include "TimeLib.h"

// On Arduino:  0 - 1023 maps to 0 - 5 voltsf
#define VOLTAGE_MAX 5.0
#define VOLTAGE_MAXCOUNTS 1023.0

unsigned int buttonCount = 0;
float voltage = 0;
elapsedMillis timeSinceLastCycle = 0;
elapsedMillis transmitData = 0;
int pressFlag = 0;
Process date;
int hours, minutes, seconds;
int lastSecond = -1;
Process sendData;

String printDate() {

  // String currTime = String(hours) + ":" + String(minutes) + ":" + String(seconds);

  if (lastSecond != seconds) { // if a second has passed
    // print the time:
    if (hours <= 9) {
      Console.print("0");  // adjust for 0-9
    }
    Console.print(hours);
    Console.print(":");
    if (minutes <= 9) {
      Console.print("0");  // adjust for 0-9
    }
    Console.print(minutes);
    Console.print(":");
    if (seconds <= 9) {
      Console.print("0");  // adjust for 0-9
    }
    Console.println(seconds);

    // restart the date process:
    if (!date.running()) {
      date.begin("date");
      date.addParameter("+%T");
      date.run();
    }
  }

  //if there's a result from the date process, parse it:
  while (date.available() > 0) {
    // get the result of the date process (should be hh:mm:ss):
    String timeString = date.readString();

    // find the colons:
    int firstColon = timeString.indexOf(":");
    int secondColon = timeString.lastIndexOf(":");

    // get the substrings for hour, minute second:
    String hourString = timeString.substring(0, firstColon);
    String minString = timeString.substring(firstColon + 1, secondColon);
    String secString = timeString.substring(secondColon + 1);

    // convert to ints,saving the previous second:
    hours = hourString.toInt();
    minutes = minString.toInt();
    lastSecond = seconds;          // save to do a time comparison
    seconds = secString.toInt();
    String currTime = hourString + ":" + minString + ":" + String(seconds);
    return currTime;
  }
}

void checkVoltage() {

  int sensorValue = analogRead(A0);
  voltage = sensorValue * (VOLTAGE_MAX / VOLTAGE_MAXCOUNTS);

  Console.println(voltage);
  delay(50);
  if (voltage >= 4.9 && pressFlag == 0) {

    Console.println("Delaying");
    sensorValue = analogRead(A0);
    voltage = sensorValue * (VOLTAGE_MAX / VOLTAGE_MAXCOUNTS);

    if (pressFlag == 0 && voltage >= 4.9) {

      unsigned long int intCycleTime = timeSinceLastCycle;
      timeSinceLastCycle = 0;
      digitalWrite(LED_BUILTIN, LOW);   // turn the LED on (HIGH is the voltage level)

      printDate();
      String pressTime = printDate();

      Console.print("PressTime is ");
      Console.println(pressTime);

      buttonCount++;
      Console.println(buttonCount);

      pressFlag = 1;

      String part1 = "curl -X POST -H \"Content-Type: application/json\" -d '{\"value1\":\"";
      String timeString = pressTime;
      Console.print(timeString + " seconds");
      String part2 = "\",\"value2\":\"";
      String numParts = String(buttonCount);
      String part3 = "\",\"value3\":\"";
      String strCycleTime = String(intCycleTime / 1000); // + " seconds";
      String part4 = "\"}' https://maker.ifttt.com/trigger/arduino2Request/with/key/gL8YmxeaUChOMJvmwpdXp -k";
      //curl -X POST -H "Content-Type: application/json" -d '{"value1":"1","value2":"2","value3":"3"}' https://maker.ifttt.com/trigger/arduino2Request/with/key/gL8YmxeaUChOMJvmwpdXp

      String curlString = part1 + timeString + part2 + numParts + part3 + strCycleTime + part4;

      // The curl string sends data to oue excel spreadhsheet using the IFTTT web service

      sendData.runShellCommandAsynchronously(curlString);

      elapsedMillis breakTimer = 0;
      /*while(sendData.running()){

          if(breakTimer > 5*1000){
            break;
          }
        } */

      Console.print("Data Available: "); // A value of 32 indicates a successful transmission of data, 0 also works if run asynchronously.
      Console.println(sendData.available());

      digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)

    }

  }
  else if (voltage < 2.5) {
    pressFlag = 0;
  }

}

void setup() {

  Bridge.begin();
  Console.begin();
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)

  // run an initial date process. Should return:
  // hh:mm:ss :
  if (!date.running()) {
    date.begin("date");
    date.addParameter("+%T");
    date.run();
  }
}

void loop() {

  checkVoltage();

  if ((timeSinceLastCycle > 300000) && (transmitData > 300000)) { // If 5 minutes have elapsed without a part being produced, output that the arduino is transmitting even if not part is available
    sendData.runShellCommand("curl -X POST -H \"Content-Type: application/json\" -d '{\"value1\":\"1\",\"value2\":\"Arduino Transmitting\"}' https://maker.ifttt.com/trigger/transmitData/with/key/gKRo-zSur5rj6rD5rviCaV2RHI5g56Dy0Vc0S_XJ-oO -k");
    transmitData = 0;
  }
}
</code>```

UPDATE: I added a series of print statements to the checkVoltage function. The code above has been updated to reflect this. I found that it hung when trying to use sendData.runShellCommandAsynchronously. The output looks like

```<code>1.58
1.54
5.00
Delaying
PressTime is n" -d
3
</code>```

Could the network connection cutting out when trying to runShellCommand cause this issue?

答:
So after following user3629249's solution, this issue appears to be resolved. Have now had multiple weeks of error free runtime. user3629249, if you want to repost your advice as an answer, I will accept it. Thank you to user3629249 and Patrick Trentin for your help!

My update ProcessDate function now contains:

```<code>if(date.available() >0){
  while (date.available() > 0) {
  // get the result of the date process (should be hh:mm:ss):
  String timeString = date.readString();

  // find the colons:
  int firstColon = timeString.indexOf(":");
  int secondColon = timeString.lastIndexOf(":");

  // get the substrings for hour, minute second:
  String hourString = timeString.substring(0, firstColon);
  String minString = timeString.substring(firstColon + 1, secondColon);
  String secString = timeString.substring(secondColon + 1);

  // convert to ints,saving the previous second:
  lastSecond = seconds;          // save to do a time comparison
  lastMinute = minutes;
  lastHour = hours;
  hours = hourString.toInt();
  minutes = minString.toInt();
  seconds = secString.toInt();
  String currTime = hourString + ":" + minString + ":" + String(seconds);
  return currTime;
}
else{
        String currTime = ""; // If there is no result from the date process, return nothing. Should not happen.
        return currTime;
      }
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to use the arduino yun to output the number of parts a machine has produced to a google spreadsheet. With the setup I have, I am able to output data to the spreadsheet temporarily. However, after some time, the yun stops working. The red LED I have on to indicate the code is running turns off, and I can no longer see the arduino in the port list. A reset of the 32u4 chip causes the LED to turn back on, indicating the code is running, but the board still does not appear in the port menu.

I have tested it at our workshop and it has run for 7-12 hours with no problems at all. It is only when we take it on to the production floor that we start experiencing these problems. Does anyone have any idea what the issue could be? Here is the most relevant part of the code:

#include <elapsedMillis.h>
#include <Process.h>
#include <Bridge.h>
#include "TimeLib.h"

// On Arduino:  0 - 1023 maps to 0 - 5 voltsf
#define VOLTAGE_MAX 5.0
#define VOLTAGE_MAXCOUNTS 1023.0

unsigned int buttonCount = 0;
float voltage = 0;
elapsedMillis timeSinceLastCycle = 0;
elapsedMillis transmitData = 0;
int pressFlag = 0;
Process date;
int hours, minutes, seconds;
int lastSecond = -1;
Process sendData;

String printDate() {

  // String currTime = String(hours) + ":" + String(minutes) + ":" + String(seconds);

  if (lastSecond != seconds) { // if a second has passed
    // print the time:
    if (hours <= 9) {
      Console.print("0");  // adjust for 0-9
    }
    Console.print(hours);
    Console.print(":");
    if (minutes <= 9) {
      Console.print("0");  // adjust for 0-9
    }
    Console.print(minutes);
    Console.print(":");
    if (seconds <= 9) {
      Console.print("0");  // adjust for 0-9
    }
    Console.println(seconds);

    // restart the date process:
    if (!date.running()) {
      date.begin("date");
      date.addParameter("+%T");
      date.run();
    }
  }

  //if there's a result from the date process, parse it:
  while (date.available() > 0) {
    // get the result of the date process (should be hh:mm:ss):
    String timeString = date.readString();

    // find the colons:
    int firstColon = timeString.indexOf(":");
    int secondColon = timeString.lastIndexOf(":");

    // get the substrings for hour, minute second:
    String hourString = timeString.substring(0, firstColon);
    String minString = timeString.substring(firstColon + 1, secondColon);
    String secString = timeString.substring(secondColon + 1);

    // convert to ints,saving the previous second:
    hours = hourString.toInt();
    minutes = minString.toInt();
    lastSecond = seconds;          // save to do a time comparison
    seconds = secString.toInt();
    String currTime = hourString + ":" + minString + ":" + String(seconds);
    return currTime;
  }
}

void checkVoltage() {

  int sensorValue = analogRead(A0);
  voltage = sensorValue * (VOLTAGE_MAX / VOLTAGE_MAXCOUNTS);

  Console.println(voltage);
  delay(50);
  if (voltage >= 4.9 && pressFlag == 0) {

    Console.println("Delaying");
    sensorValue = analogRead(A0);
    voltage = sensorValue * (VOLTAGE_MAX / VOLTAGE_MAXCOUNTS);

    if (pressFlag == 0 && voltage >= 4.9) {

      unsigned long int intCycleTime = timeSinceLastCycle;
      timeSinceLastCycle = 0;
      digitalWrite(LED_BUILTIN, LOW);   // turn the LED on (HIGH is the voltage level)

      printDate();
      String pressTime = printDate();

      Console.print("PressTime is ");
      Console.println(pressTime);

      buttonCount++;
      Console.println(buttonCount);

      pressFlag = 1;

      String part1 = "curl -X POST -H \"Content-Type: application/json\" -d '{\"value1\":\"";
      String timeString = pressTime;
      Console.print(timeString + " seconds");
      String part2 = "\",\"value2\":\"";
      String numParts = String(buttonCount);
      String part3 = "\",\"value3\":\"";
      String strCycleTime = String(intCycleTime / 1000); // + " seconds";
      String part4 = "\"}' https://maker.ifttt.com/trigger/arduino2Request/with/key/gL8YmxeaUChOMJvmwpdXp -k";
      //curl -X POST -H "Content-Type: application/json" -d '{"value1":"1","value2":"2","value3":"3"}' https://maker.ifttt.com/trigger/arduino2Request/with/key/gL8YmxeaUChOMJvmwpdXp

      String curlString = part1 + timeString + part2 + numParts + part3 + strCycleTime + part4;

      // The curl string sends data to oue excel spreadhsheet using the IFTTT web service

      sendData.runShellCommandAsynchronously(curlString);

      elapsedMillis breakTimer = 0;
      /*while(sendData.running()){

          if(breakTimer > 5*1000){
            break;
          }
        } */

      Console.print("Data Available: "); // A value of 32 indicates a successful transmission of data, 0 also works if run asynchronously.
      Console.println(sendData.available());

      digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)

    }

  }
  else if (voltage < 2.5) {
    pressFlag = 0;
  }

}

void setup() {

  Bridge.begin();
  Console.begin();
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)

  // run an initial date process. Should return:
  // hh:mm:ss :
  if (!date.running()) {
    date.begin("date");
    date.addParameter("+%T");
    date.run();
  }
}

void loop() {

  checkVoltage();

  if ((timeSinceLastCycle > 300000) && (transmitData > 300000)) { // If 5 minutes have elapsed without a part being produced, output that the arduino is transmitting even if not part is available
    sendData.runShellCommand("curl -X POST -H \"Content-Type: application/json\" -d '{\"value1\":\"1\",\"value2\":\"Arduino Transmitting\"}' https://maker.ifttt.com/trigger/transmitData/with/key/gKRo-zSur5rj6rD5rviCaV2RHI5g56Dy0Vc0S_XJ-oO -k");
    transmitData = 0;
  }
}

UPDATE: I added a series of print statements to the checkVoltage function. The code above has been updated to reflect this. I found that it hung when trying to use sendData.runShellCommandAsynchronously. The output looks like

1.58
1.54
5.00
Delaying
PressTime is n" -d
3

Could the network connection cutting out when trying to runShellCommand cause this issue?

Body:
So after following user3629249's solution, this issue appears to be resolved. Have now had multiple weeks of error free runtime. user3629249, if you want to repost your advice as an answer, I will accept it. Thank you to user3629249 and Patrick Trentin for your help!

My update ProcessDate function now contains:

if(date.available() >0){
  while (date.available() > 0) {
  // get the result of the date process (should be hh:mm:ss):
  String timeString = date.readString();

  // find the colons:
  int firstColon = timeString.indexOf(":");
  int secondColon = timeString.lastIndexOf(":");

  // get the substrings for hour, minute second:
  String hourString = timeString.substring(0, firstColon);
  String minString = timeString.substring(firstColon + 1, secondColon);
  String secString = timeString.substring(secondColon + 1);

  // convert to ints,saving the previous second:
  lastSecond = seconds;          // save to do a time comparison
  lastMinute = minutes;
  lastHour = hours;
  hours = hourString.toInt();
  minutes = minString.toInt();
  seconds = secString.toInt();
  String currTime = hourString + ":" + minString + ":" + String(seconds);
  return currTime;
}
else{
        String currTime = ""; // If there is no result from the date process, return nothing. Should not happen.
        return currTime;
      }
    }


问:
WM_MOUSEMOVE issues with position
I am working on a program that is supposed to simulate basic mouse input for a program while it stays in the background (meaning, I want to do other things in other windows with the actual mouse and keyboard while the target receives input). One thing I need to be able to do is move the mouse to a specific (x,y) point.

It seems to work for the most part, but in a certain region of the screen the message only works correctly some of the time. Other times, it moves to a consistent but wrong other point within the region. I am reading that sometimes it is relative, but if I spam the message repeatedly, it does seem to work consistently. Also, reading in Spy++, the messages that are sent by me actually moving my mouse are using what seem to be absolute coordinates.

My function is here:

```<code>void mouseMove(short x, short y) {
    PostMessage(wnd, WM_MOUSEMOVE, 0, MAKELPARAM(x, y));
}
</code>```

Preferably, I'd like for any (x,y) to be absolute so I can have the region treated as any other. But it would also be fine to set the position to a coordinate relative to the top left corner of the region.

I have tried just about all of the messages I've seen sent to the window in Spy++ before the WM_MOUSEMOVE but nothing is helping.

How might I approach this?

Edit, since details might not prove enough info:

I am sending these messages in this order:

WM_ACTIVATE 2 0

WM_MOUSEMOVE 0 MAKELPARAM(x,y)

WM_LBUTTONDOWN MK_LBUTTON MAKELPARAM(x,y)

WM_LBUTTONUP 0 MAKELPARAM(x,y)

I think what I initially thought (bad WM_SETCURSOR area) is wrong because Spy++ consistently shows HTCLIENT being used.

I have found a lot of people trying to do this (background input) and most seem to be told it's impossible. It's not impossible, and I think if someone can answer how to do this correctly once and for all it would be doing quite a few people a big favor.

答:
Synthesizes keystrokes, mouse motions, and button clicks.

```<code>   UINT WINAPI SendInput(
      _In_ UINT    nInputs,
      _In_ LPINPUT pInputs,
      _In_ int     cbSize
    );
</code>```

PostMessage function. Places (posts) a message in the message queue
  associated with the thread that created the specified window and
  returns without waiting for the thread to process the message.

For PostMessage to work you need to be in the process as the target that you can achieve with SetWindowHook but the these links will do the jobs:

https://msdn.microsoft.com/en-us/library/windows/desktop/ms646310(v=vs.85).aspx
https://msdn.microsoft.com/en-us/library/ms171542(v=vs.110).aspx

Title: WM_MOUSEMOVE issues with position

Body:
I am working on a program that is supposed to simulate basic mouse input for a program while it stays in the background (meaning, I want to do other things in other windows with the actual mouse and keyboard while the target receives input). One thing I need to be able to do is move the mouse to a specific (x,y) point.

It seems to work for the most part, but in a certain region of the screen the message only works correctly some of the time. Other times, it moves to a consistent but wrong other point within the region. I am reading that sometimes it is relative, but if I spam the message repeatedly, it does seem to work consistently. Also, reading in Spy++, the messages that are sent by me actually moving my mouse are using what seem to be absolute coordinates.

My function is here:

void mouseMove(short x, short y) {
    PostMessage(wnd, WM_MOUSEMOVE, 0, MAKELPARAM(x, y));
}

Preferably, I'd like for any (x,y) to be absolute so I can have the region treated as any other. But it would also be fine to set the position to a coordinate relative to the top left corner of the region.

I have tried just about all of the messages I've seen sent to the window in Spy++ before the WM_MOUSEMOVE but nothing is helping.

How might I approach this?

Edit, since details might not prove enough info:

I am sending these messages in this order:

WM_ACTIVATE 2 0

WM_MOUSEMOVE 0 MAKELPARAM(x,y)

WM_LBUTTONDOWN MK_LBUTTON MAKELPARAM(x,y)

WM_LBUTTONUP 0 MAKELPARAM(x,y)

I think what I initially thought (bad WM_SETCURSOR area) is wrong because Spy++ consistently shows HTCLIENT being used.

I have found a lot of people trying to do this (background input) and most seem to be told it's impossible. It's not impossible, and I think if someone can answer how to do this correctly once and for all it would be doing quite a few people a big favor.

Body:
Synthesizes keystrokes, mouse motions, and button clicks.

   UINT WINAPI SendInput(
      _In_ UINT    nInputs,
      _In_ LPINPUT pInputs,
      _In_ int     cbSize
    );

PostMessage function. Places (posts) a message in the message queue
  associated with the thread that created the specified window and
  returns without waiting for the thread to process the message.

For PostMessage to work you need to be in the process as the target that you can achieve with SetWindowHook but the these links will do the jobs:

https://msdn.microsoft.com/en-us/library/windows/desktop/ms646310(v=vs.85).aspx
https://msdn.microsoft.com/en-us/library/ms171542(v=vs.110).aspx


问:
Querying multiple tables two being junction tables
I am trying to write a sql query that queries records from multiple tables which involved junction tables. The Userprofile table has relationship with Role and team table and one to one relationship with TimeZone table.

I am trying to achieve a query that will pull records from UserProfile table as well relevant records from Role , team and timezone table. I have tried to write a query and it is getting overly complex. Could somebody verify my query and tell me the right way to do it

The tables are as follows

UserProfile table

```<code>  [EmployeeID]
  [Forename]
  [Surname]
  [PreferredName]
  [DefaultLanguageCode]
  [DefaultCountryCode]
  [TimeZoneID]
  [Domain]
  [NetworkID]
</code>```

Team table

```<code>   [TeamID]
   [CountryCode]
   [TeamName]
   [TeamDescription]
</code>```

UserTeamLinkTable

```<code>  [UserProfileTeamLinkID]
  [TeamID]
  [UserProfileID]
  [isDefault]
  [isActive]
</code>```

UserRole Table

```<code>   [RoleID]
   [RoleDescription]
   [isActive]
</code>```

UserRoleLink Table

```<code>[UserProfileRoleLinkID]
   [RoleID]
   [UserProfileID]
   [isActive]
</code>```

TimeZone table

```<code>  [TimeZoneID]
  [TimeZoneCode]
  [TimeZone]
  [TimeZoneName]
</code>```

Query

```<code>select

    userprofile.[UserProfileID]
   ,userprofile.[EmployeeID]
   ,userprofile.[Forename]
   ,userprofile.[Surname]
   ,userprofile.[PreferredName]
   ,userprofile.[DefaultCountryCode]
   ,userprofile.[DefaultLanguageCode]
   ,userprofile.[TimeZoneID]
   ,userprofile.TeamID
   ,userprofile.TeamName
   ,userprofile.[Domain]
   ,userprofile.[NetworkID]
   ,userprofile.[EmailAddress]
   ,userprofile.[CreatedDate]
   ,userprofile.[CreatedBy]
   ,userprofile.[ModifiedDate]
   ,userprofile.[ModifiedBy]

 from TimeZone tz inner join
(
select
   up.[UserProfileID]
   ,up.[EmployeeID]
   ,up.[Forename]
   ,up.[Surname]
   ,up.[PreferredName]
   ,up.[DefaultCountryCode]
   ,up.[DefaultLanguageCode]
   ,up.[TimeZoneID]
   ,te.TeamID
   ,te.TeamName
   ,up.[Domain]
   ,up.[NetworkID]
   ,up.[EmailAddress]
   ,up.[CreatedDate]
   ,up.[CreatedBy]
   ,up.[ModifiedDate]
   ,up.[ModifiedBy]

from [dbo].[UserProfileTeamLink] upt
inner join UserProfile up on up.UserProfileID = upt.UserProfileID
inner join Team te on te.TeamID = upt.TeamID ) userprofile  on tz.TimeZoneID = userprofile.TimeZoneID
</code>```

答:
It is hard to say without knowing what the data looks like or what the desired output looks like. You could join all of the tables without using sub queries if you are expecting multiple rows per user because of those many to many relationships.  </p>

```<code>select
    up.[UserProfileID]
   ,up.[EmployeeID]
   ,up.[Forename]
   ,up.[Surname]
   ,up.[PreferredName]
   ,up.[DefaultCountryCode]
   ,up.[DefaultLanguageCode]
   ,up.[TimeZoneID]
   ,tz.TimeZone
   ,te.TeamID
   ,te.TeamName
   ,up.[Domain]
   ,up.[NetworkID]
   ,up.[EmailAddress]
   ,up.[CreatedDate]
   ,up.[CreatedBy]
   ,up.[ModifiedDate]
   ,up.[ModifiedBy]
   ,ur.RoleDescription
from UserProfile up
  inner join TimeZone tz
    on tz.TimeZoneID = up.TimeZoneID
  inner join UserProfileTeamLink upt
    on upt.UserProfileID = upt.UserProfileID
  --and upt.isDefault = 1 /* default team only? */
  --and upt.isActive = 1  /* active team only? */
  inner join Team te
    on te.TeamID = upt.TeamID
  inner join UserProfileRoleLink upr /* left join if users might not have a role*/
    on up.UserProfileID = upr.UserProfileId
  --and upr.isActive = 1  /* active role only? */
  inner join UserRole ur /* left join if users might not have a role*/
    on upr.RoleId = ur.RoleId
</code>```

Body:
I am trying to write a sql query that queries records from multiple tables which involved junction tables. The Userprofile table has relationship with Role and team table and one to one relationship with TimeZone table.

I am trying to achieve a query that will pull records from UserProfile table as well relevant records from Role , team and timezone table. I have tried to write a query and it is getting overly complex. Could somebody verify my query and tell me the right way to do it

The tables are as follows

UserProfile table

  [EmployeeID]
  [Forename]
  [Surname]
  [PreferredName]
  [DefaultLanguageCode]
  [DefaultCountryCode]
  [TimeZoneID]
  [Domain]
  [NetworkID]

Team table

   [TeamID]
   [CountryCode]
   [TeamName]
   [TeamDescription]

UserTeamLinkTable

  [UserProfileTeamLinkID]
  [TeamID]
  [UserProfileID]
  [isDefault]
  [isActive]

UserRole Table

   [RoleID]
   [RoleDescription]
   [isActive]

UserRoleLink Table

[UserProfileRoleLinkID]
   [RoleID]
   [UserProfileID]
   [isActive]

TimeZone table

  [TimeZoneID]
  [TimeZoneCode]
  [TimeZone]
  [TimeZoneName]

Query

select

    userprofile.[UserProfileID]
   ,userprofile.[EmployeeID]
   ,userprofile.[Forename]
   ,userprofile.[Surname]
   ,userprofile.[PreferredName]
   ,userprofile.[DefaultCountryCode]
   ,userprofile.[DefaultLanguageCode]
   ,userprofile.[TimeZoneID]
   ,userprofile.TeamID
   ,userprofile.TeamName
   ,userprofile.[Domain]
   ,userprofile.[NetworkID]
   ,userprofile.[EmailAddress]
   ,userprofile.[CreatedDate]
   ,userprofile.[CreatedBy]
   ,userprofile.[ModifiedDate]
   ,userprofile.[ModifiedBy]

 from TimeZone tz inner join
(
select
   up.[UserProfileID]
   ,up.[EmployeeID]
   ,up.[Forename]
   ,up.[Surname]
   ,up.[PreferredName]
   ,up.[DefaultCountryCode]
   ,up.[DefaultLanguageCode]
   ,up.[TimeZoneID]
   ,te.TeamID
   ,te.TeamName
   ,up.[Domain]
   ,up.[NetworkID]
   ,up.[EmailAddress]
   ,up.[CreatedDate]
   ,up.[CreatedBy]
   ,up.[ModifiedDate]
   ,up.[ModifiedBy]

from [dbo].[UserProfileTeamLink] upt
inner join UserProfile up on up.UserProfileID = upt.UserProfileID
inner join Team te on te.TeamID = upt.TeamID ) userprofile  on tz.TimeZoneID = userprofile.TimeZoneID

Body:
It is hard to say without knowing what the data looks like or what the desired output looks like. You could join all of the tables without using sub queries if you are expecting multiple rows per user because of those many to many relationships.

select
    up.[UserProfileID]
   ,up.[EmployeeID]
   ,up.[Forename]
   ,up.[Surname]
   ,up.[PreferredName]
   ,up.[DefaultCountryCode]
   ,up.[DefaultLanguageCode]
   ,up.[TimeZoneID]
   ,tz.TimeZone
   ,te.TeamID
   ,te.TeamName
   ,up.[Domain]
   ,up.[NetworkID]
   ,up.[EmailAddress]
   ,up.[CreatedDate]
   ,up.[CreatedBy]
   ,up.[ModifiedDate]
   ,up.[ModifiedBy]
   ,ur.RoleDescription
from UserProfile up
  inner join TimeZone tz
    on tz.TimeZoneID = up.TimeZoneID
  inner join UserProfileTeamLink upt
    on upt.UserProfileID = upt.UserProfileID
  --and upt.isDefault = 1 /* default team only? */
  --and upt.isActive = 1  /* active team only? */
  inner join Team te
    on te.TeamID = upt.TeamID
  inner join UserProfileRoleLink upr /* left join if users might not have a role*/
    on up.UserProfileID = upr.UserProfileId
  --and upr.isActive = 1  /* active role only? */
  inner join UserRole ur /* left join if users might not have a role*/
    on upr.RoleId = ur.RoleId


问:
question on displaying UIProgressView in each table cell
I'm trying to upload a few files to a server. The files are listed on the UItableview. My question is:

What should i do to display UIProgressView in each table cell and show the progress of each file being uploaded.

My current code is able to show the UIProgressView in each cell but when i try to upload, the progress bar did not move. The program is suppose to upload 1 file at a time which after the first file is completed, the second will start to upload. In response, when the first file is done, the progress bar of the first file will stop and the progress bar for the secong file will start to move. Hope this is clear. I really need some help on this and i can't find it on the web.Thanks in advance. Thanks

答:
Possible solution (could be optimized): (Sorry for the formatting, could not get it working)

Create UIProgressView for each cell in your tableView

Create a field in your view controller, where you will store number of bytes already uploaded (bytesAlreadyUploaded) - you should repeatidly receive such info from your uploader.

Create a field where you will store number of bytes to be uploaded for the current upload (bytesToUpload)

Create a field where you will assign pointer to the progress view currently used (progressViewCurrentlyUsed)

Create a method in which you will refresh your progress:

(void) refreshProgress {
        progressViewCurrentlyUsed.progress =
  bytesAlreadyUploaded /
  (CGFloat)bytesToUpload;

  }

Create a NSTimer, which will call this refreshProgress method several times a second:

refreshTimer = [NSTimer
  timerWithTimeInterval:0.1 target:self
  selector:@selector(refreshProgress)
  userInfo:nil repeats:YES];

    [[NSRunLoop mainRunLoop]
  addTimer:refreshTimer
  forMode:NSDefaultRunLoopMode];

When you change the file being uploaded, change progressViewCurrentlyUsed, bytesToUpload and zero bytesAlreadyUploaded

ContentLicense: CC BY-SA 2.5


问:
How do an InputStream, InputStreamReader and BufferedReader work together in Java?
I am studying Android development (I'm a beginner in programming in general) and learning about HTTP networking and saw this code in the lesson:

```<code>private String readFromStream(InputStream inputStream) throws IOException {
  StringBuilder output = new StringBuilder();
  if (inputStream != null) {
    InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
    BufferedReader reader = new BufferedReader(inputStreamReader);
    String line = reader.readLine();
    while (line != null) {
      output.append(line);
      line = reader.readLine();
    }
  }
  return output.toString();
}
</code>```

I don't understand exactly what InputStream, InputStreamReader and BufferedReader do. All of them have a read() method and also readLine() in the case of the BufferedReader.Why can't I only use the InputStream or only add the InputStreamReader? Why do I need to add the BufferedReader? I know it has to do with efficiency but I don't understand how.

I've been researching and the documentation for the BufferedReader tries to explain this but I still don't get who is doing what:

In general, each read request made of a Reader causes a corresponding
  read request to be made of the underlying character or byte stream. It
  is therefore advisable to wrap a BufferedReader around any Reader
  whose read() operations may be costly, such as FileReaders and
  InputStreamReaders. For example,

BufferedReader in    = new BufferedReader(new FileReader("foo.in"));
  will buffer the input from the specified file. Without buffering, each
  invocation of read() or readLine() could cause bytes to be read from
  the file, converted into characters, and then returned, which can be
  very inefficient.

So, I understand that the InputStream can only read one byte, the InputStreamReader a single character, and the BufferedReader a whole line and that it also does something about efficiency which is what I don't get. I would like to have a better understanding of who is doing what, so as to understand why I need all three of them and what the difference would be without one of them.

I've researched a lot here and elsewhere on the web and don't seem to find any explanation about this that I can understand, almost all tutorials just repeat the documentation info. Here are some related questions that maybe begin to explain this but don't go deeper and solve my confusion: Q1, Q2, Q3, Q4. I think it may have to do with this last question's explanation about system calls and returning. But I would like to understand what is meant by all this.

Could it be that the BufferedReader's readLine() calls the InputStreamReader's read() method which in turn calls the InputStream's read() method? And the InputStream returns bytes converted to int, returning a single byte at a time, the InputStreamReader reads enough of these to make a single character and converts it to int and returns a single character at a time, and the BufferedReader reads enough of these characters represented as integers to make up a whole line? And returns the whole line as a String, returning only once instead of several times? I don't know, I'm just trying to get how things work.

Lots of thanks in advance!

答:
This Streams in Java concepts and usage link, give a very nice explanations.

Streams, Readers, Writers, BufferedReader, BufferedWriter – these are the terminologies you will deal with in Java.  There are the classes provided in Java to operate with input and output. It is really worth to know how these are related and how it is used. This post will explore the Streams in Java and other related classes in detail. So let us start:

Let us define each of these in high level then dig deeper.

Streams

Used to deal with byte level data

Reader/Writer

Used to deal with character level. It supports various character encoding also.

BufferedReader/BufferedWriter

To increase performance. Data to be read will be buffered in to memory for quick access.

While these are for taking input, just the corresponding classes exists for output as well. For example, if there is an InputStream that is meant to read stream of byte, and OutputStream will help in writing stream of bytes.

InputStreams

There are many types of InputStreams java provides. Each connect to distinct data sources such as byte array, File etc.

For example FileInputStream connects to a file data source and could be used to read bytes from a File. While ByteArrayInputStream could be used to treat byte array as input stream.

OutputStream

This helps in writing bytes to a data source.  For almost every InputStream there is a corresponding OutputStream, wherever it makes sense.

UPDATE

What is Buffered Stream?

Here I'm quoting from Buffered Streams, Java documentation (With a technical explanation):

Buffered Streams

Most of the examples we've seen so far use unbuffered I/O. This means
  each read or write request is handled directly by the underlying OS.
  This can make a program much less efficient, since each such request
  often triggers disk access, network activity, or some other operation
  that is relatively expensive.

To reduce this kind of overhead, the Java platform implements buffered
  I/O streams. Buffered input streams read data from a memory area known
  as a buffer; the native input API is called only when the buffer is
  empty. Similarly, buffered output streams write data to a buffer, and
  the native output API is called only when the buffer is full.

Sometimes I'm losing my hair reading a technical documentation. So, here I quote the more humane explanation from https://yfain.github.io/Java4Kids/:

In general, disk access is much slower than the processing performed
  in memory; that’s why it’s not a good idea to access the disk a
  thousand times to read a file of 1,000 bytes. To minimize the number
  of times the disk is accessed, Java provides buffers, which serve as
  reservoirs of data.

In reading File with FileInputStream then BufferedInputStream,  the
  class BufferedInputStream works as a middleman between FileInputStream
  and the file itself. It reads a big chunk of bytes from a file into
  memory (a buffer) in one shot, and the FileInputStream object then
  reads single bytes from there, which are fast memory-to-memory
  operations. BufferedOutputStream works similarly with the class
  FileOutputStream.

The main idea here is to minimize disk access. Buffered streams are
  not changing the type of the original streams — they just make reading
  more efficient. A program performs stream chaining (or stream piping)
  to connect streams, just as pipes are connected in plumbing.

Body:
I am studying Android development (I'm a beginner in programming in general) and learning about HTTP networking and saw this code in the lesson:

private String readFromStream(InputStream inputStream) throws IOException {
  StringBuilder output = new StringBuilder();
  if (inputStream != null) {
    InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
    BufferedReader reader = new BufferedReader(inputStreamReader);
    String line = reader.readLine();
    while (line != null) {
      output.append(line);
      line = reader.readLine();
    }
  }
  return output.toString();
}

I don't understand exactly what InputStream, InputStreamReader and BufferedReader do. All of them have a read() method and also readLine() in the case of the BufferedReader.Why can't I only use the InputStream or only add the InputStreamReader? Why do I need to add the BufferedReader? I know it has to do with efficiency but I don't understand how.

I've been researching and the documentation for the BufferedReader tries to explain this but I still don't get who is doing what:

In general, each read request made of a Reader causes a corresponding
  read request to be made of the underlying character or byte stream. It
  is therefore advisable to wrap a BufferedReader around any Reader
  whose read() operations may be costly, such as FileReaders and
  InputStreamReaders. For example,

BufferedReader in    = new BufferedReader(new FileReader("foo.in"));
  will buffer the input from the specified file. Without buffering, each
  invocation of read() or readLine() could cause bytes to be read from
  the file, converted into characters, and then returned, which can be
  very inefficient.

So, I understand that the InputStream can only read one byte, the InputStreamReader a single character, and the BufferedReader a whole line and that it also does something about efficiency which is what I don't get. I would like to have a better understanding of who is doing what, so as to understand why I need all three of them and what the difference would be without one of them.

I've researched a lot here and elsewhere on the web and don't seem to find any explanation about this that I can understand, almost all tutorials just repeat the documentation info. Here are some related questions that maybe begin to explain this but don't go deeper and solve my confusion: Q1, Q2, Q3, Q4. I think it may have to do with this last question's explanation about system calls and returning. But I would like to understand what is meant by all this.

Could it be that the BufferedReader's readLine() calls the InputStreamReader's read() method which in turn calls the InputStream's read() method? And the InputStream returns bytes converted to int, returning a single byte at a time, the InputStreamReader reads enough of these to make a single character and converts it to int and returns a single character at a time, and the BufferedReader reads enough of these characters represented as integers to make up a whole line? And returns the whole line as a String, returning only once instead of several times? I don't know, I'm just trying to get how things work.

Lots of thanks in advance!


问:
python scipy installation failure
Good morning:
I'm trying to install scipy in my system, and am getting the below error. Can anyone help me to fix this issue ?

PS C:\Windows> pip install scipy
Collecting scipy
  Downloading scipy-0.19.0.zip (15.3MB)
    100% |████████████████████████████████| 15.3MB 97kB/s
Installing collected packages: scipy
  Running setup.py install for scipy ... error
    Complete output from command "c:\program files (x86)\python36-32\python.exe" -u -c "import setuptools, tokenize;file='C:\Users\asekhar\AppData\Local\Te
mp\pip-build-vewzf1v9\scipy\setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exe
c'))" install --record C:\Users\asekhar\AppData\Local\Temp\pip-02ml9lzd-record\install-record.txt --single-version-externally-managed --compile:

```<code>Note: if you need reliable uninstall behavior, then install
with pip instead of using `setup.py install`:

  - `pip install .`       (from a git repo or downloaded source
                           release)
  - `pip install scipy`   (last SciPy release on PyPI)

lapack_opt_info:
lapack_mkl_info:
  libraries mkl_rt not found in ['c:\\program files (x86)\\python36-32\\lib', 'C:\\', 'c:\\program files (x86)\\python36-32\\libs']
  NOT AVAILABLE

openblas_lapack_info:
  libraries openblas not found in ['c:\\program files (x86)\\python36-32\\lib', 'C:\\', 'c:\\program files (x86)\\python36-32\\libs']
  NOT AVAILABLE

atlas_3_10_threads_info:
Setting PTATLAS=ATLAS
c:\program files (x86)\python36-32\lib\site-packages\numpy\distutils\system_info.py:1051: UserWarning: Specified path C:\projects\numpy-wheels\windows-wheel-bui
</code>```

lder\atlas-builds\atlas-3.10.1-sse2-32\lib is invalid.
      pre_dirs = system_info.get_paths(self, section, key)

      NOT AVAILABLE

```<code>atlas_3_10_info:
<class 'numpy.distutils.system_info.atlas_3_10_info'>
  NOT AVAILABLE

atlas_threads_info:
Setting PTATLAS=ATLAS
<class 'numpy.distutils.system_info.atlas_threads_info'>
  NOT AVAILABLE

atlas_info:
<class 'numpy.distutils.system_info.atlas_info'>
  NOT AVAILABLE

c:\program files (x86)\python36-32\lib\site-packages\numpy\distutils\system_info.py:572: UserWarning:
    Atlas (http://math-atlas.sourceforge.net/) libraries not found.
    Directories to search for the libraries can be specified in the
    numpy/distutils/site.cfg file (section [atlas]) or by setting
    the ATLAS environment variable.
  self.calc_info()
lapack_info:
  libraries lapack not found in ['c:\\program files (x86)\\python36-32\\lib', 'C:\\', 'c:\\program files (x86)\\python36-32\\libs']
  NOT AVAILABLE

c:\program files (x86)\python36-32\lib\site-packages\numpy\distutils\system_info.py:572: UserWarning:
    Lapack (http://www.netlib.org/lapack/) libraries not found.
    Directories to search for the libraries can be specified in the
    numpy/distutils/site.cfg file (section [lapack]) or by setting
    the LAPACK environment variable.
  self.calc_info()
lapack_src_info:
  NOT AVAILABLE

c:\program files (x86)\python36-32\lib\site-packages\numpy\distutils\system_info.py:572: UserWarning:
    Lapack (http://www.netlib.org/lapack/) sources not found.
    Directories to search for the sources can be specified in the
    numpy/distutils/site.cfg file (section [lapack_src]) or by setting
    the LAPACK_SRC environment variable.
  self.calc_info()
  NOT AVAILABLE

Running from scipy source directory.
non-existing path in 'scipy\\integrate': 'quadpack.h'
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "C:\Users\asekhar\AppData\Local\Temp\pip-build-vewzf1v9\scipy\setup.py", line 416, in <module>
    setup_package()
  File "C:\Users\asekhar\AppData\Local\Temp\pip-build-vewzf1v9\scipy\setup.py", line 412, in setup_package
    setup(**metadata)
  File "c:\program files (x86)\python36-32\lib\site-packages\numpy\distutils\core.py", line 135, in setup
    config = configuration()
  File "C:\Users\asekhar\AppData\Local\Temp\pip-build-vewzf1v9\scipy\setup.py", line 336, in configuration
    config.add_subpackage('scipy')
  File "c:\program files (x86)\python36-32\lib\site-packages\numpy\distutils\misc_util.py", line 1001, in add_subpackage
    caller_level = 2)
  File "c:\program files (x86)\python36-32\lib\site-packages\numpy\distutils\misc_util.py", line 970, in get_subpackage
    caller_level = caller_level + 1)
  File "c:\program files (x86)\python36-32\lib\site-packages\numpy\distutils\misc_util.py", line 907, in _get_configuration_from_setup_py
    config = setup_module.configuration(*args)
  File "scipy\setup.py", line 15, in configuration
    config.add_subpackage('linalg')
  File "c:\program files (x86)\python36-32\lib\site-packages\numpy\distutils\misc_util.py", line 1001, in add_subpackage
    caller_level = 2)
  File "c:\program files (x86)\python36-32\lib\site-packages\numpy\distutils\misc_util.py", line 970, in get_subpackage
    caller_level = caller_level + 1)
  File "c:\program files (x86)\python36-32\lib\site-packages\numpy\distutils\misc_util.py", line 907, in _get_configuration_from_setup_py
    config = setup_module.configuration(*args)
  File "scipy\linalg\setup.py", line 20, in configuration
    raise NotFoundError('no lapack/blas resources found')
numpy.distutils.system_info.NotFoundError: no lapack/blas resources found

----------------------------------------
</code>```

Command ""c:\program files (x86)\python36-32\python.exe" -u -c "import setuptools, tokenize;file='C:\Users\asekhar\AppData\Local\Temp\pip-build-vewzf1v9\
scipy\setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" install --record C
:\Users\asekhar\AppData\Local\Temp\pip-02ml9lzd-record\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in C:\Users\asekha
r\AppData\Local\Temp\pip-build-vewzf1v9\scipy\

答:
I use scipy with py35 on windows. Rather than compiling it is a good idea to install pre-built wheel.

Unofficial but reliable build is available from
http://www.lfd.uci.edu/~gohlke/pythonlibs/

For py36, win32 you need numpy+mkl and then scipy

Download the wheels.

numpy‑1.12.1+mkl‑cp36‑cp36m‑win32.whl

scipy‑0.19.0‑cp36‑cp36m‑win32.whl

After download.

pip install numpy‑1.12.1+mkl‑cp36‑cp36m‑win32.whl

pip install scipy‑0.19.0‑cp36‑cp36m‑win32.whl

Title: python scipy installation failure

Body:
Good morning:
I'm trying to install scipy in my system, and am getting the below error. Can anyone help me to fix this issue ?

PS C:\Windows> pip install scipy
Collecting scipy
  Downloading scipy-0.19.0.zip (15.3MB)
    100% |████████████████████████████████| 15.3MB 97kB/s
Installing collected packages: scipy
  Running setup.py install for scipy ... error
    Complete output from command "c:\program files (x86)\python36-32\python.exe" -u -c "import setuptools, tokenize;file='C:\Users\asekhar\AppData\Local\Te
mp\pip-build-vewzf1v9\scipy\setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exe
c'))" install --record C:\Users\asekhar\AppData\Local\Temp\pip-02ml9lzd-record\install-record.txt --single-version-externally-managed --compile:

Note: if you need reliable uninstall behavior, then install
with pip instead of using `setup.py install`:

  - `pip install .`       (from a git repo or downloaded source
                           release)
  - `pip install scipy`   (last SciPy release on PyPI)

lapack_opt_info:
lapack_mkl_info:
  libraries mkl_rt not found in ['c:\\program files (x86)\\python36-32\\lib', 'C:\\', 'c:\\program files (x86)\\python36-32\\libs']
  NOT AVAILABLE

openblas_lapack_info:
  libraries openblas not found in ['c:\\program files (x86)\\python36-32\\lib', 'C:\\', 'c:\\program files (x86)\\python36-32\\libs']
  NOT AVAILABLE

atlas_3_10_threads_info:
Setting PTATLAS=ATLAS
c:\program files (x86)\python36-32\lib\site-packages\numpy\distutils\system_info.py:1051: UserWarning: Specified path C:\projects\numpy-wheels\windows-wheel-bui

lder\atlas-builds\atlas-3.10.1-sse2-32\lib is invalid.
      pre_dirs = system_info.get_paths(self, section, key)

      NOT AVAILABLE

atlas_3_10_info:
<class 'numpy.distutils.system_info.atlas_3_10_info'>
  NOT AVAILABLE

atlas_threads_info:
Setting PTATLAS=ATLAS
<class 'numpy.distutils.system_info.atlas_threads_info'>
  NOT AVAILABLE

atlas_info:
<class 'numpy.distutils.system_info.atlas_info'>
  NOT AVAILABLE

c:\program files (x86)\python36-32\lib\site-packages\numpy\distutils\system_info.py:572: UserWarning:
    Atlas (http://math-atlas.sourceforge.net/) libraries not found.
    Directories to search for the libraries can be specified in the
    numpy/distutils/site.cfg file (section [atlas]) or by setting
    the ATLAS environment variable.
  self.calc_info()
lapack_info:
  libraries lapack not found in ['c:\\program files (x86)\\python36-32\\lib', 'C:\\', 'c:\\program files (x86)\\python36-32\\libs']
  NOT AVAILABLE

c:\program files (x86)\python36-32\lib\site-packages\numpy\distutils\system_info.py:572: UserWarning:
    Lapack (http://www.netlib.org/lapack/) libraries not found.
    Directories to search for the libraries can be specified in the
    numpy/distutils/site.cfg file (section [lapack]) or by setting
    the LAPACK environment variable.
  self.calc_info()
lapack_src_info:
  NOT AVAILABLE

c:\program files (x86)\python36-32\lib\site-packages\numpy\distutils\system_info.py:572: UserWarning:
    Lapack (http://www.netlib.org/lapack/) sources not found.
    Directories to search for the sources can be specified in the
    numpy/distutils/site.cfg file (section [lapack_src]) or by setting
    the LAPACK_SRC environment variable.
  self.calc_info()
  NOT AVAILABLE

Running from scipy source directory.
non-existing path in 'scipy\\integrate': 'quadpack.h'
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "C:\Users\asekhar\AppData\Local\Temp\pip-build-vewzf1v9\scipy\setup.py", line 416, in <module>
    setup_package()
  File "C:\Users\asekhar\AppData\Local\Temp\pip-build-vewzf1v9\scipy\setup.py", line 412, in setup_package
    setup(**metadata)
  File "c:\program files (x86)\python36-32\lib\site-packages\numpy\distutils\core.py", line 135, in setup
    config = configuration()
  File "C:\Users\asekhar\AppData\Local\Temp\pip-build-vewzf1v9\scipy\setup.py", line 336, in configuration
    config.add_subpackage('scipy')
  File "c:\program files (x86)\python36-32\lib\site-packages\numpy\distutils\misc_util.py", line 1001, in add_subpackage
    caller_level = 2)
  File "c:\program files (x86)\python36-32\lib\site-packages\numpy\distutils\misc_util.py", line 970, in get_subpackage
    caller_level = caller_level + 1)
  File "c:\program files (x86)\python36-32\lib\site-packages\numpy\distutils\misc_util.py", line 907, in _get_configuration_from_setup_py
    config = setup_module.configuration(*args)
  File "scipy\setup.py", line 15, in configuration
    config.add_subpackage('linalg')
  File "c:\program files (x86)\python36-32\lib\site-packages\numpy\distutils\misc_util.py", line 1001, in add_subpackage
    caller_level = 2)
  File "c:\program files (x86)\python36-32\lib\site-packages\numpy\distutils\misc_util.py", line 970, in get_subpackage
    caller_level = caller_level + 1)
  File "c:\program files (x86)\python36-32\lib\site-packages\numpy\distutils\misc_util.py", line 907, in _get_configuration_from_setup_py
    config = setup_module.configuration(*args)
  File "scipy\linalg\setup.py", line 20, in configuration
    raise NotFoundError('no lapack/blas resources found')
numpy.distutils.system_info.NotFoundError: no lapack/blas resources found

----------------------------------------

Command ""c:\program files (x86)\python36-32\python.exe" -u -c "import setuptools, tokenize;file='C:\Users\asekhar\AppData\Local\Temp\pip-build-vewzf1v9\
scipy\setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" install --record C
:\Users\asekhar\AppData\Local\Temp\pip-02ml9lzd-record\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in C:\Users\asekha
r\AppData\Local\Temp\pip-build-vewzf1v9\scipy\


问:
position: fixed - issue in IE6.
I have searched many articles, that ie6 could not support position:fixed, and maybe set position:absolute and top position. But I tried many times can not work well. Can anyone help me to modify my code?( the effection is that my code show in ie8)</p>

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<style type="text/css">
html, body{width:100%;height:100%;margin:0;padding:0;background-color:#fff;}
#headerwarp{width:100%;height:78px;margin:0;padding:0;position:fixed;left:0;top:0;z-index:10;}
#headertop{width:100%;height:28px;margin:0;padding:0;background-color:blue;position:fixed;left:0;top:0;z-index:10;}
#headerbottom{width:100%;height:50px;margin:0;padding:0;background-color:green;position:fixed;left:0;top:28px;z-index:10;}
#footerwarp{width:100%;height:53px;margin:0;padding:0;position:fixed;left:0;bottom:0;z-index:10;}
#footerbottom{width:100%;height:65px;margin:0;padding:0;background-color:#000;z-index:10;}
#localcontent{width:100%;margin:0;padding:78px 0 105px 0;top:0;}
#content1{position:fixed;width:100%;height:20px;margin:0;padding:0;background-color:#ff0;z-index:10;top:78px;}
#content2{position:fixed;width:100%;height:25px;margin:0;padding:0;background-color:#f00;z-index:10;top:98px;}
.box{width:100%;position:relative;top:45px;padding:0;margin:0;}
.slide {margin:10px;}
.sl{width:100%;}
li{margin:0 0 5px 0;padding:0;list-style:none;}
ul li,li{width:400px;overflow:hidden;position:relative;}
.contenttop{height:25px;position:fixed;z-index:10;top:123px;padding:0;margin:0;width:290px;background-color:#0FF;}
.contentbottom{width:400px;float:left;padding:0;margin:0;height:1000px;}
.col1, .col2, .col3{float:left;padding:0;margin:0 3px 0 3px;}
.pcol1, .ptcol1{float:left;margin:0 0 6px 0;}
.ptcol1{text-align:center;font-size:14px;color:#222;font-weight:bold;padding:0;position:fixed;z-index:10;top:148px;background:#f00;}
.pcol1{padding:2px;position:relative;top:30px;background:#ff0;}
.col1, .ptcol1{width:139px;}
.pcol1{width:135px;}
</style>
</head>
<body>
<div id="headerwarp">
 <div id="headertop">
    </div>
    <div id="headerbottom">
    </div>
</div>
<div id="localcontent">
        <div class="box">
         <div id="content1">
            </div>
            <div id="content2">
            </div>
            <div id="sl">
                <ul class="ul" style="z-index:1;">
                    <li class="li">
                     <div class="contenttop">
                          content
                        </div>
                        <div class="contentbottom">
                            <div class="col1">
                             <div class="ptcol1">
                              content1
                                </div>
                                <div class="pcol1">
                                111<br/>111<br/>111<br/>111<br/>111<br/>111<br/>111<br/>111<br/>111<br/>111<br/>111<br/>111<br/>111<br/>111<br/>111<br/>111<br/>111<br/>111<br/>111<br/>111<br/>111<br/>111<br/>111<br/>111<br/>111<br/>111<br/>111<br/>111<br/>111<br/>111<br/>111<br/>111<br/>111<br/>111<br/>111<br/>111<br/>111<br/>111<br/>111<br/>111<br/>
                                </div>
                            </div>
                            <div class="col1">
                             <div class="ptcol1">
                              content2
                                </div>
                                <div class="pcol1">
                                111<br/>111<br/>111<br/>111<br/>111<br/>111<br/>111<br/>111<br/>111<br/>111<br/>111<br/>111<br/>111<br/>111<br/>111<br/>111<br/>111<br/>111<br/>111<br/>111<br/>111<br/>111<br/>111<br/>111<br/>111<br/>111<br/>111<br/>111<br/>111<br/>111<br/>111<br/>111<br/>111<br/>111<br/>111<br/>111<br/>111<br/>111<br/>111<br/>111<br/>
                                </div>
                            </div>
                        </div>
                    </li>
                </ul>
            </div>
        </div>
</div>
<div id="footerwarp">
 <div id="footerbottom">
    </div>
</div>
</body>
</html>
</code>```

答: I won't claim it as my own solution because that would be unfair to the person that put so much effort into fixing it, but I believe you might want to look at the website of Stu Nicolls (CSS Play)</p>

Title: position: fixed - issue in IE6.

Body:
I have searched many articles, that ie6 could not support position:fixed, and maybe set position:absolute and top position. But I tried many times can not work well. Can anyone help me to modify my code?( the effection is that my code show in ie8)

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

<meta http-equiv="Content-type" content="text/html; charset=utf-8" />

                          content

                              content1

                                111
111
111
111
111
111
111
111
111
111
111
111
111
111
111
111
111
111
111
111
111
111
111
111
111
111
111
111
111
111
111
111
111
111
111
111
111
111
111
111

                              content2

                                111
111
111
111
111
111
111
111
111
111
111
111
111
111
111
111
111
111
111
111
111
111
111
111
111
111
111
111
111
111
111
111
111
111
111
111
111
111
111
111


问:
Sinch FCM based push notification
While implementing app-app calling with Sinch, I need to integrate push notification using firebase cloud messaging(FCM). As there is no doc available so I followed the same process like GCM but when I called

mSinchClient.setSupportManagedPush(true);

it is throwing exception missing GCM exception

com.sinch.android.rtc.MissingGCMException: Can't enable managed push as this depends on GCM, which is not available on this device

答: We currently do not support FCM for managedpush if you cant use GCM use this to implement the push methods your self https://www.sinch.com/docs/voice/android/#pushnotificationssentviayourapplicationserver</p>

Title: Sinch FCM based push notification


问:
Allow user to write access to gcp dataflow project
Following the quickstart for gcp dataflow here

I run into the following error when executing the example script here

using this command

```<code>declare -r PROJECT="beam-test"
declare -r BUCKET="gs://my-beam-test-bucket"

echo
set -v -e

python -m apache_beam.examples.wordcount \
  --project $PROJECT \
  --job_name $PROJECT-wordcount \
  --runner DataflowRunner \
  --staging_location $BUCKET/staging \
  --temp_location $BUCKET/temp \
  --output $BUCKET/output
</code>```

which results in this error:

```<code> http_response.request_url, method_config, request)
apitools.base.py.exceptions.HttpError: HttpError accessing <https://dataflow.googleapis.com/v1b3/projects/beam-test/locations/us-central1/jobs?alt=json>: response: <{'status': '403', 'content-length': '284', 'x-xss-protection': '1; mode=block', 'x-content-type-options': 'nosniff', 'transfer-encoding': 'chunked', 'vary': 'Origin, X-Origin, Referer', 'server': 'ESF', '-content-encoding': 'gzip', 'cache-control': 'private', 'date': 'Fri, 31 Mar 2017 15:52:54 GMT', 'x-frame-options': 'SAMEORIGIN', 'alt-svc': 'quic=":443"; ma=2592000; v="37,36,35"', 'content-type': 'application/json; charset=UTF-8'}>, content <{
  "error": {
    "code": 403,
    "message": "(f010d95b3e221bbf): Could not create workflow; user does not have write access to project: beam-test Causes: (f010d95b3e221432): Permission 'dataflow.jobs.create' denied on project: 'beam-test'",
    "status": "PERMISSION_DENIED"
</code>```

I have already enabled the DataFlow api for the project. And I have authorized the gcloud cli with the  owner account of the project (which I assumes has full access).

How & where do I enable write permissions?

答: Change $PROJECT=project-name to $PROJECT=project-id

Body:
Following the quickstart for gcp dataflow here

I run into the following error when executing the example script here

using this command

declare -r PROJECT="beam-test"
declare -r BUCKET="gs://my-beam-test-bucket"

echo
set -v -e

python -m apache_beam.examples.wordcount \
  --project $PROJECT \
  --job_name $PROJECT-wordcount \
  --runner DataflowRunner \
  --staging_location $BUCKET/staging \
  --temp_location $BUCKET/temp \
  --output $BUCKET/output

which results in this error:

 http_response.request_url, method_config, request)
apitools.base.py.exceptions.HttpError: HttpError accessing <https://dataflow.googleapis.com/v1b3/projects/beam-test/locations/us-central1/jobs?alt=json>: response: <{'status': '403', 'content-length': '284', 'x-xss-protection': '1; mode=block', 'x-content-type-options': 'nosniff', 'transfer-encoding': 'chunked', 'vary': 'Origin, X-Origin, Referer', 'server': 'ESF', '-content-encoding': 'gzip', 'cache-control': 'private', 'date': 'Fri, 31 Mar 2017 15:52:54 GMT', 'x-frame-options': 'SAMEORIGIN', 'alt-svc': 'quic=":443"; ma=2592000; v="37,36,35"', 'content-type': 'application/json; charset=UTF-8'}>, content <{
  "error": {
    "code": 403,
    "message": "(f010d95b3e221bbf): Could not create workflow; user does not have write access to project: beam-test Causes: (f010d95b3e221432): Permission 'dataflow.jobs.create' denied on project: 'beam-test'",
    "status": "PERMISSION_DENIED"

I have already enabled the DataFlow api for the project. And I have authorized the gcloud cli with the  owner account of the project (which I assumes has full access).

How & where do I enable write permissions?


问:
Worksheets.Add in UDF Not Working
I have a UDF that can be called from within a cell in my excel workbook. I need it to add a worksheet at the end of the workbook. I have used sheets.add multiple times in my VBA script, but never in a function called from inside a cell and this is apparently causing some issue.

The function accepts an optional parameter for file path of the workbook in which to add the sheet, and if the user leaves this blank I want to default to the active workbook.

Below is the relevant code... What am I doing wrong?

```<code>Public Function onesheet(Optional filepath As String)

Dim wb As Workbook
Dim ws As Worksheet

If filepath = "" Then
   Set wb = ActiveWorkbook
   Set target_ws = wb.Sheets.Add(after:=wb.Sheets(wb.Sheets.Count))
End If
</code>```

The function is being called from the cell with
=onesheet()

答:
You cannot add sheets through user defined function.
Here are the limitations of User Defined Functions.

A user-defined function called by a formula in a worksheet cell cannot change the environment of Microsoft Excel. This means that such a function cannot do any of the following:

1) Insert, delete, or format cells on the spreadsheet.
2) Change another cell's value.
3) Move, rename, delete, or add sheets to a workbook.
4) Change any of the environment options, such as calculation mode or screen views.
5) Add names to a workbook.
6) Set properties or execute most methods.

For more details visit this site...
https://support.microsoft.com/en-in/help/170787/description-of-limitations-of-custom-functions-in-excel

Title: Worksheets.Add in UDF Not Working

Body:
I have a UDF that can be called from within a cell in my excel workbook. I need it to add a worksheet at the end of the workbook. I have used sheets.add multiple times in my VBA script, but never in a function called from inside a cell and this is apparently causing some issue.

The function accepts an optional parameter for file path of the workbook in which to add the sheet, and if the user leaves this blank I want to default to the active workbook.

Below is the relevant code... What am I doing wrong?

Public Function onesheet(Optional filepath As String)

Dim wb As Workbook
Dim ws As Worksheet

If filepath = "" Then
   Set wb = ActiveWorkbook
   Set target_ws = wb.Sheets.Add(after:=wb.Sheets(wb.Sheets.Count))
End If

The function is being called from the cell with
=onesheet()


问:
invalid literal for int() with base 10 Python
Got an error above with the following code:

```<code>import optparse
import socket
from socket import *
from threading import *

def main():
    parser =optparse.OptionParser('usage%prog -H <target host> -p <target port>')
    parser.add_option('-p',dest='tgtPort',type='string',help='specific target port separated by comma')
    (options, args) = parser.parse_args()

    tgtPorts = str(options.tgtPort).split(', ')
    for p in tgtPorts:
        print int(p)

if  __name__ == '__main__':
    main()
</code>```

when I try to implement:

```<code>python testInt.py -p 20, 80
</code>```

Expected result:

```<code>20 80
</code>```

答:
Hmmm, when you call

```<code>python testInt.py -p 20, 80
</code>```

20, is passed to the -p argument and 80 is included in the rest of the arguments.

You need to enclose them in quotes for it to work

```<code>python testInt.py -p "20, 80"
</code>```

Body:
Got an error above with the following code:

import optparse
import socket
from socket import *
from threading import *

def main():
    parser =optparse.OptionParser('usage%prog -H <target host> -p <target port>')
    parser.add_option('-p',dest='tgtPort',type='string',help='specific target port separated by comma')
    (options, args) = parser.parse_args()

    tgtPorts = str(options.tgtPort).split(', ')
    for p in tgtPorts:
        print int(p)

if  __name__ == '__main__':
    main()

when I try to implement:

python testInt.py -p 20, 80

Expected result:

20 80

Body:
Hmmm, when you call

python testInt.py -p 20, 80

20, is passed to the -p argument and 80 is included in the rest of the arguments.

You need to enclose them in quotes for it to work

python testInt.py -p "20, 80"


问:
Excel VBA: determing rows on which the value is found
I am trying to have the row number in which the value was found:

```<code>Set rep = Sheets("Details")
For i = 2 To n
If Sheets("Work").Range("A:A").Find(Worksheets("Work_report").Range("E" & i).Value, lookat:=xlWhole) Is Nothing Then
Else:
findrow = Sheets("Work_report").Range("E" & i).Find(Worksheets("Work").Range("A:A").Value, lookat:=xlWhole).Row
o = rep.Range("A" & Rows.Count).End(xlUp).Row + 1
rep.Range("A" & o).Value = "FT_EXCEL"
rep.Range("B" & o).Value = Sheets("Start").Range("C5") & "AB" & Format(o - 1, "00")
rep.Range("C" & o).Value = Sheets("Work_report").Range("E" & findrow)
End If
Next i
</code>```

For the row I want to use "findrow" which basically would need to find the row in Work_Report. This is only executed if, from sheet Work the cell value was found in Work_Report, so in order to find the number of the row I am trying to invert the line and have it found back in Work_Report, however this gives me the error of - Object variable or With block variable not set.

Thanks!

答:
I prefer MATCH to find on single column searches:</p>

```<code>Set rep = Sheets("Details")
Dim test As Long
For i = 2 To n
    test = 0
    On Error Resume Next
    test = Application.WorksheetFunction.Match(Worksheets("Work_report").Range("E" & i).Value, Sheets("Work").Range("A:A"), 0)
    On Error GoTo 0
    If test > 0 Then
        o = rep.Range("A" & Rows.Count).End(xlUp).Row + 1
        rep.Range("A" & o).Value = "FT_EXCEL"
        rep.Range("B" & o).Value = Sheets("Start").Range("C5") & "AB" & Format(o - 1, "00")
        rep.Range("C" & o).Value = Sheets("Work_report").Range("E" & test)
    End If
Next i
</code>```

Body:
I am trying to have the row number in which the value was found:

Set rep = Sheets("Details")
For i = 2 To n
If Sheets("Work").Range("A:A").Find(Worksheets("Work_report").Range("E" & i).Value, lookat:=xlWhole) Is Nothing Then
Else:
findrow = Sheets("Work_report").Range("E" & i).Find(Worksheets("Work").Range("A:A").Value, lookat:=xlWhole).Row
o = rep.Range("A" & Rows.Count).End(xlUp).Row + 1
rep.Range("A" & o).Value = "FT_EXCEL"
rep.Range("B" & o).Value = Sheets("Start").Range("C5") & "AB" & Format(o - 1, "00")
rep.Range("C" & o).Value = Sheets("Work_report").Range("E" & findrow)
End If
Next i

For the row I want to use "findrow" which basically would need to find the row in Work_Report. This is only executed if, from sheet Work the cell value was found in Work_Report, so in order to find the number of the row I am trying to invert the line and have it found back in Work_Report, however this gives me the error of - Object variable or With block variable not set.

Thanks!

Body:
I prefer MATCH to find on single column searches:

Set rep = Sheets("Details")
Dim test As Long
For i = 2 To n
    test = 0
    On Error Resume Next
    test = Application.WorksheetFunction.Match(Worksheets("Work_report").Range("E" & i).Value, Sheets("Work").Range("A:A"), 0)
    On Error GoTo 0
    If test > 0 Then
        o = rep.Range("A" & Rows.Count).End(xlUp).Row + 1
        rep.Range("A" & o).Value = "FT_EXCEL"
        rep.Range("B" & o).Value = Sheets("Start").Range("C5") & "AB" & Format(o - 1, "00")
        rep.Range("C" & o).Value = Sheets("Work_report").Range("E" & test)
    End If
Next i


问:
Write random date to a file Python
Python 2.7.13 - version

I have a .py that contains a few methods that generates random info(Date,Name,Phone number).

```<code>def strTimeProp(start, end, format, prop):
    stime = time.mktime(time.strptime(start, format))
    etime = time.mktime(time.strptime(end, format))
    ptime = stime + prop * (etime - stime)
    return time.strftime(format, time.localtime(ptime))

def randomDate(start, end, prop):
    return strTimeProp(start, end, '%m/%d/%Y %I:%M %p', prop)

print randomDate("1/1/2008 12:00 AM", "1/1/2009 12:00 AM", random.random())

f = open("CDR.txt" ,"w")
f.write(randomDate)
f.close()
</code>```

I'm getting a typeError with f.write(randomDate) it's expecting a string or buffer and not a function. How can I send the output of the print statement to the .txt file I'm writing to?

答:
You are passing the function randomDate to f.write without any parameters

This will resolve your issue:

```<code>f.write(randomDate("1/1/2008 12:00 AM", "1/1/2009 12:00 AM", random.random()))
</code>```

Title: Write random date to a file Python

Body:
Python 2.7.13 - version

I have a .py that contains a few methods that generates random info(Date,Name,Phone number).

def strTimeProp(start, end, format, prop):
    stime = time.mktime(time.strptime(start, format))
    etime = time.mktime(time.strptime(end, format))
    ptime = stime + prop * (etime - stime)
    return time.strftime(format, time.localtime(ptime))

def randomDate(start, end, prop):
    return strTimeProp(start, end, '%m/%d/%Y %I:%M %p', prop)

print randomDate("1/1/2008 12:00 AM", "1/1/2009 12:00 AM", random.random())

f = open("CDR.txt" ,"w")
f.write(randomDate)
f.close()

I'm getting a typeError with f.write(randomDate) it's expecting a string or buffer and not a function. How can I send the output of the print statement to the .txt file I'm writing to?

Body:
You are passing the function randomDate to f.write without any parameters

This will resolve your issue:

f.write(randomDate("1/1/2008 12:00 AM", "1/1/2009 12:00 AM", random.random()))


问:
Opening, editing and saving a csv file
I have a csv called pairList which looks like:

```<code>0    BBG.XNGS.AAPL.S  BBG.XNGS.BRCM.S  0
1    BBG.XNGS.AAPL.S  BBG.XNGS.MSFT.S  0
2    BBG.XNGS.AAPL.S  BBG.XNGS.AMAT.S  0
3    BBG.XNGS.AAPL.S  BBG.XNGS.QCOM.S  0
4    BBG.XNGS.AMGN.S   BBG.XNYS.MWW.S  0
5    BBG.XNGS.BRCM.S  BBG.XNGS.MSFT.S  0
6    BBG.XNGS.BRCM.S  BBG.XNGS.AMAT.S  0
7    BBG.XNGS.BRCM.S  BBG.XNGS.QCOM.S  0
8    BBG.XNGS.MSFT.S  BBG.XNGS.AMAT.S  0
9    BBG.XNGS.MSFT.S  BBG.XNGS.QCOM.S  0
10   BBG.XNGS.AMAT.S  BBG.XNGS.QCOM.S  0
11  BBG.XNGS.CMCSA.S  BBG.XNGS.CSCO.S  0
12  BBG.XNGS.CMCSA.S  BBG.XNGS.SYMC.S  0
13   BBG.XNGS.CSCO.S  BBG.XNGS.SYMC.S  0
</code>```

I am trying to open the csv, look down each row until I find the first row where the 4 column is equal to 0 (in this case its the first row but it this would change).  Copy the data for this row to 3 variables

```<code>stock1ID
stock2ID
status
</code>```

Then update the status (the value in column 4 for the seelcted row) and then save the dataframe back to the csv.  So the csv would (in this example) end up looking like:

```<code>0    BBG.XNGS.AAPL.S  BBG.XNGS.BRCM.S  1
1    BBG.XNGS.AAPL.S  BBG.XNGS.MSFT.S  0
2    BBG.XNGS.AAPL.S  BBG.XNGS.AMAT.S  0
3    BBG.XNGS.AAPL.S  BBG.XNGS.QCOM.S  0
4    BBG.XNGS.AMGN.S   BBG.XNYS.MWW.S  0
5    BBG.XNGS.BRCM.S  BBG.XNGS.MSFT.S  0
6    BBG.XNGS.BRCM.S  BBG.XNGS.AMAT.S  0
7    BBG.XNGS.BRCM.S  BBG.XNGS.QCOM.S  0
8    BBG.XNGS.MSFT.S  BBG.XNGS.AMAT.S  0
9    BBG.XNGS.MSFT.S  BBG.XNGS.QCOM.S  0
10   BBG.XNGS.AMAT.S  BBG.XNGS.QCOM.S  0
11  BBG.XNGS.CMCSA.S  BBG.XNGS.CSCO.S  0
12  BBG.XNGS.CMCSA.S  BBG.XNGS.SYMC.S  0
13   BBG.XNGS.CSCO.S  BBG.XNGS.SYMC.S  0
</code>```

I can open the csv and select the data asigning it to the 3 variables.  I can't save the updated csv.  I end up with a csv that looks like:

```<code>    0    BBG.XNGS.AAPL.S  BBG.XNGS.BRCM.S  0  1
    1    BBG.XNGS.AAPL.S  BBG.XNGS.MSFT.S  0  1
    2    BBG.XNGS.AAPL.S  BBG.XNGS.AMAT.S  0  1
    3    BBG.XNGS.AAPL.S  BBG.XNGS.QCOM.S  0  1
    4    BBG.XNGS.AMGN.S   BBG.XNYS.MWW.S  0  1
    5    BBG.XNGS.BRCM.S  BBG.XNGS.MSFT.S  0  1
    6    BBG.XNGS.BRCM.S  BBG.XNGS.AMAT.S  0  1
    7    BBG.XNGS.BRCM.S  BBG.XNGS.QCOM.S  0  1
    8    BBG.XNGS.MSFT.S  BBG.XNGS.AMAT.S  0  1
    9    BBG.XNGS.MSFT.S  BBG.XNGS.QCOM.S  0  1
    10   BBG.XNGS.AMAT.S  BBG.XNGS.QCOM.S  0  1
    11  BBG.XNGS.CMCSA.S  BBG.XNGS.CSCO.S  0  1
    12  BBG.XNGS.CMCSA.S  BBG.XNGS.SYMC.S  0  1
    13   BBG.XNGS.CSCO.S  BBG.XNGS.SYMC.S  0  1
</code>```

The csv has an extra 4th column of 1's when all I want is that the row that has been select should have a 1 in the 3rd column only.

Please see below for the code that I have so far written:

```<code>def getPairID(TimeseriesDataPath):

#status = 0 - pair not processed
#status = 1 - pair being processed
#status = 2 - pair finined being processed
pattern = 'PairsToTestList'+'.csv'
pairToTest = 0
with open(TimeseriesDataPath+pattern,'rt') as f:
    pairList = pd.read_csv(f,engine='c',header=None,index_col=0, parse_dates=True, infer_datetime_format=True)
    for i, row in pairList.iterrows():
        if i != 'unique_id':
            stock1ID = row[1]
            stock2ID = row[2]
            status = row[3]

            if status == 0 :
                print('stock1ID ',stock1ID,'stock2ID ',stock2ID,'status ',status)

                pairToTest = 1
                pairList[row[2]] = 1

                path = os.path.join(TimeseriesDataPath,pattern)
                pairList.to_csv(path,header=False)
                break

    return stock1ID,stock2ID,pairToTest
</code>```

答:
Updated to include the iteration I think you're looking for.

I've also updated it using .iloc to find the integer position of the next line instead of using the index.

```<code>f = 'C:/Users/yourname/Desktop/test.csv'

df = pd.read_csv(f, header = None)

i = 0
while i <= df.index.max():
    subset = df.loc[df[2] == 0].head(1)

    if subset[0].count() == 0:
        stock1ID, stock2ID, status = None, None, None

    else:
        stock1ID, stock2ID, status = subset[0].iloc[0], subset[1].iloc[0], subset[2].iloc[0]
        print '{}, {}, {}'.format(stock1ID, stock2ID, status)
        df.loc[df.index == subset.index[0], 2] = 1

    i += 1

df.to_csv('C:/Users/Pete/Desktop/test2.csv', header = None)
</code>```

ContentLicense: CC BY-SA 4.0

Title: Opening, editing and saving a csv file

Body:
I have a csv called pairList which looks like:

0    BBG.XNGS.AAPL.S  BBG.XNGS.BRCM.S  0
1    BBG.XNGS.AAPL.S  BBG.XNGS.MSFT.S  0
2    BBG.XNGS.AAPL.S  BBG.XNGS.AMAT.S  0
3    BBG.XNGS.AAPL.S  BBG.XNGS.QCOM.S  0
4    BBG.XNGS.AMGN.S   BBG.XNYS.MWW.S  0
5    BBG.XNGS.BRCM.S  BBG.XNGS.MSFT.S  0
6    BBG.XNGS.BRCM.S  BBG.XNGS.AMAT.S  0
7    BBG.XNGS.BRCM.S  BBG.XNGS.QCOM.S  0
8    BBG.XNGS.MSFT.S  BBG.XNGS.AMAT.S  0
9    BBG.XNGS.MSFT.S  BBG.XNGS.QCOM.S  0
10   BBG.XNGS.AMAT.S  BBG.XNGS.QCOM.S  0
11  BBG.XNGS.CMCSA.S  BBG.XNGS.CSCO.S  0
12  BBG.XNGS.CMCSA.S  BBG.XNGS.SYMC.S  0
13   BBG.XNGS.CSCO.S  BBG.XNGS.SYMC.S  0

I am trying to open the csv, look down each row until I find the first row where the 4 column is equal to 0 (in this case its the first row but it this would change).  Copy the data for this row to 3 variables

stock1ID
stock2ID
status

Then update the status (the value in column 4 for the seelcted row) and then save the dataframe back to the csv.  So the csv would (in this example) end up looking like:

0    BBG.XNGS.AAPL.S  BBG.XNGS.BRCM.S  1
1    BBG.XNGS.AAPL.S  BBG.XNGS.MSFT.S  0
2    BBG.XNGS.AAPL.S  BBG.XNGS.AMAT.S  0
3    BBG.XNGS.AAPL.S  BBG.XNGS.QCOM.S  0
4    BBG.XNGS.AMGN.S   BBG.XNYS.MWW.S  0
5    BBG.XNGS.BRCM.S  BBG.XNGS.MSFT.S  0
6    BBG.XNGS.BRCM.S  BBG.XNGS.AMAT.S  0
7    BBG.XNGS.BRCM.S  BBG.XNGS.QCOM.S  0
8    BBG.XNGS.MSFT.S  BBG.XNGS.AMAT.S  0
9    BBG.XNGS.MSFT.S  BBG.XNGS.QCOM.S  0
10   BBG.XNGS.AMAT.S  BBG.XNGS.QCOM.S  0
11  BBG.XNGS.CMCSA.S  BBG.XNGS.CSCO.S  0
12  BBG.XNGS.CMCSA.S  BBG.XNGS.SYMC.S  0
13   BBG.XNGS.CSCO.S  BBG.XNGS.SYMC.S  0

I can open the csv and select the data asigning it to the 3 variables.  I can't save the updated csv.  I end up with a csv that looks like:

    0    BBG.XNGS.AAPL.S  BBG.XNGS.BRCM.S  0  1
    1    BBG.XNGS.AAPL.S  BBG.XNGS.MSFT.S  0  1
    2    BBG.XNGS.AAPL.S  BBG.XNGS.AMAT.S  0  1
    3    BBG.XNGS.AAPL.S  BBG.XNGS.QCOM.S  0  1
    4    BBG.XNGS.AMGN.S   BBG.XNYS.MWW.S  0  1
    5    BBG.XNGS.BRCM.S  BBG.XNGS.MSFT.S  0  1
    6    BBG.XNGS.BRCM.S  BBG.XNGS.AMAT.S  0  1
    7    BBG.XNGS.BRCM.S  BBG.XNGS.QCOM.S  0  1
    8    BBG.XNGS.MSFT.S  BBG.XNGS.AMAT.S  0  1
    9    BBG.XNGS.MSFT.S  BBG.XNGS.QCOM.S  0  1
    10   BBG.XNGS.AMAT.S  BBG.XNGS.QCOM.S  0  1
    11  BBG.XNGS.CMCSA.S  BBG.XNGS.CSCO.S  0  1
    12  BBG.XNGS.CMCSA.S  BBG.XNGS.SYMC.S  0  1
    13   BBG.XNGS.CSCO.S  BBG.XNGS.SYMC.S  0  1

The csv has an extra 4th column of 1's when all I want is that the row that has been select should have a 1 in the 3rd column only.

Please see below for the code that I have so far written:

def getPairID(TimeseriesDataPath):

#status = 0 - pair not processed
#status = 1 - pair being processed
#status = 2 - pair finined being processed
pattern = 'PairsToTestList'+'.csv'
pairToTest = 0
with open(TimeseriesDataPath+pattern,'rt') as f:
    pairList = pd.read_csv(f,engine='c',header=None,index_col=0, parse_dates=True, infer_datetime_format=True)
    for i, row in pairList.iterrows():
        if i != 'unique_id':
            stock1ID = row[1]
            stock2ID = row[2]
            status = row[3]

            if status == 0 :
                print('stock1ID ',stock1ID,'stock2ID ',stock2ID,'status ',status)

                pairToTest = 1
                pairList[row[2]] = 1

                path = os.path.join(TimeseriesDataPath,pattern)
                pairList.to_csv(path,header=False)
                break

    return stock1ID,stock2ID,pairToTest

Body:
Updated to include the iteration I think you're looking for.

I've also updated it using .iloc to find the integer position of the next line instead of using the index.

f = 'C:/Users/yourname/Desktop/test.csv'

df = pd.read_csv(f, header = None)

i = 0
while i <= df.index.max():
    subset = df.loc[df[2] == 0].head(1)

    if subset[0].count() == 0:
        stock1ID, stock2ID, status = None, None, None

    else:
        stock1ID, stock2ID, status = subset[0].iloc[0], subset[1].iloc[0], subset[2].iloc[0]
        print '{}, {}, {}'.format(stock1ID, stock2ID, status)
        df.loc[df.index == subset.index[0], 2] = 1

    i += 1

df.to_csv('C:/Users/Pete/Desktop/test2.csv', header = None)


问:
Issue writing out file path properties in ant
I'm having an issue with writing out a property which holds the value of a directory path into a property file.

My script originally reads in this particular property, call it 'appserver.home', from a props file using the <property file="source.props"/>. I've echoed the value coming in and it reads correctly as C:\\somedir\\jboss_4_2_3.

What my script needs to do next is provide this value to another properties file (used by another ant script - though that's not important). To create this other file I'm using a kind off template file with place holders surrounded by $....$ to insert the correct values in the correct place, using the following :-

```<code> <copy file="template_file.props" tofile="target.props">
    <filterset begintoken="$" endtoken="$">
        <filter token="appServerDir" value="${appserver.home}"/>
        <filter token="dbusername" value="${database.name}"/>
        ....
    </filterset>
 </copy>
</code>```

The problem is that the value now in the target.props is C:\somedir\jboss_4_2_3 ie it's lost the escape characters. When the next ant script uses this file it interprets the property value as C:somedirjboss_4_2_3.

So the question how do I tell ant that the value I'm writing is a file path ?
Note I have tried the following, which actually works :-

```<code><propertyfile file="target.props">
    <entry key="appServerDir" value="${appserver.home}"/>
</propertyfile>
</code>```

.. ie it outputs the name as c\:\\somedir\\jboss4_2_3, but I'd rather not use this technique and rather use the template file technique, as it contains some properties which are always static, as well as comments etc.

Thanks in advance

答:
I have just tested using Apache Ant version 1.7.1 compiled on May 25 2010 on Ubuntu server 10.10, and using the Apache Ant version 1.7.1 compiled on June 27 2008 in Eclipse 3.6 on Windows XP. now the results (from both the same):

Variable in source.props:

appserver.home=C\:\\somedir\\jboss_4_2_3

Echo on console:

[echo] C:\somedir\jboss_4_2_3

Variable in target.properties:

appserver.home=C:\somedir\jboss_4_2_3

EDIT - the solution below;-D

In my opinion you should use the propertyfile, if you read the manual for this task you can see that it is able to MANIPUlATE existing property files. This one works for me, and all the comments and vars from template are preserved.

```<code><copy file="template_file.props"  tofile="target.props" />
<propertyfile  file="target.props">
    <entry  key="appserver.home" value="${appserver.home}"/>
</propertyfile>
</code>```

Body:
I'm having an issue with writing out a property which holds the value of a directory path into a property file.

My script originally reads in this particular property, call it 'appserver.home', from a props file using the <property file="source.props"/>. I've echoed the value coming in and it reads correctly as C:\\somedir\\jboss_4_2_3.

What my script needs to do next is provide this value to another properties file (used by another ant script - though that's not important). To create this other file I'm using a kind off template file with place holders surrounded by $....$ to insert the correct values in the correct place, using the following :-

 <copy file="template_file.props" tofile="target.props">
    <filterset begintoken="$" endtoken="$">
        <filter token="appServerDir" value="${appserver.home}"/>
        <filter token="dbusername" value="${database.name}"/>
        ....
    </filterset>
 </copy>

The problem is that the value now in the target.props is C:\somedir\jboss_4_2_3 ie it's lost the escape characters. When the next ant script uses this file it interprets the property value as C:somedirjboss_4_2_3.

So the question how do I tell ant that the value I'm writing is a file path ?
Note I have tried the following, which actually works :-

<propertyfile file="target.props">
    <entry key="appServerDir" value="${appserver.home}"/>
</propertyfile>

.. ie it outputs the name as c\:\\somedir\\jboss4_2_3, but I'd rather not use this technique and rather use the template file technique, as it contains some properties which are always static, as well as comments etc.

Thanks in advance

Body:
I have just tested using Apache Ant version 1.7.1 compiled on May 25 2010 on Ubuntu server 10.10, and using the Apache Ant version 1.7.1 compiled on June 27 2008 in Eclipse 3.6 on Windows XP. now the results (from both the same):

Variable in source.props:

appserver.home=C\:\\somedir\\jboss_4_2_3

Echo on console:

[echo] C:\somedir\jboss_4_2_3

Variable in target.properties:

appserver.home=C:\somedir\jboss_4_2_3

EDIT - the solution below;-D

In my opinion you should use the propertyfile, if you read the manual for this task you can see that it is able to MANIPUlATE existing property files. This one works for me, and all the comments and vars from template are preserved.

<copy file="template_file.props"  tofile="target.props" />
<propertyfile  file="target.props">
    <entry  key="appserver.home" value="${appserver.home}"/>
</propertyfile>


问:
Exception while calling cassandra and elastic search from same program
I am trying to index my data at cassandra to elastic-search hosted in cloud. I am able to connect and index dummy data with elastic-search easily using transport client. But, when I add datastax driver dependency in my pom file to connect to cassandra I get following exeptions. Weird thing is I am not even connecting to the cassandra clusters. Thanks in advance

Exception in thread "main" java.lang.AbstractMethodError: io.netty.util.concurrent.MultithreadEventExecutorGroup.newChild(Ljava/util/concurrent/Executor;[Ljava/lang/Object;)Lio/netty/util/concurrent/EventExecutor;
    at io.netty.util.concurrent.MultithreadEventExecutorGroup.(MultithreadEventExecutorGroup.java:84)
    at io.netty.util.concurrent.MultithreadEventExecutorGroup.(MultithreadEventExecutorGroup.java:58)
    at io.netty.util.concurrent.MultithreadEventExecutorGroup.(MultithreadEventExecutorGroup.java:47)
    at io.netty.channel.MultithreadEventLoopGroup.(MultithreadEventLoopGroup.java:49)
    at io.netty.channel.nio.NioEventLoopGroup.(NioEventLoopGroup.java:68)
    at io.netty.channel.nio.NioEventLoopGroup.(NioEventLoopGroup.java:63)
    at io.netty.channel.nio.NioEventLoopGroup.(NioEventLoopGroup.java:54)
    at org.elasticsearch.transport.netty4.Netty4Transport.createBootstrap(Netty4Transport.java:201)
    at org.elasticsearch.transport.netty4.Netty4Transport.doStart(Netty4Transport.java:172)
    at org.elasticsearch.xpack.security.transport.netty4.SecurityNetty4Transport.doStart(SecurityNetty4Transport.java:74)
    at org.elasticsearch.common.component.AbstractLifecycleComponent.start(AbstractLifecycleComponent.java:69)
    at org.elasticsearch.transport.TransportService.doStart(TransportService.java:196)
    at org.elasticsearch.common.component.AbstractLifecycleComponent.start(AbstractLifecycleComponent.java:69)
    at org.elasticsearch.client.transport.TransportClient.buildTemplate(TransportClient.java:208)
    at org.elasticsearch.client.transport.TransportClient.(TransportClient.java:268)
    at org.elasticsearch.transport.client.PreBuiltTransportClient.(PreBuiltTransportClient.java:125)
    at org.elasticsearch.xpack.client.PreBuiltXPackTransportClient.(PreBuiltXPackTransportClient.java:55)
    at org.elasticsearch.xpack.client.PreBuiltXPackTransportClient.(PreBuiltXPackTransportClient.java:50)
    at org.elasticsearch.xpack.client.PreBuiltXPackTransportClient.(PreBuiltXPackTransportClient.java:46)

答:
To get around potential conflicts between DataStax java driver's dependency of Netty and other libraries' dependencies on maven, you could use the 'shaded' classifier of the driver jar as described in the driver docs on the 'Using the shaded jar' page:

```<code><dependency>
    <groupId>com.datastax.cassandra</groupId>
    <artifactId>cassandra-driver-core</artifactId>
    <version>3.2.0</version>
    <classifier>shaded</classifier>
    <!-- Because the shaded JAR uses the original POM, you still need
        to exclude this dependency explicitly: -->
    <exclusions>
        <exclusion>
        <groupId>io.netty</groupId>
        <artifactId>*</artifactId>
        </exclusion>
    </exclusions>
</dependency>
</code>```

Note if you aren't using maven, other build tools like gradle should have a way of specifying the classifier, otherwise you can download the shaded jar directly from maven.

Body:
To get around potential conflicts between DataStax java driver's dependency of Netty and other libraries' dependencies on maven, you could use the 'shaded' classifier of the driver jar as described in the driver docs on the 'Using the shaded jar' page:

<dependency>
    <groupId>com.datastax.cassandra</groupId>
    <artifactId>cassandra-driver-core</artifactId>
    <version>3.2.0</version>
    <classifier>shaded</classifier>
    <!-- Because the shaded JAR uses the original POM, you still need
        to exclude this dependency explicitly: -->
    <exclusions>
        <exclusion>
        <groupId>io.netty</groupId>
        <artifactId>*</artifactId>
        </exclusion>
    </exclusions>
</dependency>

Note if you aren't using maven, other build tools like gradle should have a way of specifying the classifier, otherwise you can download the shaded jar directly from maven.


问:
bootstrap modal does not come up
I am trying http://bootstrap-confirmation.js.org

my html has

```<code><html lang="en">

<head>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Log Analyzer</title>

    <!-- Bootstrap Core CSS -->
    <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

    <!-- MetisMenu CSS -->
    <link href="vendor/metisMenu/metisMenu.min.css" rel="stylesheet">

    <!-- DataTables CSS -->
    <link href="vendor/datatables-plugins/dataTables.bootstrap.css" rel="stylesheet">

    <!-- DataTables Responsive CSS -->
    <link href="vendor/datatables-responsive/dataTables.responsive.css" rel="stylesheet">

    <!-- Custom CSS -->
    <link href="dist/css/sb-admin-2.css" rel="stylesheet">

    <!-- Custom Fonts -->
    <link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">

    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
        <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
        <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->

    <style>
    td.details-control {
        background: url('images/details_open.png') no-repeat center center;
        cursor: pointer;
    }

    tr.details td.details-control {
            background: url('images/details_close.png') no-repeat center center;
    }

    td.flag-control {
        background: url('images/ban_circle.png') no-repeat center center;
        cursor: pointer;
    }

      table {
            table-layout:fixed;
        }

            .word-break-all{
                word-break:break-all;
            }
        </style>

</head>

<body>

    <div id="wrapper">

        <!-- Navigation -->

        <div id="page-wrapper">
            <div class="row">
                <div class="col-lg-12">
                       <h4></h4>
                </div>
                <!-- /.col-lg-12 -->
            </div>
            <!-- /.row -->
            <div class="row">
                <div class="col-lg-12">
                    <div class="panel panel-default">
                        <div class="panel-heading">
                          <button class="btn btn-default" data-toggle="confirmation">Confirmation</button>
</code>```

and toward bottom:

```<code><script src="vendor/jquery/jquery.min.js"></script>
<script src="vendor/bootstrap/js/bootstrap.js"></script>
<script type="text/javascript" src="js/bootstrap-confirmation.js"></script>
</code>```

my javascript has:

$(document).ready(function() {

```<code>     $('[data-toggle=confirmation]').confirmation({
        rootSelector: '[data-toggle=confirmation]'
        // other options
        });
});
</code>```

clicking the button nothing happens

Title: bootstrap modal does not come up

Body:
I am trying http://bootstrap-confirmation.js.org

my html has

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Log Analyzer</title>

    <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

    <link href="vendor/metisMenu/metisMenu.min.css" rel="stylesheet">

    <link href="vendor/datatables-plugins/dataTables.bootstrap.css" rel="stylesheet">

    <link href="vendor/datatables-responsive/dataTables.responsive.css" rel="stylesheet">

    <link href="dist/css/sb-admin-2.css" rel="stylesheet">

    <link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">

                          <button class="btn btn-default" data-toggle="confirmation">Confirmation</button>

and toward bottom:

my javascript has:

$(document).ready(function() {

     $('[data-toggle=confirmation]').confirmation({
        rootSelector: '[data-toggle=confirmation]'
        // other options
        });
});

clicking the button nothing happens

Body:
Are you sure that the files are in the right place?  in 2 of the <script> tags, you have a vendor prefix in the path, but in the third one you do not.  Is that correct?  We'd need to see your filesystem to know.

Open your browser's network inspector - are there 404's showing?  did the bootstrap-confirmation.js actually get loaded?

EDIT:
I created a pen:  http://codepen.io/anon/pen/OpegVE   It's working there.  One issue i saw was that the original version of bootstrap-confirmation may not be compatible with bootstrap 3.x.x.  This fork: https://github.com/tavicu/bs-confirmation  claims to be compatible with bootstrap 3.  The pen I made uses the version of boostrap-confirmation you mention in your original post, and also links bootstrap 2.3.1, and they are all working together.

TL;DR:  your version of the plugin and your version of boostrap might not be compatible, and be failing silently?  Worth looking into.


问:
How to split/partition a dataset into training and test datasets for, e.g., cross validation?
What is a good way to split a NumPy array randomly into training and testing/validation dataset? Something similar to the cvpartition or crossvalind functions in Matlab.

答:
As sklearn.cross_validation module was deprecated, you can use:

```<code>import numpy as np
from sklearn.model_selection import train_test_split
X, y = np.arange(10).reshape((5, 2)), range(5)

X_trn, X_tst, y_trn, y_tst = train_test_split(X, y, test_size=0.2, random_state=42)
</code>```

Body:
As sklearn.cross_validation module was deprecated, you can use:

import numpy as np
from sklearn.model_selection import train_test_split
X, y = np.arange(10).reshape((5, 2)), range(5)

X_trn, X_tst, y_trn, y_tst = train_test_split(X, y, test_size=0.2, random_state=42)