问:
jQuery validate custom method not getting called
I have used jQuery.validator.addMethod to create a custom validate method that will make sure there is at least one row in my data-entry table. Using Firebug, my breakpoint in the method isn't being hit at all. Am I missing something?

Note: I am sure there are problems with the validation method itself, but that is because I can't debug it yet. I am still very much a novice with JavaScript.

Update: I have figured out that it isn't getting triggered because I didn't have the validator on an input field. I have it working now, however, is there a way to add a validation without attaching it to an input field?

Here is what my table looks like:

```<code><table id="editorRows">
    ...
    <tbody class="editorRow">
        <tr class="row1">
        </tr>
        <tr class="row2" style="display: none;">
        </tr>
        <tr class="row3" style="display:none;">
        </tr>
    </tbody>
    <tbody class="editorRow">
        <tr class="row1">
        </tr>
        <tr class="row2" style="display: none;">
        </tr>
        <tr class="row3" style="display:none;">
        </tr>
    </tbody>
</table>
</code>```

Here is my custom validator:

```<code>jQuery.validator.addMethod('required_row', function(val, el) {
    var rowCount = $("#editorRows tbody").length;
    if (typeof rowCount != "undefined") {
        return (rowCount > 0);
    } else {
        return false;
    };
}, "Your request must contain at least one day.");

// Validate the form before submitting
$("form").validate({
    rules: {
        "#editorRow": { required_row: true }
    }
});
</code>```

答: I have figured out that it isn't getting triggered because I didn't have the validator on an input field. I have it working now, however, is there a way to add a validation without attaching it to an input field?</p>

Body:
I have used jQuery.validator.addMethod to create a custom validate method that will make sure there is at least one row in my data-entry table. Using Firebug, my breakpoint in the method isn't being hit at all. Am I missing something?

Note: I am sure there are problems with the validation method itself, but that is because I can't debug it yet. I am still very much a novice with JavaScript.

Update: I have figured out that it isn't getting triggered because I didn't have the validator on an input field. I have it working now, however, is there a way to add a validation without attaching it to an input field?

Here is what my table looks like:

    ...

Here is my custom validator:

jQuery.validator.addMethod('required_row', function(val, el) {
    var rowCount = $("#editorRows tbody").length;
    if (typeof rowCount != "undefined") {
        return (rowCount > 0);
    } else {
        return false;
    };
}, "Your request must contain at least one day.");

// Validate the form before submitting
$("form").validate({
    rules: {
        "#editorRow": { required_row: true }
    }
});


来源: stackexchange

问:
macOS app crashes and does not prompt for camera permissions
My app works fine in any other macOS version except in Catalina. I have added the camera and microphone permissions in the Info.plist file as explained here but the app keeps crashing when it should prompt for permissions (I've even tried to add every single available permission that XCode provides). If I run my app from the terminal it actually prompts with "Terminal" would like to access the camera.

Any idea with this? Here is part of the log:

```<code>Process:               FooApp [1761]
Path:                  /Applications/FooApp.app/Contents/Home/bin/./FooApp
Identifier:            com.fooApp
Version:               1.6.0.3 (1.6.0.3)
Code Type:             X86-64 (Native)
Parent Process:        ??? [1757]
User ID:               501

Date/Time:             2019-12-03 13:53:30.472 +0100
OS Version:            Mac OS X 10.15.1 (19B88)
Report Version:        12
Anonymous UUID:        0FEAB303-C00B-E970-1979-5CE1CC615C4E

Time Awake Since Boot: 3100 seconds

System Integrity Protection: disabled

Crashed Thread:        19  Dispatch queue: com.apple.root.default-qos

Exception Type:        EXC_CRASH (SIGKILL)
Exception Codes:       0x0000000000000000, 0x0000000000000000
Exception Note:        EXC_CORPSE_NOTIFY

Termination Reason:    Namespace TCC, Code 0x0

Thread 19 Crashed:: Dispatch queue: com.apple.root.default-qos
0   libsystem_kernel.dylib          0x00007fff6377c15e __terminate_with_payload + 10
1   libsystem_kernel.dylib          0x00007fff63796512 abort_with_payload_wrapper_internal + 119
2   libsystem_kernel.dylib          0x00007fff6379651d abort_with_payload + 9
3   com.apple.TCC                   0x00007fff5b9060d1 __CRASHING_DUE_TO_PRIVACY_VIOLATION__ + 163
4   com.apple.TCC                   0x00007fff5b90602e __TCCAccessRequest_block_invoke.114 + 500
5   com.apple.TCC                   0x00007fff5b903bc5 __tccd_send_message_block_invoke + 231
6   libxpc.dylib                    0x00007fff63879ef4 _xpc_connection_reply_callout + 36
7   libxpc.dylib                    0x00007fff63879e7c _xpc_connection_call_reply_async + 69
8   libdispatch.dylib               0x00007fff635dc578 _dispatch_client_callout3 + 8
9   libdispatch.dylib               0x00007fff635f3080 _dispatch_mach_msg_async_reply_invoke + 369
10  libdispatch.dylib               0x00007fff635eb48c _dispatch_kevent_worker_thread + 1324
11  libsystem_pthread.dylib         0x00007fff63835763 _pthread_wqthread + 362
12  libsystem_pthread.dylib         0x00007fff6383557b start_wqthread + 15

Thread 20:: Dispatch queue: com.apple.root.default-qos
0   libsystem_kernel.dylib          0x00007fff6377a4a2 __wait4 + 10
1   libmonosgen-2.0.1.dylib         0x000000010e87fecd mono_handle_native_crash + 397
2   libsystem_platform.dylib        0x00007fff6382db1d _sigtramp + 29
3   libsystem_c.dylib               0x00007fff636ece1b __v2printf + 475
4   libsystem_kernel.dylib          0x00007fff6379651d abort_with_payload + 9
5   com.apple.TCC                   0x00007fff5b9060d1 __CRASHING_DUE_TO_PRIVACY_VIOLATION__ + 163
6   com.apple.TCC                   0x00007fff5b90602e __TCCAccessRequest_block_invoke.114 + 500
7   com.apple.TCC                   0x00007fff5b903bc5 __tccd_send_message_block_invoke + 231
8   libxpc.dylib                    0x00007fff63879ef4 _xpc_connection_reply_callout + 36
9   libxpc.dylib                    0x00007fff63879e7c _xpc_connection_call_reply_async + 69
10  libdispatch.dylib               0x00007fff635dc578 _dispatch_client_callout3 + 8
11  libdispatch.dylib               0x00007fff635f3080 _dispatch_mach_msg_async_reply_invoke + 369
12  libdispatch.dylib               0x00007fff635eb48c _dispatch_kevent_worker_thread + 1324
13  libsystem_pthread.dylib         0x00007fff63835763 _pthread_wqthread + 362
14  libsystem_pthread.dylib         0x00007fff6383557b start_wqthread + 15
</code>```

答:
Finally, after no help on the whole Internet I found that the problem is that the program that Info.plist uses to open my application is a script that sets up some needed stuff and then opens the program.

The error here is that my application is not using the Info.plist file for the application opened with the script since the script is the owner of that file. Then the application crashes since it has no Info.plist file where getting the message to prompt for permissions.

In my case I had to create a unix executable with mono mkbundle as the major change.

I wrote a post about packaging in macOS where I explain this here: https://www.theimpostersyndrome.dev/posts/macospackaging/

ContentLicense: CC BY-SA 4.0

Body:
My app works fine in any other macOS version except in Catalina. I have added the camera and microphone permissions in the Info.plist file as explained here but the app keeps crashing when it should prompt for permissions (I've even tried to add every single available permission that XCode provides). If I run my app from the terminal it actually prompts with "Terminal" would like to access the camera.

Any idea with this? Here is part of the log:

Process:               FooApp [1761]
Path:                  /Applications/FooApp.app/Contents/Home/bin/./FooApp
Identifier:            com.fooApp
Version:               1.6.0.3 (1.6.0.3)
Code Type:             X86-64 (Native)
Parent Process:        ??? [1757]
User ID:               501

Date/Time:             2019-12-03 13:53:30.472 +0100
OS Version:            Mac OS X 10.15.1 (19B88)
Report Version:        12
Anonymous UUID:        0FEAB303-C00B-E970-1979-5CE1CC615C4E

Time Awake Since Boot: 3100 seconds

System Integrity Protection: disabled

Crashed Thread:        19  Dispatch queue: com.apple.root.default-qos

Exception Type:        EXC_CRASH (SIGKILL)
Exception Codes:       0x0000000000000000, 0x0000000000000000
Exception Note:        EXC_CORPSE_NOTIFY

Termination Reason:    Namespace TCC, Code 0x0

Thread 19 Crashed:: Dispatch queue: com.apple.root.default-qos
0   libsystem_kernel.dylib          0x00007fff6377c15e __terminate_with_payload + 10
1   libsystem_kernel.dylib          0x00007fff63796512 abort_with_payload_wrapper_internal + 119
2   libsystem_kernel.dylib          0x00007fff6379651d abort_with_payload + 9
3   com.apple.TCC                   0x00007fff5b9060d1 __CRASHING_DUE_TO_PRIVACY_VIOLATION__ + 163
4   com.apple.TCC                   0x00007fff5b90602e __TCCAccessRequest_block_invoke.114 + 500
5   com.apple.TCC                   0x00007fff5b903bc5 __tccd_send_message_block_invoke + 231
6   libxpc.dylib                    0x00007fff63879ef4 _xpc_connection_reply_callout + 36
7   libxpc.dylib                    0x00007fff63879e7c _xpc_connection_call_reply_async + 69
8   libdispatch.dylib               0x00007fff635dc578 _dispatch_client_callout3 + 8
9   libdispatch.dylib               0x00007fff635f3080 _dispatch_mach_msg_async_reply_invoke + 369
10  libdispatch.dylib               0x00007fff635eb48c _dispatch_kevent_worker_thread + 1324
11  libsystem_pthread.dylib         0x00007fff63835763 _pthread_wqthread + 362
12  libsystem_pthread.dylib         0x00007fff6383557b start_wqthread + 15

Thread 20:: Dispatch queue: com.apple.root.default-qos
0   libsystem_kernel.dylib          0x00007fff6377a4a2 __wait4 + 10
1   libmonosgen-2.0.1.dylib         0x000000010e87fecd mono_handle_native_crash + 397
2   libsystem_platform.dylib        0x00007fff6382db1d _sigtramp + 29
3   libsystem_c.dylib               0x00007fff636ece1b __v2printf + 475
4   libsystem_kernel.dylib          0x00007fff6379651d abort_with_payload + 9
5   com.apple.TCC                   0x00007fff5b9060d1 __CRASHING_DUE_TO_PRIVACY_VIOLATION__ + 163
6   com.apple.TCC                   0x00007fff5b90602e __TCCAccessRequest_block_invoke.114 + 500
7   com.apple.TCC                   0x00007fff5b903bc5 __tccd_send_message_block_invoke + 231
8   libxpc.dylib                    0x00007fff63879ef4 _xpc_connection_reply_callout + 36
9   libxpc.dylib                    0x00007fff63879e7c _xpc_connection_call_reply_async + 69
10  libdispatch.dylib               0x00007fff635dc578 _dispatch_client_callout3 + 8
11  libdispatch.dylib               0x00007fff635f3080 _dispatch_mach_msg_async_reply_invoke + 369
12  libdispatch.dylib               0x00007fff635eb48c _dispatch_kevent_worker_thread + 1324
13  libsystem_pthread.dylib         0x00007fff63835763 _pthread_wqthread + 362
14  libsystem_pthread.dylib         0x00007fff6383557b start_wqthread + 15


问:
Informatica File date string convert into timestamp
I  have a column in file Delivery_date - '02/09/2020  15:30:00 PM' in string format . It can AM OR PM both.
I need to convert it on TIMESTAMP format of oracle in informatica power center.

I have tried like below-
TO_DATE(Delivery_date,'MM-DD-YYYY HH24:MI:SS')

But its not working for AM an PM. Kindly suggest

答:
If you want a TIMESTAMP data type then use TO_TIMESTAMP. Oracle does not allow both the HH24 and AM (or PM) format models as it will be ambiguous if the 24-hour clock and meridian indicator do not match; you will have to strip one of them out and since the AM/PM indicator is at the end of the string then that is easiest to remove using SUBSTR:

TO_TIMESTAMP( SUBSTR( delivery_date, 1, 19 ), 'MM/DD/YYYY HH24:MI:SS' )
```

db<>fiddle

(and if you just want a DATE data type, which in Oracle also has a time component, then use TO_DATE instead of TO_TIMESTAMP)

Body:
If you want a TIMESTAMP data type then use TO_TIMESTAMP. Oracle does not allow both the HH24 and AM (or PM) format models as it will be ambiguous if the 24-hour clock and meridian indicator do not match; you will have to strip one of them out and since the AM/PM indicator is at the end of the string then that is easiest to remove using SUBSTR:

TO_TIMESTAMP( SUBSTR( delivery_date, 1, 19 ), 'MM/DD/YYYY HH24:MI:SS' )

db<>fiddle

(and if you just want a DATE data type, which in Oracle also has a time component, then use TO_DATE instead of TO_TIMESTAMP)


问:
Getting error while getting view of RecyclerView in onActivityCreated()
I am following a tutorial on Udemy using RecyclerView using Fragments. Everything works fine until this line 44 recyclerView = view.findViewById(R.id.rcl)

I searched a lot on internet but did not get any solution related to this. I debugged the code and view was null. Either there was a problem in that tutorial or only i am having the problem.

1- Fragment_list.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".ListFrag">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rcl"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>
</code>```

2- ListFrag.jave

```<code> @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_list, container, false);
    // Inflate the layout for this fragment
    return view;
}

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    recyclerView = view.findViewById(R.id.rcl);
    recyclerView.setHasFixedSize(true);
    layoutManager = new LinearLayoutManager(this.getActivity());
    recyclerView.setLayoutManager(layoutManager);
    adapter = new PersonAdapter(this.getActivity(), ApplicationClass.people);
    recyclerView.setAdapter(adapter);
}
</code>```

3- This is the Error :

```<code>Error :
    java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
            at com.example.recyclerfragments.ListFrag.onActivityCreated(ListFrag.java:44)
            at androidx.fragment.app.Fragment.performActivityCreated(Fragment.java:2619)
            at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:904)
            at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManagerImpl.java:1238)
            at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:1303)
            at androidx.fragment.app.FragmentManagerImpl.dispatchStateChange(FragmentManagerImpl.java:2659)
            at androidx.fragment.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManagerImpl.java:2613)
            at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:246)
            at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:542)
            at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:201)
            at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1391)
            at android.app.Activity.performStart(Activity.java:7214)
            at android.app.ActivityThread.handleStartActivity(ActivityThread.java:3189)
            at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:185)
            at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:170)
            at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:147)
            at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:73)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2031)
            at android.os.Handler.dispatchMessage(Handler.java:106)
            at android.os.Looper.loop(Looper.java:224)
            at android.app.ActivityThread.main(ActivityThread.java:7083)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:536)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:928)
</code>```

答:
put your code in onViewCreated() this is for kotlin, for java just override the method and put your code in it

make sure your view object is globally declared so it will not be null after view created

like this:

```<code>override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        recyclerView = view.findViewById(R.id.rcl)
        recyclerView.setHasFixedSize(true)
        layoutManager = LinearLayoutManager(this.activity)
        recyclerView.setLayoutManager(layoutManager)
        adapter = PersonAdapter(this.activity, ApplicationClass.people)
        recyclerView.setAdapter(adapter)
    }
</code>```

Body:
I am following a tutorial on Udemy using RecyclerView using Fragments. Everything works fine until this line 44 recyclerView = view.findViewById(R.id.rcl)

I searched a lot on internet but did not get any solution related to this. I debugged the code and view was null. Either there was a problem in that tutorial or only i am having the problem.

1- Fragment_list.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".ListFrag">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rcl"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

2- ListFrag.jave

 @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_list, container, false);
    // Inflate the layout for this fragment
    return view;
}

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    recyclerView = view.findViewById(R.id.rcl);
    recyclerView.setHasFixedSize(true);
    layoutManager = new LinearLayoutManager(this.getActivity());
    recyclerView.setLayoutManager(layoutManager);
    adapter = new PersonAdapter(this.getActivity(), ApplicationClass.people);
    recyclerView.setAdapter(adapter);
}

