问:
Homebrew is not working anymore. "The i18n gem is not available"
I am not able to use homebrew anymore on my mac (version 10.15.2). When I try to use brew in terminal I get the error below.

It seems like I have to add the i18n Gemfile, but I am not familiar with Ruby.

```<code>The i18n gem is not available. Please add it to your Gemfile and run bundle install
Traceback (most recent call last):
    34: from /usr/local/Homebrew/Library/Homebrew/brew.rb:23:in `<main>'
    33: from /usr/local/Homebrew/Library/Homebrew/brew.rb:23:in `require_relative'
    32: from /usr/local/Homebrew/Library/Homebrew/global.rb:14:in `<top (required)>'
    31: from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'
    30: from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'
    29: from /usr/local/Homebrew/Library/Homebrew/vendor/bundle/ruby/2.6.0/gems/activesupport-6.0.2.1/lib/active_support/core_ext/numeric/time.rb:3:in `<top (required)>'
    28: from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'
    27: from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'
    26: from /usr/local/Homebrew/Library/Homebrew/vendor/bundle/ruby/2.6.0/gems/activesupport-6.0.2.1/lib/active_support/duration.rb:3:in `<top (required)>'
    25: from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'
    24: from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'
    23: from /usr/local/Homebrew/Library/Homebrew/vendor/bundle/ruby/2.6.0/gems/activesupport-6.0.2.1/lib/active_support/core_ext/array/conversions.rb:3:in `<top (required)>'
    22: from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'
    21: from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'
    20: from /usr/local/Homebrew/Library/Homebrew/vendor/bundle/ruby/2.6.0/gems/activesupport-6.0.2.1/lib/active_support/xml_mini.rb:8:in `<top (required)>'
    19: from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'
    18: from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'
    17: from /usr/local/Homebrew/Library/Homebrew/vendor/bundle/ruby/2.6.0/gems/activesupport-6.0.2.1/lib/active_support/core_ext/string/inflections.rb:3:in `<top (required)>'
    16: from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'
    15: from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'
    14: from /usr/local/Homebrew/Library/Homebrew/vendor/bundle/ruby/2.6.0/gems/activesupport-6.0.2.1/lib/active_support/inflector/methods.rb:3:in `<top (required)>'
    13: from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'
    12: from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'
    11: from /usr/local/Homebrew/Library/Homebrew/vendor/bundle/ruby/2.6.0/gems/activesupport-6.0.2.1/lib/active_support/inflections.rb:3:in `<top (required)>'
    10: from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'
     9: from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'
     8: from /usr/local/Homebrew/Library/Homebrew/vendor/bundle/ruby/2.6.0/gems/activesupport-6.0.2.1/lib/active_support/inflector/inflections.rb:4:in `<top (required)>'
     7: from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'
     6: from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'
     5: from /usr/local/Homebrew/Library/Homebrew/vendor/bundle/ruby/2.6.0/gems/activesupport-6.0.2.1/lib/active_support/i18n.rb:7:in `<top (required)>'
     4: from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'
     3: from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'
     2: from /usr/local/Homebrew/Library/Homebrew/vendor/bundle/ruby/2.6.0/gems/i18n-1.8.2/lib/i18n.rb:5:in `<top (required)>'
     1: from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'
/System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require': cannot load such file -- i18n/version (LoadError)
</code>```

答:
I fixed the problem by simply reinstalling homebrew. I think it had to do with my last mac update.</p>

```<code>/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
</code>```

Body:
I am not able to use homebrew anymore on my mac (version 10.15.2). When I try to use brew in terminal I get the error below.

It seems like I have to add the i18n Gemfile, but I am not familiar with Ruby.

The i18n gem is not available. Please add it to your Gemfile and run bundle install
Traceback (most recent call last):
    34: from /usr/local/Homebrew/Library/Homebrew/brew.rb:23:in `'
    33: from /usr/local/Homebrew/Library/Homebrew/brew.rb:23:in `require_relative'
    32: from /usr/local/Homebrew/Library/Homebrew/global.rb:14:in `<top (required)>'
    31: from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'
    30: from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'
    29: from /usr/local/Homebrew/Library/Homebrew/vendor/bundle/ruby/2.6.0/gems/activesupport-6.0.2.1/lib/active_support/core_ext/numeric/time.rb:3:in `<top (required)>'
    28: from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'
    27: from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'
    26: from /usr/local/Homebrew/Library/Homebrew/vendor/bundle/ruby/2.6.0/gems/activesupport-6.0.2.1/lib/active_support/duration.rb:3:in `<top (required)>'
    25: from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'
    24: from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'
    23: from /usr/local/Homebrew/Library/Homebrew/vendor/bundle/ruby/2.6.0/gems/activesupport-6.0.2.1/lib/active_support/core_ext/array/conversions.rb:3:in `<top (required)>'
    22: from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'
    21: from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'
    20: from /usr/local/Homebrew/Library/Homebrew/vendor/bundle/ruby/2.6.0/gems/activesupport-6.0.2.1/lib/active_support/xml_mini.rb:8:in `<top (required)>'
    19: from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'
    18: from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'
    17: from /usr/local/Homebrew/Library/Homebrew/vendor/bundle/ruby/2.6.0/gems/activesupport-6.0.2.1/lib/active_support/core_ext/string/inflections.rb:3:in `<top (required)>'
    16: from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'
    15: from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'
    14: from /usr/local/Homebrew/Library/Homebrew/vendor/bundle/ruby/2.6.0/gems/activesupport-6.0.2.1/lib/active_support/inflector/methods.rb:3:in `<top (required)>'
    13: from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'
    12: from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'
    11: from /usr/local/Homebrew/Library/Homebrew/vendor/bundle/ruby/2.6.0/gems/activesupport-6.0.2.1/lib/active_support/inflections.rb:3:in `<top (required)>'
    10: from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'
     9: from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'
     8: from /usr/local/Homebrew/Library/Homebrew/vendor/bundle/ruby/2.6.0/gems/activesupport-6.0.2.1/lib/active_support/inflector/inflections.rb:4:in `<top (required)>'
     7: from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'
     6: from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'
     5: from /usr/local/Homebrew/Library/Homebrew/vendor/bundle/ruby/2.6.0/gems/activesupport-6.0.2.1/lib/active_support/i18n.rb:7:in `<top (required)>'
     4: from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'
     3: from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'
     2: from /usr/local/Homebrew/Library/Homebrew/vendor/bundle/ruby/2.6.0/gems/i18n-1.8.2/lib/i18n.rb:5:in `<top (required)>'
     1: from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'
/System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require': cannot load such file -- i18n/version (LoadError)

Body:
I fixed the problem by simply reinstalling homebrew. I think it had to do with my last mac update.

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"


来源: stackexchange

问:
How to Filter a txt file in java
As input i have a File containing a list of rooms.
Each room has the following information: (1 line of the file)

```<code>ID;name;phonenumber;PIN e.g.:
1234;A 0.12;1234;123456789 (ID is same as [first] phonenumber)
2345;A 0.12;2345;123456789 (A room can have more than 1 phonenumber - in a new line like in the example)
</code>```

Now i need a java program which returns a list like this:

```<code>Example Input:
1127,A 0.01,1127,1
2476,A 0.01,2476,1
2309,A 0.01,2309,1
2306,A 0.01,2306,1
2706,A 0.01,2706,1
2757,A 0.01,2757,1
Generates Output:
1127,A 0.01,1127,2476,2309,2306,2706,2757,1
</code>```

ID;name;phonenumber1;...;phonenumberN;PIN

This code (without main function) adds a second phone number to the existing one, if the rooms from 2 lines are the same.

```<code>public static String duplicateNumbers(String s, String x) {

    String result = s;
    if(compareString(s, x)) {
         result = result.substring(0, 21)
                 + x.charAt(21) + x.charAt(22) + x.charAt(23) + x.charAt(24)
                 + result.substring(20);
    }
    return result;
}

public static boolean compareString(String s, String x) {
    for(int i = 5; i < 10; i++) {
        if(s.charAt(i) != x.charAt(i)) return false;
    }
    return true;
}
</code>```

ß

答:
I hope this is gonna be helpful for what you need. I used Apache Common CSV. You can find more info here https://www.baeldung.com/apache-commons-csv

    File.csv
    ```
    ID;name;phonenumber;PIN;
    1127;A 0.01;1127;1;
    2476;A 0.01;2476;1;
    2309;A 0.01;2309;1;
    2306;A 0.01;2306;1;
    2706;A 0.01;2706;1;
    2757;A 0.01;2757;1;
    2722;B 0.01;2722;1;
    2723;B 0.01;2723;1;
    ```

    Unit Test in Spring Boot

```<code>@Test
public void testForAlphaOmega() throws IOException {
    @Getter
    class ROOM {
        String id;
        String name;
        String phoneNumber;
        String pin;

        private ROOM(String id, String name, String phoneNumber, String pin){
            this.id = id;
            this.name = name;
            this.phoneNumber = phoneNumber;
            this.pin = pin;
        }
        private ROOM(CSVRecord record){
            this.id = record.get("ID");
            this.name = record.get("name");
            this.phoneNumber = record.get("phoneNumber");
            this.pin = record.get("PIN");
        }
    }
    try (
        Reader reader = Files.newBufferedReader(Paths.get("....PATH_OF_FILE"));
        CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT
        .withHeader("ID", "name", "phoneNumber", "PIN")
        .withIgnoreHeaderCase()
        .withFirstRecordAsHeader()
        .withDelimiter(';')
        .withTrim())
    ) {
        List<ROOM> rooms = new ArrayList<>();
        csvParser.getRecords().stream().map(ROOM::new).collect(groupingBy(ROOM::getName)).forEach((key,val) -> rooms.add(new ROOM(val.get(0).getId(), val.get(0).getName(), val.stream().map(ROOM::getPhoneNumber).collect(Collectors.joining(",")),val.get(0).getPin())));
        rooms.forEach(item -> System.out.println(item.getId() + ";" + item.getName() +";" + item.getPhoneNumber() + ";" + item.getPin()));
    }
}
</code>```

Result
    ```
    2722;B 0.01;2722,2723;1
    1127;A 0.01;1127,2476,2309,2306,2706,2757;1
    ```

ContentLicense: CC BY-SA 4.0

Title: How to Filter a txt file in java

Body:
As input i have a File containing a list of rooms.
Each room has the following information: (1 line of the file)

ID;name;phonenumber;PIN e.g.:
1234;A 0.12;1234;123456789 (ID is same as [first] phonenumber)
2345;A 0.12;2345;123456789 (A room can have more than 1 phonenumber - in a new line like in the example)

Now i need a java program which returns a list like this:

Example Input:
1127,A 0.01,1127,1
2476,A 0.01,2476,1
2309,A 0.01,2309,1
2306,A 0.01,2306,1
2706,A 0.01,2706,1
2757,A 0.01,2757,1
Generates Output:
1127,A 0.01,1127,2476,2309,2306,2706,2757,1

ID;name;phonenumber1;...;phonenumberN;PIN

This code (without main function) adds a second phone number to the existing one, if the rooms from 2 lines are the same.

public static String duplicateNumbers(String s, String x) {

    String result = s;
    if(compareString(s, x)) {
         result = result.substring(0, 21)
                 + x.charAt(21) + x.charAt(22) + x.charAt(23) + x.charAt(24)
                 + result.substring(20);
    }
    return result;
}

