问:
I get segmentation fault whenever I try to use NPM or nodejs. Uninstalling and reinstalling doesn't fix it
I tried to update nodejs using the following:

```<code>$ sudo npm cache clean -f
$ sudo npm install -g n
$ sudo n stable
</code>```

I have always successfully used this to update nodejs, however, the update failed this time. Now, whenever I run NPM or nodejs, I get a segmentation fault.

I tried uninstalling NPM and nodejs using many variations of:

```<code>sudo apt-get remove --purge npm
sudo apt-get remove --purge nodejs
sudo apt-get remove --purge node
</code>```

And reinstalling them.

However, they never seem to uninstall. Whenever I type NPM or node, it says permission denied. When I use sudo, I get a segmentation fault.

$ which npm results in /usr/local/bin/npm
and I get similar results with nodejs.

Is there a simple way to fix this? I'm very leery about manually removing packages. I've tried this on a personal machine in the past and messed up the package manager so badly that I had no choice but to reinstall Ubuntu. I would like to avoid doing that since this is on a development server.

答:
just remove nodejs, use

```<code>sudo apt-get remove nodejs
</code>```

then go to /usr/local/bin and remove node, nodejs npm if exists:

```<code>sudo rm nodejs
sudo rm npm
sudo rm node
</code>```

reinstall nodejs with this link https://computingforgeeks.com/install-latest-node-js-and-npm-on-ubuntu-debian/

Body:
I tried to update nodejs using the following:

$ sudo npm cache clean -f
$ sudo npm install -g n
$ sudo n stable

I have always successfully used this to update nodejs, however, the update failed this time. Now, whenever I run NPM or nodejs, I get a segmentation fault.

I tried uninstalling NPM and nodejs using many variations of:

sudo apt-get remove --purge npm
sudo apt-get remove --purge nodejs
sudo apt-get remove --purge node

And reinstalling them.

However, they never seem to uninstall. Whenever I type NPM or node, it says permission denied. When I use sudo, I get a segmentation fault.

$ which npm results in /usr/local/bin/npm
and I get similar results with nodejs.

Is there a simple way to fix this? I'm very leery about manually removing packages. I've tried this on a personal machine in the past and messed up the package manager so badly that I had no choice but to reinstall Ubuntu. I would like to avoid doing that since this is on a development server.

Body:
just remove nodejs, use

sudo apt-get remove nodejs

then go to /usr/local/bin and remove node, nodejs npm if exists:

sudo rm nodejs
sudo rm npm
sudo rm node

reinstall nodejs with this link https://computingforgeeks.com/install-latest-node-js-and-npm-on-ubuntu-debian/


来源: stackexchange

问:
Why is not operator giving different result but using = giving correct answer
```<code> static int count = 0;

  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    count = 0;
    int n = sc.nextInt();
    int arr[][] = new int[n][n];
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < n; j++) {
        arr[i][j] = sc.nextInt();
      }
    }
    for (int i = 0; i < n ; i++) {
      row(arr, n, i);
      column(arr, n, i);
    }
    System.out.println(count);
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < n; j++) {
        System.out.print(arr[i][j] + " ");
      }
    }
  }

  static void row(int arr[][], int n, int row) {
    int x, y, min, yHold = 0;

    for (x = 0; x < n; x++) {
      boolean yes = false;
      min = arr[row][x];

      for (y = row; y < n; y++) {
        if (arr[y][x] < min) {
          min = arr[y][x];
          yHold = y;
          yes = true;
        }
      }
      if (yes) {
        int temp = arr[row][x];
        arr[row][x] = min;
        arr[yHold][x] = temp;
        count++;
      }
    }
</code>```

If I replace yes=true with yes=!yes, the output becomes different. Please help, can't seem to figure it out.
The part of the problem the function row is taking are of is:

If we are at ith row, then we have to work with each column at a time
  from 0 to n−1 of this row. For any jth column, swap A[i][j] with the
  minimum of all the elements which are present in a column with index j
  and rows from indices i to n−1.

答:
When you say yes = true, it is always going to be true. But when you say, yes = !yes it will flip back and forth between true and false.

```<code>boolean yes = true;
for (int i = i < 10; i++) {
 System.out.println(yes);
 yes =! yes;
}
</code>```

prints

```<code>true
false
true
false
true
false
true
false
true
false
</code>```

ContentLicense: CC BY-SA 4.0

