问:
PowerMockito.mockStatic() of a static method is not working correctly in Spring Boot Test

This is the setup of the test class:

```<code>@RunWith(PowerMockRunner.class)
@PowerMockIgnore("javax.management.*")
@PowerMockRunnerDelegate(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = ServiceApplication.class)
@PrepareForTest({ MyClass.class })
public class ControllerTest {

    @Autowired
    public TestRestTemplate restTemplate;

    public static MyClass myClass = Mockito.mock(MyClass.class);

    @BeforeClass
    public static void beforeClassSetup() throws Exception {
        PowerMockito.mockStatic(MyClass.class);
        BDDMockito.given(MyClass.getInstance(Mockito.anyString())).willReturn(myClass);
        BDDMockito.given(myClass.foo()).willReturn("BAR");
        // ...
    }
 .
 .
 .
 // test cases
</code>```

In configuration class of this project, for load some beans, I use this static call for generate the instance.

```<code>@Configuration
@ComponentScan(basePackages = { "package.from.another.project.in.production" })
public class Beans {

    @Bean
    public MyClass myClass() {
        return MyClass.getInstance(K.FOO);
    }

}
</code>```

This is my controller that uses the bean, as well as the static call according to the parameters.

```<code>@RestController
public class Controller {

    @Autowired
    private MyClass myClass;

    @GetMapping(path = "/")
    public String doSomething() {
            String filter = myClass.foo();
            return filter;
    }

    @GetMapping(path = "/two")
    public String doSomething2(@RequestParam Map<String, String> allParams) {
            String accountId = allParams.get("account_id");
            String filter = MyClass.getInstance(K.BAR + accountId).foo();
            return filter;
    }
}
</code>```

The bean is autowired because its use is greater than instantiation by the getInstance() method. In addition, the instantiation by the getIntance() method is variable according to the parameter. Don't ask me why the MyClass class is like this, because the API was old and I'm slowly refactoring.

The issue is that the autowired bean is correctly mocked by PowerMockito.mockStatic(MyClass.class) and also by @MockBean (which I used initially), but the call MyClass.getInstance() in Controller.class does not work at all.

I think the problem should happen when Spring climbs its environment and does not load everything that has been correctly mocked by PowerMockito, just the classes of its beans. Can anyone help me solve this problem?

答: This is just a wild guess, have you tried using regular Mockito as opposed to BDDMockito? Just want to rule it out as a culprit.</p>

Body:
This is the setup of the test class:

@RunWith(PowerMockRunner.class)
@PowerMockIgnore("javax.management.*")
@PowerMockRunnerDelegate(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = ServiceApplication.class)
@PrepareForTest({ MyClass.class })
public class ControllerTest {

    @Autowired
    public TestRestTemplate restTemplate;

    public static MyClass myClass = Mockito.mock(MyClass.class);

    @BeforeClass
    public static void beforeClassSetup() throws Exception {
        PowerMockito.mockStatic(MyClass.class);
        BDDMockito.given(MyClass.getInstance(Mockito.anyString())).willReturn(myClass);
        BDDMockito.given(myClass.foo()).willReturn("BAR");
        // ...
    }
 .
 .
 .
 // test cases

In configuration class of this project, for load some beans, I use this static call for generate the instance.

@Configuration
@ComponentScan(basePackages = { "package.from.another.project.in.production" })
public class Beans {

    @Bean
    public MyClass myClass() {
        return MyClass.getInstance(K.FOO);
    }

}

This is my controller that uses the bean, as well as the static call according to the parameters.

@RestController
public class Controller {

    @Autowired
    private MyClass myClass;

    @GetMapping(path = "/")
    public String doSomething() {
            String filter = myClass.foo();
            return filter;
    }