3- This is the Error :

Error :
    java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
            at com.example.recyclerfragments.ListFrag.onActivityCreated(ListFrag.java:44)
            at androidx.fragment.app.Fragment.performActivityCreated(Fragment.java:2619)
            at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:904)
            at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManagerImpl.java:1238)
            at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:1303)
            at androidx.fragment.app.FragmentManagerImpl.dispatchStateChange(FragmentManagerImpl.java:2659)
            at androidx.fragment.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManagerImpl.java:2613)
            at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:246)
            at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:542)
            at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:201)
            at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1391)
            at android.app.Activity.performStart(Activity.java:7214)
            at android.app.ActivityThread.handleStartActivity(ActivityThread.java:3189)
            at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:185)
            at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:170)
            at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:147)
            at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:73)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2031)
            at android.os.Handler.dispatchMessage(Handler.java:106)
            at android.os.Looper.loop(Looper.java:224)
            at android.app.ActivityThread.main(ActivityThread.java:7083)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:536)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:928)

Body:
put your code in onViewCreated() this is for kotlin, for java just override the method and put your code in it

make sure your view object is globally declared so it will not be null after view created

like this:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        recyclerView = view.findViewById(R.id.rcl)
        recyclerView.setHasFixedSize(true)
        layoutManager = LinearLayoutManager(this.activity)
        recyclerView.setLayoutManager(layoutManager)
        adapter = PersonAdapter(this.activity, ApplicationClass.people)
        recyclerView.setAdapter(adapter)
    }


问:
Inserting Russian characters in table when file is loaded from SSIS
I'm trying to insert some value that is having Russian characters from SSIS.

Say I have a MYDATA.TXT (comma separated) and data as below

```<code>REM,DES,ID
FR1,Головка,8
GY2,6-гр,9
MO0,Болт,2
</code>```

1st row is column headers. I'm using this in Flat file. After executing the task, the value are different in my table something like Ð“Ð¾Ð»Ð¾Ð²ÐºÐ°

After some research I found that i have to use N before the text and column should be NVARCHAR. But i'm not sure how to do this in SSIS. I have around 1.2 million records, should I prefix my column with N for all rows or is there any other way in SSIS?

答:
Try to change the code page to 65001 (UTF-8).

In Advanced tab change the Datatype of DES column to unicode string [DT_WSTR]

Output:

Body:
I'm trying to insert some value that is having Russian characters from SSIS.

Say I have a MYDATA.TXT (comma separated) and data as below

REM,DES,ID
FR1,Головка,8
GY2,6-гр,9
MO0,Болт,2

1st row is column headers. I'm using this in Flat file. After executing the task, the value are different in my table something like Ð“Ð¾Ð»Ð¾Ð²ÐºÐ°

After some research I found that i have to use N before the text and column should be NVARCHAR. But i'm not sure how to do this in SSIS. I have around 1.2 million records, should I prefix my column with N for all rows or is there any other way in SSIS?


问:
entropy python implementation
I'm trying to rewrite this matlab/octave repo in python. I've came up on what seems to be an implementation of a function of entropy (see below). After some research,I've found on google that I can use scipy's entropy implementation for python. But after reading more on scipy's entropy formula (e.g S = -sum(pk * log(pk), axis=0)), I'm having a doubt that those two are computing the same thing...

Could anyone confirm my thought please?

```<code>%�������� author by YangSong 2010.11.16 C230
%file:ys_sampEntropy.m
% code is called from line 101 of algotrading.m
%  =>   entropy180(i)=ys_sampEntropy(kmeans180s1(i,1:180));
% where kmeans180s1 is an array of size 100x181 containing the kmeans
% centroids and the prize label at position 181.

function sampEntropy=ys_sampEntropy(xdata)
m=2;
n=length(xdata);
r=0.2*std(xdata);%ƥ��ģ��������ֵ
%r=0.05;
cr=[];
gn=1;
gnmax=m;
while gn<=gnmax
      d=zeros(n-m+1,n-m);% ���ž��������ľ���
      x2m=zeros(n-m+1,m);%���ű任�������
      cr1=zeros(1,n-m+1);%���Ž����ľ���
      k=1;

      for i=1:n-m+1

          for j=1:m
              x2m(i,j)=xdata(i+j-1);
          end

      end
      x2m;

      for i=1:n-m+1

          for j=1:n-m+1

              if i~=j
                 d(i,k)=max(abs(x2m(i,:)-x2m(j,:)));%��������Ԫ�غ���ӦԪ�صľ���
                 k=k+1;
              end

          end

          k=1;
      end
      d;

      for i=1:n-m+1
          [k,l]=size(find(d(i,:)<r));%����RС�ĸ������͸�L
          cr1(1,i)=l;
      end
      cr1;

      cr1=(1/(n-m))*cr1;
      sum1=0;

      for i=1:n-m+1

          if cr1(i)~=0
             %sum1=sum1+log(cr1(i));
             sum1=sum1+cr1(i);
          end  %if����

      end  %for����

      cr1=1/(n-m+1)*sum1;
      cr(1,gn)=cr1;
      gn=gn+1;
      m=m+1;
end        %while����
cr;

sampEntropy=log(cr(1,1))-log(cr(1,2));
</code>```

