问:
Strange behaviour of lambda function inside parallel block in openmp c++
I've started to learn OpenMP for couple of days. I have come across this error that I can't resolve.
I've defined a lambda function f which captures local variable s. Now, If I change the variable s (a private variable to each thread) inside the parallel for loop then the function f doesn't reflect the change in its output and gives always 0. I can understand that I'm doing some error in scoping but unable to find the error.

```<code>#include <iostream>
#include <omp.h>

int main(int argc, char *argv[])
{

    using namespace std;
    double s;
    auto f =[&]{return s;};

#pragma omp parallel for private(s)
        for(int i = 0; i < 4 ; i++)
    {
        s = 5+i;
        double a1 = f();
#pragma omp critical
        cout << a1 << endl;
    }

    return 0;
}
</code>```

And if I define the lambda inside the parallel for loop, it actually works and returns the proper value of s and not 0, i.e.

```<code>#pragma omp parallel for private(s)
            for(int i = 0; i < 4 ; i++)
        {
            s = 5+i;
            double a1 = [&]{return s;}();
    #pragma omp critical
            cout << a1 << endl;
        }
</code>```

My guess is that the lambda function and the captured variable needs to be in the same scope.
How to fix this if the lambda function is defined outside the parallel block?

答:
You're dealing with multiple s variables. The s variable(s) within the parallel region(s) and the s variable declared in the outer scope.

The private directive declares data to have a separate copy in the memory of each thread. So, each thread will have its own copy of s which resides in a different memory location than the s declared in the outer scope double s;.

When you change the value of s in the parallel region you're only changing the thread local copy of s.

The value of s in your outer scope (which you are capturing by ref in a lambda) would not be changed. The outer s is located in a different memory location.

Side note, you should be initializing your outer s variable: double s{ 0 };.

```<code>// This value of x will remain unchanged.
int x = 5;

#pragma omp parallel private( x )
{
    // What happens in the `parallel block` stays in the
    // in the `parallel block`. In other words, incrementing this
    // local value of x will not change the value of x declared in the
    // outer scope. That's because this `parallel block` has its own copy of x.
    x++;
}

// This value of x will change.
int x = 5;

#pragma omp parallel
{
    // The x variable is now shared between each thread. What you
    // do to x here changes the value of x in the outer scope.
    #pragma omp critical
    {
        x++;
    }
}
</code>```

Body:
I've started to learn OpenMP for couple of days. I have come across this error that I can't resolve.
I've defined a lambda function f which captures local variable s. Now, If I change the variable s (a private variable to each thread) inside the parallel for loop then the function f doesn't reflect the change in its output and gives always 0. I can understand that I'm doing some error in scoping but unable to find the error.

#include <iostream>
#include <omp.h>

int main(int argc, char *argv[])
{

    using namespace std;
    double s;
    auto f =[&]{return s;};

#pragma omp parallel for private(s)
        for(int i = 0; i < 4 ; i++)
    {
        s = 5+i;
        double a1 = f();
#pragma omp critical
        cout << a1 << endl;
    }

    return 0;
}

And if I define the lambda inside the parallel for loop, it actually works and returns the proper value of s and not 0, i.e.

#pragma omp parallel for private(s)
            for(int i = 0; i < 4 ; i++)
        {
            s = 5+i;
            double a1 = [&]{return s;}();
    #pragma omp critical
            cout << a1 << endl;
        }

My guess is that the lambda function and the captured variable needs to be in the same scope.
How to fix this if the lambda function is defined outside the parallel block?

Body:
You're dealing with multiple s variables. The s variable(s) within the parallel region(s) and the s variable declared in the outer scope.

The private directive declares data to have a separate copy in the memory of each thread. So, each thread will have its own copy of s which resides in a different memory location than the s declared in the outer scope double s;.

When you change the value of s in the parallel region you're only changing the thread local copy of s.

The value of s in your outer scope (which you are capturing by ref in a lambda) would not be changed. The outer s is located in a different memory location.

Side note, you should be initializing your outer s variable: double s{ 0 };.

// This value of x will remain unchanged.
int x = 5;

#pragma omp parallel private( x )
{
    // What happens in the `parallel block` stays in the
    // in the `parallel block`. In other words, incrementing this
    // local value of x will not change the value of x declared in the
    // outer scope. That's because this `parallel block` has its own copy of x.
    x++;
}

// This value of x will change.
int x = 5;

#pragma omp parallel
{
    // The x variable is now shared between each thread. What you
    // do to x here changes the value of x in the outer scope.
    #pragma omp critical
    {
        x++;
    }
}


来源: stackexchange

问:
Qt on Android Runtime error: Invalid package identifier when getting bag for resource number 0x00000000
I am getting this strange error after updating my Qt version from 5.13.1 to 5.14.2 and I am not sure what is the cause of it (I also updated my gradle version from 4.1.0 to 5.5.1). The error give the following output message:

W ResourceType: Invalid package identifier when getting bag for
  resource number 0x00000000 E Qt      : Can't create main activity E Qt
  : android.content.res.Resources$NotFoundException: String array
  resource ID #0x0 E Qt      :  at
  android.content.res.Resources.getStringArray(Resources.java:525) E Qt
  :     at
  org.qtproject.qt5.android.bindings.QtLoader.startApp(QtLoader.java:423)
  E Qt      :   at
  org.qtproject.qt5.android.bindings.QtActivityLoader.onCreate(QtActivityLoader.java:166)
  E Qt      :   at
  org.qtproject.qt5.android.bindings.QtActivity.onCreateHook(QtActivity.java:266)
  E Qt      :   at
  org.qtproject.qt5.android.bindings.QtActivity.onCreate(QtActivity.java:273)

I have seen that this has been discussed before, but the solution given were unrelated to Qt and required the modification of Java code (which I don't think it is the problem at all in my case since I haven't changed that).

答:
Qt 5.14 requires a different AndroidManifest.xml file than Qt 5.13 or earlier. I followed the Qt recommendations and ended up with the following changes to get it to work again:

In AndroidManifest.xml, add attribute android:extractNativeLibs="true" into the <application …> element.

In AndroidManifest.xml, remove the following three lines (shown abbreviated):

```<code><meta-data android:name="android.app.bundled_in_lib_resource_id" … />
<meta-data android:name="android.app.bundled_in_assets_resource_id" … />
<meta-data android:name="android.app.load_local_libs" … />
</code>```

In AndroidManifest.xml, insert the following line among the other <meta-data …/> lines:

```<code><meta-data android:name="android.app.load_local_libs_resource_id" android:resource="@array/load_local_libs"/>
</code>```

In res/values/libs.xml in your Android config directory, insert the following lines into the <resources> … </resources> element:

```<code><array name="load_local_libs">
    <!-- %%INSERT_LOCAL_LIBS%% -->
</array>
</code>```

Using Qt 5.13 in parallel. Some more detail about this issue is available in issue QTBUG-80444. From there, unfortunately it seems that the required changes are not backwards compatible with Qt 5.13 or earlier, means you need one version of AndroidManifest.xml to build for Android with Qt 5.13 and another version to build with Qt 5.14. (Except you never want to look back to Qt 5.13, of course.)

Sources. Derived from the Qt examples diff mentioned by @daljit97 in another answer on this page. That still lead to an error "AndroidManifest.xml:80: error: resource array/load_local_libs (aka com.example.qtws:array/load_local_libs) not found." on deployment, but this comment hinted me into the right direction to fix that.

ContentLicense: CC BY-SA 4.0

Body:
Qt 5.14 requires a different AndroidManifest.xml file than Qt 5.13 or earlier. I followed the Qt recommendations and ended up with the following changes to get it to work again:

In AndroidManifest.xml, add attribute android:extractNativeLibs="true" into the <application …> element.

In AndroidManifest.xml, remove the following three lines (shown abbreviated):

<meta-data android:name="android.app.bundled_in_lib_resource_id" … />
<meta-data android:name="android.app.bundled_in_assets_resource_id" … />
<meta-data android:name="android.app.load_local_libs" … />

In AndroidManifest.xml, insert the following line among the other <meta-data …/> lines:

<meta-data android:name="android.app.load_local_libs_resource_id" android:resource="@array/load_local_libs"/>

In res/values/libs.xml in your Android config directory, insert the following lines into the <resources> … </resources> element:

<array name="load_local_libs">
    <!-- %%INSERT_LOCAL_LIBS%% -->
</array>

Using Qt 5.13 in parallel. Some more detail about this issue is available in issue QTBUG-80444. From there, unfortunately it seems that the required changes are not backwards compatible with Qt 5.13 or earlier, means you need one version of AndroidManifest.xml to build for Android with Qt 5.13 and another version to build with Qt 5.14. (Except you never want to look back to Qt 5.13, of course.)

Sources. Derived from the Qt examples diff mentioned by @daljit97 in another answer on this page. That still lead to an error "AndroidManifest.xml:80: error: resource array/load_local_libs (aka com.example.qtws:array/load_local_libs) not found." on deployment, but this comment hinted me into the right direction to fix that.


问:
Can't access docker application from localhost using docker-compose
before I start: I have searched this question already and implemented what the "Solutions" were and it did not help (setting host to 0.0.0.0). So, with that out of the way,

Directory structure

```<code>|-- osr
|    |-- __init__.py
|-- requirements.txt
|-- Dockerfile
|-- docker-compose.yml
</code>```

Dockerfile:

```<code>FROM python:3.7.5-buster

EXPOSE 5000 # i have tried with and without this

ENV INSTALL_PATH /osr
ENV FLASK_APP osr
ENV FLASK_ENV development
RUN mkdir -p $INSTALL_PATH

COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt

COPY . .

CMD [ "flask", "run", "--host=0.0.0.0"]
</code>```

docker-compose.yml:

```<code>version: '3.8'
services:
    web:
        build: .
        ports:
            - '5000:5000'
        expose:
            - '5000'
        volumes:
            - .:/osr
</code>```