Body:
 static int count = 0;

  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    count = 0;
    int n = sc.nextInt();
    int arr[][] = new int[n][n];
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < n; j++) {
        arr[i][j] = sc.nextInt();
      }
    }
    for (int i = 0; i < n ; i++) {
      row(arr, n, i);
      column(arr, n, i);
    }
    System.out.println(count);
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < n; j++) {
        System.out.print(arr[i][j] + " ");
      }
    }
  }

  static void row(int arr[][], int n, int row) {
    int x, y, min, yHold = 0;

    for (x = 0; x < n; x++) {
      boolean yes = false;
      min = arr[row][x];

      for (y = row; y < n; y++) {
        if (arr[y][x] < min) {
          min = arr[y][x];
          yHold = y;
          yes = true;
        }
      }
      if (yes) {
        int temp = arr[row][x];
        arr[row][x] = min;
        arr[yHold][x] = temp;
        count++;
      }
    }

If I replace yes=true with yes=!yes, the output becomes different. Please help, can't seem to figure it out.
The part of the problem the function row is taking are of is:

If we are at ith row, then we have to work with each column at a time
  from 0 to n−1 of this row. For any jth column, swap A[i][j] with the
  minimum of all the elements which are present in a column with index j
  and rows from indices i to n−1.

Body:
When you say yes = true, it is always going to be true. But when you say, yes = !yes it will flip back and forth between true and false.

boolean yes = true;
for (int i = i < 10; i++) {
 System.out.println(yes);
 yes =! yes;
}

prints

true
false
true
false
true
false
true
false
true
false


问:
find words that matches the 3 consecutive vowels Regex
```<code>text = "Life is beautiful"
pattern = r"[aeiou]{3,}"
result = re.findall(pattern, text)
print(result)
</code>```

desired result:
['beautiful']

the output I get:
['eau']

I have tried googling and etc....I found multiple answers but none of them worked!!
I am new to regex so maybe I am having issues but I am not sure how to get this to out

I have tried using r"\b[abcde]{3,}\b" still nothing SO please help!!

答:
Your regex only captures the 3 consecutive vowels, so you need to expand it to capture the rest of the word. This can be done by looking for a sequence of letters between two word breaks and using a positive lookahead for 3 consecutive vowels within the sequence. For example:

```<code>import re

text = "Life is beautiful"
pattern = r"\b(?=[a-z]*[aeiou]{3})[a-z]+\b"
result = re.findall(pattern, text, re.I)
print(result)
</code>```

Output:

```<code>['beautiful']
</code>```

Body:
text = "Life is beautiful"
pattern = r"[aeiou]{3,}"
result = re.findall(pattern, text)
print(result)

desired result:
['beautiful']

the output I get:
['eau']

I have tried googling and etc....I found multiple answers but none of them worked!!
I am new to regex so maybe I am having issues but I am not sure how to get this to out

I have tried using r"\b[abcde]{3,}\b" still nothing SO please help!!

Body:
Your regex only captures the 3 consecutive vowels, so you need to expand it to capture the rest of the word. This can be done by looking for a sequence of letters between two word breaks and using a positive lookahead for 3 consecutive vowels within the sequence. For example:

import re

text = "Life is beautiful"
pattern = r"\b(?=[a-z]*[aeiou]{3})[a-z]+\b"
result = re.findall(pattern, text, re.I)
print(result)

Output:

['beautiful']


问:
Problem with OpenGL through SSH connection
I'm trying to use a software (Paraview) in client/server mode opening the client on my desktop machine (linux, debian 10) and do the heavy computations on a remote server (linux, CentOS 8). The software requires OpenGL 3.2 or later implementation and it should be OK with what is installed on my machine as you see from the output of command glxinfo shown below:

```<code>myaccount@desktopmachine:$ glxinfo | grep OpenGL
OpenGL vendor string: NVIDIA Corporation
OpenGL renderer string: *GeForce GTX 650 Ti BOOST/PCIe/SSE2 OpenGL core*
profile version string: 4.6.0 NVIDIA 440.82 OpenGL core profile
shading language version string: 4.60 NVIDIA OpenGL core profile
context flags: (none) OpenGL core profile profile mask: core profile
OpenGL core profile extensions: OpenGL version string: 4.6.0 NVIDIA
440.82 OpenGL shading language version string: 4.60 NVIDIA OpenGL context flags: (none) OpenGL profile mask: (none) OpenGL extensions:
OpenGL ES profile version string: **OpenGL ES 3.2** NVIDIA 440.82 OpenGL
ES profile shading language version string: OpenGL ES GLSL ES 3.20
OpenGL ES profile extensions:
</code>```

The problem is that, when connecting to the remote server through SSH, the OpenGL resulting from the same command is:

```<code>myaccount@server:$ glxinfo | grep "OpenGL"
OpenGL vendor string: NVIDIA Corporation
OpenGL renderer string: *GeForce GTX 650 Ti BOOST/PCIe/SSE2 OpenGL*
version string: **1.4** (2.1.2 NVIDIA 440.82) OpenGL extensions:
</code>```

So it looks like the version of OpenGL is not correctly transmitted.
What should I do to fix this issue that does not allow me to run the software?

答:
In the context of ParaView and the pvserver, you need to use your local display, not the "X11 forwarding" mechanism.

Do not use -X or -Y when connecting and then run DISPLAY=:0 glxinfo, DISPLAY=:0 pvserver. on your server

Body:
I'm trying to use a software (Paraview) in client/server mode opening the client on my desktop machine (linux, debian 10) and do the heavy computations on a remote server (linux, CentOS 8). The software requires OpenGL 3.2 or later implementation and it should be OK with what is installed on my machine as you see from the output of command glxinfo shown below:

myaccount@desktopmachine:$ glxinfo | grep OpenGL
OpenGL vendor string: NVIDIA Corporation
OpenGL renderer string: *GeForce GTX 650 Ti BOOST/PCIe/SSE2 OpenGL core*
profile version string: 4.6.0 NVIDIA 440.82 OpenGL core profile
shading language version string: 4.60 NVIDIA OpenGL core profile
context flags: (none) OpenGL core profile profile mask: core profile
OpenGL core profile extensions: OpenGL version string: 4.6.0 NVIDIA
440.82 OpenGL shading language version string: 4.60 NVIDIA OpenGL context flags: (none) OpenGL profile mask: (none) OpenGL extensions:
OpenGL ES profile version string: **OpenGL ES 3.2** NVIDIA 440.82 OpenGL
ES profile shading language version string: OpenGL ES GLSL ES 3.20
OpenGL ES profile extensions:

The problem is that, when connecting to the remote server through SSH, the OpenGL resulting from the same command is:

myaccount@server:$ glxinfo | grep "OpenGL"
OpenGL vendor string: NVIDIA Corporation
OpenGL renderer string: *GeForce GTX 650 Ti BOOST/PCIe/SSE2 OpenGL*
version string: **1.4** (2.1.2 NVIDIA 440.82) OpenGL extensions:

So it looks like the version of OpenGL is not correctly transmitted.
What should I do to fix this issue that does not allow me to run the software?


问:
Spark/k8s: How to run spark submit on Kubernetes with client mode
I am trying to use spark-submit with client mode in the kubernetes pod to submit jobs to EMR (Due to some other infra issues, we don't allow cluster mode).
By default, spark-submit uses the hostname of the pod as the spark.driver.host and the hostname is the pod's hostname so spark executor could not resolve it. And the spark.driver.port is also locally to the pod (container).

I know a way to pass some confs to spark-submit so that the spark executor can talk to the driver, those configs are:

--conf spark.driver.bindAddress=0.0.0.0 --conf spark.driver.host=$HOST_IP_OF_K8S_WORKER --conf spark.driver.port=32000 --conf spark.driver.blockManager.port=32001

and create a service to in the kubernetes so that spark executor can talk to the driver:

```<code>apiVersion: v1
kind: Service
metadata:
  name: spark-block-manager
  namespace: my-app
spec:
  selector:
    app: my-app
  type: NodePort
  ports:
    - name: port-0
      nodePort: 32000
      port: 32000
      protocol: TCP
      targetPort: 32000
    - name: port-1
      nodePort: 32001
      port: 32001
      protocol: TCP
      targetPort: 32001
    - name: port-2
      nodePort: 32002
      port: 32002
      protocol: TCP
      targetPort: 32002
</code>```

But the issue is there are can be more than 1 pods running on one k8s worker and even more than 1 spark-submit jobs in one pod. So before launching a pod, we need to dynamically select few available ports in the k8s node and create a service to do the port mapping and then during launching the pod, pass those ports into the pod to tell spark-submit to use them. I feel like this is a little bit complex.

Using hostNetwork: true could potentially solve this issue but it introduces lots of other issues in our infra so this is not an option.

If spark-submit can support bindPort concept just like driver.bindAddress and driver.host or support proxy, it will be cleaner to solve the issue.

Does someone have similar situation? Please share some insights.

Thanks.

Additional context:
spark version: 2.4

答:
Spark submit can take additional args like, --conf spark.driver.bindAddress, --conf spark.driver.host, --conf spark.driver.port, --conf spark.driver.blockManager.port, --conf spark.port.maxRetries. The spark.driver.host and driver.port is used to tell Spark Executor to use this host and port to connect back to the Spark submit.

We use hostPort and containerPort to expose the ports inside the container, inject the port range and hostIP as the environment variables to the Pod so that spark-submit knows what to use. So those additional args are:

```<code>--conf spark.driver.bindAddress=0.0.0.0` # has to be `0.0.0.0` so that it is accessible outside pod
--conf spark.driver.host=$HOST_IP # k8s worker ip, can be easily injected to the pod
--conf spark.driver.port=$SPARK_DRIVER_PORT # defined as environment variable
--conf spark.driver.blockManager.port=$SPARK_DRIVER_PORT # defined as environment variable
--conf spark.port.maxRetries=$SPARK_PORT_MAX_RETRIES # defined as environment variable
</code>```

The hostPort is local to the Kubernetes worker, which means we don’t need to worry about the run out of ports. The k8s scheduler can find a host to run the pod.

We can reserve the ports from 40000 to 49000 on each host, and open 8 ports for each pod (as each spark-submit requires 2 open ports). The ports are chosen based on the pod_id. Since Kubernetes recommends running less than 100 pods per node, the ports collision will be very rare.

Body:
I am trying to use spark-submit with client mode in the kubernetes pod to submit jobs to EMR (Due to some other infra issues, we don't allow cluster mode).
By default, spark-submit uses the hostname of the pod as the spark.driver.host and the hostname is the pod's hostname so spark executor could not resolve it. And the spark.driver.port is also locally to the pod (container).

I know a way to pass some confs to spark-submit so that the spark executor can talk to the driver, those configs are:

--conf spark.driver.bindAddress=0.0.0.0 --conf spark.driver.host=$HOST_IP_OF_K8S_WORKER --conf spark.driver.port=32000 --conf spark.driver.blockManager.port=32001

and create a service to in the kubernetes so that spark executor can talk to the driver:

apiVersion: v1
kind: Service
metadata:
  name: spark-block-manager
  namespace: my-app
spec:
  selector:
    app: my-app
  type: NodePort
  ports:
    - name: port-0
      nodePort: 32000
      port: 32000
      protocol: TCP
      targetPort: 32000
    - name: port-1
      nodePort: 32001
      port: 32001
      protocol: TCP
      targetPort: 32001
    - name: port-2
      nodePort: 32002
      port: 32002
      protocol: TCP
      targetPort: 32002

But the issue is there are can be more than 1 pods running on one k8s worker and even more than 1 spark-submit jobs in one pod. So before launching a pod, we need to dynamically select few available ports in the k8s node and create a service to do the port mapping and then during launching the pod, pass those ports into the pod to tell spark-submit to use them. I feel like this is a little bit complex.

Using hostNetwork: true could potentially solve this issue but it introduces lots of other issues in our infra so this is not an option.

If spark-submit can support bindPort concept just like driver.bindAddress and driver.host or support proxy, it will be cleaner to solve the issue.

Does someone have similar situation? Please share some insights.

Thanks.

Additional context:
spark version: 2.4

Body:
Spark submit can take additional args like, --conf spark.driver.bindAddress, --conf spark.driver.host, --conf spark.driver.port, --conf spark.driver.blockManager.port, --conf spark.port.maxRetries. The spark.driver.host and driver.port is used to tell Spark Executor to use this host and port to connect back to the Spark submit.

We use hostPort and containerPort to expose the ports inside the container, inject the port range and hostIP as the environment variables to the Pod so that spark-submit knows what to use. So those additional args are:

--conf spark.driver.bindAddress=0.0.0.0` # has to be `0.0.0.0` so that it is accessible outside pod
--conf spark.driver.host=$HOST_IP # k8s worker ip, can be easily injected to the pod
--conf spark.driver.port=$SPARK_DRIVER_PORT # defined as environment variable
--conf spark.driver.blockManager.port=$SPARK_DRIVER_PORT # defined as environment variable
--conf spark.port.maxRetries=$SPARK_PORT_MAX_RETRIES # defined as environment variable

The hostPort is local to the Kubernetes worker, which means we don’t need to worry about the run out of ports. The k8s scheduler can find a host to run the pod.

We can reserve the ports from 40000 to 49000 on each host, and open 8 ports for each pod (as each spark-submit requires 2 open ports). The ports are chosen based on the pod_id. Since Kubernetes recommends running less than 100 pods per node, the ports collision will be very rare.


问:
How do I customize the default user registration page in Drupal 7
The default user registration page in Drupal 7 has fields to enter a username, password and an email address.

I have added some extra fields that show up in this form, but I would like to change the way it is displayed.

For example, I would like to change the order of the form items and add CSS.

Importantly, I would like to change the label that is displayed for Username - I would like it to say "Nickname" instead.

How can I do this?

答:
I had a similar task a few days ago and did it with the help of this post.

You do need to have  a custom theme set-up for this but that is quite easy to do there are lots of examples for this.

On a sidenote, consider posting drupal questions to http://drupal.stackexchange.com, you would probably get more answers.

Good-luck!

ContentLicense: CC BY-SA 3.0


问:
Make Fail when installing uuid pecl extension on OSX
So not to familiar with installing extensions by here is my process and the moment of fail.

```<code>$ sudo pecl install uuid
</code>```

then all is good until...

```<code>creating libtool
appending configuration tag "CXX" to libtool
configure: creating ./config.status
config.status: creating config.h
running: make
/bin/sh /private/var/tmp/pear-build-root/uuid-1.0.2/libtool --mode=compile cc  -I. -I/private/var/tmp/apache_mod_php/apache_mod_php-53~1/Build/tmp/pear/temp/uuid -DPHP_ATOM_INC -I/private/var/tmp/pear-build-root/uuid-1.0.2/include -I/private/var/tmp/pear-build-root/uuid-1.0.2/main -I/private/var/tmp/apache_mod_php/apache_mod_php-53~1/Build/tmp/pear/temp/uuid -I/usr/include/php -I/usr/include/php/main -I/usr/include/php/TSRM -I/usr/include/php/Zend -I/usr/include/php/ext -I/usr/include/php/ext/date/lib -I/include  -DHAVE_CONFIG_H  -g -O2   -c /private/var/tmp/apache_mod_php/apache_mod_php-53~1/Build/tmp/pear/temp/uuid/uuid.c -o uuid.lo
mkdir .libs
 cc -I. "-I/private/var/tmp/apache_mod_php/apache_mod_php-53~1/Build/tmp/pear/temp/uuid" -DPHP_ATOM_INC -I/private/var/tmp/pear-build-root/uuid-1.0.2/include -I/private/var/tmp/pear-build-root/uuid-1.0.2/main "-I/private/var/tmp/apache_mod_php/apache_mod_php-53~1/Build/tmp/pear/temp/uuid" -I/usr/include/php -I/usr/include/php/main -I/usr/include/php/TSRM -I/usr/include/php/Zend -I/usr/include/php/ext -I/usr/include/php/ext/date/lib -I/include -DHAVE_CONFIG_H -g -O2 -c "/private/var/tmp/apache_mod_php/apache_mod_php-53~1/Build/tmp/pear/temp/uuid/uuid.c"  -fno-common -DPIC -o .libs/uuid.o
/private/var/tmp/apache_mod_php/apache_mod_php-53~1/Build/tmp/pear/temp/uuid/uuid.c: In function ‘zm_startup_uuid’:
/private/var/tmp/apache_mod_php/apache_mod_php-53~1/Build/tmp/pear/temp/uuid/uuid.c:89: error: ‘UUID_TYPE_DCE_TIME’ undeclared (first use in this function)
/private/var/tmp/apache_mod_php/apache_mod_php-53~1/Build/tmp/pear/temp/uuid/uuid.c:89: error: (Each undeclared identifier is reported only once
/private/var/tmp/apache_mod_php/apache_mod_php-53~1/Build/tmp/pear/temp/uuid/uuid.c:89: error: for each function it appears in.)
/private/var/tmp/apache_mod_php/apache_mod_php-53~1/Build/tmp/pear/temp/uuid/uuid.c:90: error: ‘UUID_TYPE_DCE_RANDOM’ undeclared (first use in this function)
/private/var/tmp/apache_mod_php/apache_mod_php-53~1/Build/tmp/pear/temp/uuid/uuid.c: In function ‘zif_uuid_create’:
/private/var/tmp/apache_mod_php/apache_mod_php-53~1/Build/tmp/pear/temp/uuid/uuid.c:168: error: ‘UUID_TYPE_DCE_TIME’ undeclared (first use in this function)
/private/var/tmp/apache_mod_php/apache_mod_php-53~1/Build/tmp/pear/temp/uuid/uuid.c:171: error: ‘UUID_TYPE_DCE_RANDOM’ undeclared (first use in this function)
/private/var/tmp/apache_mod_php/apache_mod_php-53~1/Build/tmp/pear/temp/uuid/uuid.c:181: warning: format ‘%d’ expects type ‘int’, but argument 4 has type ‘long int’
make: *** [uuid.lo] Error 1
ERROR: `make' failed
</code>```

答:
You will need an updated version of uuid from util-linux. It is available on Homebrew.

```<code>brew install util-linux
</code>```

But util-linux is a keg-only package and will not be symlinked to /usr/local. Hence you will have to specify the following path when prompted for uuid installation directory

```<code>/usr/local/opt/util-linux
</code>```

For unattended installations, you can use

```<code>printf "/usr/local/opt/util-linux" | pecl install uuid
</code>```

Body:
So not to familiar with installing extensions by here is my process and the moment of fail.

$ sudo pecl install uuid

then all is good until...

creating libtool
appending configuration tag "CXX" to libtool
configure: creating ./config.status
config.status: creating config.h
running: make
/bin/sh /private/var/tmp/pear-build-root/uuid-1.0.2/libtool --mode=compile cc  -I. -I/private/var/tmp/apache_mod_php/apache_mod_php-53~1/Build/tmp/pear/temp/uuid -DPHP_ATOM_INC -I/private/var/tmp/pear-build-root/uuid-1.0.2/include -I/private/var/tmp/pear-build-root/uuid-1.0.2/main -I/private/var/tmp/apache_mod_php/apache_mod_php-53~1/Build/tmp/pear/temp/uuid -I/usr/include/php -I/usr/include/php/main -I/usr/include/php/TSRM -I/usr/include/php/Zend -I/usr/include/php/ext -I/usr/include/php/ext/date/lib -I/include  -DHAVE_CONFIG_H  -g -O2   -c /private/var/tmp/apache_mod_php/apache_mod_php-53~1/Build/tmp/pear/temp/uuid/uuid.c -o uuid.lo
mkdir .libs
 cc -I. "-I/private/var/tmp/apache_mod_php/apache_mod_php-53~1/Build/tmp/pear/temp/uuid" -DPHP_ATOM_INC -I/private/var/tmp/pear-build-root/uuid-1.0.2/include -I/private/var/tmp/pear-build-root/uuid-1.0.2/main "-I/private/var/tmp/apache_mod_php/apache_mod_php-53~1/Build/tmp/pear/temp/uuid" -I/usr/include/php -I/usr/include/php/main -I/usr/include/php/TSRM -I/usr/include/php/Zend -I/usr/include/php/ext -I/usr/include/php/ext/date/lib -I/include -DHAVE_CONFIG_H -g -O2 -c "/private/var/tmp/apache_mod_php/apache_mod_php-53~1/Build/tmp/pear/temp/uuid/uuid.c"  -fno-common -DPIC -o .libs/uuid.o
/private/var/tmp/apache_mod_php/apache_mod_php-53~1/Build/tmp/pear/temp/uuid/uuid.c: In function ‘zm_startup_uuid’:
/private/var/tmp/apache_mod_php/apache_mod_php-53~1/Build/tmp/pear/temp/uuid/uuid.c:89: error: ‘UUID_TYPE_DCE_TIME’ undeclared (first use in this function)
/private/var/tmp/apache_mod_php/apache_mod_php-53~1/Build/tmp/pear/temp/uuid/uuid.c:89: error: (Each undeclared identifier is reported only once
/private/var/tmp/apache_mod_php/apache_mod_php-53~1/Build/tmp/pear/temp/uuid/uuid.c:89: error: for each function it appears in.)
/private/var/tmp/apache_mod_php/apache_mod_php-53~1/Build/tmp/pear/temp/uuid/uuid.c:90: error: ‘UUID_TYPE_DCE_RANDOM’ undeclared (first use in this function)
/private/var/tmp/apache_mod_php/apache_mod_php-53~1/Build/tmp/pear/temp/uuid/uuid.c: In function ‘zif_uuid_create’:
/private/var/tmp/apache_mod_php/apache_mod_php-53~1/Build/tmp/pear/temp/uuid/uuid.c:168: error: ‘UUID_TYPE_DCE_TIME’ undeclared (first use in this function)
/private/var/tmp/apache_mod_php/apache_mod_php-53~1/Build/tmp/pear/temp/uuid/uuid.c:171: error: ‘UUID_TYPE_DCE_RANDOM’ undeclared (first use in this function)
/private/var/tmp/apache_mod_php/apache_mod_php-53~1/Build/tmp/pear/temp/uuid/uuid.c:181: warning: format ‘%d’ expects type ‘int’, but argument 4 has type ‘long int’
make: *** [uuid.lo] Error 1
ERROR: `make' failed

Body:
You will need an updated version of uuid from util-linux. It is available on Homebrew.

brew install util-linux

But util-linux is a keg-only package and will not be symlinked to /usr/local. Hence you will have to specify the following path when prompted for uuid installation directory

/usr/local/opt/util-linux

For unattended installations, you can use

printf "/usr/local/opt/util-linux" | pecl install uuid


问:
Snippets in Avalon Edit
In avalon edit there is a snippet class SnippetReplaceableTextElement and I can't understand how to use it correctly, I wrote something like that and it doesn't work:

```<code>        SnippetReplaceableTextElement snip = new SnippetReplaceableTextElement();
        snip.Text = "Console.WriteLine();";
        InsertionContext context = new InsertionContext(textEditor.TextArea, 0);
        snip.Insert(context);
</code>```

The insertion itself occurs, but the selection doesn't work. How to make the snippet work like in visual studio? Class source: https://github.com/icsharpcode/AvalonEdit/blob/28b887f78c821c7fede1d4fc461bde64f5f21bd1/ICSharpCode.AvalonEdit/Snippets/SnippetReplaceableTextElement.cs

答:
I made something like this: https://github.com/typicalHuman/typicalIDE/tree/master/CodeBox/Completions/CSCompletion/Snippets
It isn't ideal, but suitable for the base.</p>

Title: Snippets in Avalon Edit

Body:
In avalon edit there is a snippet class SnippetReplaceableTextElement and I can't understand how to use it correctly, I wrote something like that and it doesn't work:

        SnippetReplaceableTextElement snip = new SnippetReplaceableTextElement();
        snip.Text = "Console.WriteLine();";
        InsertionContext context = new InsertionContext(textEditor.TextArea, 0);
        snip.Insert(context);

The insertion itself occurs, but the selection doesn't work. How to make the snippet work like in visual studio? Class source: https://github.com/icsharpcode/AvalonEdit/blob/28b887f78c821c7fede1d4fc461bde64f5f21bd1/ICSharpCode.AvalonEdit/Snippets/SnippetReplaceableTextElement.cs


问:
What does the following algorithm approximate? (Assume m>1,ϵ>0)
```<code>x = m;
y = 1;
While (x-y > ϵ)
{
    x = (x+y)/2;
    y = m/x;
}
print(x);
</code>```

Answer is \sqrt{m}

I don't know how to reach that conclusion because i don't know the value of ϵ, I have tried but i result in bunch of equations which doesn't make sense to me.

Please help me to understand how to understand and breakdown this type of questions
Thank you

答:
I would say maybe pick a language, implement your algorithm, then print things out, you would see how the algorithm performs the task step by step:

For instance in Python, your algorithm would probably look like:

```<code>ϵ = 10
m = 30
x = m
y = 1

while x - y > ϵ:
    x = (x + y) // 2
    y = m // x

print(x)
</code>```

If we would print the variables of the algorithm, wherever you want to and step by step, you'd observe how the algorithm works:

```<code>
ϵ = 4
m = 90
x = m
y = 1

step = 0
while x - y > ϵ:
    step += 1
    print(f'-----------------step {step}----------------')
    print(f'x before first operation is {x}')
    print(f'y before first operation is {y}')
    print(f'ϵ before first operation is {ϵ}')
    print(f'x - y before first operation is {x - y}')
    print(f'm before first operation is {m}')
    x = (x + y) // 2

    print(f'x after first operation is {x}')
    print(f'y after first operation is {y}')
    print(f'ϵ after first operation is {ϵ}')
    print(f'x - y after first operation is {x - y}')
    print(f'm after first operation is {m}')

    y = m // x

    print(f'x after second operation is {x}')
    print(f'y after second operation is {y}')
    print(f'ϵ after second operation is {ϵ}')
    print(f'x - y after second operation is {x - y}')
    print(f'm after second operation is {m}')

print(x)

</code>```

Output

```<code>-----------------step 1----------------
x before first operation is 90
y before first operation is 1
ϵ before first operation is 4
x - y before first operation is 89
m before first operation is 90
x after first operation is 45
y after first operation is 1
ϵ after first operation is 4
x - y after first operation is 44
m after first operation is 90
x after second operation is 45
y after second operation is 2
ϵ after second operation is 4
x - y after second operation is 43
m after second operation is 90
-----------------step 2----------------
x before first operation is 45
y before first operation is 2
ϵ before first operation is 4
x - y before first operation is 43
m before first operation is 90
x after first operation is 23
y after first operation is 2
ϵ after first operation is 4
x - y after first operation is 21
m after first operation is 90
x after second operation is 23
y after second operation is 3
ϵ after second operation is 4
x - y after second operation is 20
m after second operation is 90
-----------------step 3----------------
x before first operation is 23
y before first operation is 3
ϵ before first operation is 4
x - y before first operation is 20
m before first operation is 90
x after first operation is 13
y after first operation is 3
ϵ after first operation is 4
x - y after first operation is 10
m after first operation is 90
x after second operation is 13
y after second operation is 6
ϵ after second operation is 4
x - y after second operation is 7
m after second operation is 90
-----------------step 4----------------
x before first operation is 13
y before first operation is 6
ϵ before first operation is 4
x - y before first operation is 7
m before first operation is 90
x after first operation is 9
y after first operation is 6
ϵ after first operation is 4
x - y after first operation is 3
m after first operation is 90
x after second operation is 9
y after second operation is 10
ϵ after second operation is 4
x - y after second operation is -1
m after second operation is 90
9

</code>```

This answer also explains it simple.

Body:
x = m;
y = 1;
While (x-y > ϵ)
{
    x = (x+y)/2;
    y = m/x;
}
print(x);

Answer is \sqrt{m}

I don't know how to reach that conclusion because i don't know the value of ϵ, I have tried but i result in bunch of equations which doesn't make sense to me.

Please help me to understand how to understand and breakdown this type of questions
Thank you

Body:
I would say maybe pick a language, implement your algorithm, then print things out, you would see how the algorithm performs the task step by step:

For instance in Python, your algorithm would probably look like:

ϵ = 10
m = 30
x = m
y = 1

while x - y > ϵ:
    x = (x + y) // 2
    y = m // x

print(x)

If we would print the variables of the algorithm, wherever you want to and step by step, you'd observe how the algorithm works:

ϵ = 4
m = 90
x = m
y = 1

step = 0
while x - y > ϵ:
    step += 1
    print(f'-----------------step {step}----------------')
    print(f'x before first operation is {x}')
    print(f'y before first operation is {y}')
    print(f'ϵ before first operation is {ϵ}')
    print(f'x - y before first operation is {x - y}')
    print(f'm before first operation is {m}')
    x = (x + y) // 2

    print(f'x after first operation is {x}')
    print(f'y after first operation is {y}')
    print(f'ϵ after first operation is {ϵ}')
    print(f'x - y after first operation is {x - y}')
    print(f'm after first operation is {m}')

    y = m // x

    print(f'x after second operation is {x}')
    print(f'y after second operation is {y}')
    print(f'ϵ after second operation is {ϵ}')
    print(f'x - y after second operation is {x - y}')
    print(f'm after second operation is {m}')

print(x)

Output

-----------------step 1----------------
x before first operation is 90
y before first operation is 1
ϵ before first operation is 4
x - y before first operation is 89
m before first operation is 90
x after first operation is 45
y after first operation is 1
ϵ after first operation is 4
x - y after first operation is 44
m after first operation is 90
x after second operation is 45
y after second operation is 2
ϵ after second operation is 4
x - y after second operation is 43
m after second operation is 90
-----------------step 2----------------
x before first operation is 45
y before first operation is 2
ϵ before first operation is 4
x - y before first operation is 43
m before first operation is 90
x after first operation is 23
y after first operation is 2
ϵ after first operation is 4
x - y after first operation is 21
m after first operation is 90
x after second operation is 23
y after second operation is 3
ϵ after second operation is 4
x - y after second operation is 20
m after second operation is 90
-----------------step 3----------------
x before first operation is 23
y before first operation is 3
ϵ before first operation is 4
x - y before first operation is 20
m before first operation is 90
x after first operation is 13
y after first operation is 3
ϵ after first operation is 4
x - y after first operation is 10
m after first operation is 90
x after second operation is 13
y after second operation is 6
ϵ after second operation is 4
x - y after second operation is 7
m after second operation is 90
-----------------step 4----------------
x before first operation is 13
y before first operation is 6
ϵ before first operation is 4
x - y before first operation is 7
m before first operation is 90
x after first operation is 9
y after first operation is 6
ϵ after first operation is 4
x - y after first operation is 3
m after first operation is 90
x after second operation is 9
y after second operation is 10
ϵ after second operation is 4
x - y after second operation is -1
m after second operation is 90
9

This answer also explains it simple.


问:
How to link windows forms with treeview in C sharp
I’d like to make a windows form and split it in to two parts vertically.
The left side contains a tree view and the right side is empty at start.
When I click on a node of the tree list, I want the right side to open a form or panel that I already made before. So basically, the tree list nodes is just a way for me to switch through the forms in the same window without opening a new window or leaving the same window.
I already know how to make a treeview and the nodes but I’m not sure about how to make the right sides witch through the forms/panels that I made.</p>

答:
You can make a SplitContainerControl and add a custom UserControl to the right panel at runtime:

```<code>scc.Panel2.Controls.Add(new YourControl(...));
</code>```

You could also add it in the designer and use the Visible property to hide it until later.

Either way, remember to set its Dock to Fill.

Body:
You can make a SplitContainerControl and add a custom UserControl to the right panel at runtime:

scc.Panel2.Controls.Add(new YourControl(...));

You could also add it in the designer and use the Visible property to hide it until later.

Either way, remember to set its Dock to Fill.


问:
Which TypeScript/JavaScript unit test framework that has an API most similar to JUnit?
I'm looking to port a significant number of tests written in JUnit to test TypeScript code on Node.js.   I know that annotations are an experimental feature in TypeScript/JavaScript, but ideally, it would use the same @Before, @Test, and @After source annotations that JUnit does.

Output in the same JUnit XML format would be plus as well.

答:
I know that I might be kind of late with my answer, but you might want to checkout TestyTs

It supports annotations similar to JUnit:

```<code>@TestSuite()
export class MyTestSuite {

    @BeforeEach()
    beforeEach() {
        // Do something
    }

    @Test()
    onePlusOne() {
        const result = 1 + 1;
        expect.toBeEqual(result, 2);
    }

    @AfterEach()
    afterEach() {
        // Do something
    }
}
</code>```

Try it on REPL

Body:
I know that I might be kind of late with my answer, but you might want to checkout TestyTs

It supports annotations similar to JUnit:

@TestSuite()
export class MyTestSuite {

    @BeforeEach()
    beforeEach() {
        // Do something
    }

    @Test()
    onePlusOne() {
        const result = 1 + 1;
        expect.toBeEqual(result, 2);
    }

    @AfterEach()
    afterEach() {
        // Do something
    }
}

Try it on REPL


问:
How to convert values in list of strings into Pandas DataFrame
I would like to convert this list of strings into a Pandas DataFrame with columns ‘Open’, ‘High’, ‘Low’, ‘Close’, ‘PeriodVolume’, OpenInterest’ and ‘Datetime’ as index. How can I extract the values and create the DataFrame? Thanks for your help!</p>

```<code>['RequestId: , Datetime: 5/28/2020 12:00:00 AM, High: 323.44, Low: 315.63, Open: 316.77, Close: 318.25, PeriodVolume: 33449103, OpenInterest: 0',

 'RequestId: , Datetime: 5/27/2020 12:00:00 AM, High: 318.71, Low: 313.09, Open: 316.14, Close: 318.11, PeriodVolume: 28236274, OpenInterest: 0',

 'RequestId: , Datetime: 5/26/2020 12:00:00 AM, High: 324.24, Low: 316.5, Open: 323.5, Close: 316.73, PeriodVolume: 31380454, OpenInterest: 0',

 'RequestId: , Datetime: 5/22/2020 12:00:00 AM, High: 319.23, Low: 315.35, Open: 315.77, Close: 318.89, PeriodVolume: 20450754, OpenInterest: 0']
</code>```

答:
You can use split() and some for loops put your data into a dictionary and then pass the dictionary to a dataframe.</p>

```<code>import pandas as pd

# First create the list containing your entries.
entries = [
    'RequestId: , Datetime: 5/28/2020 12:00:00 AM, High: 323.44, Low: 315.63,' \
    ' Open: 316.77, Close: 318.25, PeriodVolume: 33449103, OpenInterest: 0',
    'RequestId: , Datetime: 5/27/2020 12:00:00 AM, High: 318.71, Low: 313.09,' \
    ' Open: 316.14, Close: 318.11, PeriodVolume: 28236274, OpenInterest: 0',
    'RequestId: , Datetime: 5/26/2020 12:00:00 AM, High: 324.24, Low: 316.5,' \
    ' Open: 323.5, Close: 316.73, PeriodVolume: 31380454, OpenInterest: 0',
    'RequestId: , Datetime: 5/22/2020 12:00:00 AM, High: 319.23, Low: 315.35,' \
    ' Open: 315.77, Close: 318.89, PeriodVolume: 20450754, OpenInterest: 0'
]

# Next create a dictionary in which we will store the data after processing.
data = {
    'Datetime': [], 'Open': [], 'High': [], 'Low': [],
    'Close': [], 'PeriodVolume': [], 'OpenInterest': []
}
# Now split your entries by ','
split_entries = [entry.split(',') for entry in entries]

# Loop over the list
for entry in split_entries:
    # and loop over each of the inner lists
    for ent in entry:
        # Split by ': ' to get the 'key'
        # I have added the [1:] as there is a space before each
        # column name which needs to be cut out for this to work.
        key = ent.split(': ')[0][1:]

        # Now we check if the key is in the keys of the dictionary
        # we created earlier and append the value to the list
        # associated with that key if so.
        if key in data.keys():
            data[key].append(ent.split(': ')[1])

# Now we can pass the data into panda's DataFrame class
dataframe = pd.DataFrame(data)

# Then call one more method to set the index
dataframe = dataframe.set_index('Datetime')
</code>```

Body:
I would like to convert this list of strings into a Pandas DataFrame with columns ‘Open’, ‘High’, ‘Low’, ‘Close’, ‘PeriodVolume’, OpenInterest’ and ‘Datetime’ as index. How can I extract the values and create the DataFrame? Thanks for your help!

['RequestId: , Datetime: 5/28/2020 12:00:00 AM, High: 323.44, Low: 315.63, Open: 316.77, Close: 318.25, PeriodVolume: 33449103, OpenInterest: 0',

 'RequestId: , Datetime: 5/27/2020 12:00:00 AM, High: 318.71, Low: 313.09, Open: 316.14, Close: 318.11, PeriodVolume: 28236274, OpenInterest: 0',

 'RequestId: , Datetime: 5/26/2020 12:00:00 AM, High: 324.24, Low: 316.5, Open: 323.5, Close: 316.73, PeriodVolume: 31380454, OpenInterest: 0',

 'RequestId: , Datetime: 5/22/2020 12:00:00 AM, High: 319.23, Low: 315.35, Open: 315.77, Close: 318.89, PeriodVolume: 20450754, OpenInterest: 0']

Body:
You can use split() and some for loops put your data into a dictionary and then pass the dictionary to a dataframe.

import pandas as pd

# First create the list containing your entries.
entries = [
    'RequestId: , Datetime: 5/28/2020 12:00:00 AM, High: 323.44, Low: 315.63,' \
    ' Open: 316.77, Close: 318.25, PeriodVolume: 33449103, OpenInterest: 0',
    'RequestId: , Datetime: 5/27/2020 12:00:00 AM, High: 318.71, Low: 313.09,' \
    ' Open: 316.14, Close: 318.11, PeriodVolume: 28236274, OpenInterest: 0',
    'RequestId: , Datetime: 5/26/2020 12:00:00 AM, High: 324.24, Low: 316.5,' \
    ' Open: 323.5, Close: 316.73, PeriodVolume: 31380454, OpenInterest: 0',
    'RequestId: , Datetime: 5/22/2020 12:00:00 AM, High: 319.23, Low: 315.35,' \
    ' Open: 315.77, Close: 318.89, PeriodVolume: 20450754, OpenInterest: 0'
]

# Next create a dictionary in which we will store the data after processing.
data = {
    'Datetime': [], 'Open': [], 'High': [], 'Low': [],
    'Close': [], 'PeriodVolume': [], 'OpenInterest': []
}
# Now split your entries by ','
split_entries = [entry.split(',') for entry in entries]

# Loop over the list
for entry in split_entries:
    # and loop over each of the inner lists
    for ent in entry:
        # Split by ': ' to get the 'key'
        # I have added the [1:] as there is a space before each
        # column name which needs to be cut out for this to work.
        key = ent.split(': ')[0][1:]

        # Now we check if the key is in the keys of the dictionary
        # we created earlier and append the value to the list
        # associated with that key if so.
        if key in data.keys():
            data[key].append(ent.split(': ')[1])

# Now we can pass the data into panda's DataFrame class
dataframe = pd.DataFrame(data)

# Then call one more method to set the index
dataframe = dataframe.set_index('Datetime')


问:
Failing to install elasticsearch-kopf plugin
I was trying to install kopf 2.1.2 to monitor Elasticsearch 7.7.0. in a Ubuntu 20.10 VM

First I downloaded the Zip file from github and placed it in the Downloads folder. Then I typed:

```<code>$ sudo ./elasticsearch-plugin install /home/user/Downloads/elasticsearch-kopf-2.1.2.zip
</code>```

However I got the following output:

```<code>-> Installing /home/user/Downloads/elasticsearch-kopf-2.1.2.zip
-> Failed installing /home/user/Downloads/elasticsearch-kopf-2.1.2.zip
-> Rolling back /home/user/Downloads/elasticsearch-kopf-2.1.2.zip
-> Rolled back /home/user/Downloads/elasticsearch-kopf-2.1.2.zip
A tool for managing installed elasticsearch plugins
</code>```

But no further information is provided.

Any idea what the issue might be?

答:
That plugin is no longer maintained and ES will not allow to install it after version 2.x because site plugin support has been removed in ES 5.0.

As a result, that plugin author created a new plugin called cerebro that you can use with any version of ES because it runs outside of ES and connects via the REST interface.

Go ahead and try it out.

Body:
I was trying to install kopf 2.1.2 to monitor Elasticsearch 7.7.0. in a Ubuntu 20.10 VM

First I downloaded the Zip file from github and placed it in the Downloads folder. Then I typed:

$ sudo ./elasticsearch-plugin install /home/user/Downloads/elasticsearch-kopf-2.1.2.zip

However I got the following output:

-> Installing /home/user/Downloads/elasticsearch-kopf-2.1.2.zip
-> Failed installing /home/user/Downloads/elasticsearch-kopf-2.1.2.zip
-> Rolling back /home/user/Downloads/elasticsearch-kopf-2.1.2.zip
-> Rolled back /home/user/Downloads/elasticsearch-kopf-2.1.2.zip
A tool for managing installed elasticsearch plugins

But no further information is provided.

Any idea what the issue might be?


问:
VSCode jumpiness when editing markdown and preview pane is open
This problem comes and goes, but it's been getting unbearable as times goes on.

The environment:

I am using the latest version of VSCode (1.45.1) on a mac running OSX 10.15.4. with a minimal set of extensions (I have disabled everything I can), namely:

Markdown All in One 2.8.0

Markdown Preview Mermaid

Markdownlint 0.35.1

The problem:

When I am editing a Markdown document with preview alongside it, the text window jumps with the cursor location moving up the window to the point of disappearing at the top.

I am not sure exactly what triggers this behavior, but I suspect it has to do with using any sort of graphic rendering, be it MathJax, Mermaid, or a simple figure.

Online searches show similar behavior reported, and supposedly corrected, several years ago. But nothing recent which surprises me as it is maddening.

The question

Anyone has seen this behavior?

Any idea what could be triggering it?

Update:

After more than a week trying to fix this, a couple hours after posting this question (and with no changes that I can think of on my part, it seems to have fixed itself). I am just waiting for the problem to come back. This is infuriating.

Of course, a mere few hours afterwards the same problem came back. It seems to be some specific property of the markdown file as two different computers with different screen and window sizes started and stopped behaving exactly the same way with the same files.

At the suggestion of @user8682688, who found the settings for the scroll synchronization in VSCode, I turned off synchronization from the preview window back into the editor ("markdown.preview.scrollEditorWithPreview": false) this at least removed the jumping from the the editor window making it usable again, but the preview window is still jumping all over the place which is the actual bug. Of course, I could disable the updating altogether with markdown.preview.scrollPreviewWithEditor, but that's just a work-around that removes useful functionality.

答:
VSCode automatically synchronizes the Markdown editor and the preview panes. Have you tried to disable the markdown.preview.scrollPreviewWithEditor and markdown.preview.scrollEditorWithPreview settings?

ref: https://code.visualstudio.com/docs/languages/markdown#_editor-and-preview-synchronization


问:
CSS Printing: Avoiding cut-in-half DIVs between pages?
I'm writing a plug-in for a piece of software that takes a big collection of items and pops them into HTML in a WebView in Cocoa (which uses WebKit as its renderer, so basically you can assume this HTML file is being opened in Safari).

The DIVs it makes are of dynamic height, but they don't vary too much. They're usually around 200px. Anyway, with around six-hundred of these items per document, I'm having a really rough time getting it to print. Unless I get lucky, there's an entry chopped in half at the bottom and top of every page, and that makes actually using printouts very difficult.

I've tried page-break-before, page-break-after, page-break-inside, and combinations of the three to no avail. I think it might be WebKit not properly rendering the instructions, or maybe it's my lack of understanding of how to use them. At any rate, I need help. How can I prevent the cutting-in-half of my DIVs when printing?

答:
page-break-inside: avoid;  definitely does not work in webkit, in fact has been a known issue for 5+ years now https://bugs.webkit.org/show_bug.cgi?id=5097

As far as my research has gone, there is no known method to accomplish this (I am working on figuring out my own hack)

The advice I can give you is, to accomplish this functionality in FF, wrap the content that you don;t want to break ever inside a DIV (or any container) with overflow: auto  (just be careful not to cause weird scroll bars to show up by sizing the container too small).

Sadly, FF is the only browser I managed to accomplish this in, and webkit is the one I am more worried about.

ContentLicense: CC BY-SA 2.5


问:
How to determine payload size from header?
I want to send() body and header which has body size from the Side A.
On the Side B, in the first recv() header to determine the size of payload. The second, recv() body.

I tried to use recv() twice but could not through the second recv() function.

Side A

```<code>struct CommandHeader_t {
    int BodySizeByte;
};

void Send()
{
    const int BODY_SIZE_BYTE = 10;
    CommandHeader_t* header_ptr = (CommandHeader_t*) malloc(sizeof(CommandHeader_t) + BODY_SIZE_BYTE);
    header_ptr->BodySizeByte = BODY_SIZE_BYTE;

    char* body_ptr = (char*) (header_ptr + sizeof(CommandHeader_t));
    snprintf(body_ptr, BODY_SIZE_BYTE, "Hello World");

    int sock = socket(AF_LOCAL, SOCK_DGRAM, 0);
    struct sockaddr_un addr = {0};
    addr.sun_family = AF_LOCAL;
    strcpy(addr.sun_path, SENDING_SOCKET);
    sendto(sock, header_ptr, sizeof(CommandHeader_t) + BODY_SIZE_BYTE, 0, (const struct sockaddr*)&addr, sizeof(addr));
    close(sock);
}
</code>```

Side B

```<code>void Reveice()
{
    // something
    CommandHeader_t header;
    char* body_ptr;
    recv(sockfd, &header, sizeof(CommandHeader_t), 0);
    body_ptr = (char*) malloc(header.BodySizeByte);
    recv(sockfd, body_ptr, header.BodySizeByte, 0); // CANNOT recv anything
}
</code>```

答:
There are some mistakes in your code:

On the sending side, you are not doing pointer arithmetic correctly when assigning the body_ptr pointer.  As header_ptr is declared as CommandHeader_t*, doing (header_ptr + sizeof(CommandHeader_t)) will calculate a memory address that is sizeof(CommandHeader_t) number of CommandHeader_t elements past the address that header_ptr is pointing at.  That is not what you want.  You need to instead calculate an address that is sizeof(CommandHeader_t) number of chars past the header_ptr address.

So, you need to change this:

```<code>char* body_ptr = (char*) (header_ptr + sizeof(CommandHeader_t));
</code>```

To this instead:

```<code>char* body_ptr = ((char*) header_ptr) + sizeof(CommandHeader_t);
</code>```

A simpler way to handle this is to add a char[1] member to CommandHeader_t, and then subtract 1 when malloc()'ing it, eg:

```<code>#pragma pack(push, 1) // or equivalent
struct CommandHeader_t {
    int BodySizeByte;
    char data[1];
};
#pragma pack(pop) // or equivalent

CommandHeader_t* header_ptr = (CommandHeader_t*) malloc(offsetof(CommandHeader_t, data) + BODY_SIZE_BYTE);
header_ptr->BodySizeByte = BODY_SIZE_BYTE;

char* body_ptr = header_ptr->data;
snprintf(body_ptr, BODY_SIZE_BYTE, "Hello World");
</code>```

Also, since you are using SOCK_DGRAM on the sending side, the sendto() is message-oriented, sending the entire data in 1 message.  But your receiving code is written as if it were using a stream-oriented socket instead.  Don't mismatch socket types like that.  If you want to call recv() multiple times, use a stream-oriented socket on both sides.  Otherwise, use a message-oriented socket on both sides, and then have the receiver allocate a buffer large enough to receive an entire message in 1 recvfrom() (you can use ioctl(FIONREAD) to determine the size of the next pending message), and then parse the contents of that message as needed.

Also, your receiver is leaking the body_ptr buffer it allocated with malloc().

Body:
I want to send() body and header which has body size from the Side A.
On the Side B, in the first recv() header to determine the size of payload. The second, recv() body.

I tried to use recv() twice but could not through the second recv() function.

Side A

struct CommandHeader_t {
    int BodySizeByte;
};

void Send()
{
    const int BODY_SIZE_BYTE = 10;
    CommandHeader_t* header_ptr = (CommandHeader_t*) malloc(sizeof(CommandHeader_t) + BODY_SIZE_BYTE);
    header_ptr->BodySizeByte = BODY_SIZE_BYTE;

    char* body_ptr = (char*) (header_ptr + sizeof(CommandHeader_t));
    snprintf(body_ptr, BODY_SIZE_BYTE, "Hello World");

    int sock = socket(AF_LOCAL, SOCK_DGRAM, 0);
    struct sockaddr_un addr = {0};
    addr.sun_family = AF_LOCAL;
    strcpy(addr.sun_path, SENDING_SOCKET);
    sendto(sock, header_ptr, sizeof(CommandHeader_t) + BODY_SIZE_BYTE, 0, (const struct sockaddr*)&addr, sizeof(addr));
    close(sock);
}

Side B

void Reveice()
{
    // something
    CommandHeader_t header;
    char* body_ptr;
    recv(sockfd, &header, sizeof(CommandHeader_t), 0);
    body_ptr = (char*) malloc(header.BodySizeByte);
    recv(sockfd, body_ptr, header.BodySizeByte, 0); // CANNOT recv anything
}

Body:
There are some mistakes in your code:

On the sending side, you are not doing pointer arithmetic correctly when assigning the body_ptr pointer.  As header_ptr is declared as CommandHeader_t*, doing (header_ptr + sizeof(CommandHeader_t)) will calculate a memory address that is sizeof(CommandHeader_t) number of CommandHeader_t elements past the address that header_ptr is pointing at.  That is not what you want.  You need to instead calculate an address that is sizeof(CommandHeader_t) number of chars past the header_ptr address.

So, you need to change this:

char* body_ptr = (char*) (header_ptr + sizeof(CommandHeader_t));

To this instead:

char* body_ptr = ((char*) header_ptr) + sizeof(CommandHeader_t);

A simpler way to handle this is to add a char[1] member to CommandHeader_t, and then subtract 1 when malloc()'ing it, eg:

#pragma pack(push, 1) // or equivalent
struct CommandHeader_t {
    int BodySizeByte;
    char data[1];
};
#pragma pack(pop) // or equivalent

CommandHeader_t* header_ptr = (CommandHeader_t*) malloc(offsetof(CommandHeader_t, data) + BODY_SIZE_BYTE);
header_ptr->BodySizeByte = BODY_SIZE_BYTE;

char* body_ptr = header_ptr->data;
snprintf(body_ptr, BODY_SIZE_BYTE, "Hello World");

Also, since you are using SOCK_DGRAM on the sending side, the sendto() is message-oriented, sending the entire data in 1 message.  But your receiving code is written as if it were using a stream-oriented socket instead.  Don't mismatch socket types like that.  If you want to call recv() multiple times, use a stream-oriented socket on both sides.  Otherwise, use a message-oriented socket on both sides, and then have the receiver allocate a buffer large enough to receive an entire message in 1 recvfrom() (you can use ioctl(FIONREAD) to determine the size of the next pending message), and then parse the contents of that message as needed.

Also, your receiver is leaking the body_ptr buffer it allocated with malloc().


问:
NCRONTAB for every first tuesday of every month for an Azure Function
How could I create an timer trigger with Azure Functions (version 3 and .NET Core) that must be executed every first Tuesday from every month at 8 AM. Starting from now (05/08/2020) this must be the next five occurrences:

2020/06/02 Tue 08:00:00

2020/07/07 Tue 08:00:00

2020/08/04 Tue 08:00:00

2020/09/01 Tue 08:00:00

2020/10/06 Tue 08:00:00

By using www.cronmaker.com, I've next NCRONTAB:

0 0 8 ? 1/1 TUE#1 *
```

But then I've next exception:

The schedule expression 0 0 8 ? 1/1 Tue#1 * was not recognized as a valid CRON expression or TimeSpan string.

Then I've start changing the CRON expression to next varations:

CORN
Result

0 0 8 ? 1/1 Tue#1
Error from above

0 0 8 * 1/1 Tue#1
Error from above

0 0 8 1/1 Tue#1 *
Error from above

0 0 8 * 1/1 Tue 1
Error from above

0 0 8 ? 1/1 Tue 1
Error from above

0 0 8 * 1/1 Tue/1
2020/05/29 08:00:00 - 2020/05/30 08:00:00

0 0 8 * * Tue/2
2020/05/30 08:00:00 - 2020/06/02 08:00:00

0 0 8 * 1/1 Tue/2
2020/05/30 08:00:00 - 2020/06/02 08:00:00

0 0 8 ? 1/1 Tue/2
Error from above

So every expression I've made, would not work as expected. My question is now: What's the correct expression?

答:
The first Monday of the month falls on one (and only one) of the dates from the first to the 7th inclusive. Then the cron expression will be easy to get it.

Suppose it should be 0 0 8 1-7 * Tue and the below is my test, it shows the first five dates.

Body:
How could I create an timer trigger with Azure Functions (version 3 and .NET Core) that must be executed every first Tuesday from every month at 8 AM. Starting from now (05/08/2020) this must be the next five occurrences:

2020/06/02 Tue 08:00:00

2020/07/07 Tue 08:00:00

2020/08/04 Tue 08:00:00

2020/09/01 Tue 08:00:00

2020/10/06 Tue 08:00:00

By using www.cronmaker.com, I've next NCRONTAB:

0 0 8 ? 1/1 TUE#1 *

But then I've next exception:

The schedule expression 0 0 8 ? 1/1 Tue#1 * was not recognized as a valid CRON expression or TimeSpan string.

Then I've start changing the CRON expression to next varations:

CORN
Result

0 0 8 ? 1/1 Tue#1
Error from above

0 0 8 * 1/1 Tue#1
Error from above

0 0 8 1/1 Tue#1 *
Error from above

0 0 8 * 1/1 Tue 1
Error from above

0 0 8 ? 1/1 Tue 1
Error from above

0 0 8 * 1/1 Tue/1
2020/05/29 08:00:00 - 2020/05/30 08:00:00

0 0 8 * * Tue/2
2020/05/30 08:00:00 - 2020/06/02 08:00:00

0 0 8 * 1/1 Tue/2
2020/05/30 08:00:00 - 2020/06/02 08:00:00

0 0 8 ? 1/1 Tue/2
Error from above

So every expression I've made, would not work as expected. My question is now: What's the correct expression?


问:
How to list all possible combinations of taking 5 out of N objects in Excel?
The title may not perfectly describe what my intention here is. Let's suppose I have 14 objects in total and I want to pick 5 of them. Using a calculator, we can see that there are 2002 possibilities. Now if I have 17 objects and I want to pick 5 again, now there are 6188 possibilities. The problem is that online calculators don't list them.

My intention is to make Excel list the possible combinations of taking 5 objects out of N, being N a number that I would put in, for example, cell A1 (although it will always be a number between 6 and 18). Is there a way to do this?

答:
Place the 14 items in A1 through A14 then run:

```<code>Sub Kombos()
    Dim amount As Long
    amount = 14

    ZZ = 1
    For i = 1 To amount - 4
        For j = i + 1 To amount - 3
            For k = j + 1 To amount - 2
                For L = k + 1 To amount - 1
                    For m = L + 1 To amount
                        Cells(ZZ, 2) = Cells(i, 1) & Cells(j, 1) & Cells(k, 1) & Cells(L, 1) & Cells(m, 1)
                        ZZ = ZZ + 1
                    Next m
                Next L
            Next k
        Next j
    Next i

End Sub
</code>```

Body:
Place the 14 items in A1 through A14 then run:

Sub Kombos()
    Dim amount As Long
    amount = 14

    ZZ = 1
    For i = 1 To amount - 4
        For j = i + 1 To amount - 3
            For k = j + 1 To amount - 2
                For L = k + 1 To amount - 1
                    For m = L + 1 To amount
                        Cells(ZZ, 2) = Cells(i, 1) & Cells(j, 1) & Cells(k, 1) & Cells(L, 1) & Cells(m, 1)
                        ZZ = ZZ + 1
                    Next m
                Next L
            Next k
        Next j
    Next i

End Sub


问:
Removing non latin characters from a string in Python3
I'm passing a string to PIL's multiline_text() which, for some reason, doesn't support utf-8 but only Latin characters.

```<code>from PIL import Image, ImageDraw

input_string = "‘Hi’"

img_width = 500
img_height = 500
img = Image.new('RGB', (img_width, img_height), (255, 255, 255))
img_D = ImageDraw.Draw(img)
img_D.multiline_text((0, 0), input_string)    # <- bug here
img.save("test_img.jpeg", 'jpeg', optimize=True, quality = 200)
</code>```

I get this error message: UnicodeEncodeError: 'latin-1' codec can't encode character '\u2018' in position 0: ordinal not in range(256)

So I need to get rid of all non-Latin characters. How can I do that?

Note: I've seen this answer, namely input_string = regex.sub(ur'[^\p{Latin}]', u'', t1) but I'm pretty sure it's for Python2, I get the following error: SyntaxError: invalid syntax. If I remove either the u or the r or both, I get error: bad escape \p.

答:
Found a partial way:

```<code>input_string = "‘Hi’"

input_string = input_string.encode("latin", "ignore")
# you can also try "replace" but in the case of ‘ and ’ it doesn't work as it outputs b'?Hi?'

print(input_string)
# b'Hi' is a bytes object, to turn it back into a string, do:

input_string = input_string.decode("utf-8", "ignore")
# same thing, you can also try "replace", but it might lose you some characters

print(input_string)
# Hi
</code>```

However, on longer strings, it also strips accented characters (éèàù) so it's not perfect...

Body:
I'm passing a string to PIL's multiline_text() which, for some reason, doesn't support utf-8 but only Latin characters.

from PIL import Image, ImageDraw

input_string = "‘Hi’"

img_width = 500
img_height = 500
img = Image.new('RGB', (img_width, img_height), (255, 255, 255))
img_D = ImageDraw.Draw(img)
img_D.multiline_text((0, 0), input_string)    # <- bug here
img.save("test_img.jpeg", 'jpeg', optimize=True, quality = 200)

I get this error message: UnicodeEncodeError: 'latin-1' codec can't encode character '\u2018' in position 0: ordinal not in range(256)

So I need to get rid of all non-Latin characters. How can I do that?

Note: I've seen this answer, namely input_string = regex.sub(ur'[^\p{Latin}]', u'', t1) but I'm pretty sure it's for Python2, I get the following error: SyntaxError: invalid syntax. If I remove either the u or the r or both, I get error: bad escape \p.

Body:
Found a partial way:

input_string = "‘Hi’"

input_string = input_string.encode("latin", "ignore")
# you can also try "replace" but in the case of ‘ and ’ it doesn't work as it outputs b'?Hi?'

print(input_string)
# b'Hi' is a bytes object, to turn it back into a string, do:

input_string = input_string.decode("utf-8", "ignore")
# same thing, you can also try "replace", but it might lose you some characters

print(input_string)
# Hi

However, on longer strings, it also strips accented characters (éèàù) so it's not perfect...


问:
Translate ">" in XML RDF Triple
I have JSON String value > which is a special character in XML.

After the data ingestion, the XML String becomes \u003e.

How can I preserve > in the XML String?

答:
You can use the XML escaped characters

```<code>"   "
'   '
<   <
>   >
&   &
</code>```

This post might help you with more info What characters do I need to escape in XML documents?

Title: Translate ">" in XML RDF Triple

Body:
You can use the XML escaped characters

"   &quot;
'   &apos;
<   &lt;
>   &gt;
&   &amp;

This post might help you with more info What characters do I need to escape in XML documents?


问:
MySQL Interview Questions
I've been asked to screen some candidates for a MySQL DBA / Developer position for a role that requires an enterprise level skill set.

I myself am a SQL Server person so I know what I would be looking for from that point of view with regards to scalability / design etc but is there anything specific I should be asking with regards to MySQL?

I would ideally like to ask them about enterprise level features of MySQL that they would typically only use when working on a big database. Need to separate out the enterprise developers from the home / small website kind of guys.

Thanks.

答:
I think it would depend on the database type: transactional or data warehouse?

Anyhow, for all types I'd ask about specific to MySQL replication and clustering, performance tuning and monitorization concepts.

OwnerDisplayName: Campbell

Title: MySQL Interview Questions

OwnerDisplayName: Vinko Vrsalovic


问:
C++ Localization best practices?
We are localizing a cross-platform C++-based client-side application. The first localization pass was done in a big rush for a big partner on a short deadline, and now it's time to refactor it.

We currently have an XML strings file per locale, with a common key and a localized value for each resource. However, sending our not-necessarily-technical localizers an xml file isn't ideal -- they don't know about encoding special characters, etc etc.  I'd like to use an easy, well-known format like Excel/csv with the localizers (also nice because we have server-side localization as well, which could be in a different tab of the same file), and then code-gen the strings files from there.  It seems that Excel doesn't like to output UTF-8 CSV files, which is annoying, and is preventing me from throwing together a few quick scripts to automate the Excel --> strings file conversion.

This problem has been solved hundreds of times.  What workflows have people found best, especially for cases where the localizers will be external to the company? I'm looking for something easy for non-technical users and also easy for the development team to then use to generate the strings file in some simple format like XML.

答:
Use OpenOffice instead of exel, it can dump into UTF-8 encoded CSV.

We have .xls file with common ids and we send it to translation company.  Then .xls is dumped into CSV using OpenOffice.   We have a tool that generates our include localization files based on CSV file.

OwnerDisplayName: Kevin Weil

Title: C++ Localization best practices?

OwnerDisplayName: Konstantin Antselovich


问:
ag-grid (react) change rowStyle dynamically based on state
I need to change the rowStyle of few rows based on the "state"

const [highlightRowData, setHighlightRowData] = useState(0);

lets say this gets changed dynamically by some user action outside the grid.

this is my implementation of rowStyle:

```<code>const rowStyle = (params) => {
    if (params.data.someData === highlightRowData) {
      return { background: "red" };
    }
    return { background: "yellow" };
};
</code>```

but this state change doesn't get reflected in rowStyle.

答:
Not sure if you find an answer already, but like Pavan mentioned in the comment - you can checkout the gridApi.redrawRows() function described in the ag-grid doc in this link https://www.ag-grid.com/javascript-grid-refresh/#redraw-rows.

To achieve your goal here, you need to call this function after you set your highlightRowData state. As you are using hook it may look like this:

```<code>  useEffect(() => {
    // assume you have a gridApi reference here. If not yet, maybe you can hold it in a ref by useRef
    gridApi.redrawRows();
  }, [highlightRowData]);
</code>```

Body:
I need to change the rowStyle of few rows based on the "state"

const [highlightRowData, setHighlightRowData] = useState(0);

lets say this gets changed dynamically by some user action outside the grid.

this is my implementation of rowStyle:

const rowStyle = (params) => {
    if (params.data.someData === highlightRowData) {
      return { background: "red" };
    }
    return { background: "yellow" };
};

but this state change doesn't get reflected in rowStyle.

Body:
Not sure if you find an answer already, but like Pavan mentioned in the comment - you can checkout the gridApi.redrawRows() function described in the ag-grid doc in this link https://www.ag-grid.com/javascript-grid-refresh/#redraw-rows.

To achieve your goal here, you need to call this function after you set your highlightRowData state. As you are using hook it may look like this:

  useEffect(() => {
    // assume you have a gridApi reference here. If not yet, maybe you can hold it in a ref by useRef
    gridApi.redrawRows();
  }, [highlightRowData]);


问:
"Property or method 'xxxx' is not defined." On <component v-bind:is="xxxx">
I making a multi-page vue app. (trying to not use the SPA approach) I'm taking the suggested "Option 2" from this Vuejs js for multiple pages, not for a single page application

In my main layout.blade.php template I have this.

```<code><div id="app">
    @if (isset($component))
        <component v-bind:is={{ $component }} inline-template>
            <div>
    @endif

        @yield('content')

    @if (isset($component))
            </div>
        </component>
    @endif
</div>
</code>```

Then for a page that is going to use a vue instance I have this ie. meals-create.blade.php

```<code>@extends('layout.app', ['component' => 'mealcreate']) // This sets the component name for layout.blade.php

@section('content')

   // Page Content Here...

@endsection
</code>```

I have a component saved in resources/js/page-components/MealCreate.vue that will have all the vue logic for that page. That looks like this

```<code><script>
    export default {

        data() {
            return {
              // Some data ....
            };
        },
        created() {
           // ....
        },

        methods: {
            // ......
        }
    };
</script>
</code>```

In my resources/js/app.js I'm loading the component and the vue instance like this

```<code>// Page Components
Vue.component('mealcreate', require('./page-components/MealCreate.vue').default);

const app = new Vue({
    el: "#app",
});
</code>```

However now when I load the page I get this error:

Property or method "mealcreate" is not defined on the instance but referenced during render.

The property/method in this error changes to what ever I set @extends('layouts.app', ['component' => 'mealcreate']) in meal-create.blade.php

Am I missing something? Why would this be happening when its just a name of a component?

Thanks for any help!

答:
You need to add mealcreate to the components section</p>

```<code>Vue.component('mealcreate', require('./page-components/MealCreate.vue').default);

const app = new Vue({
    el: "#app",
    components: {
        mealcreate   // <-- this
    }
});
</code>```

Body:
I making a multi-page vue app. (trying to not use the SPA approach) I'm taking the suggested "Option 2" from this Vuejs js for multiple pages, not for a single page application

In my main layout.blade.php template I have this.

    @if (isset($component))
        <component v-bind:is={{ $component }} inline-template>

    @endif

        @yield('content')

    @if (isset($component))

        </component>
    @endif

Then for a page that is going to use a vue instance I have this ie. meals-create.blade.php

@extends('layout.app', ['component' => 'mealcreate']) // This sets the component name for layout.blade.php

@section('content')

   // Page Content Here...

@endsection

I have a component saved in resources/js/page-components/MealCreate.vue that will have all the vue logic for that page. That looks like this

In my resources/js/app.js I'm loading the component and the vue instance like this

// Page Components
Vue.component('mealcreate', require('./page-components/MealCreate.vue').default);

const app = new Vue({
    el: "#app",
});

However now when I load the page I get this error:

Property or method "mealcreate" is not defined on the instance but referenced during render.

The property/method in this error changes to what ever I set @extends('layouts.app', ['component' => 'mealcreate']) in meal-create.blade.php

Am I missing something? Why would this be happening when its just a name of a component?

Thanks for any help!

Body:
You need to add mealcreate to the components section

Vue.component('mealcreate', require('./page-components/MealCreate.vue').default);

const app = new Vue({
    el: "#app",
    components: {
        mealcreate   // <-- this
    }
});


问:
Reading Database File from External Storage
So, this program downloads a file from firebase storage,
my downloading code is:

```<code>private void downloadFiles(Context context, String fileName, String destinationDirectory, String url) {
    DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
    Uri uri = Uri.parse(url);
    DownloadManager.Request request = new DownloadManager.Request(uri);

    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    request.setDestinationInExternalFilesDir(context, String.valueOf(destinationDirectory), fileName);

    downloadManager.enqueue(request);
}

public void downloading(final String name) {
    downloadRef = storage.getInstance().getReference().child(name);
    downloadRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
        @Override
        public void onSuccess(Uri uri) {
            String url = uri.toString();
            downloadFiles(Main2Activity.this, name,  getApplicationContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), url);
        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            Toast.makeText(Main2Activity.this, "Failed!!!", Toast.LENGTH_LONG).show();
        }
    });
}
</code>```

and then I want to use this database so I tried to open it with:

```<code>database = SQLiteDatabase.openDatabase(myPath, null, 0);
</code>```

How can I solve this one? It would be really helpful guys.

答: You are using Environment.getExternalStorageState() which returns the current state of the primary shared/external storage media. It cannot be used to get the path as string of any file. Use  context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) to get the string value of the path to the Download directory.

Body:
So, this program downloads a file from firebase storage,
my downloading code is:

private void downloadFiles(Context context, String fileName, String destinationDirectory, String url) {
    DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
    Uri uri = Uri.parse(url);
    DownloadManager.Request request = new DownloadManager.Request(uri);

    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    request.setDestinationInExternalFilesDir(context, String.valueOf(destinationDirectory), fileName);

    downloadManager.enqueue(request);
}

public void downloading(final String name) {
    downloadRef = storage.getInstance().getReference().child(name);
    downloadRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
        @Override
        public void onSuccess(Uri uri) {
            String url = uri.toString();
            downloadFiles(Main2Activity.this, name,  getApplicationContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), url);
        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            Toast.makeText(Main2Activity.this, "Failed!!!", Toast.LENGTH_LONG).show();
        }
    });
}

and then I want to use this database so I tried to open it with:

database = SQLiteDatabase.openDatabase(myPath, null, 0);

How can I solve this one? It would be really helpful guys.


问:
Poly in poly clipping
Programs original code from here: https://www.khanacademy.org/cs/i/6630051796746240

I have a program where box faces are recursively cast out of an original box and clipped to the last faces dimensions. Although, when the player is in the center of a box the polygon clipping function inters will not produce the correct shape with empty spaces failing horizontally.

inters code

```<code>var inters=function(p0, p1){
    var p2=[], i,j,k, n0=p0.length,n1=p1.length,n2, cx,cy, dx,dy, x0,y0, x1,y1, m,m0,m1;
    for(k=0; k < n1; k+=2){
        cx=p1[k]; cy=p1[k + 1];
        dy=p1[(k + 2)%n1] - cx;
        dx=cy - p1[(k + 3)%n1];
        p2=[]; n2=0;
        for(i=0; i<n0 + 2; i+=2){
            j=i*(i - n0 >>> 31);
            x0=x1; y0=y1; m0=m1;
            x1=p0[j]; y1=p0[j + 1];
            m1=(x1 - cx)*dx + (y1 - cy)*dy;
            if(!i){continue;}
            if(m0*m1 < 0){
                m=m0/(m0 - m1);
                p2[n2    ]=x0 + (x1 - x0)*m;
                p2[n2 + 1]=y0 + (y1 - y0)*m;
                n2+=2;
            }
            if(m1 >= 0){
                p2[n2]=x1; p2[n2 + 1]=y1;
                n2+=2;
            }
        }
        if(n2 < 6){return [];}
        p0=p2; n0=n2;
    }
    return p0;
};
</code>```

I am not sure why this is, both programs (mine and original) create the same visual anamalise.

My programs code:

//This will work perfectly xD
//frameRate(0);
noiseSeed(0);
var keys = [];
var p = {
    x: 8.5,
    y: 8.5,
    z: 0.5,
    vx: 0,
    vy: 0,
    vz: 0,
    pit: 0,
    yaw: 0
};
p.setOrthogonal = function(){
    var sy=Math.sin(this.yaw), cy=Math.cos(this.yaw),
        sp=Math.sin(this.pit), cp=Math.cos(this.pit);
    this.v0x=sy*cp;
    this.v0y=cy*cp;
    this.v0z=-sp;
    this.v1x=cy;
    this.v1y=-sy;
    this.v1z=0;
    this.v2x=sy*sp;
    this.v2y=cy*sp;
    this.v2z=cp;
};
p.setOrthogonal();
//https://www.khanacademy.org/cs/-/4700070684278784
var clip=function(p0){
    var p1=[], i,j,k,n0=p0.length,n1, x0,y0,z0, x1,y1,z1, m,m0,m1;
    for(k=0; k < 4; k++){
        p1=[]; n1=0;
        for(i=0; i<n0 + 3; i+=3){
            j=i*(i - n0 >>> 31);
            x0=x1; y0=y1; z0=z1; m0=m1;
            x1=p0[j]; y1=p0[j + 1]; z1=p0[j + 2];
            m1=z1 - ((k & 2) - 1)*((k & 1)*x1 + (~k & 1)*y1);
            if(!i){continue;}
            if(m0*m1 < 0){
                m=m0/(m0 - m1);
                p1[n1    ]=x0 + (x1 - x0)*m;
                p1[n1 + 1]=y0 + (y1 - y0)*m;
                p1[n1 + 2]=z0 + (z1 - z0)*m;
                n1+=3;
            }
            if(m1 >= 0){
                p1[n1]=x1; p1[n1 + 1]=y1; p1[n1 + 2]=z1;
                n1+=3;
            }
        }
        if(n1 < 9){return [];}
        p0=p1; n0=n1;
    }
    return p0;
};
//https://en.wikipedia.org/wiki/Sutherland%E2%80%93Hodgman_algorithm
var inters=function(p0, p1){
    var p2=[], i,j,k, n0=p0.length,n1=p1.length,n2, cx,cy, dx,dy, x0,y0, x1,y1, m,m0,m1;
    for(k=0; k < n1; k+=2){
        cx=p1[k]; cy=p1[k + 1];
        dy=p1[(k + 2)%n1] - cx;
        dx=cy - p1[(k + 3)%n1];
        p2=[]; n2=0;
        for(i=0; i<n0 + 2; i+=2){
            j=i*(i - n0 >>> 31);
            x0=x1; y0=y1; m0=m1;
            x1=p0[j]; y1=p0[j + 1];
            //cx+dyt = x0 + (x1-x0)t
            //cy-dxt = y0 + (y1-y0)t
            //x| t = (x0-cx)/(dy-x1+x0)
            //y| t = (y0-cy)/(y0-y1-dx)
            //(x0-cx)/(dy-x1+x0) = (y0-cy)/(y0-y1-dx)
            //(y0-y1-dx)(x0-cx) = (dy-x1+x0)(y0-cy)
            //(y0-y1-dx)(x0-cx) - (dy-x1+x0)(y0-cy) = 0
            //(x0+(x1-x0)t-cx)*dx + (y0+(y1-y0)t-cy)*dy = 0

            m1=(x1 - cx)*dx + (y1 - cy)*dy;
            if(!i){continue;}
            if(m0*m1 < 0){
                m=m0/(m0 - m1);
                p2[n2    ]=x0 + (x1 - x0)*m;
                p2[n2 + 1]=y0 + (y1 - y0)*m;
                n2+=2;
            }
            if(m1 >= 0){
                p2[n2]=x1; p2[n2 + 1]=y1;
                n2+=2;
            }
        }
        if(n2 < 6){return [];}
        p0=p2; n0=n2;
    }
    return p0;
};
var World = (function(){
    //some stuff that is local to World
    var shift = 4;//binary shift
    var value = 1 << shift;//value of shift (16)
    var minus = value - 1;//can't think of cool name
    var depth = shift << 1;//z shift (32)
    var area = value*value*value;//area of chunck (4096)
    var noiseScale = 0.15;
    //create world object
    var World = function(){
        this.chunks = [];
        this.rd = [];
        this.boxFaces = [];
    };
    World.prototype.createChunk = function(ox, oy, oz){
        for(var y = 0; y < value; y ++){
            for(var x = 0; x < value; x ++){
                var cap = value*noise(x*noiseScale,y*noiseScale)|0;
                for(var z = 0; z < value; z ++){
                    this.chunks[z<<depth|y<<shift|x] = z>cap ? 1 : 0;
                }
            }
        }
    };
    World.prototype.recursiveFetching = function(cx, cy, cz, poly, step){
        if(step>10){return;}
        var dx,dy,dz,xp,yp,zp,x,y,z,i,j,j,k,m,nx,ny,nz,v;
        dx = cx - p.x;
        dy = cy - p.y;
        dz = cz - p.z;
        for(i = 0; i < 5; i ++){
            //cull backface
            if([dx, dy, dz][i >> 1]*(1 - (i*2 & 2)) + (~i & 1) < 0){continue;}

            //create face
            var poly3=[];
            for(j=0; j < 4; j++){
                k = i*4 + j;
                xp=dx+(0x96960f>>k&1);
                yp=dy+(0x330f69>>k&1);
                zp=dz+(0x0fcccc>>k&1);
                x=xp*p.v1x+yp*p.v1y+zp*p.v1z;
                y=xp*p.v2x+yp*p.v2y+zp*p.v2z;
                z=xp*p.v0x+yp*p.v0y+zp*p.v0z;
                poly3[j*3    ]=x;
                poly3[j*3 + 1]=y;
                poly3[j*3 + 2]=z;
            }

            //check if behind camera
            if((dx+0.5)*p.v0x + (dy+0.5)*p.v0y + (dz+0.5)*p.v0z < 2){
                poly3=clip(poly3);
                if(!poly3 || poly3.length < 9){continue;}
            }

            //convert to clip space
            var poly2 = [];
            for(j=k=0; j<poly3.length; j+=3, k+=2){
                m = 400/poly3[j + 2];
                poly2[k] = 200 + m*poly3[j];
                poly2[k + 1] = 200 + m*poly3[j + 1];
            }

            //constrain to poly
            poly2=inters(poly2, poly);
            if(!poly2 || poly2.length < 6){continue;}

            //area of polygon
            for(m=j=0, k=poly2.length; j < k; j+=2){
                m+=(poly2[j] + poly2[(j + 2)%k])*(poly2[(j + 3)%k] - poly2[j + 1]);
            }
            if(m <= 1e-4){continue;}

            //check value of border
            j = i << 1;
            nx = cx+(0x552>>j&3)-1;
            ny = cy+(0x525>>j&3)-1;
            nz = cz+(0x255>>j&3)-1;
            v = this.chunks[nz<<depth|ny<<shift|nx];
            if(((nx|ny|nz)>>shift)||v){
                if((nx|ny|nz)>>shift){
                    //this.rd.push([poly2.slice(),1,6]);
                }else{
                    this.rd.push([poly2.slice(),v,i]);
                }
                continue;
            }
            this.recursiveFetching(nx,ny,nz,poly2.slice(),step+1);
        }
    };
    World.prototype.raster = function(){
        this.rd = [];
        this.boxFaces = [];
        this.recursiveFetching(p.x|0,p.y|0,p.z|0,[0,0,400,0,400,400,0,400],0);
        for(var i = 0; i < this.rd.length; i ++){
            var data = this.rd[i];
            var poly = data[0];
            var ef = 255*data[2]/6;
            stroke(0,0,0);
            switch(data[1]){
                case 1:
                fill(ef, 0, 0);
                //stroke(ef,0,0);
                break;
                case 2:
                fill(0, 0, ef);
                //stroke(0,0,ef);
                break;
            }
            beginShape();
            for(var j = 0; j < poly.length; j +=2){
                vertex(poly[j],poly[j+1]);
            }
            endShape(CLOSE);
        }
    };
    World.prototype.getValue = function(x, y, z){
        return this.chunks[z<<depth|y<<shift|x];
    };
    //return world object
    return World;
})();
var world = new World();
world.createChunk();
draw = function() {
    background(0,150,255);
    world.raster();
    var newx = p.x, newy = p.y, newz = p.z;
    newz += p.vz;
    var spd = 0.1;
    if(keys[UP]||keys.w){
        newx += p.v0x*spd;
        newy += p.v0y*spd;
    }
    if(keys[DOWN]||keys.s){
        newx -= p.v0x*spd;
        newy -= p.v0y*spd;
    }
    if(keys[LEFT]||keys.a){
        newx -= p.v0y*spd;
        newy += p.v0x*spd;
    }
    if(keys[RIGHT]||keys.d){
        newx += p.v0y*spd;
        newy -= p.v0x*spd;
    }
    newx = constrain(newx, 0.1, 15.9);
 newy = constrain(newy, 0.1, 15.9);
 newz = constrain(newz, 0.1, 15.9);
    var nx = newx|0, ny = newy|0, nz = newz|0;
    var cx = p.x|0, cy = p.y|0, cz = p.z|0;
    if(world.getValue(cx,cy,nz+1)===0){
        p.z = newz;
        p.vz += 0.01;
        cz = nz;
    }else{
        if(keys[" "]){
            p.vz = -0.15;
        }
    }
    if(world.getValue(nx,cy,cz)===0&&world.getValue(nx,cy,cz+1)===0){
        p.x = newx;
        cx = nx;
    }
    if(world.getValue(cx,ny,cz)===0&&world.getValue(nx,ny,cz+1)===0){
        p.y = newy;
        cy = ny;
    }
    fill(255);
    noStroke();
    textSize(20);
    rect(0,0,40,25);
    fill(0,0,0);
    textAlign(LEFT,TOP);
    text(this.__frameRate|0,10,0);
};
keyPressed = function(){
    keys[keyCode] = keys[(key.toString()).toLowerCase()] = 1;
};
keyReleased = function(){
    keys[keyCode] = keys[(key.toString()).toLowerCase()]=0;
};
mouseDragged = function(){
    p.yaw += (mouseX - pmouseX) / 20;
 p.pit += (pmouseY - mouseY) / 20;
 p.setOrthogonal();
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdn.jsdelivr.net/processing.js/1.4.8/processing.min.js"></script> </code>```