答:
```<code>    ##Entropy
def entropy(Y):
    """
    Also known as Shanon Entropy
    Reference: https://en.wikipedia.org/wiki/Entropy_(information_theory)
    """
    unique, count = np.unique(Y, return_counts=True, axis=0)
    prob = count/len(Y)
    en = np.sum((-1)*prob*np.log2(prob))
    return en

#Joint Entropy
def jEntropy(Y,X):
    """
    H(Y;X)
    Reference: https://en.wikipedia.org/wiki/Joint_entropy
    """
    YX = np.c_[Y,X]
    return entropy(YX)

#Conditional Entropy
def cEntropy(Y, X):
    """
    conditional entropy = Joint Entropy - Entropy of X
    H(Y|X) = H(Y;X) - H(X)
    Reference: https://en.wikipedia.org/wiki/Conditional_entropy
    """
    return jEntropy(Y, X) - entropy(X)

#Information Gain
def gain(Y, X):
    """
    Information Gain, I(Y;X) = H(Y) - H(Y|X)
    Reference: https://en.wikipedia.org/wiki/Information_gain_in_decision_trees#Formal_definition
    """
    return entropy(Y) - cEntropy(Y,X)
</code>```

ContentLicense: CC BY-SA 3.0

Title: entropy python implementation

Body:
I'm trying to rewrite this matlab/octave repo in python. I've came up on what seems to be an implementation of a function of entropy (see below). After some research,I've found on google that I can use scipy's entropy implementation for python. But after reading more on scipy's entropy formula (e.g S = -sum(pk * log(pk), axis=0)), I'm having a doubt that those two are computing the same thing...

Could anyone confirm my thought please?

%�������� author by YangSong 2010.11.16 C230
%file:ys_sampEntropy.m
% code is called from line 101 of algotrading.m
%  =>   entropy180(i)=ys_sampEntropy(kmeans180s1(i,1:180));
% where kmeans180s1 is an array of size 100x181 containing the kmeans
% centroids and the prize label at position 181.

function sampEntropy=ys_sampEntropy(xdata)
m=2;
n=length(xdata);
r=0.2*std(xdata);%ƥ��ģ��������ֵ
%r=0.05;
cr=[];
gn=1;
gnmax=m;
while gn<=gnmax
      d=zeros(n-m+1,n-m);% ���ž��������ľ���
      x2m=zeros(n-m+1,m);%���ű任�������
      cr1=zeros(1,n-m+1);%���Ž����ľ���
      k=1;

      for i=1:n-m+1

          for j=1:m
              x2m(i,j)=xdata(i+j-1);
          end

      end
      x2m;

      for i=1:n-m+1

          for j=1:n-m+1

              if i~=j
                 d(i,k)=max(abs(x2m(i,:)-x2m(j,:)));%��������Ԫ�غ���ӦԪ�صľ���
                 k=k+1;
              end

          end

          k=1;
      end
      d;

      for i=1:n-m+1
          [k,l]=size(find(d(i,:)<r));%����RС�ĸ������͸�L
          cr1(1,i)=l;
      end
      cr1;

      cr1=(1/(n-m))*cr1;
      sum1=0;

      for i=1:n-m+1

          if cr1(i)~=0
             %sum1=sum1+log(cr1(i));
             sum1=sum1+cr1(i);
          end  %if����

      end  %for����

      cr1=1/(n-m+1)*sum1;
      cr(1,gn)=cr1;
      gn=gn+1;
      m=m+1;
end        %while����
cr;

sampEntropy=log(cr(1,1))-log(cr(1,2));


问:
Test with many variables: I looking for quick method to introduce each variable in the test
I have some data and I need to compare the average but I am looking for quick method to introduce each sample in the test.

```<code>from scipy import stats

my_variables = ["a","b","c"]
my_variables[0] = [1,2,3]
my_variables[1] = [0,1,2]
my_variables[2] = [2,3,4]

Kruskal_Wallis_test= stats.kruskal(my_variables[0], my_variables[1], my_variables[2])
</code>```

Would be it possible doing something like this?

```<code>Kruskal_Wallis_test= stats.kruskal(my_variables)
</code>```

答:
You can use * to unpack your list variable

```<code>from scipy import stats

my_variables = list()
my_variables.append([1,2,3])
my_variables.append([0,1,2])
my_variables.append([2,3,4])

Kruskal_Wallis_test= stats.kruskal(*my_variables)

print(Kruskal_Wallis_test)
</code>```

Response
KruskalResult(statistic=3.9532163742690107, pvalue=0.13853833742651062)

Body:
I have some data and I need to compare the average but I am looking for quick method to introduce each sample in the test.

from scipy import stats

my_variables = ["a","b","c"]
my_variables[0] = [1,2,3]
my_variables[1] = [0,1,2]
my_variables[2] = [2,3,4]

Kruskal_Wallis_test= stats.kruskal(my_variables[0], my_variables[1], my_variables[2])

Would be it possible doing something like this?

Kruskal_Wallis_test= stats.kruskal(my_variables)

Body:
You can use * to unpack your list variable

from scipy import stats

my_variables = list()
my_variables.append([1,2,3])
my_variables.append([0,1,2])
my_variables.append([2,3,4])

Kruskal_Wallis_test= stats.kruskal(*my_variables)

print(Kruskal_Wallis_test)

Response
KruskalResult(statistic=3.9532163742690107, pvalue=0.13853833742651062)


问:
Uploading multiple files and displaying progress bar
I'm working on a project (in Django) where I have created a page to add data information about a file and then add the file itself.

When 'More datasets' button is clicked, it adds another field to upload another file.

This can be done to attach as many files as the end-user wants in one go.

What I need is to upload all the attached files once 'Upload data-sets' is clicked and individual progress bar should be displayed.

So far, I have run through multiple tutorials but came kinda close using Vitor Freitas's tutorial.

JS code :

```<code>$(function(){
/*$("#add_new_dataset").click(function(){
    $(".file").click();
});*/

$(".file").fileupload({
    dataType: 'json',
    sequentialUploads: true, /* Send the files one by one */
    start: function(e){ /* When the upload process starts, show the modal */
        $("#modal-progress").modal("show");
    },
    stop: function(e){  /* When the upload progress finalizes, hide the modal */
        $("#modal-progress").modal("hide");
    },
    progressall: function(e, data){ /* Update the progress bar */
        var progress = parseInt(data.loaded / data.total * 100, 10),
            strProgress = progress + "%";
            $(".progress-bar").css({"width": strProgress});
            $(".progress-bar").text(strProgress);
    },
    done: function(e, data){
        if(data.result.is_valid){
            $("#gallery tbody").prepend(
                "<tr><td><a href='" + data.result.url + "'>" + data.result.name + "</a></td></tr>"
            );
        }
    }
})
});
</code>```

Template code :

```<code><form id="form" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<div class="container-fluid" id="datasets" style="margin: 0px; padding: 0px;">
    <div class="row" onfocusin="populateFilename(this);">
        <label class="col-md-2">User Name :</label>
        <input class="col-md-2" type="text" id="username" name="user_name" value="{{ user.username }}" readonly />
        <label class="col-md-2">Data-set :</label>
        <input class="col-md-2" type="text" placeholder="Enter dataset" name="dataset" required />
        <label class="col-md-2">Creation Date :</label>
        <input class="col-md-2" type="date" placeholder="YYYY-MM-DD" name="creation_date" required />
        <label class="col-md-2">Beam Line:</label>
        <input class="col-md-2" type="text" placeholder="Enter beam line" name="beamline" required />
        <label class="col-md-2">Data-set file:</label>
        <input class="col-md-2 file" type="file" name="file" data-url="{% url 'add_data_sets' %}" data-form-data='{"csrfmiddlewaretoken": "{{ csrf_token }}"}' required />
        <label class="filename"></label>

        <div class="modal fade" id="modal-progress" data-backdrop="static" data-keyboard="false">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h4 class="modal-title">Uploading...</h4>
                    </div>
                    <div class="modal-body">
                        <div class="progress">
                            <div class="progress-bar" role="progressbar" style="width: 0%;">0%</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<div style="align: center; margin-top: 5px;">
    <div class="container btn-group btn-group-justified btn-group-lg">
        <a onmouseup="addRow();" class="btn btn-outline-secondary" style="width: 50%;">More Datasets</a>
        <button type="submit" class="btn btn-outline-primary" name="add_new_dataset" id="add_new_dataset">Submit Data-set</button>
    </div>
</div>
</code>```

What should I do? I'm not very good at AJAX but I can't see any code that works to send the data to the server side. Is it so or am I missing something? Kindly ignore my ignorance on the topic and thanks to all in advance.

EDIT :

The JS code has been rewritten based on some of the answers.