public static boolean compareString(String s, String x) {
    for(int i = 5; i < 10; i++) {
        if(s.charAt(i) != x.charAt(i)) return false;
    }
    return true;
}

ß

Body:
I hope this is gonna be helpful for what you need. I used Apache Common CSV. You can find more info here https://www.baeldung.com/apache-commons-csv

    File.csv

    ID;name;phonenumber;PIN;
    1127;A 0.01;1127;1;
    2476;A 0.01;2476;1;
    2309;A 0.01;2309;1;
    2306;A 0.01;2306;1;
    2706;A 0.01;2706;1;
    2757;A 0.01;2757;1;
    2722;B 0.01;2722;1;
    2723;B 0.01;2723;1;

    Unit Test in Spring Boot

@Test
public void testForAlphaOmega() throws IOException {
    @Getter
    class ROOM {
        String id;
        String name;
        String phoneNumber;
        String pin;

        private ROOM(String id, String name, String phoneNumber, String pin){
            this.id = id;
            this.name = name;
            this.phoneNumber = phoneNumber;
            this.pin = pin;
        }
        private ROOM(CSVRecord record){
            this.id = record.get("ID");
            this.name = record.get("name");
            this.phoneNumber = record.get("phoneNumber");
            this.pin = record.get("PIN");
        }
    }
    try (
        Reader reader = Files.newBufferedReader(Paths.get("....PATH_OF_FILE"));
        CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT
        .withHeader("ID", "name", "phoneNumber", "PIN")
        .withIgnoreHeaderCase()
        .withFirstRecordAsHeader()
        .withDelimiter(';')
        .withTrim())
    ) {
        List<ROOM> rooms = new ArrayList<>();
        csvParser.getRecords().stream().map(ROOM::new).collect(groupingBy(ROOM::getName)).forEach((key,val) -> rooms.add(new ROOM(val.get(0).getId(), val.get(0).getName(), val.stream().map(ROOM::getPhoneNumber).collect(Collectors.joining(",")),val.get(0).getPin())));
        rooms.forEach(item -> System.out.println(item.getId() + ";" + item.getName() +";" + item.getPhoneNumber() + ";" + item.getPin()));
    }
}

Result

    2722;B 0.01;2722,2723;1
    1127;A 0.01;1127,2476,2309,2306,2706,2757;1


问:
Two's complement in libtommath library
I am using libtommath library for bigInteger calculation for my iphone application. I have used libtommath library to implement Diffie-Hellman key exchange.

On server sider, the code is in java, which uses Biginteger class.  In Biginteger class, there is a function toByteArray. This function takes the two's complement and returns the byte array.

I want to do similar stuff on my iphone app. Can anyone tell me how to take two's complement in big integer calculated by libtommath.

In other words,
Say Output of my calculation is in NSString *bobkey = "325522525225322525234444445646456564564654654654654654654744797239797297421749179472974721974127439729749274972974927497297439274972974927497274927497329473927497294729847289749827917974291734927149792749724972397927394797324927493274927";

Now how do i get two's complement of above number that matches with the byte array of BigInteger ?

答:
Can you clarify what you're trying to do? Part of twos complement is the precision you're dealing with, which is theoretically unlimited in BigNum packages.

Regardless, in most numerical representations, the two's complement is just the binary representation of the negated value minus 1. i.e. -1 == two's complement of 0 (or 2^n - 1 - 0 = complement(0))

ContentLicense: CC BY-SA 3.0

Title: Two's complement in libtommath library


问:
managing items in a List based off some conditions in C#
I have a couple of lists  List<OldData> oldItems = new List<OldData>(); and List<NewData> newItems = new List<NewData>();

What I am trying to achieve here is to avoid the possibility of some redundant data coming in hence to check with some conditions before values are added into the list.

First up in the oldItems  I will have some values stored and in the newItems list I will have a completely different set of values stored but it could always be the case that the newItems list may have some values that are already existing in the  oldItems list.

The two variables that are in use are a Name variable and a path variable which stores a certain path

So First I want to check if there are any values where the name in the old items List is equal to the name in the new Items List ,
if There is an Item I want to check if the respective Path variable of the corresponding items are same ,

if it is same I can simply keep that item the way it is in the OldItems list , if that happens to be different I will Remove that from the old Items List (and later use the item in the new Item List)

So all the above in a nut shell ,

I want to check for in the Old Items List where there is a Name Corresponding to it in the new Item List
If there is , I want to check if the corresponding values in the Path variable for the two items with the same name from the two List are the same or different

I have made a simple dummy application to demo this but really stuck on how i can implement the logic

any suggestion ?

```<code>class Program
{
    static void Main(string[] args)
    {

        List<OldData> oldItems = new List<OldData>();

        OldData oldData1 = new OldData();
        oldData1.Name = "Test01";
        oldData1.OriginalPath = "D:/Temp01";

        oldItems.Add(oldData1);

        OldData oldData2 = new OldData();
        oldData1.Name = "Test02";
        oldData1.OriginalPath = "D:/Temp02";
        oldItems.Add(oldData2);

        List<NewData> newItems = new List<NewData>();

        NewData newData1 = new NewData();
        newData1.Name = "Test01";
        newData1.OriginalPath = "D:/Temp01";

        newItems.Add(newData1);

        NewData newData2 = new NewData();
        oldData1.Name = "Test05";
        oldData1.OriginalPath = "D:/Temp05";
        newItems.Add(newData2);

        foreach (var item in oldItems)
        {
            //Check if there are any Names which are same from the new Item list
            //If if there is such an item check if the OriginalPath variable is the same iin both
            //If yes => Remove that particular item from the Old data List
            //If Not => Keep that Item in  the old data List
        }
    }
}

class OldData
{
    public string Name { get; set; }
    public string OriginalPath { get; set; }
}

class NewData
{
    public string Name { get; set; }
    public string OriginalPath { get; set; }
}
</code>```

In this case since the value Test01 is common to both List It will check if the path variable values corresponding to both items are the same or not

答:
You're comparing strings so the == operator will work fine.

Here's a simple answer without using LINQ.
Just a foreach loop with 2 conditions:

```<code>    for (int i = oldItems.Count - 1; i >= 0; i--)
    {
        OldData currentOldItem = oldItems[i] as OldData;
        foreach (var newItem in newItems) {
            if (currentOldItem.Name == newItem.Name) {
                if (currentOldItem.OriginalPath == newItem.OriginalPath) {
                    oldItems.RemoveAt(i);
                }
            }
        }
    }
</code>```

Body:
I have a couple of lists  List<OldData> oldItems = new List<OldData>(); and List<NewData> newItems = new List<NewData>();

What I am trying to achieve here is to avoid the possibility of some redundant data coming in hence to check with some conditions before values are added into the list.

First up in the oldItems  I will have some values stored and in the newItems list I will have a completely different set of values stored but it could always be the case that the newItems list may have some values that are already existing in the  oldItems list.

The two variables that are in use are a Name variable and a path variable which stores a certain path

So First I want to check if there are any values where the name in the old items List is equal to the name in the new Items List ,
if There is an Item I want to check if the respective Path variable of the corresponding items are same ,

if it is same I can simply keep that item the way it is in the OldItems list , if that happens to be different I will Remove that from the old Items List (and later use the item in the new Item List)

So all the above in a nut shell ,

I want to check for in the Old Items List where there is a Name Corresponding to it in the new Item List
If there is , I want to check if the corresponding values in the Path variable for the two items with the same name from the two List are the same or different

I have made a simple dummy application to demo this but really stuck on how i can implement the logic

any suggestion ?

class Program
{
    static void Main(string[] args)
    {

        List<OldData> oldItems = new List<OldData>();

        OldData oldData1 = new OldData();
        oldData1.Name = "Test01";
        oldData1.OriginalPath = "D:/Temp01";

        oldItems.Add(oldData1);

        OldData oldData2 = new OldData();
        oldData1.Name = "Test02";
        oldData1.OriginalPath = "D:/Temp02";
        oldItems.Add(oldData2);

        List<NewData> newItems = new List<NewData>();

        NewData newData1 = new NewData();
        newData1.Name = "Test01";
        newData1.OriginalPath = "D:/Temp01";

        newItems.Add(newData1);

        NewData newData2 = new NewData();
        oldData1.Name = "Test05";
        oldData1.OriginalPath = "D:/Temp05";
        newItems.Add(newData2);

        foreach (var item in oldItems)
        {
            //Check if there are any Names which are same from the new Item list
            //If if there is such an item check if the OriginalPath variable is the same iin both
            //If yes => Remove that particular item from the Old data List
            //If Not => Keep that Item in  the old data List
        }
    }
}

class OldData
{
    public string Name { get; set; }
    public string OriginalPath { get; set; }
}

class NewData
{
    public string Name { get; set; }
    public string OriginalPath { get; set; }
}

In this case since the value Test01 is common to both List It will check if the path variable values corresponding to both items are the same or not

Body:
You're comparing strings so the == operator will work fine.

Here's a simple answer without using LINQ.
Just a foreach loop with 2 conditions:

    for (int i = oldItems.Count - 1; i >= 0; i--)
    {
        OldData currentOldItem = oldItems[i] as OldData;
        foreach (var newItem in newItems) {
            if (currentOldItem.Name == newItem.Name) {
                if (currentOldItem.OriginalPath == newItem.OriginalPath) {
                    oldItems.RemoveAt(i);
                }
            }
        }
    }


问:
How do I throw an exception in my Java code?
I got a method that prints out the animals' names.
I now need an error to be printed out if the id is not one of the given ones.
How does it work?</p>

```<code>class Methode {
    static final int DEER = 0;
    static final int BIRD = 1;
    static final int COW = 2;
    static final int PIG = 3;

    public static void main(String[] args) {
            printAnimal();
    }

    public static void printAnimal (int id) {
        if (id == DEER) {
            System.out.println("Deer");
        }
        else if (id == BIRD) {
            System.out.println("Bird");
        }
        else if (id == COW) {
                System.out.println("COW");
        }
        else if (id == PIG) {
            System.out.println("Pig");
        }
    }
}
</code>```

答:
If by error you mean an Exception (otherwise I don't know why you didn't simply printed an "error" message like you did in your else if branches), then you need to create a custom class which extends Exception and throw it in a new else branch. Here is an example:

Exception:

```<code>public class NoSuchAnimalException extends Exception {
 public NoSuchAnimalException(String message) {
     super(message);
 }
}
</code>```

Test:

```<code>public static void printAnimal(int id) throws NoSuchAnimalException {
    if (id == DEER) {
        System.out.println("Deer");
    } else if (id == BIRD) {
        System.out.println("Bird");
    } else if (id == COW) {
        System.out.println("COW");
    } else if (id == PIG) {
        System.out.println("Pig");
    } else {
        throw new NoSuchAnimalException("No such animal");
    }
}

public static void main(String[] args) {
    try {
        printAnimal(6);
    } catch (NoSuchAnimalException e) {
        System.out.println(e.getMessage());
    }
}
</code>```