__ init __.py

```<code>import os
from flask import Flask

def create_app(test_config=None):
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_mapping(
        SECRET_KEY='dev'
    )

    @app.route('/hello')
    def hello():
        return 'Hello, World!'

    return app
</code>```

docker-compose build web
docker-compose run web

```<code> * Serving Flask app "osr" (lazy loading)
 * Environment: development
 * Debug mode: on
 * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 225-441-434
</code>```

all of the below return "hmm can't reach this page"

```<code>http://localhost
http://localhost:5000/hello
http://127.0.0.1:5000/hello
</code>```

I've even tried going to the containers IP with

docker exec -it 49e677 bash
ip add | grep global
    inet 172.21.0.2/16 brd 172.21.255.255 scope global eth0

```<code>http://127.21.0.2:5000/hello # nothing
</code>```

Nothing.

I'm sure the app itself works fine as I can simply run the app directly.

```<code>$env:FLASK_APP="osr"
$env:FLASK_ENV="development"
flask run --host=0.0.0.0
</code>```

And it runs fine

EDIT: UPDATE

I am actually able to get to the container when I run it through simply the Dockerfile... using

docker run -it -p 5000:5000 osr_web # the container built by docker-compose build

With this, I am able to access the endpoint through localhost:5000/hello

So the issue appears to lie in spinning it up through docker-compose run

Does this help at all?

UPDATE 2

I have discovered that when I run docker ps -a I can see that Docker run actually exposes the port, but docker-compose run does not:

答:
I found the issue. For reference, I am running these versions:

docker-compose version 1.25.5, build 8a1c60f6

Docker version 19.03.8, build afacb8b

There were a couple issues: First and foremost to get the ports exposed I needed to run one of two options.

docker-compose up web
or
docker-compose run --service-ports web

Simply running docker-compose run web would not expose the ports.

Once this was finished, I was able to access the endpoint. However I started getting another odd error,

```<code>flask.cli.NoAppException
flask.cli.NoAppException: Failed to find Flask application or factory in module
"osr". Use "FLASK_APP=osr:name to specify one.
</code>```

I had not experienced this simply using docker run -it -p 5000:5000 osr_web which was odd. However I noticed I had not set the work directory in the Dockerfile.

I changed the Dockerfile to this:

```<code>FROM python:3.7.5-buster

EXPOSE 5000
ENV INSTALL_PATH /osr
ENV FLASK_APP osr
ENV FLASK_ENV development
RUN mkdir -p $INSTALL_PATH

COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt

# added this line
WORKDIR $INSTALL_PATH

COPY . .

CMD [ "flask", "run", "--host=0.0.0.0"]
</code>```

I believe you could get away without setting the WORK_DIR if you turn the flask application into a package and install it.

Body:
before I start: I have searched this question already and implemented what the "Solutions" were and it did not help (setting host to 0.0.0.0). So, with that out of the way,

Directory structure

|-- osr
|    |-- __init__.py
|-- requirements.txt
|-- Dockerfile
|-- docker-compose.yml

Dockerfile:

FROM python:3.7.5-buster

EXPOSE 5000 # i have tried with and without this

ENV INSTALL_PATH /osr
ENV FLASK_APP osr
ENV FLASK_ENV development
RUN mkdir -p $INSTALL_PATH

COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt

COPY . .

CMD [ "flask", "run", "--host=0.0.0.0"]

docker-compose.yml:

version: '3.8'
services:
    web:
        build: .
        ports:
            - '5000:5000'
        expose:
            - '5000'
        volumes:
            - .:/osr

__ init __.py

import os
from flask import Flask

def create_app(test_config=None):
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_mapping(
        SECRET_KEY='dev'
    )

    @app.route('/hello')
    def hello():
        return 'Hello, World!'

    return app

docker-compose build web
docker-compose run web

 * Serving Flask app "osr" (lazy loading)
 * Environment: development
 * Debug mode: on
 * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 225-441-434

all of the below return "hmm can't reach this page"

http://localhost
http://localhost:5000/hello
http://127.0.0.1:5000/hello

I've even tried going to the containers IP with

docker exec -it 49e677 bash
ip add | grep global
    inet 172.21.0.2/16 brd 172.21.255.255 scope global eth0

http://127.21.0.2:5000/hello # nothing

Nothing.

I'm sure the app itself works fine as I can simply run the app directly.

$env:FLASK_APP="osr"
$env:FLASK_ENV="development"
flask run --host=0.0.0.0

And it runs fine

EDIT: UPDATE

I am actually able to get to the container when I run it through simply the Dockerfile... using

docker run -it -p 5000:5000 osr_web # the container built by docker-compose build

With this, I am able to access the endpoint through localhost:5000/hello

So the issue appears to lie in spinning it up through docker-compose run

Does this help at all?

UPDATE 2

I have discovered that when I run docker ps -a I can see that Docker run actually exposes the port, but docker-compose run does not:

Body:
I found the issue. For reference, I am running these versions:

docker-compose version 1.25.5, build 8a1c60f6

Docker version 19.03.8, build afacb8b

There were a couple issues: First and foremost to get the ports exposed I needed to run one of two options.

docker-compose up web
or
docker-compose run --service-ports web

Simply running docker-compose run web would not expose the ports.

Once this was finished, I was able to access the endpoint. However I started getting another odd error,

flask.cli.NoAppException
flask.cli.NoAppException: Failed to find Flask application or factory in module
"osr". Use "FLASK_APP=osr:name to specify one.

I had not experienced this simply using docker run -it -p 5000:5000 osr_web which was odd. However I noticed I had not set the work directory in the Dockerfile.

I changed the Dockerfile to this:

FROM python:3.7.5-buster

EXPOSE 5000
ENV INSTALL_PATH /osr
ENV FLASK_APP osr
ENV FLASK_ENV development
RUN mkdir -p $INSTALL_PATH

COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt

# added this line
WORKDIR $INSTALL_PATH

COPY . .

CMD [ "flask", "run", "--host=0.0.0.0"]

I believe you could get away without setting the WORK_DIR if you turn the flask application into a package and install it.


问:
Static Media Failure with NGINX and Gunicorn
Hello and thanks for taking time to read this request for help.

I am installing a web application called Netbox, which is built on Django. A basic Gunicorn is front-ended with NGINX in a rather simplie configuration.

The problem I'm running into is that the web application reports that it is unable to load any of the static files, and I can validate that I'm getting a 404 for these requests.

I have validated that I can view the correct files in the /static/ path referenced in the NGINX path /opt/netbox/netbox/static, and the permissions are correctly set as well.

Since this is a Django web app, I have performed a simple test with the built-in test web server and all the static files are correctly rendered; this is almost certainly an issue between Gunicorn and my NGINX configuration.

nginx.conf

```<code>server {
    listen 443 ssl;

    # CHANGE THIS TO YOUR SERVER'S NAME
    server_name netbox.example.com;

    ssl_certificate /etc/ssl/certs/netbox.crt;
    ssl_certificate_key /etc/ssl/private/netbox.key;

    client_max_body_size 25m;

    location /static/ {
        alias /opt/netbox/netbox/static/;
    }

    location / {
        proxy_pass http://127.0.0.1:8001;
        proxy_set_header X-Forwarded-Host $http_host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

server {
    # Redirect HTTP traffic to HTTPS
    listen 80;
    server_name _;
    return 301 https://$host$request_uri;
}
</code>```

gunicorn.py

```<code>bind = '127.0.0.1:8001'
workers = 5
threads = 3
timeout = 120
max_requests = 5000
max_requests_jitter = 500
</code>```

error message when browsing http://localhost:8001/

I have received the same results on the following setups:

Ubuntu 18.04 (Azure)

Ubuntu 19.10 (local VM)

Ubuntu 20.04 (local VM)

Centos 8.1 (Azure)

same error when using the Apache alternative setup method

I would appreciate any ideas on where I can go to validate things like permissions or check into logs.

答:
Try using root instead of alias. Nginx documentation recommends to use root when location matches the last part of the directive’s value. I think is to avoid duplication of the $uri, /static in your example, when using alias.

So try this:

```<code>    location /static/ {
        root /opt/netbox/netbox;
    }
</code>```

Body:
Hello and thanks for taking time to read this request for help.

I am installing a web application called Netbox, which is built on Django. A basic Gunicorn is front-ended with NGINX in a rather simplie configuration.

The problem I'm running into is that the web application reports that it is unable to load any of the static files, and I can validate that I'm getting a 404 for these requests.

I have validated that I can view the correct files in the /static/ path referenced in the NGINX path /opt/netbox/netbox/static, and the permissions are correctly set as well.

Since this is a Django web app, I have performed a simple test with the built-in test web server and all the static files are correctly rendered; this is almost certainly an issue between Gunicorn and my NGINX configuration.

nginx.conf