document.getElementById('add_new_dataset').onclick = function() {
    $(this).preventDefault();

    console.log('Files uploading begin');
    form_data = new FormData();
    const files = document.getElementsByName('file');
    let count = 0;
    for(let i = 0; i < files.length; i++){
        count++;
        form_data.append("file", files[i]);
    }

    $.ajax({
        url: "/add_data_sets",
        dataType: 'json',
        contentType: false,
        processData: false,
        data: form_data,
        type: 'POST',
        success: function(files, response, xhr, pd){
            $('.file').show();
            if(files.status != false){
                $('.progress-bar').val('/location/' + files.filename);

                var fileData = files.filename;
                console.log('Files uploading...');
            }
            else{
                alert(files.filename);
            }
        },
        /*xhrFields: {
            onprogress: function(e) {
                if(e.lengthComputable) {
                    let percentCompleted = e.loaded / evt.total;
                    pBar.style.width = percentComplete;
                    pBar.innerHTML = percentComplete + "%";
                    console.log('Percent complete : ' + percentComplete);
                }
            }
        }*/
        xhr: function(){
            let xhr = $.ajaxSettings.xhr();
            xhr.upload.onprogress = function(e) {
                let percentCompleted = e.loaded / evt.total * 100;
                pBar.style.width = percentComplete;
                pBar.innerHTML = percentComplete + "%";
                console.log('Percent complete : ' + percentComplete);
            };
            return xhr;
        }

    });
//});
};
```

<p>This is just the upload code block. The sending of the data from client-side to server-side works perfectly but it makes be suspicious as the 'console.log' calls aren't being triggered when the code runs through it. Is it so that the data is, somehow, being submitted normally and this code is doing nothing.<br /><br />
<strong>EDIT2 : </strong>
A new JS function:</p>

```function upload() {
        console.log('Upload function begins');
        let pBar = document.getElementsByClassName('progress-bar')[0],
            progressWindow = document.getElementById('modal-progress'),
            formData = new FormData(document.forms.form),
            xhr = new XMLHttpRequest(),
            percent = 0;

        console.log('Form Data created');
        // Start upload
        xhr.upload.onloadstart = function() {
            //$('#modal-progress').hide().fadeIn();
            //progressWindow
        };

        // Track upload progress
        xhr.upload.onprogress = function(event) {
            percent = parseInt(event.loaded / event.total * 100);
            pBar.innerHTML = percent + "%";
            pBar.style.width = percent + "%";
            //console.log(percent + '% completed');
            //console.log('Uploaded event.loaded of event.total');
        };

        // Report if ends with an error
        xhr.upload.onerror = function() {
            console.log('An error has occurred')
        };

        // Track completion: Both successful or not
        xhr.upload.onloadend = function() {
            //$('#modal-progress').fadeOut().hide();
            console.log('Upload complete with or without error ' + xhr.status);
        };

        // Track progress: Triggered on successful completion
        xhr.upload.onload = function() {
            console.log('Uploading complete');
            progressWindow.hidden = True;
        };

        xhr.open("POST", "{% url 'add_data_sets' %}", true);

        // The 'setRequestHeader' function can only be called when xhr is opened.
        //xhr.setRequestHeader('csrfmiddlewaretoken', '{{ csrf_token }}');
        //xhr.setRequestHeader('test-info', 'something');
        xhr.setRequestHeader('Content-Type', 'application/gzip');

        xhr.send(formData);
    }
```

<p><br />The function works fine now. It sends the data completely fine but on the development server console screen I get this error.</p>

```Forbidden (CSRF token missing or incorrect.): /accounts/add_data_set/
[22/Feb/2020 15:36:06] "POST /accounts/add_data_set/ HTTP/1.1" 403 2513
```

<p>I even checked logged the POST data being send to the server and it does contain the csrf token</p>

```<QueryDict: {'csrfmiddlewaretoken': ['WREoIV0aY4B2XyrU7d9Qw8kMwiokXqwWsmbc2QSHX5VQ0EaYjjeuv7PeysMJjecp'], 'user_name': ['rakesh'], 'dataset': ['r'], 'creation_date': ['2020-02-22'], 'beamline': ['r']}>
```

I'm kind of confused. Is this an issue?

答:
If you have any fileuploader plugin their documentations will have everything, or if you want normal file upload input you can post them by binding file input to form data and then post on action which will manipulate form data and save images, then you can return save image and display,  this way you can achieve simple ajax upload. </p>

```<code>var form_data = new FormData();
        var totalFiles = document.getElementById('file').files.length;
        var count = 0;
        for (var i = 0; i < totalFiles; i++) {
            var file = document.getElementById('file').files[i];
            count++;
            form_data.append("file", file);
        }

$.ajax({
            url: "/uploadingaction",
            dataType: 'json',
            contentType: false,
            processData: false,
            data: form_data,
            type: 'POST',
            success: function (files, response, xhr, pd) {
                $('yourloaderid').hide();
                if (files.status != false) {
                    $('#displayid').val('/location/' + files.filename);

                    var filedata = files.filename;

                } else {
                    alert(files.filename);
                }

            }
        })
</code>```

Body:
I'm working on a project (in Django) where I have created a page to add data information about a file and then add the file itself.

When 'More datasets' button is clicked, it adds another field to upload another file.

This can be done to attach as many files as the end-user wants in one go.

What I need is to upload all the attached files once 'Upload data-sets' is clicked and individual progress bar should be displayed.

So far, I have run through multiple tutorials but came kinda close using Vitor Freitas's tutorial.

JS code :

$(function(){
/*$("#add_new_dataset").click(function(){
    $(".file").click();
});*/

$(".file").fileupload({
    dataType: 'json',
    sequentialUploads: true, /* Send the files one by one */
    start: function(e){ /* When the upload process starts, show the modal */
        $("#modal-progress").modal("show");
    },
    stop: function(e){  /* When the upload progress finalizes, hide the modal */
        $("#modal-progress").modal("hide");
    },
    progressall: function(e, data){ /* Update the progress bar */
        var progress = parseInt(data.loaded / data.total * 100, 10),
            strProgress = progress + "%";
            $(".progress-bar").css({"width": strProgress});
            $(".progress-bar").text(strProgress);
    },
    done: function(e, data){
        if(data.result.is_valid){
            $("#gallery tbody").prepend(
                "
" + data.result.name + "
"
            );
        }
    }
})
});

Template code :

<form id="form" method="POST" enctype="multipart/form-data">
{% csrf_token %}

        User Name :
        <input class="col-md-2" type="text" id="username" name="user_name" value="{{ user.username }}" readonly />
        Data-set :
        <input class="col-md-2" type="text" placeholder="Enter dataset" name="dataset" required />
        Creation Date :
        <input class="col-md-2" type="date" placeholder="YYYY-MM-DD" name="creation_date" required />
        Beam Line:
        <input class="col-md-2" type="text" placeholder="Enter beam line" name="beamline" required />
        Data-set file:
        <input class="col-md-2 file" type="file" name="file" data-url="{% url 'add_data_sets' %}" data-form-data='{"csrfmiddlewaretoken": "{{ csrf_token }}"}' required />

Uploading...

0%

        More Datasets
        <button type="submit" class="btn btn-outline-primary" name="add_new_dataset" id="add_new_dataset">Submit Data-set</button>

What should I do? I'm not very good at AJAX but I can't see any code that works to send the data to the server side. Is it so or am I missing something? Kindly ignore my ignorance on the topic and thanks to all in advance.

EDIT :

The JS code has been rewritten based on some of the answers.

document.getElementById('add_new_dataset').onclick = function() {
    $(this).preventDefault();

    console.log('Files uploading begin');
    form_data = new FormData();
    const files = document.getElementsByName('file');
    let count = 0;
    for(let i = 0; i < files.length; i++){
        count++;
        form_data.append("file", files[i]);
    }

    $.ajax({
        url: "/add_data_sets",
        dataType: 'json',
        contentType: false,
        processData: false,
        data: form_data,
        type: 'POST',
        success: function(files, response, xhr, pd){
            $('.file').show();
            if(files.status != false){
                $('.progress-bar').val('/location/' + files.filename);

                var fileData = files.filename;
                console.log('Files uploading...');
            }
            else{
                alert(files.filename);
            }
        },
        /*xhrFields: {
            onprogress: function(e) {
                if(e.lengthComputable) {
                    let percentCompleted = e.loaded / evt.total;
                    pBar.style.width = percentComplete;
                    pBar.innerHTML = percentComplete + "%";
                    console.log('Percent complete : ' + percentComplete);
                }
            }
        }*/
        xhr: function(){
            let xhr = $.ajaxSettings.xhr();
            xhr.upload.onprogress = function(e) {
                let percentCompleted = e.loaded / evt.total * 100;
                pBar.style.width = percentComplete;
                pBar.innerHTML = percentComplete + "%";
                console.log('Percent complete : ' + percentComplete);
            };
            return xhr;
        }

    });
//});
};

This is just the upload code block. The sending of the data from client-side to server-side works perfectly but it makes be suspicious as the 'console.log' calls aren't being triggered when the code runs through it. Is it so that the data is, somehow, being submitted normally and this code is doing nothing.

EDIT2 :
A new JS function:

function upload() {
        console.log('Upload function begins');
        let pBar = document.getElementsByClassName('progress-bar')[0],
            progressWindow = document.getElementById('modal-progress'),
            formData = new FormData(document.forms.form),
            xhr = new XMLHttpRequest(),
            percent = 0;

        console.log('Form Data created');
        // Start upload
        xhr.upload.onloadstart = function() {
            //$('#modal-progress').hide().fadeIn();
            //progressWindow
        };

        // Track upload progress
        xhr.upload.onprogress = function(event) {
            percent = parseInt(event.loaded / event.total * 100);
            pBar.innerHTML = percent + "%";
            pBar.style.width = percent + "%";
            //console.log(percent + '% completed');
            //console.log('Uploaded event.loaded of event.total');
        };

        // Report if ends with an error
        xhr.upload.onerror = function() {
            console.log('An error has occurred')
        };

        // Track completion: Both successful or not
        xhr.upload.onloadend = function() {
            //$('#modal-progress').fadeOut().hide();
            console.log('Upload complete with or without error ' + xhr.status);
        };

        // Track progress: Triggered on successful completion
        xhr.upload.onload = function() {
            console.log('Uploading complete');
            progressWindow.hidden = True;
        };

        xhr.open("POST", "{% url 'add_data_sets' %}", true);

        // The 'setRequestHeader' function can only be called when xhr is opened.
        //xhr.setRequestHeader('csrfmiddlewaretoken', '{{ csrf_token }}');
        //xhr.setRequestHeader('test-info', 'something');
        xhr.setRequestHeader('Content-Type', 'application/gzip');

        xhr.send(formData);
    }

The function works fine now. It sends the data completely fine but on the development server console screen I get this error.

Forbidden (CSRF token missing or incorrect.): /accounts/add_data_set/
[22/Feb/2020 15:36:06] "POST /accounts/add_data_set/ HTTP/1.1" 403 2513

I even checked logged the POST data being send to the server and it does contain the csrf token

<QueryDict: {'csrfmiddlewaretoken': ['WREoIV0aY4B2XyrU7d9Qw8kMwiokXqwWsmbc2QSHX5VQ0EaYjjeuv7PeysMJjecp'], 'user_name': ['rakesh'], 'dataset': ['r'], 'creation_date': ['2020-02-22'], 'beamline': ['r']}>

I'm kind of confused. Is this an issue?

Body:
If you have any fileuploader plugin their documentations will have everything, or if you want normal file upload input you can post them by binding file input to form data and then post on action which will manipulate form data and save images, then you can return save image and display,  this way you can achieve simple ajax upload.

var form_data = new FormData();
        var totalFiles = document.getElementById('file').files.length;
        var count = 0;
        for (var i = 0; i < totalFiles; i++) {
            var file = document.getElementById('file').files[i];
            count++;
            form_data.append("file", file);
        }

$.ajax({
            url: "/uploadingaction",
            dataType: 'json',
            contentType: false,
            processData: false,
            data: form_data,
            type: 'POST',
            success: function (files, response, xhr, pd) {
                $('yourloaderid').hide();
                if (files.status != false) {
                    $('#displayid').val('/location/' + files.filename);

                    var filedata = files.filename;

                } else {
                    alert(files.filename);
                }

            }
        })


问:
Laravel 5.4 collection sortByDesc not working
I have two queries with Eloquent which I collect and merge and after i do sortByDesc but it's not sorting collection.

```<code>$f_games = collect(Game::with('fUser', 'sUser')->where('first_user_id', Auth::user()->id)>get());
$s_games = collect(Game::with('fUser', 'sUser')->where('second_user_id', Auth::user()->id)->get());