The exception will be thrown in the last else (the id provided in method call doesn't meet the previous requirements) and will be handled in the public static void main() method.

Body:
I got a method that prints out the animals' names.
I now need an error to be printed out if the id is not one of the given ones.
How does it work?

class Methode {
    static final int DEER = 0;
    static final int BIRD = 1;
    static final int COW = 2;
    static final int PIG = 3;

    public static void main(String[] args) {
            printAnimal();
    }

    public static void printAnimal (int id) {
        if (id == DEER) {
            System.out.println("Deer");
        }
        else if (id == BIRD) {
            System.out.println("Bird");
        }
        else if (id == COW) {
                System.out.println("COW");
        }
        else if (id == PIG) {
            System.out.println("Pig");
        }
    }
}

Body:
If by error you mean an Exception (otherwise I don't know why you didn't simply printed an "error" message like you did in your else if branches), then you need to create a custom class which extends Exception and throw it in a new else branch. Here is an example:

Exception:

public class NoSuchAnimalException extends Exception {
 public NoSuchAnimalException(String message) {
     super(message);
 }
}

Test:

public static void printAnimal(int id) throws NoSuchAnimalException {
    if (id == DEER) {
        System.out.println("Deer");
    } else if (id == BIRD) {
        System.out.println("Bird");
    } else if (id == COW) {
        System.out.println("COW");
    } else if (id == PIG) {
        System.out.println("Pig");
    } else {
        throw new NoSuchAnimalException("No such animal");
    }
}

public static void main(String[] args) {
    try {
        printAnimal(6);
    } catch (NoSuchAnimalException e) {
        System.out.println(e.getMessage());
    }
}

The exception will be thrown in the last else (the id provided in method call doesn't meet the previous requirements) and will be handled in the public static void main() method.


问:
Wordpress insert record if not exists and avoid duplicate
Hi i am trying to insert data to wordpress table its successfully added but it duplicates data each time page refreshed, i want to insert data if the is new otherwise do nothing</p>

```<code>foreach ( $response->data as $single_data ) {

    // post title
    $post_title    = $single_data->name;

    global $wpdb;

    //tablename
    $tablename = $wpdb->prefix . "posts";

    $wpdb->insert($tablename,
        array(
            'post_type'  => 'vimeo_videos',
            'post_title' => $post_title,
            'post_status' => 'publish',
        ),
        array('%s', '%s', '%s')
    );

}
</code>```

答:
Please try this. I created an array and tried this. Successfully inserted data into database. Please make it as you got your array. I hope it will be helpful for you

```<code>$response = array("title"=>array("title one",'title two'));
//echo "```";print_r($response);echo "```";exit();
foreach ( $response['title'] as $single_data ) {
    $post_title    = $single_data;
    global $wpdb;
    $allPosts = $wpdb->get_results( $wpdb->prepare("SELECT * FROM $wpdb->posts WHERE post_title LIKE '%s'", '%'. $wpdb->esc_like( $post_title ) .'%') );
//echo "```";print_r($allPosts);echo "```";exit();

if (count($allPosts) == 0) {
    $tablename = $wpdb->prefix . "posts";
    $wpdb->insert($tablename,
        array(
            'post_type'  => 'vimeo_videos',
            'post_title' => $post_title,
            'post_status' => 'publish',
        ),
        array('%s', '%s', '%s')
    );
} else {
    /*Do whatever you like */
}
</code>```

}

Body:
Hi i am trying to insert data to wordpress table its successfully added but it duplicates data each time page refreshed, i want to insert data if the is new otherwise do nothing

foreach ( $response->data as $single_data ) {

    // post title
    $post_title    = $single_data->name;

    global $wpdb;

    //tablename
    $tablename = $wpdb->prefix . "posts";

    $wpdb->insert($tablename,
        array(
            'post_type'  => 'vimeo_videos',
            'post_title' => $post_title,
            'post_status' => 'publish',
        ),
        array('%s', '%s', '%s')
    );

}

Body:
Please try this. I created an array and tried this. Successfully inserted data into database. Please make it as you got your array. I hope it will be helpful for you

$response = array("title"=>array("title one",'title two'));
//echo "<pre>";print_r($response);echo "</pre>";exit();
foreach ( $response['title'] as $single_data ) {
    $post_title    = $single_data;
    global $wpdb;
    $allPosts = $wpdb->get_results( $wpdb->prepare("SELECT * FROM $wpdb->posts WHERE post_title LIKE '%s'", '%'. $wpdb->esc_like( $post_title ) .'%') );
//echo "<pre>";print_r($allPosts);echo "</pre>";exit();

if (count($allPosts) == 0) {
    $tablename = $wpdb->prefix . "posts";
    $wpdb->insert($tablename,
        array(
            'post_type'  => 'vimeo_videos',
            'post_title' => $post_title,
            'post_status' => 'publish',
        ),
        array('%s', '%s', '%s')
    );
} else {
    /*Do whatever you like */
}

}


问:
No console output in Flutter IntelliJ plugin?
I am using Flutter + the Android Studio/IntelliJ plugin for Flutter. When I run my application in the IDE, there seems to be an empty console window so I cannot view my print statements from that window.

I am able to view output in the tomcat logs, so I am not blocked by this problem. Is there any reason why there is no output/functionality is my run window?

Update

Tried running using flutter run on commandline and I get my print statements on there. So this is just limited to Android Studio.

What I am expecting

What I am getting

Versions and App Information

Flutter Doctor Output

```<code>D:\manual-applications\flutter\bin\flutter.bat doctor --verbose
[√] Flutter (Channel beta, v1.0.0, on Microsoft Windows [Version 10.0.16299.785], locale en-US)
    • Flutter version 1.0.0 at D:\manual-applications\flutter
    • Framework revision 5391447fae (3 weeks ago), 2018-11-29 19:41:26 -0800
    • Engine revision 7375a0f414
    • Dart version 2.1.0 (build 2.1.0-dev.9.4 f9ebf21297)

[!] Android toolchain - develop for Android devices (Android SDK 27.0.3)
    • Android SDK at D:/android-development/sdk
    • Android NDK location not configured (optional; useful for native profiling support)
    • Platform android-27, build-tools 27.0.3
    • ANDROID_HOME = D:/android-development/sdk
    • Java binary at: D:\android-development\android-studio\jre\bin\java
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1136-b06)
    X Android license status unknown.

[√] Android Studio (version 3.2)
    • Android Studio at D:\android-development\android-studio
    • Flutter plugin version 31.3.1
    • Dart plugin version 181.5656
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1136-b06)

[!] IntelliJ IDEA Community Edition (version 2018.2)
    • IntelliJ at C:\Program Files (x86)\JetBrains\IntelliJ IDEA Community Edition 2018.2.2
    X Flutter plugin not installed; this adds Flutter specific functionality.
    X Dart plugin not installed; this adds Dart specific functionality.
    • For information about installing plugins, see
      https://flutter.io/intellij-setup/#installing-the-plugins

[√] VS Code, 64-bit edition (version 1.28.2)
    • VS Code at C:\Program Files\Microsoft VS Code
    • Flutter extension version 2.21.1

[√] Connected device (1 available)
    • Android SDK built for x86 64 • emulator-5554 • android-x64 • Android 7.1.1 (API 25) (emulator)
</code>```

答: To fix log just click on selected icon

Body:
I am using Flutter + the Android Studio/IntelliJ plugin for Flutter. When I run my application in the IDE, there seems to be an empty console window so I cannot view my print statements from that window.

I am able to view output in the tomcat logs, so I am not blocked by this problem. Is there any reason why there is no output/functionality is my run window?

Update

Tried running using flutter run on commandline and I get my print statements on there. So this is just limited to Android Studio.

What I am expecting

What I am getting

Versions and App Information

Flutter Doctor Output

D:\manual-applications\flutter\bin\flutter.bat doctor --verbose
[√] Flutter (Channel beta, v1.0.0, on Microsoft Windows [Version 10.0.16299.785], locale en-US)
    • Flutter version 1.0.0 at D:\manual-applications\flutter
    • Framework revision 5391447fae (3 weeks ago), 2018-11-29 19:41:26 -0800
    • Engine revision 7375a0f414
    • Dart version 2.1.0 (build 2.1.0-dev.9.4 f9ebf21297)

[!] Android toolchain - develop for Android devices (Android SDK 27.0.3)
    • Android SDK at D:/android-development/sdk
    • Android NDK location not configured (optional; useful for native profiling support)
    • Platform android-27, build-tools 27.0.3
    • ANDROID_HOME = D:/android-development/sdk
    • Java binary at: D:\android-development\android-studio\jre\bin\java
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1136-b06)
    X Android license status unknown.

[√] Android Studio (version 3.2)
    • Android Studio at D:\android-development\android-studio
    • Flutter plugin version 31.3.1
    • Dart plugin version 181.5656
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1136-b06)

[!] IntelliJ IDEA Community Edition (version 2018.2)
    • IntelliJ at C:\Program Files (x86)\JetBrains\IntelliJ IDEA Community Edition 2018.2.2
    X Flutter plugin not installed; this adds Flutter specific functionality.
    X Dart plugin not installed; this adds Dart specific functionality.
    • For information about installing plugins, see
      https://flutter.io/intellij-setup/#installing-the-plugins

[√] VS Code, 64-bit edition (version 1.28.2)
    • VS Code at C:\Program Files\Microsoft VS Code
    • Flutter extension version 2.21.1

[√] Connected device (1 available)
    • Android SDK built for x86 64 • emulator-5554 • android-x64 • Android 7.1.1 (API 25) (emulator)

Body: To fix log just click on selected icon


问:
WPF - View model updating property via background worker, but view is not updating some elements until focused
View model is loading data asynchronously using background worker thread in model. All properties in the model and view model raise the property changed events, and all properties are being updated in the view as expected, except 2 buttons whose IsEnabled state depends on the outcome of some properties that are loaded.

The frustrating part is that as soon as I focus on any part of the view, or set a breakpoint after the properties are updated (create a delay), then the buttons IsEnabled state is updated as expected. So it appears to be a timing issue.

Any clues as to how to the best way to solve this? I'm using mvvm-light framework, but that shouldn't matter.

I've tried binding IsEnabled to the button instead of just relying on the Command property, but that made no difference. I've confirmed via logging that view model properties are set and the PropertyChanged event is being raised for the properties associated with the buttons.

Considering sending a message using mvvm-light messenger from the view model to the view on the async completed event and then somehow? triggering a view refresh, but that seems like a kludge.

Update

Thanks to blindmeis' answer, I tested the button behaviour without the Command binding set, i.e. just binding IsEnabled property, and it works as expected!

```<code><Button
    Grid.Column="2" Content="{Binding LoadProjectsLabel}"
    VerticalAlignment="Top" HorizontalAlignment="Right"
    IsEnabled="{Binding CanLoadProjects}" />
</code>```

Obviously it's not great because I can no longer execute the command :) but as soon as I add the command back, it stops behaving:

```<code><Button
    Grid.Column="2" Content="{Binding LoadProjectsLabel}"
    VerticalAlignment="Top" HorizontalAlignment="Right"
    Command="{Binding LoadProjectsCommand}" />
</code>```

Leaving IsEnabled binding doesn't solve the problem, but that seems like a good clue.

The view model command code:

```<code>public ICommand LoadProjectsCommand
{
    get
    {
        if (_loadProjectsCommand == null)
        {
            _loadProjectsCommand = new RelayCommand(loadProjects, () => CanLoadProjects);
        }
        return _loadProjectsCommand;
    }
}
</code>```

Workaround

Wire up the Click event and avoid Command. Would be nice to solve it from the view model, but this works:

```<code><Button
    Grid.Column="2" Content="{Binding LoadProjectsLabel}"
    VerticalAlignment="Top" HorizontalAlignment="Right"
    IsEnabled="{Binding CanLoadProjects}"
    Click="loadProjects_Click"/>
</code>```

