问:
Swagger2 too many the same annotations
I integrate swagger2 to springboot project, because all of my endpoints authorization is by OAuth2, so I need to add Authorization header to every method, like the following code:

```<code>@ApiImplicitParams({
    @ApiImplicitParam(paramType="header",name="Authorization",dataType="String",required=true, value="Bearer {access-token}")
})
</code>```

These same annotations are too many, can I have some ways to refactor them?

Swagger2 Docket code:

```<code>@Bean
public Docket createRestApi() {
    return new Docket(DocumentationType.SWAGGER_2)
            .apiInfo(apiInfo())
            .ignoredParameterTypes(TokenInfo.class, HttpServletRequest.class, HttpServletResponse.class)
            .select()
            .apis(RequestHandlerSelectors.basePackage("com.xxx.yyy.resource"))
            .paths(PathSelectors.any())
            .build();
}
</code>```

答:
I spend couple of days to find out the solution. Here I give you the docket config for access_token. Configure a global parameter, can say common parameters (access_token) that includes every end-point.So you don't need to include @ApiImplicitParams to every end-point. Probable docket configuration given below (later your can change of your own for api info).

```<code>@Bean
public Docket api() {
    return new Docket(DocumentationType.SWAGGER_2)
            .select()
            .apis(RequestHandlerSelectors.basePackage("com.xxx.yyy.resource"))
            .paths(PathSelectors.any())
            .build()
            .globalOperationParameters(commonParameters())
            .apiInfo(apiInfo())
            .ignoredParameterTypes(TokenInfo.class, HttpServletRequest.class, HttpServletResponse.class)
            .securityContexts(Lists.newArrayList(securityContext()))
            .securitySchemes(Lists.newArrayList(apiKey()));
}

private List<Parameter> commonParameters() {
    List<Parameter> parameters = new ArrayList<Parameter>();
    parameters.add(new ParameterBuilder()
            .name("access_token")
            .description("token for authorization")
            .modelRef(new ModelRef("string"))
            .parameterType("query")
            .required(true)
            .build());

    return parameters;
}

private ApiInfo apiInfo() {
    ApiInfo apiInfo = new ApiInfo(
            "My REST API",
            "Some custom description of API.",
            "API TOS",
            "Terms of service",
            "myeaddress@company.com",
            "License of API",
            "API license URL");
    return apiInfo;
}

private SecurityContext securityContext() {
    return SecurityContext.builder()
            .securityReferences(defaultAuth())
            .forPaths(PathSelectors.any())
            .build();
}

List<SecurityReference> defaultAuth() {
    AuthorizationScope authorizationScope
            = new AuthorizationScope("global", "accessEverything");
    AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
    authorizationScopes[0] = authorizationScope;
    return Lists.newArrayList(
            new SecurityReference("AUTHORIZATION", authorizationScopes));
}

private ApiKey apiKey() {
    return new ApiKey("AUTHORIZATION", "access_token", "header");
}
</code>```

Just paste the code and try from swagger-ui and let me know the status.

Title: Swagger2 too many the same annotations

Body:
I integrate swagger2 to springboot project, because all of my endpoints authorization is by OAuth2, so I need to add Authorization header to every method, like the following code:

@ApiImplicitParams({
    @ApiImplicitParam(paramType="header",name="Authorization",dataType="String",required=true, value="Bearer {access-token}")
})

These same annotations are too many, can I have some ways to refactor them?

Swagger2 Docket code:

@Bean
public Docket createRestApi() {
    return new Docket(DocumentationType.SWAGGER_2)
            .apiInfo(apiInfo())
            .ignoredParameterTypes(TokenInfo.class, HttpServletRequest.class, HttpServletResponse.class)
            .select()
            .apis(RequestHandlerSelectors.basePackage("com.xxx.yyy.resource"))
            .paths(PathSelectors.any())
            .build();
}

Body:
I spend couple of days to find out the solution. Here I give you the docket config for access_token. Configure a global parameter, can say common parameters (access_token) that includes every end-point.So you don't need to include @ApiImplicitParams to every end-point. Probable docket configuration given below (later your can change of your own for api info).

@Bean
public Docket api() {
    return new Docket(DocumentationType.SWAGGER_2)
            .select()
            .apis(RequestHandlerSelectors.basePackage("com.xxx.yyy.resource"))
            .paths(PathSelectors.any())
            .build()
            .globalOperationParameters(commonParameters())
            .apiInfo(apiInfo())
            .ignoredParameterTypes(TokenInfo.class, HttpServletRequest.class, HttpServletResponse.class)
            .securityContexts(Lists.newArrayList(securityContext()))
            .securitySchemes(Lists.newArrayList(apiKey()));
}

private List<Parameter> commonParameters() {
    List<Parameter> parameters = new ArrayList<Parameter>();
    parameters.add(new ParameterBuilder()
            .name("access_token")
            .description("token for authorization")
            .modelRef(new ModelRef("string"))
            .parameterType("query")
            .required(true)
            .build());

    return parameters;
}

private ApiInfo apiInfo() {
    ApiInfo apiInfo = new ApiInfo(
            "My REST API",
            "Some custom description of API.",
            "API TOS",
            "Terms of service",
            "myeaddress@company.com",
            "License of API",
            "API license URL");
    return apiInfo;
}

private SecurityContext securityContext() {
    return SecurityContext.builder()
            .securityReferences(defaultAuth())
            .forPaths(PathSelectors.any())
            .build();
}

List<SecurityReference> defaultAuth() {
    AuthorizationScope authorizationScope
            = new AuthorizationScope("global", "accessEverything");
    AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
    authorizationScopes[0] = authorizationScope;
    return Lists.newArrayList(
            new SecurityReference("AUTHORIZATION", authorizationScopes));
}

private ApiKey apiKey() {
    return new ApiKey("AUTHORIZATION", "access_token", "header");
}

Just paste the code and try from swagger-ui and let me know the status.


来源: stackexchange

问:
How to create a dictionary from a text file in python?
I want to create a dictionary from a text file in python. My text file is:

```<code>John Doe
Apples
Bananas
Oranges

Jane Dear
Apples
Bananas
Peaches
</code>```

The format of the text file is:

```<code>Name
Fruit
Fruit
.....
Fruit
empty line
Name
Fruit
.....
</code>```

I want to return a dictionary with the fruits as the key and the names as the values such as:

```<code>{"Apples":["John Doe", "Jane Dear"], "Bananas":["John Doe", "Jane Dear"], "Peaches":["Jane Dear"], "Oranges":["John Doe"]}
</code>```

I'm just not entirely sure on how to format the text file. Thanks in advance!

EDIT: What I have done so far

```<code>def common(text):
x = open(text, "r")
a = {}
b = []
line = x.readline()
while line != "":
    b.append(line)
    line = courses.readline()
return b

def create_dict(lst):
a = []
b = {}
names = []
fruits = []
while lst != []:
   if " " in lst[1]:
      names += lst[1]
   else:
      fruits += lst[1]
</code>```

This is where I'm sort of lost...

答:
You can do the following, using some handy utils like itertools.groupby and collections.defaultdict:

```<code>from collections import defaultdict
from itertools import groupby

with open('work/test.txt') as f:
    d = [
        [s.strip() for s in g]
        for k, g in groupby(f, key=lambda l: bool(l.strip())) if k
    ]
    # [['John Doe', 'Apples', 'Bananas', 'Oranges'], ['Jane Dear', 'Apples', 'Bananas', 'Peaches']]
dd = defaultdict(list)
for l in d:
    for fruit in l[1:]:
        dd[fruit].append(l[0])
dd
# {'Apples': ['John Doe', 'Jane Dear'], 'Bananas': ['John Doe', 'Jane Dear'], 'Peaches': ['Jane Dear'], 'Oranges': ['John Doe']}
</code>```

The conditional comprehension groups the lines in the file into groups based on the property of being empty or not and then only takes the groups of non-empty lines (if k). The subsequent use of a defaultdict avoids some bumpy code to check if keys are already present.

ContentLicense: CC BY-SA 3.0

Body:
I want to create a dictionary from a text file in python. My text file is:

John Doe
Apples
Bananas
Oranges

Jane Dear
Apples
Bananas
Peaches

The format of the text file is:

Name
Fruit
Fruit
.....
Fruit
empty line
Name
Fruit
.....

I want to return a dictionary with the fruits as the key and the names as the values such as:

{"Apples":["John Doe", "Jane Dear"], "Bananas":["John Doe", "Jane Dear"], "Peaches":["Jane Dear"], "Oranges":["John Doe"]}

I'm just not entirely sure on how to format the text file. Thanks in advance!

EDIT: What I have done so far

def common(text):
x = open(text, "r")
a = {}
b = []
line = x.readline()
while line != "":
    b.append(line)
    line = courses.readline()
return b

def create_dict(lst):
a = []
b = {}
names = []
fruits = []
while lst != []:
   if " " in lst[1]:
      names += lst[1]
   else:
      fruits += lst[1]

This is where I'm sort of lost...

Body:
You can do the following, using some handy utils like itertools.groupby and collections.defaultdict:

from collections import defaultdict
from itertools import groupby

with open('work/test.txt') as f:
    d = [
        [s.strip() for s in g]
        for k, g in groupby(f, key=lambda l: bool(l.strip())) if k
    ]
    # [['John Doe', 'Apples', 'Bananas', 'Oranges'], ['Jane Dear', 'Apples', 'Bananas', 'Peaches']]
dd = defaultdict(list)
for l in d:
    for fruit in l[1:]:
        dd[fruit].append(l[0])
dd
# {'Apples': ['John Doe', 'Jane Dear'], 'Bananas': ['John Doe', 'Jane Dear'], 'Peaches': ['Jane Dear'], 'Oranges': ['John Doe']}

The conditional comprehension groups the lines in the file into groups based on the property of being empty or not and then only takes the groups of non-empty lines (if k). The subsequent use of a defaultdict avoids some bumpy code to check if keys are already present.


问:
Create two models with one create
While creating a League I'm trying to also create a join association called UsersLeagues. Here is my current attempt:

```<code>def changeset(struct, params \\ %{}) do
    struct
      |> cast(params, [:name])
      |> validate_required([:name])
      |> put_assoc(:users_leagues,UsersLeagues.changeset(%UsersLeagues{}, user_id: 1, league_id: 1, commissioner: true))
end
</code>```

When I try to create with that changeset I get this error. expected params to be a :map, got: [user_id: 1, league_id: 1, commissioner: true]

I'm not sure what it's trying to tell me?

Again, I'm trying to create one model and in that process create a join table.

答:
```<code>def changeset(struct, params \\ %{}) do
struct
  |> cast(params, [:name])
  |> validate_required([:name])
  |> put_assoc(:users_leagues,UsersLeagues.changeset(%UsersLeagues{user_id: 1, league_id: 1, commissioner: true}))
end
</code>```

try this

Changeset is used to validate data before insert it into the data base.

Title: Create two models with one create

Body:
While creating a League I'm trying to also create a join association called UsersLeagues. Here is my current attempt:

def changeset(struct, params \\ %{}) do
    struct
      |> cast(params, [:name])
      |> validate_required([:name])
      |> put_assoc(:users_leagues,UsersLeagues.changeset(%UsersLeagues{}, user_id: 1, league_id: 1, commissioner: true))
end

When I try to create with that changeset I get this error. expected params to be a :map, got: [user_id: 1, league_id: 1, commissioner: true]

I'm not sure what it's trying to tell me?

Again, I'm trying to create one model and in that process create a join table.

Body:
def changeset(struct, params \\ %{}) do
struct
  |> cast(params, [:name])
  |> validate_required([:name])
  |> put_assoc(:users_leagues,UsersLeagues.changeset(%UsersLeagues{user_id: 1, league_id: 1, commissioner: true}))
end

try this

Changeset is used to validate data before insert it into the data base.


问:
Multiple Eclipse projects in one Mercurial repository
I have a number of eclipse projects that I'd like to have in two separate hg repositories.

I've managed to do this by first creating the two hg repository using TortouiseHg and adding, committing my projects to each of the repositories first. By doing that I now have two hg repositories with two projects in each.

Next I clone that repositories in Eclipse using MercurialEclipse. The projects appear as expected in Eclipse.

Example 1:

```<code>Eclipse workspace
               |
               |--Project 1
               |--Project 2
               |--Project 3
               |--Project 4
</code>```

But if I look in the directory structure it looks like this:

Example 2:

```<code>  c:--
     |
     |-workspace
               |
               hgRepository1
               |           |--.hg
               |           |--Project 1
               |           |--Project 2
               |
               |
               hgRepository2
                           |--.hg
                           |--Project 3
                           |--Project 4
</code>```

when I want it to look like this.

Example 3:

```<code>  c:--
     |
     |-workspace
               |--.hg
               |--Project 1
               |--Project 2
               |--Project 3
               |--Project 4
</code>```

Is it possible to have a single Mercurial repository and somehow clone it and have the projects appear directly under workspace directory, and not in a subdirectory?

