问:
"libParseLib.a does not contain bitcode" error
I never had any problems when using CocoaPods up to this point (I used it a few times to integrate Parse into my iOS app). But this time I am puzzled by the message below.

When I previously used CocoaPods the project was containing only one target, this time it contains several. There may be something to be careful about, in such a case, that I don't know of. Anyway, here is the message I am getting:

```<code>        ld: '..../MyApp/Pods/Parse/libParseLib.a(PFSQLiteDatabase.o)' does not contain bitcode.
    You must rebuild it with bitcode enabled (Xcode setting ENABLE_BITCODE),
    obtain an updated library from the vendor, or disable bitcode for this target.
for architecture arm64
        clang: error: linker command failed with exit code 1 (use -v to see invocation)
</code>```

I have tried to change the Enable Bitcode flag at various level, but whatever I do I keep getting the same error.

Has anyone had this kind of issue? Or knows what to do about it?

Note that this link is related to my question but it unfortunately does not provide me a useful answer.

Update: I add hereafter the full text I get in the logs under Xcode, in case it may help someone to see where the problem is:

```<code>Ld /Users/georgewhashington/Library/Developer/Xcode/DerivedData/MyApp-dsxizsrrgeilklkhdylflpsafjrd/Build/Products/Debug-iphoneos/Parse-framework/Parse.framework/Parse normal arm64
    cd /Users/georgewhashington/Documents/iOS/MyApp/Pods
    export IPHONEOS_DEPLOYMENT_TARGET=8.0
    export PATH="/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin:/Applications/Xcode.app/Contents/Developer/usr/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"
    /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang -arch arm64 -dynamiclib -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS10.2.sdk -L/Users/georgewhashington/Library/Developer/Xcode/DerivedData/MyApp-dsxizsrrgeilklkhdylflpsafjrd/Build/Products/Debug-iphoneos/Parse-framework -L/Users/georgewhashington/Documents/iOS/MyApp/Pods/Parse -F/Users/georgewhashington/Library/Developer/Xcode/DerivedData/MyApp-dsxizsrrgeilklkhdylflpsafjrd/Build/Products/Debug-iphoneos/Parse-framework -F/Users/georgewhashington/Library/Developer/Xcode/DerivedData/MyApp-dsxizsrrgeilklkhdylflpsafjrd/Build/Products/Debug-iphoneos/Bolts-framework -filelist /Users/georgewhashington/Library/Developer/Xcode/DerivedData/MyApp-dsxizsrrgeilklkhdylflpsafjrd/Build/Intermediates/Pods.build/Debug-iphoneos/Parse-framework.build/Objects-normal/arm64/Parse.LinkFileList -install_name @rpath/Parse.framework/Parse -Xlinker -rpath -Xlinker @executable_path/Frameworks -Xlinker -rpath -Xlinker @loader_path/Frameworks -miphoneos-version-min=8.0 -dead_strip -Xlinker -object_path_lto -Xlinker /Users/georgewhashington/Library/Developer/Xcode/DerivedData/MyApp-dsxizsrrgeilklkhdylflpsafjrd/Build/Intermediates/Pods.build/Debug-iphoneos/Parse-framework.build/Objects-normal/arm64/Parse_lto.o -Xlinker -export_dynamic -Xlinker -no_deduplicate -fembed-bitcode-marker -fobjc-arc -fobjc-link-runtime -ObjC -lParseLib -lsqlite3 -lz -framework AudioToolbox -framework CFNetwork -framework CoreGraphics -framework CoreLocation -framework QuartzCore -framework Security -framework StoreKit -framework SystemConfiguration -weak_framework Accounts -weak_framework Social -framework AudioToolbox -framework Bolts -framework CFNetwork -framework CoreGraphics -framework CoreLocation -framework Foundation -framework QuartzCore -framework Security -framework StoreKit -framework SystemConfiguration -single_module -compatibility_version 1 -current_version 1 -Xlinker -dependency_info -Xlinker /Users/georgewhashington/Library/Developer/Xcode/DerivedData/MyApp-dsxizsrrgeilklkhdylflpsafjrd/Build/Intermediates/Pods.build/Debug-iphoneos/Parse-framework.build/Objects-normal/arm64/Parse_dependency_info.dat -o /Users/georgewhashington/Library/Developer/Xcode/DerivedData/MyApp-dsxizsrrgeilklkhdylflpsafjrd/Build/Products/Debug-iphoneos/Parse-framework/Parse.framework/Parse

ld: '..../MyApp/Pods/Parse/libParseLib.a(PFSQLiteDatabase.o)' does not contain bitcode. You must rebuild it with bitcode enabled (Xcode setting ENABLE_BITCODE), obtain an updated library from the vendor, or disable bitcode for this target. for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
</code>```

答:
My solution was to disable bitcode in the project, like this

everything works fine after.

Body:
I never had any problems when using CocoaPods up to this point (I used it a few times to integrate Parse into my iOS app). But this time I am puzzled by the message below.

When I previously used CocoaPods the project was containing only one target, this time it contains several. There may be something to be careful about, in such a case, that I don't know of. Anyway, here is the message I am getting:

        ld: '..../MyApp/Pods/Parse/libParseLib.a(PFSQLiteDatabase.o)' does not contain bitcode.
    You must rebuild it with bitcode enabled (Xcode setting ENABLE_BITCODE),
    obtain an updated library from the vendor, or disable bitcode for this target.
for architecture arm64
        clang: error: linker command failed with exit code 1 (use -v to see invocation)

I have tried to change the Enable Bitcode flag at various level, but whatever I do I keep getting the same error.

Has anyone had this kind of issue? Or knows what to do about it?

Note that this link is related to my question but it unfortunately does not provide me a useful answer.

Update: I add hereafter the full text I get in the logs under Xcode, in case it may help someone to see where the problem is:

Ld /Users/georgewhashington/Library/Developer/Xcode/DerivedData/MyApp-dsxizsrrgeilklkhdylflpsafjrd/Build/Products/Debug-iphoneos/Parse-framework/Parse.framework/Parse normal arm64
    cd /Users/georgewhashington/Documents/iOS/MyApp/Pods
    export IPHONEOS_DEPLOYMENT_TARGET=8.0
    export PATH="/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin:/Applications/Xcode.app/Contents/Developer/usr/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"
    /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang -arch arm64 -dynamiclib -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS10.2.sdk -L/Users/georgewhashington/Library/Developer/Xcode/DerivedData/MyApp-dsxizsrrgeilklkhdylflpsafjrd/Build/Products/Debug-iphoneos/Parse-framework -L/Users/georgewhashington/Documents/iOS/MyApp/Pods/Parse -F/Users/georgewhashington/Library/Developer/Xcode/DerivedData/MyApp-dsxizsrrgeilklkhdylflpsafjrd/Build/Products/Debug-iphoneos/Parse-framework -F/Users/georgewhashington/Library/Developer/Xcode/DerivedData/MyApp-dsxizsrrgeilklkhdylflpsafjrd/Build/Products/Debug-iphoneos/Bolts-framework -filelist /Users/georgewhashington/Library/Developer/Xcode/DerivedData/MyApp-dsxizsrrgeilklkhdylflpsafjrd/Build/Intermediates/Pods.build/Debug-iphoneos/Parse-framework.build/Objects-normal/arm64/Parse.LinkFileList -install_name @rpath/Parse.framework/Parse -Xlinker -rpath -Xlinker @executable_path/Frameworks -Xlinker -rpath -Xlinker @loader_path/Frameworks -miphoneos-version-min=8.0 -dead_strip -Xlinker -object_path_lto -Xlinker /Users/georgewhashington/Library/Developer/Xcode/DerivedData/MyApp-dsxizsrrgeilklkhdylflpsafjrd/Build/Intermediates/Pods.build/Debug-iphoneos/Parse-framework.build/Objects-normal/arm64/Parse_lto.o -Xlinker -export_dynamic -Xlinker -no_deduplicate -fembed-bitcode-marker -fobjc-arc -fobjc-link-runtime -ObjC -lParseLib -lsqlite3 -lz -framework AudioToolbox -framework CFNetwork -framework CoreGraphics -framework CoreLocation -framework QuartzCore -framework Security -framework StoreKit -framework SystemConfiguration -weak_framework Accounts -weak_framework Social -framework AudioToolbox -framework Bolts -framework CFNetwork -framework CoreGraphics -framework CoreLocation -framework Foundation -framework QuartzCore -framework Security -framework StoreKit -framework SystemConfiguration -single_module -compatibility_version 1 -current_version 1 -Xlinker -dependency_info -Xlinker /Users/georgewhashington/Library/Developer/Xcode/DerivedData/MyApp-dsxizsrrgeilklkhdylflpsafjrd/Build/Intermediates/Pods.build/Debug-iphoneos/Parse-framework.build/Objects-normal/arm64/Parse_dependency_info.dat -o /Users/georgewhashington/Library/Developer/Xcode/DerivedData/MyApp-dsxizsrrgeilklkhdylflpsafjrd/Build/Products/Debug-iphoneos/Parse-framework/Parse.framework/Parse

ld: '..../MyApp/Pods/Parse/libParseLib.a(PFSQLiteDatabase.o)' does not contain bitcode. You must rebuild it with bitcode enabled (Xcode setting ENABLE_BITCODE), obtain an updated library from the vendor, or disable bitcode for this target. for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)


来源: stackexchange

问:
C++ conditional statement to test if variable is a string
I have a C++ method findID that uses templates, and I want to be able to run a condition in this method based on the input type. The template parameter U will either be of type int or type string. I want to run a different condition based on the type of ID.

The code I have is follows:

```<code>template <typename S>
template <typename U>
S * findID(U ID){
    for (typename vector<S*>::collectionsIter element = collection.begin() ; element != collection.end(); ++element)
        if((*element)->getID() == ID) return *element;
    return NULL;
}
</code>```

I want my code to do the following:

```<code>template <typename S>
    template <typename U>
    S * findID(U ID){

      ***if ID is an int:
        for (typename vector<S*>::collectionsIter element = collection.begin() ; element != collection.end(); ++element)
            if((*element)->getID() == ID) return *element;

      ***if ID is a string:

         for (typename vector<S*>::collectionsIter element = collection.begin() ; element != collection.end(); ++element)
            if((*element)->getStringID() == ID) return *element;

       ***else

        return NULL;

    }
</code>```

The reason that I want to do this is because I want to be able to compare string variables of ID to the string method of getStringID(), and the int variables of ID to the int method of getID(). In addition I do not want to break these up into separate methods, so I am trying to use templates and these conditions to refactor it into 1 method.

答:
Here's one way to do it using C++17 if constexpr:

```<code>struct Foo {
    int id;
    std::string stringId;

    int getId() const { return id; }
    const std::string& getStringId() const { return stringId; }
};

template <typename Cont, typename T>
auto findId(const Cont& c, const T& id) {
    const auto pred = [&id](const auto& x) {
        if constexpr (std::is_convertible_v<T, std::string>)
            return x.getStringId() == id;
        else if constexpr (std::is_convertible_v<T, int>)
            return x.getId() == id;
        else
            static_assert(false, "Unsupported id type.");
        return false;
    };
    const auto findIt = std::find_if(begin(c), end(c), pred);
    return findIt == end(c) ? nullptr : &(*findIt);
}

int main() {
    using namespace std;
    vector<Foo> foos{{1, "1"}, {2, "2"}, {3, "3"}};
    auto foo2Int = findId(foos, 2);
    auto foo2String = findId(foos, "2"s);
    cout << foo2Int->id << ", " << foo2String->stringId << '\n';
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a C++ method findID that uses templates, and I want to be able to run a condition in this method based on the input type. The template parameter U will either be of type int or type string. I want to run a different condition based on the type of ID.

The code I have is follows:

template <typename S>
template <typename U>
S * findID(U ID){
    for (typename vector<S*>::collectionsIter element = collection.begin() ; element != collection.end(); ++element)
        if((*element)->getID() == ID) return *element;
    return NULL;
}

I want my code to do the following:

template <typename S>
    template <typename U>
    S * findID(U ID){

      ***if ID is an int:
        for (typename vector<S*>::collectionsIter element = collection.begin() ; element != collection.end(); ++element)
            if((*element)->getID() == ID) return *element;

      ***if ID is a string:

         for (typename vector<S*>::collectionsIter element = collection.begin() ; element != collection.end(); ++element)
            if((*element)->getStringID() == ID) return *element;

       ***else

        return NULL;

    }

The reason that I want to do this is because I want to be able to compare string variables of ID to the string method of getStringID(), and the int variables of ID to the int method of getID(). In addition I do not want to break these up into separate methods, so I am trying to use templates and these conditions to refactor it into 1 method.

Body:
Here's one way to do it using C++17 if constexpr:

struct Foo {
    int id;
    std::string stringId;

    int getId() const { return id; }
    const std::string& getStringId() const { return stringId; }
};

template <typename Cont, typename T>
auto findId(const Cont& c, const T& id) {
    const auto pred = [&id](const auto& x) {
        if constexpr (std::is_convertible_v<T, std::string>)
            return x.getStringId() == id;
        else if constexpr (std::is_convertible_v<T, int>)
            return x.getId() == id;
        else
            static_assert(false, "Unsupported id type.");
        return false;
    };
    const auto findIt = std::find_if(begin(c), end(c), pred);
    return findIt == end(c) ? nullptr : &(*findIt);
}

int main() {
    using namespace std;
    vector<Foo> foos{{1, "1"}, {2, "2"}, {3, "3"}};
    auto foo2Int = findId(foos, 2);
    auto foo2String = findId(foos, "2"s);
    cout << foo2Int->id << ", " << foo2String->stringId << '\n';
}


问:
Java split not working consistently
I have the following code below the output.

My issue is that the split function is not working correctly/consistently.
I want to split on each "$".
Reason being is that I want to parse the GGA and RMC data.
Before anyone spends to much time, is this the right way to do this?
My steps:
Read GPS data
Store sentence type (GGA, RMC) in variables that only store the most recent data
Parse those variables and pass to program and then database?

[
$GPGSV,,,,,,,,,*43

$GPRMC,055106.000,A,,N,,W,0.00,61.40,,,,A*4D]

[
$GPVTG,,,,,,T,,M,,,,K,A*3E

$GPGGA,055107.000,,N,,W,,,,M,-33.3,M,,0000*6T

$GPGLL,,N,,W,055107.000,A,A*44]

[

$GPRMC,055107.000,A,,N,,W,0.00,,,,,A*4F

$GPVTG,,,,,,T,,M,0.00,,0.0,,A*3E]

[

$GPGGA,055108.000,3,N,,W,1,09,0.9,,,M,,0000*62]

```<code>import jssc.SerialPort;
import jssc.SerialPortEvent;
import jssc.SerialPortEventListener; import jssc.SerialPortException;
import java.util.Arrays;
//import java.awt.List;
//import java.util.Base64;
//import java.io.BufferedReader;
//import java.io.ByteArrayInputStream;
//import java.io.InputStream;
//import java.io.InputStreamReader;
//import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.io.IOException;
import java.lang.*;
//import static java.util.Arrays.asList;
//import java.util.List;
//import java.util.stream.Collectors;
//import org.apache.commons.lang3.StringUtils;

public class test {
static List<String> datat = new ArrayList<String>();
static SerialPort serialPort;

public static void main(String[] args) {
    serialPort = new SerialPort("COM1");
    try {
        serialPort.openPort();//Open ports
        serialPort.setParams(4800, 8, 1, 0);//Set params
      int mask = SerialPort.MASK_RXCHAR + SerialPort.MASK_CTS + SerialPort.MASK_DSR;//Prepare mask
       serialPort.setEventsMask(mask);//Set mask
       serialPort.addEventListener(new SerialPortReader());//Add SerialPortEventListener

    }
    catch (SerialPortException ex) {
        System.out.println(ex);
    }
}

/*
 * In this class must implement the method serialEvent, through it we learn about
 * events that happened to our port. But we will not report on all events but only
 * those that we put in the mask. In this case the arrival of the data and change the
 * status lines CTS and DSR
 */

static class SerialPortReader implements SerialPortEventListener {

    public void serialEvent(SerialPortEvent event) {
    //   if(event.isRXCHAR()){//If data is available
      //     if(event.getEventValue() < 577){//Check bytes count in the input buffer
                //Read data, if 10 bytes available

                try {
                    String getdata =  serialPort.readString(event.getEventValue()+1);
                String[] parts= getdata.split("$");

                if(!datat.isEmpty()){
                    datat.set(datat.size() - 1, datat.get(datat.size() - 1) + parts[0]);
                }
                //data.set(data.size() - 1, data.get(data.size() - 1) + parts[0]);
                for (int i=1; i<parts.length; i++) {
                    datat.add(parts[i]);
               //     System.out.println(Arrays.toString(parts));
                }

               String[] data2 = datat.toArray(new String[0]);

               for(String s : data2)
               {

                   data2 = s.split("$");

                   List<String> data3 = Arrays.asList(data2);
                 //  int testing = data3.size();
                   System.out.println(data3);

               }

                }
                catch (SerialPortException ex) {
             }

       }
}

}
</code>```

答:
The split function takes a regular expression, not a string, You are using a special character in a regular expresion ($) then you need to scape that character</p>

```<code>String s= "$........$...$....";
String[] data2= s.split("\\$");
</code>```

Title: Java split not working consistently

Body:
I have the following code below the output.

My issue is that the split function is not working correctly/consistently.
I want to split on each "$".
Reason being is that I want to parse the GGA and RMC data.
Before anyone spends to much time, is this the right way to do this?
My steps:
Read GPS data
Store sentence type (GGA, RMC) in variables that only store the most recent data
Parse those variables and pass to program and then database?

[
$GPGSV,,,,,,,,,*43

$GPRMC,055106.000,A,,N,,W,0.00,61.40,,,,A*4D]

[
$GPVTG,,,,,,T,,M,,,,K,A*3E

$GPGGA,055107.000,,N,,W,,,,M,-33.3,M,,0000*6T

$GPGLL,,N,,W,055107.000,A,A*44]

[

$GPRMC,055107.000,A,,N,,W,0.00,,,,,A*4F

$GPVTG,,,,,,T,,M,0.00,,0.0,,A*3E]

[

$GPGGA,055108.000,3,N,,W,1,09,0.9,,,M,,0000*62]

import jssc.SerialPort;
import jssc.SerialPortEvent;
import jssc.SerialPortEventListener; import jssc.SerialPortException;
import java.util.Arrays;
//import java.awt.List;
//import java.util.Base64;
//import java.io.BufferedReader;
//import java.io.ByteArrayInputStream;
//import java.io.InputStream;
//import java.io.InputStreamReader;
//import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.io.IOException;
import java.lang.*;
//import static java.util.Arrays.asList;
//import java.util.List;
//import java.util.stream.Collectors;
//import org.apache.commons.lang3.StringUtils;

public class test {
static List<String> datat = new ArrayList<String>();
static SerialPort serialPort;

public static void main(String[] args) {
    serialPort = new SerialPort("COM1");
    try {
        serialPort.openPort();//Open ports
        serialPort.setParams(4800, 8, 1, 0);//Set params
      int mask = SerialPort.MASK_RXCHAR + SerialPort.MASK_CTS + SerialPort.MASK_DSR;//Prepare mask
       serialPort.setEventsMask(mask);//Set mask
       serialPort.addEventListener(new SerialPortReader());//Add SerialPortEventListener

    }
    catch (SerialPortException ex) {
        System.out.println(ex);
    }
}

/*
 * In this class must implement the method serialEvent, through it we learn about
 * events that happened to our port. But we will not report on all events but only
 * those that we put in the mask. In this case the arrival of the data and change the
 * status lines CTS and DSR
 */

static class SerialPortReader implements SerialPortEventListener {

    public void serialEvent(SerialPortEvent event) {
    //   if(event.isRXCHAR()){//If data is available
      //     if(event.getEventValue() < 577){//Check bytes count in the input buffer
                //Read data, if 10 bytes available

                try {
                    String getdata =  serialPort.readString(event.getEventValue()+1);
                String[] parts= getdata.split("$");

                if(!datat.isEmpty()){
                    datat.set(datat.size() - 1, datat.get(datat.size() - 1) + parts[0]);
                }
                //data.set(data.size() - 1, data.get(data.size() - 1) + parts[0]);
                for (int i=1; i<parts.length; i++) {
                    datat.add(parts[i]);
               //     System.out.println(Arrays.toString(parts));
                }

               String[] data2 = datat.toArray(new String[0]);

               for(String s : data2)
               {

                   data2 = s.split("$");

                   List<String> data3 = Arrays.asList(data2);
                 //  int testing = data3.size();
                   System.out.println(data3);

               }

                }
                catch (SerialPortException ex) {
             }

       }
}

}

Body:
The split function takes a regular expression, not a string, You are using a special character in a regular expresion ($) then you need to scape that character

String s= "$........$...$....";
String[] data2= s.split("\\$");


问:
Generate a “where in” statement using the Criteria API in Hibernate
I put in place the following specification that represents the predicate construction for querying Students based on their age and their ClassRoom's teachers' name (one student can have one or more classroom)

```<code>public class StudentSpecification implements Specification<Student> {

  private final Integer age;

  public StudentSpecification(Integer age){
    this.age = age;
  }

  @Override
  public Predicate toPredicate(Root<Student> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
      List<Predicate> predicates = new ArrayList<>();

      predicates.add(criteriaBuilder.greaterThanOrEqualTo(root.<Integert>get(age), Integer.valueOf(v)));

      SetJoin<Student, ClassRoom> classRooms = root.join(Student_.classRooms);

      predicates.add(criteriaBuilder.equal(classRooms.get(ClassRoom_.teacher), "Marta"));
      predicates.add(criteriaBuilder.equal(classRooms.get(ClassRoom_.teacher), "Fowler"));

      return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
  }
}
</code>```

Here is an example of data :

```<code>Student
_____________________________________________
ID     CLASSROOM_ID     NAME         AGE
2      120              Pascal       22
8      120              Bryan        21

ClassRoom
_____________________________________________
ID     CLASSROOM_ID     TEACHER
1      120              Marta
2      120              McAllister
2      120              Fowler
</code>```

The specification returns nothing.

When I see the generated statement, I understand why it doesn't work :

```<code> where
  classRooms.teacher=?
  and classRooms.teacher=?
</code>```

I was expecting something like :

```<code>where
  students0.classroom_id in (
    select classrooms0.classroom_id where
    classRooms.teacher=?
  )
  and students0.classroom_id in (
    select classrooms0.classroom_id where
    classRooms.teacher=?
  )