$response = $f_games->merge($s_games)->sortByDesc('id');
</code>```

答:
The sortByDesc method sorts the collection by field that belongs to some eloquent relation in your model.

If you are trying to sort collection with sortByDesc for model itself ( your current object of model), please user orderBy rather than sortByDesc

Example:

For model itself

```<code>{$collection_list = $this->model_name->orderBy('field_name','DESC')->get();}
</code>```

For relations that will be lazy loaded in views

```<code>{$collection_list = $this->model_name->get()->sortBy('table_name.field_name', SORT_REGULAR, true);}
</code>```

Note: sortByDesc internally called sortBy() with descending order,
       true means Descending Order and false means Ascending Order.

Body:
I have two queries with Eloquent which I collect and merge and after i do sortByDesc but it's not sorting collection.

$f_games = collect(Game::with('fUser', 'sUser')->where('first_user_id', Auth::user()->id)>get());
$s_games = collect(Game::with('fUser', 'sUser')->where('second_user_id', Auth::user()->id)->get());

$response = $f_games->merge($s_games)->sortByDesc('id');

Body:
The sortByDesc method sorts the collection by field that belongs to some eloquent relation in your model.

If you are trying to sort collection with sortByDesc for model itself ( your current object of model), please user orderBy rather than sortByDesc

Example:

For model itself

{$collection_list = $this->model_name->orderBy('field_name','DESC')->get();}

For relations that will be lazy loaded in views

{$collection_list = $this->model_name->get()->sortBy('table_name.field_name', SORT_REGULAR, true);}

Note: sortByDesc internally called sortBy() with descending order,
       true means Descending Order and false means Ascending Order.


问:
Flutter - Stream error not persisting (using bloc pattern)
So I am trying to make a signup form in flutter using streams and the bloc pattern.

The problem is that the error added to the sink for one my streams does not seem to persist?

The submitValid getter does not seem to consider the error added to the passwordretype stream, this causes the login button to be clickable when it shouldn't

Steps to reproduce:

Fill out a valid email

Fill out a valid password (password field)

Fill out a valid password (password retype field)

Delete everything from the retype field

Delete everything from the password field.

Type a valid password in the password field and the login button appears clickable even though the retype field is empty.

Here's my code along with a screenshot.

Bloc.dart

```<code>import 'dart:async';
import 'package:firebase_auth/firebase_auth.dart';

import 'validators.dart';
import 'dart:io';
import 'package:rxdart/rxdart.dart';

class Bloc extends Object with Validators {

  final _email = BehaviorSubject<String>();
  final _password = BehaviorSubject<String>();
  final _passwordretype = BehaviorSubject<String>();
  final _isSignedIn = BehaviorSubject<bool>();

  //Add data to stream
  Stream<String> get email => _email.stream.transform(validateEmail);
  Stream<String> get password => _password.stream.transform(validatePassword);

  Stream<String> get passwordretype=> _passwordretype.stream.transform(validatePasswordRetype)
  .doOnData((String c){
    if(0 != _password.value.compareTo(c)){
      _passwordretype.addError("Passwords do not match");
    }
  });

  Stream<bool> get signInStatus => _isSignedIn.stream;

  Stream<bool> get submitValid =>
    Rx.combineLatest3(email, password, passwordretype, (e, p, r) => true);

  //Change data
  Function(String) get changeEmail => _email.sink.add;
  Function(String) get changePassword => _password.sink.add;
  Function(String) get changePasswordRetype => _passwordretype.sink.add;
  Function(bool) get showProgressBar => _isSignedIn.add;

  register() async {

    final FirebaseAuth _auth = FirebaseAuth.instance;

    try {
      showProgressBar(true);
      final FirebaseUser user = (await _auth.createUserWithEmailAndPassword(
        email: _email.value,
        password: _password.value,
      ))
          .user;
      if (user != null) {
//        setState(() {
//          _success = true;
//          _userEmail = user.email;
//          Navigator.of(context).pushNamedAndRemoveUntil(
//              '/home', (Route<dynamic> route) => false);
//
////        Navigator.of(context).pushReplacementNamed('/home');
//
//        });
      } else {
//        Scaffold.of(context).showSnackBar(SnackBar(
//          content: Text("Error occured, please try again later"),
//        ));
//        _success = false;
      }
    } catch (err) {
      _isSignedIn.addError(err);
      print(err);
//      setState(() {
//        _showLoading = false;
//        _error = true;
//      });
    }

  }

  dispose() {
    _email.drain();
    _email.close();
    _password.drain();
    _password.close();
    _passwordretype.drain();
    _passwordretype.close();
  }

}
</code>```

SignupScreen.dart

```<code>import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:lendy/src/blocs/bloc.dart';
import 'package:lendy/src/blocs/provider.dart';

class SignupScreen extends StatelessWidget {
//  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
//  final TextEditingController _emailController = TextEditingController();
//  final TextEditingController _passwordController = TextEditingController();
//  final TextEditingController _passwordController2 = TextEditingController();
  final FirebaseAuth _auth = FirebaseAuth.instance;
//  final GoogleSignIn _googleSignIn = GoogleSignIn();
  String _userID = "";

  bool _success;
  String _userEmail;

  @override
  Widget build(BuildContext context) {
    final bloc = Provider.of(context);

    return Scaffold(
      appBar: AppBar(
        title: Text("Signup"),
      ),
      body: Container(
        child: Column(
          children: <Widget>[
            emailField(bloc),
            passwordField(bloc),
            passwordFieldRe(bloc),
            SizedBox(
              height: 10.0,
            ),
            button(bloc)
          ],
        ),
      ),
    );
  }

  Widget emailField(Bloc bloc) {
    return StreamBuilder(
      stream: bloc.email,
      builder: (context, snapshot) {
        return TextField(
          onChanged: bloc.changeEmail,
          keyboardType: TextInputType.emailAddress,
          decoration: InputDecoration(
              hintText: 'Enter email address',
              labelText: 'Email-address',
              errorText: snapshot.error),
        );
      },
    );
  }

  Widget passwordField(Bloc bloc) {
    return StreamBuilder(
        stream: bloc.password,
        builder: (context, snapshot) {
          return TextField(
            onChanged: bloc.changePassword,
            decoration: InputDecoration(
                hintText: 'Enter password',
                labelText: 'Password',
                errorText: snapshot.error),
          );
        });
  }

  Widget passwordFieldRe(Bloc bloc) {
    return StreamBuilder(
        stream: bloc.passwordretype,
        builder: (context, snapshot) {
          return TextField(
            onChanged: bloc.changePasswordRetype,
            decoration: InputDecoration(
                hintText: 'Retype password',
                labelText: 'Password',
                errorText: snapshot.error),
          );
        });
  }

  Widget button(Bloc bloc) {
    return StreamBuilder(
      stream: bloc.submitValid,
      builder: (context, snapshot) {
        return RaisedButton(
            child: Text('Register'),
            color: Colors.blue,
            //if true
            onPressed: snapshot.hasData
                ? () {
//            bloc.showProgressBar(true);
                    bloc.register();
                  }
                : null);
      },
    );
  }

  Widget buttons(Bloc bloc) {
    return StreamBuilder(
      stream: bloc.submitValid,
      builder: (context, snapshot1) {
        return StreamBuilder(
          stream: bloc.signInStatus,
          builder: (context, snapshot2) {
            if (!snapshot2.hasData || snapshot2.hasError) {
              return Column(
                children: <Widget>[
                  RaisedButton(
                    child: Text('Register'),
                    color: Colors.blue,
                    onPressed: snapshot1.hasData
                        ? () {
                      bloc.register();
                    }
                        : null,
                  ),
                  snapshot2.hasError ? Text("ee") : Container()
                ],
              );
            } else {
              return CircularProgressIndicator();
            }
          },
        );
      },
    );
  }

  Widget submitButton(Bloc bloc) {
    return StreamBuilder(
        stream: bloc.signInStatus,
        builder: (context, snapshot) {
          if (snapshot.hasError || !snapshot.hasData) {
            return buttons(bloc);
          } else {
            return CircularProgressIndicator();
          }
        });

  }

/
</code>```

Validators.dart

```<code>import 'dart:async';

class Validators {

  final validateEmail = StreamTransformer<String, String>.fromHandlers(
      handleData: (email, sink){
        if (RegExp(
        r"^[a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+@[a-zA-Z0-9]+\.[a-zA-Z]+")
        .hasMatch(email)){
          sink.add(email);
        } else {
          sink.addError('Please enter a valid email address.');
        }
      }
  );

  final validatePassword = StreamTransformer<String, String>.fromHandlers(
      handleData: (password, sink){
        if (password.length > 3){
          sink.add(password);
        } else {
          sink.addError('Password is too short.');
        }
      }
  );