答:
You shouldn't save project from an Eclipse workspace, or restore them in an Eclipse workspace.

Those projects (.project, .classpath, and other project specific resources) should be in their own directory, outside of the Eclipse workspace (and then imported into the workspace).

That way, any directory structure will be fine for importing the different project into a new Eclipse workspace.

ContentLicense: CC BY-SA 2.5

Body:
I have a number of eclipse projects that I'd like to have in two separate hg repositories.

I've managed to do this by first creating the two hg repository using TortouiseHg and adding, committing my projects to each of the repositories first. By doing that I now have two hg repositories with two projects in each.

Next I clone that repositories in Eclipse using MercurialEclipse. The projects appear as expected in Eclipse.

Example 1:

Eclipse workspace
               |
               |--Project 1
               |--Project 2
               |--Project 3
               |--Project 4

But if I look in the directory structure it looks like this:

Example 2:

  c:--
     |
     |-workspace
               |
               hgRepository1
               |           |--.hg
               |           |--Project 1
               |           |--Project 2
               |
               |
               hgRepository2
                           |--.hg
                           |--Project 3
                           |--Project 4

when I want it to look like this.

Example 3:

  c:--
     |
     |-workspace
               |--.hg
               |--Project 1
               |--Project 2
               |--Project 3
               |--Project 4

Is it possible to have a single Mercurial repository and somehow clone it and have the projects appear directly under workspace directory, and not in a subdirectory?


问:
JSSC - Breaking a connection causes blocking serial ports
I'm using the JSSC Serial Port package to exchange a data between my application and a device connected to the serial port. I made a simple application which can send identification message to the device and prints a response. I wanted it to be resistant to connection errors (for example after unplugging the cable during the communication).

Sequence of actions Init -> Open -> IDN -> Close works perfectly.
When I unplug the cable after opening the port, I can't send a message (seems logical to me) and close the port (there's nothing to be closed anymore so I also understand that).

At the beginning I was surprised that I couldn't close the port after plugging the cable again but I discovered that after every connection of the device, OS gives it a different number which JSSC library use to handle the port. Fortunately, it turned out that simply opening the port after reconnection solves all the problems, because the application can send messages again.

Unfortunately, problems start when there were more attempts of disconnecting/connecting the cable while the port was opened. After every try the application works slower and slower to end at the state when no messages can be sent anymore. Another thing is that in that state all the serial ports (not only the one I try to communicate with) are blocked and I can't even access them through a terminal-like applications.

So the question is:

How can I make the application to be resistant to connection breaks without blocking ports and loosing performance?

I suppose it might be about some sort of resources, memory management or so but my knowledge of these thing isn't sufficient enough to solve the problem by myself.

Implementation of the communication:

```<code>import jssc.SerialPort;
import jssc.SerialPortEvent;
import jssc.SerialPortEventListener;
import jssc.SerialPortException;

class Connection implements SerialPortEventListener {
  private static final int SERIAL_PORT_BAUD_RATE = 9600;
  private static final int SERIAL_PORT_DATA_BITS_NUMBER = 8;
  private static final int SERIAL_PORT_STOP_BITS_NUMBER = 1;
  private static final int SERIAL_PORT_PARITY = 0;

  private SerialPort serialPort;
  private String portName;

  public Connection(String portName) {
    this.portName = portName;
  }

  public void open() throws SerialPortException {
    serialPort = new SerialPort(portName);
    serialPort.openPort();
    serialPort.setParams(SERIAL_PORT_BAUD_RATE,
            SERIAL_PORT_DATA_BITS_NUMBER,
            SERIAL_PORT_STOP_BITS_NUMBER,
            SERIAL_PORT_PARITY);
    serialPort.addEventListener(this);
  }

  public void close() throws SerialPortException {
    if (serialPort != null) {
      serialPort.closePort();
    }
  }

  public void simpleMessage() throws SerialPortException {
    if (serialPort != null) {
      serialPort.writeString("IDN");
    }
  }

  @Override
  public void serialEvent(SerialPortEvent serialPortEvent) {
    if (serialPortEvent.getEventType() == SerialPortEvent.RXCHAR) {
      try {
        System.out.println(serialPort.readString());
      } catch (SerialPortException e) {
        System.out.println("Error while reading a string.");
      }
    }
  }
}
</code>```

Main class:

```<code>import javafx.application.Application;
import javafx.application.Platform;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import java.io.IOException;

public class MainApplication extends Application{
  public static void main(String [] args) {
    Application.launch();
  }

  @Override
  public void start(Stage primaryStage) throws Exception {
    Pane rootPane = null;
    FXMLLoader loader = new FXMLLoader();
    loader.setLocation(MainApplication.class.getResource("front.fxml"));

    try{
      rootPane = loader.load();
    } catch (IOException exception) {
      exception.printStackTrace();
    }

    Scene scene = new Scene(rootPane);
    primaryStage.setScene(scene);
    primaryStage.show();
    primaryStage.setOnCloseRequest(event -> {
      Platform.exit();
      System.exit(0);
    });
  }
}
</code>```

FXML code:

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

<?import javafx.scene.layout.StackPane?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.layout.VBox?>

<StackPane fx:id="rootPane"
           xmlns="http://javafx.com/javafx/8.0.60"
           xmlns:fx="http://javafx.com/fxml/1"
           fx:controller="FrontController">
    <VBox>
        <Button text="Init" onAction="#init"/>
        <Button text="Open" onAction="#openPort"/>
        <Button text="Close" onAction="#closePort"/>
        <Button text="IDN" onAction="#idn"/>
        <Button text="Get Ports" onAction="#getPorts"/>
        <Button text="Is opened?" onAction="#isPortOpen"/>
    </VBox>
</StackPane>
</code>```

Controller:

```<code>import javafx.fxml.FXML;
import jssc.SerialPortException;
import jssc.SerialPortList;
import java.util.Arrays;

public class FrontController {

  private Connection connection;

  @FXML
  private void init() {
    String portName = "COM4";
    connection = new Connection(portName);
  }

  @FXML
  private void openPort() {
    try {
      connection.open();
    } catch (SerialPortException e) {
      e.printStackTrace();
    }
  }

  @FXML
  private void closePort() {
    try {
      connection.close();
    } catch (SerialPortException e) {
      e.printStackTrace();
    }
  }

  @FXML
  private void idn() {
    try {
      connection.idnMessage();
    } catch (SerialPortException e) {
      e.printStackTrace();
    }
  }

  @FXML
  private void getPorts() {
    System.out.println(Arrays.toString(SerialPortList.getPortNames()));
  }

  @FXML
  private void isPortOpen() {
    System.out.println(connection.getSerialPort().isOpened());
  }
}
</code>```

答:
Basically unplugging device without closing sometimes (infact most times in windows OS) leaves OS in inconsistent state. You need to do clean up when device is removed. Please note it is very important to close port even if device has been removed. We may leave the return value of close. This gives hint to OS that app is also not interested in device so OS has the liberty to release resources which we also want.
So in a nutshell we need to create a thread which will monitor if our device is attached to system or not.</p>

Body:
I'm using the JSSC Serial Port package to exchange a data between my application and a device connected to the serial port. I made a simple application which can send identification message to the device and prints a response. I wanted it to be resistant to connection errors (for example after unplugging the cable during the communication).

Sequence of actions Init -> Open -> IDN -> Close works perfectly.
When I unplug the cable after opening the port, I can't send a message (seems logical to me) and close the port (there's nothing to be closed anymore so I also understand that).

At the beginning I was surprised that I couldn't close the port after plugging the cable again but I discovered that after every connection of the device, OS gives it a different number which JSSC library use to handle the port. Fortunately, it turned out that simply opening the port after reconnection solves all the problems, because the application can send messages again.

Unfortunately, problems start when there were more attempts of disconnecting/connecting the cable while the port was opened. After every try the application works slower and slower to end at the state when no messages can be sent anymore. Another thing is that in that state all the serial ports (not only the one I try to communicate with) are blocked and I can't even access them through a terminal-like applications.

So the question is:

How can I make the application to be resistant to connection breaks without blocking ports and loosing performance?

I suppose it might be about some sort of resources, memory management or so but my knowledge of these thing isn't sufficient enough to solve the problem by myself.

Implementation of the communication:

import jssc.SerialPort;
import jssc.SerialPortEvent;
import jssc.SerialPortEventListener;
import jssc.SerialPortException;

class Connection implements SerialPortEventListener {
  private static final int SERIAL_PORT_BAUD_RATE = 9600;
  private static final int SERIAL_PORT_DATA_BITS_NUMBER = 8;
  private static final int SERIAL_PORT_STOP_BITS_NUMBER = 1;
  private static final int SERIAL_PORT_PARITY = 0;

  private SerialPort serialPort;
  private String portName;

  public Connection(String portName) {
    this.portName = portName;
  }

  public void open() throws SerialPortException {
    serialPort = new SerialPort(portName);
    serialPort.openPort();
    serialPort.setParams(SERIAL_PORT_BAUD_RATE,
            SERIAL_PORT_DATA_BITS_NUMBER,
            SERIAL_PORT_STOP_BITS_NUMBER,
            SERIAL_PORT_PARITY);
    serialPort.addEventListener(this);
  }

  public void close() throws SerialPortException {
    if (serialPort != null) {
      serialPort.closePort();
    }
  }

  public void simpleMessage() throws SerialPortException {
    if (serialPort != null) {
      serialPort.writeString("IDN");
    }
  }

  @Override
  public void serialEvent(SerialPortEvent serialPortEvent) {
    if (serialPortEvent.getEventType() == SerialPortEvent.RXCHAR) {
      try {
        System.out.println(serialPort.readString());
      } catch (SerialPortException e) {
        System.out.println("Error while reading a string.");
      }
    }
  }
}

Main class:

import javafx.application.Application;
import javafx.application.Platform;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import java.io.IOException;

public class MainApplication extends Application{
  public static void main(String [] args) {
    Application.launch();
  }

  @Override
  public void start(Stage primaryStage) throws Exception {
    Pane rootPane = null;
    FXMLLoader loader = new FXMLLoader();
    loader.setLocation(MainApplication.class.getResource("front.fxml"));

    try{
      rootPane = loader.load();
    } catch (IOException exception) {
      exception.printStackTrace();
    }

    Scene scene = new Scene(rootPane);
    primaryStage.setScene(scene);
    primaryStage.show();
    primaryStage.setOnCloseRequest(event -> {
      Platform.exit();
      System.exit(0);
    });
  }
}

FXML code:

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

<?import javafx.scene.layout.StackPane?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.layout.VBox?>

<StackPane fx:id="rootPane"
           xmlns="http://javafx.com/javafx/8.0.60"
           xmlns:fx="http://javafx.com/fxml/1"
           fx:controller="FrontController">
    <VBox>
        <Button text="Init" onAction="#init"/>
        <Button text="Open" onAction="#openPort"/>
        <Button text="Close" onAction="#closePort"/>
        <Button text="IDN" onAction="#idn"/>
        <Button text="Get Ports" onAction="#getPorts"/>
        <Button text="Is opened?" onAction="#isPortOpen"/>
    </VBox>
</StackPane>

Controller:

import javafx.fxml.FXML;
import jssc.SerialPortException;
import jssc.SerialPortList;
import java.util.Arrays;

public class FrontController {

  private Connection connection;

  @FXML
  private void init() {
    String portName = "COM4";
    connection = new Connection(portName);
  }

  @FXML
  private void openPort() {
    try {
      connection.open();
    } catch (SerialPortException e) {
      e.printStackTrace();
    }
  }

  @FXML
  private void closePort() {
    try {
      connection.close();
    } catch (SerialPortException e) {
      e.printStackTrace();
    }
  }

  @FXML
  private void idn() {
    try {
      connection.idnMessage();
    } catch (SerialPortException e) {
      e.printStackTrace();
    }
  }

  @FXML
  private void getPorts() {
    System.out.println(Arrays.toString(SerialPortList.getPortNames()));
  }

  @FXML
  private void isPortOpen() {
    System.out.println(connection.getSerialPort().isOpened());
  }
}


问:
How to validate date with format "mm/dd/yyyy" in JavaScript?
I want to validate the date format on an input using the format mm/dd/yyyy.

I found below codes in one site and then used it but it doesn't work:

```<code>function isDate(ExpiryDate) {
    var objDate,  // date object initialized from the ExpiryDate string
        mSeconds, // ExpiryDate in milliseconds
        day,      // day
        month,    // month
        year;     // year
    // date length should be 10 characters (no more no less)
    if (ExpiryDate.length !== 10) {
        return false;
    }
    // third and sixth character should be '/'
    if (ExpiryDate.substring(2, 3) !== '/' || ExpiryDate.substring(5, 6) !== '/') {
        return false;
    }
    // extract month, day and year from the ExpiryDate (expected format is mm/dd/yyyy)
    // subtraction will cast variables to integer implicitly (needed
    // for !== comparing)
    month = ExpiryDate.substring(0, 2) - 1; // because months in JS start from 0
    day = ExpiryDate.substring(3, 5) - 0;
    year = ExpiryDate.substring(6, 10) - 0;
    // test year range
    if (year < 1000 || year > 3000) {
        return false;
    }
    // convert ExpiryDate to milliseconds
    mSeconds = (new Date(year, month, day)).getTime();
    // initialize Date() object from calculated milliseconds
    objDate = new Date();
    objDate.setTime(mSeconds);
    // compare input date and parts from Date() object
    // if difference exists then date isn't valid
    if (objDate.getFullYear() !== year ||
        objDate.getMonth() !== month ||
        objDate.getDate() !== day) {
        return false;
    }
    // otherwise return true
    return true;
}