</code>```

Question : how can make a query with the Criteria API work in my case ?

答:
If you want an in Clause instead of an equals clause just use it:

```<code>predicates.add(criteriaBuilder.in(classRooms.get(ClassRoom_.teacher), "Marta"));
predicates.add(criteriaBuilder.in(classRooms.get(ClassRoom_.teacher), "Fowler"));
</code>```

See https://docs.oracle.com/javaee/6/api/javax/persistence/criteria/CriteriaBuilder.html#in(javax.persistence.criteria.Expression)

Body:
I put in place the following specification that represents the predicate construction for querying Students based on their age and their ClassRoom's teachers' name (one student can have one or more classroom)

public class StudentSpecification implements Specification<Student> {

  private final Integer age;

  public StudentSpecification(Integer age){
    this.age = age;
  }

  @Override
  public Predicate toPredicate(Root<Student> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
      List<Predicate> predicates = new ArrayList<>();

      predicates.add(criteriaBuilder.greaterThanOrEqualTo(root.<Integert>get(age), Integer.valueOf(v)));

      SetJoin<Student, ClassRoom> classRooms = root.join(Student_.classRooms);

      predicates.add(criteriaBuilder.equal(classRooms.get(ClassRoom_.teacher), "Marta"));
      predicates.add(criteriaBuilder.equal(classRooms.get(ClassRoom_.teacher), "Fowler"));

      return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
  }
}

Here is an example of data :

Student
_____________________________________________
ID     CLASSROOM_ID     NAME         AGE
2      120              Pascal       22
8      120              Bryan        21

ClassRoom
_____________________________________________
ID     CLASSROOM_ID     TEACHER
1      120              Marta
2      120              McAllister
2      120              Fowler

The specification returns nothing.

When I see the generated statement, I understand why it doesn't work :

 where
  classRooms.teacher=?
  and classRooms.teacher=?

I was expecting something like :

where
  students0.classroom_id in (
    select classrooms0.classroom_id where
    classRooms.teacher=?
  )
  and students0.classroom_id in (
    select classrooms0.classroom_id where
    classRooms.teacher=?
  )

Question : how can make a query with the Criteria API work in my case ?

Body:
If you want an in Clause instead of an equals clause just use it:

predicates.add(criteriaBuilder.in(classRooms.get(ClassRoom_.teacher), "Marta"));
predicates.add(criteriaBuilder.in(classRooms.get(ClassRoom_.teacher), "Fowler"));

See https://docs.oracle.com/javaee/6/api/javax/persistence/criteria/CriteriaBuilder.html#in(javax.persistence.criteria.Expression)


问:
How to copy a directory structure but only include certain files (using windows batch files)
As the title says, how can I recursively copy a directory structure but only include some files. E.g given the following directory structure:

```<code>folder1
  folder2
    folder3
      data.zip
      info.txt
      abc.xyz
    folder4
    folder5
      data.zip
      somefile.exe
      someotherfile.dll
</code>```

The files data.zip and info.txt can appear everywhere in the directory structure. How can I copy the full directory structure, but only include files named data.zip and info.txt (all other files should be ignored)?

The resulting directory structure should look like this:

```<code>copy_of_folder1
  folder2
    folder3
      data.zip
      info.txt
    folder4
    folder5
      data.zip
</code>```

答:
Similar to Paulius' solution, but the files you don't care about are not copied then deleted:</p>

```<code>@echo OFF

:: Replace c:\temp with the directory where folder1 resides.
cd c:\temp

:: You can make this more generic by passing in args for the source and destination folders.
for /f "usebackq" %%I in (`dir /b /s /a:-d folder1`) do @echo %%~nxI | find /V "data.zip" | find /v "info.txt" >> exclude_list.txt
xcopy folder1 copy_of_folder1 /EXCLUDE:exclude_list.txt /E /I
</code>```

OwnerDisplayName: Martin

ContentLicense: CC BY-SA 2.5

Body:
As the title says, how can I recursively copy a directory structure but only include some files. E.g given the following directory structure:

folder1
  folder2
    folder3
      data.zip
      info.txt
      abc.xyz
    folder4
    folder5
      data.zip
      somefile.exe
      someotherfile.dll

The files data.zip and info.txt can appear everywhere in the directory structure. How can I copy the full directory structure, but only include files named data.zip and info.txt (all other files should be ignored)?

The resulting directory structure should look like this:

copy_of_folder1
  folder2
    folder3
      data.zip
      info.txt
    folder4
    folder5
      data.zip

Body:
Similar to Paulius' solution, but the files you don't care about are not copied then deleted:

@echo OFF

:: Replace c:\temp with the directory where folder1 resides.
cd c:\temp

:: You can make this more generic by passing in args for the source and destination folders.
for /f "usebackq" %%I in (`dir /b /s /a:-d folder1`) do @echo %%~nxI | find /V "data.zip" | find /v "info.txt" >> exclude_list.txt
xcopy folder1 copy_of_folder1 /EXCLUDE:exclude_list.txt /E /I

OwnerDisplayName: Patrick Cuff


问:
Regular expression string search in Java
I know this can be done in many ways but im curious as to what the regex would be to pick out all strings not containing a particular substring, say GDA from
strings like GADSA, GDSARTCC, , THGDAERY. </p>

答: You don't need a regex. Just use string.contains("GDA") to see if a string contains a particular substring. It will return false if it doesn't.


问:
Convert unicode json to normal json in python
I got the following json: {u'a': u'aValue', u'b': u'bValue', u'c': u'cValue'} by doing request.json in my python code. Now, I want to convert the unicode json to normal json, something which should like this: {"a": "aValue", "b": "bValue", "c": "cValue"}. How do I get this done, without having to do any manual replacements? Please help.

答:
For python 2.x

```<code>import yaml
import json
json_data = yaml.load(json.dumps(request.json()))
</code>```

Now this json_data can be used as a json and can have list of json as well.

Body:
For python 2.x

import yaml
import json
json_data = yaml.load(json.dumps(request.json()))

Now this json_data can be used as a json and can have list of json as well.


问:
Error unit testing ASP.NET MVC 5
I'm developing an ASP.NET MVC 5 app and it works as expected.

Now trying to unit test one controller in the test project when I run it I get the following exception

An exception of type 'System.IO.FileLoadException' occurred in
  ControlCompras.UnitTests.dll but was not handled in user code

Additional information: Could not load file or assembly
  'System.Web.Mvc, Version=5.0.0.0, Culture=neutral,
  PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The
  located assembly's manifest definition does not match the assembly
  reference. (Exception from HRESULT: 0x80131040)

However the version of System.Web.Mvc.dll that is referenced in the Test project is 5.2.2.0. It's the same assembly that's referenced by the ASP.NET project.

Why it's trying to load the version 5.0.0.0?

Can someone please give me a clue about how to solve this?

Here's what I've tried:

The System.Web.Mvc.dll has the property Copy Local = true

I've reinstalled the package Microsoft.AspNet.Mvc with the following nuget command install-package Microsoft.AspNet.Mvc -version 5.2.2

here's the app.config file

Thanks in advance.

答:
I had the same error. I tried updating "System.Web.Mvc" package from nuget package manager in the unit test project. But it didn't reflect any change in references to the unit test project.
Heres my solution:

I opened the main project references and double clicked
"System.Web.Mvc" package which led to view in object browser.

Then I just copied that path of file opened it in file explorer. where I found dll file of "System.Web.Mvc" package.

I did the same procedure for the unit test project where I found dll file of "System.Web.Mvc" package of older version.

I replaced it with dll file of "System.Web.Mvc" package found from main project.

It worked. Though it's not proper way for upgrading pages but its quick.

Title: Error unit testing ASP.NET MVC 5


问:
container not building with mentioned dockerfile - multiple containers
I am working with a case where there is a main kernel application that uses mysql and influxdb as the databases and grafana for showing the data pictorially. I am creating separate containers for each using docker-compose and individual Dockerfiles.

The folder structure is as such :

dockercompose

docker-compose.yml

kernel

Dockerfilekernel

app.war

sqldb

Dockerfilesqldb

dump.sql

startup.sh

grafana

Dockerfilegrafana

grafana.env

run.sh

tsdbdb

Dockerfiletsdb

influxdb.env

init-influxdb.sh

entrypoint.sh

The container for kernel builds but on checking the logs, it is displaying the logs of influxdb, the same that displays on checking the logs for tsdbdb container.

Code for docker-compose :

```<code>version: '3'
services:
    mysqldb:
        build:
            context: ./sqldb
            dockerfile: Dockerfilesqldb
        container_name: sql
        command: mysqld --user=root --verbose
        volumes:
        - ./sqldb:/app/sql
        restart: always
        expose:
        - "3306"
        ports:
        - "3306:3306"
        environment:
        - MYSQL_ROOT_PASSWORD=secretpassword
        - MYSQL_DATABASE=dbtest
        - MYSQL_USER=user
        - MYSQL_PASSWORD=password
        - MYSQL_ALLOW_EMPTY_PASSWORD=yes
    tsdbdb:
        build:
            context: ./tsdbdb
            dockerfile: Dockerfiletsdb
        container_name: influx
        restart: always
        expose:
        - "8083"
        - "8086"
        ports:
        - "8083:8083"
        - "8086:8086"
        volumes:
        - ./tsdb:/app/tsdb
        env_file:
        - './tsdbdb/influxdb.env'
    grafana:
        build:
            context: ./grafana
            dockerfile: Dockerfilegrafana
        container_name: grafana
        env_file:
        - './grafana/grafana.env'
        expose:
        - "3000"
        ports:
        - "3003:3000"
        links:
        - tsdbdb
    web:
        build:
            context: ./kernel
            dockerfile: Dockerfilekernel
        container_name: kernel
        restart: always
        expose:
        - "8080"
        ports:
        - "8082:8080"
        depends_on:
        - mysqldb
        links:
        - tsdbdb
        - mysqldb
        volumes:
        - ./kernel:/app/kernel
</code>```

Dockerfile of kernel :

```<code>FROM java:openjdk-8-jre-alpine

ENV JHIPSTER_SLEEP 0

WORKDIR /app/kernel

# add directly the war
ADD *.war /app/kernel/app.war

RUN sh -c 'touch /app/kernel/app.war'
VOLUME /tmp

EXPOSE 8080

CMD echo "The application will start in ${JHIPSTER_SLEEP}s..." && \
    sleep ${JHIPSTER_SLEEP} && \
    java -Djava.security.egd=file:/dev/./urandom -jar /app/kernel/app.war
</code>```

Dockerfile for influxdb, just in case :

```<code>FROM buildpack-deps:stretch-curl

WORKDIR /app/tsdb

RUN set -ex && \
    for key in \
        05CE15085FC09D18E99EFB22684A14CF2582E0C5 ; \
    do \
        gpg --keyserver ha.pool.sks-keyservers.net --recv-keys "$key" || \
        gpg --keyserver pgp.mit.edu --recv-keys "$key" || \
        gpg --keyserver keyserver.pgp.com --recv-keys "$key" ; \
    done

ENV INFLUXDB_VERSION 1.2.4
ENV INFLUXDB_ADMIN_PASSWORD secretpassword
ENV INFLUXDB_DB master_db

RUN ARCH= && dpkgArch="$(dpkg --print-architecture)" && \
    case "${dpkgArch##*-}" in \
      amd64) ARCH='amd64';; \
      arm64) ARCH='arm64';; \
      armhf) ARCH='armhf';; \
      armel) ARCH='armel';; \
      *)     echo "Unsupported architecture: ${dpkgArch}"; exit 1;; \
    esac && \
    wget -q https://dl.influxdata.com/influxdb/releases/influxdb_${INFLUXDB_VERSION}_${ARCH}.deb.asc && \
    wget -q https://dl.influxdata.com/influxdb/releases/influxdb_${INFLUXDB_VERSION}_${ARCH}.deb && \
    gpg --batch --verify influxdb_${INFLUXDB_VERSION}_${ARCH}.deb.asc influxdb_${INFLUXDB_VERSION}_${ARCH}.deb && \
    dpkg -i influxdb_${INFLUXDB_VERSION}_${ARCH}.deb && \
    rm -f influxdb_${INFLUXDB_VERSION}_${ARCH}.deb*