I am sure the problem is with poly in poly clipping, any new algorithm that does not produce the same anomalies will be excepted as an answer

答: precision error, I rounded onscreen coordinates to fix problem.</p>

Title: Poly in poly clipping

Body:
Programs original code from here: https://www.khanacademy.org/cs/i/6630051796746240

I have a program where box faces are recursively cast out of an original box and clipped to the last faces dimensions. Although, when the player is in the center of a box the polygon clipping function inters will not produce the correct shape with empty spaces failing horizontally.

inters code

var inters=function(p0, p1){
    var p2=[], i,j,k, n0=p0.length,n1=p1.length,n2, cx,cy, dx,dy, x0,y0, x1,y1, m,m0,m1;
    for(k=0; k < n1; k+=2){
        cx=p1[k]; cy=p1[k + 1];
        dy=p1[(k + 2)%n1] - cx;
        dx=cy - p1[(k + 3)%n1];
        p2=[]; n2=0;
        for(i=0; i<n0 + 2; i+=2){
            j=i*(i - n0 >>> 31);
            x0=x1; y0=y1; m0=m1;
            x1=p0[j]; y1=p0[j + 1];
            m1=(x1 - cx)*dx + (y1 - cy)*dy;
            if(!i){continue;}
            if(m0*m1 < 0){
                m=m0/(m0 - m1);
                p2[n2    ]=x0 + (x1 - x0)*m;
                p2[n2 + 1]=y0 + (y1 - y0)*m;
                n2+=2;
            }
            if(m1 >= 0){
                p2[n2]=x1; p2[n2 + 1]=y1;
                n2+=2;
            }
        }
        if(n2 < 6){return [];}
        p0=p2; n0=n2;
    }
    return p0;
};