Code behind:

```<code>void loadProjects_Click(object sender, RoutedEventArgs e)
{
    SettingsViewModel vm = (SettingsViewModel)DataContext;
    vm.LoadProjectsCommand.Execute(null);
}
</code>```

答: You should bind command parameter property to any updatable property on viewmodel and can execute must use this command parameter to enable button. If command parameter's target is updated, binding will enable/disable based on return value of can excute. </p>

Body:
View model is loading data asynchronously using background worker thread in model. All properties in the model and view model raise the property changed events, and all properties are being updated in the view as expected, except 2 buttons whose IsEnabled state depends on the outcome of some properties that are loaded.

The frustrating part is that as soon as I focus on any part of the view, or set a breakpoint after the properties are updated (create a delay), then the buttons IsEnabled state is updated as expected. So it appears to be a timing issue.

Any clues as to how to the best way to solve this? I'm using mvvm-light framework, but that shouldn't matter.

I've tried binding IsEnabled to the button instead of just relying on the Command property, but that made no difference. I've confirmed via logging that view model properties are set and the PropertyChanged event is being raised for the properties associated with the buttons.

Considering sending a message using mvvm-light messenger from the view model to the view on the async completed event and then somehow? triggering a view refresh, but that seems like a kludge.

Update

Thanks to blindmeis' answer, I tested the button behaviour without the Command binding set, i.e. just binding IsEnabled property, and it works as expected!

<Button
    Grid.Column="2" Content="{Binding LoadProjectsLabel}"
    VerticalAlignment="Top" HorizontalAlignment="Right"
    IsEnabled="{Binding CanLoadProjects}" />

Obviously it's not great because I can no longer execute the command :) but as soon as I add the command back, it stops behaving:

<Button
    Grid.Column="2" Content="{Binding LoadProjectsLabel}"
    VerticalAlignment="Top" HorizontalAlignment="Right"
    Command="{Binding LoadProjectsCommand}" />

Leaving IsEnabled binding doesn't solve the problem, but that seems like a good clue.

The view model command code:

public ICommand LoadProjectsCommand
{
    get
    {
        if (_loadProjectsCommand == null)
        {
            _loadProjectsCommand = new RelayCommand(loadProjects, () => CanLoadProjects);
        }
        return _loadProjectsCommand;
    }
}

Workaround

Wire up the Click event and avoid Command. Would be nice to solve it from the view model, but this works:

<Button
    Grid.Column="2" Content="{Binding LoadProjectsLabel}"
    VerticalAlignment="Top" HorizontalAlignment="Right"
    IsEnabled="{Binding CanLoadProjects}"
    Click="loadProjects_Click"/>

Code behind:

void loadProjects_Click(object sender, RoutedEventArgs e)
{
    SettingsViewModel vm = (SettingsViewModel)DataContext;
    vm.LoadProjectsCommand.Execute(null);
}


问:
aws s3 node js sdk method generatePutUrl returns differnt results for localhost and deployment on heroku
I am trying to manage direct file upload to S3 according to heroku recomendations

first one need to generate presigned URL at ones server

use this url in client to direct upload of image from browser to S3 bucket

and finally manage to works it locally.
but when I tried to deploy server on heroku it starts to fail with no reason or readable error. Just common error and strange message when I try to print it

what looks strange for me that presigned urls are completely different when I make call from local host or from heroku
response for localhost looks like this:

```<code>https://mybucket.s3.eu-west-1.amazonaws.com/5e3ec346d0b5af34ef9dfadf_avatar.png?AWSAccessKeyId=<AWSKeyIdHere>&Content-Encoding=base64&Content-Type=image%2Fpng&Expires=1581172437&Signature=xDJcRBiA%2FmQF1qKhBZrnhFXWdaM%3D
</code>```

and response for heroku deployment looks like this:

```<code>https://mybucket.s3.u-west-1.amazonaws.com/5e3ee2bd1513b60017d85c6c_avatar.png?Content-Type=image%2Fpng&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=<credentials-key-here>%2F20200208%2Fu-west-1%2Fs3%2Faws4_request&X-Amz-Date=20200208T163315Z&X-Amz-Expires=900&X-Amz-Signature=<someSignature>&X-Amz-SignedHeaders=content-encoding%3Bhost
</code>```

server code is almost like in examples:

```<code>const Bucket = process.env.BUCKET_NAME
const region = process.env.BUCKET_REGION

AWS.config = new AWS.Config({
accessKeyId: process.env.S3_KEY,
secretAccessKey: process.env.S3_SECRET,
region,
logger: console
})

const s3 = new AWS.S3()

async function generatePutUrl(inputParams = {}) {
  const params = { Bucket, ...inputParams }
  const { Key } = inputParams
  const putUrl = await s3.getSignedUrl('putObject', params)
  const getUrl = generateGetUrlLocaly(Key)

  return {putUrl, getUrl}
}
</code>```

the only difference that I can imagine is SSL - I run local server VIA http and heroku goes over https by default...

but I don't understand how it may influence here.
I will appreciate any meaningful advises how to debug and fix it.
thank you.

答:
Please update your BUCKET_REGION in environment variables at Heroku Server settings from

u-west-1

to

eu-west-1

and restart the dynos. It may solve your problem.

Body:
I am trying to manage direct file upload to S3 according to heroku recomendations

first one need to generate presigned URL at ones server

use this url in client to direct upload of image from browser to S3 bucket

and finally manage to works it locally.
but when I tried to deploy server on heroku it starts to fail with no reason or readable error. Just common error and strange message when I try to print it

what looks strange for me that presigned urls are completely different when I make call from local host or from heroku
response for localhost looks like this:

https://mybucket.s3.eu-west-1.amazonaws.com/5e3ec346d0b5af34ef9dfadf_avatar.png?AWSAccessKeyId=<AWSKeyIdHere>&Content-Encoding=base64&Content-Type=image%2Fpng&Expires=1581172437&Signature=xDJcRBiA%2FmQF1qKhBZrnhFXWdaM%3D

and response for heroku deployment looks like this:

https://mybucket.s3.u-west-1.amazonaws.com/5e3ee2bd1513b60017d85c6c_avatar.png?Content-Type=image%2Fpng&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=<credentials-key-here>%2F20200208%2Fu-west-1%2Fs3%2Faws4_request&X-Amz-Date=20200208T163315Z&X-Amz-Expires=900&X-Amz-Signature=<someSignature>&X-Amz-SignedHeaders=content-encoding%3Bhost

server code is almost like in examples:

const Bucket = process.env.BUCKET_NAME
const region = process.env.BUCKET_REGION

AWS.config = new AWS.Config({
accessKeyId: process.env.S3_KEY,
secretAccessKey: process.env.S3_SECRET,
region,
logger: console
})

const s3 = new AWS.S3()

async function generatePutUrl(inputParams = {}) {
  const params = { Bucket, ...inputParams }
  const { Key } = inputParams
  const putUrl = await s3.getSignedUrl('putObject', params)
  const getUrl = generateGetUrlLocaly(Key)

  return {putUrl, getUrl}
}

the only difference that I can imagine is SSL - I run local server VIA http and heroku goes over https by default...

but I don't understand how it may influence here.
I will appreciate any meaningful advises how to debug and fix it.
thank you.


问:
Mysql Count row data by every date but only have few data date
I have a table "activity" like this

```<code>idEmployee  | activity | Date
1           | a        | 2019/01/01
1           | b        | 2019/01/01
2           | c        | 2019/01/01
2           | d        | 2019/01/01
1           | e        | 2019/01/02
2           | f        | 2019/01/03
1           | f        | 2019/01/03
3           | c        | 2019/01/01
4           | d        | 2019/01/03
1           | e        | 2019/01/02
2           | f        | 2019/01/03
</code>```

and i want to count every date from 2019/01/01 - 2019/01/03 that has no activity by every idEmpolyee (as total_no_actitivity) like this

```<code>idEmployee | total_no_activity
1          | 0
2          | 1 (2019/01/02
3          | 2 (2019/01/02,2019/01/03)
4          | 2 (2019/01/01,2019/01/02)
</code>```

but i only can select idemployee that has no activity , without count total_no_activity.

```<code>SELECT idEmployee, namaLengkap, date
FROM account LEFT JOIN timesheet USING (idEmployee)
WHERE NOT EXISTS (SELECT idEmployee
                  FROM timesheet
                  WHERE account.idEmployee = timesheet.idEmployee AND weekday(date) AND date                    between '2019/08/05' and '2019/08/09' AND idrole = '4' AND statusaktif = '1' )
ORDER BY idEmployee ASC
</code>```

is it possible to count total_no_activity with table "activity" only?

答:
I would suggest:

```<code>select a.idEmployee,
       (datediff(params.date2, params.date1) + 1 -
        count(distinct ac.date)
       ) as missing_days
from (select date('2019-01-01') as date1, date('2019-01-03') as date2
     ) params cross join   -- a convenience so we don't have to retype the constants
     accounts a left join
     activity ac
     on ac.idEmployee = a.idEmployee and
        ac.date >= params.date1 and
        ac.date <= params.date2
group by a.idEmployee;
</code>```

To prevent typos and to allow the dates to change easily, this introduces a subquery, params, that has the date values.

Body:
I have a table "activity" like this

idEmployee  | activity | Date
1           | a        | 2019/01/01
1           | b        | 2019/01/01
2           | c        | 2019/01/01
2           | d        | 2019/01/01
1           | e        | 2019/01/02
2           | f        | 2019/01/03
1           | f        | 2019/01/03
3           | c        | 2019/01/01
4           | d        | 2019/01/03
1           | e        | 2019/01/02
2           | f        | 2019/01/03

and i want to count every date from 2019/01/01 - 2019/01/03 that has no activity by every idEmpolyee (as total_no_actitivity) like this