COPY influxdb.conf /etc/influxdb/influxdb.conf

EXPOSE 8086

VOLUME /var/lib/influxdb

COPY entrypoint.sh /entrypoint.sh
COPY init-influxdb.sh /init-influxdb.sh
ENTRYPOINT ["/entrypoint.sh"]
CMD ["influxd"]
</code>```

It might be possible that this is happening due to a silly mistake but I am not able to find where exactly is the problem.

答:
So I was able to solve the problem by doing the following -

Changed the service name from web to kernel and in docker-compose.yml I added the command line for kernel service:

```<code>version: '3'
services:
    mysqldb:
        build:
            context: ./sqldb
            dockerfile: Dockerfilesqldb
        container_name: sql
        command: mysqld --user=root --verbose
        # volumes:
        # - ./sqldb:/app/sql
        restart: always
        # expose:
        # - "3306"
        ports:
        - "3306:3306"
        environment:
        - MYSQL_ROOT_PASSWORD=secretpassword
        - MYSQL_DATABASE=dbtest
        - MYSQL_USER=user
        - MYSQL_PASSWORD=password
        - MYSQL_ALLOW_EMPTY_PASSWORD=yes
    tsdbdb:
        build:
            context: ./tsdbdb
            dockerfile: Dockerfiletsdb
        container_name: influx
        restart: always
        # expose:
        # - "8083"
        # - "8086"
        ports:
        - "8083:8083"
        - "8086:8086"
        # volumes:
        # - ./tsdb:/app/tsdb
        env_file:
        - './tsdbdb/influxdb.env'
    grafana:
        build:
            context: ./grafana
            dockerfile: Dockerfilegrafana
        container_name: grafana
        env_file:
        - './grafana/grafana.env'
        expose:
        - "3000"
        ports:
        - "3003:3000"
        links:
        - tsdbdb
    kernel:
        build:
            context: ./kernel
            dockerfile: Dockerfilekernel
        container_name: kernel
        command: java -Djava.security.egd=file:/dev/./urandom -jar /app/kernel/app.war
        restart: always
        # expose:
        # - "8080"
        ports:
        - "8082:8080"
        links:
        - tsdbdb
        - mysqldb
        # volumes:
        # - ./kernel:/app/kernel
</code>```

Although I am not sure why only adding command solved the problem.

Body:
I am working with a case where there is a main kernel application that uses mysql and influxdb as the databases and grafana for showing the data pictorially. I am creating separate containers for each using docker-compose and individual Dockerfiles.

The folder structure is as such :

dockercompose

docker-compose.yml

kernel

Dockerfilekernel

app.war

sqldb

Dockerfilesqldb

dump.sql

startup.sh

grafana

Dockerfilegrafana

grafana.env

run.sh

tsdbdb

Dockerfiletsdb

influxdb.env

init-influxdb.sh

entrypoint.sh

The container for kernel builds but on checking the logs, it is displaying the logs of influxdb, the same that displays on checking the logs for tsdbdb container.

Code for docker-compose :

version: '3'
services:
    mysqldb:
        build:
            context: ./sqldb
            dockerfile: Dockerfilesqldb
        container_name: sql
        command: mysqld --user=root --verbose
        volumes:
        - ./sqldb:/app/sql
        restart: always
        expose:
        - "3306"
        ports:
        - "3306:3306"
        environment:
        - MYSQL_ROOT_PASSWORD=secretpassword
        - MYSQL_DATABASE=dbtest
        - MYSQL_USER=user
        - MYSQL_PASSWORD=password
        - MYSQL_ALLOW_EMPTY_PASSWORD=yes
    tsdbdb:
        build:
            context: ./tsdbdb
            dockerfile: Dockerfiletsdb
        container_name: influx
        restart: always
        expose:
        - "8083"
        - "8086"
        ports:
        - "8083:8083"
        - "8086:8086"
        volumes:
        - ./tsdb:/app/tsdb
        env_file:
        - './tsdbdb/influxdb.env'
    grafana:
        build:
            context: ./grafana
            dockerfile: Dockerfilegrafana
        container_name: grafana
        env_file:
        - './grafana/grafana.env'
        expose:
        - "3000"
        ports:
        - "3003:3000"
        links:
        - tsdbdb
    web:
        build:
            context: ./kernel
            dockerfile: Dockerfilekernel
        container_name: kernel
        restart: always
        expose:
        - "8080"
        ports:
        - "8082:8080"
        depends_on:
        - mysqldb
        links:
        - tsdbdb
        - mysqldb
        volumes:
        - ./kernel:/app/kernel

Dockerfile of kernel :

FROM java:openjdk-8-jre-alpine

ENV JHIPSTER_SLEEP 0

WORKDIR /app/kernel

# add directly the war
ADD *.war /app/kernel/app.war

RUN sh -c 'touch /app/kernel/app.war'
VOLUME /tmp

EXPOSE 8080

CMD echo "The application will start in ${JHIPSTER_SLEEP}s..." && \
    sleep ${JHIPSTER_SLEEP} && \
    java -Djava.security.egd=file:/dev/./urandom -jar /app/kernel/app.war

Dockerfile for influxdb, just in case :

FROM buildpack-deps:stretch-curl

WORKDIR /app/tsdb

RUN set -ex && \
    for key in \
        05CE15085FC09D18E99EFB22684A14CF2582E0C5 ; \
    do \
        gpg --keyserver ha.pool.sks-keyservers.net --recv-keys "$key" || \
        gpg --keyserver pgp.mit.edu --recv-keys "$key" || \
        gpg --keyserver keyserver.pgp.com --recv-keys "$key" ; \
    done

ENV INFLUXDB_VERSION 1.2.4
ENV INFLUXDB_ADMIN_PASSWORD secretpassword
ENV INFLUXDB_DB master_db

RUN ARCH= && dpkgArch="$(dpkg --print-architecture)" && \
    case "${dpkgArch##*-}" in \
      amd64) ARCH='amd64';; \
      arm64) ARCH='arm64';; \
      armhf) ARCH='armhf';; \
      armel) ARCH='armel';; \
      *)     echo "Unsupported architecture: ${dpkgArch}"; exit 1;; \
    esac && \
    wget -q https://dl.influxdata.com/influxdb/releases/influxdb_${INFLUXDB_VERSION}_${ARCH}.deb.asc && \
    wget -q https://dl.influxdata.com/influxdb/releases/influxdb_${INFLUXDB_VERSION}_${ARCH}.deb && \
    gpg --batch --verify influxdb_${INFLUXDB_VERSION}_${ARCH}.deb.asc influxdb_${INFLUXDB_VERSION}_${ARCH}.deb && \
    dpkg -i influxdb_${INFLUXDB_VERSION}_${ARCH}.deb && \
    rm -f influxdb_${INFLUXDB_VERSION}_${ARCH}.deb*
COPY influxdb.conf /etc/influxdb/influxdb.conf

EXPOSE 8086

VOLUME /var/lib/influxdb

COPY entrypoint.sh /entrypoint.sh
COPY init-influxdb.sh /init-influxdb.sh
ENTRYPOINT ["/entrypoint.sh"]
CMD ["influxd"]

It might be possible that this is happening due to a silly mistake but I am not able to find where exactly is the problem.

Body:
So I was able to solve the problem by doing the following -

Changed the service name from web to kernel and in docker-compose.yml I added the command line for kernel service:

version: '3'
services:
    mysqldb:
        build:
            context: ./sqldb
            dockerfile: Dockerfilesqldb
        container_name: sql
        command: mysqld --user=root --verbose
        # volumes:
        # - ./sqldb:/app/sql
        restart: always
        # expose:
        # - "3306"
        ports:
        - "3306:3306"
        environment:
        - MYSQL_ROOT_PASSWORD=secretpassword
        - MYSQL_DATABASE=dbtest
        - MYSQL_USER=user
        - MYSQL_PASSWORD=password
        - MYSQL_ALLOW_EMPTY_PASSWORD=yes
    tsdbdb:
        build:
            context: ./tsdbdb
            dockerfile: Dockerfiletsdb
        container_name: influx
        restart: always
        # expose:
        # - "8083"
        # - "8086"
        ports:
        - "8083:8083"
        - "8086:8086"
        # volumes:
        # - ./tsdb:/app/tsdb
        env_file:
        - './tsdbdb/influxdb.env'
    grafana:
        build:
            context: ./grafana
            dockerfile: Dockerfilegrafana
        container_name: grafana
        env_file:
        - './grafana/grafana.env'
        expose:
        - "3000"
        ports:
        - "3003:3000"
        links:
        - tsdbdb
    kernel:
        build:
            context: ./kernel
            dockerfile: Dockerfilekernel
        container_name: kernel
        command: java -Djava.security.egd=file:/dev/./urandom -jar /app/kernel/app.war
        restart: always
        # expose:
        # - "8080"
        ports:
        - "8082:8080"
        links:
        - tsdbdb
        - mysqldb
        # volumes:
        # - ./kernel:/app/kernel

Although I am not sure why only adding command solved the problem.


问:
How to splite with number with , in filed with missing number in given number?
I am trying to getting this output. But failed to missing numbers in separate by this ',' one ?</p>

```<code>Input: 1, 2, 3, 4.. 9, 10,13.. 17, 18, 19.. 25
Output: 1 2 3 4 5 6 7 8 9 10 13 14 15 16 17 18 19 20 21 22 23 24 25
</code>```

答:
Here is a working implementation which does what you need, further explanation below the code:

```<code>public static String getCSV(int start, int end) {
    List<String> list = IntStream.range(start, end).boxed()
       .map(i -> i.toString()).collect(Collectors.toList());
    String csv = String.join(" ", list);

    return csv;
}

