问:
Firebase FCM returns Unauthorized error with right server key
I am trying to send a push notification from my server using Firebase Cloud Messaging but keep getting the following error:

Client error: POST https://fcm.googleapis.com/v1/projects/my-project/messages:send resulted in a 401 Unauthorized response... Request had invalid authentication credentials. Expected OAuth 2 access

I have looked everywhere online and everywhere made mention of "using the Server Key instead of the API Key". I am doing this and still receiving the error. Nothing online has helped.

Here is my request:

```<code>POST https://fcm.googleapis.com/v1/projects/my-project/messages:send

Headers:
    Authorization: Bearer <MY SERVER KEY>
    Content-Type: application/x-www-form-urlencoded (I have also tried application/json)

Body:
    {
        "message": {
            "topic": "",
            "notifications": {
                "title": "Some title",
                "body": "Some notification body"
            }
        }
    }
</code>```

Push notifications directly from the Firebase console work just fine, I just can't get this to work server side.

答:
It seems you are using the v1 HTTP API, but you're trying to authorize it using the instructions from the legacy API.  They aren't compatible.  As the documentation states:

Important: The server key found in the console cannot authorize send
  requests made via the HTTP v1 API—it is used only for legacy HTTP and
  XMPP requests.

If you want to use the v1 API, must follow the instructions in the v1 API documentation.  If you don't want to use the v1 API, then you will have to use the legacy API instead.

Body:
I am trying to send a push notification from my server using Firebase Cloud Messaging but keep getting the following error:

Client error: POST https://fcm.googleapis.com/v1/projects/my-project/messages:send resulted in a 401 Unauthorized response... Request had invalid authentication credentials. Expected OAuth 2 access

I have looked everywhere online and everywhere made mention of "using the Server Key instead of the API Key". I am doing this and still receiving the error. Nothing online has helped.

Here is my request:

POST https://fcm.googleapis.com/v1/projects/my-project/messages:send

Headers:
    Authorization: Bearer <MY SERVER KEY>
    Content-Type: application/x-www-form-urlencoded (I have also tried application/json)

Body:
    {
        "message": {
            "topic": "",
            "notifications": {
                "title": "Some title",
                "body": "Some notification body"
            }
        }
    }

Push notifications directly from the Firebase console work just fine, I just can't get this to work server side.


来源: stackexchange

问:
String to new object with parameters
How do i create a new instance of an object from a string?

I want to do this:

```<code>Event event = new Event("hello");
event.setName("nice!");
</code>```

but only having

```<code>String object = "Event";
String object_variable_name = "event";
String object_params = "hello";
</code>```

Is this possible?

答:
Here is how you get the class instance (so you can call the constructor): How to get a Class Object from the Class Name in Java

Now you can you the Beans API to get the getter for the property name. See this question: Java Reflection: Instantiate a new object with specified type

Or you can use reflectasm or reflections or commons-beanutils to make your life much more simple

ContentLicense: CC BY-SA 3.0

Title: String to new object with parameters

Body:
How do i create a new instance of an object from a string?

I want to do this:

Event event = new Event("hello");
event.setName("nice!");

but only having

String object = "Event";
String object_variable_name = "event";
String object_params = "hello";

Is this possible?


问:
intel C++ cannot open "wchar.h" on mac osx
System OSX 10.14.6, macbook pro

Trying to compile this simple C++ program:

```<code>#include <iostream>
int main() {
    sdt::cout << "hello world" << std::endl;
    return 0;
}
</code>```

Have gcc 9 installed via homebrew, as well as XCode command line tools.

Both of the following work

c++ main.cpp
g++-9 main.cpp
```

<p>Trying out the latest Intel Parallel Studio, the following fails:</p>

<pre class="lang-sh prettyprint-override"><code>> icpc main.cpp
In file included from /Library/Developer/CommandLineTools/usr/include/c++/v1/iosfwd(90),
                 from /Library/Developer/CommandLineTools/usr/include/c++/v1/ios(215),
                 from /Library/Developer/CommandLineTools/usr/include/c++/v1/iostream(38),
                 from main.cpp(1):
/Library/Developer/CommandLineTools/usr/include/c++/v1/wchar.h(119): catastrophic error: cannot open source file "wchar.h"
  #include_next <wchar.h>
                         ^

compilation aborted for main.cpp (code 4)
</code>```

Can someone tell me what I am missing here?

EDIT RESPONSE TO COMMENT ABOUT find

searching from / for wchar.h yields many wchar.h files, including the one from the error:

```<code>./usr/local/Cellar/gcc/9.2.0_3/include/c++/9.2.0/tr1/wchar.h
./Library/Developer/CommandLineTools/usr/include/c++/v1/wchar.h
./Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/wchar.h
./Applications/Xcode.app/Contents/Developer/Platforms/AppleTVOS.platform/Developer/SDKs/AppleTVOS.sdk/usr/include/wchar.h
./Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS.sdk/usr/include/wchar.h
./Applications/Xcode.app/Contents/Developer/Platforms/WatchOS.platform/Developer/SDKs/WatchOS.sdk/usr/include/wchar.h
./Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/wchar.h
./Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/DriverKit19.0.sdk/System/DriverKit/usr/include/wchar.h
./Applications/Xcode.app/Contents/Developer/Platforms/WatchSimulator.platform/Developer/SDKs/WatchSimulator.sdk/usr/include/wchar.h
./Applications/Xcode.app/Contents/Developer/Platforms/AppleTVSimulator.platform/Developer/SDKs/AppleTVSimulator.sdk/usr/include/wchar.h
./Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk/usr/include/wchar.h
./Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/wchar.h
./opt/intel/intelpython3/include/c++/v1/support/solaris/wchar.h
./opt/intel/intelpython3/include/c++/v1/wchar.h
./opt/intel/intelpython3/pkgs/libcxx-4.0.1-hcfea43d_1/include/c++/v1/support/solaris/wchar.h
./opt/intel/intelpython3/pkgs/libcxx-4.0.1-hcfea43d_1/include/c++/v1/wchar.h
./dev/fd/3/Applications/Xcode.app/Contents/Developer/Platforms/AppleTVOS.platform/Developer/SDKs/AppleTVOS.sdk/usr/include/wchar.h
./dev/fd/3/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS.sdk/usr/include/wchar.h
./dev/fd/3/Applications/Xcode.app/Contents/Developer/Platforms/WatchOS.platform/Developer/SDKs/WatchOS.sdk/usr/include/wchar.h
./dev/fd/3/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/wchar.h
./dev/fd/3/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/DriverKit19.0.sdk/System/DriverKit/usr/include/wchar.h
./dev/fd/3/Applications/Xcode.app/Contents/Developer/Platforms/WatchSimulator.platform/Developer/SDKs/WatchSimulator.sdk/usr/include/wchar.h
./dev/fd/3/Applications/Xcode.app/Contents/Developer/Platforms/AppleTVSimulator.platform/Developer/SDKs/AppleTVSimulator.sdk/usr/include/wchar.h
./dev/fd/3/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk/usr/include/wchar.h
./dev/fd/3/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/wchar.h
./dev/fd/3/opt/intel/intelpython3/include/c++/v1/support/solaris/wchar.h
./dev/fd/3/opt/intel/intelpython3/include/c++/v1/wchar.h
./dev/fd/3/opt/intel/intelpython3/pkgs/libcxx-4.0.1-hcfea43d_1/include/c++/v1/support/solaris/wchar.h
./dev/fd/3/opt/intel/intelpython3/pkgs/libcxx-4.0.1-hcfea43d_1/include/c++/v1/wchar.h

</code>```

答:
Intel C++ compiler on macOS is highly sensitive to the version of Xcode being used. For example, I receive the same errors as above when using icpc 2020 Initial Release and Xcode 11.3.1, but the code compiles and executes just fine with "icpc main.cpp" when using Xcode 11.2.1.

This has been the situation with Intel C++ compilers for some time on macOS... check your Xcode version and try again.

ContentLicense: CC BY-SA 4.0

Body:
System OSX 10.14.6, macbook pro

Trying to compile this simple C++ program:

#include <iostream>
int main() {
    sdt::cout << "hello world" << std::endl;
    return 0;
}

Have gcc 9 installed via homebrew, as well as XCode command line tools.

Both of the following work

c++ main.cpp
g++-9 main.cpp

Trying out the latest Intel Parallel Studio, the following fails:

> icpc main.cpp
In file included from /Library/Developer/CommandLineTools/usr/include/c++/v1/iosfwd(90),
                 from /Library/Developer/CommandLineTools/usr/include/c++/v1/ios(215),
                 from /Library/Developer/CommandLineTools/usr/include/c++/v1/iostream(38),
                 from main.cpp(1):
/Library/Developer/CommandLineTools/usr/include/c++/v1/wchar.h(119): catastrophic error: cannot open source file "wchar.h"
  #include_next <wchar.h>
                         ^

compilation aborted for main.cpp (code 4)

Can someone tell me what I am missing here?

EDIT RESPONSE TO COMMENT ABOUT find

searching from / for wchar.h yields many wchar.h files, including the one from the error:

./usr/local/Cellar/gcc/9.2.0_3/include/c++/9.2.0/tr1/wchar.h
./Library/Developer/CommandLineTools/usr/include/c++/v1/wchar.h
./Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/wchar.h
./Applications/Xcode.app/Contents/Developer/Platforms/AppleTVOS.platform/Developer/SDKs/AppleTVOS.sdk/usr/include/wchar.h
./Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS.sdk/usr/include/wchar.h
./Applications/Xcode.app/Contents/Developer/Platforms/WatchOS.platform/Developer/SDKs/WatchOS.sdk/usr/include/wchar.h
./Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/wchar.h
./Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/DriverKit19.0.sdk/System/DriverKit/usr/include/wchar.h
./Applications/Xcode.app/Contents/Developer/Platforms/WatchSimulator.platform/Developer/SDKs/WatchSimulator.sdk/usr/include/wchar.h
./Applications/Xcode.app/Contents/Developer/Platforms/AppleTVSimulator.platform/Developer/SDKs/AppleTVSimulator.sdk/usr/include/wchar.h
./Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk/usr/include/wchar.h
./Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/wchar.h
./opt/intel/intelpython3/include/c++/v1/support/solaris/wchar.h
./opt/intel/intelpython3/include/c++/v1/wchar.h
./opt/intel/intelpython3/pkgs/libcxx-4.0.1-hcfea43d_1/include/c++/v1/support/solaris/wchar.h
./opt/intel/intelpython3/pkgs/libcxx-4.0.1-hcfea43d_1/include/c++/v1/wchar.h
./dev/fd/3/Applications/Xcode.app/Contents/Developer/Platforms/AppleTVOS.platform/Developer/SDKs/AppleTVOS.sdk/usr/include/wchar.h
./dev/fd/3/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS.sdk/usr/include/wchar.h
./dev/fd/3/Applications/Xcode.app/Contents/Developer/Platforms/WatchOS.platform/Developer/SDKs/WatchOS.sdk/usr/include/wchar.h
./dev/fd/3/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/wchar.h
./dev/fd/3/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/DriverKit19.0.sdk/System/DriverKit/usr/include/wchar.h
./dev/fd/3/Applications/Xcode.app/Contents/Developer/Platforms/WatchSimulator.platform/Developer/SDKs/WatchSimulator.sdk/usr/include/wchar.h
./dev/fd/3/Applications/Xcode.app/Contents/Developer/Platforms/AppleTVSimulator.platform/Developer/SDKs/AppleTVSimulator.sdk/usr/include/wchar.h
./dev/fd/3/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk/usr/include/wchar.h
./dev/fd/3/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/wchar.h
./dev/fd/3/opt/intel/intelpython3/include/c++/v1/support/solaris/wchar.h
./dev/fd/3/opt/intel/intelpython3/include/c++/v1/wchar.h
./dev/fd/3/opt/intel/intelpython3/pkgs/libcxx-4.0.1-hcfea43d_1/include/c++/v1/support/solaris/wchar.h
./dev/fd/3/opt/intel/intelpython3/pkgs/libcxx-4.0.1-hcfea43d_1/include/c++/v1/wchar.h