function checkDate(){
    // define date string to test
    var ExpiryDate = document.getElementById(' ExpiryDate').value;
    // check date and print message
    if (isDate(ExpiryDate)) {
        alert('OK');
    }
    else {
        alert('Invalid date format!');
    }
}
</code>```

Any suggestion about what could be wrong?

答:
Here is one snippet to check for valid date:

function validateDate(dateStr) {
   const regExp = /^(\d\d?)\/(\d\d?)\/(\d{4})$/;
   let matches = dateStr.match(regExp);
   let isValid = matches;
   let maxDate = [0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

   if (matches) {
     const month = parseInt(matches[1]);
     const date = parseInt(matches[2]);
     const year = parseInt(matches[3]);

     isValid = month <= 12 && month > 0;
     isValid &= date <= maxDate[month] && date > 0;

     const leapYear = (year % 400 == 0)
        || (year % 4 == 0 && year % 100 != 0);
     isValid &= month != 2 || leapYear || date <= 28;
   }

   return isValid
}

console.log(['1/1/2017', '01/1/2017', '1/01/2017', '01/01/2017', '13/12/2017', '13/13/2017', '12/35/2017'].map(validateDate));```

Body:
I want to validate the date format on an input using the format mm/dd/yyyy.

I found below codes in one site and then used it but it doesn't work:

function isDate(ExpiryDate) {
    var objDate,  // date object initialized from the ExpiryDate string
        mSeconds, // ExpiryDate in milliseconds
        day,      // day
        month,    // month
        year;     // year
    // date length should be 10 characters (no more no less)
    if (ExpiryDate.length !== 10) {
        return false;
    }
    // third and sixth character should be '/'
    if (ExpiryDate.substring(2, 3) !== '/' || ExpiryDate.substring(5, 6) !== '/') {
        return false;
    }
    // extract month, day and year from the ExpiryDate (expected format is mm/dd/yyyy)
    // subtraction will cast variables to integer implicitly (needed
    // for !== comparing)
    month = ExpiryDate.substring(0, 2) - 1; // because months in JS start from 0
    day = ExpiryDate.substring(3, 5) - 0;
    year = ExpiryDate.substring(6, 10) - 0;
    // test year range
    if (year < 1000 || year > 3000) {
        return false;
    }
    // convert ExpiryDate to milliseconds
    mSeconds = (new Date(year, month, day)).getTime();
    // initialize Date() object from calculated milliseconds
    objDate = new Date();
    objDate.setTime(mSeconds);
    // compare input date and parts from Date() object
    // if difference exists then date isn't valid
    if (objDate.getFullYear() !== year ||
        objDate.getMonth() !== month ||
        objDate.getDate() !== day) {
        return false;
    }
    // otherwise return true
    return true;
}

function checkDate(){
    // define date string to test
    var ExpiryDate = document.getElementById(' ExpiryDate').value;
    // check date and print message
    if (isDate(ExpiryDate)) {
        alert('OK');
    }
    else {
        alert('Invalid date format!');
    }
}

Any suggestion about what could be wrong?


问:
Any known Vulnerabilities in RxJS 5
Trying to understand if RxJs can be used safely in production.
Anyone knows about Vulnerabilities in RxJS 5.
Are the below issues known with RxJS5. Please help. </p>

```<code>**Vulnerabilities - Public Data**
CVE-2017-1000048 High Risk Prototype Override Protection Bypass qs 2.4.2
CVE-2015-8855 High Risk Regular Expression Denial Of Service (ReDoS) semver 2.3.2
CVE-2017-1000048 High Risk Prototype Override Protection Bypass qs 5.2.1
CVE-2017-1000048 High Risk Prototype Override Protection Bypass qs 2.3.3
CVE-2017-15010 Medium Risk Regular Expression Denial Of Service (ReDoS) Via Parsing Cookies tough-cookie 2.3.2
CVE-2017-15010 Medium Risk Regular Expression Denial Of Service (ReDoS) Via Parsing Cookies tough-cookie 2.2.2

**Vulnerabilities - Premium Data**
RESERVED (CVE-2016-1000023) High Risk Regular Expression Denial Of Service (ReDoS) minimatch 0.3.0
RESERVED (CVE-2016-1000023) High Risk Regular Expression Denial Of Service (ReDoS) minimatch 2.0.10
NO-CVE High Risk Remote Code Execution (RCE) growl 1.9.2
RESERVED (CVE-2016-1000023) High Risk Regular Expression Denial Of Service (ReDoS) minimatch 2.0.4
NO-CVE Medium Risk Insecure Cipher request 2.55.0
NO-CVE Medium Risk Remote Memory Disclosure request 2.55.0
NO-CVE Medium Risk Insecure Cipher request 2.67.0
NO-CVE Medium Risk Remote Memory Disclosure request 2.67.0
RESERVED (CVE-2016-2515) Medium Risk Regular Expression Denial Of Service (ReDoS) hawk 2.3.1
NO-CVE Medium Risk Insecure Cipher request 2.79.0
NO-CVE Medium Risk Regular Expression Denial Of Service (ReDoS) debug 2.6.8
NO-CVE Medium Risk Insecure Cipher request 2.81.0
NO-CVE Medium Risk Denial Of Service (DoS) ws 1.1.5
NO-CVE Medium Risk Timing Attacks http-signature 0.10.1
NO-CVE Medium Risk Arbitrary Command Injection shelljs 0.7.6
RESERVED (CVE-2016-1000013) Medium Risk Cross-site Scripting (XSS) Due To Sanitization Bypass Using HTML Entities marked 0.3.5
NO-CVE Medium Risk Cross-site Scripting (XSS) marked 0.3.5
NO-CVE Medium Risk Cross-Site Scripting (XSS) marked 0.3.5
NO-CVE Medium Risk Regular Expression Denial Of Service (ReDoS) marked 0.3.5
NO-CVE Medium Risk Regular Expression Denial Of Service (ReDoS) debug 2.2.0
NO-CVE Medium Risk Regular Expression Denial Of Service (ReDoS) ms 0.7.3
NO-CVE Medium Risk Regular Expression Denial Of Service (ReDoS) ms 0.7.1
NO-CVE Medium Risk Regular Expression Denial Of Service (ReDoS) debug 2.6.6
NO-CVE Medium Risk Information Disclosure tunnel-agent 0.4.3
NO-CVE Medium Risk Regular Expression Denial Of Service (ReDoS) Via Long String Of Semicolons tough-cookie 2.2.2
</code>```

答:
Problem solved. The report given to me got reverted back, saying some issue on how the SourceClear was run.

No Vulnerabilities are found in RxJS. All Good.

The new report came back with Zero (0) Vulnerabilities.

Title: Any known Vulnerabilities in RxJS 5

Body:
Trying to understand if RxJs can be used safely in production.
Anyone knows about Vulnerabilities in RxJS 5.
Are the below issues known with RxJS5. Please help.

**Vulnerabilities - Public Data**
CVE-2017-1000048 High Risk Prototype Override Protection Bypass qs 2.4.2
CVE-2015-8855 High Risk Regular Expression Denial Of Service (ReDoS) semver 2.3.2
CVE-2017-1000048 High Risk Prototype Override Protection Bypass qs 5.2.1
CVE-2017-1000048 High Risk Prototype Override Protection Bypass qs 2.3.3
CVE-2017-15010 Medium Risk Regular Expression Denial Of Service (ReDoS) Via Parsing Cookies tough-cookie 2.3.2
CVE-2017-15010 Medium Risk Regular Expression Denial Of Service (ReDoS) Via Parsing Cookies tough-cookie 2.2.2

**Vulnerabilities - Premium Data**
RESERVED (CVE-2016-1000023) High Risk Regular Expression Denial Of Service (ReDoS) minimatch 0.3.0
RESERVED (CVE-2016-1000023) High Risk Regular Expression Denial Of Service (ReDoS) minimatch 2.0.10
NO-CVE High Risk Remote Code Execution (RCE) growl 1.9.2
RESERVED (CVE-2016-1000023) High Risk Regular Expression Denial Of Service (ReDoS) minimatch 2.0.4
NO-CVE Medium Risk Insecure Cipher request 2.55.0
NO-CVE Medium Risk Remote Memory Disclosure request 2.55.0
NO-CVE Medium Risk Insecure Cipher request 2.67.0
NO-CVE Medium Risk Remote Memory Disclosure request 2.67.0
RESERVED (CVE-2016-2515) Medium Risk Regular Expression Denial Of Service (ReDoS) hawk 2.3.1
NO-CVE Medium Risk Insecure Cipher request 2.79.0
NO-CVE Medium Risk Regular Expression Denial Of Service (ReDoS) debug 2.6.8
NO-CVE Medium Risk Insecure Cipher request 2.81.0
NO-CVE Medium Risk Denial Of Service (DoS) ws 1.1.5
NO-CVE Medium Risk Timing Attacks http-signature 0.10.1
NO-CVE Medium Risk Arbitrary Command Injection shelljs 0.7.6
RESERVED (CVE-2016-1000013) Medium Risk Cross-site Scripting (XSS) Due To Sanitization Bypass Using HTML Entities marked 0.3.5
NO-CVE Medium Risk Cross-site Scripting (XSS) marked 0.3.5
NO-CVE Medium Risk Cross-Site Scripting (XSS) marked 0.3.5
NO-CVE Medium Risk Regular Expression Denial Of Service (ReDoS) marked 0.3.5
NO-CVE Medium Risk Regular Expression Denial Of Service (ReDoS) debug 2.2.0
NO-CVE Medium Risk Regular Expression Denial Of Service (ReDoS) ms 0.7.3
NO-CVE Medium Risk Regular Expression Denial Of Service (ReDoS) ms 0.7.1
NO-CVE Medium Risk Regular Expression Denial Of Service (ReDoS) debug 2.6.6
NO-CVE Medium Risk Information Disclosure tunnel-agent 0.4.3
NO-CVE Medium Risk Regular Expression Denial Of Service (ReDoS) Via Long String Of Semicolons tough-cookie 2.2.2


问:
Ubuntu 14.04:Export mysql database failed with command line
I am using Ubuntu 14.04 and Vagrant, And I want to export the database with mysql command line,But always failed with this message:

you have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'mysqldump -u root -p hockey_development>/home/jason/Documents/Projects/hockey_development1.sql'

I think there is no problems in this command line and the database;

error message

答:
Using mysqldump, you can backup a local database using a single command.

backup: # mysqldump -u root -p[root_password] [database_name] > dumpfilename.sql

Source: Backup and Restore MySQL Database Using mysqldump


问:
AbsoluteUri need to return correct path
Using method bellow in my MVC view I am getting URL like "localhost:54871/Home/Index" but I don't want "Index" on last. It should be only "localhost:54871/Home". How should I implement this?

```<code>@(Request.Url.AbsoluteUri)
</code>```

Thank you for your help!

答:
While using Request.Url.AbsoluteUri  the url changes based on the user's current page.

If user visits http://localhost:0000/Home/ then AbsoluteUri is  http://localhost:0000/Home/

If user visits http://localhost:0000/Home/Index then AbsoluteUri is  http://localhost:0000/Home/Index

In MVC url generation is based on the route definition defined in RouteConfig.cs file.

You can define route just for controller name, check this and this

Also there is another solution as below:

```<code>@{
Uri uriAddress = new Uri(Request.Url.AbsoluteUri);

string urlLeftPart = uriAddress.GetLeftPart(UriPartial.Authority);

string controllerName = HttpContext.Current.Request.RequestContext.RouteData.
Values["controller"].ToString();

string finalURL = urlLeftPart + "/" + controllerName;
}

<a href="@finalURL">Url Without Action Name</a>
</code>```

References

1.

2.

Title: AbsoluteUri need to return correct path

Body:
Using method bellow in my MVC view I am getting URL like "localhost:54871/Home/Index" but I don't want "Index" on last. It should be only "localhost:54871/Home". How should I implement this?

@(Request.Url.AbsoluteUri)

Thank you for your help!

Body:
While using Request.Url.AbsoluteUri  the url changes based on the user's current page.

If user visits http://localhost:0000/Home/ then AbsoluteUri is  http://localhost:0000/Home/