server {
    listen 443 ssl;

    # CHANGE THIS TO YOUR SERVER'S NAME
    server_name netbox.example.com;

    ssl_certificate /etc/ssl/certs/netbox.crt;
    ssl_certificate_key /etc/ssl/private/netbox.key;

    client_max_body_size 25m;

    location /static/ {
        alias /opt/netbox/netbox/static/;
    }

    location / {
        proxy_pass http://127.0.0.1:8001;
        proxy_set_header X-Forwarded-Host $http_host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

server {
    # Redirect HTTP traffic to HTTPS
    listen 80;
    server_name _;
    return 301 https://$host$request_uri;
}

gunicorn.py

bind = '127.0.0.1:8001'
workers = 5
threads = 3
timeout = 120
max_requests = 5000
max_requests_jitter = 500

error message when browsing http://localhost:8001/

I have received the same results on the following setups:

Ubuntu 18.04 (Azure)

Ubuntu 19.10 (local VM)

Ubuntu 20.04 (local VM)

Centos 8.1 (Azure)

same error when using the Apache alternative setup method

I would appreciate any ideas on where I can go to validate things like permissions or check into logs.

Body:
Try using root instead of alias. Nginx documentation recommends to use root when location matches the last part of the directive’s value. I think is to avoid duplication of the $uri, /static in your example, when using alias.

So try this:

    location /static/ {
        root /opt/netbox/netbox;
    }


问:
Darwinex ZeroMQ & MT4 - How to iterate on ZeroQM returned values? (Python)
I am trying to create a bridge between Metatrader 4 and Darwinex ZeroMQ (Python). I got the connection 100% working - returning values. The problem is the values are returned as 'NoneType', looks like a dictionary but it is not iterable. Does anybory knows how can I assign the information to a variable?
I am new in python and I am trying to create a small robot.

Follow the link for for the Darwinex docs: https://github.com/darwinex/dwx-zeromq-connector

See below my Python code and the returned values:

```<code>from DWX_ZeroMQ_Connector_v2_0_1_RC8 import DWX_ZeroMQ_Connector

_zmq = DWX_ZeroMQ_Connector(_verbose=True)

_zmq._generate_default_order_dict()

_zmq._DWX_MTX_GET_ALL_OPEN_TRADES_()

_zmq._DWX_MTX_GET_ALL_OPEN_TRADES_().get('_trades')

</code>```

Follow below an screenshot on Jupiter notebook, easier to see the results:

答:
i use my own Sockets for communication. Here some edited Code Examples:

```<code>import zmq
import threading
import time
import ast

def fetch_to_db(data):
    try:
        if 'OPEN_TRADES' in data:
            res = ast.literal_eval(data)
            orders = res['_trades']
            for key,value in orders.items():
                #print(key)
                value['orderID'] = key
                print(value)
            print()
        else:
            print('FETCH ERROR')
    except Exception as e:
        print(e)

def get_open_trades(stop):
    try:
        while True:
            data = str('TRADE;GET_OPEN_TRADES')
            c = zmq.Context()
            s = c.socket(zmq.PUSH)
            s.connect('tcp://127.0.0.1:32768')
            s.send_string(data)
            s.send_string(data)
            time.sleep(1)
            if stop():
                s.close()
                break
    except Exception as e:
        print(e)

def receiver_sock(stop):
    try:
        c = zmq.Context()
        s = c.socket(zmq.PULL)
        s.setsockopt(zmq.RCVHWM, 1)
        s.connect('tcp://127.0.0.1:32769')
        while True:
            data = s.recv_string()
            fetch_to_db(data)
            time.sleep(0.00001)
            if stop():
                s.close()
                break
    except Exception as e:
        print(e)

def loop_s():
    try:
        stop_threads = False
        receiver_socket = threading.Thread(target = receiver_sock, args =(lambda : stop_threads, ))
        receiver_socket.setDaemon(True)
        receiver_socket.start()
        open_trades = threading.Thread(target = get_open_trades, args =(lambda : stop_threads, ))
        open_trades.setDaemon(True)
        open_trades.start()
    except Exception as e:
        print(e)

try:
    loop_s()
    while True: time.sleep(100)
except KeyboardInterrupt:
    print('CLOSING')
    processes = [get_open_trades,receiver_sock]
    for i in processes:
        stop_threads = True
        t1 = threading.Thread(target = i, args =(lambda : stop_threads, ))
</code>```

the fetch_to_db function return a dict for every order including orderID

regards

Body:
I am trying to create a bridge between Metatrader 4 and Darwinex ZeroMQ (Python). I got the connection 100% working - returning values. The problem is the values are returned as 'NoneType', looks like a dictionary but it is not iterable. Does anybory knows how can I assign the information to a variable?
I am new in python and I am trying to create a small robot.

Follow the link for for the Darwinex docs: https://github.com/darwinex/dwx-zeromq-connector

See below my Python code and the returned values:

from DWX_ZeroMQ_Connector_v2_0_1_RC8 import DWX_ZeroMQ_Connector

_zmq = DWX_ZeroMQ_Connector(_verbose=True)

_zmq._generate_default_order_dict()

_zmq._DWX_MTX_GET_ALL_OPEN_TRADES_()

_zmq._DWX_MTX_GET_ALL_OPEN_TRADES_().get('_trades')

Follow below an screenshot on Jupiter notebook, easier to see the results:

Body:
i use my own Sockets for communication. Here some edited Code Examples:

import zmq
import threading
import time
import ast

def fetch_to_db(data):
    try:
        if 'OPEN_TRADES' in data:
            res = ast.literal_eval(data)
            orders = res['_trades']
            for key,value in orders.items():
                #print(key)
                value['orderID'] = key
                print(value)
            print()
        else:
            print('FETCH ERROR')
    except Exception as e:
        print(e)

def get_open_trades(stop):
    try:
        while True:
            data = str('TRADE;GET_OPEN_TRADES')
            c = zmq.Context()
            s = c.socket(zmq.PUSH)
            s.connect('tcp://127.0.0.1:32768')
            s.send_string(data)
            s.send_string(data)
            time.sleep(1)
            if stop():
                s.close()
                break
    except Exception as e:
        print(e)

def receiver_sock(stop):
    try:
        c = zmq.Context()
        s = c.socket(zmq.PULL)
        s.setsockopt(zmq.RCVHWM, 1)
        s.connect('tcp://127.0.0.1:32769')
        while True:
            data = s.recv_string()
            fetch_to_db(data)
            time.sleep(0.00001)
            if stop():
                s.close()
                break
    except Exception as e:
        print(e)

def loop_s():
    try:
        stop_threads = False
        receiver_socket = threading.Thread(target = receiver_sock, args =(lambda : stop_threads, ))
        receiver_socket.setDaemon(True)
        receiver_socket.start()
        open_trades = threading.Thread(target = get_open_trades, args =(lambda : stop_threads, ))
        open_trades.setDaemon(True)
        open_trades.start()
    except Exception as e:
        print(e)

try:
    loop_s()
    while True: time.sleep(100)
except KeyboardInterrupt:
    print('CLOSING')
    processes = [get_open_trades,receiver_sock]
    for i in processes:
        stop_threads = True
        t1 = threading.Thread(target = i, args =(lambda : stop_threads, ))

the fetch_to_db function return a dict for every order including orderID

regards


问:
Matching date and time using regex
I am trying to write a regex that matches the date and time in this format - d/m/Y H:m am/pm. For example, 1/2/2020 1.30pm

This is the regex I am using but it does not match the date and time specified in the example -

```<code>$value = '1/2/2020 1.30pm';
if(preg_match("/^[0-9]{1,2}/[0-9]{1,2}/[0-9]{4} (0\d|1[0-2]):([0-5]\d)(?::((?2)))?\h*([ap]m)? $/", $value) === 0) {
     return false;
}else{
     return true;
}
</code>```

Please kindly help correct my mistakes on the regex expression

答:
If you don't care about some freedom in the format (like accepting both pm and PM), you can use DateTime::createFromFormat():

$dateTime = DateTime::createFromFormat('j/n/Y g.ia', $value);
$isValid = $dateTime !== false;
```

Title: Matching date and time using regex

Body:
I am trying to write a regex that matches the date and time in this format - d/m/Y H:m am/pm. For example, 1/2/2020 1.30pm

This is the regex I am using but it does not match the date and time specified in the example -

$value = '1/2/2020 1.30pm';
if(preg_match("/^[0-9]{1,2}/[0-9]{1,2}/[0-9]{4} (0\d|1[0-2]):([0-5]\d)(?::((?2)))?\h*([ap]m)? $/", $value) === 0) {
     return false;
}else{
     return true;
}

Please kindly help correct my mistakes on the regex expression


问:
Form element validation using jQuery
I am trying to make a validation page and I need to stop saying "Please fill in the form" when text is entered in the text box. I only needed to validate when the text boxes are empty

<form action="mailto:kyletab03@gmail.com" name="myForm" method="post" onsubmit="return validation();" enctype="text/plain">
  Name:
  <input type="text" name="name" id="name" />

  Surname:
  <input type="text" name="surname" id="surname" />

  Email:
  <input type="email" name="email" id="email" />

  Message:
  <textarea name="Message" maxlength="3500"></textarea>

  <button id="submit" onclick="validation()">Submit</button>
</form>
```

答:
The easiest way to validate forms with jquery is to use jquery validate.

I would definately advise you NOT to use mailto directly in your form post url simply because spam bots and things like that may catch hold of your form and try to use it to send spam mail. i add jquery validation and captcha on all of the contact us pages that i create for clients.

```<code>$('#frmsendemail').validate({ // Send Email Form
    ignore: '.ignore',
    rules: {
        seFullname: {
            required: true,
            minlength: 2
        },
        seContact: {
            required: true,
            phonesUK: true,
        },
        seMail: {

            required: true,
            email: true
        },
        seMsg: {
            required: true
        },
        seCaptchaStatus: {
            required: function () {
                // verify the user response

                var thisresponse = grecaptcha.getResponse(seCaptcha);
                if (thisresponse == "") {
                    return true;
                } else {
                    return false;
                }
            }
        }
    },
    messages: {
        seFullname: {
            required: "Please Enter Your Name",
            minlength: jQuery.validator.format("Please ensure you enter a name more than {0} characters long.")
        },
        seContact: {
            required: "Please Enter a contact number",
            phonesUK: "Your Contact Numer should be in the format of: 07123 456 789 or 0123 123 4567",
            minlength: jQuery.validator.format("Your contact number should me at least {0} numbers.")
        },
        seMail: {
            required: "Please Enter Your Email Address",
            email: "Your email address should be in the format of "username@domain.com""
        },
        seMsg: "Please Enter A Message",
        seCaptchaStatus: "Please complete reCaptcha."
    },
    highlight: function (element) {
        var id_attr = "#" + $(element).attr("id");
        $(element).closest('.pure-form-control-group').removeClass('border-success icon-valid').addClass('border-error icon-invalid');
        $(id_attr).removeClass('glyphicon-ok icon-valid').addClass('glyphicon-remove icon-invalid');
    },
    unhighlight: function (element) {
        var id_attr = "#" + $(element).attr("id");
        $(element).closest('.pure-form-control-group').removeClass('border-danger icon-valid').addClass('border-success icon-valid');
        $(id_attr).removeClass('glyphicon-remove icon-invalid').addClass('glyphicon-ok icon-valid');
    },
    showErrors: function (errorMap, errorList) {

        $(".seerrors").html('<h6><i class="fa fa-exclamation-circle"></i> Your form contains ' +
            this.numberOfInvalids() +
            ' errors, see details below.</h6');
        this.defaultShowErrors();
    },
    validClass: "border-success",
    invalidClass: "border-danger",
    errorClass: "border-danger",
    errorElement: 'div',
    errorLabelContainer: ".seerrors",
    submitHandler: function () {

        //Now that all validation is satified we can send the form to the mail script.
        //Using AJAX we can send the form, get email sent and get a response and display a nice
        //message to the user saying thank you.
        //For Debugging
        //console.log("Sending Form");

        $.post("../php/sendemail.php", $('#frmsendemail').serialize(), function (result) {
            //do stuff with returned data here
            //result = $.parseJSON(result);
            console.log(result.Status);

            if (result.Status == "Error") {
                //Create message from returned data.
                //This helps the user see what went wrong.
                //If its a form error they can correct it,
                //if not then they can see whats wrong and alert us.

                var message3 = '<p style="font-size:10pt;text-align:left !important;">We encountered an error while processing the information you requested to send.</p><p style="font-size:10px;text-align:left;">We appologise for this, details of the error are included below.<p><hr><p style="text-align:left;font-size:10px;">Error Details:' + result.Reason.toString() + '</p><pstyle="text-align:left;font-size:10px;">If this error persists, please email enquiries@cadsolutions.wales</p>';
                // Show JConfirm Dialog with error.
                $.confirm({
                    title: '<h2 style="text-align:left"><i class="fa fa-exclamation-circle"></i> We encountered an error<h2>',
                    content: message3,
                    type: 'red',
                    // Set Theme for the popup
                    theme: 'Material',
                    typeAnimated: true,
                    buttons: {
                        close: function () {}
                    }
                });
</code>```

The above code is from a page that i created for a contact us script. the script sets all the inputs that are on the page using the name= attribute and then sets messages for the inputs when validation rules are not met, highlights and un-highlights the fields with errors, shows error messages in a set div tag and then handles form submit when the form is valid. :)

Title: Form element validation using jQuery

Body:
The easiest way to validate forms with jquery is to use jquery validate.

I would definately advise you NOT to use mailto directly in your form post url simply because spam bots and things like that may catch hold of your form and try to use it to send spam mail. i add jquery validation and captcha on all of the contact us pages that i create for clients.

$('#frmsendemail').validate({ // Send Email Form
    ignore: '.ignore',
    rules: {
        seFullname: {
            required: true,
            minlength: 2
        },
        seContact: {
            required: true,
            phonesUK: true,
        },
        seMail: {

            required: true,
            email: true
        },
        seMsg: {
            required: true
        },
        seCaptchaStatus: {
            required: function () {
                // verify the user response

                var thisresponse = grecaptcha.getResponse(seCaptcha);
                if (thisresponse == "") {
                    return true;
                } else {
                    return false;
                }
            }
        }
    },
    messages: {
        seFullname: {
            required: "Please Enter Your Name",
            minlength: jQuery.validator.format("Please ensure you enter a name more than {0} characters long.")
        },
        seContact: {
            required: "Please Enter a contact number",
            phonesUK: "Your Contact Numer should be in the format of: 07123 456 789 or 0123 123 4567",
            minlength: jQuery.validator.format("Your contact number should me at least {0} numbers.")
        },
        seMail: {
            required: "Please Enter Your Email Address",
            email: "Your email address should be in the format of &quot;username@domain.com&quot;"
        },
        seMsg: "Please Enter A Message",
        seCaptchaStatus: "Please complete reCaptcha."
    },
    highlight: function (element) {
        var id_attr = "#" + $(element).attr("id");
        $(element).closest('.pure-form-control-group').removeClass('border-success icon-valid').addClass('border-error icon-invalid');
        $(id_attr).removeClass('glyphicon-ok icon-valid').addClass('glyphicon-remove icon-invalid');
    },
    unhighlight: function (element) {
        var id_attr = "#" + $(element).attr("id");
        $(element).closest('.pure-form-control-group').removeClass('border-danger icon-valid').addClass('border-success icon-valid');
        $(id_attr).removeClass('glyphicon-remove icon-invalid').addClass('glyphicon-ok icon-valid');
    },
    showErrors: function (errorMap, errorList) {

        $(".seerrors").html('<h6><i class="fa fa-exclamation-circle"></i>&nbsp;Your form contains ' +
            this.numberOfInvalids() +
            ' errors, see details below.</h6');
        this.defaultShowErrors();
    },
    validClass: "border-success",
    invalidClass: "border-danger",
    errorClass: "border-danger",
    errorElement: 'div',
    errorLabelContainer: ".seerrors",
    submitHandler: function () {

        //Now that all validation is satified we can send the form to the mail script.
        //Using AJAX we can send the form, get email sent and get a response and display a nice
        //message to the user saying thank you.
        //For Debugging
        //console.log("Sending Form");

        $.post("../php/sendemail.php", $('#frmsendemail').serialize(), function (result) {
            //do stuff with returned data here
            //result = $.parseJSON(result);
            console.log(result.Status);

            if (result.Status == "Error") {
                //Create message from returned data.
                //This helps the user see what went wrong.
                //If its a form error they can correct it,
                //if not then they can see whats wrong and alert us.

                var message3 = '<p style="font-size:10pt;text-align:left !important;">We encountered an error while processing the information you requested to send.</p><p style="font-size:10px;text-align:left;">We appologise for this, details of the error are included below.<p><hr><p style="text-align:left;font-size:10px;">Error Details:' + result.Reason.toString() + '</p><pstyle="text-align:left;font-size:10px;">If this error persists, please email enquiries@cadsolutions.wales</p>';
                // Show JConfirm Dialog with error.
                $.confirm({
                    title: '<h2 style="text-align:left"><i class="fa fa-exclamation-circle"></i>&nbsp;We encountered an error<h2>',
                    content: message3,
                    type: 'red',
                    // Set Theme for the popup
                    theme: 'Material',
                    typeAnimated: true,
                    buttons: {
                        close: function () {}
                    }
                });

The above code is from a page that i created for a contact us script. the script sets all the inputs that are on the page using the name= attribute and then sets messages for the inputs when validation rules are not met, highlights and un-highlights the fields with errors, shows error messages in a set div tag and then handles form submit when the form is valid. :)


问:
How to resolve the converting circular structure to JSON issue in fetch
I want to get the list of the repositories by providing a username.
Below is what I have done so far.

```<code>router.get('/github/:username', (req, res) => {
    try {
        const url = `https://api.github.com/users/${req.params.username}/repos?per_page=5&sort=created:asc&client_id=${config.get('githubClientId')}&clientSecret=${config.get('githubSecret')}`;
        const headers = {
            "Content-Type": "application/x-www-form-urlencoded",
        };
        console.log(url);
        fetch(url, {
            method: 'GET',
            headers: headers,
        }).then(data => {
            if (data.status !== 200) {
                return res.status(404).send({
                    msg: 'No GitHub profile found'
                });
            } else {
                return data.json();
            }
        }).then(result => res.json(result));
    } catch (err) {
        console.error(err.message);
        res.status(500).send('Server Error');
    }
})
</code>```

When I use the dynamically created URL in the browser, I get the response

When I pass valid user-name, I get the repositories in Postman, where I am testing the API

When I pass invalid user-name, I get the following error

```<code>(node:18684) UnhandledPromiseRejectionWarning: TypeError: Converting circular structure to JSON
    at JSON.stringify (<anonymous>)
    at stringify (E:\Connector\node_modules\express\lib\response.js:1123:12)
    at ServerResponse.json (E:\Connector\node_modules\express\lib\response.js:260:14)
    at fetch.then.then.result (E:\Connector\routes\api\profile.js:396:31)
    at process._tickCallback (internal/process/next_tick.js:68:7)
(node:18684) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
</code>```

Can anybody tell me how to resolve this error? I have looked at many resources but could not find any concrete.

答:
The problem is the return res.status(404).send(…) in the first then callback. The second then callback will then try to res.json(result) that return value.

You should instead write

```<code>router.get('/github/:username', (req, res) => {
    const url = `https://api.github.com/users/${req.params.username}/repos?per_page=5&sort=created:asc&client_id=${config.get('githubClientId')}&clientSecret=${config.get('githubSecret')}`;
    const headers = {
        "Content-Type": "application/x-www-form-urlencoded",
    };
    console.log(url);
    fetch(url, {
        method: 'GET',
        headers: headers,
    }).then(data => {
        if (data.status !== 200) {
            res.status(404).send({
                msg: 'No GitHub profile found'
            });
        } else {
            return data.json().then(result => {
                res.json(result);
            });
        }
    }).catch(err => {
        console.error(err.message);
        res.status(500).send('Server Error');
    });
})
</code>```

Body:
I want to get the list of the repositories by providing a username.
Below is what I have done so far.

router.get('/github/:username', (req, res) => {
    try {
        const url = `https://api.github.com/users/${req.params.username}/repos?per_page=5&sort=created:asc&client_id=${config.get('githubClientId')}&clientSecret=${config.get('githubSecret')}`;
        const headers = {
            "Content-Type": "application/x-www-form-urlencoded",
        };
        console.log(url);
        fetch(url, {
            method: 'GET',
            headers: headers,
        }).then(data => {
            if (data.status !== 200) {
                return res.status(404).send({
                    msg: 'No GitHub profile found'
                });
            } else {
                return data.json();
            }
        }).then(result => res.json(result));
    } catch (err) {
        console.error(err.message);
        res.status(500).send('Server Error');
    }
})