问:
Using which and ! functions in R
```<code>x <- c("a", "b", "c", "d", "e", "f", "g")
y <- c("a", "c", "d", "z")
</code>```

I am trying to compare y to x and find an index  where in y that does not match with anything in x. in this case z does match and I want R to return the index of z.

This is one of the things I tried and it does not work.

```<code>index <- which(y != x)
</code>```

答:
You can also use match which will return NA if there is no match.

```<code>which(is.na(match(y, x)))
#[1] 4
</code>```

Or another variation with setdiff

```<code>which(y %in% setdiff(y, x))
</code>```

Title: Using which and ! functions in R

Body:
x <- c("a", "b", "c", "d", "e", "f", "g")
y <- c("a", "c", "d", "z")

I am trying to compare y to x and find an index  where in y that does not match with anything in x. in this case z does match and I want R to return the index of z.

This is one of the things I tried and it does not work.

index <- which(y != x)

Body:
You can also use match which will return NA if there is no match.

which(is.na(match(y, x)))
#[1] 4

Or another variation with setdiff

which(y %in% setdiff(y, x))


问:
Missing rest resource for certain requests in ready api project
I have created a composite project to test rest api using ready api tool and commited to git. Then someone imports that project from git, some api endpoints missed under api section, also some test steps missed under test cases. Here, once I added endpoints under APIs, i renamed services and gave the refering test suite name or meaning full name.

https://support.smartbear.com/readyapi/docs/_images/apis/organize/rest-structure.png

I noticed that if I use the same for in both locations, that means test suite name and service, this error happens. How could I solve this problem?.  Because I have already developed this project.

答: You might want to change the names to a different one instead of using the same in both location and do ensure that you SAVE your entire project before committing to GitHub. </p>


问:
Send/receive UK SMS via web api? What's a good reasonably priced service?
I'm googling for sms gateways and am seeing a few alternatives (eg http://txtlocal.co.uk).  I'm wondering what people here have used for this?  All we need is a service where

a) we set up an account with the service, with a mobile number

b) we send their api a recipient number and some text and they text it out from the above number

c) any incoming texts to that number get converted into web requests and sent to a url of our choosing.

Obviously i'm not expecting it to be free but are there any that just charge you for sending out texts and don't charge for receiving?  Or any others that have 'package' deals, eg "up to 5000 texts a month for £X" sort of thing?

Just wondering what other people have used.  cheers, max

答:
You should have a look at BulkSMS.

You can send messages by a simple HTTP call, including specifying the originating address (sender). Replies can be routed to you via an HTTP call to your server. The are additional options, such as dedicated incoming numbers which remain persistent to your account.

Credits can be purchased in bulk and do not expire at the end of the month.

They also have developers that assist on SO :)

Disclaimer: I work for BulkSMS


问:
Variable Type Issue For Parameter? - Powershell
I am trying to run the below code to search for inactive user accounts in an OU.  It seems like the type of variable I'm using may not be able to used with parameters.  Does that seem correct and if so what type of variable should I be using?

```<code>$scope = "-UsersOnly"

$accounts = Search-ADAccount -SearchBase "OU=Users,OU=testLab02,DC=test,DC=local" -AccountInactive -TimeSpan ([timespan]7D) $scope
    foreach($account in $accounts){
        If ($noDisable -notcontains $account.Name) {
            Write-Host $account
            #Disable-ADAccount -Identity $account.DistinguishedName -Verbose $whatIf | Export-Csv $logFile
        }
    }
</code>```

I receive the below error:

Search-ADAccount : A positional parameter cannot be found that accepts argument '-UsersOnly'.
At C:\Users\Administrator\Documents\Disable-ADAccounts.ps1:63 char:21
+ ... $accounts = Search-ADAccount -SearchBase $OU.DistinguishedName -Accou ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Search-ADAccount], ParameterBindingException
    + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.ActiveDirectory.Management.Commands.SearchADAccount

However, if I run the command manually without variables it works as expected:

```<code>Search-ADAccount -SearchBase "OU=Users,OU=testLab02,DC=test,DC=local" -AccountInactive -TimeSpan ([timespan]7D) -UsersOnly
</code>```

答:
$scope = "-UsersOnly"

You can't pass a (switch) parameter stored in a variable that way - it'll invariably be treated as a (positional) argument, which explains the error you saw; with directly passed arguments, only unquoted, literal tokens such as -UsersOnly are recognized as parameter names.

You can use splatting to pass parameters via variables, which in your case means:

```<code># Define a hash table of parameter values.
# This hash table encodes switch parameter -UsersOnly
$scope = @{ UsersOnly = $true } # [switch] parameters are represented as Booleans

# Note the use of sigil @ instead of $ to achieve splatting
Search-ADAccount @scope -SearchBase "OU=Users,OU=testLab02,DC=test,DC=local" -AccountInactive -TimeSpan ([timespan]7D)
</code>```

$scope is defined as a hash table (@{ ... }) whose entries represent parameter name-value pairs.

Here, only one parameter name-value pair is defined:

Parameter name -UsersOnly (the entry key must be defined without the - sigil) ...

... with value $true, which for a [switch] (flag) parameter is equivalent to passing the parameter; $false is typically[1] equivalent to omitting it.

To pass the parameter values represented by hashtable $scope to a command via splatting, sigil @ instead of $ must be used, i.e, @scope in this case.

[1] A command can technically distinguish between a switch being omitted and it being passed with value $false, and on occasion that results in different behavior, notably with the common -Confirm parameter, where -Confirm:$false overrides the $ConfirmPreference preference variable.

Body:
I am trying to run the below code to search for inactive user accounts in an OU.  It seems like the type of variable I'm using may not be able to used with parameters.  Does that seem correct and if so what type of variable should I be using?

$scope = "-UsersOnly"

$accounts = Search-ADAccount -SearchBase "OU=Users,OU=testLab02,DC=test,DC=local" -AccountInactive -TimeSpan ([timespan]7D) $scope
    foreach($account in $accounts){
        If ($noDisable -notcontains $account.Name) {
            Write-Host $account
            #Disable-ADAccount -Identity $account.DistinguishedName -Verbose $whatIf | Export-Csv $logFile
        }
    }

I receive the below error:

Search-ADAccount : A positional parameter cannot be found that accepts argument '-UsersOnly'.
At C:\Users\Administrator\Documents\Disable-ADAccounts.ps1:63 char:21
+ ... $accounts = Search-ADAccount -SearchBase $OU.DistinguishedName -Accou ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Search-ADAccount], ParameterBindingException
    + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.ActiveDirectory.Management.Commands.SearchADAccount

However, if I run the command manually without variables it works as expected:

Search-ADAccount -SearchBase "OU=Users,OU=testLab02,DC=test,DC=local" -AccountInactive -TimeSpan ([timespan]7D) -UsersOnly

Body:
$scope = "-UsersOnly"

You can't pass a (switch) parameter stored in a variable that way - it'll invariably be treated as a (positional) argument, which explains the error you saw; with directly passed arguments, only unquoted, literal tokens such as -UsersOnly are recognized as parameter names.

You can use splatting to pass parameters via variables, which in your case means:

# Define a hash table of parameter values.
# This hash table encodes switch parameter -UsersOnly
$scope = @{ UsersOnly = $true } # [switch] parameters are represented as Booleans

# Note the use of sigil @ instead of $ to achieve splatting
Search-ADAccount @scope -SearchBase "OU=Users,OU=testLab02,DC=test,DC=local" -AccountInactive -TimeSpan ([timespan]7D)

$scope is defined as a hash table (@{ ... }) whose entries represent parameter name-value pairs.

Here, only one parameter name-value pair is defined:

Parameter name -UsersOnly (the entry key must be defined without the - sigil) ...

... with value $true, which for a [switch] (flag) parameter is equivalent to passing the parameter; $false is typically[1] equivalent to omitting it.

To pass the parameter values represented by hashtable $scope to a command via splatting, sigil @ instead of $ must be used, i.e, @scope in this case.

[1] A command can technically distinguish between a switch being omitted and it being passed with value $false, and on occasion that results in different behavior, notably with the common -Confirm parameter, where -Confirm:$false overrides the $ConfirmPreference preference variable.


问:
Cannot find the Outliers (More specifically the IQR) of my data set
Trying to find the outliers of an excel sheet using pandas in python. I am able to find the first and third quartiles, but cannot subtract one from the other without returning NaN.

Here is the essential code:

```<code>absent = pd.read_excel('Absenteeism_at_work.xls')

print("\nOUTLIERS:")
# q1 = (absent.loc[:741, ['Distance from Residence to Work']].quantile([0.25]))
# q3 = (absent.loc[:741, ['Distance from Residence to Work']].quantile([0.75]))

#print(absent.loc[:741, 'Distance from Residence to Work'].quantile([0.25])) #quartile

#print(q1)
# q1, q3 = absent.loc[:741, ['Distance from Residence to Work', 'Transportation expense', 'Month of absence',
  #                       'Social smoker', 'Social drinker', 'Education']].quantile([0.25 - 0.75])

print(absent.loc[:741, ['Distance from Residence to Work', 'Transportation expense', 'Month of absence',
                      'Social smoker', 'Social drinker', 'Education']].quantile([0.75])
   - absent.loc[:741, ['Distance from Residence to Work', 'Transportation expense', 'Month of absence',
                    'Social smoker', 'Social drinker', 'Education']].quantile([0.25]))
</code>```

OUTPUT:

```<code>OUTLIERS:
      Distance from Residence to Work  Transportation expense  \
0.25                              NaN                     NaN
0.75                              NaN                     NaN

      Month of absence  Social smoker  Social drinker  Education
0.25               NaN            NaN             NaN        NaN
0.75               NaN            NaN             NaN        NaN
</code>```

答:
You code is just simply quartile range calculation. if it can work for you, that will be fine. If you need true outlier detect which is more complicated than quartile based mode, especially multivariables you can resort to python package like sklearn or pyod.

using quantile functioni, you need clean the raw data to make sure it is numerica only. Especially, you import excel file as data source.

check data by

tmp_df = absent.iloc[:741]

cols =  ['Distance from Residence to Work',
         'Transportation expense',
         'Month of absence',
         'Social smoker',
         'Social drinker',
         'Education']

print(tmp_df[col].quantile(0.25,0.75))

print(tmp_df[col].describe(include='all'))

Good luck.

WY

Body:
Trying to find the outliers of an excel sheet using pandas in python. I am able to find the first and third quartiles, but cannot subtract one from the other without returning NaN.

Here is the essential code:

absent = pd.read_excel('Absenteeism_at_work.xls')

print("\nOUTLIERS:")
# q1 = (absent.loc[:741, ['Distance from Residence to Work']].quantile([0.25]))
# q3 = (absent.loc[:741, ['Distance from Residence to Work']].quantile([0.75]))