  final validatePasswordRetype = StreamTransformer<String, String>.fromHandlers(
      handleData: (password, sink){
        print("HANDLE DATA");
        if (password.length > 3){
          sink.add(password);
        } else {
          sink.addError('Password is too short.');
        }
      }
  );

}
</code>```

screenshot

答:
Found a similar issue here

I changed my submitValid function like so:

```<code>Stream<bool> get submitValid =>
    Rx.combineLatest3(email, password, passwordretype, (e, p, r) {
      if (p == _password.value && r == _passwordretype.value){
        return true;
      } else {
        return false;
      }
    });
</code>```

And changed onPressed in my button Widget like so. It only renders the clickable button if the snapshot returns true.

```<code>  Widget button(Bloc bloc) {
    return StreamBuilder(
      stream: bloc.submitValid,
      builder: (context, snapshot) {
        return RaisedButton(
            child: Text('Register'),
            color: Colors.blue,
            onPressed: snapshot.hasData && snapshot.data
                ? () {
              bloc.register();
            }
                : null);
      },
    );
  }
</code>```

Body:
So I am trying to make a signup form in flutter using streams and the bloc pattern.

The problem is that the error added to the sink for one my streams does not seem to persist?

The submitValid getter does not seem to consider the error added to the passwordretype stream, this causes the login button to be clickable when it shouldn't

Steps to reproduce:

Fill out a valid email

Fill out a valid password (password field)

Fill out a valid password (password retype field)

Delete everything from the retype field

Delete everything from the password field.

Type a valid password in the password field and the login button appears clickable even though the retype field is empty.

Here's my code along with a screenshot.

Bloc.dart

import 'dart:async';
import 'package:firebase_auth/firebase_auth.dart';

import 'validators.dart';
import 'dart:io';
import 'package:rxdart/rxdart.dart';

class Bloc extends Object with Validators {

  final _email = BehaviorSubject<String>();
  final _password = BehaviorSubject<String>();
  final _passwordretype = BehaviorSubject<String>();
  final _isSignedIn = BehaviorSubject<bool>();

  //Add data to stream
  Stream<String> get email => _email.stream.transform(validateEmail);
  Stream<String> get password => _password.stream.transform(validatePassword);

  Stream<String> get passwordretype=> _passwordretype.stream.transform(validatePasswordRetype)
  .doOnData((String c){
    if(0 != _password.value.compareTo(c)){
      _passwordretype.addError("Passwords do not match");
    }
  });

  Stream<bool> get signInStatus => _isSignedIn.stream;

  Stream<bool> get submitValid =>
    Rx.combineLatest3(email, password, passwordretype, (e, p, r) => true);

  //Change data
  Function(String) get changeEmail => _email.sink.add;
  Function(String) get changePassword => _password.sink.add;
  Function(String) get changePasswordRetype => _passwordretype.sink.add;
  Function(bool) get showProgressBar => _isSignedIn.add;

  register() async {

    final FirebaseAuth _auth = FirebaseAuth.instance;

    try {
      showProgressBar(true);
      final FirebaseUser user = (await _auth.createUserWithEmailAndPassword(
        email: _email.value,
        password: _password.value,
      ))
          .user;
      if (user != null) {
//        setState(() {
//          _success = true;
//          _userEmail = user.email;
//          Navigator.of(context).pushNamedAndRemoveUntil(
//              '/home', (Route<dynamic> route) => false);
//
////        Navigator.of(context).pushReplacementNamed('/home');
//
//        });
      } else {
//        Scaffold.of(context).showSnackBar(SnackBar(
//          content: Text("Error occured, please try again later"),
//        ));
//        _success = false;
      }
    } catch (err) {
      _isSignedIn.addError(err);
      print(err);
//      setState(() {
//        _showLoading = false;
//        _error = true;
//      });
    }

  }

  dispose() {
    _email.drain();
    _email.close();
    _password.drain();
    _password.close();
    _passwordretype.drain();
    _passwordretype.close();
  }

}

SignupScreen.dart

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:lendy/src/blocs/bloc.dart';
import 'package:lendy/src/blocs/provider.dart';

class SignupScreen extends StatelessWidget {
//  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
//  final TextEditingController _emailController = TextEditingController();
//  final TextEditingController _passwordController = TextEditingController();
//  final TextEditingController _passwordController2 = TextEditingController();
  final FirebaseAuth _auth = FirebaseAuth.instance;
//  final GoogleSignIn _googleSignIn = GoogleSignIn();
  String _userID = "";

  bool _success;
  String _userEmail;

  @override
  Widget build(BuildContext context) {
    final bloc = Provider.of(context);

    return Scaffold(
      appBar: AppBar(
        title: Text("Signup"),
      ),
      body: Container(
        child: Column(
          children: <Widget>[
            emailField(bloc),
            passwordField(bloc),
            passwordFieldRe(bloc),
            SizedBox(
              height: 10.0,
            ),
            button(bloc)
          ],
        ),
      ),
    );
  }

  Widget emailField(Bloc bloc) {
    return StreamBuilder(
      stream: bloc.email,
      builder: (context, snapshot) {
        return TextField(
          onChanged: bloc.changeEmail,
          keyboardType: TextInputType.emailAddress,
          decoration: InputDecoration(
              hintText: 'Enter email address',
              labelText: 'Email-address',
              errorText: snapshot.error),
        );
      },
    );
  }

  Widget passwordField(Bloc bloc) {
    return StreamBuilder(
        stream: bloc.password,
        builder: (context, snapshot) {
          return TextField(
            onChanged: bloc.changePassword,
            decoration: InputDecoration(
                hintText: 'Enter password',
                labelText: 'Password',
                errorText: snapshot.error),
          );
        });
  }

  Widget passwordFieldRe(Bloc bloc) {
    return StreamBuilder(
        stream: bloc.passwordretype,
        builder: (context, snapshot) {
          return TextField(
            onChanged: bloc.changePasswordRetype,
            decoration: InputDecoration(
                hintText: 'Retype password',
                labelText: 'Password',
                errorText: snapshot.error),
          );
        });
  }

  Widget button(Bloc bloc) {
    return StreamBuilder(
      stream: bloc.submitValid,
      builder: (context, snapshot) {
        return RaisedButton(
            child: Text('Register'),
            color: Colors.blue,
            //if true
            onPressed: snapshot.hasData
                ? () {
//            bloc.showProgressBar(true);
                    bloc.register();
                  }
                : null);
      },
    );
  }

  Widget buttons(Bloc bloc) {
    return StreamBuilder(
      stream: bloc.submitValid,
      builder: (context, snapshot1) {
        return StreamBuilder(
          stream: bloc.signInStatus,
          builder: (context, snapshot2) {
            if (!snapshot2.hasData || snapshot2.hasError) {
              return Column(
                children: <Widget>[
                  RaisedButton(
                    child: Text('Register'),
                    color: Colors.blue,
                    onPressed: snapshot1.hasData
                        ? () {
                      bloc.register();
                    }
                        : null,
                  ),
                  snapshot2.hasError ? Text("ee") : Container()
                ],
              );
            } else {
              return CircularProgressIndicator();
            }
          },
        );
      },
    );
  }

  Widget submitButton(Bloc bloc) {
    return StreamBuilder(
        stream: bloc.signInStatus,
        builder: (context, snapshot) {
          if (snapshot.hasError || !snapshot.hasData) {
            return buttons(bloc);
          } else {
            return CircularProgressIndicator();
          }
        });

  }

/

Validators.dart

import 'dart:async';

class Validators {

  final validateEmail = StreamTransformer<String, String>.fromHandlers(
      handleData: (email, sink){
        if (RegExp(
        r"^[a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+@[a-zA-Z0-9]+\.[a-zA-Z]+")
        .hasMatch(email)){
          sink.add(email);
        } else {
          sink.addError('Please enter a valid email address.');
        }
      }
  );

  final validatePassword = StreamTransformer<String, String>.fromHandlers(
      handleData: (password, sink){
        if (password.length > 3){
          sink.add(password);
        } else {
          sink.addError('Password is too short.');
        }
      }
  );

  final validatePasswordRetype = StreamTransformer<String, String>.fromHandlers(
      handleData: (password, sink){
        print("HANDLE DATA");
        if (password.length > 3){
          sink.add(password);
        } else {
          sink.addError('Password is too short.');
        }
      }
  );

}

screenshot

Body:
Found a similar issue here

I changed my submitValid function like so:

Stream<bool> get submitValid =>
    Rx.combineLatest3(email, password, passwordretype, (e, p, r) {
      if (p == _password.value && r == _passwordretype.value){
        return true;
      } else {
        return false;
      }
    });

And changed onPressed in my button Widget like so. It only renders the clickable button if the snapshot returns true.

  Widget button(Bloc bloc) {
    return StreamBuilder(
      stream: bloc.submitValid,
      builder: (context, snapshot) {
        return RaisedButton(
            child: Text('Register'),
            color: Colors.blue,
            onPressed: snapshot.hasData && snapshot.data
                ? () {
              bloc.register();
            }
                : null);
      },
    );
  }


答:
Error is here:

```<code>recyclerView = view.findViewById(R.id.rcl);
</code>```

view is null.

Try to replace by:

```<code>private RecyclerView mRecyclerView;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_list, container, false);
    // Add this.. Here, view won't be null
    recyclerView = view.findViewById(R.id.rcl);
    return view;
}

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    // recyclerView = view.findViewById(R.id.rcl); --> Remove this from here.
    recyclerView.setHasFixedSize(true);
    layoutManager = new LinearLayoutManager(this.getActivity());
    recyclerView.setLayoutManager(layoutManager);
    adapter = new PersonAdapter(this.getActivity(), ApplicationClass.people);
    recyclerView.setAdapter(adapter);
}
</code>```

Another options is replacing view by getActivity():

```<code>@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    recyclerView = getActivity().findViewById(R.id.rcl);
    ....
}
</code>```

Title: Getting error while getting view of RecyclerView in onActivityCreated()

Body:
Error is here:

recyclerView = view.findViewById(R.id.rcl);

view is null.

Try to replace by:

private RecyclerView mRecyclerView;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_list, container, false);
    // Add this.. Here, view won't be null
    recyclerView = view.findViewById(R.id.rcl);
    return view;
}

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    // recyclerView = view.findViewById(R.id.rcl); --> Remove this from here.
    recyclerView.setHasFixedSize(true);
    layoutManager = new LinearLayoutManager(this.getActivity());
    recyclerView.setLayoutManager(layoutManager);
    adapter = new PersonAdapter(this.getActivity(), ApplicationClass.people);
    recyclerView.setAdapter(adapter);
}

Another options is replacing view by getActivity():

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    recyclerView = getActivity().findViewById(R.id.rcl);
    ....
}


问:
Always empty paypal IPN custom field
I'm trying to send my custom field like this(using sandbox):

```<code>paypal.Buttons({

                            createOrder: function(data, actions) {
                                return actions.order.create({
                                    purchase_units: [{
                                        amount: {
                                            value: dataResponse.value
                                        },
                                        custom: 'SOME_DATA',
                                    }]
                                });
                            },

                            // Finalize the transaction
                            onApprove: function(data, actions) {
                                return actions.order.capture().then(function(details) {
                                    // Show a success message to the buyer
                                    alert('Transaction completed by ' + details.payer.name.given_name + '!');
                                });
                            }

                        }).render('#paypal-button-container');