If user visits http://localhost:0000/Home/Index then AbsoluteUri is  http://localhost:0000/Home/Index

In MVC url generation is based on the route definition defined in RouteConfig.cs file.

You can define route just for controller name, check this and this

Also there is another solution as below:

@{
Uri uriAddress = new Uri(Request.Url.AbsoluteUri);

string urlLeftPart = uriAddress.GetLeftPart(UriPartial.Authority);

string controllerName = HttpContext.Current.Request.RequestContext.RouteData.
Values["controller"].ToString();

string finalURL = urlLeftPart + "/" + controllerName;
}

<a href="@finalURL">Url Without Action Name</a>

References

1.

2.


问:
POSTGRES : SELECT : Query for number of rows which EXIST BETWEEN given range
I have to query the table to search for given conditions :

order_no specified in the range must exist.

Example:  I am getting a request for a range of order_no: 003 - 007. So, I want to check whether all the order_no mentioned in range exist or not.If not exist return false.

The order_status of ALL order_no must be 1. If not exist return false.

Order_string    Order_no   Order_status
    ABE              1                1
    ABE              2                1
    ABE              3                0
    PSB              4                0
    PSB              5                1
    PSB              6                0
    REL              7                0
    REL              8                1
    REL              9                1
    REL              10               1

I was trying EXIST and BETWEEN but unable to query the DB.

答:
If I understand you question correctly, you want a false if at least one of the ORDER_STATUS for ORDER_NO between 3 and 7 is 0

```<code>SELECT
CASE WHEN Z.SUM_STATUS > 0 THEN 'FALSE' ELSE 'TRUE' END AS RESULT
FROM
    (SELECT
    SUM(CASE WHEN (ORDER_NO BETWEEN 3 AND 7) AND (ORDER_STATUS = 0) THEN 1 ELSE 0 END) AS SUM_STATUS
    FROM YOUR_TABLE) Z;
</code>```

Body:
If I understand you question correctly, you want a false if at least one of the ORDER_STATUS for ORDER_NO between 3 and 7 is 0

SELECT
CASE WHEN Z.SUM_STATUS > 0 THEN 'FALSE' ELSE 'TRUE' END AS RESULT
FROM
    (SELECT
    SUM(CASE WHEN (ORDER_NO BETWEEN 3 AND 7) AND (ORDER_STATUS = 0) THEN 1 ELSE 0 END) AS SUM_STATUS
    FROM YOUR_TABLE) Z;


问:
Soundpool crashes when loading WAV file on Samsung Galaxy Note 8
I'm using the SoundPool object to load 2 wav files like so:

```<code> public RingtoneManager(Context context) {

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        soundPool = createSoundPool();
    } else {
        soundPool = createLegacySoundPool();
    }

    RING_OUT = soundPool.load(context, R.raw.groovy, 1);
    sounds.put(RING_OUT, -1);

    RING_IN = soundPool.load(context, R.raw.ring_ring_wav, 1); // crashes on this line
    sounds.put(RING_IN, -1);

}

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
protected SoundPool createSoundPool() {

    Logger.log(TAG, "createSoundPool load attributes");
    AudioAttributes attributes = new AudioAttributes.Builder()
            .setUsage(AudioAttributes.USAGE_VOICE_COMMUNICATION_SIGNALLING)
            .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
            .build();

    Logger.log(TAG, "build soundpool");
    return new SoundPool.Builder()
            .setAudioAttributes(attributes)
            .build();
}

@SuppressWarnings("deprecation")
protected SoundPool createLegacySoundPool() {
    Logger.log(TAG, "createLegacySoundPool");
    return new SoundPool(5, AudioManager.STREAM_MUSIC, 0);
}
</code>```

I've had no problem on any device with this code until recently I tested on a new Samsung Galaxy Note 8. It crashes consistently when attempting to load the ring_ring_wav.wav file with the following stack trace:

```<code>    09-27 20:30:20.033 23644-23644/? A/DEBUG: *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
09-27 20:30:20.033 23644-23644/? A/DEBUG: Build fingerprint: 'samsung/greatltexx/greatlte:7.1.1/NMF26X/N950FXXU1AQI1:user/release-keys'
09-27 20:30:20.033 23644-23644/? A/DEBUG: Revision: '9'
09-27 20:30:20.033 23644-23644/? A/DEBUG: ABI: 'arm'
09-27 20:30:20.034 23644-23644/? A/DEBUG: pid: 23526, tid: 23629, name: SoundPoolThread  >>> com.wizix.gridme <<<
09-27 20:30:20.034 23644-23644/? A/DEBUG: signal 6 (SIGABRT), code -6 (SI_TKILL), fault addr --------
09-27 20:30:20.041 23644-23644/? A/DEBUG: Abort message: 'buffer(0xddf28068) localRefcount 1 != 0, remoteRefcount 0'
09-27 20:30:20.041 23644-23644/? A/DEBUG:     r0 00000000  r1 00005c4d  r2 00000006  r3 00000008
09-27 20:30:20.041 23644-23644/? A/DEBUG:     r4 c59b9978  r5 00000006  r6 c59b9920  r7 0000010c
09-27 20:30:20.041 23644-23644/? A/DEBUG:     r8 c6018120  r9 e7ae5ee6  sl e7ae5fb0  fp c9e716b0
09-27 20:30:20.041 23644-23644/? A/DEBUG:     ip 00000000  sp c59b92f0  lr e9ff1097  pc e9ff38f4  cpsr 200e0010
09-27 20:30:20.052 23644-23644/? A/DEBUG: backtrace:
09-27 20:30:20.053 23644-23644/? A/DEBUG:     #00 pc 0004a8f4  /system/lib/libc.so (tgkill+12)
09-27 20:30:20.053 23644-23644/? A/DEBUG:     #01 pc 00048093  /system/lib/libc.so (pthread_kill+34)
09-27 20:30:20.053 23644-23644/? A/DEBUG:     #02 pc 0001db6d  /system/lib/libc.so (raise+10)
09-27 20:30:20.053 23644-23644/? A/DEBUG:     #03 pc 00019271  /system/lib/libc.so (__libc_android_abort+34)
09-27 20:30:20.053 23644-23644/? A/DEBUG:     #04 pc 0001718c  /system/lib/libc.so (abort+4)
09-27 20:30:20.053 23644-23644/? A/DEBUG:     #05 pc 0000c971  /system/lib/libcutils.so (__android_log_assert+112)
09-27 20:30:20.053 23644-23644/? A/DEBUG:     #06 pc 00018355  /system/lib/libstagefright_foundation.so (_ZN7android16MediaBufferGroupD1Ev+168)
09-27 20:30:20.053 23644-23644/? A/DEBUG:     #07 pc 00018399  /system/lib/libstagefright_foundation.so (_ZN7android16MediaBufferGroupD0Ev+2)
09-27 20:30:20.053 23644-23644/? A/DEBUG:     #08 pc 00121eb1  /system/lib/libstagefright.so (_ZN7android9WAVSource4stopEv+20)
09-27 20:30:20.053 23644-23644/? A/DEBUG:     #09 pc 00121aeb  /system/lib/libstagefright.so (_ZN7android9WAVSourceD2Ev+34)
09-27 20:30:20.053 23644-23644/? A/DEBUG:     #10 pc 00121bd7  /system/lib/libstagefright.so (_ZTv0_n12_N7android9WAVSourceD0Ev+18)
09-27 20:30:20.053 23644-23644/? A/DEBUG:     #11 pc 0000bd87  /system/lib/libutils.so (_ZNK7android7RefBase9decStrongEPKv+58)
09-27 20:30:20.053 23644-23644/? A/DEBUG:     #12 pc 0000520b  /system/lib/libsoundextractor.so (_ZN7android20SoundExtractorParserD1Ev+46)
09-27 20:30:20.053 23644-23644/? A/DEBUG:     #13 pc 00005343  /system/lib/libsoundextractor.so (_ZN7android23SoundExtractorMp3ParserD0Ev+2)
09-27 20:30:20.053 23644-23644/? A/DEBUG:     #14 pc 0000bd87  /system/lib/libutils.so (_ZNK7android7RefBase9decStrongEPKv+58)
09-27 20:30:20.053 23644-23644/? A/DEBUG:     #15 pc 00005b31  /system/lib/libsoundextractor.so (_ZN7android19SoundExtractorCodecD1Ev+24)
09-27 20:30:20.053 23644-23644/? A/DEBUG:     #16 pc 00005bdb  /system/lib/libsoundextractor.so (_ZN7android22SoundExtractorRawCodecD0Ev+2)
09-27 20:30:20.053 23644-23644/? A/DEBUG:     #17 pc 0000bd87  /system/lib/libutils.so (_ZNK7android7RefBase9decStrongEPKv+58)
09-27 20:30:20.053 23644-23644/? A/DEBUG:     #18 pc 0000513d  /system/lib/libsoundextractor.so (_ZN7android14SoundExtractor7releaseEv+12)
09-27 20:30:20.053 23644-23644/? A/DEBUG:     #19 pc 00005ecf  /system/lib/libsoundpool.so (_ZN7android6Sample6doLoadEv+258)
09-27 20:30:20.053 23644-23644/? A/DEBUG:     #20 pc 000069ad  /system/lib/libsoundpool.so (_ZN7android15SoundPoolThread12doLoadSampleEi+32)
09-27 20:30:20.053 23644-23644/? A/DEBUG:     #21 pc 0000695f  /system/lib/libsoundpool.so (_ZN7android15SoundPoolThread3runEv+18)
09-27 20:30:20.053 23644-23644/? A/DEBUG:     #22 pc 000068e7  /system/lib/libsoundpool.so (_ZN7android15SoundPoolThread11beginThreadEPv+2)
09-27 20:30:20.053 23644-23644/? A/DEBUG:     #23 pc 0006b65d  /system/lib/libandroid_runtime.so (_ZN7android14AndroidRuntime15javaThreadShellEPv+80)
09-27 20:30:20.053 23644-23644/? A/DEBUG:     #24 pc 00047b63  /system/lib/libc.so (_ZL15__pthread_startPv+22)
09-27 20:30:20.053 23644-23644/? A/DEBUG:     #25 pc 00019ee1  /system/lib/libc.so (__start_thread+6)
</code>```

If I download the file directly to the device it plays fine through Chrome. The other wav file loads and plays fine in the soundpool.

答:
Me too. It's happen only on Samsung Galaxy Note 8.
Edit: sound is wav type.

My code is very simple

```<code>SoundPool soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
soundPool.load(activity, R.raw.music01, 1);
</code>```

Crash log:

```<code>12-04 15:33:10.226 28617-29183/com.company.appname D/MediaBufferGroup: creating MemoryDealer
12-04 15:33:10.232 28617-29183/com.company.appname A/MediaBufferGroup: buffer(0xaf561118) localRefcount 1 != 0, remoteRefcount 0
12-04 15:33:10.308 3823-4594/? E/Watchdog: !@Sync 237 [2017-12-04 15:33:10.308]

                                           --------- beginning of crash
12-04 15:33:10.395 29207-29183/? A/google-breakpad: Microdump skipped (uninteresting)
12-04 15:33:10.417 28617-29183/com.company.appname W/google-breakpad: ### ### ### ### ### ### ### ### ### ### ### ### ###
12-04 15:33:10.417 28617-29183/com.company.appname W/google-breakpad: Chrome build fingerprint:
12-04 15:33:10.417 28617-29183/com.company.appname W/google-breakpad: 1.0.0
12-04 15:33:10.417 28617-29183/com.company.appname W/google-breakpad: 1
12-04 15:33:10.417 28617-29183/com.company.appname W/google-breakpad: ### ### ### ### ### ### ### ### ### ### ### ### ###
12-04 15:33:10.419 28617-29183/com.company.appname A/libc: Fatal signal 6 (SIGABRT), code -6 in tid 29183 (SoundPoolThread)

                                                        [ 12-04 15:33:10.422  3230: 3230 W/         ]
                                                        debuggerd: handling request: pid=28617 uid=10215 gid=10215 tid=29183
12-04 15:33:10.492 3426-3426/? E/audit: type=1400 audit(1512369190.486:741): avc:  denied  { search } for  pid=29208 comm="debuggerd" name="com.company.appname" dev="dm-1" ino=1310724 scontext=u:r:debuggerd:s0 tcontext=u:object_r:app_data_file:s0:c512,c768 tclass=dir permissive=0 SEPF_SECMOBILE_7.1.1_0001 audit_filtered
12-04 15:33:10.493 3426-3426/? E/audit: type=1300 audit(1512369190.486:741): arch=40000028 syscall=322 per=8 success=no exit=-13 a0=ffffff9c a1=f4c97880 a2=20000 a3=0 items=0 ppid=3230 pid=29208 auid=4294967295 uid=0 gid=0 euid=0 suid=0 fsuid=0 egid=0 sgid=0 fsgid=0 tty=(none) ses=4294967295 comm="debuggerd" exe="/system/bin/debuggerd" subj=u:r:debuggerd:s0 key=(null)
12-04 15:33:10.493 3426-3426/? E/audit: type=1327 audit(1512369190.486:741): proctitle="/system/bin/debuggerd"
12-04 15:33:10.618 29208-29208/? A/DEBUG: *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
12-04 15:33:10.619 29208-29208/? A/DEBUG: Build fingerprint: 'samsung/greatlteks/greatlteks:7.1.1/NMF26X/N950NKSU1AQI2:user/release-keys'
12-04 15:33:10.619 29208-29208/? A/DEBUG: Revision: '9'
12-04 15:33:10.619 29208-29208/? A/DEBUG: ABI: 'arm'
12-04 15:33:10.619 29208-29208/? A/DEBUG: pid: 28617, tid: 29183, name: SoundPoolThread  >>> com.company.appname <<<
12-04 15:33:10.619 29208-29208/? A/DEBUG: signal 6 (SIGABRT), code -6 (SI_TKILL), fault addr --------
12-04 15:33:10.625 29208-29208/? A/DEBUG: Abort message: 'buffer(0xaf561118) localRefcount 1 != 0, remoteRefcount 0'
12-04 15:33:10.625 29208-29208/? A/DEBUG:     r0 00000000  r1 000071ff  r2 00000006  r3 00000008
12-04 15:33:10.626 29208-29208/? A/DEBUG:     r4 b0800978  r5 00000006  r6 b0800920  r7 0000010c
12-04 15:33:10.626 29208-29208/? A/DEBUG:     r8 af52b4c0  r9 e9459ee6  sl e9459fb0  fp ae9ffd70
12-04 15:33:10.626 29208-29208/? A/DEBUG:     ip 00000000  sp b08002f0  lr e76da097  pc e76dc8f4  cpsr 20070010
12-04 15:33:10.636 29208-29208/? A/DEBUG: backtrace:
12-04 15:33:10.636 29208-29208/? A/DEBUG:     #00 pc 0004a8f4  /system/lib/libc.so (tgkill+12)
12-04 15:33:10.636 29208-29208/? A/DEBUG:     #01 pc 00048093  /system/lib/libc.so (pthread_kill+34)
12-04 15:33:10.636 29208-29208/? A/DEBUG:     #02 pc 0001db6d  /system/lib/libc.so (raise+10)
12-04 15:33:10.637 29208-29208/? A/DEBUG:     #03 pc 00019271  /system/lib/libc.so (__libc_android_abort+34)
12-04 15:33:10.637 29208-29208/? A/DEBUG:     #04 pc 0001718c  /system/lib/libc.so (abort+4)
12-04 15:33:10.637 29208-29208/? A/DEBUG:     #05 pc 0000c971  /system/lib/libcutils.so (__android_log_assert+112)
12-04 15:33:10.637 29208-29208/? A/DEBUG:     #06 pc 00018355  /system/lib/libstagefright_foundation.so (_ZN7android16MediaBufferGroupD1Ev+168)
12-04 15:33:10.637 29208-29208/? A/DEBUG:     #07 pc 00018399  /system/lib/libstagefright_foundation.so (_ZN7android16MediaBufferGroupD0Ev+2)
12-04 15:33:10.637 29208-29208/? A/DEBUG:     #08 pc 001220b1  /system/lib/libstagefright.so (_ZN7android9WAVSource4stopEv+20)
12-04 15:33:10.637 29208-29208/? A/DEBUG:     #09 pc 00121ceb  /system/lib/libstagefright.so (_ZN7android9WAVSourceD2Ev+34)
12-04 15:33:10.637 29208-29208/? A/DEBUG:     #10 pc 00121dd7  /system/lib/libstagefright.so (_ZTv0_n12_N7android9WAVSourceD0Ev+18)
12-04 15:33:10.637 29208-29208/? A/DEBUG:     #11 pc 0000bd87  /system/lib/libutils.so (_ZNK7android7RefBase9decStrongEPKv+58)
12-04 15:33:10.637 29208-29208/? A/DEBUG:     #12 pc 0000520b  /system/lib/libsoundextractor.so (_ZN7android20SoundExtractorParserD1Ev+46)
12-04 15:33:10.637 29208-29208/? A/DEBUG:     #13 pc 00005343  /system/lib/libsoundextractor.so (_ZN7android23SoundExtractorMp3ParserD0Ev+2)
12-04 15:33:10.637 29208-29208/? A/DEBUG:     #14 pc 0000bd87  /system/lib/libutils.so (_ZNK7android7RefBase9decStrongEPKv+58)
12-04 15:33:10.637 29208-29208/? A/DEBUG:     #15 pc 00005b31  /system/lib/libsoundextractor.so (_ZN7android19SoundExtractorCodecD1Ev+24)
12-04 15:33:10.637 29208-29208/? A/DEBUG:     #16 pc 00005bdb  /system/lib/libsoundextractor.so (_ZN7android22SoundExtractorRawCodecD0Ev+2)
12-04 15:33:10.637 29208-29208/? A/DEBUG:     #17 pc 0000bd87  /system/lib/libutils.so (_ZNK7android7RefBase9decStrongEPKv+58)
12-04 15:33:10.637 29208-29208/? A/DEBUG:     #18 pc 0000513d  /system/lib/libsoundextractor.so (_ZN7android14SoundExtractor7releaseEv+12)
12-04 15:33:10.637 29208-29208/? A/DEBUG:     #19 pc 00005ecf  /system/lib/libsoundpool.so (_ZN7android6Sample6doLoadEv+258)
12-04 15:33:10.638 29208-29208/? A/DEBUG:     #20 pc 000069ad  /system/lib/libsoundpool.so (_ZN7android15SoundPoolThread12doLoadSampleEi+32)
12-04 15:33:10.638 29208-29208/? A/DEBUG:     #21 pc 0000695f  /system/lib/libsoundpool.so (_ZN7android15SoundPoolThread3runEv+18)
12-04 15:33:10.638 29208-29208/? A/DEBUG:     #22 pc 000068e7  /system/lib/libsoundpool.so (_ZN7android15SoundPoolThread11beginThreadEPv+2)
12-04 15:33:10.638 29208-29208/? A/DEBUG:     #23 pc 0006b65d  /system/lib/libandroid_runtime.so (_ZN7android14AndroidRuntime15javaThreadShellEPv+80)
12-04 15:33:10.638 29208-29208/? A/DEBUG:     #24 pc 00047b63  /system/lib/libc.so (_ZL15__pthread_startPv+22)
12-04 15:33:10.638 29208-29208/? A/DEBUG:     #25 pc 00019ee1  /system/lib/libc.so (__start_thread+6)
</code>```

Body:
I'm using the SoundPool object to load 2 wav files like so:

 public RingtoneManager(Context context) {

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        soundPool = createSoundPool();
    } else {
        soundPool = createLegacySoundPool();
    }

    RING_OUT = soundPool.load(context, R.raw.groovy, 1);
    sounds.put(RING_OUT, -1);

    RING_IN = soundPool.load(context, R.raw.ring_ring_wav, 1); // crashes on this line
    sounds.put(RING_IN, -1);

}

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
protected SoundPool createSoundPool() {

    Logger.log(TAG, "createSoundPool load attributes");
    AudioAttributes attributes = new AudioAttributes.Builder()
            .setUsage(AudioAttributes.USAGE_VOICE_COMMUNICATION_SIGNALLING)
            .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
            .build();

    Logger.log(TAG, "build soundpool");
    return new SoundPool.Builder()
            .setAudioAttributes(attributes)
            .build();
}

@SuppressWarnings("deprecation")
protected SoundPool createLegacySoundPool() {
    Logger.log(TAG, "createLegacySoundPool");
    return new SoundPool(5, AudioManager.STREAM_MUSIC, 0);
}

I've had no problem on any device with this code until recently I tested on a new Samsung Galaxy Note 8. It crashes consistently when attempting to load the ring_ring_wav.wav file with the following stack trace:

    09-27 20:30:20.033 23644-23644/? A/DEBUG: *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
09-27 20:30:20.033 23644-23644/? A/DEBUG: Build fingerprint: 'samsung/greatltexx/greatlte:7.1.1/NMF26X/N950FXXU1AQI1:user/release-keys'
09-27 20:30:20.033 23644-23644/? A/DEBUG: Revision: '9'
09-27 20:30:20.033 23644-23644/? A/DEBUG: ABI: 'arm'
09-27 20:30:20.034 23644-23644/? A/DEBUG: pid: 23526, tid: 23629, name: SoundPoolThread  >>> com.wizix.gridme <<<
09-27 20:30:20.034 23644-23644/? A/DEBUG: signal 6 (SIGABRT), code -6 (SI_TKILL), fault addr --------
09-27 20:30:20.041 23644-23644/? A/DEBUG: Abort message: 'buffer(0xddf28068) localRefcount 1 != 0, remoteRefcount 0'
09-27 20:30:20.041 23644-23644/? A/DEBUG:     r0 00000000  r1 00005c4d  r2 00000006  r3 00000008
09-27 20:30:20.041 23644-23644/? A/DEBUG:     r4 c59b9978  r5 00000006  r6 c59b9920  r7 0000010c
09-27 20:30:20.041 23644-23644/? A/DEBUG:     r8 c6018120  r9 e7ae5ee6  sl e7ae5fb0  fp c9e716b0
09-27 20:30:20.041 23644-23644/? A/DEBUG:     ip 00000000  sp c59b92f0  lr e9ff1097  pc e9ff38f4  cpsr 200e0010
09-27 20:30:20.052 23644-23644/? A/DEBUG: backtrace:
09-27 20:30:20.053 23644-23644/? A/DEBUG:     #00 pc 0004a8f4  /system/lib/libc.so (tgkill+12)
09-27 20:30:20.053 23644-23644/? A/DEBUG:     #01 pc 00048093  /system/lib/libc.so (pthread_kill+34)
09-27 20:30:20.053 23644-23644/? A/DEBUG:     #02 pc 0001db6d  /system/lib/libc.so (raise+10)
09-27 20:30:20.053 23644-23644/? A/DEBUG:     #03 pc 00019271  /system/lib/libc.so (__libc_android_abort+34)
09-27 20:30:20.053 23644-23644/? A/DEBUG:     #04 pc 0001718c  /system/lib/libc.so (abort+4)
09-27 20:30:20.053 23644-23644/? A/DEBUG:     #05 pc 0000c971  /system/lib/libcutils.so (__android_log_assert+112)
09-27 20:30:20.053 23644-23644/? A/DEBUG:     #06 pc 00018355  /system/lib/libstagefright_foundation.so (_ZN7android16MediaBufferGroupD1Ev+168)
09-27 20:30:20.053 23644-23644/? A/DEBUG:     #07 pc 00018399  /system/lib/libstagefright_foundation.so (_ZN7android16MediaBufferGroupD0Ev+2)
09-27 20:30:20.053 23644-23644/? A/DEBUG:     #08 pc 00121eb1  /system/lib/libstagefright.so (_ZN7android9WAVSource4stopEv+20)
09-27 20:30:20.053 23644-23644/? A/DEBUG:     #09 pc 00121aeb  /system/lib/libstagefright.so (_ZN7android9WAVSourceD2Ev+34)
09-27 20:30:20.053 23644-23644/? A/DEBUG:     #10 pc 00121bd7  /system/lib/libstagefright.so (_ZTv0_n12_N7android9WAVSourceD0Ev+18)
09-27 20:30:20.053 23644-23644/? A/DEBUG:     #11 pc 0000bd87  /system/lib/libutils.so (_ZNK7android7RefBase9decStrongEPKv+58)
09-27 20:30:20.053 23644-23644/? A/DEBUG:     #12 pc 0000520b  /system/lib/libsoundextractor.so (_ZN7android20SoundExtractorParserD1Ev+46)
09-27 20:30:20.053 23644-23644/? A/DEBUG:     #13 pc 00005343  /system/lib/libsoundextractor.so (_ZN7android23SoundExtractorMp3ParserD0Ev+2)
09-27 20:30:20.053 23644-23644/? A/DEBUG:     #14 pc 0000bd87  /system/lib/libutils.so (_ZNK7android7RefBase9decStrongEPKv+58)
09-27 20:30:20.053 23644-23644/? A/DEBUG:     #15 pc 00005b31  /system/lib/libsoundextractor.so (_ZN7android19SoundExtractorCodecD1Ev+24)
09-27 20:30:20.053 23644-23644/? A/DEBUG:     #16 pc 00005bdb  /system/lib/libsoundextractor.so (_ZN7android22SoundExtractorRawCodecD0Ev+2)
09-27 20:30:20.053 23644-23644/? A/DEBUG:     #17 pc 0000bd87  /system/lib/libutils.so (_ZNK7android7RefBase9decStrongEPKv+58)
09-27 20:30:20.053 23644-23644/? A/DEBUG:     #18 pc 0000513d  /system/lib/libsoundextractor.so (_ZN7android14SoundExtractor7releaseEv+12)
09-27 20:30:20.053 23644-23644/? A/DEBUG:     #19 pc 00005ecf  /system/lib/libsoundpool.so (_ZN7android6Sample6doLoadEv+258)
09-27 20:30:20.053 23644-23644/? A/DEBUG:     #20 pc 000069ad  /system/lib/libsoundpool.so (_ZN7android15SoundPoolThread12doLoadSampleEi+32)
09-27 20:30:20.053 23644-23644/? A/DEBUG:     #21 pc 0000695f  /system/lib/libsoundpool.so (_ZN7android15SoundPoolThread3runEv+18)
09-27 20:30:20.053 23644-23644/? A/DEBUG:     #22 pc 000068e7  /system/lib/libsoundpool.so (_ZN7android15SoundPoolThread11beginThreadEPv+2)
09-27 20:30:20.053 23644-23644/? A/DEBUG:     #23 pc 0006b65d  /system/lib/libandroid_runtime.so (_ZN7android14AndroidRuntime15javaThreadShellEPv+80)
09-27 20:30:20.053 23644-23644/? A/DEBUG:     #24 pc 00047b63  /system/lib/libc.so (_ZL15__pthread_startPv+22)
09-27 20:30:20.053 23644-23644/? A/DEBUG:     #25 pc 00019ee1  /system/lib/libc.so (__start_thread+6)