#print(absent.loc[:741, 'Distance from Residence to Work'].quantile([0.25])) #quartile

#print(q1)
# q1, q3 = absent.loc[:741, ['Distance from Residence to Work', 'Transportation expense', 'Month of absence',
  #                       'Social smoker', 'Social drinker', 'Education']].quantile([0.25 - 0.75])

print(absent.loc[:741, ['Distance from Residence to Work', 'Transportation expense', 'Month of absence',
                      'Social smoker', 'Social drinker', 'Education']].quantile([0.75])
   - absent.loc[:741, ['Distance from Residence to Work', 'Transportation expense', 'Month of absence',
                    'Social smoker', 'Social drinker', 'Education']].quantile([0.25]))

OUTPUT:

OUTLIERS:
      Distance from Residence to Work  Transportation expense  \
0.25                              NaN                     NaN
0.75                              NaN                     NaN

      Month of absence  Social smoker  Social drinker  Education
0.25               NaN            NaN             NaN        NaN
0.75               NaN            NaN             NaN        NaN


问:
Accessing files on Android phone from Python on a Desktop
When I connect my android phone to a (Windows) desktop via a USB cable, I would like to automate downloading photos and other files from the phone to the desktop by using a script, preferably Python, but C# would do.

Is there a ready package available for this task? If not, what is the way to access the file system on the phone? How to get to the phone data using Windows system API?

答:
ADB stands for Android Debug Bridge; it is the official command line tool and provides shell terminal access to Android phones that has allowed developer debug access.

There seems to be 3rd-party python API for this.
https://github.com/google/python-adb


问:
Proportion vs contingency chi-square tests giving different p-values in Python
I have found different methods of conducting a chi-square test for A/B testing looking at users vs conversion rate of a control and a test group.

The first method uses statsmodels and uses proportions_chisquare

The second method uses scipy and chi2_contingency

It seems that chi2_contingency always has a higher value that proportions. Any idea for the difference and which test is more applicable for a simple A/B test?

I apologize for not including an example here is one below:

Example1 (p-value = 0.037):

```<code>import statsmodels.stats.proportion as proportion
import numpy as np

conv_a = 20
conv_b = 35
clicks_a = 500
clicks_b = 500
converted = np.array([conv_a, conv_b])
clicks = np.array([clicks_a,clicks_b])

chisq, pvalue, table = proportion.proportions_chisquare(converted, clicks)
print('Results are ','chisq =%.3f, pvalue = %.3f'%(chisq, pvalue))
</code>```

Example 2 (p-value = 0.0521):

```<code>import numpy
import scipy.stats

control_size = 500
A_CONVERSIONS = 20
A_NO_CONVERSIONS= control_size - A_CONVERSIONS
test_size = 500
B_CONVERSIONS = 35
B_NO_CONVERSIONS = test_size - B_CONVERSIONS

data = numpy.array([[A_NO_CONVERSIONS, A_CONVERSIONS],
                    [B_NO_CONVERSIONS, B_CONVERSIONS]])

chi_square, p_value = scipy.stats.chi2_contingency(data)[:2]

print('χ²: %.4f' % chi_square)
print('p-value: %.4f' % p_value)
</code>```

答:
Further to my comment above, here is a reproducible minimal example showing the use of proportions_chisquare from statsmodels and chi2_contingency from scipy. As expected, results agree.

Let's generate some sample data; data are taken from Fleiss JL, Statistical methods for rates and proportions, New York: John Wiley & Sons (1981).

import pandas as pd
data = pd.DataFrame({
    "Smokers": [83, 90, 129, 70],
    "Patients": [86, 93, 136, 82]
})
```

<p>Results from both tests are given below</p>

<pre class="lang-py prettyprint-override"><code>import statsmodels.stats.proportion as ssp
(chi2, p, arr) = ssp.proportions_chisquare(count = data.Smokers, nobs = data.sum(axis = 1))
"chi2 = %4.2f, p-value = %4.3f" % (chi2, p)
#'chi2 = 0.42, p-value = 0.936'

import scipy.stats as ss
(chi2, p, df, arr) = ss.chi2_contingency(data, correction = False)
"chi2 = %4.2f, p-value = %4.3f" % (chi2, p)
#'chi2 = 0.42, p-value = 0.936'
</code>```

As to the difference between a chi-square test and z-test (test of equal proportions), I refer to an excellent post on Cross Validated.

Body:
I have found different methods of conducting a chi-square test for A/B testing looking at users vs conversion rate of a control and a test group.

The first method uses statsmodels and uses proportions_chisquare

The second method uses scipy and chi2_contingency

It seems that chi2_contingency always has a higher value that proportions. Any idea for the difference and which test is more applicable for a simple A/B test?

I apologize for not including an example here is one below:

Example1 (p-value = 0.037):

import statsmodels.stats.proportion as proportion
import numpy as np

conv_a = 20
conv_b = 35
clicks_a = 500
clicks_b = 500
converted = np.array([conv_a, conv_b])
clicks = np.array([clicks_a,clicks_b])

chisq, pvalue, table = proportion.proportions_chisquare(converted, clicks)
print('Results are ','chisq =%.3f, pvalue = %.3f'%(chisq, pvalue))

Example 2 (p-value = 0.0521):

import numpy
import scipy.stats

control_size = 500
A_CONVERSIONS = 20
A_NO_CONVERSIONS= control_size - A_CONVERSIONS
test_size = 500
B_CONVERSIONS = 35
B_NO_CONVERSIONS = test_size - B_CONVERSIONS

data = numpy.array([[A_NO_CONVERSIONS, A_CONVERSIONS],
                    [B_NO_CONVERSIONS, B_CONVERSIONS]])

chi_square, p_value = scipy.stats.chi2_contingency(data)[:2]

print('χ²: %.4f' % chi_square)
print('p-value: %.4f' % p_value)

Body:
Further to my comment above, here is a reproducible minimal example showing the use of proportions_chisquare from statsmodels and chi2_contingency from scipy. As expected, results agree.

Let's generate some sample data; data are taken from Fleiss JL, Statistical methods for rates and proportions, New York: John Wiley & Sons (1981).

import pandas as pd
data = pd.DataFrame({
    "Smokers": [83, 90, 129, 70],
    "Patients": [86, 93, 136, 82]
})

Results from both tests are given below

import statsmodels.stats.proportion as ssp
(chi2, p, arr) = ssp.proportions_chisquare(count = data.Smokers, nobs = data.sum(axis = 1))
"chi2 = %4.2f, p-value = %4.3f" % (chi2, p)
#'chi2 = 0.42, p-value = 0.936'

import scipy.stats as ss
(chi2, p, df, arr) = ss.chi2_contingency(data, correction = False)
"chi2 = %4.2f, p-value = %4.3f" % (chi2, p)
#'chi2 = 0.42, p-value = 0.936'

As to the difference between a chi-square test and z-test (test of equal proportions), I refer to an excellent post on Cross Validated.


问:
How to Play Videos PHAsset in iOS?
I want to play video from PHAsset, collected from iOS Photos. PHAsset video nsurl (https://stackoverflow.com/a/35099857/1084174) is valid to my own application lets say MyPlayer for few moments/blocks. When I am copying the image/video into MyPlayers own sandbox only then the nsurl becomes always valid. It seems to me,

I need to copy each video from temporary PHAsset nsurl to MyPlayers
  sandbox (appgroup/documents) and only then I can play the video with
  sandbox relative nsurl.

If this is the case how do all other player play long videos on the fly? If there is any other way to play video without copying to apps sandbox, please let me know the way.

答:
The below solution works for slow-motion videos as well.

```<code>func playVideo(asset: PHAsset) {
    guard asset.mediaType == .video else {
        // Handle if the asset is not a video.
        return
    }

    let options = PHVideoRequestOptions()
    options.isNetworkAccessAllowed = true

    PHCachingImageManager().requestPlayerItem(forVideo: asset, options: options) { (playerItem, info) in
        DispatchQueue.main.async {
            let playerViewController = AVPlayerViewController()
            playerViewController.player = AVPlayer(playerItem: playerItem)
            present(playerViewController, animated: true) {
                playerViewController.player?.play()
            }
        }
    }
}
</code>```

Title: How to Play Videos PHAsset in iOS?

Body:
The below solution works for slow-motion videos as well.

func playVideo(asset: PHAsset) {
    guard asset.mediaType == .video else {
        // Handle if the asset is not a video.
        return
    }

    let options = PHVideoRequestOptions()
    options.isNetworkAccessAllowed = true

    PHCachingImageManager().requestPlayerItem(forVideo: asset, options: options) { (playerItem, info) in
        DispatchQueue.main.async {
            let playerViewController = AVPlayerViewController()
            playerViewController.player = AVPlayer(playerItem: playerItem)
            present(playerViewController, animated: true) {
                playerViewController.player?.play()
            }
        }
    }
}


问:
How can I use an Outlet Collection with labels and buttons in one collection?
I am trying to make an Outlet collection that consists of labels and buttons. I was thinking I could just do something like @IBOutlet var basicCollection: [Any]! this doesn't seem to work. Any idea would be great.

答:
Try

```<code>@IBOutlet var basicCollection: [UIView]!
</code>```

Works for me.

Body:
Try

@IBOutlet var basicCollection: [UIView]!

Works for me.


问:
Regex for at least 8 + upper and lower+numbers or other non-alphabetic

Contains at least 8 characters.

Contains upper and lower case letters.

Contains numbers or other non-alphabetic characters.

What could be the reg ex for the above criteria?

I am creating a check for stronger password :)

c# i am using

答:
This should do it:

```<code>(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[^a-zA-Z]).{8,}
</code>```

See here: rubular

Explained:

```<code>(?=.*?[a-z]) //lookahead, there has to be a lower case alphabetic char
(?=.*?[A-Z]) //lookahead, there has to be a upper case alphabetic char
(?=.*?[^a-zA-Z]) //lookahead, there has to be a non-alphabetic char
.{8,} // any character at least 8 times
</code>```

Body:
This should do it:

(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[^a-zA-Z]).{8,}

See here: rubular

Explained:

(?=.*?[a-z]) //lookahead, there has to be a lower case alphabetic char
(?=.*?[A-Z]) //lookahead, there has to be a upper case alphabetic char
(?=.*?[^a-zA-Z]) //lookahead, there has to be a non-alphabetic char
.{8,} // any character at least 8 times


问:
How to customize the payment method in payment intent example in stripe
I am trying to follow the example shown in the following link https://stripe.com/docs/payments/accept-a-payment.

I have the following code in the client side

```<code> var cardNumber = elements.create('cardNumber', {
    placeholder:'',
    style: style
});
var cardexpiry = elements.create('cardExpiry',{
    placeholder:'',
    style:style
});
var cardCVV = elements.create('cardCvc',{
    placeholder:'',
    style:style
});

// Add an instance of the card Element into the `card-element` <div>.
cardNumber.mount('#card-element');
cardexpiry.mount("#card-expiry")
cardCVV.mount("#card-cvv")
</code>```

instead of this

```<code>var card = elements.create("card", { style: style });
card.mount("#card-element");
</code>```

Because the I wanted to some UI manipulation. According to the code posted in the link
I should do the following