idEmployee | total_no_activity
1          | 0
2          | 1 (2019/01/02
3          | 2 (2019/01/02,2019/01/03)
4          | 2 (2019/01/01,2019/01/02)

but i only can select idemployee that has no activity , without count total_no_activity.

SELECT idEmployee, namaLengkap, date
FROM account LEFT JOIN timesheet USING (idEmployee)
WHERE NOT EXISTS (SELECT idEmployee
                  FROM timesheet
                  WHERE account.idEmployee = timesheet.idEmployee AND weekday(date) AND date                    between '2019/08/05' and '2019/08/09' AND idrole = '4' AND statusaktif = '1' )
ORDER BY idEmployee ASC

is it possible to count total_no_activity with table "activity" only?

Body:
I would suggest:

select a.idEmployee,
       (datediff(params.date2, params.date1) + 1 -
        count(distinct ac.date)
       ) as missing_days
from (select date('2019-01-01') as date1, date('2019-01-03') as date2
     ) params cross join   -- a convenience so we don't have to retype the constants
     accounts a left join
     activity ac
     on ac.idEmployee = a.idEmployee and
        ac.date >= params.date1 and
        ac.date <= params.date2
group by a.idEmployee;

To prevent typos and to allow the dates to change easily, this introduces a subquery, params, that has the date values.


问:
I want to print the dictionary in python
```<code>l = {}
name = [(str, input().split()) for i in range(0, 15)]
dob = [(int, input().split()) for i in range(0, 15)]
print({name[i]:dob[i] for i in range(len(dob))})
</code>```

I want to print 15 items in a dictionary format of name as key and dateofbirth(dob) as value.What wrong I am doing?
    .....................................................................................

```<code>the error is:
Traceback (most recent call last):
  File "main.py", line 4, in <module>
    print({name[i]:dob[i] for i in range(len(dob))})
  File "main.py", line 4, in <dictcomp>
    print({name[i]:dob[i] for i in range(len(dob))})
TypeError: unhashable type: 'list'
</code>```

答:
The issue is not in the print() function but in the way you make up the first list: instead of pulling out the names, it gives you a (<class 'str'>, 'string') tuple that cannot be used as a key for a dictionary. The same happens with the 'dob' variable, but the issue is only with keys.

Try doing:

```<code>name = [input() for i in range(0, 15)] #this takes and returns the input. no need to convert to string
dob = [int(input()) for i in range(0, 15)] #this takes an input and returns it's numeric value
</code>```

Body:
l = {}
name = [(str, input().split()) for i in range(0, 15)]
dob = [(int, input().split()) for i in range(0, 15)]
print({name[i]:dob[i] for i in range(len(dob))})

I want to print 15 items in a dictionary format of name as key and dateofbirth(dob) as value.What wrong I am doing?
    .....................................................................................

the error is:
Traceback (most recent call last):
  File "main.py", line 4, in <module>
    print({name[i]:dob[i] for i in range(len(dob))})
  File "main.py", line 4, in <dictcomp>
    print({name[i]:dob[i] for i in range(len(dob))})
TypeError: unhashable type: 'list'

Body:
The issue is not in the print() function but in the way you make up the first list: instead of pulling out the names, it gives you a (<class 'str'>, 'string') tuple that cannot be used as a key for a dictionary. The same happens with the 'dob' variable, but the issue is only with keys.

Try doing:

name = [input() for i in range(0, 15)] #this takes and returns the input. no need to convert to string
dob = [int(input()) for i in range(0, 15)] #this takes an input and returns it's numeric value


问:
What is _md5.md5 and why is hashlib.md5 so much slower?
Found this undocumented _md5 when getting frustrated with the slow stdlib hashlib.md5 implementation.

On a macbook:

```<code>>>> timeit hashlib.md5(b"hello world")
597 ns ± 17.2 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
>>> timeit _md5.md5(b"hello world")
224 ns ± 3.18 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
>>> _md5
<module '_md5' from '/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload/_md5.cpython-37m-darwin.so'>
</code>```

On a Windows box:

```<code>>>> timeit hashlib.md5(b"stonk overflow")
328 ns ± 21.8 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
>>> timeit _md5.md5(b"stonk overflow")
110 ns ± 12.5 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
>>> _md5
<module '_md5' (built-in)>
</code>```

On a Linux box:

```<code>>>> timeit hashlib.md5(b"https://adventofcode.com/2016/day/5")
259 ns ± 1.33 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
>>> timeit _md5.md5(b"https://adventofcode.com/2016/day/5")
102 ns ± 0.0576 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
>>> _md5
<module '_md5' from '/usr/local/lib/python3.8/lib-dynload/_md5.cpython-38-x86_64-linux-gnu.so'>
</code>```

For hashing short messages, it's way faster. For long messages, similar performance.

Why is it hidden away in an underscore extension module, and why isn't this faster implementation used by default in hashlib?  What is the _md5 module and why doesn't it have public API?

答:
Until Python 2.5, hashes and digests were implemented in their own modules (e.g. [Python 2.Docs]: md5 - MD5 message digest algorithm).

Starting with v2.5, [Python 2.6.Docs]: hashlib - Secure hashes and message digests was added. Its purpose was to:

Offer an unified access method to the hashes / digests (via their name)

Switch (by default) to an external cryptography provider (it seems the logical step to delegate to some entity specialized in that field, as maintaining all those algorithms could be an overkill). At that time OpenSSL was the best choice: mature enough, known and compatible (there were a bunch of similar Java providers, but those were pretty useless)

As a side effect of #2., the Python implementations were hidden from the public API (renamed them: _md5, _sha1, _sha256, _sha512, and the latter ones added: _blake2, _sha3), as redundancy often creates confusions.

But, another side effect was _hashlib.so dependency on OpenSSL's libcrypto*.so (this is Nix (at least Linux) specific, on Win, a static libeay32.lib was linked in _hashlib.pyd, and also _ssl.pyd (which I consider lame), till v3.7+, where OpenSSL .dlls are part of the Python installation).

Probably on 90%+ of the machines things were smooth, as OpenSSL was / is installed by default, but for those where it isn't, many things might get broken because for example hashlib is imported by many modules (one such example is random which itself gets imported by lots of others), so trivial pieces of code that are not related at all to cryptography (at least not at 1st sight) will stop working. That's why the old implementations are kept (but again, they are only fallbacks as OpenSSL versions are / should be better maintained).

[cfati@cfati-ubtu16x64-0:~/Work/Dev/StackOverflow/q059955854]> ~/sopr.sh
### Set shorter prompt to better fit when pasted in StackOverflow (or other) pages ###

[064bit-prompt]> python3 -c "import sys, hashlib as hl, _md5, ssl;print(\"{0:}\n{1:}\n{2:}\n{3:}\".format(sys.version, _md5, hl._hashlib, ssl.OPENSSL_VERSION))"
3.5.2 (default, Oct  8 2019, 13:06:37)
[GCC 5.4.0 20160609]
<module '_md5' (built-in)>
<module '_hashlib' from '/usr/lib/python3.5/lib-dynload/_hashlib.cpython-35m-x86_64-linux-gnu.so'>
OpenSSL 1.0.2g  1 Mar 2016
[064bit-prompt]>
[064bit-prompt]> ldd /usr/lib/python3.5/lib-dynload/_hashlib.cpython-35m-x86_64-linux-gnu.so
        linux-vdso.so.1 =>  (0x00007fffa7d0b000)
        libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007f50d9e4d000)
        libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f50d9a83000)
        libcrypto.so.1.0.0 => /lib/x86_64-linux-gnu/libcrypto.so.1.0.0 (0x00007f50d963e000)
        /lib64/ld-linux-x86-64.so.2 (0x00007f50da271000)
        libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007f50d943a000)
[064bit-prompt]>
[064bit-prompt]> openssl version -a
OpenSSL 1.0.2g  1 Mar 2016
built on: reproducible build, date unspecified
platform: debian-amd64
options:  bn(64,64) rc4(16x,int) des(idx,cisc,16,int) blowfish(idx)
compiler: cc -I. -I.. -I../include  -fPIC -DOPENSSL_PIC -DOPENSSL_THREADS -D_REENTRANT -DDSO_DLFCN -DHAVE_DLFCN_H -m64 -DL_ENDIAN -g -O2 -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -Wl,-Bsymbolic-functions -Wl,-z,relro -Wa,--noexecstack -Wall -DMD32_REG_T=int -DOPENSSL_IA32_SSE2 -DOPENSSL_BN_ASM_MONT -DOPENSSL_BN_ASM_MONT5 -DOPENSSL_BN_ASM_GF2m -DSHA1_ASM -DSHA256_ASM -DSHA512_ASM -DMD5_ASM -DAES_ASM -DVPAES_ASM -DBSAES_ASM -DWHIRLPOOL_ASM -DGHASH_ASM -DECP_NISTZ256_ASM
OPENSSLDIR: "/usr/lib/ssl"
[064bit-prompt]>
[064bit-prompt]> python3 -c "import _md5, hashlib as hl;print(_md5.md5(b\"A\").hexdigest(), hl.md5(b\"A\").hexdigest())"
7fc56270e7a70fa81a5935b72eacbe29 7fc56270e7a70fa81a5935b72eacbe29
```
</blockquote>
<p>According to [Python 3.Docs]: hashlib.algorithms_guaranteed:</p>
<blockquote>
<p>A set containing the names of the hash algorithms guaranteed to be supported by this module on all platforms. Note that ‘md5’ is in this list despite some upstream vendors offering an odd “FIPS compliant” Python build that excludes it.</p>
</blockquote>
<p>Below it's an example of <strong>a custom <em>Python 2.7</em> installation</strong> (that I built quite a while ago, worth mentioning that it dynamically links to <em>OpenSSL</em> <em>.dll</em>s):</p>
<blockquote>
<pre class="lang-bat prettyprint-override"><code>[cfati@CFATI-5510-0:e:\Work\Dev\StackOverflow\q059955854]> sopr.bat
### Set shorter prompt to better fit when pasted in StackOverflow (or other) pages ###

[prompt]> "F:\Install\pc064\HPE\OPSWpython\2.7.10__00\python.exe" -c "import sys, ssl;print(\"{0:}\n{1:}\".format(sys.version, ssl.OPENSSL_VERSION))"
2.7.10 (default, Mar  8 2016, 15:02:46) [MSC v.1600 64 bit (AMD64)]
OpenSSL 1.0.2j-fips  26 Sep 2016

[prompt]> "F:\Install\pc064\HPE\OPSWpython\2.7.10__00\python.exe" -c "import hashlib as hl;print(hl.md5(\"A\").hexdigest())"
7fc56270e7a70fa81a5935b72eacbe29

[prompt]> "F:\Install\pc064\HPE\OPSWpython\2.7.10__00\python.exe" -c "import ssl;ssl.FIPS_mode_set(True);import hashlib as hl;print(hl.md5(\"A\").hexdigest())"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
ValueError: error:060A80A3:digital envelope routines:FIPS_DIGESTINIT:disabled for fips
</code>```

As for the speed question I can only speculate:

Python implementation was (obviously) written specifically for Python, meaning it is "more optimized" (yes, this is grammatically incorrect) for Python than a generic version, and also resides in python*.so (or the python executable itself)

OpenSSL implementation resides in libcrypto*.so, and it's being accessed by the wrapper _hashlib.so, which does the back and forth conversions between Python types (PyObject*) and the OpenSSL ones (EVP_MD_CTX*)

Considering the above, it would make sense that the former is (slightly) faster (at least for small messages, where the overhead (function call and other Python underlying operations) takes a significant percentage of the total time compared to the hashing itself). There are also other factors to be considered (e.g. whether OpenSSL assembler speedups were used).

Update #0

Below are some benchmarks of my own.

code00.py:

#!/usr/bin/env python

import sys
import timeit
from hashlib import md5 as md5_openssl
from _md5 import md5 as md5_builtin

MD5S = (
    md5_openssl,
    md5_builtin,
)

def main(*argv):
    base_text = b"A"
    number = 1000000
    print("timeit attempts number: {:d}".format(number))
    #x = []
    #y = {}
    for count in range(0, 16):
        factor = 2 ** count
        text = base_text * factor
        globals_dict = {"text": text}
        #x.append(factor)
        print("\nUsing a {:8d} (2 ** {:2d}) bytes message".format(len(text), count))
        for func in MD5S:
            globals_dict["md5"] = func
            t = timeit.timeit(stmt="md5(text)", globals=globals_dict, number=number)
            print("    {:12s} took: {:11.6f} seconds".format(func.__name__, t))
            #y.setdefault(func.__name__, []).append(t)
    #print(x, y)

if __name__ == "__main__":
    print("Python {:s} {:03d}bit on {:s}\n".format(" ".join(elem.strip() for elem in sys.version.split("\n")),
                                                   64 if sys.maxsize > 0x100000000 else 32, sys.platform))
    rc = main(*sys.argv[1:])
    print("\nDone.\n")
    sys.exit(rc)