When I use the dynamically created URL in the browser, I get the response

When I pass valid user-name, I get the repositories in Postman, where I am testing the API

When I pass invalid user-name, I get the following error

(node:18684) UnhandledPromiseRejectionWarning: TypeError: Converting circular structure to JSON
    at JSON.stringify (<anonymous>)
    at stringify (E:\Connector\node_modules\express\lib\response.js:1123:12)
    at ServerResponse.json (E:\Connector\node_modules\express\lib\response.js:260:14)
    at fetch.then.then.result (E:\Connector\routes\api\profile.js:396:31)
    at process._tickCallback (internal/process/next_tick.js:68:7)
(node:18684) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)

Can anybody tell me how to resolve this error? I have looked at many resources but could not find any concrete.

Body:
The problem is the return res.status(404).send(…) in the first then callback. The second then callback will then try to res.json(result) that return value.

You should instead write

router.get('/github/:username', (req, res) => {
    const url = `https://api.github.com/users/${req.params.username}/repos?per_page=5&sort=created:asc&client_id=${config.get('githubClientId')}&clientSecret=${config.get('githubSecret')}`;
    const headers = {
        "Content-Type": "application/x-www-form-urlencoded",
    };
    console.log(url);
    fetch(url, {
        method: 'GET',
        headers: headers,
    }).then(data => {
        if (data.status !== 200) {
            res.status(404).send({
                msg: 'No GitHub profile found'
            });
        } else {
            return data.json().then(result => {
                res.json(result);
            });
        }
    }).catch(err => {
        console.error(err.message);
        res.status(500).send('Server Error');
    });
})