If I download the file directly to the device it plays fine through Chrome. The other wav file loads and plays fine in the soundpool.

Body:
Me too. It's happen only on Samsung Galaxy Note 8.
Edit: sound is wav type.

My code is very simple

SoundPool soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
soundPool.load(activity, R.raw.music01, 1);

Crash log:

12-04 15:33:10.226 28617-29183/com.company.appname D/MediaBufferGroup: creating MemoryDealer
12-04 15:33:10.232 28617-29183/com.company.appname A/MediaBufferGroup: buffer(0xaf561118) localRefcount 1 != 0, remoteRefcount 0
12-04 15:33:10.308 3823-4594/? E/Watchdog: !@Sync 237 [2017-12-04 15:33:10.308]

                                           --------- beginning of crash
12-04 15:33:10.395 29207-29183/? A/google-breakpad: Microdump skipped (uninteresting)
12-04 15:33:10.417 28617-29183/com.company.appname W/google-breakpad: ### ### ### ### ### ### ### ### ### ### ### ### ###
12-04 15:33:10.417 28617-29183/com.company.appname W/google-breakpad: Chrome build fingerprint:
12-04 15:33:10.417 28617-29183/com.company.appname W/google-breakpad: 1.0.0
12-04 15:33:10.417 28617-29183/com.company.appname W/google-breakpad: 1
12-04 15:33:10.417 28617-29183/com.company.appname W/google-breakpad: ### ### ### ### ### ### ### ### ### ### ### ### ###
12-04 15:33:10.419 28617-29183/com.company.appname A/libc: Fatal signal 6 (SIGABRT), code -6 in tid 29183 (SoundPoolThread)

                                                        [ 12-04 15:33:10.422  3230: 3230 W/         ]
                                                        debuggerd: handling request: pid=28617 uid=10215 gid=10215 tid=29183
12-04 15:33:10.492 3426-3426/? E/audit: type=1400 audit(1512369190.486:741): avc:  denied  { search } for  pid=29208 comm="debuggerd" name="com.company.appname" dev="dm-1" ino=1310724 scontext=u:r:debuggerd:s0 tcontext=u:object_r:app_data_file:s0:c512,c768 tclass=dir permissive=0 SEPF_SECMOBILE_7.1.1_0001 audit_filtered
12-04 15:33:10.493 3426-3426/? E/audit: type=1300 audit(1512369190.486:741): arch=40000028 syscall=322 per=8 success=no exit=-13 a0=ffffff9c a1=f4c97880 a2=20000 a3=0 items=0 ppid=3230 pid=29208 auid=4294967295 uid=0 gid=0 euid=0 suid=0 fsuid=0 egid=0 sgid=0 fsgid=0 tty=(none) ses=4294967295 comm="debuggerd" exe="/system/bin/debuggerd" subj=u:r:debuggerd:s0 key=(null)
12-04 15:33:10.493 3426-3426/? E/audit: type=1327 audit(1512369190.486:741): proctitle="/system/bin/debuggerd"
12-04 15:33:10.618 29208-29208/? A/DEBUG: *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
12-04 15:33:10.619 29208-29208/? A/DEBUG: Build fingerprint: 'samsung/greatlteks/greatlteks:7.1.1/NMF26X/N950NKSU1AQI2:user/release-keys'
12-04 15:33:10.619 29208-29208/? A/DEBUG: Revision: '9'
12-04 15:33:10.619 29208-29208/? A/DEBUG: ABI: 'arm'
12-04 15:33:10.619 29208-29208/? A/DEBUG: pid: 28617, tid: 29183, name: SoundPoolThread  >>> com.company.appname <<<
12-04 15:33:10.619 29208-29208/? A/DEBUG: signal 6 (SIGABRT), code -6 (SI_TKILL), fault addr --------
12-04 15:33:10.625 29208-29208/? A/DEBUG: Abort message: 'buffer(0xaf561118) localRefcount 1 != 0, remoteRefcount 0'
12-04 15:33:10.625 29208-29208/? A/DEBUG:     r0 00000000  r1 000071ff  r2 00000006  r3 00000008
12-04 15:33:10.626 29208-29208/? A/DEBUG:     r4 b0800978  r5 00000006  r6 b0800920  r7 0000010c
12-04 15:33:10.626 29208-29208/? A/DEBUG:     r8 af52b4c0  r9 e9459ee6  sl e9459fb0  fp ae9ffd70
12-04 15:33:10.626 29208-29208/? A/DEBUG:     ip 00000000  sp b08002f0  lr e76da097  pc e76dc8f4  cpsr 20070010
12-04 15:33:10.636 29208-29208/? A/DEBUG: backtrace:
12-04 15:33:10.636 29208-29208/? A/DEBUG:     #00 pc 0004a8f4  /system/lib/libc.so (tgkill+12)
12-04 15:33:10.636 29208-29208/? A/DEBUG:     #01 pc 00048093  /system/lib/libc.so (pthread_kill+34)
12-04 15:33:10.636 29208-29208/? A/DEBUG:     #02 pc 0001db6d  /system/lib/libc.so (raise+10)
12-04 15:33:10.637 29208-29208/? A/DEBUG:     #03 pc 00019271  /system/lib/libc.so (__libc_android_abort+34)
12-04 15:33:10.637 29208-29208/? A/DEBUG:     #04 pc 0001718c  /system/lib/libc.so (abort+4)
12-04 15:33:10.637 29208-29208/? A/DEBUG:     #05 pc 0000c971  /system/lib/libcutils.so (__android_log_assert+112)
12-04 15:33:10.637 29208-29208/? A/DEBUG:     #06 pc 00018355  /system/lib/libstagefright_foundation.so (_ZN7android16MediaBufferGroupD1Ev+168)
12-04 15:33:10.637 29208-29208/? A/DEBUG:     #07 pc 00018399  /system/lib/libstagefright_foundation.so (_ZN7android16MediaBufferGroupD0Ev+2)
12-04 15:33:10.637 29208-29208/? A/DEBUG:     #08 pc 001220b1  /system/lib/libstagefright.so (_ZN7android9WAVSource4stopEv+20)
12-04 15:33:10.637 29208-29208/? A/DEBUG:     #09 pc 00121ceb  /system/lib/libstagefright.so (_ZN7android9WAVSourceD2Ev+34)
12-04 15:33:10.637 29208-29208/? A/DEBUG:     #10 pc 00121dd7  /system/lib/libstagefright.so (_ZTv0_n12_N7android9WAVSourceD0Ev+18)
12-04 15:33:10.637 29208-29208/? A/DEBUG:     #11 pc 0000bd87  /system/lib/libutils.so (_ZNK7android7RefBase9decStrongEPKv+58)
12-04 15:33:10.637 29208-29208/? A/DEBUG:     #12 pc 0000520b  /system/lib/libsoundextractor.so (_ZN7android20SoundExtractorParserD1Ev+46)
12-04 15:33:10.637 29208-29208/? A/DEBUG:     #13 pc 00005343  /system/lib/libsoundextractor.so (_ZN7android23SoundExtractorMp3ParserD0Ev+2)
12-04 15:33:10.637 29208-29208/? A/DEBUG:     #14 pc 0000bd87  /system/lib/libutils.so (_ZNK7android7RefBase9decStrongEPKv+58)
12-04 15:33:10.637 29208-29208/? A/DEBUG:     #15 pc 00005b31  /system/lib/libsoundextractor.so (_ZN7android19SoundExtractorCodecD1Ev+24)
12-04 15:33:10.637 29208-29208/? A/DEBUG:     #16 pc 00005bdb  /system/lib/libsoundextractor.so (_ZN7android22SoundExtractorRawCodecD0Ev+2)
12-04 15:33:10.637 29208-29208/? A/DEBUG:     #17 pc 0000bd87  /system/lib/libutils.so (_ZNK7android7RefBase9decStrongEPKv+58)
12-04 15:33:10.637 29208-29208/? A/DEBUG:     #18 pc 0000513d  /system/lib/libsoundextractor.so (_ZN7android14SoundExtractor7releaseEv+12)
12-04 15:33:10.637 29208-29208/? A/DEBUG:     #19 pc 00005ecf  /system/lib/libsoundpool.so (_ZN7android6Sample6doLoadEv+258)
12-04 15:33:10.638 29208-29208/? A/DEBUG:     #20 pc 000069ad  /system/lib/libsoundpool.so (_ZN7android15SoundPoolThread12doLoadSampleEi+32)
12-04 15:33:10.638 29208-29208/? A/DEBUG:     #21 pc 0000695f  /system/lib/libsoundpool.so (_ZN7android15SoundPoolThread3runEv+18)
12-04 15:33:10.638 29208-29208/? A/DEBUG:     #22 pc 000068e7  /system/lib/libsoundpool.so (_ZN7android15SoundPoolThread11beginThreadEPv+2)
12-04 15:33:10.638 29208-29208/? A/DEBUG:     #23 pc 0006b65d  /system/lib/libandroid_runtime.so (_ZN7android14AndroidRuntime15javaThreadShellEPv+80)
12-04 15:33:10.638 29208-29208/? A/DEBUG:     #24 pc 00047b63  /system/lib/libc.so (_ZL15__pthread_startPv+22)
12-04 15:33:10.638 29208-29208/? A/DEBUG:     #25 pc 00019ee1  /system/lib/libc.so (__start_thread+6)


问:
Unable to add dependency module in gradle intellij
I'm using gradle (IDE: Intellij) to run my automated scripts. I've few modules Module A, Module B, Module C so on. I'm trying add module B as a dependent module to module C. I tried

a. specifying it in module C build.gradle file

b. tried a cyclic reference as in both the modules's build.gradle file (module B and module C)

c. tried under Project Structure --> module dependency

d. in the global build.gradle which is a common file for module A,B,C

e. Tried File | Invalidate Caches

```<code> dependencies {
        testCompile ":modulename" --> I tried with single quote and double quotes
    }
</code>```

I'm trying to access a class from module B in module C class but it's saying class not found. Both the class have public access.

What else can I try?

答:
Got it working. Thanks to this post.

The solution that worked for me is in the module specific gradle file, enter it as

```<code>dependencies{
    testCompile project(':moduleA').sourceSets.test.output

}
</code>```

Body:
I'm using gradle (IDE: Intellij) to run my automated scripts. I've few modules Module A, Module B, Module C so on. I'm trying add module B as a dependent module to module C. I tried

a. specifying it in module C build.gradle file

b. tried a cyclic reference as in both the modules's build.gradle file (module B and module C)

c. tried under Project Structure --> module dependency

d. in the global build.gradle which is a common file for module A,B,C

e. Tried File | Invalidate Caches

 dependencies {
        testCompile ":modulename" --> I tried with single quote and double quotes
    }

I'm trying to access a class from module B in module C class but it's saying class not found. Both the class have public access.

What else can I try?

Body:
Got it working. Thanks to this post.

The solution that worked for me is in the module specific gradle file, enter it as

dependencies{
    testCompile project(':moduleA').sourceSets.test.output

}


问:
How to switch frames using Protractor
I know this has been asked multiple times, and the suggested solution has been to use something like browser.driver.switchTo('your-frame-name') but I can't seem to access the same switchTo() method in my code.

This is my test :

```<code>import { AppPage } from './app.po';
import {browser, by, element} from 'protractor';

describe('angular-test App', () => {
  let page: AppPage;

  beforeEach(() => {
    page = new AppPage();
  });

  it('should display welcome message', () => {
    page.navigateTo();
    browser.driver.switchToParentFrame()

    //expect(page.getParagraphText()).toEqual('Welcome to app!');
    expect(element(by.id('myHeader')).getText()).toEqual('Welcome to Angular Test App!  ');
  });
});
</code>```