```
<p><strong>Output</strong>:</p>
<ul>
<li><p><em>Win 10 pc064</em> (running on a <em>Dell Precision 5510</em> laptop):</p>
<blockquote>
<pre class="lang-bat prettyprint-override"><code>[prompt]> "e:\Work\Dev\VEnvs\py_pc064_03.07.06_test0\Scripts\python.exe" code00.py
Python 3.7.6 (tags/v3.7.6:43364a7ae0, Dec 19 2019, 00:42:30) [MSC v.1916 64 bit (AMD64)] 64bit on win32

timeit attempts number: 1000000

Using a        1 (2 **  0) bytes message
    openssl_md5  took:    0.449134 seconds
    md5          took:    0.120021 seconds

Using a        2 (2 **  1) bytes message
    openssl_md5  took:    0.460399 seconds
    md5          took:    0.118555 seconds

Using a        4 (2 **  2) bytes message
    openssl_md5  took:    0.451850 seconds
    md5          took:    0.121166 seconds

Using a        8 (2 **  3) bytes message
    openssl_md5  took:    0.438398 seconds
    md5          took:    0.118127 seconds

Using a       16 (2 **  4) bytes message
    openssl_md5  took:    0.454653 seconds
    md5          took:    0.122818 seconds

Using a       32 (2 **  5) bytes message
    openssl_md5  took:    0.450776 seconds
    md5          took:    0.118594 seconds

Using a       64 (2 **  6) bytes message
    openssl_md5  took:    0.555761 seconds
    md5          took:    0.278812 seconds

Using a      128 (2 **  7) bytes message
    openssl_md5  took:    0.681296 seconds
    md5          took:    0.455921 seconds

Using a      256 (2 **  8) bytes message
    openssl_md5  took:    0.895952 seconds
    md5          took:    0.807457 seconds

Using a      512 (2 **  9) bytes message
    openssl_md5  took:    1.401584 seconds
    md5          took:    1.499279 seconds

Using a     1024 (2 ** 10) bytes message
    openssl_md5  took:    2.360966 seconds
    md5          took:    2.878650 seconds

Using a     2048 (2 ** 11) bytes message
    openssl_md5  took:    4.383245 seconds
    md5          took:    5.655477 seconds

Using a     4096 (2 ** 12) bytes message
    openssl_md5  took:    8.264774 seconds
    md5          took:   10.920909 seconds

Using a     8192 (2 ** 13) bytes message
    openssl_md5  took:   15.521947 seconds
    md5          took:   21.895179 seconds

Using a    16384 (2 ** 14) bytes message
    openssl_md5  took:   29.947287 seconds
    md5          took:   43.198639 seconds

Using a    32768 (2 ** 15) bytes message
    openssl_md5  took:   59.123447 seconds
    md5          took:   86.453821 seconds

Done.
</code>```

Ubuntu 16 pc064 (VM running in VirtualBox on the above machine):

[064bit-prompt]> python3 code00.py
Python 3.5.2 (default, Oct  8 2019, 13:06:37) [GCC 5.4.0 20160609] 64bit on linux

timeit attempts number: 1000000

Using a        1 (2 **  0) bytes message
    openssl_md5  took:    0.246166 seconds
    md5          took:    0.130589 seconds

Using a        2 (2 **  1) bytes message
    openssl_md5  took:    0.251019 seconds
    md5          took:    0.127750 seconds

Using a        4 (2 **  2) bytes message
    openssl_md5  took:    0.257018 seconds
    md5          took:    0.123116 seconds

Using a        8 (2 **  3) bytes message
    openssl_md5  took:    0.245399 seconds
    md5          took:    0.128267 seconds

Using a       16 (2 **  4) bytes message
    openssl_md5  took:    0.251832 seconds
    md5          took:    0.136373 seconds

Using a       32 (2 **  5) bytes message
    openssl_md5  took:    0.248410 seconds
    md5          took:    0.140708 seconds

Using a       64 (2 **  6) bytes message
    openssl_md5  took:    0.361016 seconds
    md5          took:    0.267021 seconds

Using a      128 (2 **  7) bytes message
    openssl_md5  took:    0.478735 seconds
    md5          took:    0.413986 seconds

Using a      256 (2 **  8) bytes message
    openssl_md5  took:    0.707602 seconds
    md5          took:    0.695042 seconds

Using a      512 (2 **  9) bytes message
    openssl_md5  took:    1.216832 seconds
    md5          took:    1.268570 seconds

Using a     1024 (2 ** 10) bytes message
    openssl_md5  took:    2.122014 seconds
    md5          took:    2.429623 seconds

Using a     2048 (2 ** 11) bytes message
    openssl_md5  took:    4.158188 seconds
    md5          took:    4.847686 seconds

Using a     4096 (2 ** 12) bytes message
    openssl_md5  took:    7.839173 seconds
    md5          took:    9.242224 seconds

Using a     8192 (2 ** 13) bytes message
    openssl_md5  took:   15.282232 seconds
    md5          took:   18.368874 seconds

Using a    16384 (2 ** 14) bytes message
    openssl_md5  took:   30.681912 seconds
    md5          took:   36.755073 seconds

Using a    32768 (2 ** 15) bytes message
    openssl_md5  took:   60.230543 seconds
    md5          took:   73.237356 seconds