问:
How to take unique IDs and convert each row of another column into another column in R and Python
My data has the form:

```<code>groups <- c("4","4.2","4.2.1","4.2.1.1", "1", "1.2", "1.2.1", "1.2.1.2","1.2.1.2.1")
x <- data.frame(ID = c(rep("samp_1", 4), rep("samp_2", 5)), Group = groups)
</code>```

How do I get this?:

```<code>ID       col_1   col_2   col_3   col_4     col_5
samp_1   4       4.2     4.2.1   4.2.1.1   NA
samp_2   1       1.2     1.2.1   1.2.1.2   1.2.1.2.1
</code>```

Each column will be determined by the length of the string, so all data in column 4 will have length 4 (or length 7 including the dots).

I am looking for the most general solution to this (e.g. using loops; using as few packages as possible) because I need to implement this in both R and Python.

答:
Excellent options by akrun. If the data is a bit out of order, you may want to try this:

```<code>x %>%
  mutate(temp = str_c('col_', str_count(Group, "\\."))) %>%
  pivot_wider(names_from = temp, values_from = Group) %>%
  select(ID, order(colnames(.)))
</code>```

Data:

```<code>groups <- c("41.2","4","4.2.1","4.2.1.1", "1", "1.2", "1.2.1", "1.2.1.2","1.2.1.2.1")
x <- data.frame(ID = c(rep("samp_1", 4), rep("samp_2", 5)), Group = groups)
</code>```

Result:

```<code># A tibble: 2 x 6
  ID     col_0 col_1 col_2 col_3   col_4
  <chr>  <chr> <chr> <chr> <chr>   <chr>
1 samp_1 4     41.2  4.2.1 4.2.1.1 NA
2 samp_2 1     1.2   1.2.1 1.2.1.2 1.2.1.2.1
</code>```

Body:
My data has the form:

groups <- c("4","4.2","4.2.1","4.2.1.1", "1", "1.2", "1.2.1", "1.2.1.2","1.2.1.2.1")
x <- data.frame(ID = c(rep("samp_1", 4), rep("samp_2", 5)), Group = groups)

How do I get this?:

ID       col_1   col_2   col_3   col_4     col_5
samp_1   4       4.2     4.2.1   4.2.1.1   NA
samp_2   1       1.2     1.2.1   1.2.1.2   1.2.1.2.1

Each column will be determined by the length of the string, so all data in column 4 will have length 4 (or length 7 including the dots).

I am looking for the most general solution to this (e.g. using loops; using as few packages as possible) because I need to implement this in both R and Python.

Body:
Excellent options by akrun. If the data is a bit out of order, you may want to try this:

x %>%
  mutate(temp = str_c('col_', str_count(Group, "\\."))) %>%
  pivot_wider(names_from = temp, values_from = Group) %>%
  select(ID, order(colnames(.)))

Data:

groups <- c("41.2","4","4.2.1","4.2.1.1", "1", "1.2", "1.2.1", "1.2.1.2","1.2.1.2.1")
x <- data.frame(ID = c(rep("samp_1", 4), rep("samp_2", 5)), Group = groups)

Result:

# A tibble: 2 x 6
  ID     col_0 col_1 col_2 col_3   col_4
  <chr>  <chr> <chr> <chr> <chr>   <chr>
1 samp_1 4     41.2  4.2.1 4.2.1.1 NA
2 samp_2 1     1.2   1.2.1 1.2.1.2 1.2.1.2.1


问:
Gcc-4.2 failed with exit code 1 Error
I am getting this error when i am trying to build my app. In the simulator it works fine but when coming to build for ipa it gives the following error:

Command /Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/gcc-4.2 failed with exit code 1

What is causing this error?

Edited

Ld
  build/halalgauge.build/Release-iphoneos/halalgauge.build/Objects-normal/armv6/halalgauge
  normal armv6 cd /Users/admin/Desktop/ShopSavvy setenv
  IPHONEOS_DEPLOYMENT_TARGET 4.2 setenv PATH
  "/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin:/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"
  /Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/gcc-4.2 -arch
  armv6 -isysroot
  /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.2.sdk
  -L/Users/admin/Desktop/ShopSavvy/build/Release-iphoneos -L/Users/admin/Desktop/ShopSavvy -L/Users/admin/Desktop/ShopSavvy/Classes/ZBarSDK -L/Users/admin/Desktop/ShopSavvy/Classes/ScannerKit-4.0.3 -F/Users/admin/Desktop/ShopSavvy/build/Release-iphoneos -filelist /Users/admin/Desktop/ShopSavvy/build/halalgauge.build/Release-iphoneos/halalgauge.build/Objects-normal/armv6/halalgauge.LinkFileList
  -Xlinker -map -Xlinker /Users/admin/Desktop/ShopSavvy/build/halalgauge.build/Release-iphoneos/halalgauge.build/halalgauge-LinkMap-normal-armv6.txt
  -dead_strip all_load -lstdc++ -miphoneos-version-min=4.2 -framework CoreGraphics -framework AVFoundation -framework CoreVideo -framework
  CoreMedia -framework Foundation -framework AudioToolbox -framework
  QuartzCore -framework UIKit -framework iAd -lsqlite3.0 -framework
  MessageUI -framework AddressBook -framework AddressBookUI -framework
  MapKit -framework CoreLocation -liconv -lScannerKit -framework
  SystemConfiguration -framework MediaPlayer -o
  /Users/admin/Desktop/ShopSavvy/build/halalgauge.build/Release-iphoneos/halalgauge.build/Objects-normal/armv6/halalgauge

arm-apple-darwin10-gcc-4.2.1: all_load: No such file or directory
  Command
  /Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/gcc-4.2
  failed with exit code 1

答:
If you inspect the linker invocation, you’ll see the following:

```<code>-dead_strip all_load -lstdc++
</code>```

The linker interprets that all_load as a file that must be linked, hence the error:

arm-apple-darwin10-gcc-4.2.1: all_load: No such file or directory

You need to specify -all_load (with an hyphen) instead of all_load in the linker flags.

ContentLicense: CC BY-SA 3.0

Title: Gcc-4.2 failed with exit code 1 Error

Body:
If you inspect the linker invocation, you’ll see the following:

-dead_strip all_load -lstdc++

The linker interprets that all_load as a file that must be linked, hence the error:

arm-apple-darwin10-gcc-4.2.1: all_load: No such file or directory

You need to specify -all_load (with an hyphen) instead of all_load in the linker flags.


问:
Jenkins pipeline httpRequest giving NotSerializableException
I want to do a simple httpRequest to get some json data. Its giving me NotSerializableException when I use httpRequest plugin.

I tried adding @NonCPS, but it had no effect.

I tried directly returning the httpRequest response without any assignments to variables, but still getting that exception.

I tried doing sh "curl 'https://xxxxxx/api/getUser'", but I get similar NotSerializableException.

I am using Jenkinsfile. Jenkins ver: 2.172

Here is my Jenkins pipeline code:

```<code>pipeline {
    agent any

    stages {....}
    post {
        always {
            handleBuildNotification()
        }
    }
}

def handleBuildNotification() {
    String emails = fetchUserEmails()
}

@NonCPS
def fetchUserEmails() {

    String httpResponse = httpRequest(url: 'https://xxxxxx/api/getUser')

    def jsonResponse = readJSON text: httpResponse.content;
    return jsonResponse.response.result
}
</code>```

Exception that I get:

```<code>[Pipeline] httpRequest
HttpMethod: GET
URL: https://xxxxxx/api/getUser
Sending request to url: https://xxxxxx/api/getUser
Error when executing always post condition:
java.io.NotSerializableException: hudson.model.User
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:926)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:568)
    at org.jboss.marshalling.river.BlockMarshaller.doWriteObject(BlockMarshaller.java:65)
    at org.jboss.marshalling.river.BlockMarshaller.writeObject(BlockMarshaller.java:56)
    at org.jboss.marshalling.MarshallerObjectOutputStream.writeObjectOverride(MarshallerObjectOutputStream.java:50)
    at org.jboss.marshalling.river.RiverObjectOutputStream.writeObjectOverride(RiverObjectOutputStream.java:179)
    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:344)
    at java.util.HashMap.internalWriteEntries(HashMap.java:1793)
    at java.util.HashMap.writeObject(HashMap.java:1363)
    at sun.reflect.GeneratedMethodAccessor40.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.jboss.marshalling.reflect.JDKSpecific$SerMethods.callWriteObject(JDKSpecific.java:156)
    at org.jboss.marshalling.reflect.SerializableClass.callWriteObject(SerializableClass.java:191)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:1028)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:920)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1082)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:1040)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:920)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1082)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:1040)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:1019)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:920)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1082)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:1040)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:1019)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:920)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1082)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:1040)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:1019)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:920)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1082)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:1040)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:1019)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:920)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1082)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:1040)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:1019)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:920)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1082)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:1040)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:1019)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:920)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1082)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:1040)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:920)
    at org.jboss.marshalling.river.BlockMarshaller.doWriteObject(BlockMarshaller.java:65)
    at org.jboss.marshalling.river.BlockMarshaller.writeObject(BlockMarshaller.java:56)
    at org.jboss.marshalling.MarshallerObjectOutputStream.writeObjectOverride(MarshallerObjectOutputStream.java:50)
    at org.jboss.marshalling.river.RiverObjectOutputStream.writeObjectOverride(RiverObjectOutputStream.java:179)
    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:344)
    at java.util.TreeMap.writeObject(TreeMap.java:2438)
    at sun.reflect.GeneratedMethodAccessor98.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.jboss.marshalling.reflect.JDKSpecific$SerMethods.callWriteObject(JDKSpecific.java:156)
    at org.jboss.marshalling.reflect.SerializableClass.callWriteObject(SerializableClass.java:191)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:1028)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:920)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1082)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:1040)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:920)
    at org.jboss.marshalling.AbstractObjectOutput.writeObject(AbstractObjectOutput.java:58)
    at org.jboss.marshalling.AbstractMarshaller.writeObject(AbstractMarshaller.java:111)
    at org.jenkinsci.plugins.workflow.support.pickles.serialization.RiverWriter.lambda$writeObject$0(RiverWriter.java:144)
    at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.GroovySandbox.runInSandbox(GroovySandbox.java:241)
    at org.jenkinsci.plugins.workflow.support.pickles.serialization.RiverWriter.writeObject(RiverWriter.java:143)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.saveProgram(CpsThreadGroup.java:500)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.saveProgram(CpsThreadGroup.java:476)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.saveProgramIfPossible(CpsThreadGroup.java:463)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.run(CpsThreadGroup.java:387)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.access$200(CpsThreadGroup.java:93)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:259)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:247)
    at org.jenkinsci.plugins.workflow.cps.CpsVmExecutorService$2.call(CpsVmExecutorService.java:64)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at hudson.remoting.SingleLaneExecutorService$1.run(SingleLaneExecutorService.java:131)
    at jenkins.util.ContextResettingExecutorService$1.run(ContextResettingExecutorService.java:28)
    at jenkins.security.ImpersonatingExecutorService$1.run(ImpersonatingExecutorService.java:59)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
Caused by: an exception which occurred:
    in field com.cloudbees.groovy.cps.impl.BlockScopeEnv.locals
    in object com.cloudbees.groovy.cps.impl.BlockScopeEnv@6fd164e
    in field com.cloudbees.groovy.cps.impl.CallEnv.caller
    in object com.cloudbees.groovy.cps.impl.FunctionCallEnv@7a01e553
    in field com.cloudbees.groovy.cps.impl.ProxyEnv.parent
    in object com.cloudbees.groovy.cps.impl.BlockScopeEnv@3b8a49f9
    in field com.cloudbees.groovy.cps.impl.ProxyEnv.parent
    in object com.cloudbees.groovy.cps.impl.BlockScopeEnv@2c3dfe33
    in field com.cloudbees.groovy.cps.impl.ProxyEnv.parent
    in object com.cloudbees.groovy.cps.impl.BlockScopeEnv@7e950392
    in field com.cloudbees.groovy.cps.impl.CallEnv.caller
    in object com.cloudbees.groovy.cps.impl.FunctionCallEnv@18f9406b
    in field com.cloudbees.groovy.cps.Continuable.e
    in object org.jenkinsci.plugins.workflow.cps.SandboxContinuable@1ada1a6a
    in field org.jenkinsci.plugins.workflow.cps.CpsThread.program
    in object org.jenkinsci.plugins.workflow.cps.CpsThread@3caa56cd
    in field org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.threads
    in object org.jenkinsci.plugins.workflow.cps.CpsThreadGroup@2c748474
    in object org.jenkinsci.plugins.workflow.cps.CpsThreadGroup@2c748474

[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
an exception which occurred:
    in field com.cloudbees.groovy.cps.impl.BlockScopeEnv.locals
    in object com.cloudbees.groovy.cps.impl.BlockScopeEnv@6fd164e
    in field com.cloudbees.groovy.cps.impl.CallEnv.caller
    in object com.cloudbees.groovy.cps.impl.FunctionCallEnv@7a01e553
    in field com.cloudbees.groovy.cps.impl.ProxyEnv.parent
    in object com.cloudbees.groovy.cps.impl.BlockScopeEnv@3b8a49f9
    in field com.cloudbees.groovy.cps.impl.ProxyEnv.parent
    in object com.cloudbees.groovy.cps.impl.BlockScopeEnv@2c3dfe33
    in field com.cloudbees.groovy.cps.impl.ProxyEnv.parent
    in object com.cloudbees.groovy.cps.impl.BlockScopeEnv@7e950392
    in field com.cloudbees.groovy.cps.impl.CallEnv.caller
    in object com.cloudbees.groovy.cps.impl.FunctionCallEnv@18f9406b
    in field com.cloudbees.groovy.cps.Continuable.e
    in object org.jenkinsci.plugins.workflow.cps.SandboxContinuable@1ada1a6a
    in field org.jenkinsci.plugins.workflow.cps.CpsThread.program
    in object org.jenkinsci.plugins.workflow.cps.CpsThread@3caa56cd
    in field org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.threads
    in object org.jenkinsci.plugins.workflow.cps.CpsThreadGroup@2c748474
    in object org.jenkinsci.plugins.workflow.cps.CpsThreadGroup@2c748474
Caused: java.io.NotSerializableException: hudson.model.User
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:926)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:568)
    at org.jboss.marshalling.river.BlockMarshaller.doWriteObject(BlockMarshaller.java:65)
    at org.jboss.marshalling.river.BlockMarshaller.writeObject(BlockMarshaller.java:56)
    at org.jboss.marshalling.MarshallerObjectOutputStream.writeObjectOverride(MarshallerObjectOutputStream.java:50)
    at org.jboss.marshalling.river.RiverObjectOutputStream.writeObjectOverride(RiverObjectOutputStream.java:179)
    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:344)
    at java.util.HashMap.internalWriteEntries(HashMap.java:1793)
    at java.util.HashMap.writeObject(HashMap.java:1363)
    at sun.reflect.GeneratedMethodAccessor40.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.jboss.marshalling.reflect.JDKSpecific$SerMethods.callWriteObject(JDKSpecific.java:156)
    at org.jboss.marshalling.reflect.SerializableClass.callWriteObject(SerializableClass.java:191)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:1028)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:920)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1082)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:1040)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:920)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1082)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:1040)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:1019)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:920)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1082)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:1040)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:1019)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:920)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1082)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:1040)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:1019)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:920)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1082)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:1040)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:1019)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:920)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1082)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:1040)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:1019)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:920)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1082)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:1040)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:1019)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:920)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1082)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:1040)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:920)
    at org.jboss.marshalling.river.BlockMarshaller.doWriteObject(BlockMarshaller.java:65)
    at org.jboss.marshalling.river.BlockMarshaller.writeObject(BlockMarshaller.java:56)
    at org.jboss.marshalling.MarshallerObjectOutputStream.writeObjectOverride(MarshallerObjectOutputStream.java:50)
    at org.jboss.marshalling.river.RiverObjectOutputStream.writeObjectOverride(RiverObjectOutputStream.java:179)
    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:344)
    at java.util.TreeMap.writeObject(TreeMap.java:2438)
    at sun.reflect.GeneratedMethodAccessor98.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.jboss.marshalling.reflect.JDKSpecific$SerMethods.callWriteObject(JDKSpecific.java:156)
    at org.jboss.marshalling.reflect.SerializableClass.callWriteObject(SerializableClass.java:191)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:1028)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:920)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1082)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:1040)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:920)
    at org.jboss.marshalling.AbstractObjectOutput.writeObject(AbstractObjectOutput.java:58)
    at org.jboss.marshalling.AbstractMarshaller.writeObject(AbstractMarshaller.java:111)
    at org.jenkinsci.plugins.workflow.support.pickles.serialization.RiverWriter.lambda$writeObject$0(RiverWriter.java:144)
    at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.GroovySandbox.runInSandbox(GroovySandbox.java:241)
    at org.jenkinsci.plugins.workflow.support.pickles.serialization.RiverWriter.writeObject(RiverWriter.java:143)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.saveProgram(CpsThreadGroup.java:500)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.saveProgram(CpsThreadGroup.java:476)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.saveProgramIfPossible(CpsThreadGroup.java:463)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.run(CpsThreadGroup.java:387)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.access$200(CpsThreadGroup.java:93)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:259)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:247)
    at org.jenkinsci.plugins.workflow.cps.CpsVmExecutorService$2.call(CpsVmExecutorService.java:64)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at hudson.remoting.SingleLaneExecutorService$1.run(SingleLaneExecutorService.java:131)
    at jenkins.util.ContextResettingExecutorService$1.run(ContextResettingExecutorService.java:28)
    at jenkins.security.ImpersonatingExecutorService$1.run(ImpersonatingExecutorService.java:59)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
Finished: FAILURE
</code>```