I am not sure why this is, both programs (mine and original) create the same visual anamalise.

My programs code:

//This will work perfectly xD
//frameRate(0);
noiseSeed(0);
var keys = [];
var p = {
    x: 8.5,
    y: 8.5,
    z: 0.5,
    vx: 0,
    vy: 0,
    vz: 0,
    pit: 0,
    yaw: 0
};
p.setOrthogonal = function(){
    var sy=Math.sin(this.yaw), cy=Math.cos(this.yaw),
        sp=Math.sin(this.pit), cp=Math.cos(this.pit);
    this.v0x=sy*cp;
    this.v0y=cy*cp;
    this.v0z=-sp;
    this.v1x=cy;
    this.v1y=-sy;
    this.v1z=0;
    this.v2x=sy*sp;
    this.v2y=cy*sp;
    this.v2z=cp;
};
p.setOrthogonal();
//https://www.khanacademy.org/cs/-/4700070684278784
var clip=function(p0){
    var p1=[], i,j,k,n0=p0.length,n1, x0,y0,z0, x1,y1,z1, m,m0,m1;
    for(k=0; k < 4; k++){
        p1=[]; n1=0;
        for(i=0; i<n0 + 3; i+=3){
            j=i*(i - n0 >>> 31);
            x0=x1; y0=y1; z0=z1; m0=m1;
            x1=p0[j]; y1=p0[j + 1]; z1=p0[j + 2];
            m1=z1 - ((k & 2) - 1)*((k & 1)*x1 + (~k & 1)*y1);
            if(!i){continue;}
            if(m0*m1 < 0){
                m=m0/(m0 - m1);
                p1[n1    ]=x0 + (x1 - x0)*m;
                p1[n1 + 1]=y0 + (y1 - y0)*m;
                p1[n1 + 2]=z0 + (z1 - z0)*m;
                n1+=3;
            }
            if(m1 >= 0){
                p1[n1]=x1; p1[n1 + 1]=y1; p1[n1 + 2]=z1;
                n1+=3;
            }
        }
        if(n1 < 9){return [];}
        p0=p1; n0=n1;
    }
    return p0;
};
//https://en.wikipedia.org/wiki/Sutherland%E2%80%93Hodgman_algorithm
var inters=function(p0, p1){
    var p2=[], i,j,k, n0=p0.length,n1=p1.length,n2, cx,cy, dx,dy, x0,y0, x1,y1, m,m0,m1;
    for(k=0; k < n1; k+=2){
        cx=p1[k]; cy=p1[k + 1];
        dy=p1[(k + 2)%n1] - cx;
        dx=cy - p1[(k + 3)%n1];
        p2=[]; n2=0;
        for(i=0; i<n0 + 2; i+=2){
            j=i*(i - n0 >>> 31);
            x0=x1; y0=y1; m0=m1;
            x1=p0[j]; y1=p0[j + 1];
            //cx+dyt = x0 + (x1-x0)t
            //cy-dxt = y0 + (y1-y0)t
            //x| t = (x0-cx)/(dy-x1+x0)
            //y| t = (y0-cy)/(y0-y1-dx)
            //(x0-cx)/(dy-x1+x0) = (y0-cy)/(y0-y1-dx)
            //(y0-y1-dx)(x0-cx) = (dy-x1+x0)(y0-cy)
            //(y0-y1-dx)(x0-cx) - (dy-x1+x0)(y0-cy) = 0
            //(x0+(x1-x0)t-cx)*dx + (y0+(y1-y0)t-cy)*dy = 0

            m1=(x1 - cx)*dx + (y1 - cy)*dy;
            if(!i){continue;}
            if(m0*m1 < 0){
                m=m0/(m0 - m1);
                p2[n2    ]=x0 + (x1 - x0)*m;
                p2[n2 + 1]=y0 + (y1 - y0)*m;
                n2+=2;
            }
            if(m1 >= 0){
                p2[n2]=x1; p2[n2 + 1]=y1;
                n2+=2;
            }
        }
        if(n2 < 6){return [];}
        p0=p2; n0=n2;
    }
    return p0;
};
var World = (function(){
    //some stuff that is local to World
    var shift = 4;//binary shift
    var value = 1 << shift;//value of shift (16)
    var minus = value - 1;//can't think of cool name
    var depth = shift << 1;//z shift (32)
    var area = value*value*value;//area of chunck (4096)
    var noiseScale = 0.15;
    //create world object
    var World = function(){
        this.chunks = [];
        this.rd = [];
        this.boxFaces = [];
    };
    World.prototype.createChunk = function(ox, oy, oz){
        for(var y = 0; y < value; y ++){
            for(var x = 0; x < value; x ++){
                var cap = value*noise(x*noiseScale,y*noiseScale)|0;
                for(var z = 0; z < value; z ++){
                    this.chunks[z<<depth|y<<shift|x] = z>cap ? 1 : 0;
                }
            }
        }
    };
    World.prototype.recursiveFetching = function(cx, cy, cz, poly, step){
        if(step>10){return;}
        var dx,dy,dz,xp,yp,zp,x,y,z,i,j,j,k,m,nx,ny,nz,v;
        dx = cx - p.x;
        dy = cy - p.y;
        dz = cz - p.z;
        for(i = 0; i < 5; i ++){
            //cull backface
            if([dx, dy, dz][i >> 1]*(1 - (i*2 & 2)) + (~i & 1) < 0){continue;}

            //create face
            var poly3=[];
            for(j=0; j < 4; j++){
                k = i*4 + j;
                xp=dx+(0x96960f>>k&1);
                yp=dy+(0x330f69>>k&1);
                zp=dz+(0x0fcccc>>k&1);
                x=xp*p.v1x+yp*p.v1y+zp*p.v1z;
                y=xp*p.v2x+yp*p.v2y+zp*p.v2z;
                z=xp*p.v0x+yp*p.v0y+zp*p.v0z;
                poly3[j*3    ]=x;
                poly3[j*3 + 1]=y;
                poly3[j*3 + 2]=z;
            }

            //check if behind camera
            if((dx+0.5)*p.v0x + (dy+0.5)*p.v0y + (dz+0.5)*p.v0z < 2){
                poly3=clip(poly3);
                if(!poly3 || poly3.length < 9){continue;}
            }

            //convert to clip space
            var poly2 = [];
            for(j=k=0; j<poly3.length; j+=3, k+=2){
                m = 400/poly3[j + 2];
                poly2[k] = 200 + m*poly3[j];
                poly2[k + 1] = 200 + m*poly3[j + 1];
            }

            //constrain to poly
            poly2=inters(poly2, poly);
            if(!poly2 || poly2.length < 6){continue;}

            //area of polygon
            for(m=j=0, k=poly2.length; j < k; j+=2){
                m+=(poly2[j] + poly2[(j + 2)%k])*(poly2[(j + 3)%k] - poly2[j + 1]);
            }
            if(m <= 1e-4){continue;}

            //check value of border
            j = i << 1;
            nx = cx+(0x552>>j&3)-1;
            ny = cy+(0x525>>j&3)-1;
            nz = cz+(0x255>>j&3)-1;
            v = this.chunks[nz<<depth|ny<<shift|nx];
            if(((nx|ny|nz)>>shift)||v){
                if((nx|ny|nz)>>shift){
                    //this.rd.push([poly2.slice(),1,6]);
                }else{
                    this.rd.push([poly2.slice(),v,i]);
                }
                continue;
            }
            this.recursiveFetching(nx,ny,nz,poly2.slice(),step+1);
        }
    };
    World.prototype.raster = function(){
        this.rd = [];
        this.boxFaces = [];
        this.recursiveFetching(p.x|0,p.y|0,p.z|0,[0,0,400,0,400,400,0,400],0);
        for(var i = 0; i < this.rd.length; i ++){
            var data = this.rd[i];
            var poly = data[0];
            var ef = 255*data[2]/6;
            stroke(0,0,0);
            switch(data[1]){
                case 1:
                fill(ef, 0, 0);
                //stroke(ef,0,0);
                break;
                case 2:
                fill(0, 0, ef);
                //stroke(0,0,ef);
                break;
            }
            beginShape();
            for(var j = 0; j < poly.length; j +=2){
                vertex(poly[j],poly[j+1]);
            }
            endShape(CLOSE);
        }
    };
    World.prototype.getValue = function(x, y, z){
        return this.chunks[z<<depth|y<<shift|x];
    };
    //return world object
    return World;
})();
var world = new World();
world.createChunk();
draw = function() {
    background(0,150,255);
    world.raster();
    var newx = p.x, newy = p.y, newz = p.z;
    newz += p.vz;
    var spd = 0.1;
    if(keys[UP]||keys.w){
        newx += p.v0x*spd;
        newy += p.v0y*spd;
    }
    if(keys[DOWN]||keys.s){
        newx -= p.v0x*spd;
        newy -= p.v0y*spd;
    }
    if(keys[LEFT]||keys.a){
        newx -= p.v0y*spd;
        newy += p.v0x*spd;
    }
    if(keys[RIGHT]||keys.d){
        newx += p.v0y*spd;
        newy -= p.v0x*spd;
    }
    newx = constrain(newx, 0.1, 15.9);
 newy = constrain(newy, 0.1, 15.9);
 newz = constrain(newz, 0.1, 15.9);
    var nx = newx|0, ny = newy|0, nz = newz|0;
    var cx = p.x|0, cy = p.y|0, cz = p.z|0;
    if(world.getValue(cx,cy,nz+1)===0){
        p.z = newz;
        p.vz += 0.01;
        cz = nz;
    }else{
        if(keys[" "]){
            p.vz = -0.15;
        }
    }
    if(world.getValue(nx,cy,cz)===0&&world.getValue(nx,cy,cz+1)===0){
        p.x = newx;
        cx = nx;
    }
    if(world.getValue(cx,ny,cz)===0&&world.getValue(nx,ny,cz+1)===0){
        p.y = newy;
        cy = ny;
    }
    fill(255);
    noStroke();
    textSize(20);
    rect(0,0,40,25);
    fill(0,0,0);
    textAlign(LEFT,TOP);
    text(this.__frameRate|0,10,0);
};
keyPressed = function(){
    keys[keyCode] = keys[(key.toString()).toLowerCase()] = 1;
};
keyReleased = function(){
    keys[keyCode] = keys[(key.toString()).toLowerCase()]=0;
};
mouseDragged = function(){
    p.yaw += (mouseX - pmouseX) / 20;
 p.pit += (pmouseY - mouseY) / 20;
 p.setOrthogonal();
};

I am sure the problem is with poly in poly clipping, any new algorithm that does not produce the same anomalies will be excepted as an answer