```<code>var submitButton = document.getElementById('submit');

submitButton.addEventListener('click', function(ev) {
 stripe.confirmCardPayment(clientSecret, {
   payment_method: {card: card}
 }).then(function(result) {
 if (result.error) {
  // Show error to your customer (e.g., insufficient funds)
  console.log(result.error.message);
 } else {
  // The payment has been processed!
  if (result.paymentIntent.status === 'succeeded') {
    // Show a success message to your customer
    // There's a risk of the customer closing the window before callback
    // execution. Set up a webhook or plugin to listen for the
    // payment_intent.succeeded event that handles any business critical
    // post-payment actions.
    }
 }
});
});
</code>```

However in the example above in the payment_method the card object is passed, which is not the case in my code. How can I pass my card number and exp/date as well CVC separately in the  stripe.confirmCardPayment(clientSecret, {
       payment_method: {card: card}

答:
There was a similar question about how to call stripe.createToken() when you aren't using a card element.

According to the Stripe documentation for createToken:

The cardNumber Element you wish to tokenize data from. If applicable, the Element pulls data from other elements you’ve created on the same instance of Elements to tokenize—you only need to supply one Element as the parameter.

Now, for this case in particular, the section for confirmCardPayment says:

Use stripe.confirmCardPayment with payment data from an Element by passing a card or cardNumber Element as payment_method[card] in the data argument.

Basically you just have to pass the cardNumber element to payment_method["card"] and it will pull the data from the other elements you’ve created.

```<code>...
stripe.confirmCardPayment(clientSecret, {
  payment_method: {card: cardNumber}
})
...
</code>```

Body:
I am trying to follow the example shown in the following link https://stripe.com/docs/payments/accept-a-payment.

I have the following code in the client side

 var cardNumber = elements.create('cardNumber', {
    placeholder:'',
    style: style
});
var cardexpiry = elements.create('cardExpiry',{
    placeholder:'',
    style:style
});
var cardCVV = elements.create('cardCvc',{
    placeholder:'',
    style:style
});

// Add an instance of the card Element into the `card-element`
.
cardNumber.mount('#card-element');
cardexpiry.mount("#card-expiry")
cardCVV.mount("#card-cvv")

instead of this

var card = elements.create("card", { style: style });
card.mount("#card-element");

Because the I wanted to some UI manipulation. According to the code posted in the link
I should do the following

var submitButton = document.getElementById('submit');

submitButton.addEventListener('click', function(ev) {
 stripe.confirmCardPayment(clientSecret, {
   payment_method: {card: card}
 }).then(function(result) {
 if (result.error) {
  // Show error to your customer (e.g., insufficient funds)
  console.log(result.error.message);
 } else {
  // The payment has been processed!
  if (result.paymentIntent.status === 'succeeded') {
    // Show a success message to your customer
    // There's a risk of the customer closing the window before callback
    // execution. Set up a webhook or plugin to listen for the
    // payment_intent.succeeded event that handles any business critical
    // post-payment actions.
    }
 }
});
});

However in the example above in the payment_method the card object is passed, which is not the case in my code. How can I pass my card number and exp/date as well CVC separately in the  stripe.confirmCardPayment(clientSecret, {
       payment_method: {card: card}

Body:
There was a similar question about how to call stripe.createToken() when you aren't using a card element.

According to the Stripe documentation for createToken:

The cardNumber Element you wish to tokenize data from. If applicable, the Element pulls data from other elements you’ve created on the same instance of Elements to tokenize—you only need to supply one Element as the parameter.

Now, for this case in particular, the section for confirmCardPayment says:

Use stripe.confirmCardPayment with payment data from an Element by passing a card or cardNumber Element as payment_method[card] in the data argument.

Basically you just have to pass the cardNumber element to payment_method["card"] and it will pull the data from the other elements you’ve created.

...
stripe.confirmCardPayment(clientSecret, {
  payment_method: {card: cardNumber}
})
...


问:
Ajax GET request data is not reaching to view from controller in ASP.NET Core MVC on success
In my application in .NET Core (2.2) MVC, I am doing a get request to my controller with user input using ajax.

Here is the code:

```<code> $.ajax({
            type: 'GET',
            url: "/BuildSheetsArea/TesterParameters/GetMassEditing",
            data: { 'ChangeTypeId': ChangeTypeId, 'param': param, 'ParameterValue': ParameterValue },
            dataType: 'json',
            success: function (data) {
                alert('success');
                console.log(data);

            },
            error: function (emp) {
                alert('error');
            }
        });
</code>```

I am getting hit to my controller successfully and my controller is returning the result.

Here is my controller code:

```<code>[HttpGet]
public System.Web.Mvc.JsonResult GetMassEditing(string ChangeTypeId, string param, string ParameterValue = "")
{
    List<TesterParameterMassEditingViewModel> finalList = new List<TesterParameterMassEditingViewModel>();

    // Code to perform necessary action

    return new System.Web.Mvc.JsonResult { Data = finalList, JsonRequestBehavior = System.Web.Mvc.JsonRequestBehavior.AllowGet };
}
</code>```

Here is a screenshot where controller is returning the result successfully

BUT on success I am not getting anything to my view. As you see in my ajax call on success I am trying to write the data from controller to console, but after controller returning the data nothing is happening. It never goes back to my ajax success function.

Am I missing anything? Kindly help.

I am using .NET Core 2.2 and Entity Framework Core 2.2.6

EDIT:
Adding the network tab result screenshot here

EDIT2:
After @Rena's suggesting I have change my code. but Now I am having a new problem. From my controller when I am trying to do a DB query any in retun tries to pass the object my request goes to pending status. Explanation is below.
 here is my AXAJ request:

```<code>$.ajax({
            type: 'POST',
            url: "/BuildSheetsArea/TesterParameters/GetMassEditing",
            data: {'ChangeTypeId': ChangeTypeId, 'param': param, 'ParameterValue': ParameterValue },
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                debugger;
                alert('success');
                console.log(data);
            },
            error: function (emp) {
                alert('error');
            },
        });
    });
</code>```

And here is my controller code:

```<code>        [HttpPost]
    public async Task<JsonResult> GetMassEditing(string ChangeTypeId, string param, string ParameterValue)
    {
        List<TesterParameter> deviceList = await _context.TesterParameters.ToListAsync();
        string val = "See from console";
        return Json(deviceList);
    }
</code>```

My Device list has 120 objects in it. This case in my network tab in browser I am getting this. My first request is in pending status and I am not getting anything in my ajax success method.

But if I donot do any db query and simply return a string, it works fine

```<code>        [HttpPost]
    public async Task<JsonResult> GetMassEditing(string ChangeTypeId, string param, string ParameterValue)
    {
        string val = "See from console";
        return Json(val);
    }
</code>```

In 3rd case if I do the db query only but return the simple string, my network tab shows request in pending and in ajax success method I get nothing.

Please help.

答:
If you are sure that you use asp.net core 2.2,you need to use Microsoft.AspNetCore.Mvc.JsonResult instead of System.Web.Mvc.JsonResult.

Change like below:

```<code>[HttpGet]
public Microsoft.AspNetCore.Mvc.JsonResult GetMassEditing(string ChangeTypeId, string param, string ParameterValue = "")
{
    List<TesterParameterMassEditingViewModel> finalList = new List<TesterParameterMassEditingViewModel>();

    // Code to perform necessary action

    return new JsonResult(finalList);
}
</code>```

Result:

Body:
In my application in .NET Core (2.2) MVC, I am doing a get request to my controller with user input using ajax.

Here is the code:

 $.ajax({
            type: 'GET',
            url: "/BuildSheetsArea/TesterParameters/GetMassEditing",
            data: { 'ChangeTypeId': ChangeTypeId, 'param': param, 'ParameterValue': ParameterValue },
            dataType: 'json',
            success: function (data) {
                alert('success');
                console.log(data);

            },
            error: function (emp) {
                alert('error');
            }
        });

I am getting hit to my controller successfully and my controller is returning the result.

Here is my controller code:

[HttpGet]
public System.Web.Mvc.JsonResult GetMassEditing(string ChangeTypeId, string param, string ParameterValue = "")
{
    List<TesterParameterMassEditingViewModel> finalList = new List<TesterParameterMassEditingViewModel>();

    // Code to perform necessary action

    return new System.Web.Mvc.JsonResult { Data = finalList, JsonRequestBehavior = System.Web.Mvc.JsonRequestBehavior.AllowGet };
}

Here is a screenshot where controller is returning the result successfully

BUT on success I am not getting anything to my view. As you see in my ajax call on success I am trying to write the data from controller to console, but after controller returning the data nothing is happening. It never goes back to my ajax success function.

Am I missing anything? Kindly help.

I am using .NET Core 2.2 and Entity Framework Core 2.2.6

EDIT:
Adding the network tab result screenshot here

EDIT2:
After @Rena's suggesting I have change my code. but Now I am having a new problem. From my controller when I am trying to do a DB query any in retun tries to pass the object my request goes to pending status. Explanation is below.
 here is my AXAJ request:

$.ajax({
            type: 'POST',
            url: "/BuildSheetsArea/TesterParameters/GetMassEditing",
            data: {'ChangeTypeId': ChangeTypeId, 'param': param, 'ParameterValue': ParameterValue },
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                debugger;
                alert('success');
                console.log(data);
            },
            error: function (emp) {
                alert('error');
            },
        });
    });

And here is my controller code:

        [HttpPost]
    public async Task<JsonResult> GetMassEditing(string ChangeTypeId, string param, string ParameterValue)
    {
        List<TesterParameter> deviceList = await _context.TesterParameters.ToListAsync();
        string val = "See from console";
        return Json(deviceList);
    }

My Device list has 120 objects in it. This case in my network tab in browser I am getting this. My first request is in pending status and I am not getting anything in my ajax success method.

But if I donot do any db query and simply return a string, it works fine

        [HttpPost]
    public async Task<JsonResult> GetMassEditing(string ChangeTypeId, string param, string ParameterValue)
    {
        string val = "See from console";
        return Json(val);
    }

In 3rd case if I do the db query only but return the simple string, my network tab shows request in pending and in ajax success method I get nothing.

Please help.

Body:
If you are sure that you use asp.net core 2.2,you need to use Microsoft.AspNetCore.Mvc.JsonResult instead of System.Web.Mvc.JsonResult.

Change like below:

[HttpGet]
public Microsoft.AspNetCore.Mvc.JsonResult GetMassEditing(string ChangeTypeId, string param, string ParameterValue = "")
{
    List<TesterParameterMassEditingViewModel> finalList = new List<TesterParameterMassEditingViewModel>();

    // Code to perform necessary action

    return new JsonResult(finalList);
}

Result:


问:
Pandas: Drop consecutive duplicates
What's the most efficient way to drop only consecutive duplicates in pandas?

drop_duplicates gives this:

```<code>In [3]: a = pandas.Series([1,2,2,3,2], index=[1,2,3,4,5])

In [4]: a.drop_duplicates()
Out[4]:
1    1
2    2
4    3
dtype: int64
</code>```

But I want this:

```<code>In [4]: a.something()
Out[4]:
1    1
2    2
4    3
5    2
dtype: int64
</code>```

答:
Here is a function that handles both pd.Series and pd.Dataframes. You can mask/drop, choose the axis and finally choose to drop with 'any' or 'all' 'NaN'. It is not optimized in term of computation time, but it has the advantage to be robust and pretty clear.

```<code>import numpy as np
import pandas as pd

# To mask/drop successive values in pandas
def Mask_Or_Drop_Successive_Identical_Values(df, drop=False,
                                             keep_first=True,
                                             axis=0, how='all'):

    '''
    #Function built with the help of:
    # 1) https://stackoverflow.com/questions/48428173/how-to-change-consecutive-repeating-values-in-pandas-dataframe-series-to-nan-or
    # 2) https://stackoverflow.com/questions/19463985/pandas-drop-consecutive-duplicates

    Input:
    df should be a pandas.DataFrame of a a pandas.Series
    Output:
    df of ts with masked or dropped values
    '''

    # Mask keeping the first occurrence
    if keep_first:
        df = df.mask(df.shift(1) == df)
    # Mask including the first occurrence
    else:
        df = df.mask((df.shift(1) == df) | (df.shift(-1) == df))

    # Drop the values (e.g. rows are deleted)
    if drop:
        return df.dropna(axis=axis, how=how)
    # Only mask the values (e.g. become 'NaN')
    else:
        return df
</code>```

Here is a test code to include in the script:

```<code>
if __name__ == "__main__":

    # With time series
    print("With time series:\n")
    ts = pd.Series([1,1,2,2,3,2,6,6,float('nan'), 6,6,float('nan'),float('nan')],
                    index=[0,1,2,3,4,5,6,7,8,9,10,11,12])

    print("#Original ts:")
    print(ts)

    print("\n## 1) Mask keeping the first occurrence:")
    print(Mask_Or_Drop_Successive_Identical_Values(ts, drop=False,
                                                   keep_first=True))

    print("\n## 2) Mask including the first occurrence:")
    print(Mask_Or_Drop_Successive_Identical_Values(ts, drop=False,
                                                   keep_first=False))

    print("\n## 3) Drop keeping the first occurrence:")
    print(Mask_Or_Drop_Successive_Identical_Values(ts, drop=True,
                                                   keep_first=True))

    print("\n## 4) Drop including the first occurrence:")
    print(Mask_Or_Drop_Successive_Identical_Values(ts, drop=True,
                                                   keep_first=False))

    # With dataframes
    print("With dataframe:\n")
    df = pd.DataFrame(np.random.randn(15, 3))
    df.iloc[4:9,0]=40
    df.iloc[8:15,1]=22
    df.iloc[8:12,2]=0.23

    print("#Original df:")
    print(df)

    print("\n## 5) Mask keeping the first occurrence:")
    print(Mask_Or_Drop_Successive_Identical_Values(df, drop=False,
                                                   keep_first=True))

    print("\n## 6) Mask including the first occurrence:")
    print(Mask_Or_Drop_Successive_Identical_Values(df, drop=False,
                                                   keep_first=False))

    print("\n## 7) Drop 'any' keeping the first occurrence:")
    print(Mask_Or_Drop_Successive_Identical_Values(df, drop=True,
                                                   keep_first=True,
                                                   how='any'))

    print("\n## 8) Drop 'all' keeping the first occurrence:")
    print(Mask_Or_Drop_Successive_Identical_Values(df, drop=True,
                                                   keep_first=True,
                                                   how='all'))

    print("\n## 9) Drop 'any' including the first occurrence:")
    print(Mask_Or_Drop_Successive_Identical_Values(df, drop=True,
                                                   keep_first=False,
                                                   how='any'))

    print("\n## 10) Drop 'all' including the first occurrence:")
    print(Mask_Or_Drop_Successive_Identical_Values(df, drop=True,
                                                   keep_first=False,
                                                   how='all'))
</code>```

And here is the expected result:

```<code>With time series:

#Original ts:
0     1.0
1     1.0
2     2.0
3     2.0
4     3.0
5     2.0
6     6.0
7     6.0
8     NaN
9     6.0
10    6.0
11    NaN
12    NaN
dtype: float64

## 1) Mask keeping the first occurrence:
0     1.0
1     NaN
2     2.0
3     NaN
4     3.0
5     2.0
6     6.0
7     NaN
8     NaN
9     6.0
10    NaN
11    NaN
12    NaN
dtype: float64

## 2) Mask including the first occurrence:
0     NaN
1     NaN
2     NaN
3     NaN
4     3.0
5     2.0
6     NaN
7     NaN
8     NaN
9     NaN
10    NaN
11    NaN
12    NaN
dtype: float64

## 3) Drop keeping the first occurrence:
0    1.0
2    2.0
4    3.0
5    2.0
6    6.0
9    6.0
dtype: float64

## 4) Drop including the first occurrence:
4    3.0
5    2.0
dtype: float64
With dataframe:

#Original df:
            0          1         2
0   -1.890137  -3.125224 -1.029065
1   -0.224712  -0.194742  1.891365
2    1.009388   0.589445  0.927405
3    0.212746  -0.392314 -0.781851
4   40.000000   1.889781 -1.394573
5   40.000000  -0.470958 -0.339213
6   40.000000   1.613524  0.271641
7   40.000000  -1.810958 -1.568372
8   40.000000  22.000000  0.230000
9   -0.296557  22.000000  0.230000
10  -0.921238  22.000000  0.230000
11  -0.170195  22.000000  0.230000
12   1.460457  22.000000 -0.295418
13   0.307825  22.000000 -0.759131
14   0.287392  22.000000  0.378315

## 5) Mask keeping the first occurrence:
            0          1         2
0   -1.890137  -3.125224 -1.029065
1   -0.224712  -0.194742  1.891365
2    1.009388   0.589445  0.927405
3    0.212746  -0.392314 -0.781851
4   40.000000   1.889781 -1.394573
5         NaN  -0.470958 -0.339213
6         NaN   1.613524  0.271641
7         NaN  -1.810958 -1.568372
8         NaN  22.000000  0.230000
9   -0.296557        NaN       NaN
10  -0.921238        NaN       NaN
11  -0.170195        NaN       NaN
12   1.460457        NaN -0.295418
13   0.307825        NaN -0.759131
14   0.287392        NaN  0.378315

## 6) Mask including the first occurrence:
           0         1         2
0  -1.890137 -3.125224 -1.029065
1  -0.224712 -0.194742  1.891365
2   1.009388  0.589445  0.927405
3   0.212746 -0.392314 -0.781851
4        NaN  1.889781 -1.394573
5        NaN -0.470958 -0.339213
6        NaN  1.613524  0.271641
7        NaN -1.810958 -1.568372
8        NaN       NaN       NaN
9  -0.296557       NaN       NaN
10 -0.921238       NaN       NaN
11 -0.170195       NaN       NaN
12  1.460457       NaN -0.295418
13  0.307825       NaN -0.759131
14  0.287392       NaN  0.378315

## 7) Drop 'any' keeping the first occurrence:
           0         1         2
0  -1.890137 -3.125224 -1.029065
1  -0.224712 -0.194742  1.891365
2   1.009388  0.589445  0.927405
3   0.212746 -0.392314 -0.781851
4  40.000000  1.889781 -1.394573

## 8) Drop 'all' keeping the first occurrence:
            0          1         2
0   -1.890137  -3.125224 -1.029065
1   -0.224712  -0.194742  1.891365
2    1.009388   0.589445  0.927405
3    0.212746  -0.392314 -0.781851
4   40.000000   1.889781 -1.394573
5         NaN  -0.470958 -0.339213
6         NaN   1.613524  0.271641
7         NaN  -1.810958 -1.568372
8         NaN  22.000000  0.230000
9   -0.296557        NaN       NaN
10  -0.921238        NaN       NaN
11  -0.170195        NaN       NaN
12   1.460457        NaN -0.295418
13   0.307825        NaN -0.759131
14   0.287392        NaN  0.378315

## 9) Drop 'any' including the first occurrence:
          0         1         2
0 -1.890137 -3.125224 -1.029065
1 -0.224712 -0.194742  1.891365
2  1.009388  0.589445  0.927405
3  0.212746 -0.392314 -0.781851

## 10) Drop 'all' including the first occurrence:
           0         1         2
0  -1.890137 -3.125224 -1.029065
1  -0.224712 -0.194742  1.891365
2   1.009388  0.589445  0.927405
3   0.212746 -0.392314 -0.781851
4        NaN  1.889781 -1.394573
5        NaN -0.470958 -0.339213
6        NaN  1.613524  0.271641
7        NaN -1.810958 -1.568372
9  -0.296557       NaN       NaN
10 -0.921238       NaN       NaN
11 -0.170195       NaN       NaN
12  1.460457       NaN -0.295418
13  0.307825       NaN -0.759131
14  0.287392       NaN  0.378315

</code>```

Title: Pandas: Drop consecutive duplicates

Body:
What's the most efficient way to drop only consecutive duplicates in pandas?

drop_duplicates gives this:

In [3]: a = pandas.Series([1,2,2,3,2], index=[1,2,3,4,5])

In [4]: a.drop_duplicates()
Out[4]:
1    1
2    2
4    3
dtype: int64

But I want this:

In [4]: a.something()
Out[4]:
1    1
2    2
4    3
5    2
dtype: int64

Body:
Here is a function that handles both pd.Series and pd.Dataframes. You can mask/drop, choose the axis and finally choose to drop with 'any' or 'all' 'NaN'. It is not optimized in term of computation time, but it has the advantage to be robust and pretty clear.

import numpy as np
import pandas as pd

# To mask/drop successive values in pandas
def Mask_Or_Drop_Successive_Identical_Values(df, drop=False,
                                             keep_first=True,
                                             axis=0, how='all'):

    '''
    #Function built with the help of:
    # 1) https://stackoverflow.com/questions/48428173/how-to-change-consecutive-repeating-values-in-pandas-dataframe-series-to-nan-or
    # 2) https://stackoverflow.com/questions/19463985/pandas-drop-consecutive-duplicates

    Input:
    df should be a pandas.DataFrame of a a pandas.Series
    Output:
    df of ts with masked or dropped values
    '''

    # Mask keeping the first occurrence
    if keep_first:
        df = df.mask(df.shift(1) == df)
    # Mask including the first occurrence
    else:
        df = df.mask((df.shift(1) == df) | (df.shift(-1) == df))

    # Drop the values (e.g. rows are deleted)
    if drop:
        return df.dropna(axis=axis, how=how)
    # Only mask the values (e.g. become 'NaN')
    else:
        return df

Here is a test code to include in the script:

if __name__ == "__main__":

    # With time series
    print("With time series:\n")
    ts = pd.Series([1,1,2,2,3,2,6,6,float('nan'), 6,6,float('nan'),float('nan')],
                    index=[0,1,2,3,4,5,6,7,8,9,10,11,12])

    print("#Original ts:")
    print(ts)

    print("\n## 1) Mask keeping the first occurrence:")
    print(Mask_Or_Drop_Successive_Identical_Values(ts, drop=False,
                                                   keep_first=True))

    print("\n## 2) Mask including the first occurrence:")
    print(Mask_Or_Drop_Successive_Identical_Values(ts, drop=False,
                                                   keep_first=False))

    print("\n## 3) Drop keeping the first occurrence:")
    print(Mask_Or_Drop_Successive_Identical_Values(ts, drop=True,
                                                   keep_first=True))

    print("\n## 4) Drop including the first occurrence:")
    print(Mask_Or_Drop_Successive_Identical_Values(ts, drop=True,
                                                   keep_first=False))

    # With dataframes
    print("With dataframe:\n")
    df = pd.DataFrame(np.random.randn(15, 3))
    df.iloc[4:9,0]=40
    df.iloc[8:15,1]=22
    df.iloc[8:12,2]=0.23

    print("#Original df:")
    print(df)

    print("\n## 5) Mask keeping the first occurrence:")
    print(Mask_Or_Drop_Successive_Identical_Values(df, drop=False,
                                                   keep_first=True))

    print("\n## 6) Mask including the first occurrence:")
    print(Mask_Or_Drop_Successive_Identical_Values(df, drop=False,
                                                   keep_first=False))

    print("\n## 7) Drop 'any' keeping the first occurrence:")
    print(Mask_Or_Drop_Successive_Identical_Values(df, drop=True,
                                                   keep_first=True,
                                                   how='any'))

    print("\n## 8) Drop 'all' keeping the first occurrence:")
    print(Mask_Or_Drop_Successive_Identical_Values(df, drop=True,
                                                   keep_first=True,
                                                   how='all'))

    print("\n## 9) Drop 'any' including the first occurrence:")
    print(Mask_Or_Drop_Successive_Identical_Values(df, drop=True,
                                                   keep_first=False,
                                                   how='any'))

    print("\n## 10) Drop 'all' including the first occurrence:")
    print(Mask_Or_Drop_Successive_Identical_Values(df, drop=True,
                                                   keep_first=False,
                                                   how='all'))

And here is the expected result:

With time series:

#Original ts:
0     1.0
1     1.0
2     2.0
3     2.0
4     3.0
5     2.0
6     6.0
7     6.0
8     NaN
9     6.0
10    6.0
11    NaN
12    NaN
dtype: float64

## 1) Mask keeping the first occurrence:
0     1.0
1     NaN
2     2.0
3     NaN
4     3.0
5     2.0
6     6.0
7     NaN
8     NaN
9     6.0
10    NaN
11    NaN
12    NaN
dtype: float64

## 2) Mask including the first occurrence:
0     NaN
1     NaN
2     NaN
3     NaN
4     3.0
5     2.0
6     NaN
7     NaN
8     NaN
9     NaN
10    NaN
11    NaN
12    NaN
dtype: float64

## 3) Drop keeping the first occurrence:
0    1.0
2    2.0
4    3.0
5    2.0
6    6.0
9    6.0
dtype: float64

## 4) Drop including the first occurrence:
4    3.0
5    2.0
dtype: float64
With dataframe:

#Original df:
            0          1         2
0   -1.890137  -3.125224 -1.029065
1   -0.224712  -0.194742  1.891365
2    1.009388   0.589445  0.927405
3    0.212746  -0.392314 -0.781851
4   40.000000   1.889781 -1.394573
5   40.000000  -0.470958 -0.339213
6   40.000000   1.613524  0.271641
7   40.000000  -1.810958 -1.568372
8   40.000000  22.000000  0.230000
9   -0.296557  22.000000  0.230000
10  -0.921238  22.000000  0.230000
11  -0.170195  22.000000  0.230000
12   1.460457  22.000000 -0.295418
13   0.307825  22.000000 -0.759131
14   0.287392  22.000000  0.378315

## 5) Mask keeping the first occurrence:
            0          1         2
0   -1.890137  -3.125224 -1.029065
1   -0.224712  -0.194742  1.891365
2    1.009388   0.589445  0.927405
3    0.212746  -0.392314 -0.781851
4   40.000000   1.889781 -1.394573
5         NaN  -0.470958 -0.339213
6         NaN   1.613524  0.271641
7         NaN  -1.810958 -1.568372
8         NaN  22.000000  0.230000
9   -0.296557        NaN       NaN
10  -0.921238        NaN       NaN
11  -0.170195        NaN       NaN
12   1.460457        NaN -0.295418
13   0.307825        NaN -0.759131
14   0.287392        NaN  0.378315

## 6) Mask including the first occurrence:
           0         1         2
0  -1.890137 -3.125224 -1.029065
1  -0.224712 -0.194742  1.891365
2   1.009388  0.589445  0.927405
3   0.212746 -0.392314 -0.781851
4        NaN  1.889781 -1.394573
5        NaN -0.470958 -0.339213
6        NaN  1.613524  0.271641
7        NaN -1.810958 -1.568372
8        NaN       NaN       NaN
9  -0.296557       NaN       NaN
10 -0.921238       NaN       NaN
11 -0.170195       NaN       NaN
12  1.460457       NaN -0.295418
13  0.307825       NaN -0.759131
14  0.287392       NaN  0.378315

## 7) Drop 'any' keeping the first occurrence:
           0         1         2
0  -1.890137 -3.125224 -1.029065
1  -0.224712 -0.194742  1.891365
2   1.009388  0.589445  0.927405
3   0.212746 -0.392314 -0.781851
4  40.000000  1.889781 -1.394573

## 8) Drop 'all' keeping the first occurrence:
            0          1         2
0   -1.890137  -3.125224 -1.029065
1   -0.224712  -0.194742  1.891365
2    1.009388   0.589445  0.927405
3    0.212746  -0.392314 -0.781851
4   40.000000   1.889781 -1.394573
5         NaN  -0.470958 -0.339213
6         NaN   1.613524  0.271641
7         NaN  -1.810958 -1.568372
8         NaN  22.000000  0.230000
9   -0.296557        NaN       NaN
10  -0.921238        NaN       NaN
11  -0.170195        NaN       NaN
12   1.460457        NaN -0.295418
13   0.307825        NaN -0.759131
14   0.287392        NaN  0.378315

## 9) Drop 'any' including the first occurrence:
          0         1         2
0 -1.890137 -3.125224 -1.029065
1 -0.224712 -0.194742  1.891365
2  1.009388  0.589445  0.927405
3  0.212746 -0.392314 -0.781851

## 10) Drop 'all' including the first occurrence:
           0         1         2
0  -1.890137 -3.125224 -1.029065
1  -0.224712 -0.194742  1.891365
2   1.009388  0.589445  0.927405
3   0.212746 -0.392314 -0.781851
4        NaN  1.889781 -1.394573
5        NaN -0.470958 -0.339213
6        NaN  1.613524  0.271641
7        NaN -1.810958 -1.568372
9  -0.296557       NaN       NaN
10 -0.921238       NaN       NaN
11 -0.170195       NaN       NaN
12  1.460457       NaN -0.295418
13  0.307825       NaN -0.759131
14  0.287392       NaN  0.378315


问:
How to connect MetaMask with Web3.js version 1.2.6?
I have written a smart contract (deployed on Ropsten) and a website (node.js, express.js and ejs)

I can read data from the contract with Infura API and shown on the web page successfully. However, I want to write data on the contract through Metamask.
Currently. I cannot connect MetaMask with web3.js 1.2.6. I have checked Web3.givenProvider return null also.

(I can interactive with my smart contract through MyEtherWallet + Meta Mask)

Detail information:

Development envrionment: node.js express.js ejs web3.js(1.2.6)

Browser: chrome + MetaMask: localhost:3000 / 127.0.0.1:3000

```<code>const express = require('express');
const router = express.Router();

const Web3 = require('web3');
//const web3 = new Web3(new Web3.providers.HttpProvider("https://ropsten.infura.io/v3/xxxxxxxx"));
const web3 = new Web3(Web3.givenProvider);

const Tx = require('ethereumjs-tx');

let myAddress = '0x3E0980E7cea6804B01BEA49cb70F9B7Cxxxxxxxx';
const abi = [***VERY LONG ABI***];
const address = "0x07cf2ecef130495ea18a25e4f1dfbfc4xxxxxxxx";
const MyContract = new web3.eth.Contract(abi, address);

// define the home page route
router.get('/', (req, res, next) => {
    const resultHome = [];

    MyContract.methods.name().call().then((name) => {
        resultHome.push(name);
        symbol();
    })
    const symbol = () => {
        MyContract.methods.symbol().call().then((symbol) => {
            resultHome.push(symbol);
            totalSupply();
        })
    }
    const totalSupply = () => {
        MyContract.methods.totalSupply().call().then((totalSupply) => {
            resultHome.push(totalSupply);
            home();
        })
    }

    const home = () => {
        res.render('erc20/index', {
            pageTitle: 'ERC-20E Token Standard Enhanced - Info',
            path: 'erc20',
            subPath: 'erc20Info',
            name: resultHome[0],
            symbol: resultHome[1],
            address: address,
            totalSupply: resultHome[2] / 100
        })
    }
})

router.get('/source', (req, res, next) => {
    res.sendFile(__dirname + '/erc20Source.txt');
})

// define the controller route
router.get('/controller', (req, res, next) => {
    let resultController = [];

    MyContract.methods.showRun().call().then((showRun) => {
        resultController.push(showRun);
        controller();
    })

    const controller = () => {
        res.render('erc20/controller', {
            pageTitle: 'ERC-20E Token Standard Enhanced - Controller',
            path: 'erc20',
            subPath: 'erc20Controller',
            showRun: resultController[0]
        })
    }
})

module.exports = router;
</code>```

答: The problem have solved since I put the web3 at the front end instead of the back end.</p>

Body:
I have written a smart contract (deployed on Ropsten) and a website (node.js, express.js and ejs)

I can read data from the contract with Infura API and shown on the web page successfully. However, I want to write data on the contract through Metamask.
Currently. I cannot connect MetaMask with web3.js 1.2.6. I have checked Web3.givenProvider return null also.

(I can interactive with my smart contract through MyEtherWallet + Meta Mask)

Detail information:

Development envrionment: node.js express.js ejs web3.js(1.2.6)

Browser: chrome + MetaMask: localhost:3000 / 127.0.0.1:3000

const express = require('express');
const router = express.Router();

const Web3 = require('web3');
//const web3 = new Web3(new Web3.providers.HttpProvider("https://ropsten.infura.io/v3/xxxxxxxx"));
const web3 = new Web3(Web3.givenProvider);

const Tx = require('ethereumjs-tx');

let myAddress = '0x3E0980E7cea6804B01BEA49cb70F9B7Cxxxxxxxx';
const abi = [***VERY LONG ABI***];
const address = "0x07cf2ecef130495ea18a25e4f1dfbfc4xxxxxxxx";
const MyContract = new web3.eth.Contract(abi, address);

// define the home page route
router.get('/', (req, res, next) => {
    const resultHome = [];

    MyContract.methods.name().call().then((name) => {
        resultHome.push(name);
        symbol();
    })
    const symbol = () => {
        MyContract.methods.symbol().call().then((symbol) => {
            resultHome.push(symbol);
            totalSupply();
        })
    }
    const totalSupply = () => {
        MyContract.methods.totalSupply().call().then((totalSupply) => {
            resultHome.push(totalSupply);
            home();
        })
    }

    const home = () => {
        res.render('erc20/index', {
            pageTitle: 'ERC-20E Token Standard Enhanced - Info',
            path: 'erc20',
            subPath: 'erc20Info',
            name: resultHome[0],
            symbol: resultHome[1],
            address: address,
            totalSupply: resultHome[2] / 100
        })
    }
})

router.get('/source', (req, res, next) => {
    res.sendFile(__dirname + '/erc20Source.txt');
})

// define the controller route
router.get('/controller', (req, res, next) => {
    let resultController = [];

    MyContract.methods.showRun().call().then((showRun) => {
        resultController.push(showRun);
        controller();
    })

    const controller = () => {
        res.render('erc20/controller', {
            pageTitle: 'ERC-20E Token Standard Enhanced - Controller',
            path: 'erc20',
            subPath: 'erc20Controller',
            showRun: resultController[0]
        })
    }
})

module.exports = router;


问:
gphoto2 how to handle Out of Focus warning
Here is how I capture image with my camera

```<code>import logging
import gphoto2 as gp
def main():
    def callback(level, domain, string, data=None):
        print('Callback: level =', level, ', domain =', domain, ', string =', string)
        if data:
            print('Callback data:', data)

    logging.basicConfig(
        format='%(levelname)s: %(name)s: %(message)s', level=logging.WARNING)
    callback_obj = gp.check_result(gp.use_python_logging())

    camera = gp.Camera()
    camera.init()
    try:
        camera_file_path = gp.check_result(camera.capture(gp.GP_CAPTURE_IMAGE))
    except gp.GPhoto2Error as ex:
        print("callback: ", ex, ex.code, ex.message, ex.string)
    camera.exit()

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

If the camera is not able to focus it generates following error

```<code>...
WARNING: gphoto2: (ptp_usb_getresp [usb.c:466]) PTP_OC 0x90c8 receiving resp failed: Out of Focus (0xa002)
WARNING: gphoto2: (camera_nikon_capture [library.c:3153]) 'ret' failed: 'Out of Focus' (0xa002)
WARNING: gphoto2: (gp_context_error) Out of Focus
WARNING: gphoto2: (gp_camera_capture [gphoto2-camera.c:1340]) 'camera->functions->capture (camera, type, path, context)' failed: -1
('callback: ', GPhoto2Error('[-1] Unspecified error',), -1, '[-1] Unspecified error', 'Unspecified error')
</code>```

The exception error code is -1 but how can I capture Out of Focus warning?

UPDATE

Filtered out unnecessary errors from logs

```<code>import logging
import gphoto2 as gp
from datetime import datetime
def main():
    def callback(level, domain, string, data=None):
        err_codes = ("(0x2005)", "(0x2019)")
        if not string.decode().endswith(err_codes):
            print("[{0}] {1}: {2}".format(datetime.utcnow(), domain.decode(), string.decode()))
        if data:
            print('Callback data:', data)

    callback_obj = gp.check_result(gp.gp_log_add_func(gp.GP_LOG_ERROR, callback))
    camera = gp.Camera()
    try:
        camera.init()
    except gp.GPhoto2Error as err:
        exit(err.code)

    try:
        camera_file_path = camera.capture(gp.GP_CAPTURE_IMAGE)
    except gp.GPhoto2Error as err:
        exit(err.code)
    camera.exit()

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

答:
If you can figure out the name of the logger, you can add your own handler to it and do your own log processing.

Calling "getLogger" with your camera library's name would get you the logger.

Calling AddHandler on that logger with a custom handler would allow you to do your own log processing for logs coming from that logger.

Please see Python's Logging Cookbook for more info

Hope this helps

Body:
Here is how I capture image with my camera

import logging
import gphoto2 as gp
def main():
    def callback(level, domain, string, data=None):
        print('Callback: level =', level, ', domain =', domain, ', string =', string)
        if data:
            print('Callback data:', data)

    logging.basicConfig(
        format='%(levelname)s: %(name)s: %(message)s', level=logging.WARNING)
    callback_obj = gp.check_result(gp.use_python_logging())

    camera = gp.Camera()
    camera.init()
    try:
        camera_file_path = gp.check_result(camera.capture(gp.GP_CAPTURE_IMAGE))
    except gp.GPhoto2Error as ex:
        print("callback: ", ex, ex.code, ex.message, ex.string)
    camera.exit()

if __name__ == "__main__" : exit(main())

If the camera is not able to focus it generates following error

...
WARNING: gphoto2: (ptp_usb_getresp [usb.c:466]) PTP_OC 0x90c8 receiving resp failed: Out of Focus (0xa002)
WARNING: gphoto2: (camera_nikon_capture [library.c:3153]) 'ret' failed: 'Out of Focus' (0xa002)
WARNING: gphoto2: (gp_context_error) Out of Focus
WARNING: gphoto2: (gp_camera_capture [gphoto2-camera.c:1340]) 'camera->functions->capture (camera, type, path, context)' failed: -1
('callback: ', GPhoto2Error('[-1] Unspecified error',), -1, '[-1] Unspecified error', 'Unspecified error')

The exception error code is -1 but how can I capture Out of Focus warning?

UPDATE

Filtered out unnecessary errors from logs

import logging
import gphoto2 as gp
from datetime import datetime
def main():
    def callback(level, domain, string, data=None):
        err_codes = ("(0x2005)", "(0x2019)")
        if not string.decode().endswith(err_codes):
            print("[{0}] {1}: {2}".format(datetime.utcnow(), domain.decode(), string.decode()))
        if data:
            print('Callback data:', data)

    callback_obj = gp.check_result(gp.gp_log_add_func(gp.GP_LOG_ERROR, callback))
    camera = gp.Camera()
    try:
        camera.init()
    except gp.GPhoto2Error as err:
        exit(err.code)

    try:
        camera_file_path = camera.capture(gp.GP_CAPTURE_IMAGE)
    except gp.GPhoto2Error as err:
        exit(err.code)
    camera.exit()

if __name__ == "__main__" : exit(main())


问:
Dynamic Code that applies a code row by row in VBA
Excel Sheet

I have the following code that corresponds to one row in the sheet. My Question is how to write this such that it continuously applies the code row by row until we reach the last row? Then, how would I write a dynamic code where if I added new rows, it recognizes to apply the code to those new lines.

For context what this code does is that it takes a user input, subtracts that value from March until either there is no more user input to subtract or if march has a value of 0. If march is 0 and we haven't subtracted all of the user input we move on to February and do the same thing, and so on until we reach January.

```<code>Sub variance_sub()

    Dim reduce As Double, c As Range, diff As Double

    reduce = InputBox("what is the Variance required? (Pressure use a positive number)")

    Set c = ActiveSheet.Range("T7") 'march cell

    If reduce = 0 Then
        MsgBox "No further action required"
    ElseIf reduce > 0 Then      'This is for a pressure'
        Do
            If c.Value >= reduce Then
                c.Value = c.Value - reduce
                reduce = 0
            Else
                diff = reduce - c.Value
                c.Value = 0
                reduce = diff
            End If
            If c.Column > 1 Then Set c = c.Offset(0, -1) 'move left if we can
        Loop While reduce > 0 And c.Column >= 18
    Else
        c.Value = c.Value + reduce
    End If

End Sub
</code>```

答:
Something like:</p>

```<code>Sub variance_sub()

    Dim reduce As Double, c As Range, diff As Double, rng As Range

    reduce = InputBox("what is the Variance required? (Pressure use a positive number)")
    'get range to process
    With ActiveSheet
        Set rng = .Range("T7:T" & .Cells(.Rows.Count, "T").End(xlUp).Row) 'march cell
    End With

    'loop through range
    For Each c In rng.Cells

        If reduce = 0 Then
            Debug.Print "No further action required" 'probably don't want msgbox
        ElseIf reduce > 0 Then      'This is for a pressure'
            Do
                If c.Value >= reduce Then
                    c.Value = c.Value - reduce
                    reduce = 0
                Else
                    diff = reduce - c.Value
                    c.Value = 0
                    reduce = diff
                End If
                If c.Column > 1 Then Set c = c.Offset(0, -1) 'move left if we can
            Loop While reduce > 0 And c.Column >= 18
        Else
            c.Value = c.Value + reduce
        End If

    Next c

End Sub
</code>```

Body:
Excel Sheet

I have the following code that corresponds to one row in the sheet. My Question is how to write this such that it continuously applies the code row by row until we reach the last row? Then, how would I write a dynamic code where if I added new rows, it recognizes to apply the code to those new lines.

For context what this code does is that it takes a user input, subtracts that value from March until either there is no more user input to subtract or if march has a value of 0. If march is 0 and we haven't subtracted all of the user input we move on to February and do the same thing, and so on until we reach January.

Sub variance_sub()

    Dim reduce As Double, c As Range, diff As Double

    reduce = InputBox("what is the Variance required? (Pressure use a positive number)")

    Set c = ActiveSheet.Range("T7") 'march cell

    If reduce = 0 Then
        MsgBox "No further action required"
    ElseIf reduce > 0 Then      'This is for a pressure'
        Do
            If c.Value >= reduce Then
                c.Value = c.Value - reduce
                reduce = 0
            Else
                diff = reduce - c.Value
                c.Value = 0
                reduce = diff
            End If
            If c.Column > 1 Then Set c = c.Offset(0, -1) 'move left if we can
        Loop While reduce > 0 And c.Column >= 18
    Else
        c.Value = c.Value + reduce
    End If

End Sub

Body:
Something like:

Sub variance_sub()

    Dim reduce As Double, c As Range, diff As Double, rng As Range

    reduce = InputBox("what is the Variance required? (Pressure use a positive number)")
    'get range to process
    With ActiveSheet
        Set rng = .Range("T7:T" & .Cells(.Rows.Count, "T").End(xlUp).Row) 'march cell
    End With

    'loop through range
    For Each c In rng.Cells

        If reduce = 0 Then
            Debug.Print "No further action required" 'probably don't want msgbox
        ElseIf reduce > 0 Then      'This is for a pressure'
            Do
                If c.Value >= reduce Then
                    c.Value = c.Value - reduce
                    reduce = 0
                Else
                    diff = reduce - c.Value
                    c.Value = 0
                    reduce = diff
                End If
                If c.Column > 1 Then Set c = c.Offset(0, -1) 'move left if we can
            Loop While reduce > 0 And c.Column >= 18
        Else
            c.Value = c.Value + reduce
        End If

    Next c

End Sub


问:
Run my JavaScript code on every page on my browser, similar to how a Chrome extension would
I know with Chrome I can use snippets to manually run some JavaScript code on a webpage. But this required manually executing the snippet. Is there a way to have some JavaScript code that my browser (Chrome or Firefox) would load every time I visit a new page?</p>

答:
You may be looking for userscripts. These allow you to write JavaScript code which will then be automatically executed whenever you visit a page matching a particular pattern.

For example, the following userscript:

```<code>// ==UserScript==
// @name             example name
// @include          /^https://example\.com/
// @grant            none
// ==/UserScript==

console.log('Hello, World!');
</code>```

will result in Hello, World! being logged to the console every time you visit https://example.com/.

To run userscripts, you need a userscript manager. Tampermonkey is the most popular choice - it works for all modern browsers.

Another option is a bookmarklet, which allow you to store code in a browser bookmark, but they require you to click on the bookmark link in order to execute the code - it won't run automatically. For example, a bookmark with the following URL:

```<code>javascript: (() => {  console.log('Hello, World!') })();
</code>```

will result in Hello, World! being logged to the console whenever the bookmarklet is clicked. For any code that isn't trivially short, a userscript is probably the more maintainable choice.

Body:
You may be looking for userscripts. These allow you to write JavaScript code which will then be automatically executed whenever you visit a page matching a particular pattern.

For example, the following userscript:

// ==UserScript==
// @name             example name
// @include          /^https://example\.com/
// @grant            none
// ==/UserScript==

console.log('Hello, World!');

will result in Hello, World! being logged to the console every time you visit https://example.com/.

To run userscripts, you need a userscript manager. Tampermonkey is the most popular choice - it works for all modern browsers.

Another option is a bookmarklet, which allow you to store code in a browser bookmark, but they require you to click on the bookmark link in order to execute the code - it won't run automatically. For example, a bookmark with the following URL:

javascript: (() => {  console.log('Hello, World!') })();

will result in Hello, World! being logged to the console whenever the bookmarklet is clicked. For any code that isn't trivially short, a userscript is probably the more maintainable choice.


问:
Remove white space from postgresql database columns not working
I'm trying to remove the whitespace that is trailing text in my PostgreSQL database, but nothing I try seems to work.

I have tried:

UPDATE posts SET caption = TRIM(caption)

UPDATE posts SET caption = TRIM(regexp_replace(caption, '\s+', ' ', 'g'))

Neither one of these has worked. I must have searched and tried several other things with no success.

I am using node-postgres in an express app to make API calls to retrieve my data.
After I update and I return my data via my API I get these results:

It's worth mentioning that if I do this:

SELECT TRIM(TRAILING FROM caption)...

This will remove the trailing whitespace. (yes, I have tried this on the update statement as well.)

Is there something else I can try?

I want to avoid adding TRIM to all of my columns that need it when there are a lot of them.

答:
Your "whitespace" chars could be vertical tab chars, which AFAIK are not "whitepace" chars.

Try using an extended characters in the regular replace() function:

```<code>update posts set caption  = trim(replace(replace(replace(caption, E'\v', ''), E'\n', ''), E'\r', '')))
</code>```

or regex:

```<code>update posts set caption = trim(regexp_replace(caption, '[\n\r\v\f\t]', '', 'g'))
</code>```

If this doesn't work, try inspecting each byte of your value to discover exactly what chars are in there:

```<code>select encode(caption::bytea, 'hex') -- display each character as hex
</code>```

Body:
Your "whitespace" chars could be vertical tab chars, which AFAIK are not "whitepace" chars.

Try using an extended characters in the regular replace() function:

update posts set caption  = trim(replace(replace(replace(caption, E'\v', ''), E'\n', ''), E'\r', '')))