答:
I’m trying to make an intelligent guess here: I bet the HTTP request doesn’t return a JSON string, either you must pass login credentials or need to pass proper request headers like Accept: application/json. The error seems to come from the JSON deserializer.

You could use print httpResponse.content in your script, to debug the response body.

Body:
I want to do a simple httpRequest to get some json data. Its giving me NotSerializableException when I use httpRequest plugin.

I tried adding @NonCPS, but it had no effect.

I tried directly returning the httpRequest response without any assignments to variables, but still getting that exception.

I tried doing sh "curl 'https://xxxxxx/api/getUser'", but I get similar NotSerializableException.

I am using Jenkinsfile. Jenkins ver: 2.172

Here is my Jenkins pipeline code:

pipeline {
    agent any

    stages {....}
    post {
        always {
            handleBuildNotification()
        }
    }
}

def handleBuildNotification() {
    String emails = fetchUserEmails()
}

@NonCPS
def fetchUserEmails() {

    String httpResponse = httpRequest(url: 'https://xxxxxx/api/getUser')

    def jsonResponse = readJSON text: httpResponse.content;
    return jsonResponse.response.result
}

Exception that I get:

[Pipeline] httpRequest
HttpMethod: GET
URL: https://xxxxxx/api/getUser
Sending request to url: https://xxxxxx/api/getUser
Error when executing always post condition:
java.io.NotSerializableException: hudson.model.User
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:926)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:568)
    at org.jboss.marshalling.river.BlockMarshaller.doWriteObject(BlockMarshaller.java:65)
    at org.jboss.marshalling.river.BlockMarshaller.writeObject(BlockMarshaller.java:56)
    at org.jboss.marshalling.MarshallerObjectOutputStream.writeObjectOverride(MarshallerObjectOutputStream.java:50)
    at org.jboss.marshalling.river.RiverObjectOutputStream.writeObjectOverride(RiverObjectOutputStream.java:179)
    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:344)
    at java.util.HashMap.internalWriteEntries(HashMap.java:1793)
    at java.util.HashMap.writeObject(HashMap.java:1363)
    at sun.reflect.GeneratedMethodAccessor40.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.jboss.marshalling.reflect.JDKSpecific$SerMethods.callWriteObject(JDKSpecific.java:156)
    at org.jboss.marshalling.reflect.SerializableClass.callWriteObject(SerializableClass.java:191)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:1028)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:920)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1082)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:1040)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:920)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1082)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:1040)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:1019)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:920)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1082)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:1040)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:1019)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:920)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1082)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:1040)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:1019)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:920)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1082)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:1040)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:1019)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:920)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1082)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:1040)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:1019)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:920)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1082)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:1040)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:1019)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:920)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1082)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:1040)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:920)
    at org.jboss.marshalling.river.BlockMarshaller.doWriteObject(BlockMarshaller.java:65)
    at org.jboss.marshalling.river.BlockMarshaller.writeObject(BlockMarshaller.java:56)
    at org.jboss.marshalling.MarshallerObjectOutputStream.writeObjectOverride(MarshallerObjectOutputStream.java:50)
    at org.jboss.marshalling.river.RiverObjectOutputStream.writeObjectOverride(RiverObjectOutputStream.java:179)
    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:344)
    at java.util.TreeMap.writeObject(TreeMap.java:2438)
    at sun.reflect.GeneratedMethodAccessor98.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.jboss.marshalling.reflect.JDKSpecific$SerMethods.callWriteObject(JDKSpecific.java:156)
    at org.jboss.marshalling.reflect.SerializableClass.callWriteObject(SerializableClass.java:191)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:1028)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:920)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1082)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:1040)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:920)
    at org.jboss.marshalling.AbstractObjectOutput.writeObject(AbstractObjectOutput.java:58)
    at org.jboss.marshalling.AbstractMarshaller.writeObject(AbstractMarshaller.java:111)
    at org.jenkinsci.plugins.workflow.support.pickles.serialization.RiverWriter.lambda$writeObject$0(RiverWriter.java:144)
    at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.GroovySandbox.runInSandbox(GroovySandbox.java:241)
    at org.jenkinsci.plugins.workflow.support.pickles.serialization.RiverWriter.writeObject(RiverWriter.java:143)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.saveProgram(CpsThreadGroup.java:500)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.saveProgram(CpsThreadGroup.java:476)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.saveProgramIfPossible(CpsThreadGroup.java:463)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.run(CpsThreadGroup.java:387)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.access$200(CpsThreadGroup.java:93)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:259)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:247)
    at org.jenkinsci.plugins.workflow.cps.CpsVmExecutorService$2.call(CpsVmExecutorService.java:64)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at hudson.remoting.SingleLaneExecutorService$1.run(SingleLaneExecutorService.java:131)
    at jenkins.util.ContextResettingExecutorService$1.run(ContextResettingExecutorService.java:28)
    at jenkins.security.ImpersonatingExecutorService$1.run(ImpersonatingExecutorService.java:59)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
Caused by: an exception which occurred:
    in field com.cloudbees.groovy.cps.impl.BlockScopeEnv.locals
    in object com.cloudbees.groovy.cps.impl.BlockScopeEnv@6fd164e
    in field com.cloudbees.groovy.cps.impl.CallEnv.caller
    in object com.cloudbees.groovy.cps.impl.FunctionCallEnv@7a01e553
    in field com.cloudbees.groovy.cps.impl.ProxyEnv.parent
    in object com.cloudbees.groovy.cps.impl.BlockScopeEnv@3b8a49f9
    in field com.cloudbees.groovy.cps.impl.ProxyEnv.parent
    in object com.cloudbees.groovy.cps.impl.BlockScopeEnv@2c3dfe33
    in field com.cloudbees.groovy.cps.impl.ProxyEnv.parent
    in object com.cloudbees.groovy.cps.impl.BlockScopeEnv@7e950392
    in field com.cloudbees.groovy.cps.impl.CallEnv.caller
    in object com.cloudbees.groovy.cps.impl.FunctionCallEnv@18f9406b
    in field com.cloudbees.groovy.cps.Continuable.e
    in object org.jenkinsci.plugins.workflow.cps.SandboxContinuable@1ada1a6a
    in field org.jenkinsci.plugins.workflow.cps.CpsThread.program
    in object org.jenkinsci.plugins.workflow.cps.CpsThread@3caa56cd
    in field org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.threads
    in object org.jenkinsci.plugins.workflow.cps.CpsThreadGroup@2c748474
    in object org.jenkinsci.plugins.workflow.cps.CpsThreadGroup@2c748474

[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
an exception which occurred:
    in field com.cloudbees.groovy.cps.impl.BlockScopeEnv.locals
    in object com.cloudbees.groovy.cps.impl.BlockScopeEnv@6fd164e
    in field com.cloudbees.groovy.cps.impl.CallEnv.caller
    in object com.cloudbees.groovy.cps.impl.FunctionCallEnv@7a01e553
    in field com.cloudbees.groovy.cps.impl.ProxyEnv.parent
    in object com.cloudbees.groovy.cps.impl.BlockScopeEnv@3b8a49f9
    in field com.cloudbees.groovy.cps.impl.ProxyEnv.parent
    in object com.cloudbees.groovy.cps.impl.BlockScopeEnv@2c3dfe33
    in field com.cloudbees.groovy.cps.impl.ProxyEnv.parent
    in object com.cloudbees.groovy.cps.impl.BlockScopeEnv@7e950392
    in field com.cloudbees.groovy.cps.impl.CallEnv.caller
    in object com.cloudbees.groovy.cps.impl.FunctionCallEnv@18f9406b
    in field com.cloudbees.groovy.cps.Continuable.e
    in object org.jenkinsci.plugins.workflow.cps.SandboxContinuable@1ada1a6a
    in field org.jenkinsci.plugins.workflow.cps.CpsThread.program
    in object org.jenkinsci.plugins.workflow.cps.CpsThread@3caa56cd
    in field org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.threads
    in object org.jenkinsci.plugins.workflow.cps.CpsThreadGroup@2c748474
    in object org.jenkinsci.plugins.workflow.cps.CpsThreadGroup@2c748474
Caused: java.io.NotSerializableException: hudson.model.User
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:926)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:568)
    at org.jboss.marshalling.river.BlockMarshaller.doWriteObject(BlockMarshaller.java:65)
    at org.jboss.marshalling.river.BlockMarshaller.writeObject(BlockMarshaller.java:56)
    at org.jboss.marshalling.MarshallerObjectOutputStream.writeObjectOverride(MarshallerObjectOutputStream.java:50)
    at org.jboss.marshalling.river.RiverObjectOutputStream.writeObjectOverride(RiverObjectOutputStream.java:179)
    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:344)
    at java.util.HashMap.internalWriteEntries(HashMap.java:1793)
    at java.util.HashMap.writeObject(HashMap.java:1363)
    at sun.reflect.GeneratedMethodAccessor40.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.jboss.marshalling.reflect.JDKSpecific$SerMethods.callWriteObject(JDKSpecific.java:156)
    at org.jboss.marshalling.reflect.SerializableClass.callWriteObject(SerializableClass.java:191)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:1028)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:920)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1082)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:1040)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:920)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1082)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:1040)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:1019)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:920)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1082)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:1040)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:1019)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:920)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1082)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:1040)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:1019)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:920)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1082)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:1040)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:1019)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:920)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1082)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:1040)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:1019)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:920)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1082)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:1040)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:1019)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:920)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1082)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:1040)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:920)
    at org.jboss.marshalling.river.BlockMarshaller.doWriteObject(BlockMarshaller.java:65)
    at org.jboss.marshalling.river.BlockMarshaller.writeObject(BlockMarshaller.java:56)
    at org.jboss.marshalling.MarshallerObjectOutputStream.writeObjectOverride(MarshallerObjectOutputStream.java:50)
    at org.jboss.marshalling.river.RiverObjectOutputStream.writeObjectOverride(RiverObjectOutputStream.java:179)
    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:344)
    at java.util.TreeMap.writeObject(TreeMap.java:2438)
    at sun.reflect.GeneratedMethodAccessor98.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.jboss.marshalling.reflect.JDKSpecific$SerMethods.callWriteObject(JDKSpecific.java:156)
    at org.jboss.marshalling.reflect.SerializableClass.callWriteObject(SerializableClass.java:191)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:1028)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:920)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1082)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:1040)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:920)
    at org.jboss.marshalling.AbstractObjectOutput.writeObject(AbstractObjectOutput.java:58)
    at org.jboss.marshalling.AbstractMarshaller.writeObject(AbstractMarshaller.java:111)
    at org.jenkinsci.plugins.workflow.support.pickles.serialization.RiverWriter.lambda$writeObject$0(RiverWriter.java:144)
    at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.GroovySandbox.runInSandbox(GroovySandbox.java:241)
    at org.jenkinsci.plugins.workflow.support.pickles.serialization.RiverWriter.writeObject(RiverWriter.java:143)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.saveProgram(CpsThreadGroup.java:500)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.saveProgram(CpsThreadGroup.java:476)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.saveProgramIfPossible(CpsThreadGroup.java:463)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.run(CpsThreadGroup.java:387)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.access$200(CpsThreadGroup.java:93)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:259)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:247)
    at org.jenkinsci.plugins.workflow.cps.CpsVmExecutorService$2.call(CpsVmExecutorService.java:64)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at hudson.remoting.SingleLaneExecutorService$1.run(SingleLaneExecutorService.java:131)
    at jenkins.util.ContextResettingExecutorService$1.run(ContextResettingExecutorService.java:28)
    at jenkins.security.ImpersonatingExecutorService$1.run(ImpersonatingExecutorService.java:59)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