switchToParentFrame() is the only available method I get after the browser.driver.

This is how my HTML looks like

Any help is appreaciated, sorry for the vague description of the question but I'm pretty new to coding/protractor e2e testing.

答:
```<code>var elem = element(by.xpath('iframe element')); // .//div[contains(@id,\'cke\')]/iframe
browser.sleep(3000);
elem.click();
browser.switchTo().frame(elem.getWebElement());
browser.sleep(3000);
element(by.tagName('body')).sendKeys('test');
browser.switchTo().defaultContent();
browser.sleep(3000);
</code>```

Title: How to switch frames using Protractor

Body:
I know this has been asked multiple times, and the suggested solution has been to use something like browser.driver.switchTo('your-frame-name') but I can't seem to access the same switchTo() method in my code.

This is my test :

import { AppPage } from './app.po';
import {browser, by, element} from 'protractor';

describe('angular-test App', () => {
  let page: AppPage;

  beforeEach(() => {
    page = new AppPage();
  });

  it('should display welcome message', () => {
    page.navigateTo();
    browser.driver.switchToParentFrame()

    //expect(page.getParagraphText()).toEqual('Welcome to app!');
    expect(element(by.id('myHeader')).getText()).toEqual('Welcome to Angular Test App!  ');
  });
});

switchToParentFrame() is the only available method I get after the browser.driver.

This is how my HTML looks like

Any help is appreaciated, sorry for the vague description of the question but I'm pretty new to coding/protractor e2e testing.


问:
pull-right / float-right not working in Bootstrap 4
How can I make bootstrap-tabdrop.js compatible with Bootstrap 4?

Demo

I changed pull-right to float-right but did not work :(

please help me.

答:
See this answer float right / left not works in flex item you need to change the order of item and put the margin-left:auto

```<code>li.tabdrop{
    order:2;
    margin-left:auto;
}
</code>```

https://jsfiddle.net/ag4sa7fr/2/

Body:
See this answer float right / left not works in flex item you need to change the order of item and put the margin-left:auto

li.tabdrop{
    order:2;
    margin-left:auto;
}

https://jsfiddle.net/ag4sa7fr/2/


问:
How to show maps first and then download image markers?
I'm trying to show custom marker with images here images are download from internet.

Everything is fine getting result as expected.

Here is the output image

But it is taking lot of time to show maps here it is downloading images and then showing maps. Is there any way to show maps first and then download images and set markers.

Here is the code i tried

```<code> @Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    MapsInitializer.initialize(this);

    LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    assert locationManager != null;
    String provider = locationManager.getBestProvider(criteria, true);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (ActivityCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.ACCESS_COARSE_LOCATION
            }, LOCATION_REQUEST_CODE);
            return;
        }
    }
    mLastLocation = locationManager.getLastKnownLocation(provider);

    userLatLng = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());

    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userLatLng, 14.0f));
    mMap.setMyLocationEnabled(true);
    mMap.getUiSettings().setZoomControlsEnabled(true);
    mMap.setBuildingsEnabled(true);
    try {
        bussinessBitmap = new AddMarkers(imgUrl2).execute().get();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }
    if (bussinessLatLng != null) {
        bussinessMarker = mMap.addMarker(new MarkerOptions()
                .position(bussinessLatLng)
                .title(businessUser)
                .snippet(getLocation(bussinessLatLng))
                .icon(BitmapDescriptorFactory.fromBitmap(getMarkerBitmapFromView(bussinessBitmap))));
    } else {
        bussinessMarker = mMap.addMarker(new MarkerOptions()
                .position(bussinessLatLng)
                .title(businessUser)
                .snippet(getLocation(bussinessLatLng)));
    }

    try {
        userBitmap = new AddMarkers(imgUrl).execute().get();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }
    if (mLastLocation != null) {
        if (userBitmap != null) {
            userMarker = mMap.addMarker(new MarkerOptions().position(userLatLng)
                    .title(username)
                    .snippet(getLocation(userLatLng))
                    .icon(BitmapDescriptorFactory.fromBitmap(getMarkerBitmapFromView(userBitmap))));
        } else {
            userMarker = mMap.addMarker(new MarkerOptions().position(userLatLng)
                    .title(username)
                    .snippet(getLocation(userLatLng)));
        }
    }

    if(!(userLatLng == null || bussinessLatLng == null)) {

        Polyline distanceLine = mMap.addPolyline(new PolylineOptions().add(userLatLng, bussinessLatLng).width(4).color(Color.GREEN));
    }
}
</code>```

I'm using asynctask to download the images here is the code for that

```<code>public AddMarkers(String imgUrl) {
        this.imgUrl = imgUrl;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pd = new ProgressDialog(MapsActivity.this);
        pd.setTitle("Loading");
        pd.setMessage("Please wait..");
        pd.show();
    }

    @Override
    protected Bitmap doInBackground(Void... voids) {

        URL url;
        try {
            url = new URL(imgUrl);
            return BitmapFactory.decodeStream(url.openConnection().getInputStream());

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Bitmap bitmap) {
        super.onPostExecute(bitmap);
        if (pd != null && pd.isShowing()) pd.dismiss();
    }
}
</code>```

答:
The GoogleMap object has a method to set a callback for when the map is loaded. Add the following in your onMapReady method:

```<code>mMap.setOnMapLoadedCallback(this);
</code>```

and have a method in your class that then implements the callback:

```<code>@Override
public void OnMapLoaded() {
    AddMarkers addMarkersTask = new AddMarkers(url);
    addMarkersTask.execute();
}
</code>```

Body:
I'm trying to show custom marker with images here images are download from internet.

Everything is fine getting result as expected.

Here is the output image

But it is taking lot of time to show maps here it is downloading images and then showing maps. Is there any way to show maps first and then download images and set markers.

Here is the code i tried

 @Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    MapsInitializer.initialize(this);

    LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    assert locationManager != null;
    String provider = locationManager.getBestProvider(criteria, true);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (ActivityCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.ACCESS_COARSE_LOCATION
            }, LOCATION_REQUEST_CODE);
            return;
        }
    }
    mLastLocation = locationManager.getLastKnownLocation(provider);

    userLatLng = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());

    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userLatLng, 14.0f));
    mMap.setMyLocationEnabled(true);
    mMap.getUiSettings().setZoomControlsEnabled(true);
    mMap.setBuildingsEnabled(true);
    try {
        bussinessBitmap = new AddMarkers(imgUrl2).execute().get();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }
    if (bussinessLatLng != null) {
        bussinessMarker = mMap.addMarker(new MarkerOptions()
                .position(bussinessLatLng)
                .title(businessUser)
                .snippet(getLocation(bussinessLatLng))
                .icon(BitmapDescriptorFactory.fromBitmap(getMarkerBitmapFromView(bussinessBitmap))));
    } else {
        bussinessMarker = mMap.addMarker(new MarkerOptions()
                .position(bussinessLatLng)
                .title(businessUser)
                .snippet(getLocation(bussinessLatLng)));
    }

    try {
        userBitmap = new AddMarkers(imgUrl).execute().get();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }
    if (mLastLocation != null) {
        if (userBitmap != null) {
            userMarker = mMap.addMarker(new MarkerOptions().position(userLatLng)
                    .title(username)
                    .snippet(getLocation(userLatLng))
                    .icon(BitmapDescriptorFactory.fromBitmap(getMarkerBitmapFromView(userBitmap))));
        } else {
            userMarker = mMap.addMarker(new MarkerOptions().position(userLatLng)
                    .title(username)
                    .snippet(getLocation(userLatLng)));
        }
    }

    if(!(userLatLng == null || bussinessLatLng == null)) {

        Polyline distanceLine = mMap.addPolyline(new PolylineOptions().add(userLatLng, bussinessLatLng).width(4).color(Color.GREEN));
    }
}

I'm using asynctask to download the images here is the code for that

public AddMarkers(String imgUrl) {
        this.imgUrl = imgUrl;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pd = new ProgressDialog(MapsActivity.this);
        pd.setTitle("Loading");
        pd.setMessage("Please wait..");
        pd.show();
    }

    @Override
    protected Bitmap doInBackground(Void... voids) {

        URL url;
        try {
            url = new URL(imgUrl);
            return BitmapFactory.decodeStream(url.openConnection().getInputStream());

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Bitmap bitmap) {
        super.onPostExecute(bitmap);
        if (pd != null && pd.isShowing()) pd.dismiss();
    }
}

Body:
The GoogleMap object has a method to set a callback for when the map is loaded. Add the following in your onMapReady method:

mMap.setOnMapLoadedCallback(this);

and have a method in your class that then implements the callback:

@Override
public void OnMapLoaded() {
    AddMarkers addMarkersTask = new AddMarkers(url);
    addMarkersTask.execute();
}


问:
Dyntable sort does not work at all from Ajax
I am using dyna table with Ajax. Sorting, searching, pagination nothing is working. I only get a list in my table but on clicking the column header nothing happens.

Please help.This is my code.

My html file is

```<code><table style="width:100%" id="my-final-table" class="tablesorter" >
    <thead>
        <tr bgcolor="#239B56">
          <th><font style="color:#fff">Rollno</font></th>
          <th><font style="color:#fff">Name</font></th>
          <th><font style="color:#fff">Marks</font></th>
          <th><font style="color:#fff">Percentage</font></th>
      </tr>
  </thead>
  <tbody>

  </tbody>
</table>
</code>```

My Ajax code is

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="/jquery.dynatable.js"></script>
<style src="/jquery.dynatable.css"></style>

<script type="text/javascript">
    $(document).ready(function()
    {
        $('#my-final-table').dynatable({

          dataset: {
            ajax: true,
            ajaxOnLoad: true,
            ajaxUrl: '/result_analysis_subject_json.json',
            records: []
        }
    });

    });