or regex:

update posts set caption = trim(regexp_replace(caption, '[\n\r\v\f\t]', '', 'g'))

If this doesn't work, try inspecting each byte of your value to discover exactly what chars are in there:

select encode(caption::bytea, 'hex') -- display each character as hex


问:
Launch storyboards and iPhone X Safe Areas
I am updating an old app, and I would like the app to run letterbox, NOT full screen on iPhone X. That is, I want the entire app to stay within the Safe Areas and see black bars on the top and bottom.  Unfortunately the app uses a Launch Storyboard, which triggers the app to run full screen. The old solution was to use a launch image instead of a launch storyboard, but as of iOS 13 Apple has deprecated launch images. What can I do? The client definitely wants a logo to appear on launch. </p>

答:
What you are asking to do is now illegal. Your app must use a launch storyboard and occupy the entire screen or it will be rejected at the App Store.

The client definitely wants a logo to appear on launch.

Hmmm, it sounds as if you and/or the client don't understand what a launch screen is. A launch screen is merely the outline of the actual app interface, to provide something to fill the nasty pause between the time the user taps the app icon and the time the app's interface is up and running. If the client wants a logo on launch, that would be a view (possibly belonging to a view controller) shown as part of the running app when it starts up.


问:
Number of numeric values present in NVarchar column in SQL Server 2005
I have a Nvarchar column which contains data related to different data types such as Numerics, Dates and so on.
I wanted to find out number of cells with Numeric data type and number of cells with Date data type.