public static void main(String args[])
{
    String input = "1, 2, 3, 4.. 9, 10,13.. 17, 18, 19.. 25";
    input = input.replaceAll(",\\s*", " ");
    Pattern r = Pattern.compile("(\\d+)\\.\\.\\s*(\\d+)");
    Matcher m = r.matcher(input);
    StringBuffer stringBuffer = new StringBuffer();
    while (m.find( )) {
        int start = Integer.parseInt(m.group(1));
        int end = Integer.parseInt(m.group(2));
        m.appendReplacement(stringBuffer, getCSV(start, end+1));
    }
    System.out.println(stringBuffer);
}
</code>```

Output:

```<code>1 2 3 4 5 6 7 8 9 10 13 14 15 16 17 18 19 20 21 22 23 24 25
</code>```

This approach uses a regex matcher to identify every pair of numbers which is in ellipsis (e.g. 4.. 9), and then replaces it with a space separated continuous range from the starting to ending point.  Java 8 streams come in handy here, and the getCSV() method generates a string containing the sequence of numbers from the starting and ending input values.  Then, we need only iterate over the entire input, and replace each ellipsis using the helper method.

Demo

Body:
I am trying to getting this output. But failed to missing numbers in separate by this ',' one ?

Input: 1, 2, 3, 4.. 9, 10,13.. 17, 18, 19.. 25
Output: 1 2 3 4 5 6 7 8 9 10 13 14 15 16 17 18 19 20 21 22 23 24 25

Body:
Here is a working implementation which does what you need, further explanation below the code:

public static String getCSV(int start, int end) {
    List<String> list = IntStream.range(start, end).boxed()
       .map(i -> i.toString()).collect(Collectors.toList());
    String csv = String.join(" ", list);

    return csv;
}

public static void main(String args[])
{
    String input = "1, 2, 3, 4.. 9, 10,13.. 17, 18, 19.. 25";
    input = input.replaceAll(",\\s*", " ");
    Pattern r = Pattern.compile("(\\d+)\\.\\.\\s*(\\d+)");
    Matcher m = r.matcher(input);
    StringBuffer stringBuffer = new StringBuffer();
    while (m.find( )) {
        int start = Integer.parseInt(m.group(1));
        int end = Integer.parseInt(m.group(2));
        m.appendReplacement(stringBuffer, getCSV(start, end+1));
    }
    System.out.println(stringBuffer);
}

Output:

1 2 3 4 5 6 7 8 9 10 13 14 15 16 17 18 19 20 21 22 23 24 25

This approach uses a regex matcher to identify every pair of numbers which is in ellipsis (e.g. 4.. 9), and then replaces it with a space separated continuous range from the starting to ending point.  Java 8 streams come in handy here, and the getCSV() method generates a string containing the sequence of numbers from the starting and ending input values.  Then, we need only iterate over the entire input, and replace each ellipsis using the helper method.

Demo


问:
Load View with NavigationCacheMode="Enabled" whitout navigate to it
I would like to know if it is possible to implement this concept:

I have two views:

1 - First view

2 - Second View with NavigationCacheMode="Enabled"

when initializing my application navigates in view 1, I would like to initialize view 2 as well during this phase, without navigating.

example:

my first view is a simple welcome view, my second view is used to view a document. I would like to have a document loaded in view 2 during the initialization of view 1.
So that the user has the document ready when navigating in view 2.

答:
It's impossible. Even if you could initialize view 2, but when you call Frame.Navigate() to naviagte to view 2, all UIElements will be re-rendered again.

For your case, you said you have a document that needs to be displayed. I think what you need to think about is how to reduce the loading time. For example, you could display the document by paging instead of showing it at once.


问:
POWER BI Refresh data source from Excel where file name changes daily
I am building a report in Power BI of my company's daily figures. Those figures are published each morning in an excel file to our company server. I would change the scripts that build this file, but at the moment that's not an option.

However, that file name has the date in it each day, so the filename CHANGES every day.

Essentially I am trying to use an expression for the excel query to include the system date in the concatenated filename each morning.

答:
Power BI's Queries can start by reading a folder of files (Get Data / Folder).  It treats them as a table of data (one row per file).

You can then filter that table (e.g. Sort by Date modified, Keep Rows / Keep Top Rows / 1), before using the Combine Files button on the Content column - this will generate a function that will work against any file(s) allowed through your filters.


问:
DELETE From table Group By
SQL query:

```<code>`SELECT * FROM `adl_auth_user` WHERE `user_id` = 1919`
</code>```

Result is

```<code>id  user_id     type_id     type       auth_    role_id
66428   1919     1                97    103     6

66429   1919    1                 97    104     6

66430   1919    1                 97    105     6

66431   1919    1                 97    106     6
</code>```

When I Add Group By

```<code>SELECT * FROM `adl_auth_user` WHERE `user_id` = 1919 group by type,type_id
</code>```

Result is

```<code>id  user_id     type_id     type    auth_item_id    role_id

66428   1919    1   97                103             6
</code>```

I dont need all Details with query

```<code>`SELECT * FROM `adl_auth_user` WHERE `user_id` = 1919` (its simple)
</code>```

How can i delete table details of following

```<code>SELECT * FROM `adl_auth_user` WHERE `user_id` = 1919 group by type,type_id
</code>```

Note : All details are edited format ...

答:
This query:

```<code>DELETE adl_auth_user
FROM adl_auth_user
LEFT JOIN adl_auth_user t2
   ON adl_auth_user.type_id = t2.type_id AND
      adl_auth_user.type = t2.type AND
      adl_auth_user.id > t2.id
WHERE adl_auth_user.user_id = 1919 AND t2.id IS NOT NULL
</code>```

deletes all records having the same type_id and type values except from the one having the smallest id value.

Demo here

Title: DELETE From table Group By

Body:
SQL query:

`SELECT * FROM `adl_auth_user` WHERE `user_id` = 1919`

Result is

id  user_id     type_id     type       auth_    role_id
66428   1919     1                97    103     6

66429   1919    1                 97    104     6

66430   1919    1                 97    105     6

66431   1919    1                 97    106     6

When I Add Group By

SELECT * FROM `adl_auth_user` WHERE `user_id` = 1919 group by type,type_id

Result is

id  user_id     type_id     type    auth_item_id    role_id

66428   1919    1   97                103             6

I dont need all Details with query

`SELECT * FROM `adl_auth_user` WHERE `user_id` = 1919` (its simple)

How can i delete table details of following

SELECT * FROM `adl_auth_user` WHERE `user_id` = 1919 group by type,type_id

Note : All details are edited format ...

Body:
This query:

DELETE adl_auth_user
FROM adl_auth_user
LEFT JOIN adl_auth_user t2
   ON adl_auth_user.type_id = t2.type_id AND
      adl_auth_user.type = t2.type AND
      adl_auth_user.id > t2.id
WHERE adl_auth_user.user_id = 1919 AND t2.id IS NOT NULL

deletes all records having the same type_id and type values except from the one having the smallest id value.

Demo here


问:
how to identify if a number is of float or double type in java
How 19.5 is a double value. Why we need to append F to it to make it float? Just want to know how we identify a number whether it is float or double.

答:
For handling downcasts, or narrowing conversions. Whenever you downcast a long to an int, or a double to a float, the possibility for data loss exists. So, the compiler will force you to indicate that you really want to perform the narrowing conversion, by signaling a compile error for something like this:

float f = 19.5;

Because 19.5 represents a double, you have to explicitly cast it to a float (basically signing off on the narrowing conversion). Otherwise, you could indicate that the number is really a float, by using the correct suffix;

float f = 19.5f;

by default 19.5 is double literal, So to tell compiler to treat it as float explicitly -> it uses f or F


问:
How to implement `using` in javascript?
I would like to make something like this (similar to c#):

```<code>using("content/jquery.js");

$("div").fadeOut();
</code>```

So if content/jquery.js is not on a script in the head I would like to load it and continue the execution after it loads.

Is it possible to implement this or something similar? Note: I could have more than 1 using

答:
These are called script loaders.

You can take a look at RequireJS, which behaves in a very similar way:

```<code>require(["helper/util"], function() {
    //This function is called when scripts/helper/util.js is loaded.
});
</code>```

There's also LabJS and ControlJS, which are more focused on async script loading rather than dependencies, but may be worth checking out. Also in this category, our very own @jAndy's SupplyJS.

Title: How to implement `using` in javascript?

Body:
I would like to make something like this (similar to c#):

using("content/jquery.js");

$("div").fadeOut();

So if content/jquery.js is not on a script in the head I would like to load it and continue the execution after it loads.

Is it possible to implement this or something similar? Note: I could have more than 1 using

Body:
These are called script loaders.

You can take a look at RequireJS, which behaves in a very similar way:

require(["helper/util"], function() {
    //This function is called when scripts/helper/util.js is loaded.
});

There's also LabJS and ControlJS, which are more focused on async script loading rather than dependencies, but may be worth checking out. Also in this category, our very own @jAndy's SupplyJS.


问:
VB.net Logic is not giving expected output
When I add this code in my project then the logic is not giving expected output

```<code>If e.KeyCode = Keys.Enter And cbmPassportCountry.Text.Trim() <> "" Then
    SendKeys.Send("{tab}")
Else
    If btnSave.Enabled = True Then
        btnSave.Focus()
    End If
End If
</code>```

If I use this logic then my code gives expected output

```<code>Private Sub cbmPassportCountry_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles cbmPassportCountry.KeyDown
    'If e.KeyCode = Keys.Enter And cbmPassportCountry.Text.Trim() <> "" Then
    If e.KeyCode = Keys.Enter Then
        If btnSave.Enabled = True Then
            btnSave.Focus()
        Else
            SendKeys.Send("{tab}")
        End If
    End If
End Sub
</code>```

But I want to implement that And Logic in my code which will work like my next logic

答:
If you want your first block to work like the second, but checking that cbmPassportCountry.Text isn't empty, why don't you just add that to your second statement?

```<code>If e.KeyCode = Keys.Enter AndAlso cbmPassportCountry.Text.Trim() <> "" Then
    If btnSave.Enabled = True Then
        btnSave.Focus()
    Else
        SendKeys.Send("{tab}")
    End If
End If
</code>```

You cannot put this in one If-statement without having to make additional, unnecessary checks.

Body:
When I add this code in my project then the logic is not giving expected output

If e.KeyCode = Keys.Enter And cbmPassportCountry.Text.Trim() <> "" Then
    SendKeys.Send("{tab}")
Else
    If btnSave.Enabled = True Then
        btnSave.Focus()
    End If
End If

If I use this logic then my code gives expected output

Private Sub cbmPassportCountry_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles cbmPassportCountry.KeyDown
    'If e.KeyCode = Keys.Enter And cbmPassportCountry.Text.Trim() <> "" Then
    If e.KeyCode = Keys.Enter Then
        If btnSave.Enabled = True Then
            btnSave.Focus()
        Else
            SendKeys.Send("{tab}")
        End If
    End If
End Sub

But I want to implement that And Logic in my code which will work like my next logic

Body:
If you want your first block to work like the second, but checking that cbmPassportCountry.Text isn't empty, why don't you just add that to your second statement?

If e.KeyCode = Keys.Enter AndAlso cbmPassportCountry.Text.Trim() <> "" Then
    If btnSave.Enabled = True Then
        btnSave.Focus()
    Else
        SendKeys.Send("{tab}")
    End If
End If

You cannot put this in one If-statement without having to make additional, unnecessary checks.


问:
Get Route record (or :name) for a given request
I'm using compojure-api, and I'm looking for a function that, given my api route structure thingie and a request, returns the Route record (or :name) for that request, without applying its handler.

I've been able to find kind of the inverse of what I'm looking for in compojure.api.routes/path-for, which, given a :name, returns the path for the corresponding route. In the same namespace there are also functions like get-routes which seem promising, but I've yet to find exactly what I'm looking for.

In other words, given this simple example

```<code>(defapi my-api
  (context "/" []
    (GET "/myroute" request
      :name :my-get
      (ok))
    (POST "/myroute" request
      :name :my-post
      (ok))))
</code>```

I'm looking for a function foo that works like this

```<code>(foo my-api (mock/request :get "/myroute"))
;; => #Route{:path "/myroute", :method :get, :info {:name :my-get, :public {:x-name :my-get}}}
;; or
;; => :my-get
</code>```

Any ideas?

答:
my-api is defined as a Route Record, so you can evaluate it at the repl to see what it looks like:

```<code>#Route{:info {:coercion :schema},
       :childs [#Route{:childs [#Route{:path "/",
                                       :info {:static-context? true},
                                       :childs [#Route{:path "/myroute",
                                                       :method :get,
                                                       :info {:name :my-get, :public {:x-name :my-get}}}
                                                #Route{:path "/myroute",
                                                       :method :post,
                                                       :info {:name :my-post, :public {:x-name :my-post}}}]}]}]}