    @GetMapping(path = "/two")
    public String doSomething2(@RequestParam Map<String, String> allParams) {
            String accountId = allParams.get("account_id");
            String filter = MyClass.getInstance(K.BAR + accountId).foo();
            return filter;
    }
}

The bean is autowired because its use is greater than instantiation by the getInstance() method. In addition, the instantiation by the getIntance() method is variable according to the parameter. Don't ask me why the MyClass class is like this, because the API was old and I'm slowly refactoring.

The issue is that the autowired bean is correctly mocked by PowerMockito.mockStatic(MyClass.class) and also by @MockBean (which I used initially), but the call MyClass.getInstance() in Controller.class does not work at all.

I think the problem should happen when Spring climbs its environment and does not load everything that has been correctly mocked by PowerMockito, just the classes of its beans. Can anyone help me solve this problem?


来源: stackexchange

问:
<input type="text"> does not allow resizing
I can't figure out why my input does not allow me to resize it.

<input type="text">

Example of the problem

I only want to have a working resize on my biginput class.

答:
You need textarea for that :-

<textarea name="entry.585452596" type="text" class="biginput"></textarea>```

ContentLicense: CC BY-SA 3.0


问:
How to check if a specific pixel of an image is transparent?
Is there any way to check if a selected (x,y) point of a PNG image is transparent?</p>

答:
The two previous answers demonstrate how to use Canvas and ImageData. I would like to propose an answer with runnable example and using an image processing framework, so you don't need to handle the pixel data manually.

MarvinJ provides the method image.getAlphaComponent(x,y) which simply returns the transparency value for the pixel in x,y coordinate. If this value is 0, pixel is totally transparent, values between 1 and 254 are transparency levels, finally 255 is opaque.

For demonstrating I've used the image below (300x300) with transparent background and two pixels at coordinates (0,0) and (150,150).

Console output:

(0,0): TRANSPARENT

(150,150): NOT_TRANSPARENT

image = new MarvinImage();
image.load("https://i.imgur.com/eLZVbQG.png", imageLoaded);

function imageLoaded(){
  console.log("(0,0): "+(image.getAlphaComponent(0,0) > 0 ? "NOT_TRANSPARENT" : "TRANSPARENT"));
  console.log("(150,150): "+(image.getAlphaComponent(150,150) > 0 ? "NOT_TRANSPARENT" : "TRANSPARENT"));
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://www.marvinj.org/releases/marvinj-0.7.js"></script></code>```

ContentLicense: CC BY-SA 4.0

Body:
The two previous answers demonstrate how to use Canvas and ImageData. I would like to propose an answer with runnable example and using an image processing framework, so you don't need to handle the pixel data manually.

MarvinJ provides the method image.getAlphaComponent(x,y) which simply returns the transparency value for the pixel in x,y coordinate. If this value is 0, pixel is totally transparent, values between 1 and 254 are transparency levels, finally 255 is opaque.

For demonstrating I've used the image below (300x300) with transparent background and two pixels at coordinates (0,0) and (150,150).

Console output:

(0,0): TRANSPARENT

(150,150): NOT_TRANSPARENT

image = new MarvinImage();
image.load("https://i.imgur.com/eLZVbQG.png", imageLoaded);

function imageLoaded(){
  console.log("(0,0): "+(image.getAlphaComponent(0,0) > 0 ? "NOT_TRANSPARENT" : "TRANSPARENT"));
  console.log("(150,150): "+(image.getAlphaComponent(150,150) > 0 ? "NOT_TRANSPARENT" : "TRANSPARENT"));
}

<script src="https://www.marvinj.org/releases/marvinj-0.7.js"></script>


问:
Generate manifest files for registration-free COM
I have some applications (some native, some .NET) which use manifest files so that they can be deployed in complete isolation, without requiring any global COM registration. For example, the dependency on the dbgrid32.ocx com server is declared as follows in the myapp.exe.manifest file which sits in the same folder as myapp.exe:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
  <assemblyIdentity type="win32" name="myapp.exe" version="1.2.3.4" />
  <dependency>
    <dependentAssembly>
      <assemblyIdentity type="win32" name="dbgrid32.ocx" version="5.1.81.4" />
    </dependentAssembly>
  </dependency>
</assembly>
```

<p>The dbgrid32.ocx is deployed to the same folder, along with it's own dbgrid32.ocx.manifest file:</p>

<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="utf-8" standalone="yes"?>
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
  <assemblyIdentity type="win32" name="dbgrid32.ocx" version="5.1.81.4" />
  <file name="dbgrid32.ocx">
     <typelib
        tlbid="{00028C01-0000-0000-0000-000000000046}"
        version="1.0"
        helpdir=""/>
    <comClass progid="MSDBGrid.DBGrid"
       clsid="{00028C00-0000-0000-0000-000000000046}"
       description="DBGrid  Control" />
  </file>
</assembly>
</code>```

This all works fine but maintaining these manifest files manually is a bit of a pain. Is there a way to generate these files automatically? Ideally I would just like to declare the application's dependency on a list of COM servers (both native and .NET) and then let the rest be generated automatically. Is it possible?

答:
It looks like the perfect solution does not yet exist. To summarize some research:

Make My Manifest (link)

This tool scans a VB6 project to look for COM dependencies, but it also supports manual declaration of late-bound COM dependencies (i.e. those used via CreateObject).

Interestingly enough, this tool puts all information about the dependencies inside the application manifest. The application exe and its dependencies are described as a single assembly consisting of multiple files. I hadn't realized before that this was possible.

Looks like a very good tool but as of version 0.6.6 it has the following limitations:

only for VB6 applications, starts
from VB6 project file. Shame, because
a lot of what it does really has nothing to do
with VB6.

wizard style application, not
suitable to integrate in a build
process. This is not a huge problem if your
dependencies don't change a lot.

freeware without source, risky to rely on it because it could become abandonware at any moment.

I did not test whether it supports .NET com libraries.

regsvr42 (codeproject link)

This command line tool generates manifest files for native COM libraries. It invokes DllRegisterServer and then spies on the self-registration as it adds information into the registry. It can also generate a client manifest for applications.

This utility does not support .NET COM libraries, since these don't expose a DllRegisterServer routine.

The utility is written in C++. The source code is available.

mt.exe

Part of the windows SDK (can be downloaded from MSDN), which you already have if you have visual studio installed. It is documented here.
You can generate manifest files for native COM libraries with it like this:

```<code>mt.exe -tlb:mycomlib.ocx -dll:mycomlib.ocx -out:mycomlib.ocx.manifest
</code>```

You can generate manifest files for .NET COM libraries with it like this:

```<code>mt.exe -managedassemblyname:netlib.dll -nodependency -out:netlib.dll.manifest
</code>```

However, there are some problems with this tool:

The first snippet will not generate
progid attributes, breaking clients
which use CreateObject with progids.

The second snippet will generate
<runtime> and <mvid> elements
which need to be stripped out before
the manifests actually work.

Generation of client manifests for
applications is not supported.

Maybe future SDK releases will improve this tool, I tested the one in the Windows SDK 6.0a (vista).

OwnerDisplayName: wcoenen

Body:
I have some applications (some native, some .NET) which use manifest files so that they can be deployed in complete isolation, without requiring any global COM registration. For example, the dependency on the dbgrid32.ocx com server is declared as follows in the myapp.exe.manifest file which sits in the same folder as myapp.exe:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
  <assemblyIdentity type="win32" name="myapp.exe" version="1.2.3.4" />
  <dependency>
    <dependentAssembly>
      <assemblyIdentity type="win32" name="dbgrid32.ocx" version="5.1.81.4" />
    </dependentAssembly>
  </dependency>
</assembly>

The dbgrid32.ocx is deployed to the same folder, along with it's own dbgrid32.ocx.manifest file:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
  <assemblyIdentity type="win32" name="dbgrid32.ocx" version="5.1.81.4" />
  <file name="dbgrid32.ocx">
     <typelib
        tlbid="{00028C01-0000-0000-0000-000000000046}"
        version="1.0"
        helpdir=""/>
    <comClass progid="MSDBGrid.DBGrid"
       clsid="{00028C00-0000-0000-0000-000000000046}"
       description="DBGrid  Control" />
  </file>
</assembly>

This all works fine but maintaining these manifest files manually is a bit of a pain. Is there a way to generate these files automatically? Ideally I would just like to declare the application's dependency on a list of COM servers (both native and .NET) and then let the rest be generated automatically. Is it possible?

LastEditorDisplayName: MarkJ

Body:
It looks like the perfect solution does not yet exist. To summarize some research:

Make My Manifest (link)

This tool scans a VB6 project to look for COM dependencies, but it also supports manual declaration of late-bound COM dependencies (i.e. those used via CreateObject).

Interestingly enough, this tool puts all information about the dependencies inside the application manifest. The application exe and its dependencies are described as a single assembly consisting of multiple files. I hadn't realized before that this was possible.

Looks like a very good tool but as of version 0.6.6 it has the following limitations:

only for VB6 applications, starts
from VB6 project file. Shame, because
a lot of what it does really has nothing to do
with VB6.

wizard style application, not
suitable to integrate in a build
process. This is not a huge problem if your
dependencies don't change a lot.

freeware without source, risky to rely on it because it could become abandonware at any moment.

I did not test whether it supports .NET com libraries.

regsvr42 (codeproject link)

This command line tool generates manifest files for native COM libraries. It invokes DllRegisterServer and then spies on the self-registration as it adds information into the registry. It can also generate a client manifest for applications.

This utility does not support .NET COM libraries, since these don't expose a DllRegisterServer routine.

The utility is written in C++. The source code is available.

mt.exe

Part of the windows SDK (can be downloaded from MSDN), which you already have if you have visual studio installed. It is documented here.
You can generate manifest files for native COM libraries with it like this:

mt.exe -tlb:mycomlib.ocx -dll:mycomlib.ocx -out:mycomlib.ocx.manifest

You can generate manifest files for .NET COM libraries with it like this:

mt.exe -managedassemblyname:netlib.dll -nodependency -out:netlib.dll.manifest

However, there are some problems with this tool:

The first snippet will not generate
progid attributes, breaking clients
which use CreateObject with progids.

The second snippet will generate
<runtime> and <mvid> elements
which need to be stripped out before
the manifests actually work.

Generation of client manifests for
applications is not supported.

Maybe future SDK releases will improve this tool, I tested the one in the Windows SDK 6.0a (vista).

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: wcoenen


问:
Cannot find symbol : when compiling java code
I am writing some Java classes to implement RMI. I wrote all the classes and the program worked fine. But from the very next day I am getting a compiler error indicating that the absence of files:

Filename: ServerInterface.java

```<code>import java.rmi.*;

public interface ServerInterface extends Remote
{
  public double sum(double[] temp) throws RemoteException;
};
</code>```

Filename: ServerImplement.java

```<code>import java.rmi.*;
import java.rmi.server.*;

public class ServerImplement extends UnicastRemoteObject implements ServerInterface
{

 public ServerImplement() throws RemoteException
 {
 }

 public double sum(double[] temp) throws RemoteException
 {
   double sum=0;
   int len=temp.length;
   for(int i=0;i<len;i++)
     sum+=temp[i];

   return sum;
 }
};
</code>```

Even to prove that its not any filename errors:

```<code>F:\E\java\rmi final>dir
 Volume in drive F is My Volume
 Volume Serial Number is E0F9-4F89

 Directory of F:\E\java\rmi final

22-01-2011  23:23    <DIR>          .
22-01-2011  23:23    <DIR>          ..
22-12-2009  13:09             1,849 additionImplementer_Stub.class
21-01-2011  21:52             1,076 Client.class
18-01-2011  02:54               649 Client.java
21-01-2011  21:52             1,847 ClientTry.class
18-01-2011  02:54             1,268 ClientTry.java
21-01-2011  21:52               444 ServerImplement.class
18-01-2011  02:30               386 ServerImplement.java
18-01-2011  02:54             1,783 ServerImplement_Stub.class
21-01-2011  21:54               209 ServerInterface.class
22-12-2009  12:07               132 ServerInterface.java
21-01-2011  21:52               919 ServerMain.class
18-01-2011  02:36               409 ServerMain.java
          12 File(s)         10,971 bytes
</code>```

If I try: javac *.java , it works fine (but trying java on any of the .class files leads to error : Exception in thread "main" java.lang.NoClassDefFoundError: ServerMain

If I try javac ServerImplement.java I get an error (in fact none of my java programs are able to link):
(I am in the same directory)

E:\java\rmi final>javac  ServerMain.java

  ServerImplement.java:4: cannot find symbol

  symbol: class ServerInterface

  public class ServerImplement extends UnicastRemoteObject implements ServerInterface

  ^

  1 error

The program is even working fine at my college lab. Should I reinstall JDK? Or is there any way to provide linking explicitly?

答:
There is no linking when compiling java code.
The compiler still needs to find all classes that are referenced by the code being compiled.
If you don't use packages, make sure you run javac in the same directory your .java is in. A javac *.java should be able to resolve your problems.</p>

Body:
I am writing some Java classes to implement RMI. I wrote all the classes and the program worked fine. But from the very next day I am getting a compiler error indicating that the absence of files:

Filename: ServerInterface.java

import java.rmi.*;

public interface ServerInterface extends Remote
{
  public double sum(double[] temp) throws RemoteException;
};

Filename: ServerImplement.java

import java.rmi.*;
import java.rmi.server.*;

public class ServerImplement extends UnicastRemoteObject implements ServerInterface
{

 public ServerImplement() throws RemoteException
 {
 }

 public double sum(double[] temp) throws RemoteException
 {
   double sum=0;
   int len=temp.length;
   for(int i=0;i<len;i++)
     sum+=temp[i];

   return sum;
 }
};

Even to prove that its not any filename errors:

F:\E\java\rmi final>dir
 Volume in drive F is My Volume
 Volume Serial Number is E0F9-4F89

 Directory of F:\E\java\rmi final

22-01-2011  23:23    <DIR>          .
22-01-2011  23:23    <DIR>          ..
22-12-2009  13:09             1,849 additionImplementer_Stub.class
21-01-2011  21:52             1,076 Client.class
18-01-2011  02:54               649 Client.java
21-01-2011  21:52             1,847 ClientTry.class
18-01-2011  02:54             1,268 ClientTry.java
21-01-2011  21:52               444 ServerImplement.class
18-01-2011  02:30               386 ServerImplement.java
18-01-2011  02:54             1,783 ServerImplement_Stub.class
21-01-2011  21:54               209 ServerInterface.class
22-12-2009  12:07               132 ServerInterface.java
21-01-2011  21:52               919 ServerMain.class
18-01-2011  02:36               409 ServerMain.java
          12 File(s)         10,971 bytes

If I try: javac *.java , it works fine (but trying java on any of the .class files leads to error : Exception in thread "main" java.lang.NoClassDefFoundError: ServerMain

If I try javac ServerImplement.java I get an error (in fact none of my java programs are able to link):
(I am in the same directory)

E:\java\rmi final>javac  ServerMain.java

  ServerImplement.java:4: cannot find symbol

  symbol: class ServerInterface

  public class ServerImplement extends UnicastRemoteObject implements ServerInterface

  ^

  1 error

The program is even working fine at my college lab. Should I reinstall JDK? Or is there any way to provide linking explicitly?


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

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

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

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

        return inputname;
    }

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

答:
Try this:

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

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

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

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

You must do two things:

Store Dialog()'s returned inputname in a variable.

Hand that value over to Print().

What you miss is that you loose the user's data as you don't store it in a variable.

Title: Returning String from method in Java

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

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

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

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

        return inputname;
    }

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

Body:
Try this:

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

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

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

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

You must do two things:

Store Dialog()'s returned inputname in a variable.

Hand that value over to Print().

What you miss is that you loose the user's data as you don't store it in a variable.


问:
How to get a key in a dictionary in a dictionary
here's my list :

```<code>data_config = [{'music': {' extension': 'mp3'}},
 {'reports/INFOB131': {' extension': ['doc', 'docx', 'pdf'],
   ' max_size': '100000',
   ' name_contains': 'INFOB131'}},
 {'reports/INFOB132': {' extension': ['doc', 'docx', 'pdf'],
   ' max_size': '100000',
   ' name_contains': 'INFOB132'}},
 {'games': {' name_contains': ['SC2', 'Wesnoth']}},
 {'pictures/Namur': {' extension': 'jpeg',
   ' min_size': '5000000',
   ' name_contains': 'cercle'}},
 {'pictures/autres': {' extension': 'jpeg', ' min_size': '5000000'}}]
</code>```

When I do these instructions, I get :

```<code>for i in data_config[0]['music']:
    print(data_config[0]['music'][i])

output : mp3
</code>```

But when I do this, I get an error:

```<code>print(data_config[0]['music']['extension'])

output : ---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-9-f71c5ad09034> in <module>()
----> 1 print(data_config[0]['music']['extension'])

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

Does anyone have an idea ?

Thank you !

答:
Looks like you have a space in your key name.  It's not extension, it's
    " extension"</p>

Body:
here's my list :

data_config = [{'music': {' extension': 'mp3'}},
 {'reports/INFOB131': {' extension': ['doc', 'docx', 'pdf'],
   ' max_size': '100000',
   ' name_contains': 'INFOB131'}},
 {'reports/INFOB132': {' extension': ['doc', 'docx', 'pdf'],
   ' max_size': '100000',
   ' name_contains': 'INFOB132'}},
 {'games': {' name_contains': ['SC2', 'Wesnoth']}},
 {'pictures/Namur': {' extension': 'jpeg',
   ' min_size': '5000000',
   ' name_contains': 'cercle'}},
 {'pictures/autres': {' extension': 'jpeg', ' min_size': '5000000'}}]

When I do these instructions, I get :

for i in data_config[0]['music']:
    print(data_config[0]['music'][i])

output : mp3

But when I do this, I get an error:

print(data_config[0]['music']['extension'])

output : ---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-9-f71c5ad09034> in <module>()
----> 1 print(data_config[0]['music']['extension'])

KeyError: 'extension'

Does anyone have an idea ?

Thank you !


问:
How to fix this loop for sorting packages by weight
I need to create a program that asks the customer how many packages they have (after the input it creates an array of that size) which then ask the customer to enter the weights of them. It then has to sort the packages into small, medium, or large and then prints how many of each size package there is.

```<code>public static void main(String[] args)
{
    Scanner scan = new Scanner(System.in);
    int small = 0;
    int medium = 0;
    int large = 0;
    int size = 0;
    int[] intArray = {size};

    System.out.printf("Please enter the number of weights to enter: ");
    size = scan.nextInt();

    for (double i = 0; i < intArray.length; i++){
        if (i < size)
            System.out.print("Please Enter weight1: ");
            double weights = scan.nextInt();

    System.out.println("\nPackage Weights");
        System.out.print(weights);

        if (weights <= 5)
            small = 1 + small;
        if (weights <= 10 && weights >= 6)
            medium = 1 + medium;
        if (weights >= 11)
            large = 1 + large;

            System.out.println("\n\nSmall: " + small);
            System.out.println("Medium: " +  medium);
            System.out.println("Large:" + large);

    }
}
</code>```

}

I got the sorting to work, but I can only get it to ask for one package, which means my array and loop aren't working. Just now learning arrays / loops so i'm kinda stuck on this.

答:
The problem is the time at which your intArray is initialised.
It gets initialised just after size is initialized with the value of 0.
Therefore you end up with a single Element in your array.

All you have to do is move the initialisation of your intArray after the user  input:

```<code>int[] intArray;