Done.
```

The result seem to be quite different than yours. In my case:

Starting somewhere in [~512B .. ~1KiB] sized messages, OpenSSL implementation seems to perform better than builtin one

I know that there are too few results to claim a pattern, but it seems that both implementations seem to be linearly proportional (in terms of time) with message size (but the builtin slope seems to be a bit steeper - meaning it will perform worse on the long run)

As a conclusion, if all your messages are small, and the builtin implementation works best for you, then use it.

Update #1

Graphical representation (I had to reduce the timeit iterations number by an order of magnitude, as it would take much too long for large messages):

and zooming on the area where the 2 graphs intersect:

Body:
Found this undocumented _md5 when getting frustrated with the slow stdlib hashlib.md5 implementation.

On a macbook:

>>> timeit hashlib.md5(b"hello world")
597 ns ± 17.2 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
>>> timeit _md5.md5(b"hello world")
224 ns ± 3.18 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
>>> _md5
<module '_md5' from '/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload/_md5.cpython-37m-darwin.so'>

On a Windows box:

>>> timeit hashlib.md5(b"stonk overflow")
328 ns ± 21.8 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
>>> timeit _md5.md5(b"stonk overflow")
110 ns ± 12.5 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
>>> _md5
<module '_md5' (built-in)>

On a Linux box:

>>> timeit hashlib.md5(b"https://adventofcode.com/2016/day/5")
259 ns ± 1.33 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
>>> timeit _md5.md5(b"https://adventofcode.com/2016/day/5")
102 ns ± 0.0576 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
>>> _md5
<module '_md5' from '/usr/local/lib/python3.8/lib-dynload/_md5.cpython-38-x86_64-linux-gnu.so'>

For hashing short messages, it's way faster. For long messages, similar performance.

Why is it hidden away in an underscore extension module, and why isn't this faster implementation used by default in hashlib?  What is the _md5 module and why doesn't it have public API?

Body:
Until Python 2.5, hashes and digests were implemented in their own modules (e.g. [Python 2.Docs]: md5 - MD5 message digest algorithm).

Starting with v2.5, [Python 2.6.Docs]: hashlib - Secure hashes and message digests was added. Its purpose was to:

Offer an unified access method to the hashes / digests (via their name)

Switch (by default) to an external cryptography provider (it seems the logical step to delegate to some entity specialized in that field, as maintaining all those algorithms could be an overkill). At that time OpenSSL was the best choice: mature enough, known and compatible (there were a bunch of similar Java providers, but those were pretty useless)

As a side effect of #2., the Python implementations were hidden from the public API (renamed them: _md5, _sha1, _sha256, _sha512, and the latter ones added: _blake2, _sha3), as redundancy often creates confusions.

But, another side effect was _hashlib.so dependency on OpenSSL's libcrypto*.so (this is Nix (at least Linux) specific, on Win, a static libeay32.lib was linked in _hashlib.pyd, and also _ssl.pyd (which I consider lame), till v3.7+, where OpenSSL .dlls are part of the Python installation).

Probably on 90%+ of the machines things were smooth, as OpenSSL was / is installed by default, but for those where it isn't, many things might get broken because for example hashlib is imported by many modules (one such example is random which itself gets imported by lots of others), so trivial pieces of code that are not related at all to cryptography (at least not at 1st sight) will stop working. That's why the old implementations are kept (but again, they are only fallbacks as OpenSSL versions are / should be better maintained).

[cfati@cfati-ubtu16x64-0:~/Work/Dev/StackOverflow/q059955854]> ~/sopr.sh
### Set shorter prompt to better fit when pasted in StackOverflow (or other) pages ###

[064bit-prompt]> python3 -c "import sys, hashlib as hl, _md5, ssl;print(\"{0:}\n{1:}\n{2:}\n{3:}\".format(sys.version, _md5, hl._hashlib, ssl.OPENSSL_VERSION))"
3.5.2 (default, Oct  8 2019, 13:06:37)
[GCC 5.4.0 20160609]
<module '_md5' (built-in)>
<module '_hashlib' from '/usr/lib/python3.5/lib-dynload/_hashlib.cpython-35m-x86_64-linux-gnu.so'>
OpenSSL 1.0.2g  1 Mar 2016
[064bit-prompt]>
[064bit-prompt]> ldd /usr/lib/python3.5/lib-dynload/_hashlib.cpython-35m-x86_64-linux-gnu.so
        linux-vdso.so.1 =>  (0x00007fffa7d0b000)
        libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007f50d9e4d000)
        libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f50d9a83000)
        libcrypto.so.1.0.0 => /lib/x86_64-linux-gnu/libcrypto.so.1.0.0 (0x00007f50d963e000)
        /lib64/ld-linux-x86-64.so.2 (0x00007f50da271000)
        libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007f50d943a000)
[064bit-prompt]>
[064bit-prompt]> openssl version -a
OpenSSL 1.0.2g  1 Mar 2016
built on: reproducible build, date unspecified
platform: debian-amd64
options:  bn(64,64) rc4(16x,int) des(idx,cisc,16,int) blowfish(idx)
compiler: cc -I. -I.. -I../include  -fPIC -DOPENSSL_PIC -DOPENSSL_THREADS -D_REENTRANT -DDSO_DLFCN -DHAVE_DLFCN_H -m64 -DL_ENDIAN -g -O2 -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -Wl,-Bsymbolic-functions -Wl,-z,relro -Wa,--noexecstack -Wall -DMD32_REG_T=int -DOPENSSL_IA32_SSE2 -DOPENSSL_BN_ASM_MONT -DOPENSSL_BN_ASM_MONT5 -DOPENSSL_BN_ASM_GF2m -DSHA1_ASM -DSHA256_ASM -DSHA512_ASM -DMD5_ASM -DAES_ASM -DVPAES_ASM -DBSAES_ASM -DWHIRLPOOL_ASM -DGHASH_ASM -DECP_NISTZ256_ASM
OPENSSLDIR: "/usr/lib/ssl"
[064bit-prompt]>
[064bit-prompt]> python3 -c "import _md5, hashlib as hl;print(_md5.md5(b\"A\").hexdigest(), hl.md5(b\"A\").hexdigest())"
7fc56270e7a70fa81a5935b72eacbe29 7fc56270e7a70fa81a5935b72eacbe29

According to [Python 3.Docs]: hashlib.algorithms_guaranteed:

A set containing the names of the hash algorithms guaranteed to be supported by this module on all platforms. Note that ‘md5’ is in this list despite some upstream vendors offering an odd “FIPS compliant” Python build that excludes it.

Below it's an example of a custom Python 2.7 installation (that I built quite a while ago, worth mentioning that it dynamically links to OpenSSL .dlls):

[cfati@CFATI-5510-0:e:\Work\Dev\StackOverflow\q059955854]> sopr.bat
### Set shorter prompt to better fit when pasted in StackOverflow (or other) pages ###

[prompt]> "F:\Install\pc064\HPE\OPSWpython\2.7.10__00\python.exe" -c "import sys, ssl;print(\"{0:}\n{1:}\".format(sys.version, ssl.OPENSSL_VERSION))"
2.7.10 (default, Mar  8 2016, 15:02:46) [MSC v.1600 64 bit (AMD64)]
OpenSSL 1.0.2j-fips  26 Sep 2016

[prompt]> "F:\Install\pc064\HPE\OPSWpython\2.7.10__00\python.exe" -c "import hashlib as hl;print(hl.md5(\"A\").hexdigest())"
7fc56270e7a70fa81a5935b72eacbe29

[prompt]> "F:\Install\pc064\HPE\OPSWpython\2.7.10__00\python.exe" -c "import ssl;ssl.FIPS_mode_set(True);import hashlib as hl;print(hl.md5(\"A\").hexdigest())"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
ValueError: error:060A80A3:digital envelope routines:FIPS_DIGESTINIT:disabled for fips

As for the speed question I can only speculate:

Python implementation was (obviously) written specifically for Python, meaning it is "more optimized" (yes, this is grammatically incorrect) for Python than a generic version, and also resides in python*.so (or the python executable itself)

OpenSSL implementation resides in libcrypto*.so, and it's being accessed by the wrapper _hashlib.so, which does the back and forth conversions between Python types (PyObject*) and the OpenSSL ones (EVP_MD_CTX*)

Considering the above, it would make sense that the former is (slightly) faster (at least for small messages, where the overhead (function call and other Python underlying operations) takes a significant percentage of the total time compared to the hashing itself). There are also other factors to be considered (e.g. whether OpenSSL assembler speedups were used).

Update #0

Below are some benchmarks of my own.

code00.py:

#!/usr/bin/env python

import sys
import timeit
from hashlib import md5 as md5_openssl
from _md5 import md5 as md5_builtin

MD5S = (
    md5_openssl,
    md5_builtin,
)

def main(*argv):
    base_text = b"A"
    number = 1000000
    print("timeit attempts number: {:d}".format(number))
    #x = []
    #y = {}
    for count in range(0, 16):
        factor = 2 ** count
        text = base_text * factor
        globals_dict = {"text": text}
        #x.append(factor)
        print("\nUsing a {:8d} (2 ** {:2d}) bytes message".format(len(text), count))
        for func in MD5S:
            globals_dict["md5"] = func
            t = timeit.timeit(stmt="md5(text)", globals=globals_dict, number=number)
            print("    {:12s} took: {:11.6f} seconds".format(func.__name__, t))
            #y.setdefault(func.__name__, []).append(t)
    #print(x, y)

if __name__ == "__main__":
    print("Python {:s} {:03d}bit on {:s}\n".format(" ".join(elem.strip() for elem in sys.version.split("\n")),
                                                   64 if sys.maxsize > 0x100000000 else 32, sys.platform))
    rc = main(*sys.argv[1:])
    print("\nDone.\n")
    sys.exit(rc)

Output:

Win 10 pc064 (running on a Dell Precision 5510 laptop):

[prompt]> "e:\Work\Dev\VEnvs\py_pc064_03.07.06_test0\Scripts\python.exe" code00.py
Python 3.7.6 (tags/v3.7.6:43364a7ae0, Dec 19 2019, 00:42:30) [MSC v.1916 64 bit (AMD64)] 64bit on win32

timeit attempts number: 1000000

Using a        1 (2 **  0) bytes message
    openssl_md5  took:    0.449134 seconds
    md5          took:    0.120021 seconds

Using a        2 (2 **  1) bytes message
    openssl_md5  took:    0.460399 seconds
    md5          took:    0.118555 seconds

Using a        4 (2 **  2) bytes message
    openssl_md5  took:    0.451850 seconds
    md5          took:    0.121166 seconds

Using a        8 (2 **  3) bytes message
    openssl_md5  took:    0.438398 seconds
    md5          took:    0.118127 seconds

Using a       16 (2 **  4) bytes message
    openssl_md5  took:    0.454653 seconds
    md5          took:    0.122818 seconds

Using a       32 (2 **  5) bytes message
    openssl_md5  took:    0.450776 seconds
    md5          took:    0.118594 seconds

Using a       64 (2 **  6) bytes message
    openssl_md5  took:    0.555761 seconds
    md5          took:    0.278812 seconds

Using a      128 (2 **  7) bytes message
    openssl_md5  took:    0.681296 seconds
    md5          took:    0.455921 seconds

Using a      256 (2 **  8) bytes message
    openssl_md5  took:    0.895952 seconds
    md5          took:    0.807457 seconds

Using a      512 (2 **  9) bytes message
    openssl_md5  took:    1.401584 seconds
    md5          took:    1.499279 seconds

Using a     1024 (2 ** 10) bytes message
    openssl_md5  took:    2.360966 seconds
    md5          took:    2.878650 seconds

Using a     2048 (2 ** 11) bytes message
    openssl_md5  took:    4.383245 seconds
    md5          took:    5.655477 seconds

Using a     4096 (2 ** 12) bytes message
    openssl_md5  took:    8.264774 seconds
    md5          took:   10.920909 seconds

Using a     8192 (2 ** 13) bytes message
    openssl_md5  took:   15.521947 seconds
    md5          took:   21.895179 seconds

Using a    16384 (2 ** 14) bytes message
    openssl_md5  took:   29.947287 seconds
    md5          took:   43.198639 seconds

Using a    32768 (2 ** 15) bytes message
    openssl_md5  took:   59.123447 seconds
    md5          took:   86.453821 seconds

Done.

Ubuntu 16 pc064 (VM running in VirtualBox on the above machine):

[064bit-prompt]> python3 code00.py
Python 3.5.2 (default, Oct  8 2019, 13:06:37) [GCC 5.4.0 20160609] 64bit on linux

timeit attempts number: 1000000

Using a        1 (2 **  0) bytes message
    openssl_md5  took:    0.246166 seconds
    md5          took:    0.130589 seconds

Using a        2 (2 **  1) bytes message
    openssl_md5  took:    0.251019 seconds
    md5          took:    0.127750 seconds

Using a        4 (2 **  2) bytes message
    openssl_md5  took:    0.257018 seconds
    md5          took:    0.123116 seconds

Using a        8 (2 **  3) bytes message
    openssl_md5  took:    0.245399 seconds
    md5          took:    0.128267 seconds

Using a       16 (2 **  4) bytes message
    openssl_md5  took:    0.251832 seconds
    md5          took:    0.136373 seconds

Using a       32 (2 **  5) bytes message
    openssl_md5  took:    0.248410 seconds
    md5          took:    0.140708 seconds

Using a       64 (2 **  6) bytes message
    openssl_md5  took:    0.361016 seconds
    md5          took:    0.267021 seconds

Using a      128 (2 **  7) bytes message
    openssl_md5  took:    0.478735 seconds
    md5          took:    0.413986 seconds

Using a      256 (2 **  8) bytes message
    openssl_md5  took:    0.707602 seconds
    md5          took:    0.695042 seconds

Using a      512 (2 **  9) bytes message
    openssl_md5  took:    1.216832 seconds
    md5          took:    1.268570 seconds

Using a     1024 (2 ** 10) bytes message
    openssl_md5  took:    2.122014 seconds
    md5          took:    2.429623 seconds

Using a     2048 (2 ** 11) bytes message
    openssl_md5  took:    4.158188 seconds
    md5          took:    4.847686 seconds

Using a     4096 (2 ** 12) bytes message
    openssl_md5  took:    7.839173 seconds
    md5          took:    9.242224 seconds

Using a     8192 (2 ** 13) bytes message
    openssl_md5  took:   15.282232 seconds
    md5          took:   18.368874 seconds

Using a    16384 (2 ** 14) bytes message
    openssl_md5  took:   30.681912 seconds
    md5          took:   36.755073 seconds

Using a    32768 (2 ** 15) bytes message
    openssl_md5  took:   60.230543 seconds
    md5          took:   73.237356 seconds

Done.

The result seem to be quite different than yours. In my case:

Starting somewhere in [~512B .. ~1KiB] sized messages, OpenSSL implementation seems to perform better than builtin one

I know that there are too few results to claim a pattern, but it seems that both implementations seem to be linearly proportional (in terms of time) with message size (but the builtin slope seems to be a bit steeper - meaning it will perform worse on the long run)

As a conclusion, if all your messages are small, and the builtin implementation works best for you, then use it.

Update #1

Graphical representation (I had to reduce the timeit iterations number by an order of magnitude, as it would take much too long for large messages):

and zooming on the area where the 2 graphs intersect:


问:
Detecting change in two consecutive pictures
As a toy project i want to write an application that will take pictures from a web cam and then detect changes in them. I want to detect if someone walked in front of the webcam.

Can you guys, show me some pointers on how can i detect a major change in two consecutive shots?

答:
Subtract the per pixel lightness values from one image to the other.

This will give you high values per pixel where something is moved, and low values for where things are the same. Total these values and check to see if it's above a certain threshold number to see if a major change has occured.

I took a photo of my hand from my laptop to show this:

OwnerDisplayName: Hamza Yerlikaya

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Daniel Von Fange

LastEditorDisplayName: Daniel Von Fange


问:
rake aborted! no such file to load -- sqlite3
I've set up a new rails3 app and my gemfile is below

```<code>source 'http://rubygems.org'
gem 'rails', '3.0.0'
gem 'nifty-generators'
gem 'pg'
gem 'authlogic'
gem 'jquery-rails'
gem "mocha", :group => :test
</code>```

as seen from the Gemfile, I intend on using postgresql as the database and not the default sqllite3.  however, when I tried doing rake db:create or rake db:migrate for the first time, it keeps giving me error rake aborted! no such file to load -- sqllite3

There was a file in db/development.sqllite which I deleted after I got this error...thinking that it will help. but it didn't.

答:
Check your /config/database.yml file

You probably have it still set to connect to a sqlite3 database (the default)

Body:
I've set up a new rails3 app and my gemfile is below

source 'http://rubygems.org'
gem 'rails', '3.0.0'
gem 'nifty-generators'
gem 'pg'
gem 'authlogic'
gem 'jquery-rails'
gem "mocha", :group => :test

as seen from the Gemfile, I intend on using postgresql as the database and not the default sqllite3.  however, when I tried doing rake db:create or rake db:migrate for the first time, it keeps giving me error rake aborted! no such file to load -- sqllite3

There was a file in db/development.sqllite which I deleted after I got this error...thinking that it will help. but it didn't.


问:
Gateway 502 errors on swapping
I am getting a pretty inexplicable issue when swapping an app service. It only recently started doing this and it is rather strange.

Essentially the production/staging slot works, doing the 1st phase of swap works. However as soon as I do the complete swap the app becomes unresponsive and eventually returns a gateway error 502 forcing me to swap back.

This is the first time this has ever been an issue (5+ years)

答:
Thanks for asking question! You may look into ‘Diagnose & Solve problems’ blade to see what happened during swap operation and what caused it to fail. Click on “Check Swap Operations” this will open a page showing all the swaps performed on the Web app and their results and  includes possible root causes for the failures and recommendations on how to fix them.

Screenshots of the above steps

Title: Gateway 502 errors on swapping


问:
dplyr separate with regex
I have the following dataframe. It has 1 column of text that I would like to separate into multiple columns using the separate function from dplyr.

```<code>df <- structure(list(CPT.Codes = structure(c(2L, 1L, 3L, 4L, 5L), .Label = c("28296 - CORRECTION OF BUNION...., 64445P - N BLOCK INJ, SCIATIC, SNG, 76942P - US GUIDE, NEEDLE PLACEMENT",
"36821 - AV FUSION DIRECT ANY SITE, 99100P - ANESTHESIA FOR PT OF EXTREME AGE",
"41899 - DENTAL SURGERY PROCEDURE", "50593 - PERC CRYO ABLATE RENAL TUM, 99100P - ANESTHESIA FOR PT OF EXTREME AGE",
"64721 - CARPAL TUNNEL SURGERY"), class = "factor")), class = "data.frame", row.names = c(NA,
-5L))
</code>```

My desired output is the dataframe below. Each 5-digit number or 5-digit number + letter represents the code and the text following the dash is the code's description. Sometime's the code's description has single-digit numbers and multiple commas, so the regular expression will need to recognize the 5-digit number as a new code.

```<code>dfDesired <- structure(list(CPTcode1 = c(36821L, 28296L, 41899L, 50593L, 64721L
), CPTdescrip1 = structure(c(1L, 3L, 4L, 5L, 2L), .Label = c("AV FUSION DIRECT ANY SITE",
"CARPAL TUNNEL SURGERY", "CORRECTION OF BUNION....", "DENTAL SURGERY PROCEDURE",
"PERC CRYO ABLATE RENAL TUM"), class = "factor"), CPTcode2 = structure(c(2L,
1L, NA, 2L, NA), .Label = c("64445P", "99100P"), class = "factor"),
    CPTdescrip2 = structure(c(1L, 2L, NA, 1L, NA), .Label = c("ANESTHESIA FOR PT OF EXTREME AGE",
    "N BLOCK INJ"), class = "factor"), CPTcode3 = structure(c(NA,
    1L, NA, NA, NA), .Label = "76942P", class = "factor"), CPTdescrip3 = structure(c(NA,
    1L, NA, NA, NA), .Label = "US GUIDE NEEDLE PLACEMENT", class = "factor")), class = "data.frame", row.names = c(NA,
-5L))
</code>```

I have tried variations of the code below. It is wrong. I am new to regular expressions, and cannot figure this out with existing examples.

```<code> CPT %>%
  separate(CPT.Codes,
           into = c("CPTcode1", "CPTdescrip1", "CTPcode2", "CPTdescrip2", "CPTcode3", "CPTdescrip3"),
           sep = "(?<=[A-Z]) ?(?=[0-9])", remove = F) %>%
  glimpse