</code>```

There are helpers in compojure.api.routes to transform the structure:

```<code>(require '[compojure.api.routes :as routes])

(routes/get-routes my-api)
; [["/myroute" :get {:coercion :schema, :static-context? true, :name :my-get, :public {:x-name :my-get}}]
;  ["/myroute" :post {:coercion :schema, :static-context? true, :name :my-post, :public {:x-name :my-post}}]]
</code>```

, which effectively flattens the route tree while retaining the order. For reverse routing there is:

```<code>(-> my-api
    routes/get-routes
    routes/route-lookup-table)
; {:my-get {"/myroute" {:method :get}}
;  :my-post {"/myroute" {:method :post}}}
</code>```

More utilities can be added if needed.

Hope this helps.

Body:
I'm using compojure-api, and I'm looking for a function that, given my api route structure thingie and a request, returns the Route record (or :name) for that request, without applying its handler.

I've been able to find kind of the inverse of what I'm looking for in compojure.api.routes/path-for, which, given a :name, returns the path for the corresponding route. In the same namespace there are also functions like get-routes which seem promising, but I've yet to find exactly what I'm looking for.

In other words, given this simple example

(defapi my-api
  (context "/" []
    (GET "/myroute" request
      :name :my-get
      (ok))
    (POST "/myroute" request
      :name :my-post
      (ok))))

I'm looking for a function foo that works like this

(foo my-api (mock/request :get "/myroute"))
;; => #Route{:path "/myroute", :method :get, :info {:name :my-get, :public {:x-name :my-get}}}
;; or
;; => :my-get

Any ideas?

Body:
my-api is defined as a Route Record, so you can evaluate it at the repl to see what it looks like:

#Route{:info {:coercion :schema},
       :childs [#Route{:childs [#Route{:path "/",
                                       :info {:static-context? true},
                                       :childs [#Route{:path "/myroute",
                                                       :method :get,
                                                       :info {:name :my-get, :public {:x-name :my-get}}}
                                                #Route{:path "/myroute",
                                                       :method :post,
                                                       :info {:name :my-post, :public {:x-name :my-post}}}]}]}]}

There are helpers in compojure.api.routes to transform the structure:

(require '[compojure.api.routes :as routes])

(routes/get-routes my-api)
; [["/myroute" :get {:coercion :schema, :static-context? true, :name :my-get, :public {:x-name :my-get}}]
;  ["/myroute" :post {:coercion :schema, :static-context? true, :name :my-post, :public {:x-name :my-post}}]]

, which effectively flattens the route tree while retaining the order. For reverse routing there is:

(-> my-api
    routes/get-routes
    routes/route-lookup-table)
; {:my-get {"/myroute" {:method :get}}
;  :my-post {"/myroute" {:method :post}}}

More utilities can be added if needed.

Hope this helps.


问:
Upload image to firebase with React Native
I have tried to follow this tutorial: https://github.com/CodeLinkIO/Firebase-Image-Upload-React-Native

but got stuck in RNFB_ANDROID_PERMISSIONS=true react-native link

This command crashed my application and I cannot continue anymore. Is there any other good tutorial to do this?

答:
Are you running this command inside the console in Windows? The command sets the env variable and then runs react-native link, so the issue could be that you are just not setting the env variable right.
The following post should might help
https://superuser.com/questions/212150/how-to-set-env-variable-in-windows-cmd-line


问:
On ios Cancel and send button on the native mail not working.User got blocked
Below is the function  for the native mail app open , Nothing happed  when cancel button clicked and Send button on native mail app is sending the mail but user also got blocked.User didn't get any action respone.</p>

```<code>   @IBAction func openNativeEmail(_ sender: AnyObject){
        if MFMailComposeViewController.canSendMail() {
            debugPrint("can send mail")
        let mailVC = MFMailComposeViewController()
        mailVC.mailComposeDelegate = self
        mailVC.setToRecipients(["pawanline@gmail.com"])
        mailVC.setSubject("Testing mail App features")
        mailVC.setCcRecipients(["pawan.kumar@iic.ac.in"])
        mailVC.setMessageBody("Hi,just testing ", isHTML: false)
            present(mailVC, animated: true, completion: nil)
        } else {
            print("Unable to send the mail")
        }

    func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
            controller.dismiss(animated: true, completion: nil)
    }
</code>```

答:
You missing a closing bracket:</p>

```<code>   @IBAction func openNativeEmail(_ sender: AnyObject){
        if MFMailComposeViewController.canSendMail() {
            debugPrint("can send mail")
        let mailVC = MFMailComposeViewController()
        mailVC.mailComposeDelegate = self
        mailVC.setToRecipients(["pawanline@gmail.com"])
        mailVC.setSubject("Testing mail App features")
        mailVC.setCcRecipients(["pawan.kumar@iic.ac.in"])
        mailVC.setMessageBody("Hi,just testing ", isHTML: false)
            present(mailVC, animated: true, completion: nil)
        } else {
            print("Unable to send the mail")
        }
    } // <----- THIS WAS MISSING

    func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
            controller.dismiss(animated: true, completion: nil)
    }