</code>```

Like that i get a response on the server(i use paypal/ipn-code-samples):

```<code>$data_text = "";
foreach ($_POST as $key => $value) {
    $data_text .= $key . " = " . $value . "\r\n";
}
</code>```

And this is how the IPN looks like(part of it):

```<code>paypal_ipn_status = RECEIVER EMAIL MISMATCH
paypal_ipn_date = 2020-02-20 12:20:53 +05
mc_gross = 27.00
protection_eligibility = Eligible
address_status = confirmed
payer_id = 6F3VC36BWPQ7J
address_street = \u0443\u043B\u0438\u0446\u0430 \u041F\u0435\u0440\u0432\u0430\u044F
payment_date = 23:20:41 Feb 19, 2020 PST
payment_status = Completed
charset = KOI8_R
address_zip = 127001
first_name = John
mc_fee = 11.05
address_country_code = RU
address_name = Doe John
notify_version = 3.9
custom =
payer_status = verified
business = sb-gvgju1033031@business.example.com
</code>```

Can anyone tell me what I'm doing wrong?
Thanks!

答:
Well, i found a mistake.

instead of this:

```<code>                                return actions.order.create({
                                    purchase_units: [{
                                        amount: {
                                            value: dataResponse.value
                                        },
                                        custom: 'SOME_DATA',
                                    }]
                                });
</code>```

Need to use this(prop named - custom_id):

```<code>return actions.order.create({
                                    purchase_units: [{
                                        amount: {
                                            value: dataResponse.value
                                        },
                                        custom_id: 'SOME_DATA',
                                    }]
                                });
</code>```

and now i finally got my custom field in IPN

```<code>address_country_code = RU
address_name = Doe John
notify_version = 3.9
custom = SOME DATA
</code>```

I hope this helps someone.

Title: Always empty paypal IPN custom field

Body:
I'm trying to send my custom field like this(using sandbox):

paypal.Buttons({

                            createOrder: function(data, actions) {
                                return actions.order.create({
                                    purchase_units: [{
                                        amount: {
                                            value: dataResponse.value
                                        },
                                        custom: 'SOME_DATA',
                                    }]
                                });
                            },

                            // Finalize the transaction
                            onApprove: function(data, actions) {
                                return actions.order.capture().then(function(details) {
                                    // Show a success message to the buyer
                                    alert('Transaction completed by ' + details.payer.name.given_name + '!');
                                });
                            }

                        }).render('#paypal-button-container');

Like that i get a response on the server(i use paypal/ipn-code-samples):

$data_text = "";
foreach ($_POST as $key => $value) {
    $data_text .= $key . " = " . $value . "\r\n";
}

And this is how the IPN looks like(part of it):

paypal_ipn_status = RECEIVER EMAIL MISMATCH
paypal_ipn_date = 2020-02-20 12:20:53 +05
mc_gross = 27.00
protection_eligibility = Eligible
address_status = confirmed
payer_id = 6F3VC36BWPQ7J
address_street = \u0443\u043B\u0438\u0446\u0430 \u041F\u0435\u0440\u0432\u0430\u044F
payment_date = 23:20:41 Feb 19, 2020 PST
payment_status = Completed
charset = KOI8_R
address_zip = 127001
first_name = John
mc_fee = 11.05
address_country_code = RU
address_name = Doe John
notify_version = 3.9
custom =
payer_status = verified
business = sb-gvgju1033031@business.example.com

Can anyone tell me what I'm doing wrong?
Thanks!

Body:
Well, i found a mistake.

instead of this:

                                return actions.order.create({
                                    purchase_units: [{
                                        amount: {
                                            value: dataResponse.value
                                        },
                                        custom: 'SOME_DATA',
                                    }]
                                });

Need to use this(prop named - custom_id):

return actions.order.create({
                                    purchase_units: [{
                                        amount: {
                                            value: dataResponse.value
                                        },
                                        custom_id: 'SOME_DATA',
                                    }]
                                });

and now i finally got my custom field in IPN

address_country_code = RU
address_name = Doe John
notify_version = 3.9
custom = SOME DATA

I hope this helps someone.


问:
SciPy: solve_bvp Problem 2nd Order Diff. Eq
Trying to solve a 2nd order diff. eq. with 2 boundary conditions and nothing I try seems to work and I can't find a tutorial which includes all/similar terms to what I have in my expression and, at least to me, the scipy documentation doesn't really explain how to use solve_bvp clearly.

I have the equation: y'' + 2/r * y' = A * y + b * y^3 where y is a function of r.

I've rewritten it as follows:

y1 = y(r)

y2 = y1'

so that y2' = -2/r * y2 + y1(A + b * y1^2)

With conditions that y'(0) = 0, y(r=10) = constant

A, b and the constant are known.

I have the following code but it doesn't seem to work, and as said, I'm a little confused by the documentation so any help would be appreciated!

```<code>def fun(x, y):
    return np.vstack((y[2], -2/x*y[1]+y[0]*(A+b*y[0]*y[0])))

def bc(ya, yb):
    return np.array([ya[2], yb[1]-constant])

x = np.linspace(1, 10, 10)
ya = np.zeros((3, x.size))
yb = np.zeros((3, x.size))

sol_1 = solve_bvp(fun, bc, x, ya)
sol_2 = solve_bvp(fun, bc, x, yb)
</code>```

Thanks!

==========EDIT=========================
There is an analytical solution, for which I have calculated, it was just seeing if I could also find the same solution numerically, I think the major issue is that there are two separate regions for the solutions, one where r < R (in) and one where r > R (out). This leads to two different solutions (only valid in their respective domain) with the conditions that y_in(R) == y_out(R) and y_in'(R) == y_out'(R). Full 2-part solution where Radius = 1, a=99, b = 1 and constant = 1, y(inf) = constant

From Lutz Lehmann's solution, it gets the right shape (at least for the inner region, although not on the right scales).

I'm just unsure how you'd go about coding all the equating solutions and I suppose even getting their solutions in the first place, although Lutz's answer is an amazing point in the right direction.
Thanks

答:
Issues

The order of the equation is 2, thus the dimension of the state vector is 2, the value is always y[0], the derivative y[1], there is no y[2], probably a remnant from the translation from Matlab.

Also in the boundary conditions, there is no ya[2], the derivative value is ya[1], and the function value in the second one is yb[0].

The initial solution guess has to have the same number 2 of state components.

Why do you compute two solutions with identical data?

Remark: It is not necessary to convert the return values into numpy types, the solver checks and converts anyway.

BVP framework with singularity treatment

The ODE is singular at r=0, so one has to treat the first segment in a special way. The mean value theorem gives

```<code>(y'(r)-y'(0))/r->y''(0)  for  r->0,
</code>```

so that in that limit r->0 you get

```<code>3*y''(0) = a*y(0) + b*y(0)^3`.
</code>```

This allows to define the first arc as

```<code>y(r) = y0 + (a*y0 + b*y0^3)*r^2/6
y'(r) = (a*y0 + b*y0^3)*r/3
</code>```

up to order r³ and r². So if you want precision 1e-9 in y(r), then the first segment should not be longer than 1e-3.

Instead of trying to eliminate y0 from the equations for y(h) and y'(h) to get a condition connecting ya[0] and ya[1], let the solver do also this work and add y0 as parameter to the system. Then the boundary conditions have 3 slots corresponding to the added virtual dimension for the parameter, which can be naturally filled with the equations y(h)=ya[0] and ya[1]=y'(h) and the right boundary condition.

Altogether you can define the system as

h = 1e-3;

def fun(r, y, p):
    return  y[1], -2/r*y[1]+y[0]*(a+b*y[0]*y[0])

def bc(ya, yb, p):
    y0, = p
    yh = y0 + y0*(a+b*y0*y0)*h*h/6;
    dyh = y0*(a+b*y0*y0)*h/3
    return ya[0]-yh, ya[1]-dyh, yb[0]-c

x = np.linspace(h, 10, 10)
ya = np.zeros((2, x.size))

sol = solve_bvp(fun, bc, x, ya, p=[1])
print(sol.message,f"y(0)={sol.p[0]}");
plt.plot(sol.x, sol.y[0]);
```

so that with example parameters a, b, c = -1, 0.2, 3 you get a convergent solver call with y(0)=2.236081087849196 and the resulting plot

Body:
Trying to solve a 2nd order diff. eq. with 2 boundary conditions and nothing I try seems to work and I can't find a tutorial which includes all/similar terms to what I have in my expression and, at least to me, the scipy documentation doesn't really explain how to use solve_bvp clearly.

I have the equation: y'' + 2/r * y' = A * y + b * y^3 where y is a function of r.

I've rewritten it as follows:

y1 = y(r)

y2 = y1'

so that y2' = -2/r * y2 + y1(A + b * y1^2)

With conditions that y'(0) = 0, y(r=10) = constant

A, b and the constant are known.

I have the following code but it doesn't seem to work, and as said, I'm a little confused by the documentation so any help would be appreciated!

def fun(x, y):
    return np.vstack((y[2], -2/x*y[1]+y[0]*(A+b*y[0]*y[0])))

def bc(ya, yb):
    return np.array([ya[2], yb[1]-constant])

x = np.linspace(1, 10, 10)
ya = np.zeros((3, x.size))
yb = np.zeros((3, x.size))

sol_1 = solve_bvp(fun, bc, x, ya)
sol_2 = solve_bvp(fun, bc, x, yb)

Thanks!

==========EDIT=========================
There is an analytical solution, for which I have calculated, it was just seeing if I could also find the same solution numerically, I think the major issue is that there are two separate regions for the solutions, one where r < R (in) and one where r > R (out). This leads to two different solutions (only valid in their respective domain) with the conditions that y_in(R) == y_out(R) and y_in'(R) == y_out'(R). Full 2-part solution where Radius = 1, a=99, b = 1 and constant = 1, y(inf) = constant

From Lutz Lehmann's solution, it gets the right shape (at least for the inner region, although not on the right scales).

I'm just unsure how you'd go about coding all the equating solutions and I suppose even getting their solutions in the first place, although Lutz's answer is an amazing point in the right direction.
Thanks

Body:
Issues

The order of the equation is 2, thus the dimension of the state vector is 2, the value is always y[0], the derivative y[1], there is no y[2], probably a remnant from the translation from Matlab.

Also in the boundary conditions, there is no ya[2], the derivative value is ya[1], and the function value in the second one is yb[0].

The initial solution guess has to have the same number 2 of state components.

Why do you compute two solutions with identical data?

Remark: It is not necessary to convert the return values into numpy types, the solver checks and converts anyway.

BVP framework with singularity treatment

The ODE is singular at r=0, so one has to treat the first segment in a special way. The mean value theorem gives

(y'(r)-y'(0))/r->y''(0)  for  r->0,

so that in that limit r->0 you get

3*y''(0) = a*y(0) + b*y(0)^3`.