Finished: FAILURE


问:
How to inject React Component inside WebView (react-native-webview)?
Is there a way to pass in a web React component to WebView directly? Something like this-</p>

```<code>import ReactContainer from 'somewhere';
import { WebView } from "react-native-webview";

<WebView
        source={{ html: "<ReactContainer/>" }}
></WebView>
</code>```

答:
You can render a React component to its initial HTML with renderToString() and then display it inside your WebView like so:

import { renderToString } from 'react-dom/server'
import ReactContainer from 'somewhere';
import { WebView } from "react-native-webview";

<WebView source={{ html: renderToString(<ReactContainer />) }}></WebView>;

```

More infos about ReactDOMServer here.

Body:
Is there a way to pass in a web React component to WebView directly? Something like this-

import ReactContainer from 'somewhere';
import { WebView } from "react-native-webview";

<WebView
        source={{ html: "<ReactContainer/>" }}
></WebView>

Body:
You can render a React component to its initial HTML with renderToString() and then display it inside your WebView like so:

import { renderToString } from 'react-dom/server'
import ReactContainer from 'somewhere';
import { WebView } from "react-native-webview";

<WebView source={{ html: renderToString(<ReactContainer />) }}></WebView>;

More infos about ReactDOMServer here.


问:
Azure SQL Monthly Partitioning (Split)
I've used an example from the Microsoft help page to create a partition using YYYYMM on a DateTime2 property (code and link below).

I set the start partition from 201702 (Feb 2017) to 202006 (June 2020).

I want to be able to add (split?) a new partition for the next month, at the beginning of the previous month - if it does not already exist. When the date is 1st June 2020, it will then create a new partition for July. I'm unsure how to proceed.

I've tried looking at the Azure documentation but it only contains an example for a standard number.

https://learn.microsoft.com/en-us/sql/t-sql/statements/create-partition-function-transact-sql?view=sql-server-ver15

```<code>--Create date partition function with increment by month.
DECLARE @DatePartitionFunction nvarchar(max) =
    N'CREATE PARTITION FUNCTION DatePartitionFunction (datetime2)
    AS RANGE RIGHT FOR VALUES (';
DECLARE @i datetime2 = '20170201';
WHILE @i < '20200601'
BEGIN
SET @DatePartitionFunction += '''' + CAST(@i as nvarchar(10)) + '''' + N', ';
SET @i = DATEADD(MM, 1, @i);
END
SET @DatePartitionFunction += '''' + CAST(@i as nvarchar(10))+ '''' + N');';
EXEC sp_executesql @DatePartitionFunction;
GO
</code>```

答:
I don't know why they chose to use dynamic SQL in the example but that is not needed. Below is a version with static SQL using a variable to specify the new boundary and includes a partition scheme for completeness.

```<code>--Create monthly partitions for all months in the desired range
CREATE PARTITION FUNCTION DatePartitionFunction (datetime2)
    AS RANGE RIGHT FOR VALUES ();

DECLARE @MonthStartDate datetime2 = '20170201';
WHILE @MonthStartDate < '20200601'
BEGIN
    ALTER PARTITION FUNCTION DatePartitionFunction()
        SPLIT RANGE(@MonthStartDate);
    SET @MonthStartDate = DATEADD(month, 1, @MonthStartDate);
END;

CREATE PARTITION SCHEME DatePartitionScheme
    AS PARTITION DatePartitionFunction ALL TO ([PRIMARY]);
GO
</code>```

It is best to create new monthly partitions before the start of the next period to avoid costly data movement during SPLIT, which also requires about 4 times the logging compared to normal DML. This example will create a partition for the next month, if it doesn't already exist:

```<code>--Run this to create a new partition before the next future month if it doesn't already exist
DECLARE @MonthStartDate datetime2 = DATEADD(day, 1, CAST(EOMONTH(GETDATE()) AS date));
IF NOT EXISTS(
    SELECT *
    FROM sys.partition_functions AS pf
    JOIN sys.partition_range_values AS prv ON prv.function_id = pf.function_id
    WHERE
        pf.name = N'DatePartitionFunction'
        AND prv.value = @MonthStartDate
    )
BEGIN
    ALTER PARTITION SCHEME DatePartitionScheme
        NEXT USED [PRIMARY];
    ALTER PARTITION FUNCTION DatePartitionFunction()
        SPLIT RANGE(@MonthStartDate);
END;
GO
</code>```

Title: Azure SQL Monthly Partitioning (Split)

Body:
I've used an example from the Microsoft help page to create a partition using YYYYMM on a DateTime2 property (code and link below).

I set the start partition from 201702 (Feb 2017) to 202006 (June 2020).

I want to be able to add (split?) a new partition for the next month, at the beginning of the previous month - if it does not already exist. When the date is 1st June 2020, it will then create a new partition for July. I'm unsure how to proceed.

I've tried looking at the Azure documentation but it only contains an example for a standard number.

https://learn.microsoft.com/en-us/sql/t-sql/statements/create-partition-function-transact-sql?view=sql-server-ver15

--Create date partition function with increment by month.
DECLARE @DatePartitionFunction nvarchar(max) =
    N'CREATE PARTITION FUNCTION DatePartitionFunction (datetime2)
    AS RANGE RIGHT FOR VALUES (';
DECLARE @i datetime2 = '20170201';
WHILE @i < '20200601'
BEGIN
SET @DatePartitionFunction += '''' + CAST(@i as nvarchar(10)) + '''' + N', ';
SET @i = DATEADD(MM, 1, @i);
END
SET @DatePartitionFunction += '''' + CAST(@i as nvarchar(10))+ '''' + N');';
EXEC sp_executesql @DatePartitionFunction;
GO

Body:
I don't know why they chose to use dynamic SQL in the example but that is not needed. Below is a version with static SQL using a variable to specify the new boundary and includes a partition scheme for completeness.

--Create monthly partitions for all months in the desired range
CREATE PARTITION FUNCTION DatePartitionFunction (datetime2)
    AS RANGE RIGHT FOR VALUES ();

DECLARE @MonthStartDate datetime2 = '20170201';
WHILE @MonthStartDate < '20200601'
BEGIN
    ALTER PARTITION FUNCTION DatePartitionFunction()
        SPLIT RANGE(@MonthStartDate);
    SET @MonthStartDate = DATEADD(month, 1, @MonthStartDate);
END;

CREATE PARTITION SCHEME DatePartitionScheme
    AS PARTITION DatePartitionFunction ALL TO ([PRIMARY]);
GO

It is best to create new monthly partitions before the start of the next period to avoid costly data movement during SPLIT, which also requires about 4 times the logging compared to normal DML. This example will create a partition for the next month, if it doesn't already exist:

--Run this to create a new partition before the next future month if it doesn't already exist
DECLARE @MonthStartDate datetime2 = DATEADD(day, 1, CAST(EOMONTH(GETDATE()) AS date));
IF NOT EXISTS(
    SELECT *
    FROM sys.partition_functions AS pf
    JOIN sys.partition_range_values AS prv ON prv.function_id = pf.function_id
    WHERE
        pf.name = N'DatePartitionFunction'
        AND prv.value = @MonthStartDate
    )
BEGIN
    ALTER PARTITION SCHEME DatePartitionScheme
        NEXT USED [PRIMARY];
    ALTER PARTITION FUNCTION DatePartitionFunction()
        SPLIT RANGE(@MonthStartDate);
END;
GO


问:
How to install numpy on vscode on mac?
It's saying:

```<code>"ModuleNotFoundError: No module named 'numpy'"
</code>```

and then when I do "pip install numpy" it says:

```<code>Requirement already satisfied: numpy in ./Library/Python/2.7/lib/python/site-packages (1.16.6)"
</code>```

答:
Probably you are using python 3.X while pip is configured for python 2.X.

Try running pip3 install numpy

Basically you are installing a package for python 2, while running the script with python 3.

Title: How to install numpy on vscode on mac?

Body:
It's saying:

"ModuleNotFoundError: No module named 'numpy'"

and then when I do "pip install numpy" it says:

Requirement already satisfied: numpy in ./Library/Python/2.7/lib/python/site-packages (1.16.6)"