</code>```

Thanks in advance.

答:
Not as general (won't work if you have more than 3 possible patterns), but maybe more readable, you can use unglue_unnest() :

```<code>library(magrittr)
library(unglue)

patterns <- c(
  "{CPTcode1} - {CPTdescrip1}, {CPTcode2=[^ ]+} - {CPTdescrip2}, {CPTcode3=[^ ]+} - {CPTdescrip3}",
  "{CPTcode1} - {CPTdescrip1}, {CPTcode2=[^ ]+} - {CPTdescrip2}",
  "{CPTcode1} - {CPTdescrip1}")

unglue_unnest(df, CPT.Codes, patterns)
#>   CPTcode1                CPTdescrip1 CPTcode2                      CPTdescrip2 CPTcode3                CPTdescrip3
#> 1    36821  AV FUSION DIRECT ANY SITE   99100P ANESTHESIA FOR PT OF EXTREME AGE     <NA>                       <NA>
#> 2    28296   CORRECTION OF BUNION....   64445P        N BLOCK INJ, SCIATIC, SNG   76942P US GUIDE, NEEDLE PLACEMENT
#> 3    41899   DENTAL SURGERY PROCEDURE     <NA>                             <NA>     <NA>                       <NA>
#> 4    50593 PERC CRYO ABLATE RENAL TUM   99100P ANESTHESIA FOR PT OF EXTREME AGE     <NA>                       <NA>
#> 5    64721      CARPAL TUNNEL SURGERY     <NA>                             <NA>     <NA>                       <NA>
</code>```

Title: dplyr separate with regex

Body:
I have the following dataframe. It has 1 column of text that I would like to separate into multiple columns using the separate function from dplyr.

df <- structure(list(CPT.Codes = structure(c(2L, 1L, 3L, 4L, 5L), .Label = c("28296 - CORRECTION OF BUNION...., 64445P - N BLOCK INJ, SCIATIC, SNG, 76942P - US GUIDE, NEEDLE PLACEMENT",
"36821 - AV FUSION DIRECT ANY SITE, 99100P - ANESTHESIA FOR PT OF EXTREME AGE",
"41899 - DENTAL SURGERY PROCEDURE", "50593 - PERC CRYO ABLATE RENAL TUM, 99100P - ANESTHESIA FOR PT OF EXTREME AGE",
"64721 - CARPAL TUNNEL SURGERY"), class = "factor")), class = "data.frame", row.names = c(NA,
-5L))

My desired output is the dataframe below. Each 5-digit number or 5-digit number + letter represents the code and the text following the dash is the code's description. Sometime's the code's description has single-digit numbers and multiple commas, so the regular expression will need to recognize the 5-digit number as a new code.

dfDesired <- structure(list(CPTcode1 = c(36821L, 28296L, 41899L, 50593L, 64721L
), CPTdescrip1 = structure(c(1L, 3L, 4L, 5L, 2L), .Label = c("AV FUSION DIRECT ANY SITE",
"CARPAL TUNNEL SURGERY", "CORRECTION OF BUNION....", "DENTAL SURGERY PROCEDURE",
"PERC CRYO ABLATE RENAL TUM"), class = "factor"), CPTcode2 = structure(c(2L,
1L, NA, 2L, NA), .Label = c("64445P", "99100P"), class = "factor"),
    CPTdescrip2 = structure(c(1L, 2L, NA, 1L, NA), .Label = c("ANESTHESIA FOR PT OF EXTREME AGE",
    "N BLOCK INJ"), class = "factor"), CPTcode3 = structure(c(NA,
    1L, NA, NA, NA), .Label = "76942P", class = "factor"), CPTdescrip3 = structure(c(NA,
    1L, NA, NA, NA), .Label = "US GUIDE NEEDLE PLACEMENT", class = "factor")), class = "data.frame", row.names = c(NA,
-5L))

I have tried variations of the code below. It is wrong. I am new to regular expressions, and cannot figure this out with existing examples.

 CPT %>%
  separate(CPT.Codes,
           into = c("CPTcode1", "CPTdescrip1", "CTPcode2", "CPTdescrip2", "CPTcode3", "CPTdescrip3"),
           sep = "(?<=[A-Z]) ?(?=[0-9])", remove = F) %>%
  glimpse

Thanks in advance.

Body:
Not as general (won't work if you have more than 3 possible patterns), but maybe more readable, you can use unglue_unnest() :

library(magrittr)
library(unglue)

patterns <- c(
  "{CPTcode1} - {CPTdescrip1}, {CPTcode2=[^ ]+} - {CPTdescrip2}, {CPTcode3=[^ ]+} - {CPTdescrip3}",
  "{CPTcode1} - {CPTdescrip1}, {CPTcode2=[^ ]+} - {CPTdescrip2}",
  "{CPTcode1} - {CPTdescrip1}")

unglue_unnest(df, CPT.Codes, patterns)
#>   CPTcode1                CPTdescrip1 CPTcode2                      CPTdescrip2 CPTcode3                CPTdescrip3
#> 1    36821  AV FUSION DIRECT ANY SITE   99100P ANESTHESIA FOR PT OF EXTREME AGE     <NA>                       <NA>
#> 2    28296   CORRECTION OF BUNION....   64445P        N BLOCK INJ, SCIATIC, SNG   76942P US GUIDE, NEEDLE PLACEMENT
#> 3    41899   DENTAL SURGERY PROCEDURE     <NA>                             <NA>     <NA>                       <NA>
#> 4    50593 PERC CRYO ABLATE RENAL TUM   99100P ANESTHESIA FOR PT OF EXTREME AGE     <NA>                       <NA>
#> 5    64721      CARPAL TUNNEL SURGERY     <NA>                             <NA>     <NA>                       <NA>


问:
Wordpress .htaccess rewrite rule not working
I have my wordpress in a sub-folder on my domain with a .htacess file on the root which does all the redirecting.

i want to do a redirect, the site IP to WWW. which works for the main site on the root but not for the sub-folder which is  Wordpress.

iv got a feeling wordpress is overwriting this some where?

this is what iv used in root .htaccess

```<code>RewriteCond %{HTTP_HOST} ^IP.IP.IP.IP [NC]
RewriteRule ^(.*)$ http://www.NAME.com/$1 [R=301,L]
</code>```

but this does not work for the wordpress sub-folder
iv even tried to copy this into the .htaccess file in the WP root folder but still not work

答:
It is because in your Wordpress wp-admin panel there is a setting:

```<code>Settings -> General -> WordPress address (URL)
</code>```

and

```<code>Settings -> General -> Blog address (URL)
</code>```

Make sure to update them to http://www.domain.com/subfolder then it will start working.

UPDATE (Based on your comments)

Use following .htaccess inside WP install folder '/blog'

```<code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On

RewriteBase /blog/

RewriteRule ^/?$ /blog/index.php [L]

RewriteCond %{HTTP_HOST} ^IP\.IP\.IP\.IP$
RewriteRule . http://www.NAME.com%{REQUEST_URI} [R=301,L]

RewriteRule ^index\.php$ - [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /blog/index.php [L]
</IfModule>

# END WordPress
</code>```

Body:
I have my wordpress in a sub-folder on my domain with a .htacess file on the root which does all the redirecting.

i want to do a redirect, the site IP to WWW. which works for the main site on the root but not for the sub-folder which is  Wordpress.

iv got a feeling wordpress is overwriting this some where?

this is what iv used in root .htaccess

RewriteCond %{HTTP_HOST} ^IP.IP.IP.IP [NC]
RewriteRule ^(.*)$ http://www.NAME.com/$1 [R=301,L]

but this does not work for the wordpress sub-folder
iv even tried to copy this into the .htaccess file in the WP root folder but still not work

Body:
It is because in your Wordpress wp-admin panel there is a setting:

Settings -> General -> WordPress address (URL)

and

Settings -> General -> Blog address (URL)

Make sure to update them to http://www.domain.com/subfolder then it will start working.

UPDATE (Based on your comments)

Use following .htaccess inside WP install folder '/blog'

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On

RewriteBase /blog/

RewriteRule ^/?$ /blog/index.php [L]

RewriteCond %{HTTP_HOST} ^IP\.IP\.IP\.IP$
RewriteRule . http://www.NAME.com%{REQUEST_URI} [R=301,L]

RewriteRule ^index\.php$ - [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /blog/index.php [L]
</IfModule>

# END WordPress