Thanks

答:
First at all you should split you column (create split function which will transform delimited string into column) . You can find a lot of examples in Internet. I have got one here . So here is an example:

```<code>declare @text nvarchar(max)='1211221,ssssss,1212,2010-02-01,20100201'
DECLARE @delimiter char(1)=','
 ;WITH Pieces(pn, start, stop) AS (
      SELECT CASt(1 as Int), CAST(1 as integer), CHARINDEX(@delimiter,@text)
      UNION ALL
      SELECT pn + 1, CAST(stop + 1 as integer), CHARINDEX(@delimiter,@text, stop + 1)
      FROM Pieces
      WHERE stop > 0
    ), T as(
    SELECT pn,
      SUBSTRING(@text, start, CASE WHEN stop > 0 THEN stop-start ELSE 512 END) AS s
    FROM Pieces)
SELECT
    SUM(CASE WHEN ISNUMERIC(T.s)=1 AND ISDATE(T.s)=0 THEN 1 ELSE 0 END) NumericCount,
    SUM(CASE WHEN ISDATE(T.s)=0 THEN 0 ELSE 1 END)DateCount
FROM T
</code>```

You will have 2 dates and 2 numeric counts

Body:
First at all you should split you column (create split function which will transform delimited string into column) . You can find a lot of examples in Internet. I have got one here . So here is an example:

declare @text nvarchar(max)='1211221,ssssss,1212,2010-02-01,20100201'
DECLARE @delimiter char(1)=','
 ;WITH Pieces(pn, start, stop) AS (
      SELECT CASt(1 as Int), CAST(1 as integer), CHARINDEX(@delimiter,@text)
      UNION ALL
      SELECT pn + 1, CAST(stop + 1 as integer), CHARINDEX(@delimiter,@text, stop + 1)
      FROM Pieces
      WHERE stop > 0
    ), T as(
    SELECT pn,
      SUBSTRING(@text, start, CASE WHEN stop > 0 THEN stop-start ELSE 512 END) AS s
    FROM Pieces)
SELECT
    SUM(CASE WHEN ISNUMERIC(T.s)=1 AND ISDATE(T.s)=0 THEN 1 ELSE 0 END) NumericCount,
    SUM(CASE WHEN ISDATE(T.s)=0 THEN 0 ELSE 1 END)DateCount
FROM T

You will have 2 dates and 2 numeric counts


问:
Nested documents in ElasticSearch without mapping types
With the planned removal of mapping types coming to ElasticSearch, does this also mean the deprecation of nested documents and nested queries? How would/will ElasticSearch support queries of nested objects in typeless context?

The functionality I'm considering is being able to return only the hits in a nested array that match search criteria.