</code>```

Body:
Below is the function  for the native mail app open , Nothing happed  when cancel button clicked and Send button on native mail app is sending the mail but user also got blocked.User didn't get any action respone.

   @IBAction func openNativeEmail(_ sender: AnyObject){
        if MFMailComposeViewController.canSendMail() {
            debugPrint("can send mail")
        let mailVC = MFMailComposeViewController()
        mailVC.mailComposeDelegate = self
        mailVC.setToRecipients(["pawanline@gmail.com"])
        mailVC.setSubject("Testing mail App features")
        mailVC.setCcRecipients(["pawan.kumar@iic.ac.in"])
        mailVC.setMessageBody("Hi,just testing ", isHTML: false)
            present(mailVC, animated: true, completion: nil)
        } else {
            print("Unable to send the mail")
        }

    func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
            controller.dismiss(animated: true, completion: nil)
    }

Body:
You missing a closing bracket:

   @IBAction func openNativeEmail(_ sender: AnyObject){
        if MFMailComposeViewController.canSendMail() {
            debugPrint("can send mail")
        let mailVC = MFMailComposeViewController()
        mailVC.mailComposeDelegate = self
        mailVC.setToRecipients(["pawanline@gmail.com"])
        mailVC.setSubject("Testing mail App features")
        mailVC.setCcRecipients(["pawan.kumar@iic.ac.in"])
        mailVC.setMessageBody("Hi,just testing ", isHTML: false)
            present(mailVC, animated: true, completion: nil)
        } else {
            print("Unable to send the mail")
        }
    } // <----- THIS WAS MISSING

    func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
            controller.dismiss(animated: true, completion: nil)
    }


问:
How to access Outer Variable of for loop in java8?
Following is My Code

```<code>List<Lead> Mylead = adminService.GetMyData(10);
int i=0;
Mylead.forEach(lead->{
  i++;
});
</code>```

Error : Local variable I defined in an enclosing scope must be final
  or effectively final

答:
You have to create a wrapper for i, a simple way to do this would be an array.

```<code>List<Lead> Mylead = adminService.GetMyData(10);
final int[] i={0};
Mylead.forEach(lead->{
  i[0]++;
});
</code>```

For a detailed explanation how this works see: Java 8 Lambda variable scope

Body:
Following is My Code

List<Lead> Mylead = adminService.GetMyData(10);
int i=0;
Mylead.forEach(lead->{
  i++;
});

Error : Local variable I defined in an enclosing scope must be final
  or effectively final

Body:
You have to create a wrapper for i, a simple way to do this would be an array.

List<Lead> Mylead = adminService.GetMyData(10);
final int[] i={0};
Mylead.forEach(lead->{
  i[0]++;
});

For a detailed explanation how this works see: Java 8 Lambda variable scope


问:
Kotlin + Mockito: getting a null
Please I am a bit confused, this test fails with "java.lang.IllegalStateException: notNull() must not be null":

```<code>@Test
fun when_resume_subscribe() {
    // WHEN
    presenter.onStart()
    // THEN
    verify<Model>(model).subscribe(notNull()) // <---- fails here
}
</code>```

here is the method under test:

```<code>override fun onStart() {
    model.subscribe(object : Observer<Bar> {
        override fun onCompleted() {
            view?.showProgress(false)
        }
//... more stuff...
</code>```

Please what is happening?

答:
This is basically casing the Null Object into the specific class object using Generic. The code as below, where we override any() to handle the issue accordingly.

```<code>private fun <T> any(): T {
Mockito.any<T>()
return uninitialized()
  }
private fun <T> uninitialized(): T = null as T
</code>```

For more detail you can check this https://medium.com/@elye.project/befriending-kotlin-and-mockito-1c2e7b0ef791 tutorial.

Title: Kotlin + Mockito: getting a null

Body:
Please I am a bit confused, this test fails with "java.lang.IllegalStateException: notNull() must not be null":

@Test
fun when_resume_subscribe() {
    // WHEN
    presenter.onStart()
    // THEN
    verify<Model>(model).subscribe(notNull()) // <---- fails here
}

here is the method under test:

override fun onStart() {
    model.subscribe(object : Observer<Bar> {
        override fun onCompleted() {
            view?.showProgress(false)
        }
//... more stuff...

Please what is happening?

Body:
This is basically casing the Null Object into the specific class object using Generic. The code as below, where we override any() to handle the issue accordingly.

private fun <T> any(): T {
Mockito.any<T>()
return uninitialized()
  }
private fun <T> uninitialized(): T = null as T

For more detail you can check this https://medium.com/@elye.project/befriending-kotlin-and-mockito-1c2e7b0ef791 tutorial.


问:
Missing icons in Visual Studio 2015 after installing extension
I followed the steps to create a Visual Studio extension, however after installing the extension in VS2015, Visual Studio does not display any icons in toolbars in menus. Any idea what could be the cause and how to restore icons.</p>

答:
In Visual Studio 2017 solve this ;
Open this folder

C:\Users\YourName\AppData\Local\Microsoft\VisualStudio\15.0_533da44c\ImageLibrary

than remove the ImageLibrary.cache file


问:
mysql Foreign key constraint is incorrectly formed error
I have two tables, table1 is the parent table with a column ID and table2 with a column IDFromTable1 (not the actual name) when I put a FK on IDFromTable1 to ID in table1 I get the error Foreign key constraint is incorrectly formed error. I would like to delete table 2 record if table1 record gets deleted. Thanks for any help

```<code>ALTER TABLE `table2`
   ADD CONSTRAINT `FK1`
      FOREIGN KEY (`IDFromTable1`) REFERENCES `table1` (`ID`)
      ON UPDATE CASCADE
      ON DELETE CASCADE;
</code>```

Let me know if any other information is needed. I am new to mysql

答:
Even i ran into the same issue with mysql and liquibase.
    So this is what the problem is:
    The table from which you want to reference a column of other table is different either in case of datatype or in terms of size of the datatype.</p>

```<code>Error appears in below scenario:
Scenario 1:
Table A has column id, type=bigint
Table B column referenced_id type varchar(this column gets the value from the id column of Table A.)
Liquibase changeset for table B:

    <changeset id="XXXXXXXXXXX-1" author="xyz">
            <column name="referenced_id" **type="varchar"**>
        </column>
            </changeset>
    <changeSet id="XXXXXXXXXXX-2" author="xyz">
                <addForeignKeyConstraint constraintName="FK_table_A"
                    referencedTableName="A" **baseColumnNames="referenced_id**"
                    referencedColumnNames="id" baseTableName="B" />
    </changeSet>

Table A changeSet:

    <changeSet id="YYYYYYYYYY" author="xyz">
     <column **name="id"** **type="bigint"** autoIncrement="${autoIncrement}">
                    <constraints primaryKey="true" nullable="false"/>
                </column>
    </changeSet>

Solution:
correct the type of table B to bigint because the referenced table has type bigint.

Scenrario 2:
The type might be correct but the size might not.
e.g. :
Table B : referenced column type="varchar 50"
Table A : base column type ="varchar 255"

Solution change the size of referenced column to that of base table's column size.
</code>```

Body:
I have two tables, table1 is the parent table with a column ID and table2 with a column IDFromTable1 (not the actual name) when I put a FK on IDFromTable1 to ID in table1 I get the error Foreign key constraint is incorrectly formed error. I would like to delete table 2 record if table1 record gets deleted. Thanks for any help

ALTER TABLE `table2`
   ADD CONSTRAINT `FK1`
      FOREIGN KEY (`IDFromTable1`) REFERENCES `table1` (`ID`)
      ON UPDATE CASCADE
      ON DELETE CASCADE;

Let me know if any other information is needed. I am new to mysql

Body:
Even i ran into the same issue with mysql and liquibase.
    So this is what the problem is:
    The table from which you want to reference a column of other table is different either in case of datatype or in terms of size of the datatype.

Error appears in below scenario:
Scenario 1:
Table A has column id, type=bigint
Table B column referenced_id type varchar(this column gets the value from the id column of Table A.)
Liquibase changeset for table B:

    <changeset id="XXXXXXXXXXX-1" author="xyz">
            <column name="referenced_id" **type="varchar"**>
        </column>
            </changeset>
    <changeSet id="XXXXXXXXXXX-2" author="xyz">
                <addForeignKeyConstraint constraintName="FK_table_A"
                    referencedTableName="A" **baseColumnNames="referenced_id**"
                    referencedColumnNames="id" baseTableName="B" />
    </changeSet>

Table A changeSet:

    <changeSet id="YYYYYYYYYY" author="xyz">
     <column **name="id"** **type="bigint"** autoIncrement="${autoIncrement}">
                    <constraints primaryKey="true" nullable="false"/>
                </column>
    </changeSet>

Solution:
correct the type of table B to bigint because the referenced table has type bigint.

Scenrario 2:
The type might be correct but the size might not.
e.g. :
Table B : referenced column type="varchar 50"
Table A : base column type ="varchar 255"

Solution change the size of referenced column to that of base table's column size.


问:
Searching particular string in a string array of split operations
I have a string

```<code>str = "Abc=1,gdf=1,ghj=1,pqr=1"
</code>```

Now I to increment the value of pqr=1 to pqr2 whenever prq will come it will increment the value by 1.  So I decided to start by Spitting this string at every ","  so that a part of spilited string array will contain pqr=1 and then I can perform my operation of incrementing.

Code is as follows

```<code>String []  parts=str.split("=");
</code>```

This gives parts of string which contains pqr at index 3 but it is not necessary everytime pqr will be at index 3 so I want to make I it generic.  For that I am trying to do as follows:

```<code>if(Arrays. asList(parts). contains("pqr") {
    // Do my other split operation
}
</code>```

But I am not able to make it generic by this.  I am not getting any error but code is not going inside if statement.  Please suggest how to do it.

答:
First of all, it is not at all advisable to use String for this purpose. I think what you need is a HashMap<String,Integer> instead.

Moreover, you can simply iterate over your first array and check in every String for the substring pqr.

```<code>str = "Abc=1,gdf=1,ghj=1,pqr=1";
String[] arr = str.split(",");
for(String member: arr) {
    if(member.contains("pqr")) {
        //Do your operation here
    }
}
</code>```

Body:
I have a string

str = "Abc=1,gdf=1,ghj=1,pqr=1"

Now I to increment the value of pqr=1 to pqr2 whenever prq will come it will increment the value by 1.  So I decided to start by Spitting this string at every ","  so that a part of spilited string array will contain pqr=1 and then I can perform my operation of incrementing.

Code is as follows

String []  parts=str.split("=");

This gives parts of string which contains pqr at index 3 but it is not necessary everytime pqr will be at index 3 so I want to make I it generic.  For that I am trying to do as follows:

if(Arrays. asList(parts). contains("pqr") {
    // Do my other split operation
}

But I am not able to make it generic by this.  I am not getting any error but code is not going inside if statement.  Please suggest how to do it.

Body:
First of all, it is not at all advisable to use String for this purpose. I think what you need is a HashMap<String,Integer> instead.

Moreover, you can simply iterate over your first array and check in every String for the substring pqr.

str = "Abc=1,gdf=1,ghj=1,pqr=1";
String[] arr = str.split(",");
for(String member: arr) {
    if(member.contains("pqr")) {
        //Do your operation here
    }
}


问:
Summary details using php html
I want to display multiple PHP outputs to a single HTML page. Here after 1 summary, script.php output should be displayed and after 2 summary, script1.php output should be displayed. But I'm getting output of PHP after 2 summary.

```<code><!DOCTYPE html>
<html lang="en">
    <head>
        <h2 align="center">DASHBOARD</h2>
    </head>
    <body>
        <details>
            <summary>1</summary>
            <?php echo file_get_contents("https://servername/script.php"); ?>
        </details>
        <details>
            <summary>2</summary>
            <?php echo file_get_contents("https://servername/script1.php"); ?>
        </details>
    </body>
</html>
</code>```

答:
I believe you want to use  include,

file_get_contents will fetch data from the network, so the output will be the same as in your browser (goto https://servername/script1.php and take a look at Page Source)

If your script is located on another server, then, of course, you will not be able to use include, or execute in any way script from other resource.

Title: Summary details using php html

Body:
I want to display multiple PHP outputs to a single HTML page. Here after 1 summary, script.php output should be displayed and after 2 summary, script1.php output should be displayed. But I'm getting output of PHP after 2 summary.

<!DOCTYPE html>

DASHBOARD

            1
            <?php echo file_get_contents("https://servername/script.php"); ?>

            2
            <?php echo file_get_contents("https://servername/script1.php"); ?>


问:
Joining on Is Null MS Access SQL
How do I join 2 tables in MS Access that may have NULL values in the join fields?  For instance I have 2 tables, Table1 and Table2.  I would like to join them on Table1.[Test Field 1] = Table2.[Test Field 1].  Also if the field in both tables is NULL I would like them to join.  I have tried a couple different ways of going about this, including the SQL below.  When I try to run that I get the error message: "Missing ),], or Item in Query expression..."  I've tried inserting more brackets etc but nothing has worked.  </p>

```<code>SELECT Table1.[Test Field 1], Table1.[Test Field 2], Table2.[Test Field 1], Table2.[Test Field 2]
FROM Table1 INNER JOIN Table2 ON Table1.[Test Field 1] = Table2.[Test Field 1]
OR (ISNULL(table1.[test field 1]) AND ISNULL(table2.[Test Field 1]));
</code>```

答:
Any ON clause in Access with more than 1 comparison needs to be wrapped in parentheses. Unfortunately, the error message you got is not very descriptive, but it's easy to fix.

```<code>SELECT Table1.[Test Field 1], Table1.[Test Field 2], Table2.[Test Field 1], Table2.[Test Field 2]
FROM Table1 INNER JOIN Table2 ON (Table1.[Test Field 1] = Table2.[Test Field 1]
OR (ISNULL(table1.[test field 1]) AND ISNULL(table2.[Test Field 1])));
</code>```

Title: Joining on Is Null MS Access SQL

Body:
How do I join 2 tables in MS Access that may have NULL values in the join fields?  For instance I have 2 tables, Table1 and Table2.  I would like to join them on Table1.[Test Field 1] = Table2.[Test Field 1].  Also if the field in both tables is NULL I would like them to join.  I have tried a couple different ways of going about this, including the SQL below.  When I try to run that I get the error message: "Missing ),], or Item in Query expression..."  I've tried inserting more brackets etc but nothing has worked.

SELECT Table1.[Test Field 1], Table1.[Test Field 2], Table2.[Test Field 1], Table2.[Test Field 2]
FROM Table1 INNER JOIN Table2 ON Table1.[Test Field 1] = Table2.[Test Field 1]
OR (ISNULL(table1.[test field 1]) AND ISNULL(table2.[Test Field 1]));

Body:
Any ON clause in Access with more than 1 comparison needs to be wrapped in parentheses. Unfortunately, the error message you got is not very descriptive, but it's easy to fix.

SELECT Table1.[Test Field 1], Table1.[Test Field 2], Table2.[Test Field 1], Table2.[Test Field 2]
FROM Table1 INNER JOIN Table2 ON (Table1.[Test Field 1] = Table2.[Test Field 1]
OR (ISNULL(table1.[test field 1]) AND ISNULL(table2.[Test Field 1])));


问:
How to retrieve key, value pair in one shot?
Is there any way to get key, value pair in one shot ?
please suggest any logic for</p>

答:
if you want to iterate over a Map.Entry of a Map you can directly refer to the entry</p>

```<code>Map<String, Object> map = ...
for (Map.Entry entry: map.entrySet()){
    String key = entry.getKey();
    Object value = entry.getValue();
}
</code>```

Body:
if you want to iterate over a Map.Entry of a Map you can directly refer to the entry

Map<String, Object> map = ...
for (Map.Entry entry: map.entrySet()){
    String key = entry.getKey();
    Object value = entry.getValue();
}


问:
SQL Query - Count inside GROUP BY no result
I want to count the patient diagnosis per municipality and consultation per municipality:

so it should be:

diagnosis per municipality + consultation per municipality

```<code>SELECT COUNT(consultations.id) +
(SELECT COUNT(patientdiagnosis.id)
    FROM consultations
    LEFT JOIN patientdiagnosis
    ON patientdiagnosis.consultation_id = consultations.id
    LEFT JOIN patients
    ON consultations.patient_id = patients.id
    LEFT JOIN rcitymun
    ON patients.municipality = rcitymun.citycode
    /*GROUP BY PER MUNICIPALITY SHOULD BE HERE*/
) as encounters, rcitymun.cityname
FROM consultations
LEFT JOIN patients
ON consultations.patient_id = patients.id
LEFT JOIN rcitymun
ON patients.municipality = rcitymun.citycode
GROUP BY patients.municipality;
</code>```

current output:

```<code>encounters         municipality
10323                 BATAC
10423                 NUEVA ERA
</code>```

the encounter data is huge because it's counting all of the diagnosis instead of per municipality

what i want is to count the diagnosis per municipality.

desired output is something like this:

```<code>encounters         municipality
105                   BATAC
70                   NUEVA ERA
</code>```

答:
It may be possible to reduce this by one subquery, but often it is best to start with independently grouped subqueries. </p>

```<code>SELECT
       rcitymun.cityname
     , SUM(c.consult_count) consult_count
     , SUM(d.diag_count) diag_count
FROM patients
INNER JOIN rcitymun ON patients.municipality = rcitymun.citycode
LEFT JOIN (
      SELECT
            consultations.patient_id
          , COUNT(*) consult_count
      FROM consultations
      GROUP BY
            consultations.patient_id
) c ON patients.id = c.patient_id
LEFT JOIN (
      SELECT
            consultations.patient_id
          , COUNT(*) diag_count
      FROM consultations
      INNER JOIN patientdiagnosis ON patientdiagnosis.consultation_id = consultations.id
      GROUP BY
            consultations.patient_id
) d ON patients.id = d.patient_id
GROUP BY
       rcitymun.cityname
</code>```

Body:
I want to count the patient diagnosis per municipality and consultation per municipality:

so it should be:

diagnosis per municipality + consultation per municipality

SELECT COUNT(consultations.id) +
(SELECT COUNT(patientdiagnosis.id)
    FROM consultations
    LEFT JOIN patientdiagnosis
    ON patientdiagnosis.consultation_id = consultations.id
    LEFT JOIN patients
    ON consultations.patient_id = patients.id
    LEFT JOIN rcitymun
    ON patients.municipality = rcitymun.citycode
    /*GROUP BY PER MUNICIPALITY SHOULD BE HERE*/
) as encounters, rcitymun.cityname
FROM consultations
LEFT JOIN patients
ON consultations.patient_id = patients.id
LEFT JOIN rcitymun
ON patients.municipality = rcitymun.citycode
GROUP BY patients.municipality;

current output:

encounters         municipality
10323                 BATAC
10423                 NUEVA ERA

the encounter data is huge because it's counting all of the diagnosis instead of per municipality

what i want is to count the diagnosis per municipality.

desired output is something like this:

encounters         municipality
105                   BATAC
70                   NUEVA ERA

Body:
It may be possible to reduce this by one subquery, but often it is best to start with independently grouped subqueries.

SELECT
       rcitymun.cityname
     , SUM(c.consult_count) consult_count
     , SUM(d.diag_count) diag_count
FROM patients
INNER JOIN rcitymun ON patients.municipality = rcitymun.citycode
LEFT JOIN (
      SELECT
            consultations.patient_id
          , COUNT(*) consult_count
      FROM consultations
      GROUP BY
            consultations.patient_id
) c ON patients.id = c.patient_id
LEFT JOIN (
      SELECT
            consultations.patient_id
          , COUNT(*) diag_count
      FROM consultations
      INNER JOIN patientdiagnosis ON patientdiagnosis.consultation_id = consultations.id
      GROUP BY
            consultations.patient_id
) d ON patients.id = d.patient_id
GROUP BY
       rcitymun.cityname


问:
Android Application not installed error
I have created one application in AndroidStudio ,I used my Sony mobile as a ADB. The Application works fine in my mobile, also I generated the signed APK but the problem is when i try to install that it says, application not installed.Then I tried with my friend mobile it remains the same.we are using the same SDK OS.Currently am using Android studio 2.3 version.I have tried the build gradle method also,but not working.Can anyone help me?

答: If you're using Android Studio 3.0 then go to Build option and click "Build Apk" option and generate the debug apk first and install it on device.</p>

Title: Android Application not installed error


问:
Python input validation?
I have a simple input validation code asking the user for either ACT or SAT.

```<code>test=input("Are you taking SAT or ACT?..")
while test!=("SAT" or "ACT"):
    print("error")
    test=input("Are you taking SAT or ACT?..")
</code>```

It seems to work correctly for "SAT" which is in front on line 2, but not ACT! When I type in ACT in the module it will print "error" like it was false. What is my flaw here? Logic? Syntax? Semantic? What can I do to fix it?

Thank you.

答:
I don't think that this statement is valid:

```<code>test!=("SAT" or "ACT")
</code>```

You may use

```<code>test != "SAT" and test != "ACT"
</code>```

Or use in operator:

```<code>test=input("Are you taking SAT or ACT?..")
while test not in ("SAT", "ACT"):
    print("error")
    test=input("Are you taking SAT or ACT?..")
</code>```

Title: Python input validation?

Body:
I have a simple input validation code asking the user for either ACT or SAT.

test=input("Are you taking SAT or ACT?..")
while test!=("SAT" or "ACT"):
    print("error")
    test=input("Are you taking SAT or ACT?..")

It seems to work correctly for "SAT" which is in front on line 2, but not ACT! When I type in ACT in the module it will print "error" like it was false. What is my flaw here? Logic? Syntax? Semantic? What can I do to fix it?

Thank you.

Body:
I don't think that this statement is valid:

test!=("SAT" or "ACT")

You may use

test != "SAT" and test != "ACT"

Or use in operator:

test=input("Are you taking SAT or ACT?..")
while test not in ("SAT", "ACT"):
    print("error")
    test=input("Are you taking SAT or ACT?..")


问:
Is there a shorter way for if-else chains?
```<code>if (80 <= m <= 100):
    g = "A"
elif (70 <= m < 80):
    g = "B"
elif (60 <= m < 70):
    g = "C"
elif (50 <= m < 60):
    g = "D"
elif (m < 50):
    g = "U"
</code>```

This is basically a grade measuring piece of code that takes in value m, meaning mark, and obtains grade g. Is there a shorter not necessarily more pythonic way for the same purpose?

Thanks in advance.

答:
Here's another variant, apart from the many already posted:

```<code>marks = [0, 50, 60, 70, 80, 100]
grades = ["U", "D", "C", "B", "A"]
g = [grades[i] for i in range(len(grades)) if ((m >= marks[i]) and (m < marks[i+1])) ][0]
</code>```

The current student's marks are in m and the grade is put in g.

Body:
if (80 <= m <= 100):
    g = "A"
elif (70 <= m < 80):
    g = "B"
elif (60 <= m < 70):
    g = "C"
elif (50 <= m < 60):
    g = "D"
elif (m < 50):
    g = "U"

This is basically a grade measuring piece of code that takes in value m, meaning mark, and obtains grade g. Is there a shorter not necessarily more pythonic way for the same purpose?

Thanks in advance.

Body:
Here's another variant, apart from the many already posted:

marks = [0, 50, 60, 70, 80, 100]
grades = ["U", "D", "C", "B", "A"]
g = [grades[i] for i in range(len(grades)) if ((m >= marks[i]) and (m < marks[i+1])) ][0]

The current student's marks are in m and the grade is put in g.


问:
instanceof operator Vs obj.constructor
I want to know if is there any difference between these two methods of checking whether an object is an instance of a class/constructor. I searched about it and found these two ways.

```<code>obj instanceof SomeConstructor

obj.constructor === SomeConstructor
</code>```

So my questions are:
Is there any difference between the two?

Which one is a better practice?

Also, Is there any other way better than these two?

答:
Found this on web,

instanceof

The instanceof operator tests whether the prototype property of a constructor appears anywhere in the prototype chain of an object.

constructor

Returns a reference to the Object constructor function that created the instance object. Note that the value of this property is a reference to the function itself, not a string containing the function's name.

Reference

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor

Title: instanceof operator Vs obj.constructor

Body:
I want to know if is there any difference between these two methods of checking whether an object is an instance of a class/constructor. I searched about it and found these two ways.

obj instanceof SomeConstructor

obj.constructor === SomeConstructor

So my questions are:
Is there any difference between the two?

Which one is a better practice?

Also, Is there any other way better than these two?


问:
Domino Designer Plugin Ant class path
I've build an osgi plug-in to wrap a jar files. I've been following this guide.

In the last step, I can´t “Build all” to generate the update site because an error said that couldn't find the ant classpath

Any idea?
Thanks

The version that i'm using is Release 9.0.1FP9
Revision 20170815.0729-FP9 (Release 9.0.1FP9)

答:
Try running Ant on the command line to see the full output. Here is a GitHub project showing specifically how to run Ant tasks for Domino.

Here also are some details about setting the Ant classpath for a given build in build.xml:

```<code><!-- create our ant classpath using the fileset task -->
<path id="class.path">

  <!-- include all jars in the lib directory and all sub-directories -->
  <fileset dir="${lib.dir}">
    <include name="**/*.jar" />
  </fileset>

</path>
</code>```

I find that Eclipse plugins often just assemble and execute terminal commands, but when they fail they tend not to be great at making clear the cause. Often, running the equivalent commands in the terminal (be they ant, maven, etc.) is clearer when failures occur because you'll see the full error output. And it gives you the added benefit--sometimes--of having a clearer understanding of what's happening under the hood.

Title: Domino Designer Plugin Ant class path

Body:
Try running Ant on the command line to see the full output. Here is a GitHub project showing specifically how to run Ant tasks for Domino.

Here also are some details about setting the Ant classpath for a given build in build.xml:

<!-- create our ant classpath using the fileset task -->
<path id="class.path">

  <!-- include all jars in the lib directory and all sub-directories -->
  <fileset dir="${lib.dir}">
    <include name="**/*.jar" />
  </fileset>

</path>

I find that Eclipse plugins often just assemble and execute terminal commands, but when they fail they tend not to be great at making clear the cause. Often, running the equivalent commands in the terminal (be they ant, maven, etc.) is clearer when failures occur because you'll see the full error output. And it gives you the added benefit--sometimes--of having a clearer understanding of what's happening under the hood.


问:
Wordpress - WPBakery Page Builder - can I setup several builders for a single page?
I need to setup 2 content boxes for the page. The first one will be shown inside the page header, the second one - in the page content. The design is quite complex, so I can't use one content box and just add some styles. The main issue is I need the 2nd content box to be manageable via WPBakery Page Builder as well, and it's seems like there's no such feature. Perhaps I could create the custom element, add it to the 1st row, then hook to the the_content filter, and just remove the row with that element. Then in the header make almost the same thing: check if there's custom element in the post content, then just cut out everything and just echo my element. But I'm afraid the JS and the styling will be broken. Maybe there're some addons for this?

答:
I have not found the way I can use 2 editors, so I decided to make the row with class "header" appear in the header and the other content - in the content section.</p>

```<code><?php //functions.php
/* define which class should we use to separate the content */
define("CLASS_FOR_HEADER", "header");
define("HEADER_SECTION_REGEX", "/\[vc_row([^\w\]])el_class=(?:\"|'|)(.*?)".CLASS_FOR_HEADER."(.*?)(?:\"|'|)(.*?)\]+(.*?|\n)+\[\/vc_row]/");

/* Used in the header to leave only header section.
 * header-part-content is a custom action called in the header by
 * apply_filters('header-part-content', $post->post_content);
 */
 add_filter('header-part-content', function ($content) {
    $matches = [];
    preg_match_all(HEADER_SECTION_REGEX, $content, $matches);
    if (empty($matches) || empty($matches[0])) {
        return "";
    }
    return do_shortcode(implode($matches[0]));
}, 10, 1);

/* Used to cut the header elements out of the content */
add_filter('the_content', function ($content) {
    return preg_replace(HEADER_SECTION_REGEX, "", $content);
}, 1);
</code>```

Body:
I have not found the way I can use 2 editors, so I decided to make the row with class "header" appear in the header and the other content - in the content section.

<?php //functions.php
/* define which class should we use to separate the content */
define("CLASS_FOR_HEADER", "header");
define("HEADER_SECTION_REGEX", "/\[vc_row([^\w\]])el_class=(?:\"|'|)(.*?)".CLASS_FOR_HEADER."(.*?)(?:\"|'|)(.*?)\]+(.*?|\n)+\[\/vc_row]/");

/* Used in the header to leave only header section.
 * header-part-content is a custom action called in the header by
 * apply_filters('header-part-content', $post->post_content);
 */
 add_filter('header-part-content', function ($content) {
    $matches = [];
    preg_match_all(HEADER_SECTION_REGEX, $content, $matches);
    if (empty($matches) || empty($matches[0])) {
        return "";
    }
    return do_shortcode(implode($matches[0]));
}, 10, 1);

/* Used to cut the header elements out of the content */
add_filter('the_content', function ($content) {
    return preg_replace(HEADER_SECTION_REGEX, "", $content);
}, 1);