</script>
</code>```

And my JSON file is

```<code>{"records":[{"rollno":"1","name":"Aditya Kumar Sharma","marks":"12.00","percentage":40},{"rollno":"2","name":"Aksh Kathuria","marks":"19.00","percentage":63},{"rollno":"3","name":"Anant ","marks":"14.00","percentage":47},{"rollno":"4","name":"Arnav Arora","marks":"28.00","percentage":93},{"rollno":"5","name":"Ayush Sai Raina","marks":"26.00","percentage":87},{"rollno":"6","name":"Ayush Rawat","marks":"21.00","percentage":70},{"rollno":"7","name":"Bhagya Dua","marks":"11.00","percentage":37},{"rollno":"8","name":"Bhvesh Gautam","marks":"26.00","percentage":87},{"rollno":"9","name":"Chaitanya Dubey","marks":"18.00","percentage":60},{"rollno":"10","name":"Chanchal","marks":"5.00","percentage":17},{"rollno":"11","name":"Deeksha","marks":"28.00","percentage":93},{"rollno":"12","name":"Dimple Bhatia","marks":"26.00","percentage":87},{"rollno":"13","name":"Ekta Yadav","marks":"27.00","percentage":90},{"rollno":"14","name":"Eshan Sharma","marks":"24.00","percentage":80},{"rollno":"15","name":"Harman Arora","marks":"13.00","percentage":43},{"rollno":"16","name":"Himanya ","marks":"18.00","percentage":60},{"rollno":"17","name":"Hiya Bhatia","marks":"29.00","percentage":97},{"rollno":"18","name":"Ishmeet Kaur","marks":"13.00","percentage":43},{"rollno":"19","name":"Jivitesh Gwadi","marks":"20.00","percentage":67},{"rollno":"20","name":"Jiya Hussain","marks":"7.00","percentage":23},{"rollno":"21","name":"Krish Kohli","marks":"13.00","percentage":43},{"rollno":"22","name":"Krishna Sharma","marks":"22.00","percentage":73},{"rollno":"23","name":"Lisha Kapoor","marks":"27.00","percentage":90},{"rollno":"24","name":"Mannant Sehgal","marks":"20.00","percentage":67},{"rollno":"25","name":"Mayank Mehta","marks":"19.00","percentage":63},{"rollno":"26","name":"Mehak Singh","marks":"26.00","percentage":87},{"rollno":"27","name":"Nandini Bhargava","marks":"29.00","percentage":97},{"rollno":"28","name":"Parth Talwar","marks":"27.00","percentage":90},{"rollno":"29","name":"Pawni Yadav","marks":"27.00","percentage":90},{"rollno":"30","name":"Prachi Dahiya","marks":"21.00","percentage":70},{"rollno":"31","name":"Prachi Sharma","marks":"18.00","percentage":60},{"rollno":"32","name":"Rashi Bainsla","marks":"19.00","percentage":63},{"rollno":"33","name":"Ravinder Singh","marks":"5.00","percentage":17},{"rollno":"34","name":"Riya Sethi","marks":"14.00","percentage":47},{"rollno":"35","name":"Sahib Kharbanda","marks":"24.00","percentage":80},{"rollno":"36","name":"Sajal Kukreja","marks":"23.00","percentage":77},{"rollno":"37","name":"Shrishty Singh","marks":"26.00","percentage":87},{"rollno":"38","name":"Tanisha Kaur","marks":"26.00","percentage":87},{"rollno":"39","name":"Toshiv Mudgal","marks":"16.00","percentage":53},{"rollno":"40","name":"Yash Anand","marks":"23.00","percentage":77}],"queryRecordCount":40,"totalRecordCount":40}
</code>```

答:
From what i can read from the documentation , the sorting, searching, and paginating needs to be done on the server side

NOTE: When using AJAX to load data, operations such as sorting, searching, and paginating are performed on the server before building the returned JSON. This example has these features disabled since, we're just loading a static JSON file for the purposes of documentation.

When using Dynatable in "AJAX mode" (dataset.ajax = true), delegates all operations (pagination, sorting, and querying/filtering) to the server. For each operation, dynatalbe culls the parameters (sort, search, page) into an AJAX request and fetches the results from dataset.ajaxUrl (if this setting isn't set, it will send an AJAX request to the URL of the current page).

more info

Body:
I am using dyna table with Ajax. Sorting, searching, pagination nothing is working. I only get a list in my table but on clicking the column header nothing happens.

Please help.This is my code.

My html file is

          Rollno
          Name
          Marks
          Percentage

My Ajax code is

And my JSON file is

{"records":[{"rollno":"1","name":"Aditya Kumar Sharma","marks":"12.00","percentage":40},{"rollno":"2","name":"Aksh Kathuria","marks":"19.00","percentage":63},{"rollno":"3","name":"Anant ","marks":"14.00","percentage":47},{"rollno":"4","name":"Arnav Arora","marks":"28.00","percentage":93},{"rollno":"5","name":"Ayush Sai Raina","marks":"26.00","percentage":87},{"rollno":"6","name":"Ayush Rawat","marks":"21.00","percentage":70},{"rollno":"7","name":"Bhagya Dua","marks":"11.00","percentage":37},{"rollno":"8","name":"Bhvesh Gautam","marks":"26.00","percentage":87},{"rollno":"9","name":"Chaitanya Dubey","marks":"18.00","percentage":60},{"rollno":"10","name":"Chanchal","marks":"5.00","percentage":17},{"rollno":"11","name":"Deeksha","marks":"28.00","percentage":93},{"rollno":"12","name":"Dimple Bhatia","marks":"26.00","percentage":87},{"rollno":"13","name":"Ekta Yadav","marks":"27.00","percentage":90},{"rollno":"14","name":"Eshan Sharma","marks":"24.00","percentage":80},{"rollno":"15","name":"Harman Arora","marks":"13.00","percentage":43},{"rollno":"16","name":"Himanya ","marks":"18.00","percentage":60},{"rollno":"17","name":"Hiya Bhatia","marks":"29.00","percentage":97},{"rollno":"18","name":"Ishmeet Kaur","marks":"13.00","percentage":43},{"rollno":"19","name":"Jivitesh Gwadi","marks":"20.00","percentage":67},{"rollno":"20","name":"Jiya Hussain","marks":"7.00","percentage":23},{"rollno":"21","name":"Krish Kohli","marks":"13.00","percentage":43},{"rollno":"22","name":"Krishna Sharma","marks":"22.00","percentage":73},{"rollno":"23","name":"Lisha Kapoor","marks":"27.00","percentage":90},{"rollno":"24","name":"Mannant Sehgal","marks":"20.00","percentage":67},{"rollno":"25","name":"Mayank Mehta","marks":"19.00","percentage":63},{"rollno":"26","name":"Mehak Singh","marks":"26.00","percentage":87},{"rollno":"27","name":"Nandini Bhargava","marks":"29.00","percentage":97},{"rollno":"28","name":"Parth Talwar","marks":"27.00","percentage":90},{"rollno":"29","name":"Pawni Yadav","marks":"27.00","percentage":90},{"rollno":"30","name":"Prachi Dahiya","marks":"21.00","percentage":70},{"rollno":"31","name":"Prachi Sharma","marks":"18.00","percentage":60},{"rollno":"32","name":"Rashi Bainsla","marks":"19.00","percentage":63},{"rollno":"33","name":"Ravinder Singh","marks":"5.00","percentage":17},{"rollno":"34","name":"Riya Sethi","marks":"14.00","percentage":47},{"rollno":"35","name":"Sahib Kharbanda","marks":"24.00","percentage":80},{"rollno":"36","name":"Sajal Kukreja","marks":"23.00","percentage":77},{"rollno":"37","name":"Shrishty Singh","marks":"26.00","percentage":87},{"rollno":"38","name":"Tanisha Kaur","marks":"26.00","percentage":87},{"rollno":"39","name":"Toshiv Mudgal","marks":"16.00","percentage":53},{"rollno":"40","name":"Yash Anand","marks":"23.00","percentage":77}],"queryRecordCount":40,"totalRecordCount":40}


答:
TRY: You can use this concept, if it will return 1 then TRUE else FALSE

```<code>SELECT 1
FROM tmp t
WHERE Order_no BETWEEN 003 AND 007
    AND Order_status = 1
HAVING COUNT(*) = (007-003)+1
</code>```

Title: POSTGRES : SELECT : Query for number of rows which EXIST BETWEEN given range

Body:
I have to query the table to search for given conditions :

order_no specified in the range must exist.

Example:  I am getting a request for a range of order_no: 003 - 007. So, I want to check whether all the order_no mentioned in range exist or not.If not exist return false.

The order_status of ALL order_no must be 1. If not exist return false.

Order_string    Order_no   Order_status
    ABE              1                1
    ABE              2                1
    ABE              3                0
    PSB              4                0
    PSB              5                1
    PSB              6                0
    REL              7                0
    REL              8                1
    REL              9                1
    REL              10               1

I was trying EXIST and BETWEEN but unable to query the DB.

Body:
TRY: You can use this concept, if it will return 1 then TRUE else FALSE

SELECT 1
FROM tmp t
WHERE Order_no BETWEEN 003 AND 007
    AND Order_status = 1
HAVING COUNT(*) = (007-003)+1


问:
Different consoles for stderr and stdout in Intellij IDEA?
Stderr and stdout messages appear in the same console log in IntelliJ IDEA (typically in black and in red). Is there a simple way to suppress either stderr or stdout messages or redirect the two different streams to different console windows?</p>

答:
How I deal with this situation is to redirect stdout to a file, such as stdout.log, when system begins.

Then Configuring IDEA's Run/Debug Configurations - Logs to add a log file that locate stdout.log

Thus, you can get stdin at console you just created and stderr at old output.


问:
Sort products by DESC order in Woocommerce
I wrote this code in functions.php file of my active theme:

```<code>    add_filter( 'woocommerce_get_catalog_ordering_args',
    'custom_woocommerce_get_catalog_ordering_args' );
    function custom_woocommerce_get_catalog_ordering_args( $args ) {
     $orderby_value = isset( $_GET['orderby'] ) ? woocommerce_clean( $_GET['orderby'] ) : apply_filters( 'woocommerce_default_catalog_orderby', get_option( 'woocommerce_default_catalog_orderby' ) );
    if ( 'random_list' == $orderby_value ) {
        $args['orderby'] = 'date';
        $args['order'] = 'desc';
        $args['meta_key'] = '';
    }
    return $args;
}
add_filter( 'woocommerce_default_catalog_orderby_options', 'custom_woocommerce_catalog_orderby' );
add_filter( 'woocommerce_catalog_orderby', 'custom_woocommerce_catalog_orderby' );
function custom_woocommerce_catalog_orderby( $sortby ) {
    $sortby['random_list'] = 'DESC SORT';
    return $sortby;
}
</code>```

I am trying to sort products by Desc, but products still sorting by default (ASC).

How can I sort them by DESC?

答:
You need to decide first that by which field you want to sort either price title etc. But i have written all the possible ways u can use it,

add_filter( 'woocommerce_get_catalog_ordering_args','custom_query_sort_args' );

function custom_query_sort_args() {

```<code>    // Sort by and order
    $current_order = ( isset( $_SESSION['orderby'] ) ) ? $_SESSION['orderby'] : apply_filters( 'woocommerce_default_catalog_orderby', get_option( 'woocommerce_default_catalog_orderby' ) );

    switch ( $current_order ) {
        case 'date' :
            $orderby = 'date';
            $order = 'desc';
            $meta_key = '';
        break;
        case 'price' :
            $orderby = 'meta_value_num';
            $order = 'asc';
            $meta_key = '_price';
        break;
        case 'title' :
            $orderby = 'meta_value';
            $order = 'asc';
            $meta_key = '_woocommerce_product_short_title';
        break;
        default :
            $orderby = 'menu_order title';
            $order = 'asc';
            $meta_key = '';
        break;
    }

    $args = array();

    $args['orderby']        = $orderby;
    $args['order']          = $order;

    if ($meta_key) :
        $args['meta_key'] = $meta_key;
    endif;

    return $args;
</code>```

}

Body:
I wrote this code in functions.php file of my active theme:

    add_filter( 'woocommerce_get_catalog_ordering_args',
    'custom_woocommerce_get_catalog_ordering_args' );
    function custom_woocommerce_get_catalog_ordering_args( $args ) {
     $orderby_value = isset( $_GET['orderby'] ) ? woocommerce_clean( $_GET['orderby'] ) : apply_filters( 'woocommerce_default_catalog_orderby', get_option( 'woocommerce_default_catalog_orderby' ) );
    if ( 'random_list' == $orderby_value ) {
        $args['orderby'] = 'date';
        $args['order'] = 'desc';
        $args['meta_key'] = '';
    }
    return $args;
}
add_filter( 'woocommerce_default_catalog_orderby_options', 'custom_woocommerce_catalog_orderby' );
add_filter( 'woocommerce_catalog_orderby', 'custom_woocommerce_catalog_orderby' );
function custom_woocommerce_catalog_orderby( $sortby ) {
    $sortby['random_list'] = 'DESC SORT';
    return $sortby;
}

I am trying to sort products by Desc, but products still sorting by default (ASC).

How can I sort them by DESC?

Body:
You need to decide first that by which field you want to sort either price title etc. But i have written all the possible ways u can use it,

add_filter( 'woocommerce_get_catalog_ordering_args','custom_query_sort_args' );

function custom_query_sort_args() {

    // Sort by and order
    $current_order = ( isset( $_SESSION['orderby'] ) ) ? $_SESSION['orderby'] : apply_filters( 'woocommerce_default_catalog_orderby', get_option( 'woocommerce_default_catalog_orderby' ) );

    switch ( $current_order ) {
        case 'date' :
            $orderby = 'date';
            $order = 'desc';
            $meta_key = '';
        break;
        case 'price' :
            $orderby = 'meta_value_num';
            $order = 'asc';
            $meta_key = '_price';
        break;
        case 'title' :
            $orderby = 'meta_value';
            $order = 'asc';
            $meta_key = '_woocommerce_product_short_title';
        break;
        default :
            $orderby = 'menu_order title';
            $order = 'asc';
            $meta_key = '';
        break;
    }

    $args = array();

    $args['orderby']        = $orderby;
    $args['order']          = $order;

    if ($meta_key) :
        $args['meta_key'] = $meta_key;
    endif;

    return $args;

}


问:
UNRESOLVED DEPENDENCIES for commons-codec
I'm trying to retrieve the library for Google Reporting API:

```<code>compile 'com.google.apis:google-api-services-analytics:v3-rev74-1.17.0-rc'
</code>```

but I got an unresolved dependencies error and I don't know what to do with it:

```<code>:: commons-codec#commons-codec;1.6: configuration not found in commons-codec#commons-codec;1.6: 'master'. It was required from org.apache.httpcomponents#httpclient;4.0.1 compile
</code>```

I checked the .grails\ivy-cache\ folder and there's a commons-codec folder with jars of commons-codec-1.5, few xml files ivy-1.5.xml and ivy-1.6.xml and ivydata-1.5.properties and ivydata-1.6.properties. I also tried to delete the whole ivy-cache folder, but the result is the same.

答: Removing .ivy2/cache/ helped me resolving the dependencies.

Body:
I'm trying to retrieve the library for Google Reporting API:

compile 'com.google.apis:google-api-services-analytics:v3-rev74-1.17.0-rc'

but I got an unresolved dependencies error and I don't know what to do with it:

:: commons-codec#commons-codec;1.6: configuration not found in commons-codec#commons-codec;1.6: 'master'. It was required from org.apache.httpcomponents#httpclient;4.0.1 compile

I checked the .grails\ivy-cache\ folder and there's a commons-codec folder with jars of commons-codec-1.5, few xml files ivy-1.5.xml and ivy-1.6.xml and ivydata-1.5.properties and ivydata-1.6.properties. I also tried to delete the whole ivy-cache folder, but the result is the same.

ContentLicense: CC BY-SA 4.0