Edit 1: Example mapping + query in ElasticSearch version 6

ElasticSearch 6 Mapping

```<code>{
    "rec": {
        "mappings": {
            "history": {
                "properties": {
                    "dateCompleted": {
                        "type": "keyword"
                    },
                    "dateCreated": {
                        "type": "keyword"
                    },
                    "dateOrdered": {
                        "type": "keyword"
                    },
                    "dateToArrive": {
                        "type": "keyword"
                    },
                    "details": {
                        "type": "nested",
                        "properties": {

                            "clientId": {
                                "type": "keyword"
                            },
                            "company": {
                                "type": "text",
                                "fields": {
                                    "keyword": {
                                        "type": "keyword",
                                        "ignore_above": 256
                                    }
                                }
                            },
                            "orderNumber": {
                                "type": "text",
                                "fields": {
                                    "keyword": {
                                        "type": "keyword",
                                        "ignore_above": 256
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
</code>```

ElasticSearch 6 Query

```<code>{
  "from": 0,
  "query": {
    "nested": {
      "inner_hits": {},
      "path": "details",
      "query": {
        "bool": {
          "must": [
            {
              "match_phrase": {
                "details.company.keyword": {
                  "query": "ABCD"
                }
              }
            }
          ]
        }
      }
    }
  },
  "size": 10,
  "sort": [],
  "_source": false
}
</code>```

答: It looks like the GetMapping method on the NEST client in versions 7+ has moved to IElasticSearchClient.Indicies.GetFieldMapping. My misunderstanding was that all types were being removed. In reality, it seems like the plan is to just have one type per index. Thanks @ibexit for the clarification.

Body:
With the planned removal of mapping types coming to ElasticSearch, does this also mean the deprecation of nested documents and nested queries? How would/will ElasticSearch support queries of nested objects in typeless context?

The functionality I'm considering is being able to return only the hits in a nested array that match search criteria.

Edit 1: Example mapping + query in ElasticSearch version 6

ElasticSearch 6 Mapping

{
    "rec": {
        "mappings": {
            "history": {
                "properties": {
                    "dateCompleted": {
                        "type": "keyword"
                    },
                    "dateCreated": {
                        "type": "keyword"
                    },
                    "dateOrdered": {
                        "type": "keyword"
                    },
                    "dateToArrive": {
                        "type": "keyword"
                    },
                    "details": {
                        "type": "nested",
                        "properties": {

                            "clientId": {
                                "type": "keyword"
                            },
                            "company": {
                                "type": "text",
                                "fields": {
                                    "keyword": {
                                        "type": "keyword",
                                        "ignore_above": 256
                                    }
                                }
                            },
                            "orderNumber": {
                                "type": "text",
                                "fields": {
                                    "keyword": {
                                        "type": "keyword",
                                        "ignore_above": 256
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

ElasticSearch 6 Query

{
  "from": 0,
  "query": {
    "nested": {
      "inner_hits": {},
      "path": "details",
      "query": {
        "bool": {
          "must": [
            {
              "match_phrase": {
                "details.company.keyword": {
                  "query": "ABCD"
                }
              }
            }
          ]
        }
      }
    }
  },
  "size": 10,
  "sort": [],
  "_source": false
}


问:
How can I populate a pandas DataFrame with the result of a Snowflake sql query?
Using the Python Connector I can query Snowflake:

```<code>import snowflake.connector

# Gets the version
ctx = snowflake.connector.connect(
    user=USER,
    password=PASSWORD,
    account=ACCOUNT,
    authenticator='https://XXXX.okta.com',
    )
ctx.cursor().execute('USE warehouse MY_WH')
ctx.cursor().execute('USE MYDB.MYSCHEMA')

query = '''
select * from MYDB.MYSCHEMA.MYTABLE
LIMIT 10;
'''

cur = ctx.cursor().execute(query)
</code>```

The result is a snowflake.connector.cursor.SnowflakeCursor. How can I convert that to a pandas DataFrame?

答:
There is now a method .fetch_pandas.all() for this, no need for SQL Alchemy anymore.

Note that you need to install snowflake.connector for pandas by doing this

```<code>pip install snowflake-connector-python[pandas]
</code>```

Full documentation here

```<code>import pandas as pd
import snowflake.connector

conn = snowflake.connector.connect(
            user="xxx",
            password="xxx",
            account="xxx",
            warehouse="xxx",
            database="MYDB",
            schema="MYSCHEMA"
            )

cur = conn.cursor()

# Execute a statement that will generate a result set.
sql = "select * from MYTABLE limit 10"
cur.execute(sql)
# Fetch the result set from the cursor and deliver it as the Pandas DataFrame.
df = cur.fetch_pandas_all()
</code>```

Body:
Using the Python Connector I can query Snowflake:

import snowflake.connector

# Gets the version
ctx = snowflake.connector.connect(
    user=USER,
    password=PASSWORD,
    account=ACCOUNT,
    authenticator='https://XXXX.okta.com',
    )
ctx.cursor().execute('USE warehouse MY_WH')
ctx.cursor().execute('USE MYDB.MYSCHEMA')

query = '''
select * from MYDB.MYSCHEMA.MYTABLE
LIMIT 10;
'''

cur = ctx.cursor().execute(query)

The result is a snowflake.connector.cursor.SnowflakeCursor. How can I convert that to a pandas DataFrame?

Body:
There is now a method .fetch_pandas.all() for this, no need for SQL Alchemy anymore.

Note that you need to install snowflake.connector for pandas by doing this

pip install snowflake-connector-python[pandas]

Full documentation here

import pandas as pd
import snowflake.connector

conn = snowflake.connector.connect(
            user="xxx",
            password="xxx",
            account="xxx",
            warehouse="xxx",
            database="MYDB",
            schema="MYSCHEMA"
            )

cur = conn.cursor()

# Execute a statement that will generate a result set.
sql = "select * from MYTABLE limit 10"
cur.execute(sql)
# Fetch the result set from the cursor and deliver it as the Pandas DataFrame.
df = cur.fetch_pandas_all()