This allows to define the first arc as

y(r) = y0 + (a*y0 + b*y0^3)*r^2/6
y'(r) = (a*y0 + b*y0^3)*r/3

up to order r³ and r². So if you want precision 1e-9 in y(r), then the first segment should not be longer than 1e-3.

Instead of trying to eliminate y0 from the equations for y(h) and y'(h) to get a condition connecting ya[0] and ya[1], let the solver do also this work and add y0 as parameter to the system. Then the boundary conditions have 3 slots corresponding to the added virtual dimension for the parameter, which can be naturally filled with the equations y(h)=ya[0] and ya[1]=y'(h) and the right boundary condition.

Altogether you can define the system as

h = 1e-3;

def fun(r, y, p):
    return  y[1], -2/r*y[1]+y[0]*(a+b*y[0]*y[0])

def bc(ya, yb, p):
    y0, = p
    yh = y0 + y0*(a+b*y0*y0)*h*h/6;
    dyh = y0*(a+b*y0*y0)*h/3
    return ya[0]-yh, ya[1]-dyh, yb[0]-c

x = np.linspace(h, 10, 10)
ya = np.zeros((2, x.size))

sol = solve_bvp(fun, bc, x, ya, p=[1])
print(sol.message,f"y(0)={sol.p[0]}");
plt.plot(sol.x, sol.y[0]);

so that with example parameters a, b, c = -1, 0.2, 3 you get a convergent solver call with y(0)=2.236081087849196 and the resulting plot


问:
Wrong coordinates on multiple monitors
I have a Datagrid and I want to know the position of a datacell for overlaying it with a window.

It works fine with only one monitor, but with multiple monitors, the window is displaced.

Here's the code:

```<code>Point point = cell.PointToScreen(new Point(0, 0));
...
Window myWindow = new Window();
myWindow.Top = point.Y;
myWindow.Left = point.X;
</code>```

Somebody has some experience with positioning on multiple monitors?

EDIT:

I made following test:

```<code>public MyWindow()
{
    ...
    this.LocationChanged += MyWindow_LocationChanged;
}

void MyWindow_LocationChanged(object sender, EventArgs e)
{
    Console.WriteLine(this.Top + " <--> " + this.PointToScreen(new Point(0, 0)).Y);
}
</code>```

Results:

- Single-Monitor: 0 <--> 30; 20 <--> 50; 100  <--> 130

   ==> Always difference of 30 (may be caused by title bar)

- Dual-Monitor: 0  <--> 30;  20 <--> 55; 100 <--> 153

==> At 0,0 difference of 30. But the more I moved the window away from 0,0. the greater becomes the difference, but should stay the same. Very strange!

EDIT2:

Here's my solution, thanks to CodeNaked for the hint:

```<code>Point point = cell.PointToScreen(new Point(0, 0));
...
Window myWindow = new Window();
PresentationSource source = PresentationSource.FromVisual(this);
myWindow.Top = point.Y / source.CompositionTarget.TransformToDevice.M22;
myWindow.Left = point.X / source.CompositionTarget.TransformToDevice.M11;
</code>```

答:
I'm unable to reproduce the problem your experience. The upper left corner of the client area of the window (the point returned by PointToScreen) is always translated 8 pixels horizontally and 30 pixels vertically from the upper left corner of the window. This is on a two-monitor setup.

You should be able to compute the values 8 and 30 from the SystemParameters class, however I must admit that I'm not sure exactly what parameters to use to arrive at the actual values on my system.

Title: Wrong coordinates on multiple monitors

Body:
I have a Datagrid and I want to know the position of a datacell for overlaying it with a window.

It works fine with only one monitor, but with multiple monitors, the window is displaced.

Here's the code:

Point point = cell.PointToScreen(new Point(0, 0));
...
Window myWindow = new Window();
myWindow.Top = point.Y;
myWindow.Left = point.X;

Somebody has some experience with positioning on multiple monitors?

EDIT:

I made following test:

public MyWindow()
{
    ...
    this.LocationChanged += MyWindow_LocationChanged;
}

void MyWindow_LocationChanged(object sender, EventArgs e)
{
    Console.WriteLine(this.Top + " <--> " + this.PointToScreen(new Point(0, 0)).Y);
}

Results:

- Single-Monitor: 0 <--> 30; 20 <--> 50; 100  <--> 130

   ==> Always difference of 30 (may be caused by title bar)

- Dual-Monitor: 0  <--> 30;  20 <--> 55; 100 <--> 153

==> At 0,0 difference of 30. But the more I moved the window away from 0,0. the greater becomes the difference, but should stay the same. Very strange!

EDIT2:

Here's my solution, thanks to CodeNaked for the hint:

Point point = cell.PointToScreen(new Point(0, 0));
...
Window myWindow = new Window();
PresentationSource source = PresentationSource.FromVisual(this);
myWindow.Top = point.Y / source.CompositionTarget.TransformToDevice.M22;
myWindow.Left = point.X / source.CompositionTarget.TransformToDevice.M11;


问:
How to import my python file in another file in visual studio code
I am using python/selenium in visual studio code. I am trying to import my another python class driverScript which resides in executionEngine module and in the file DriverScript. I have imported as below:

```<code>import driverScript from executionEngine.DriverScript
</code>```

It is producing error:

```<code>Traceback (most recent call last):
  File "c:/Selenium/Selenium-Python Framework/RK_Practice/Tests/mainTest.py", line 5, in <module>
  from executionEngine.DriverScript import driverScript
ModuleNotFoundError: No module named 'executionEngine'
</code>```

How can I import correctly? Your help is very much appreciated.

答:
If your python file is on the same level in dir, then you can import just by calling:

```<code>import filename
</code>```

If your python file is inside another folder, then you need to create a blank __init__.py file that will help python to understand it's a package. Then you can import that as follows:

```<code>from folderName import filename
</code>```

Body:
I am using python/selenium in visual studio code. I am trying to import my another python class driverScript which resides in executionEngine module and in the file DriverScript. I have imported as below:

import driverScript from executionEngine.DriverScript

It is producing error:

Traceback (most recent call last):
  File "c:/Selenium/Selenium-Python Framework/RK_Practice/Tests/mainTest.py", line 5, in <module>
  from executionEngine.DriverScript import driverScript
ModuleNotFoundError: No module named 'executionEngine'

How can I import correctly? Your help is very much appreciated.

Body:
If your python file is on the same level in dir, then you can import just by calling:

import filename

If your python file is inside another folder, then you need to create a blank __init__.py file that will help python to understand it's a package. Then you can import that as follows:

from folderName import filename


问:
Remove comma only from number separators (regular expression grouping)
I have a column of alpha-numeric string in pandas dataframe.
The goal is to only remove comma from number separators. For example:

```<code>Hello, world! -> Hello, world!
</code>```

but

```<code>Warhammer 40,000 -> Warhammer 40000
Codename 1,337 -> Codename 1337
</code>```

I can deduce that only when both sides are numerics '[0-9]+,[0-9]+' do I want to remove the comma. However, I can't seem to figure out a way to keep the same digits. Could someone help? If related, the size of the dataframe is a few hundred thousand rows and an average string is about 100 words.

p.s. this is my first post. I tried searching for related issue but found none. English is not my mother-tougue, chances are, I might have missed the keyword for this issue. Please do link me to the right place should this happens. Many thanks and much appreciated :)

Update: added the keyword 'grouping' as reminder for myself.

答:
You can use Pandas' str.replace() with a regular expression:

import pandas as pd

data = [
    "Hello, world!",
    "Warhammer 40,000",
    "Codename 1,337",
    "Total USD 1,27",
    "1,080,000,000 kilometers per hour"
]

df = pd.DataFrame(data, columns=["title"])
df["title"] = df["title"].str.replace(",(\d{3})", "\\1")
df
```

<p>which yields</p>

```    title
0   Hello, world!
1   Warhammer 40000
2   Codename 1337
3   Total USD 1,27
4   1080000000 kilometers per hour

```

Body:
I have a column of alpha-numeric string in pandas dataframe.
The goal is to only remove comma from number separators. For example:

Hello, world! -> Hello, world!

but

Warhammer 40,000 -> Warhammer 40000
Codename 1,337 -> Codename 1337

I can deduce that only when both sides are numerics '[0-9]+,[0-9]+' do I want to remove the comma. However, I can't seem to figure out a way to keep the same digits. Could someone help? If related, the size of the dataframe is a few hundred thousand rows and an average string is about 100 words.

p.s. this is my first post. I tried searching for related issue but found none. English is not my mother-tougue, chances are, I might have missed the keyword for this issue. Please do link me to the right place should this happens. Many thanks and much appreciated :)

Update: added the keyword 'grouping' as reminder for myself.

Body:
You can use Pandas' str.replace() with a regular expression:

import pandas as pd

data = [
    "Hello, world!",
    "Warhammer 40,000",
    "Codename 1,337",
    "Total USD 1,27",
    "1,080,000,000 kilometers per hour"
]

df = pd.DataFrame(data, columns=["title"])
df["title"] = df["title"].str.replace(",(\d{3})", "\\1")
df

which yields

    title
0   Hello, world!
1   Warhammer 40000
2   Codename 1337
3   Total USD 1,27
4   1080000000 kilometers per hour