    System.out.printf("Please enter the number of weights to enter: ");
    size = scan.nextInt();
    intArray = new int[size]; //<-- initialization of the array after the user input

    for (double i = 0; i < intArray.length; i++){
</code>```

Body:
I need to create a program that asks the customer how many packages they have (after the input it creates an array of that size) which then ask the customer to enter the weights of them. It then has to sort the packages into small, medium, or large and then prints how many of each size package there is.

public static void main(String[] args)
{
    Scanner scan = new Scanner(System.in);
    int small = 0;
    int medium = 0;
    int large = 0;
    int size = 0;
    int[] intArray = {size};

    System.out.printf("Please enter the number of weights to enter: ");
    size = scan.nextInt();

    for (double i = 0; i < intArray.length; i++){
        if (i < size)
            System.out.print("Please Enter weight1: ");
            double weights = scan.nextInt();

    System.out.println("\nPackage Weights");
        System.out.print(weights);

        if (weights <= 5)
            small = 1 + small;
        if (weights <= 10 && weights >= 6)
            medium = 1 + medium;
        if (weights >= 11)
            large = 1 + large;

            System.out.println("\n\nSmall: " + small);
            System.out.println("Medium: " +  medium);
            System.out.println("Large:" + large);

    }
}

}

I got the sorting to work, but I can only get it to ask for one package, which means my array and loop aren't working. Just now learning arrays / loops so i'm kinda stuck on this.

Body:
The problem is the time at which your intArray is initialised.
It gets initialised just after size is initialized with the value of 0.
Therefore you end up with a single Element in your array.

All you have to do is move the initialisation of your intArray after the user  input:

int[] intArray;

    System.out.printf("Please enter the number of weights to enter: ");
    size = scan.nextInt();
    intArray = new int[size]; //<-- initialization of the array after the user input

    for (double i = 0; i < intArray.length; i++){


问:
Laravel 5.5 Supplementing Resource Controllers example
I have difficults to create a supplementing Resource in a controller laravel and insert it in the web.php for the routing.

I would to implement a search functions, in an Articles controller .Beyond the authomatic generated function like (index, show...) i have created another one:

public function search($title){
      $articles = Article::findOrFail($title);
        return $articles;
      }

And I have added it in the web.php for the routing:

```<code>Route::resource('articles/{title}', 'ArticleController@search');
</code>```

When I try to test this search, it doesn't work. All the implicit controller go well, I have problem only with this selfmade function.

How can I solve this issue?

thanks

答:
You need to add another route before resource one to make it work:

```<code>Route::get('articles/{title}', 'ArticleController@search');
</code>```

You also want to change the query if you want to find an article by it's slug, for example:

```<code>$article = User::where('slug', $title)->first();
</code>```

Body:
I have difficults to create a supplementing Resource in a controller laravel and insert it in the web.php for the routing.

I would to implement a search functions, in an Articles controller .Beyond the authomatic generated function like (index, show...) i have created another one:

public function search($title){
      $articles = Article::findOrFail($title);
        return $articles;
      }

And I have added it in the web.php for the routing:

Route::resource('articles/{title}', 'ArticleController@search');

When I try to test this search, it doesn't work. All the implicit controller go well, I have problem only with this selfmade function.

How can I solve this issue?

thanks

Body:
You need to add another route before resource one to make it work:

Route::get('articles/{title}', 'ArticleController@search');

You also want to change the query if you want to find an article by it's slug, for example:

$article = User::where('slug', $title)->first();


答: However your question is a bit confusing to me what exactly you mean by reducing the rows.  Guessing it be deletion,  you can achieve same by delete query with where clause parameters also with time range less than or greater than operator. </p>

Title: SQL query to reduce,delete unnecessary rows

Body:
I want to achieve this

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

from these rows in the same table

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

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

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


问:
Apache Ignite.NET SQL not searching for non english characters
Using Apache Ignite .NET 2.3.0
Trying to search using Linq extension (Apache.Ignite.Linq).

Configuration:

```<code>     CacheConfiguration = new[]
     {
         new CacheConfiguration
         {
             QueryEntities = new []
             {
                  new QueryEntity(typeof(string), typeof(SecuritiesItem))
                  {
                      Fields = new []
                      {
                          new QueryField { Name = "SearchString", FieldType = typeof(string)}
                      }
                  }
             }
         }
     }
</code>```

SecuritiesItem definition:

```<code>public class SecuritiesItem
{
    /* all other fields */

    public string ShortName { get; set; }
    public string SearchString { get; set; }
}
</code>```

SearchString contains merged data from all fields what need to be used in search. Like this:

Открытое акционерное общество " Рога и копыта
  "#☢#Systems Open Joint-Stock Company#☢#ОАО
  "РиК"#☢#Ssys#☢#335468321#☢#bner#☢#ОАО "РиК"#☢#
  Systems Open Joint-Stock Company#☢#Открытое акционерное
  общество "Рога и копыта"#☢#Systems
  Open Joint-Stock Company#☢#RU003572593#☢#1-22-22222-A

Searching like this:

```<code>_securitiesCache
    .AsCacheQueryable()
    .Where(s => s.Value.SearchString.Contains(query))
    // or .Where(s => s.Value.SearchString.ToLower().IndexOf(query) != -1)
    .ToArray()
    .Select(x => x.Value);
</code>```

So, if i searching for "Open" - it find everithing normally. But if i searching for "Откр", no results found.

Trying to search by specific field in object, like ShortName using '==', same result. Should I convert the text into a specific encoding?

SelfResolved

it's postman fault. https://github.com/postmanlabs/postman-app-support/issues/2263 bug in url encoding.

答:
Can you share a sample project-reproducer?

I updated several tests and they work fine for a similar case. I did not change encoding or convert text into some specific encoding, it is in UTF-8 by default.

Body:
Using Apache Ignite .NET 2.3.0
Trying to search using Linq extension (Apache.Ignite.Linq).

Configuration:

     CacheConfiguration = new[]
     {
         new CacheConfiguration
         {
             QueryEntities = new []
             {
                  new QueryEntity(typeof(string), typeof(SecuritiesItem))
                  {
                      Fields = new []
                      {
                          new QueryField { Name = "SearchString", FieldType = typeof(string)}
                      }
                  }
             }
         }
     }

SecuritiesItem definition:

public class SecuritiesItem
{
    /* all other fields */

    public string ShortName { get; set; }
    public string SearchString { get; set; }
}

SearchString contains merged data from all fields what need to be used in search. Like this:

Открытое акционерное общество " Рога и копыта
  "#☢#Systems Open Joint-Stock Company#☢#ОАО
  "РиК"#☢#Ssys#☢#335468321#☢#bner#☢#ОАО "РиК"#☢#
  Systems Open Joint-Stock Company#☢#Открытое акционерное
  общество "Рога и копыта"#☢#Systems
  Open Joint-Stock Company#☢#RU003572593#☢#1-22-22222-A

Searching like this:

_securitiesCache
    .AsCacheQueryable()
    .Where(s => s.Value.SearchString.Contains(query))
    // or .Where(s => s.Value.SearchString.ToLower().IndexOf(query) != -1)
    .ToArray()
    .Select(x => x.Value);

So, if i searching for "Open" - it find everithing normally. But if i searching for "Откр", no results found.

Trying to search by specific field in object, like ShortName using '==', same result. Should I convert the text into a specific encoding?

SelfResolved

it's postman fault. https://github.com/postmanlabs/postman-app-support/issues/2263 bug in url encoding.


问:
Excel,Multiple Criteria Index - Match keeps returning #NA value
I'm trying to find the total number of sessions on column E regarding the year,month and segment columns.
I'm using the index - match formula withing a array formula as I'm adding 3 matching criteria but I still get the #NA result.

The reason why I want to do it this way is that I'm working on some vba code and want to assign the value of that cell to a variable. Then I can use dynamic variables to iterate through each row and column as I don't know how long the list will grow.

This is the excel formula I'm using:

```<code>=INDEX($A$1:$E$27,MATCH(1,($A$1:$E$27=H1)*($A1:$E27=H2)*($A1:$E27=H3),0),5)
</code>```

On the attached image I have highlighted the row and columns that I'm using for this example, so the result would have to get the number 988860.

So my question is: How do I use the array formula with multiple criteria to find the number of  sessions?

Thanks!

答:
Thank you tigeravatar,I changed the formula to look each criteria on its specific column and it works!
So the final formula looks like this:</p>

```<code>={INDEX($E$2:$E$27,MATCH(1,($B$1:$B$27=$H$1)*($A$1:$A$27=$H$2)*($D$1:$D$27=$H$3),0),5)}
</code>```

Body:
I'm trying to find the total number of sessions on column E regarding the year,month and segment columns.
I'm using the index - match formula withing a array formula as I'm adding 3 matching criteria but I still get the #NA result.

The reason why I want to do it this way is that I'm working on some vba code and want to assign the value of that cell to a variable. Then I can use dynamic variables to iterate through each row and column as I don't know how long the list will grow.

This is the excel formula I'm using:

=INDEX($A$1:$E$27,MATCH(1,($A$1:$E$27=H1)*($A1:$E27=H2)*($A1:$E27=H3),0),5)

On the attached image I have highlighted the row and columns that I'm using for this example, so the result would have to get the number 988860.

So my question is: How do I use the array formula with multiple criteria to find the number of  sessions?

Thanks!

Body:
Thank you tigeravatar,I changed the formula to look each criteria on its specific column and it works!
So the final formula looks like this:

={INDEX($E$2:$E$27,MATCH(1,($B$1:$B$27=$H$1)*($A$1:$A$27=$H$2)*($D$1:$D$27=$H$3),0),5)}


问:
R - Change column name using get()

I have several data.frames in my Global Environment that I need to merge. Many of the data.frames have identical column names. I want to append a suffix to each column that marks its originating data.frame. Because I have many data.frames, I wanted to automate the process as in the following example.

```<code>df1 <-  data.frame(id = 1:5,x = LETTERS[1:5])
df2 <-  data.frame(id = 1:5,x = LETTERS[6:10])

obj <- ls()

for(o in obj){
  s <- sub('df','',eval(o))
  names(get(o))[-1] <- paste0(names(get(o))[-1],'.',s)
}

# Error in get(o) <- `*vtmp*` : could not find function "get<-"'
</code>```

But the individual pieces of the assignment work fine:

```<code>names(get(o))[-1]
# [1] "x"
paste0(names(get(o))[-1],'.',s)
# [1] "x.1"
</code>```

I've used get in a similar way to write.csveach object to a file.

```<code>for(o in obj){
  write.csv(get(o),file = paste0(o,'.csv'),row.names = F)
}
</code>```

Any ideas why it's not working in the assignment to change the column names?

答:
The error "could not find function get<-" is R telling you that you can't use <- to update a "got" object. You could probably use assign, but this code is already difficult enough to read. The better solution is to use a list.

From your example:

```<code>df1 <-  data.frame(id = 1:5,x = LETTERS[1:5])
df2 <-  data.frame(id = 1:5,x = LETTERS[6:10])

# put your data frames in a list
df_names = ls(pattern = "df[0-9]+")
df_names   # make sure this is the objects you want
# [1] "df1" "df2"
df_list = mget(df_names)

# now we can use a simple for loop (or lapply, mapply, etc.)
for(i in seq_along(df_list)) {
    names(df_list[[i]])[-1] =
        paste(names(df_list[[i]])[-1],
              sub('df', '', names(df_list)[i]),
              sep = "."
        )
}

# and the column names of the data frames in the list have been updated
df_list
# $df1
#   id x.1
# 1  1   A
# 2  2   B
# 3  3   C
# 4  4   D
# 5  5   E
#
# $df2
#   id x.2
# 1  1   F
# 2  2   G
# 3  3   H
# 4  4   I
# 5  5   J
</code>```

It's also now easy to merge them:

```<code>Reduce(f = merge, x = df_list)
#   id x.1 x.2
# 1  1   A   F
# 2  2   B   G
# 3  3   C   H
# 4  4   D   I
# 5  5   E   J
</code>```

For more discussion and examples, see How do I make a list of data frames?

Title: R - Change column name using get()

Body:
I have several data.frames in my Global Environment that I need to merge. Many of the data.frames have identical column names. I want to append a suffix to each column that marks its originating data.frame. Because I have many data.frames, I wanted to automate the process as in the following example.

df1 <-  data.frame(id = 1:5,x = LETTERS[1:5])
df2 <-  data.frame(id = 1:5,x = LETTERS[6:10])

obj <- ls()

for(o in obj){
  s <- sub('df','',eval(o))
  names(get(o))[-1] <- paste0(names(get(o))[-1],'.',s)
}

# Error in get(o) <- `*vtmp*` : could not find function "get<-"'

But the individual pieces of the assignment work fine:

names(get(o))[-1]
# [1] "x"
paste0(names(get(o))[-1],'.',s)
# [1] "x.1"

I've used get in a similar way to write.csveach object to a file.

for(o in obj){
  write.csv(get(o),file = paste0(o,'.csv'),row.names = F)
}

Any ideas why it's not working in the assignment to change the column names?

Body:
The error "could not find function get<-" is R telling you that you can't use <- to update a "got" object. You could probably use assign, but this code is already difficult enough to read. The better solution is to use a list.

From your example:

df1 <-  data.frame(id = 1:5,x = LETTERS[1:5])
df2 <-  data.frame(id = 1:5,x = LETTERS[6:10])

# put your data frames in a list
df_names = ls(pattern = "df[0-9]+")
df_names   # make sure this is the objects you want
# [1] "df1" "df2"
df_list = mget(df_names)

# now we can use a simple for loop (or lapply, mapply, etc.)
for(i in seq_along(df_list)) {
    names(df_list[[i]])[-1] =
        paste(names(df_list[[i]])[-1],
              sub('df', '', names(df_list)[i]),
              sep = "."
        )
}

# and the column names of the data frames in the list have been updated
df_list
# $df1
#   id x.1
# 1  1   A
# 2  2   B
# 3  3   C
# 4  4   D
# 5  5   E
#
# $df2
#   id x.2
# 1  1   F
# 2  2   G
# 3  3   H
# 4  4   I
# 5  5   J

It's also now easy to merge them:

Reduce(f = merge, x = df_list)
#   id x.1 x.2
# 1  1   A   F
# 2  2   B   G
# 3  3   C   H
# 4  4   D   I
# 5  5   E   J

For more discussion and examples, see How do I make a list of data frames?


问:
OnNext not being called on observable when using combineLatest and take
I'm trying to get a subscription to automatically unsubscribe when it emits an item. The base observable is created like this.

```<code>public static Observable<RxBleConnection> setupConnection(RxBleDevice device, PublishSubject<Void> disconnectTrigger) {
    return device
            .establishConnection(false)
            .takeUntil(disconnectTrigger)
            .retry(3)
            .retryWhen(o -> o.delay(RETRY_DELAY, TimeUnit.MILLISECONDS))
            .compose(new ConnectionSharingAdapter());
}
</code>```

Then I try to combine three read operations into a ProgramModel.

```<code>private void readCharacteristics(Action1<ProgramModel> onReadSuccess) {
    mConnectionObservable
            .flatMap(rxBleConnection ->
                    // combines the following three observables into a single observable that is
                    // emitted in onNext of the subscribe
                    Observable.combineLatest(
                            rxBleConnection.readCharacteristic(UUID_SERIAL_NUMBER),
                            rxBleConnection.readCharacteristic(UUID_MACHINE_TYPE),
                            rxBleConnection.readCharacteristic(UUID_CHARACTERISTIC),
                            ProgramModel::new))
            .observeOn(AndroidSchedulers.mainThread())
            .take(1)
            .subscribe(programModel -> {
                programModel.trimSerial();
                onReadSuccess.call(programModel);
            }, BleUtil::logError);
}
</code>```

So theoretically once a program model is comes through oNext of the subscribe, the subscription will be unsubscribed from. For some reason the operation gets stuck and onNext and onError are never called. If I remove the take(1) this works fine but I don't want to have to deal with holding onto a reference to the subscription and unsubscribing manually. Does anyone know what I'm doing wrong or why onNext is not being called?

答: I needed to call take(1) before the flatMap as well as after. This post sort of explains it Read multiple characteristics from an Android device using library RxAndroidBle

Body:
I'm trying to get a subscription to automatically unsubscribe when it emits an item. The base observable is created like this.

public static Observable<RxBleConnection> setupConnection(RxBleDevice device, PublishSubject<Void> disconnectTrigger) {
    return device
            .establishConnection(false)
            .takeUntil(disconnectTrigger)
            .retry(3)
            .retryWhen(o -> o.delay(RETRY_DELAY, TimeUnit.MILLISECONDS))
            .compose(new ConnectionSharingAdapter());
}

Then I try to combine three read operations into a ProgramModel.

private void readCharacteristics(Action1<ProgramModel> onReadSuccess) {
    mConnectionObservable
            .flatMap(rxBleConnection ->
                    // combines the following three observables into a single observable that is
                    // emitted in onNext of the subscribe
                    Observable.combineLatest(
                            rxBleConnection.readCharacteristic(UUID_SERIAL_NUMBER),
                            rxBleConnection.readCharacteristic(UUID_MACHINE_TYPE),
                            rxBleConnection.readCharacteristic(UUID_CHARACTERISTIC),
                            ProgramModel::new))
            .observeOn(AndroidSchedulers.mainThread())
            .take(1)
            .subscribe(programModel -> {
                programModel.trimSerial();
                onReadSuccess.call(programModel);
            }, BleUtil::logError);
}

So theoretically once a program model is comes through oNext of the subscribe, the subscription will be unsubscribed from. For some reason the operation gets stuck and onNext and onError are never called. If I remove the take(1) this works fine but I don't want to have to deal with holding onto a reference to the subscription and unsubscribing manually. Does anyone know what I'm doing wrong or why onNext is not being called?


问:
Saiku Mondrian Schema error - parentheses perhaps?
I'm using Mondrian xml schema for Saiku report (Pentaho 7.0) and when defining roles, Saiku throws errors whenever there are parentheses. (Actually from my different combo of testing it's the conclusion I came up with. No solid evidence.)
XML parser doesn't throw errors but when loading data cubes, Saiku doesn't like it.
For example

```<code>  <Role name="ABC-DEF.GHI(JKL)">
    <SchemaGrant access="none">
      <CubeGrant cube="Some Cube" access="all">
        <DimensionGrant dimension="[Measures]" access="all"/>
        <HierarchyGrant hierarchy="Some Hierarchy (with parentheses)" access="none">
        </HierarchyGrant>
      </CubeGrant>
     </SchemaGrant>
   </Role>
</code>```

Did anyone come across this issue?

答:
The best way to test a Mondrian Schema without having to upload it to the server and with better diagnosis is to download the Mondrian Schema Workbench from SourceForge, and try to load the xml. You do not have to use it to build your schema (xml is good enough), but it will try to interpret the schema and put a red flag on any potential error.

A second way its to edit the pentaho-server/tomcat/webapps/pentaho/WEB-INF/classes/log4j.xml. Find the section starting with  and uncomment the following lines. Then restart your biserver and read the logs with tail -f tomcat/logs/pentaho.log. It will tell you all what happens wrong when the server loads the cubes.

And it may very well be that Saiku does not like parenthesis (it is fading memories for me). Try

```<code><HierarchyGrant hierarchy="Some Hierarchy (with parentheses)" access="none">.
</code>```

If your hypothesis about parenthesis is exact then think about others and answer your own question or comment my answer.

Body:
I'm using Mondrian xml schema for Saiku report (Pentaho 7.0) and when defining roles, Saiku throws errors whenever there are parentheses. (Actually from my different combo of testing it's the conclusion I came up with. No solid evidence.)
XML parser doesn't throw errors but when loading data cubes, Saiku doesn't like it.
For example

  <Role name="ABC-DEF.GHI(JKL)">
    <SchemaGrant access="none">
      <CubeGrant cube="Some Cube" access="all">
        <DimensionGrant dimension="[Measures]" access="all"/>
        <HierarchyGrant hierarchy="Some Hierarchy (with parentheses)" access="none">
        </HierarchyGrant>
      </CubeGrant>
     </SchemaGrant>
   </Role>

Did anyone come across this issue?

Body:
The best way to test a Mondrian Schema without having to upload it to the server and with better diagnosis is to download the Mondrian Schema Workbench from SourceForge, and try to load the xml. You do not have to use it to build your schema (xml is good enough), but it will try to interpret the schema and put a red flag on any potential error.

A second way its to edit the pentaho-server/tomcat/webapps/pentaho/WEB-INF/classes/log4j.xml. Find the section starting with <!-- Special Log File specifically for Mondrian --> and uncomment the following lines. Then restart your biserver and read the logs with tail -f tomcat/logs/pentaho.log. It will tell you all what happens wrong when the server loads the cubes.

And it may very well be that Saiku does not like parenthesis (it is fading memories for me). Try

<HierarchyGrant hierarchy="Some Hierarchy &#40;with parentheses&#41;" access="none">.

If your hypothesis about parenthesis is exact then think about others and answer your own question or comment my answer.


问:
How to run a shell command at analysis time in bazel?
I'm trying to bake the mercurial version into my Bazel file, so that I can get something like this:

```<code># These I set manually, since they're "semantic"
MAJOR_VERSION = 2
MINOR_VERSION = 3
BUGFIX_VERSION = 1

# This should be the result of `hg id -n`
BUILD_VERSION = ?

apple_bundle_version(
    name = "my_version",
    build_version = "{}.{}.{}.{}".format(MAJOR_VERSION, MINOR_VERSION, BUGFIX_VERSION, BUILD_VERSION),
    short_version_string = "{}.{}.{}".format(MAJOR_VERSION, MINOR_VERSION, BUGFIX_VERSION),
)
</code>```

This obviously is not hermetic, so I know it violates some of Bazel's assumptions, so I'm open to other options.

Here's some possible options:

Actually run hg id -n during Bazel analysis, which I don't know how to do.

Pass the build version in via command line, e.g., --define=build_version=$(hg id -n). Unfortunately, this requires a separate command to wrap bazel build.

Manually set the BUILD_VERSION. Obviously, this would be annoying.

Is there a way to do #1? What are my other options?

答:
By default, the apple_bundle_version rule uses regular expressions to parse whatever you pass in to --embed_label on the Bazel command line.

So, the simplest way to achieve this would be first writing something like this:

bazel build //your:target --embed_label="$(hd id -n)"

That will set BUILD_EMBED_LABEL to the your Mercurial version in your workspace info file, for example:

```<code>BUILD_EMBED_LABEL 156
BUILD_HOST ...
BUILD_USER ...
</code>```

Then you have to tell apple_bundle_version what your version numbers should look like:

```<code>VERSION_PREFIX = "{}.{}.{}".format(MAJOR, MINOR, BUGFIX)

apple_bundle_version(
    name = "my_version",
    # This is where you define that BUILD_EMBED_LABEL will look like
    # this, where each thing inside {} is one of the capture groups
    # below. So in this case, it will be a number.
    build_label_pattern = "{build}",
    capture_groups = {
        "build": "\d+",
    },
    # CFBundleVersion should be the VERSION_PREFIX above, plus a dot
    # followed by {build} extracted from BUILD_EMBED_LABEL.
    build_version = VERSION_PREFIX + ".{build}",
    # CFBundleShortVersionString will just be the VERSION_PREFIX.
    short_version_string = VERSION_PREFIX,
)
</code>```

Something like that should do the trick.

Getting more advanced

If you don't want to manually pass the result of hg id -n each time you build, the apple_bundle_version rule is extensible so you can make it happen automatically. The only requirement of the version attribute on ios_application and related rules is that it point to a target that returns an AppleBundleVersionInfo provider—it doesn't have to be apple_bundle_version.

That provider propagates a small JSON file containing your bundle version and short bundle version string, so you could write your own rule that invokes hg id -n as a custom action, writes it out to a JSON formatted file with the right keys, and then use that target as your version attribute on your application instead.

Body:
I'm trying to bake the mercurial version into my Bazel file, so that I can get something like this:

# These I set manually, since they're "semantic"
MAJOR_VERSION = 2
MINOR_VERSION = 3
BUGFIX_VERSION = 1

# This should be the result of `hg id -n`
BUILD_VERSION = ?

apple_bundle_version(
    name = "my_version",
    build_version = "{}.{}.{}.{}".format(MAJOR_VERSION, MINOR_VERSION, BUGFIX_VERSION, BUILD_VERSION),
    short_version_string = "{}.{}.{}".format(MAJOR_VERSION, MINOR_VERSION, BUGFIX_VERSION),
)

This obviously is not hermetic, so I know it violates some of Bazel's assumptions, so I'm open to other options.

Here's some possible options:

Actually run hg id -n during Bazel analysis, which I don't know how to do.

Pass the build version in via command line, e.g., --define=build_version=$(hg id -n). Unfortunately, this requires a separate command to wrap bazel build.

Manually set the BUILD_VERSION. Obviously, this would be annoying.

Is there a way to do #1? What are my other options?

Body:
By default, the apple_bundle_version rule uses regular expressions to parse whatever you pass in to --embed_label on the Bazel command line.

So, the simplest way to achieve this would be first writing something like this:

bazel build //your:target --embed_label="$(hd id -n)"

That will set BUILD_EMBED_LABEL to the your Mercurial version in your workspace info file, for example:

BUILD_EMBED_LABEL 156
BUILD_HOST ...
BUILD_USER ...

Then you have to tell apple_bundle_version what your version numbers should look like:

VERSION_PREFIX = "{}.{}.{}".format(MAJOR, MINOR, BUGFIX)

apple_bundle_version(
    name = "my_version",
    # This is where you define that BUILD_EMBED_LABEL will look like
    # this, where each thing inside {} is one of the capture groups
    # below. So in this case, it will be a number.
    build_label_pattern = "{build}",
    capture_groups = {
        "build": "\d+",
    },
    # CFBundleVersion should be the VERSION_PREFIX above, plus a dot
    # followed by {build} extracted from BUILD_EMBED_LABEL.
    build_version = VERSION_PREFIX + ".{build}",
    # CFBundleShortVersionString will just be the VERSION_PREFIX.
    short_version_string = VERSION_PREFIX,
)

Something like that should do the trick.

Getting more advanced

If you don't want to manually pass the result of hg id -n each time you build, the apple_bundle_version rule is extensible so you can make it happen automatically. The only requirement of the version attribute on ios_application and related rules is that it point to a target that returns an AppleBundleVersionInfo provider—it doesn't have to be apple_bundle_version.

That provider propagates a small JSON file containing your bundle version and short bundle version string, so you could write your own rule that invokes hg id -n as a custom action, writes it out to a JSON formatted file with the right keys, and then use that target as your version attribute on your application instead.


问:
Difference between Server-side and Backend
What is the difference between Server-side and Backend?

I am new to all of this coding and I want to create a website. I'm going to use Node.js for the backend, but what is server-side? Can someone explain in simple words to me how this works? Also, what is a backend anyway?

答:
The back-end, or the "server-side", is basically how the site works, updates and changes. This refers to everything the user can't see in the browser, like databases and servers.

Node is your "server-side" in this case.

The front-end is everything involved with what the user sees, including design.

You can read more here


问:
Create copy of class passed as argument
I am creating a project in VBA to automate handling of asynchronous quasi-multithreading (mouthful, sorry). This revolves around creating and running multiple copies of a class which Implements a certain interface, and raises some known events when the async task is complete. The interfacing is similar to this example

My program calls the class to execute its code, and listens to the events raised, that's all working fine. Now my final task is to take any given class which Implements the appropriate interface, and make multiple copies to set running in parallel.

How do I make copies of a class which is passed to a routine?

How can I take a class reference and make several New versions?

Or in code, each one of my thread classes (the classes which handle the async class which is passed) will have a Worker property to save their task.

```<code>Private workerObject As IWorker
Public Property Set Worker(workObj As IWorker) 'pass unknown class with IWorker interface
    'What goes here?
    Set workerObject = workObj
    'This won't work as then every thread points to the same worker
    'I want something to create a New one, like
    Set workerObject = New ClassOf(workObj)
    'But of course that doesn't work
End Property
</code>```

答:
You would need to inspect the possible types and act accordingly:

```<code>Dim workerObject As IWorker

If TypeOf workObj Is ImplementingClass1 Then
    Set workerObject = New ImplementingClass1

ElseIf TypeOf workObj Is ImplementingClass2 Then
    Set workerObject = New ImplementingClass2

End If
</code>```

Alternatively you could add a factory method to the interface:

```<code>Public Function CreateNew() As IWorker: End Function
</code>```

Implement it in the classes:

```<code>Public Function IWorker_CreateNew() As IWorker
    Set IWorker_CreateNew = New ImplementingClass1
End Function
</code>```

And then:

```<code>Set workerObject = workObj.IWorker_CreateNew()
</code>```

Title: Create copy of class passed as argument

Body:
I am creating a project in VBA to automate handling of asynchronous quasi-multithreading (mouthful, sorry). This revolves around creating and running multiple copies of a class which Implements a certain interface, and raises some known events when the async task is complete. The interfacing is similar to this example

My program calls the class to execute its code, and listens to the events raised, that's all working fine. Now my final task is to take any given class which Implements the appropriate interface, and make multiple copies to set running in parallel.

How do I make copies of a class which is passed to a routine?

How can I take a class reference and make several New versions?

Or in code, each one of my thread classes (the classes which handle the async class which is passed) will have a Worker property to save their task.

Private workerObject As IWorker
Public Property Set Worker(workObj As IWorker) 'pass unknown class with IWorker interface
    'What goes here?
    Set workerObject = workObj
    'This won't work as then every thread points to the same worker
    'I want something to create a New one, like
    Set workerObject = New ClassOf(workObj)
    'But of course that doesn't work
End Property

Body:
You would need to inspect the possible types and act accordingly:

Dim workerObject As IWorker

If TypeOf workObj Is ImplementingClass1 Then
    Set workerObject = New ImplementingClass1

ElseIf TypeOf workObj Is ImplementingClass2 Then
    Set workerObject = New ImplementingClass2

End If

Alternatively you could add a factory method to the interface:

Public Function CreateNew() As IWorker: End Function

Implement it in the classes:

Public Function IWorker_CreateNew() As IWorker
    Set IWorker_CreateNew = New ImplementingClass1
End Function

And then:

Set workerObject = workObj.IWorker_CreateNew()


答:
It only asks for one package because you initialize intArray as an array containing exactly one element.  Instead of pointlessly initializing it in its declaration, before you even know how large it needs to be, create and assign the needed array after you input its length. At your option, you can move the whole declaration there:

```<code>    // ...
    size = scan.nextInt();
    int[] intArray = new int[size];
</code>```

Inasmuch as that's the case, I'm inclined to doubt your claim that you had the sorting part working -- you don't have a suitable place to store the weights that are entered.  Perhaps you cut that part out of the code you presented.  Indeed, if your program ever had any semblance of sorting then you must have performed quite a hack job on it.

Title: How to fix this loop for sorting packages by weight

Body:
I need to create a program that asks the customer how many packages they have (after the input it creates an array of that size) which then ask the customer to enter the weights of them. It then has to sort the packages into small, medium, or large and then prints how many of each size package there is.

public static void main(String[] args)
{
    Scanner scan = new Scanner(System.in);
    int small = 0;
    int medium = 0;
    int large = 0;
    int size = 0;
    int[] intArray = {size};

    System.out.printf("Please enter the number of weights to enter: ");
    size = scan.nextInt();

    for (double i = 0; i < intArray.length; i++){
        if (i < size)
            System.out.print("Please Enter weight1: ");
            double weights = scan.nextInt();

    System.out.println("\nPackage Weights");
        System.out.print(weights);

        if (weights <= 5)
            small = 1 + small;
        if (weights <= 10 && weights >= 6)
            medium = 1 + medium;
        if (weights >= 11)
            large = 1 + large;

            System.out.println("\n\nSmall: " + small);
            System.out.println("Medium: " +  medium);
            System.out.println("Large:" + large);

    }
}

}

I got the sorting to work, but I can only get it to ask for one package, which means my array and loop aren't working. Just now learning arrays / loops so i'm kinda stuck on this.

Body:
It only asks for one package because you initialize intArray as an array containing exactly one element.  Instead of pointlessly initializing it in its declaration, before you even know how large it needs to be, create and assign the needed array after you input its length. At your option, you can move the whole declaration there:

    // ...
    size = scan.nextInt();
    int[] intArray = new int[size];

Inasmuch as that's the case, I'm inclined to doubt your claim that you had the sorting part working -- you don't have a suitable place to store the weights that are entered.  Perhaps you cut that part out of the code you presented.  Indeed, if your program ever had any semblance of sorting then you must have performed quite a hack job on it.


问:
R error with spatial point data frame when using lapply
I have a list of lists called flat_head.

```<code>dput(flat_head)
structure(list(`0.25_0.05` = list(c(66, 102, 4.84), c(56, 75,
3.63), c(15, 134, 0)), `0.25_0.1` = list(c(147, 27, 0), c(98,
18, 4.84), c(141, 54, 4.84)), `0.5_0.05` = list(c(64, 130, 4.84
), c(61, 97, 4.84), c(58, 16, 4.84))), .Names = c("0.25_0.05",
"0.25_0.1", "0.5_0.05"))
</code>```

I wrote a small function to run through each list and calculate Moran's I from a spatial points data frame. It works for a single list but it throws an error when I use lapply.

```<code>require(spdep)
M_fun <-  function(x){
  x2 <- unlist(x[[1]])
  x3 <- matrix(x2,ncol = 3, byrow=TRUE)
  colnames(x3) <- c("x","y","prey")
  coords1<-as.data.frame(x3[,1:2])
  spdf <- SpatialPointsDataFrame(coords1,as.data.frame(x3[,3]))
  nm <- knn2nb(knearneigh(spdf))
  all.linked <- max(unlist(nbdists(nm, spdf)))
  nb <- dnearneigh(spdf, 0, all.linked)
  colW <- nb2listw(nb, style="W")
  results1<-moran(spdf@data$`x3[, 3]`, colW, length(nb), Szero(colW))
  return(results1)
}
y<- M_fun(flat_head) # works
final<-lapply(flat_head, M_fun) # does not work
</code>```

Any suggestions on what I'm doing wrong?

答:
y<- M_fun(flat_head) # works
final<-lapply(flat_head, M_fun) # does not work

For these two to be equivalent you would have to have y <- M_fun(flat_head[[1]]) or similar since lapply() applies the function to each element of the list.

At the moment my guess is that y<- M_fun(flat_head) is giving you the output of M_fun for just the first list of flat_head. This is because you have x2 <- unlist(x[[1]]) in the first line of the function.

If you change this to x2 <- unlist(x) it should work.

Consider using dput(flat_head) to create a better reproducible example.

Body:
I have a list of lists called flat_head.

dput(flat_head)
structure(list(`0.25_0.05` = list(c(66, 102, 4.84), c(56, 75,
3.63), c(15, 134, 0)), `0.25_0.1` = list(c(147, 27, 0), c(98,
18, 4.84), c(141, 54, 4.84)), `0.5_0.05` = list(c(64, 130, 4.84
), c(61, 97, 4.84), c(58, 16, 4.84))), .Names = c("0.25_0.05",
"0.25_0.1", "0.5_0.05"))

I wrote a small function to run through each list and calculate Moran's I from a spatial points data frame. It works for a single list but it throws an error when I use lapply.

require(spdep)
M_fun <-  function(x){
  x2 <- unlist(x[[1]])
  x3 <- matrix(x2,ncol = 3, byrow=TRUE)
  colnames(x3) <- c("x","y","prey")
  coords1<-as.data.frame(x3[,1:2])
  spdf <- SpatialPointsDataFrame(coords1,as.data.frame(x3[,3]))
  nm <- knn2nb(knearneigh(spdf))
  all.linked <- max(unlist(nbdists(nm, spdf)))
  nb <- dnearneigh(spdf, 0, all.linked)
  colW <- nb2listw(nb, style="W")
  results1<-moran(spdf@data$`x3[, 3]`, colW, length(nb), Szero(colW))
  return(results1)
}
y<- M_fun(flat_head) # works
final<-lapply(flat_head, M_fun) # does not work

Any suggestions on what I'm doing wrong?


问:
How to access Entity class from Sonata Admin's Admin class?
Let me explain: I have an Entity class Item with a method getName() in it, namespace App\Entity. I have an admin class for it in Sonata Admin, namespace App\Admin, and would like to call that method from within, how to do so?

```<code>//Symfony2 Entity
...
class Item
{
    public function getName(){
         return $this->name;
    }
}

...
//Sonata Admin class
class ItemAdmin extends Admin
{
  ...
  protected function configureListFields(ListMapper $listMapper){
     //how to access Item class' getName() method from here?
  }
}
</code>```

EDIT: This works inside configureListFields(), but what about without find() and if with find() only, then how to automatically get 'id'?

```<code> $item=$this->getConfigurationPool()->getContainer()->get('Doctrine')->getRepository('AppBundle:Item')->find('15');
 echo $item->getName();
</code>```

答:
Simple and easy</p>

```<code>$container = $this->getConfigurationPool()->getContainer();
$em = $container->get('doctrine.orm.entity_manager');
</code>```

Body:
Let me explain: I have an Entity class Item with a method getName() in it, namespace App\Entity. I have an admin class for it in Sonata Admin, namespace App\Admin, and would like to call that method from within, how to do so?

//Symfony2 Entity
...
class Item
{
    public function getName(){
         return $this->name;
    }
}

...
//Sonata Admin class
class ItemAdmin extends Admin
{
  ...
  protected function configureListFields(ListMapper $listMapper){
     //how to access Item class' getName() method from here?
  }
}

EDIT: This works inside configureListFields(), but what about without find() and if with find() only, then how to automatically get 'id'?

 $item=$this->getConfigurationPool()->getContainer()->get('Doctrine')->getRepository('AppBundle:Item')->find('15');
 echo $item->getName();

Body:
Simple and easy

$container = $this->getConfigurationPool()->getContainer();
$em = $container->get('doctrine.orm.entity_manager');


问:
Is it possible to cache a dynamic php file with service worker?
I am trying to cache the html from a dynamic php-file when logged in (with session-cookie) but the html-file is fetched from the server without the credentials from the session-cookie. (I do not specify a filename in the URL only the path)

```<code>let cacheName = 'q2';

    let files = [
     '/q/',
     '/q/sw.js',
     '/q/js/main.js',
     '/q/js/init.js',
     '/q/js/lib.js',
     '/q/css/css.css',
     '/q/images/b.jpg',
     '/q/apps/BOK/js/main.js'
    ];

    self.addEventListener('install', (event) => {
        event.waitUntil(
            caches.open(cacheName)
            .then((cache) => {
                return cache.addAll(files)
                .then(() => {
                    console.info('All files are cached');
                    return self.skipWaiting();
                })
                .catch((error) =>  {
                    console.error('Failed to cache', error);
                });
            })
        );
    });
</code>```

(I have omitted the self.addEventListener("fetch", function(event) )

When I look at the text/html file from '/q/ the service worker has fetched it from the server without the php session cookie PHPSESSID and the contents is therefore wrong.

(Otherwise it works perfect offline)

Is there a solution to this?

答:
This behavior is explained in the Fetch API Specification.

HTTP cookies (and a few other things) are referred to as "credentials".

Whether or not credentials are including in an outgoing HTTP request is determined by the value of the credentials property of the Request object. By default, credentials is set to 'omit', which leads to the behavior you're seeing. If you want credentials like HTTP cookies included, you need to use Request objects whose credentials properties are set to 'include'.

To do this, instead of passing in an array of strings to cache.addAll(), you should pass in an array of Request objects with the proper credentials mode explicitly set. Here's how your code would change:

```<code>const requestsWithCredentials = [
  '/q/',
  '/q/sw.js',
  '/q/js/main.js',
  '/q/js/init.js',
  '/q/js/lib.js',
  '/q/css/css.css',
  '/q/images/b.jpg',
  '/q/apps/BOK/js/main.js'
].map(url => new Request(url, {credentials: 'include'}));

// Later...
cache.addAll(requestsWithCredentials);
</code>```

Body:
I am trying to cache the html from a dynamic php-file when logged in (with session-cookie) but the html-file is fetched from the server without the credentials from the session-cookie. (I do not specify a filename in the URL only the path)

let cacheName = 'q2';

    let files = [
     '/q/',
     '/q/sw.js',
     '/q/js/main.js',
     '/q/js/init.js',
     '/q/js/lib.js',
     '/q/css/css.css',
     '/q/images/b.jpg',
     '/q/apps/BOK/js/main.js'
    ];

    self.addEventListener('install', (event) => {
        event.waitUntil(
            caches.open(cacheName)
            .then((cache) => {
                return cache.addAll(files)
                .then(() => {
                    console.info('All files are cached');
                    return self.skipWaiting();
                })
                .catch((error) =>  {
                    console.error('Failed to cache', error);
                });
            })
        );
    });

(I have omitted the self.addEventListener("fetch", function(event) )

When I look at the text/html file from '/q/ the service worker has fetched it from the server without the php session cookie PHPSESSID and the contents is therefore wrong.

(Otherwise it works perfect offline)

Is there a solution to this?

Body:
This behavior is explained in the Fetch API Specification.

HTTP cookies (and a few other things) are referred to as "credentials".

Whether or not credentials are including in an outgoing HTTP request is determined by the value of the credentials property of the Request object. By default, credentials is set to 'omit', which leads to the behavior you're seeing. If you want credentials like HTTP cookies included, you need to use Request objects whose credentials properties are set to 'include'.

To do this, instead of passing in an array of strings to cache.addAll(), you should pass in an array of Request objects with the proper credentials mode explicitly set. Here's how your code would change:

const requestsWithCredentials = [
  '/q/',
  '/q/sw.js',
  '/q/js/main.js',
  '/q/js/init.js',
  '/q/js/lib.js',
  '/q/css/css.css',
  '/q/images/b.jpg',
  '/q/apps/BOK/js/main.js'
].map(url => new Request(url, {credentials: 'include'}));

// Later...
cache.addAll(requestsWithCredentials);


答:
Server-side and Back-end are identical statements. They both mean that the code is run on you server as opposed to the clients machine, often for dealing with databases. Where as Client-side and Front-end both mean the code is executed on the users computer, usually for UI and design.

https://en.wikipedia.org/wiki/Server-side

Title: Difference between Server-side and Backend

Body:
What is the difference between Server-side and Backend?

I am new to all of this coding and I want to create a website. I'm going to use Node.js for the backend, but what is server-side? Can someone explain in simple words to me how this works? Also, what is a backend anyway?


问:
How to join lines based on between only?
I am investigating the causality of two different entries in two DB tables with no common ID that I could link by.

The only thing I have is unix timestamp in one, and and a date time column in the other. I am pretty sure a certain operation triggers another one, but I need to double check.

So I tried something like this:

SELECT * FROM requests
RIGHT JOIN log_service on (log_service.date is BETWEEN FROM_UNIXTIME(1512312363) and FROM_UNIXTIME(1512312363+2))

For example I have row in requests table with timestamp_send as 1512312363, and I have two matching rows in log_service table with a date value that is like: 2017-12-03 16:46:02
2017-12-03 16:46:03
(Its GMT+2)

Therefore, I want to right join the log_service table, associating it with the request I am looking at.

The query attempt above does not work.
It returns:

ELECT * FROM requests
RIGHT JOIN log_service on (log_service.date is BETWEEN FROM_UNIXTIME(1512312363) and FROM_UNIXTIME(1512312363+2))
1064 - 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 'BETWEEN FROM_UNIXTIME(1512312363) and FROM_UNIXTIME(1512312363+2))' at line 2
Time: 0.189s

Obviously the hardcoded number in the finished query would be the requests.timestamp_send column from the left table.

Any suggestions how to do this?

答:
As I noted in my comment to the question,  first, remove the spurious IS keyword before BETWEEN.  (The IS keyword is used for comparing boolean expressions, it's not a part of the BETWEEN comparison operator.)

For datetime range comparisons, we typically use a pattern of two comparisons, with only one side including the equality.

```<code>       foo >= start  AND  foo < end
</code>```

There are some good several good write-ups about the reasons for this, and the unintentional errors that are introduced with BETWEEN. But this may not fit your paticular use case, where you really do want equality on both sides of the comparison. I would still recommend the pattern of two comparisons, even if it means we have to repeat an expression.

```<code>       foo >= start  AND  foo <= end
</code>```

I also recommend ditching the * in the SELECT list, and specifically list the expressions the query is supposed to return. This gives the future reader the names of the columns, the number of columns, and more of an indication which columns are actually of interest.

Also, it seems like we are wanting to find the log_service rows that are associated with "the request I am looking at". That suggests that there may be some criteria that identify the row(s) from request we are interested in.

It also suggests we want to return the row from request, along with any matching rows from log_service... and that suggests the outer join would be the other way around, a LEFT join rather than a RIGHT join.

The next issue is identifying the actual datatypes of the columns involved in the "date" and "unix timestamp" comparison. Without that information, we're kind of just guessing...  timestamp_send column in request is INTEGER type and contains unix-style number of seconds since the beginning of the epoch, and the date column in log_service is DATETIME.

Based on the specification provided, we would tend to write a query like this:

```<code>SELECT rq.timestamp_send                AS rq_timestamp_send
     , FROM_UNIXTIME(rq.timestamp_send) AS rq_datetime_send
     , ls.date
     , ls.foo
     , ...
  FROM requests rq
  LEFT
  JOIN log_service ls
    ON ls.date >= FROM_UNIXTIME( rq.timestamp_send )
   AND ls.date  < FROM_UNIXTIME( rq.timestamp_send ) + INTERVAL 3 SECOND
 WHERE rq.somecol = 'the request i am looking at'
</code>```

Body:
As I noted in my comment to the question,  first, remove the spurious IS keyword before BETWEEN.  (The IS keyword is used for comparing boolean expressions, it's not a part of the BETWEEN comparison operator.)

For datetime range comparisons, we typically use a pattern of two comparisons, with only one side including the equality.

       foo >= start  AND  foo < end

There are some good several good write-ups about the reasons for this, and the unintentional errors that are introduced with BETWEEN. But this may not fit your paticular use case, where you really do want equality on both sides of the comparison. I would still recommend the pattern of two comparisons, even if it means we have to repeat an expression.

       foo >= start  AND  foo <= end

I also recommend ditching the * in the SELECT list, and specifically list the expressions the query is supposed to return. This gives the future reader the names of the columns, the number of columns, and more of an indication which columns are actually of interest.

Also, it seems like we are wanting to find the log_service rows that are associated with "the request I am looking at". That suggests that there may be some criteria that identify the row(s) from request we are interested in.

It also suggests we want to return the row from request, along with any matching rows from log_service... and that suggests the outer join would be the other way around, a LEFT join rather than a RIGHT join.

The next issue is identifying the actual datatypes of the columns involved in the "date" and "unix timestamp" comparison. Without that information, we're kind of just guessing...  timestamp_send column in request is INTEGER type and contains unix-style number of seconds since the beginning of the epoch, and the date column in log_service is DATETIME.

Based on the specification provided, we would tend to write a query like this:

SELECT rq.timestamp_send                AS rq_timestamp_send
     , FROM_UNIXTIME(rq.timestamp_send) AS rq_datetime_send
     , ls.date
     , ls.foo
     , ...
  FROM requests rq
  LEFT
  JOIN log_service ls
    ON ls.date >= FROM_UNIXTIME( rq.timestamp_send )
   AND ls.date  < FROM_UNIXTIME( rq.timestamp_send ) + INTERVAL 3 SECOND
 WHERE rq.somecol = 'the request i am looking at'


问:
Is it possible to address one specific form using MockMvc

Hello there,

I wanted to aks if it's possible to address one specific form in a html template using MockMvc. I have got a template which has 3 forms, and I am not able to address one of them.

This is my test:

```<code>@Test
public void CreateNewIllMessageTest() throws Exception {

    initializeDummyTourWithDummyGuide();

    User user = userRepository.findUserByName("dummy");
    String moreInf = "moreInformation";

    mvc.perform(get("/tourmanagement").with(user(user.getUsername()).roles("EMPLOYEE"))).
            andExpect(status().isOk()).
            andExpect(view().name("tourmanagement")).
            andExpect(model().attributeExists("illnessform")).
            andExpect(model().attribute("illnessform", hasProperty("customer", is(nullValue())))).
            andExpect(model().attribute("illnessform", hasProperty("moreInf", isEmptyOrNullString())));
    mvc.perform(post("/tourmanagement").with(user(user.getUsername()).roles("EMPLOYEE")).
            param("customer", user.getAccount().getId().toString()).
            param("moreInf", moreInf)
            ).
            andExpect(status().is3xxRedirection());
}
</code>```

This is the template:

```<code><form action="#" th:object="${illnessform}" method="post" name="illnessform"
          th:action="@{/tourmanagement/ill(tour=${tourid}, start=${startDate}, end=${endDate}, tourname=${tour.name})}">
        <div id="ill" style="display: none" class="form-group">

            <label for="illselect" th:text="#{tourmanagement.whoisill}">Which Tourist Is Ill?</label>
            <select class="form-control" id="illselect" name="customer">

                <option th:each="customer : ${customerList}" th:value="${customer.account.id}">
                    <p th:text="${customer.account.id}"></p>
                </option>

            </select>

            <label for="illInf" th:text="#{tourmanagement.moreinfs}">More Information:</label>
            <input id="illInf" type="text" class="form-control" required name="moreInf" th:field="*{moreInf}">

            <button class="btn btn-info" name="submit" type="submit" th:text="#{contact.submit}">Submit</button>
        </div>
    </form>

    <form action="#" th:object="${insuranceform}" method="post"
          th:action="@{/tourmanagement/ins(tour=${tourid}, start=${startDate}, end=${endDate}, tourname=${tour.name})}">
        <div id="ins" style="display: none" class="form-group">

            <label for="inssellect" th:text="#{tourmanagement.whatkindofins}">What Kind Of Insurance Case?</label>
            <select class="form-control" id="inssellect" name="caseType" th:field="*{caseType}">
                <option th:text="#{tourmanagement.theft}" th:value="#{tourmanagement.theft}">Theft</option>
                <option th:text="#{tourmanagement.accident}" th:value="#{tourmanagement.accident}">Accident</option>
            </select>

            <label for="inssellecttourist" th:text="#{tourmanagement.whichtourist}">Which Tourist Did It Happen
                To?</label>
            <select class="form-control" id="inssellecttourist" name="customer" th:field="*{customer}">

                <option th:each="customer : ${customerList}" th:value="${customer.account.id}">
                    <p th:text="${customer.account.id}"></p>
                </option>

            </select>

            <label for="insInf" th:text="#{tourmanagement.moreinfs}">More Information:</label>
            <input id="insInf" type="text" class="form-control" required name="moreInf" th:field="*{moreInf}">

            <button class="btn btn-info" type="submit" th:text="#{contact.submit}">Submit</button>
        </div>
    </form>
</code>```

As you can see, I have more than one form and I want to test the first. The error I get is:

```<code>java.lang.AssertionError: Range for response status value 405
</code>```

Expected :REDIRECTION
Actual   :CLIENT_ERROR

```<code>at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:54)
at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:81)
at org.springframework.test.web.servlet.result.StatusResultMatchers$5.match(StatusResultMatchers.java:107)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:171)
at kickstart.Message.MessageIntegrationTest.CreateNewIllMessageTest(MessageIntegrationTest.java:145)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
</code>```

I would really appreciate any help or alternative ways to test these forms.

Greetings, Alex

答: The server (in this case MockMVC) does not know anything about the forms. The forms send different requests that must have a characteristic which is used by your server to distinguish them. These characteristics have to be send with the requests in your test.</p>

Body:
Hello there,

I wanted to aks if it's possible to address one specific form in a html template using MockMvc. I have got a template which has 3 forms, and I am not able to address one of them.

This is my test:

@Test
public void CreateNewIllMessageTest() throws Exception {

    initializeDummyTourWithDummyGuide();

    User user = userRepository.findUserByName("dummy");
    String moreInf = "moreInformation";

    mvc.perform(get("/tourmanagement").with(user(user.getUsername()).roles("EMPLOYEE"))).
            andExpect(status().isOk()).
            andExpect(view().name("tourmanagement")).
            andExpect(model().attributeExists("illnessform")).
            andExpect(model().attribute("illnessform", hasProperty("customer", is(nullValue())))).
            andExpect(model().attribute("illnessform", hasProperty("moreInf", isEmptyOrNullString())));
    mvc.perform(post("/tourmanagement").with(user(user.getUsername()).roles("EMPLOYEE")).
            param("customer", user.getAccount().getId().toString()).
            param("moreInf", moreInf)
            ).
            andExpect(status().is3xxRedirection());
}

This is the template:

<form action="#" th:object="${illnessform}" method="post" name="illnessform"
          th:action="@{/tourmanagement/ill(tour=${tourid}, start=${startDate}, end=${endDate}, tourname=${tour.name})}">

            Which Tourist Is Ill?
            <select class="form-control" id="illselect" name="customer">

                <option th:each="customer : ${customerList}" th:value="${customer.account.id}">

                </option>

            </select>

            More Information:
            <input id="illInf" type="text" class="form-control" required name="moreInf" th:field="*{moreInf}">

            <button class="btn btn-info" name="submit" type="submit" th:text="#{contact.submit}">Submit</button>

    </form>

    <form action="#" th:object="${insuranceform}" method="post"
          th:action="@{/tourmanagement/ins(tour=${tourid}, start=${startDate}, end=${endDate}, tourname=${tour.name})}">

            What Kind Of Insurance Case?
            <select class="form-control" id="inssellect" name="caseType" th:field="*{caseType}">
                <option th:text="#{tourmanagement.theft}" th:value="#{tourmanagement.theft}">Theft</option>
                <option th:text="#{tourmanagement.accident}" th:value="#{tourmanagement.accident}">Accident</option>
            </select>

            Which Tourist Did It Happen
                To?
            <select class="form-control" id="inssellecttourist" name="customer" th:field="*{customer}">

                <option th:each="customer : ${customerList}" th:value="${customer.account.id}">

                </option>

            </select>

            More Information:
            <input id="insInf" type="text" class="form-control" required name="moreInf" th:field="*{moreInf}">

            <button class="btn btn-info" type="submit" th:text="#{contact.submit}">Submit</button>

    </form>

As you can see, I have more than one form and I want to test the first. The error I get is:

java.lang.AssertionError: Range for response status value 405

Expected :REDIRECTION
Actual   :CLIENT_ERROR

at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:54)
at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:81)
at org.springframework.test.web.servlet.result.StatusResultMatchers$5.match(StatusResultMatchers.java:107)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:171)
at kickstart.Message.MessageIntegrationTest.CreateNewIllMessageTest(MessageIntegrationTest.java:145)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

I would really appreciate any help or alternative ways to test these forms.

Greetings, Alex