问:
git config command returns: fatal: unable to read config file '%HOMEDRIVE%%HOMEPATH%/.gitconfig': No such file or directory
On My Windows 10 box, when I run:

```<code>git config --global -l
</code>```

it fails with the message:

fatal: unable to read config file '%HOMEDRIVE%%HOMEPATH%/.gitconfig':
  No such file or directory

Both env vars look ok (to me) and .gitgconfig is where it should be I think:

```<code>C:\Users\BRITTG2>echo %homedrive%
P:

C:\Users\BRITTG2>echo %homepath%
\

C:\Users\BRITTG2>dir %homedrive%%homepath%.gitconfig
 Volume in drive P is home
 Volume Serial Number is 8076-09DA

 Directory of P:\

03/25/2019  02:34 PM               658 .gitconfig
               1 File(s)            658 bytes
               0 Dir(s)  2,908,136,849,408 bytes free
</code>```

What am I missing?

答:
Run powershell as administrator (but you can use cmd, Git bash, etc) and try again.
In my case:</p>

```<code>cd C:\ROstuff\ROprojects\Python\
git init
git config --global user.name "Rodrigo H Padilla"
git config --global user.email "Myemail@email.com"
git config --global -l
</code>```

Body:
On My Windows 10 box, when I run:

git config --global -l

it fails with the message:

fatal: unable to read config file '%HOMEDRIVE%%HOMEPATH%/.gitconfig':
  No such file or directory

Both env vars look ok (to me) and .gitgconfig is where it should be I think:

C:\Users\BRITTG2>echo %homedrive%
P:

C:\Users\BRITTG2>echo %homepath%
\

C:\Users\BRITTG2>dir %homedrive%%homepath%.gitconfig
 Volume in drive P is home
 Volume Serial Number is 8076-09DA

 Directory of P:\

03/25/2019  02:34 PM               658 .gitconfig
               1 File(s)            658 bytes
               0 Dir(s)  2,908,136,849,408 bytes free

What am I missing?

Body:
Run powershell as administrator (but you can use cmd, Git bash, etc) and try again.
In my case:

cd C:\ROstuff\ROprojects\Python\
git init
git config --global user.name "Rodrigo H Padilla"
git config --global user.email "Myemail@email.com"
git config --global -l


来源: stackexchange

问:
Nginx: Failed to start A high performance web server and a reverse proxy server
I try to start this service but i can´t, the error below occur:</p>

```<code>root@zabbix:/home/appliance# systemctl status nginx.service

nginx.service - A high performance web server and a reverse proxy server
   Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
   Active: failed (Result: exit-code) since Wed 2018-07-25 18:33:26 UTC; 1min 27s ago
  Process: 30040 ExecStart=/usr/sbin/nginx -g daemon on; master_process on; (code=exited, status=1/FAILURE)
  Process: 30037 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_process on; (code=exited, status=0/SUCCESS)

Jul 25 18:33:25 zabbix nginx[30040]: nginx: [emerg] listen() to [::]:80, backlog 511 failed (98: Address already in use)
Jul 25 18:33:25 zabbix nginx[30040]: nginx: [emerg] listen() to 0.0.0.0:80, backlog 511 failed (98: Address already in use)
Jul 25 18:33:25 zabbix nginx[30040]: nginx: [emerg] listen() to [::]:80, backlog 511 failed (98: Address already in use)
Jul 25 18:33:26 zabbix nginx[30040]: nginx: [emerg] listen() to 0.0.0.0:80, backlog 511 failed (98: Address already in use)
Jul 25 18:33:26 zabbix nginx[30040]: nginx: [emerg] listen() to [::]:80, backlog 511 failed (98: Address already in use)
Jul 25 18:33:26 zabbix nginx[30040]: nginx: [emerg] still could not bind()
Jul 25 18:33:26 zabbix systemd[1]: nginx.service: Control process exited, code=exited status=1

Jul 25 18:33:26 zabbix systemd[1]: *******Failed to start A high performance web server*** and a reverse proxy server.****

Jul 25 18:33:26 zabbix systemd[1]: nginx.service: Unit entered failed state.
Jul 25 18:33:26 zabbix systemd[1]: nginx.service: Failed with result 'exit-code'.
</code>```

答:
You already have a process bound to the HTTP port 80 (Specially after upgrading systems! it will start apache2 by default)

So try this first :

```<code>sudo service apache2 stop
sudo systemctl restart nginx
</code>```

If the problem is not solved then run this command sudo lsof -i:80 to get a list of processes using the port and then stop or disable web server.

Try to stop the process which are using the port 80 using :

```<code>sudo fuser -k 80/tcp
sudo systemctl restart nginx
</code>```

In some cases it may be some issues in the configuration file.

You can use nginx -t -c /etc/nginx/nginx.conf command to find any miss-configuration.

In some cases this error is caused by a default Nginx site already on port 80, removing default config works if you don't need a default one.

```<code>sudo rm /etc/nginx/sites-enabled/default
sudo service nginx restart
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I try to start this service but i can´t, the error below occur:

root@zabbix:/home/appliance# systemctl status nginx.service

nginx.service - A high performance web server and a reverse proxy server
   Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
   Active: failed (Result: exit-code) since Wed 2018-07-25 18:33:26 UTC; 1min 27s ago
  Process: 30040 ExecStart=/usr/sbin/nginx -g daemon on; master_process on; (code=exited, status=1/FAILURE)
  Process: 30037 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_process on; (code=exited, status=0/SUCCESS)

Jul 25 18:33:25 zabbix nginx[30040]: nginx: [emerg] listen() to [::]:80, backlog 511 failed (98: Address already in use)
Jul 25 18:33:25 zabbix nginx[30040]: nginx: [emerg] listen() to 0.0.0.0:80, backlog 511 failed (98: Address already in use)
Jul 25 18:33:25 zabbix nginx[30040]: nginx: [emerg] listen() to [::]:80, backlog 511 failed (98: Address already in use)
Jul 25 18:33:26 zabbix nginx[30040]: nginx: [emerg] listen() to 0.0.0.0:80, backlog 511 failed (98: Address already in use)
Jul 25 18:33:26 zabbix nginx[30040]: nginx: [emerg] listen() to [::]:80, backlog 511 failed (98: Address already in use)
Jul 25 18:33:26 zabbix nginx[30040]: nginx: [emerg] still could not bind()
Jul 25 18:33:26 zabbix systemd[1]: nginx.service: Control process exited, code=exited status=1

Jul 25 18:33:26 zabbix systemd[1]: *******Failed to start A high performance web server*** and a reverse proxy server.****

Jul 25 18:33:26 zabbix systemd[1]: nginx.service: Unit entered failed state.
Jul 25 18:33:26 zabbix systemd[1]: nginx.service: Failed with result 'exit-code'.

Body:
You already have a process bound to the HTTP port 80 (Specially after upgrading systems! it will start apache2 by default)

So try this first :

sudo service apache2 stop
sudo systemctl restart nginx

If the problem is not solved then run this command sudo lsof -i:80 to get a list of processes using the port and then stop or disable web server.

Try to stop the process which are using the port 80 using :

sudo fuser -k 80/tcp
sudo systemctl restart nginx

In some cases it may be some issues in the configuration file.

You can use nginx -t -c /etc/nginx/nginx.conf command to find any miss-configuration.

In some cases this error is caused by a default Nginx site already on port 80, removing default config works if you don't need a default one.

sudo rm /etc/nginx/sites-enabled/default
sudo service nginx restart


问:
convert docker-compose.yml file to kubernetes
I am converting a docker-compose file to kubernetes using kompose running the follwing command:

$kompose convert -f docker-compose.yml -o kubernetes_image.yaml

After the command finish the ouput is the following.

```<code>WARN Volume mount on the host "/usr/docker/adpater/dbdata" isn't supported - ignoring path on the host
INFO Network integration is detected at Source, shall be converted to equivalent NetworkPolicy at Destination
WARN Volume mount on the host "/usr/docker/adpater/license.json" isn't supported - ignoring path on the host
WARN Volume mount on the host "/usr/docker/adpater/certificates/ssl.crt" isn't supported - ignoring path on the host
WARN Volume mount on the host "/usr/docker/adpater/certificates/ssl.key" isn't supported - ignoring path on the host
WARN Volume mount on the host "/usr/docker/adpater/server.xml" isn't supported - ignoring path on the host
INFO Network integration is detected at Source, shall be converted to equivalent NetworkPolicy at Destination
</code>```

To push the converted file to kubernetes I run the follwoing command:

$kubectl apply -f kubernetes_image.yaml

```<code>NAME                      READY   STATUS             RESTARTS   AGE
mysql-557dd849c8-bsdq7    1/1     Running            1          17h
tomcat-7cd65d4556-spjbl   0/1     CrashLoopBackOff   76         18h
</code>```

if I run:
$ kubectl describe pod tomcat-7cd65d4556-spjbl
I get the following message:

```<code>Last State:     Terminated
      Reason:       ContainerCannotRun
      Message:      OCI runtime create failed: container_linux.go:349: starting container process caused "process_linux.go:449: container init caused \"rootfs_linux.go:58: mounting \\\"/usr/docker/adapter/server.xml\\\" to rootfs \\\"/var/lib/docker/overlay2/a6df90a0ef4cbe8b2a3fa5352be5f304cd7b648fb1381492308f0a7fceb931cc/merged\\\" at \\\"/var/lib/docker/overlay2/a6df90a0ef4cbe8b2a3fa5352be5f304cd7b648fb1381492308f0a7fceb931cc/merged/usr/local/tomcat/conf/server.xml\\\" caused \\\"not a directory\\\"\"": unknown: Are you trying to mount a directory onto a file (or vice-versa)? Check if the specified host path exists and is the expected type
      Exit Code:    127
      Started:      Sun, 31 May 2020 13:35:00 +0100
      Finished:     Sun, 31 May 2020 13:35:00 +0100
    Ready:          False
    Restart Count:  75
    Environment:    <none>
    Mounts:
      /run/secrets/rji_license.json from tomcat-hostpath0 (rw)
      /usr/local/tomcat/conf/server.xml from tomcat-hostpath3 (rw)
      /usr/local/tomcat/conf/ssl.crt from tomcat-hostpath1 (rw)
      /usr/local/tomcat/conf/ssl.key from tomcat-hostpath2 (rw)
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-8dhnk (ro)
</code>```

This is my docker-compose.yml file:

```<code>version: '3.6'

networks:
  integration:

services:
  mysql:
    environment:
      MYSQL_USER: 'integrationdb'
      MYSQL_PASSWORD: 'password'
      MYSQL_ROOT_PASSWORD: 'password'
    image: db:poc
    networks:
    - integration
    ports:
    - '3306:3306'
    restart: always
    volumes:
       - ./dbdata:/var/lib/mysql
  tomcat:
    image: adapter:poc
    networks:
    - integration
    ports:
    - '8080:8080'
    - '8443:8443'
    restart: always
    volumes:
      - ./license.json:/run/secrets/rji_license.json
      - ./certificates/ssl.crt:/usr/local/tomcat/conf/ssl.crt
      - ./certificates/ssl.key:/usr/local/tomcat/conf/ssl.key
      - ./server.xml:/usr/local/tomcat/conf/server.xml
</code>```

Versions of the tools:

```<code>kompose: 1.21.0 (992df58d8)

docker: 19.03.9

kubectl:Major:"1", Minor:"18"
</code>```

I think my challange here is whithin this type of volumes or files, I dont know how can I migrate or convert them to kubernetes and put the tomcat pod running fine.
Could someone give me a hand?

```<code> volumes:
          - ./license.json:/run/secrets/rji_license.json
          - ./certificates/ssl.crt:/usr/local/tomcat/conf/ssl.crt
          - ./certificates/ssl.key:/usr/local/tomcat/conf/ssl.key
          - ./server.xml:/usr/local/tomcat/conf/server.xml
</code>```

thanks in advance.

答:
When Kompose warns you:

WARN Volume mount on the host "/usr/docker/adpater/license.json" isn't supported - ignoring path on the host
```

<p>It means that it can't translate this fragment of the <code>docker-compose.yml</code> file into Kubernetes syntax:</p>

<pre class="lang-yaml prettyprint-override"><code>volumes:
    - ./license.json:/run/secrets/rji_license.json
</code>```

In native Kubernetes, you'd need to provide this content in ConfigMap or Secret objects, and then mount the file into the pod.  You can't directly access content on the system from which you're launching the containers.

You can't really get around directly working with the Kubernetes YAML files here.  You could run kompose convert to generate the skeleton files, but then you'll need to edit those to add the ConfigMaps, PersistentVolumeClaims (for the database storage), and relevant volume and mount declarations, and then run kubectl apply -f to actually run them.  I'd check the Kubernetes YAML files into source control, and maintain them in parallel with your Docker Compose setup.

Body:
I am converting a docker-compose file to kubernetes using kompose running the follwing command:

$kompose convert -f docker-compose.yml -o kubernetes_image.yaml

After the command finish the ouput is the following.

WARN Volume mount on the host "/usr/docker/adpater/dbdata" isn't supported - ignoring path on the host
INFO Network integration is detected at Source, shall be converted to equivalent NetworkPolicy at Destination
WARN Volume mount on the host "/usr/docker/adpater/license.json" isn't supported - ignoring path on the host
WARN Volume mount on the host "/usr/docker/adpater/certificates/ssl.crt" isn't supported - ignoring path on the host
WARN Volume mount on the host "/usr/docker/adpater/certificates/ssl.key" isn't supported - ignoring path on the host
WARN Volume mount on the host "/usr/docker/adpater/server.xml" isn't supported - ignoring path on the host
INFO Network integration is detected at Source, shall be converted to equivalent NetworkPolicy at Destination

To push the converted file to kubernetes I run the follwoing command:

$kubectl apply -f kubernetes_image.yaml

NAME                      READY   STATUS             RESTARTS   AGE
mysql-557dd849c8-bsdq7    1/1     Running            1          17h
tomcat-7cd65d4556-spjbl   0/1     CrashLoopBackOff   76         18h

if I run:
$ kubectl describe pod tomcat-7cd65d4556-spjbl
I get the following message:

Last State:     Terminated
      Reason:       ContainerCannotRun
      Message:      OCI runtime create failed: container_linux.go:349: starting container process caused "process_linux.go:449: container init caused \"rootfs_linux.go:58: mounting \\\"/usr/docker/adapter/server.xml\\\" to rootfs \\\"/var/lib/docker/overlay2/a6df90a0ef4cbe8b2a3fa5352be5f304cd7b648fb1381492308f0a7fceb931cc/merged\\\" at \\\"/var/lib/docker/overlay2/a6df90a0ef4cbe8b2a3fa5352be5f304cd7b648fb1381492308f0a7fceb931cc/merged/usr/local/tomcat/conf/server.xml\\\" caused \\\"not a directory\\\"\"": unknown: Are you trying to mount a directory onto a file (or vice-versa)? Check if the specified host path exists and is the expected type
      Exit Code:    127
      Started:      Sun, 31 May 2020 13:35:00 +0100
      Finished:     Sun, 31 May 2020 13:35:00 +0100
    Ready:          False
    Restart Count:  75
    Environment:    <none>
    Mounts:
      /run/secrets/rji_license.json from tomcat-hostpath0 (rw)
      /usr/local/tomcat/conf/server.xml from tomcat-hostpath3 (rw)
      /usr/local/tomcat/conf/ssl.crt from tomcat-hostpath1 (rw)
      /usr/local/tomcat/conf/ssl.key from tomcat-hostpath2 (rw)
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-8dhnk (ro)

This is my docker-compose.yml file:

version: '3.6'

networks:
  integration:

services:
  mysql:
    environment:
      MYSQL_USER: 'integrationdb'
      MYSQL_PASSWORD: 'password'
      MYSQL_ROOT_PASSWORD: 'password'
    image: db:poc
    networks:
    - integration
    ports:
    - '3306:3306'
    restart: always
    volumes:
       - ./dbdata:/var/lib/mysql
  tomcat:
    image: adapter:poc
    networks:
    - integration
    ports:
    - '8080:8080'
    - '8443:8443'
    restart: always
    volumes:
      - ./license.json:/run/secrets/rji_license.json
      - ./certificates/ssl.crt:/usr/local/tomcat/conf/ssl.crt
      - ./certificates/ssl.key:/usr/local/tomcat/conf/ssl.key
      - ./server.xml:/usr/local/tomcat/conf/server.xml

Versions of the tools:

kompose: 1.21.0 (992df58d8)

docker: 19.03.9

kubectl:Major:"1", Minor:"18"

I think my challange here is whithin this type of volumes or files, I dont know how can I migrate or convert them to kubernetes and put the tomcat pod running fine.
Could someone give me a hand?

 volumes:
          - ./license.json:/run/secrets/rji_license.json
          - ./certificates/ssl.crt:/usr/local/tomcat/conf/ssl.crt
          - ./certificates/ssl.key:/usr/local/tomcat/conf/ssl.key
          - ./server.xml:/usr/local/tomcat/conf/server.xml

thanks in advance.

Body:
When Kompose warns you:

WARN Volume mount on the host "/usr/docker/adpater/license.json" isn't supported - ignoring path on the host

It means that it can't translate this fragment of the docker-compose.yml file into Kubernetes syntax:

volumes:
    - ./license.json:/run/secrets/rji_license.json

In native Kubernetes, you'd need to provide this content in ConfigMap or Secret objects, and then mount the file into the pod.  You can't directly access content on the system from which you're launching the containers.

You can't really get around directly working with the Kubernetes YAML files here.  You could run kompose convert to generate the skeleton files, but then you'll need to edit those to add the ConfigMaps, PersistentVolumeClaims (for the database storage), and relevant volume and mount declarations, and then run kubectl apply -f to actually run them.  I'd check the Kubernetes YAML files into source control, and maintain them in parallel with your Docker Compose setup.


问:
From where can i get libmp3lame.so file?
can anybody give me links to dowlnload libmp3lame.so file.I want to convert mp3 stream to pcm.
I want to do it using android ndk.</p>

答:
Try the following url

http://mandrivausers.org/index.php?/topic/25941-where-to-get-libmp3lameso-solved/

http://hany.sk/~hany/RPM/libmp3lame.so.0.html

Thanks
Deepak

ContentLicense: CC BY-SA 3.0


问:
Typescript how to write nested keyof
I have the following code;

```<code>class Transform<T> {
  constructor(private value: T) {}
}

class Test<T extends object> {
  constructor(private a: T) {}

  transform(): { [K in keyof T]: Transform<T[K]> } {
    // functionality omitted
    return this.a as any;
  }
}

const test = new Test({
    a: '',
    b: {
      c: '',
      d: {
          v: ''
      }
    }
})

const transformed = test.transform();
</code>```

The issue is that the transform method return type is:

```<code>const transformed: {
    a: Transform<string>;
    b: Transform<{
        c: string;
        d: {
            v: string;
        };
    }>;
}
</code>```

But what I want is that every key will be of type Transform:

```<code>const transformed: {
    a: Transform<string>;
    b: Transform<{
        c: Transform<string>;
        d: Transform<{
            v: Transform<string>;
        }>;
    }>;
}
</code>```

There is a way to achieve it with TS?

答:
Sure. Try a conditional recursive type like this:

```<code>type Transformed<T> = {
  [K in keyof T]:
    T[K] extends object
      ? Transform<Transformed<T[K]>>
      : Transform<T[K]>
};
</code>```

Use it as the return type for transform().

```<code>class Test<T extends object> {
  constructor(private a: T) {}

  transform(): Transformed<T> {
    // functionality omitted
    return this.a as any;
  }
}
</code>```

The result:

```<code>/**
 * @returns
 *
 * {
 *    a: Transform<string>;
 *    b: Transform<{
 *        c: Transform<string>;
 *        d: Transform<{
 *            v: Transform<string>;
 *        }>;
 *    }>;
 * }
 *
 */
const transformed = test.transform();
</code>```

Note: Some IDEs (like Visual Studio Code) may not show the expanded return type. If you want to make sure that my solution is indeed what you are looking for, use a helper type like Compact so that the return type appears in full glory.

```<code>/**
 * @see https://github.com/microsoft/TypeScript/issues/14829#issuecomment-320754731
 */
type Compact<T> = {} & { [P in keyof T]: T[P] };

type Transformed<T> = Compact<{
  [K in keyof T]:
    T[K] extends object
      ? Transform<Transformed<T[K]>>
      : Transform<T[K]>
}>;
</code>```

Now it will look exactly like what you asked for. Hope that helps!

Title: Typescript how to write nested keyof

Body:
I have the following code;

class Transform<T> {
  constructor(private value: T) {}
}

class Test<T extends object> {
  constructor(private a: T) {}

  transform(): { [K in keyof T]: Transform<T[K]> } {
    // functionality omitted
    return this.a as any;
  }
}

const test = new Test({
    a: '',
    b: {
      c: '',
      d: {
          v: ''
      }
    }
})

const transformed = test.transform();

The issue is that the transform method return type is:

const transformed: {
    a: Transform<string>;
    b: Transform<{
        c: string;
        d: {
            v: string;
        };
    }>;
}

But what I want is that every key will be of type Transform:

const transformed: {
    a: Transform<string>;
    b: Transform<{
        c: Transform<string>;
        d: Transform<{
            v: Transform<string>;
        }>;
    }>;
}

There is a way to achieve it with TS?

Body:
Sure. Try a conditional recursive type like this:

type Transformed<T> = {
  [K in keyof T]:
    T[K] extends object
      ? Transform<Transformed<T[K]>>
      : Transform<T[K]>
};

Use it as the return type for transform().

class Test<T extends object> {
  constructor(private a: T) {}

  transform(): Transformed<T> {
    // functionality omitted
    return this.a as any;
  }
}

The result:

/**
 * @returns
 *
 * {
 *    a: Transform<string>;
 *    b: Transform<{
 *        c: Transform<string>;
 *        d: Transform<{
 *            v: Transform<string>;
 *        }>;
 *    }>;
 * }
 *
 */
const transformed = test.transform();

Note: Some IDEs (like Visual Studio Code) may not show the expanded return type. If you want to make sure that my solution is indeed what you are looking for, use a helper type like Compact so that the return type appears in full glory.

/**
 * @see https://github.com/microsoft/TypeScript/issues/14829#issuecomment-320754731
 */
type Compact<T> = {} & { [P in keyof T]: T[P] };

type Transformed<T> = Compact<{
  [K in keyof T]:
    T[K] extends object
      ? Transform<Transformed<T[K]>>
      : Transform<T[K]>
}>;

Now it will look exactly like what you asked for. Hope that helps!


问:
how to search for a value in different Json files
what i trying to do is when a user enters the longtitude and latitude of a location, the application returns the associated grid code which is stored in one of the 3 json data files.
i am trying to search in all three files at the same time this is my try but smees  not working.

```<code>  async function lookupGridcodeByLatAndLong(lat, long){
    const response=await fetch('data/GHI_part01.json');
    const line=await response.json();

    var result = line.find(x => x.lat == lat && x.long == long);
       if (result) {
      return result.GRIDCODE;
       } else {
      lookupGHI_part02(lat, long);
       }

}
async function lookupGHI_part02(lat, long){
    const response=await fetch('data/GHI_part02.json');
    const line=await response.json();
    var result = line.find(x => x.lat == lat && x.long == long);
       if (result) {
      return result.GRIDCODE;
       } else {
      lookupGHI_part03(lat, long);
       }
}
async function lookupGHI_part03(lat, long){
    const response=await fetch('data/GHI_part03.json');
    const line=await response.json();

    var result = line.find(x => x.lat == lat && x.long == long);
       if (result) {
      return result.GRIDCODE;
       } else {
      return new Error('No records found');
       }
}
$("#Btn" ).click(function() {
    lookupGridcodeByLatAndLong(lat, long)
    .then(gridcode => {
    var ghi = gridcode;})
$("#result").show();
$("#resultat").html(ghi);
}
</code>```

this how my data look like

```<code>[{"GRIDCODE":2115,"Lat":29.478,"Long":-5.565},{"GRIDCODE":2115,"Lat":29.478,"Long":-5.562},{"GRIDCODE":2115,"Lat":29.486,"Long":-5.572},{"GRIDCODE":2113,"Lat":29.483,"Long":-5.567},{"GRIDCODE":2109,"Lat":29.483,"Long":-5.559},{"GRIDCODE":2115,"Lat":29.485,"Long":-5.554},{"GRIDCODE":2115,"Lat":29.493,"Long":-5.616},{"GRIDCODE":2120,"Lat":29.492,"Long":-5.609},{"GRIDCODE":2116,"Lat":29.492,"Long":-5.601},{"GRIDCODE":2116,"Lat":29.492,"Long":-5.592},{"GRIDCODE":2115,"Lat":29.493,"Long":-5.584},{"GRIDCODE":2110,"Lat":29.491,"Long":-5.575}]
</code>```

答:
first error was in

```<code>var result = line.find(x => x.Lat == lat && x.Long == long);
</code>```

I changed to capital "L"s in x.Lat and x.Long

scecond inseted of calling function inside another funcution i change it to this

```<code>    async function lookupGridcodeByLatAndLong(lat, long){
    const response=await fetch('data/GHI_part01.json');
    const line=await response.json();
    var check =0;
    var result = line.find(x => x.Lat == lat && x.Long == long);
       if (result) {
      return result.GRIDCODE;
       }
             else {
       var check = 1;
       }
             if (check == 1)
             {
                const response=await fetch('data/GHI_part02.json');
                const line=await response.json();

                var result = line.find(x => x.Lat == lat && x.Long == long);
                   if (result) {
                  return result.GRIDCODE;
                   } else {
                    check = 2
                   }
             }
             if (check = 2)
             {
                 const response=await fetch('data/GHI_part03.json');
                const line=await response.json();

                var result = line.find(x => x.Lat == lat && x.Long == long);
                   if (result) {
                  return result.GRIDCODE;
                   } else {
                  return new Error('No records found');
                   }
             }
}
</code>```

Body:
what i trying to do is when a user enters the longtitude and latitude of a location, the application returns the associated grid code which is stored in one of the 3 json data files.
i am trying to search in all three files at the same time this is my try but smees  not working.

  async function lookupGridcodeByLatAndLong(lat, long){
    const response=await fetch('data/GHI_part01.json');
    const line=await response.json();

    var result = line.find(x => x.lat == lat && x.long == long);
       if (result) {
      return result.GRIDCODE;
       } else {
      lookupGHI_part02(lat, long);
       }

}
async function lookupGHI_part02(lat, long){
    const response=await fetch('data/GHI_part02.json');
    const line=await response.json();
    var result = line.find(x => x.lat == lat && x.long == long);
       if (result) {
      return result.GRIDCODE;
       } else {
      lookupGHI_part03(lat, long);
       }
}
async function lookupGHI_part03(lat, long){
    const response=await fetch('data/GHI_part03.json');
    const line=await response.json();

    var result = line.find(x => x.lat == lat && x.long == long);
       if (result) {
      return result.GRIDCODE;
       } else {
      return new Error('No records found');
       }
}
$("#Btn" ).click(function() {
    lookupGridcodeByLatAndLong(lat, long)
    .then(gridcode => {
    var ghi = gridcode;})
$("#result").show();
$("#resultat").html(ghi);
}

this how my data look like

[{"GRIDCODE":2115,"Lat":29.478,"Long":-5.565},{"GRIDCODE":2115,"Lat":29.478,"Long":-5.562},{"GRIDCODE":2115,"Lat":29.486,"Long":-5.572},{"GRIDCODE":2113,"Lat":29.483,"Long":-5.567},{"GRIDCODE":2109,"Lat":29.483,"Long":-5.559},{"GRIDCODE":2115,"Lat":29.485,"Long":-5.554},{"GRIDCODE":2115,"Lat":29.493,"Long":-5.616},{"GRIDCODE":2120,"Lat":29.492,"Long":-5.609},{"GRIDCODE":2116,"Lat":29.492,"Long":-5.601},{"GRIDCODE":2116,"Lat":29.492,"Long":-5.592},{"GRIDCODE":2115,"Lat":29.493,"Long":-5.584},{"GRIDCODE":2110,"Lat":29.491,"Long":-5.575}]

Body:
first error was in

var result = line.find(x => x.Lat == lat && x.Long == long);

I changed to capital "L"s in x.Lat and x.Long

scecond inseted of calling function inside another funcution i change it to this

    async function lookupGridcodeByLatAndLong(lat, long){
    const response=await fetch('data/GHI_part01.json');
    const line=await response.json();
    var check =0;
    var result = line.find(x => x.Lat == lat && x.Long == long);
       if (result) {
      return result.GRIDCODE;
       }
             else {
       var check = 1;
       }
             if (check == 1)
             {
                const response=await fetch('data/GHI_part02.json');
                const line=await response.json();

                var result = line.find(x => x.Lat == lat && x.Long == long);
                   if (result) {
                  return result.GRIDCODE;
                   } else {
                    check = 2
                   }
             }
             if (check = 2)
             {
                 const response=await fetch('data/GHI_part03.json');
                const line=await response.json();

                var result = line.find(x => x.Lat == lat && x.Long == long);
                   if (result) {
                  return result.GRIDCODE;
                   } else {
                  return new Error('No records found');
                   }
             }
}


问:
nifi ingestion with 10,000+ sensor data?
I am planning to use nifi to ingest data from more than 10,000 sensors. There are 50-100 types of sensors which will send a specific metric to nifi.

I am pondering over whether I should assign 1 port number to listen to all the sensors or I should assign 1 port for each type of sensor to facilitate my data pipeline. which is the better option?

Is there a upper limit of the no of ports which I can "listen" using nifi?

答:
@ilovetolearn

NiFi is such a powerful tool.  You can do either of your ideas, but I would recommend to do what is easier for you.   If you have data source sensors that need different data flows, use different ports.  However, if you can fire everything at a single port, I would do this.  This makes it easier to implement, consistent, easier to support later, and easier to scale.

In large scale highly available NiFi, you may want a Load Balancer to handle the inbound data.  This would push the sensor data toward a single host:port on the LB appliance, that then directs to NiFi with 3-5-10+ nodes.


问:
return in "wait Task<string>.Run (..)" sometimes hangs
This is a repro of my code, where the return in wait Task<string>.Run (..) sometimes hangs. If it fails, it's mostly on the first call.

How can I improve it?

```<code>using System.Threading.Tasks;
using System.Diagnostics;

private void Button_Click(object sender, RoutedEventArgs e)
{
    // This can be a very huge list
    string[] servers = new string[] { "10.17.100.1", "10.17.100.10", "10.17.100.20" };

    // the max parallel tasks must be limited
    Parallel.ForEach(servers,
        new ParallelOptions { MaxDegreeOfParallelism = 10 },
        (forServer) =>
    {
        this.Method1Async(forServer).Wait();
    });

    Debug.WriteLine("Finished");
}

private async Task Method1Async(string server)
{
    await this.Method2Async(server);
}

private async Task Method2Async(string server)
{
    Debug.WriteLine("> Method2Async");

    string result = await Task<string>.Run(() =>
    {

        Debug.WriteLine("  Method2Async before return");

        return GetDataFromServer(server);
    });

    Debug.WriteLine("< Method2Async");
}

private string GetDataFromServer(string server)
{
    // any long time running stuff

    Thread.Sleep(10000);

    return "the server data";
}
</code>```

Wanted output:

```<code>> Method2Async
  Method2Async before return
< Method2Async
Finished
</code>```

Output when return hangs:

```<code>> Method2Async
  Method2Async before return
</code>```

答:
Note: thanks to Theodor Zoulias mentioning this:

According to this question Parallel.ForEach does not wait for the tasks to finish, therefore awaiting inside the action does not do anything and IsCompleted will be set to true as soon as all tasks are started.

Change the signature of the ForEach's Action to async to enable awaiting.

```<code>using System.Threading.Tasks;
using System.Diagnostics;

private void Button_Click(object sender, RoutedEventArgs e)
{
    string[] dummyArray = new string[] { "anyvalue" };

    Parallel.ForEach(dummyArray, async (forDummy) =>
    {
        await this.Method1Async();
    });

    Debug.WriteLine("Finished");
}

private async Task Method1Async()
{
    await this.Method2Async();
}

private async Task Method2Async()
{
    Debug.WriteLine("> Method2Async");

    string result = await Task<string>.Run(() =>
    {
        Debug.WriteLine("  Method2Async before return");
        return "anydata"; // this return sometimes does not "come back" ...
    });

    // ... so this code is never reached
    Debug.WriteLine("< Method2Async" + result);
}
</code>```

Generally, when writing async code you must avoid synchronous calls (Wait, Result, etc.) or otherwise there is no point in writing asynchronous code. Just remove all Tasks, async and await and your code will run faster.

An exception to this rule is when you deliberately want to block thread, such as in legacy code.

Edit:

If you want to wait for all tasks to finish before going to the next statement, you can use WhenAll:

```<code>private async void Button_Click(object sender, RoutedEventArgs e)
{
    string[] dummyArray = new string[] { "anyvalue" };

    Task[] tasks = dummyArray.Select(async x => await Method1Async()).ToArray();
    await Task.WhenAll(tasks);
}
</code>```

or

```<code>private async void Button_Click(object sender, RoutedEventArgs e)
{
    string[] dummyArray = new string[] { "anyvalue" };

    Task[] tasks = dummyArray.Select(x => Method1Async()).ToArray();
    await Task.WhenAll(tasks);
}
</code>```

Edit:

If you want to limit the number of parallel tasks then you can do this:

```<code>    public async Task Button_Click()
    {
        string[] servers = new string[] { "1", "2", "3", "4", "5" };

        var maxParallel = 3;
        var throttler = new SemaphoreSlim(initialCount: maxParallel);
        var tasks = servers.Select(async server =>
        {
            try
            {
                await throttler.WaitAsync();
                await Method1Async(server);
            }
            finally
            {
                throttler.Release();
            }
        });
        await Task.WhenAll(tasks);

        Console.WriteLine("Finished");
    }
</code>```

Body:
This is a repro of my code, where the return in wait Task<string>.Run (..) sometimes hangs. If it fails, it's mostly on the first call.

How can I improve it?

using System.Threading.Tasks;
using System.Diagnostics;

private void Button_Click(object sender, RoutedEventArgs e)
{
    // This can be a very huge list
    string[] servers = new string[] { "10.17.100.1", "10.17.100.10", "10.17.100.20" };

    // the max parallel tasks must be limited
    Parallel.ForEach(servers,
        new ParallelOptions { MaxDegreeOfParallelism = 10 },
        (forServer) =>
    {
        this.Method1Async(forServer).Wait();
    });

    Debug.WriteLine("Finished");
}

private async Task Method1Async(string server)
{
    await this.Method2Async(server);
}

private async Task Method2Async(string server)
{
    Debug.WriteLine("> Method2Async");

    string result = await Task<string>.Run(() =>
    {

        Debug.WriteLine("  Method2Async before return");

        return GetDataFromServer(server);
    });

    Debug.WriteLine("< Method2Async");
}

private string GetDataFromServer(string server)
{
    // any long time running stuff

    Thread.Sleep(10000);

    return "the server data";
}

Wanted output:

> Method2Async
  Method2Async before return
< Method2Async
Finished

Output when return hangs:

> Method2Async
  Method2Async before return

Body:
Note: thanks to Theodor Zoulias mentioning this:

According to this question Parallel.ForEach does not wait for the tasks to finish, therefore awaiting inside the action does not do anything and IsCompleted will be set to true as soon as all tasks are started.

Change the signature of the ForEach's Action to async to enable awaiting.

using System.Threading.Tasks;
using System.Diagnostics;

private void Button_Click(object sender, RoutedEventArgs e)
{
    string[] dummyArray = new string[] { "anyvalue" };

    Parallel.ForEach(dummyArray, async (forDummy) =>
    {
        await this.Method1Async();
    });

    Debug.WriteLine("Finished");
}

private async Task Method1Async()
{
    await this.Method2Async();
}

private async Task Method2Async()
{
    Debug.WriteLine("> Method2Async");

    string result = await Task<string>.Run(() =>
    {
        Debug.WriteLine("  Method2Async before return");
        return "anydata"; // this return sometimes does not "come back" ...
    });

    // ... so this code is never reached
    Debug.WriteLine("< Method2Async" + result);
}

Generally, when writing async code you must avoid synchronous calls (Wait, Result, etc.) or otherwise there is no point in writing asynchronous code. Just remove all Tasks, async and await and your code will run faster.

An exception to this rule is when you deliberately want to block thread, such as in legacy code.

Edit:

If you want to wait for all tasks to finish before going to the next statement, you can use WhenAll:

private async void Button_Click(object sender, RoutedEventArgs e)
{
    string[] dummyArray = new string[] { "anyvalue" };

    Task[] tasks = dummyArray.Select(async x => await Method1Async()).ToArray();
    await Task.WhenAll(tasks);
}

or

private async void Button_Click(object sender, RoutedEventArgs e)
{
    string[] dummyArray = new string[] { "anyvalue" };

    Task[] tasks = dummyArray.Select(x => Method1Async()).ToArray();
    await Task.WhenAll(tasks);
}

Edit:

If you want to limit the number of parallel tasks then you can do this:

    public async Task Button_Click()
    {
        string[] servers = new string[] { "1", "2", "3", "4", "5" };

        var maxParallel = 3;
        var throttler = new SemaphoreSlim(initialCount: maxParallel);
        var tasks = servers.Select(async server =>
        {
            try
            {
                await throttler.WaitAsync();
                await Method1Async(server);
            }
            finally
            {
                throttler.Release();
            }
        });
        await Task.WhenAll(tasks);

        Console.WriteLine("Finished");
    }


问:
Component not rendering when calling this.setState()
I have a component which calling a method in componentDidMount.
This method fetches the data and updates state through this.setState(). But then nothing happens. State is updating, but component is not rendering.

There is the code:

```<code>import React from 'react';
import TimelineChart from './TimeLineChart/index.js';
import axios from 'axios';

class MoneyChart extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            chartData: [{ x: 0, y1: 0, y2: 0 }]
        };
      }
    componentDidMount() {
        this.fillData()
    }

  fillData = () => {
    let prepChart = [{ x: 0, y1: 0, y2: 0 }]
        axios.get('http://0.0.0.0:10003/stream')
        .then(res => {
            res.data.items[0].items.forEach(el => {
                prepChart.push({
                    x: el.date_time,
                    y1: el.total,
                    y2: 0

                })
            });
            this.update_state(prepChart);
        })
}
    update_state(prepChart) {
        this.setState ({
        chartData: prepChart
        },
        () => console.log(this.state.chartData)
        );
    }

    render () {
        return(<div>
            <TimelineChart height={800} data={this.state.chartData} titleMap={{ y1: 'Этот год', y2: 'Прошлый год' }} />,
        </div>)
    }
}

export default MoneyChart;
</code>```

Here is the TimelineChart code:

```<code>import React from 'react';
import { Chart, Tooltip, Geom, Legend, Axis } from 'bizcharts';
import DataSet from '@antv/data-set';
// import Slider from 'bizcharts-plugin-slider';

import styles from './index.less';

class TimelineChart extends React.Component {
  render() {
    const {
      title,
      height = 400,
      padding = [60, 20, 40, 40],
      titleMap = {
        y1: 'y1',
        y2: 'y2',
      },
      borderWidth = 2,
      data: sourceData,
    } = this.props;

    const data = Array.isArray(sourceData) ? sourceData : [{ x: 0, y1: 0, y2: 0 }];

    data.sort((a, b) => a.x - b.x);

    let max;
    if (data[0] && data[0].y1 && data[0].y2) {
      max = Math.max(
        [...data].sort((a, b) => b.y1 - a.y1)[0].y1,
        [...data].sort((a, b) => b.y2 - a.y2)[0].y2
      );
    }

    const ds = new DataSet({
      state: {
        start: data[0].x,
        end: data[data.length - 1].x,
      },
    });

    const dv = ds.createView();
    dv.source(data)
      .transform({
        type: 'filter',
        callback: obj => {
          const date = obj.x;
          return date <= ds.state.end && date >= ds.state.start;
        },
      })
      .transform({
        type: 'map',
        callback(row) {
          const newRow = { ...row };
          newRow[titleMap.y1] = row.y1;
          newRow[titleMap.y2] = row.y2;
          return newRow;
        },
      })
      .transform({
        type: 'fold',
        fields: [titleMap.y1, titleMap.y2], // 展开字段集
        key: 'key', // key字段
        value: 'value', // value字段
      });

    const timeScale = {
      type: 'time',
      tickInterval: 60 * 60 * 1000,
      mask: 'HH:mm',
      range: [0, 1],
    };

    const cols = {
      x: timeScale,
      value: {
        max,
        min: 0,
      },
    };

    return (
      <div className={styles.timelineChart} style={{ height: height + 30 }}>
        <div>
          {title && <h4>{title}</h4>}
          <Chart height={height} padding={padding} data={dv} scale={cols} forceFit>
            <Axis name="x" />
            <Tooltip />
            <Legend name="key" position="top" />
            <Geom type="line" position="x*value" size={borderWidth} color="key" />
          </Chart>
        </div>
      </div>
    );
  }
}

export default TimelineChart;
</code>```

I expect it to re-render after every state change. How can i achieve that?

答:
```<code>fillData = () => {
  let prepChart = [{ x: 0, y1: 0, y2: 0 }]
</code>```

Well it was a stupid mistake. Problem was in this second row.

I should change it to let prepChart = []. That's all.

Body:
I have a component which calling a method in componentDidMount.
This method fetches the data and updates state through this.setState(). But then nothing happens. State is updating, but component is not rendering.

There is the code:

import React from 'react';
import TimelineChart from './TimeLineChart/index.js';
import axios from 'axios';

class MoneyChart extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            chartData: [{ x: 0, y1: 0, y2: 0 }]
        };
      }
    componentDidMount() {
        this.fillData()
    }

  fillData = () => {
    let prepChart = [{ x: 0, y1: 0, y2: 0 }]
        axios.get('http://0.0.0.0:10003/stream')
        .then(res => {
            res.data.items[0].items.forEach(el => {
                prepChart.push({
                    x: el.date_time,
                    y1: el.total,
                    y2: 0

                })
            });
            this.update_state(prepChart);
        })
}
    update_state(prepChart) {
        this.setState ({
        chartData: prepChart
        },
        () => console.log(this.state.chartData)
        );
    }

    render () {
        return(

            <TimelineChart height={800} data={this.state.chartData} titleMap={{ y1: 'Этот год', y2: 'Прошлый год' }} />,

)
    }
}

export default MoneyChart;

Here is the TimelineChart code:

import React from 'react';
import { Chart, Tooltip, Geom, Legend, Axis } from 'bizcharts';
import DataSet from '@antv/data-set';
// import Slider from 'bizcharts-plugin-slider';

import styles from './index.less';

class TimelineChart extends React.Component {
  render() {
    const {
      title,
      height = 400,
      padding = [60, 20, 40, 40],
      titleMap = {
        y1: 'y1',
        y2: 'y2',
      },
      borderWidth = 2,
      data: sourceData,
    } = this.props;

    const data = Array.isArray(sourceData) ? sourceData : [{ x: 0, y1: 0, y2: 0 }];

    data.sort((a, b) => a.x - b.x);

    let max;
    if (data[0] && data[0].y1 && data[0].y2) {
      max = Math.max(
        [...data].sort((a, b) => b.y1 - a.y1)[0].y1,
        [...data].sort((a, b) => b.y2 - a.y2)[0].y2
      );
    }

    const ds = new DataSet({
      state: {
        start: data[0].x,
        end: data[data.length - 1].x,
      },
    });

    const dv = ds.createView();
    dv.source(data)
      .transform({
        type: 'filter',
        callback: obj => {
          const date = obj.x;
          return date <= ds.state.end && date >= ds.state.start;
        },
      })
      .transform({
        type: 'map',
        callback(row) {
          const newRow = { ...row };
          newRow[titleMap.y1] = row.y1;
          newRow[titleMap.y2] = row.y2;
          return newRow;
        },
      })
      .transform({
        type: 'fold',
        fields: [titleMap.y1, titleMap.y2], // 展开字段集
        key: 'key', // key字段
        value: 'value', // value字段
      });

    const timeScale = {
      type: 'time',
      tickInterval: 60 * 60 * 1000,
      mask: 'HH:mm',
      range: [0, 1],
    };

    const cols = {
      x: timeScale,
      value: {
        max,
        min: 0,
      },
    };

    return (

          {title &&
{title}
}
          <Chart height={height} padding={padding} data={dv} scale={cols} forceFit>
            <Axis name="x" />
            <Tooltip />
            <Legend name="key" position="top" />
            <Geom type="line" position="x*value" size={borderWidth} color="key" />
          </Chart>

    );
  }
}

export default TimelineChart;

I expect it to re-render after every state change. How can i achieve that?

Body:
fillData = () => {
  let prepChart = [{ x: 0, y1: 0, y2: 0 }]

Well it was a stupid mistake. Problem was in this second row.

I should change it to let prepChart = []. That's all.


问:
What is regular expression for "Test123"
I tried - "Test\d\d\d" and it works but problem is, String in expression could contain any number of digits so it could be "Test1" or "Test12" or "Test123". Hence it could be in range [000] to [999]</p>

答: If you mean "any number of digits", so that Test123456 is also viable, Test[0-9]+ or Test\d+ is another option.


问:
How do I make 2 lists correspond to each other?
I have 2 lists here:

```<code>list1 = [happy, sad, grumpy, mad]
list2 = [2, 5, 6, 9]
</code>```

I want to make it so that the numbers are assigned to the emotions? (happy is equal to 2, sad is equal to 5, etc). Ideally, I want to make it so you can compare items from list1, for example:

```<code>if happy > sad:
    print ("you are happy")
</code>```

I want to make this code as efficient as possible, so I do not want to separately assign each variable from list1 a number.

答:
You may use the standard enum module to accomplish it:

```<code>from enum import IntEnum

class Mood(IntEnum):
    happy = 2
    sad = 5
    grumpy = 6
    mad = 9

if Mood.happy > Mood.sad:         # Nonsense; do you mean "if yourmood < Mood.sad:"?
    print ("you are happy")
</code>```

Body:
I have 2 lists here:

list1 = [happy, sad, grumpy, mad]
list2 = [2, 5, 6, 9]

I want to make it so that the numbers are assigned to the emotions? (happy is equal to 2, sad is equal to 5, etc). Ideally, I want to make it so you can compare items from list1, for example:

if happy > sad:
    print ("you are happy")

I want to make this code as efficient as possible, so I do not want to separately assign each variable from list1 a number.

Body:
You may use the standard enum module to accomplish it:

from enum import IntEnum

class Mood(IntEnum):
    happy = 2
    sad = 5
    grumpy = 6
    mad = 9

if Mood.happy > Mood.sad:         # Nonsense; do you mean "if yourmood < Mood.sad:"?
    print ("you are happy")


问:
Statement-Level Read Consistency in various SQL/NoSQL DBs
Recently I was thinking about query consistency in various SQL and NoSQL databases. What happens, when I have a (long running) query and rows are inserted or updated while the query is running? A simple theoretic example:

Let’s assume the following query takes a long time:

```<code>SELECT SUM(salary) FROM emp;
</code>```

And while this query is running, another transaction does:

```<code>UPDATE emp SET salary = salary * 1.05 WHERE salary > 10000;
COMMIT;
</code>```

When the SUM query has read half of the updated employees before the update, and the other half after the update, I would get an inconsistent nonsense result. Does this phenomenon have a name? By definition, it is not really a phantom read, because just one query is involved.

How do various DBs handle this situation? I am especially interested in SQL Server, MongoDB, RavenDB and Azure Table Storage.

Oracle for example guarantees statement-level read consistency, which says that the data returned by a single query is committed and consistent for a single point in time.

UPDATE: SQL Server seems to only prevent this kind of problem when READ_COMMITTED_SNAPSHOT is set to ON.

答:
By default (read committed), you get your query and the update is blocked by the shared lock taken by your SELECT, until it completes.

If you enable Read Committed Snapshot Isolation Level (RCSI) as a database option, you continue to see the previous version of the data but the update isn't blocked.

Similarly, if the update was running first, when you have RSCI enabled, it doesn't block you, but you see the data before the update started.

RCSI is generally (but not 100% always) a good thing. I always design with it on. In Azure SQL DB, it's on by default.

Body:
Recently I was thinking about query consistency in various SQL and NoSQL databases. What happens, when I have a (long running) query and rows are inserted or updated while the query is running? A simple theoretic example:

Let’s assume the following query takes a long time:

SELECT SUM(salary) FROM emp;

And while this query is running, another transaction does:

UPDATE emp SET salary = salary * 1.05 WHERE salary > 10000;
COMMIT;

When the SUM query has read half of the updated employees before the update, and the other half after the update, I would get an inconsistent nonsense result. Does this phenomenon have a name? By definition, it is not really a phantom read, because just one query is involved.

How do various DBs handle this situation? I am especially interested in SQL Server, MongoDB, RavenDB and Azure Table Storage.

Oracle for example guarantees statement-level read consistency, which says that the data returned by a single query is committed and consistent for a single point in time.

UPDATE: SQL Server seems to only prevent this kind of problem when READ_COMMITTED_SNAPSHOT is set to ON.


问:
Cannot set the value of read-only property 'classDirectories' for task '...' of type org.gradle.testing.jacoco.tasks.JacocoReport
I just updated my Android Studio to 4.0 with a new version of Gradle, and I now have an error on my build.

Cannot set the value of read-only property 'classDirectories' for task ':app:testNameOfMyFlavorDebugUnitTestCoverage' of type org.gradle.testing.jacoco.tasks.JacocoReport.

It's been working fine so far, I don't know what to change to make it work again.

答:
Found the response here : https://docs.gradle.org/current/userguide/upgrading_version_5.html#other_deprecated_behaviors_and_apis

And here : Filter JaCoCo coverage reports with Gradle

For example, classDirectories is replaced by classDirectories.from


问:
TypeError: a bytes-like object is required, not 'RowProxy'
I am trying to implement a log in/sign up/log out element in my python web app. I am using Flask.  I am using bcrypt to hash and salt passwords but keep receiving this error: TypeError: a bytes-like object is required, not 'RowProxy'. passwords are definitely getting stored in a hash and salt. But will not allow users to log in.

```<code>@app.route("/searchPage", methods=['POST','GET'])
def loggingin():
    title = "Search"

    #get request form variables
    username = request.form.get('username')
    if db.execute("SELECT username FROM users WHERE username = :username",{"username": username}).rowcount == 0:
        return render_template("login.html", message="invalid username, please try again.")
    hashed_password = db.execute("SELECT username, password FROM users WHERE username = :username",{"username": username}).fetchone()
    if bcrypt.checkpw(request.form.get('password'), hashed_password):
        return render_template("searchPage.html", title=title)
    else:
        return render_template("login.html", message="Incorrect Password.")
</code>```

And my html is:

```<code>{% extends "nav.html" %}
{% block body %}
  <main>
    <h1>{{ message }}</h1>
    <h3>Log In </h3>
    <form action="{{ url_for('loggingin') }}" method="POST">
      <div class="form-group">
        <label>Username</label>
        <input class="form-control" type="text" name="username">
      </div>
      <div class="form-group">
        <label>Password</label>
        <input class="form-control" type="password" name="password">
      </div>
      <button class="btn btn-success" type="submit">Log In</button>
    </form>
  </main>

{% endblock %}
</code>```

答:
db.execute("SELECT username, password FROM users WHERE username = :username",{"username": username}).fetchone()['password']

Differnce was the ['password'] at end of this line. @mechanical_meat

Body:
I am trying to implement a log in/sign up/log out element in my python web app. I am using Flask.  I am using bcrypt to hash and salt passwords but keep receiving this error: TypeError: a bytes-like object is required, not 'RowProxy'. passwords are definitely getting stored in a hash and salt. But will not allow users to log in.

@app.route("/searchPage", methods=['POST','GET'])
def loggingin():
    title = "Search"

    #get request form variables
    username = request.form.get('username')
    if db.execute("SELECT username FROM users WHERE username = :username",{"username": username}).rowcount == 0:
        return render_template("login.html", message="invalid username, please try again.")
    hashed_password = db.execute("SELECT username, password FROM users WHERE username = :username",{"username": username}).fetchone()
    if bcrypt.checkpw(request.form.get('password'), hashed_password):
        return render_template("searchPage.html", title=title)
    else:
        return render_template("login.html", message="Incorrect Password.")

And my html is:

{% extends "nav.html" %}
{% block body %}

{{ message }}

Log In

    <form action="{{ url_for('loggingin') }}" method="POST">

        Username
        <input class="form-control" type="text" name="username">

        Password
        <input class="form-control" type="password" name="password">

      <button class="btn btn-success" type="submit">Log In</button>
    </form>

{% endblock %}


问:
How can I display a matplotlib Pie chart in an ipywidget out widget? I am using Jupyter Notebook, presently nothing gets displayed
My code result currently, but I want the Pie chart to show up under the Algo Tab

My code

```<code>out_algo = widgets.Output()
out_ht = widgets.Output()
outioi_trd = widgets.Output()
out_adv = widgets.Output()
out_fundexp = widgets.Output()
out_stratexp = widgets.Output()

tab = widgets.Tab(children = [out_algo,out_ht,outioi_trd,out_adv,out_fundexp,out_stratexp])
tab.set_title(0,'Algo Trades')
tab.set_title(1,'HT Trades')
tab.set_title(2,'IOI Trades')
tab.set_title(3,'Top 20 ADV Trades')
tab.set_title(4,'Fund Exposure')
tab.set_title(5,'Strategy Exposure')
display(tab)

broker_list_test = broker_list_test.set_index('Broker')
#drop columns not needed
broker_list_test = broker_list_test.drop(['Direction', 'Investment_Team', 'portfolio_name', 'full_name','Desk', 'trader', 'trade_date', 'pct_adv_1m', 'trade_qty', 'price'],axis=1)
#group by broker and USD notional sum
broker_list_test2 = broker_list_test.groupby('Broker')
broker_list_test3 = broker_list_test2.sum() #group by value per broker
broker_list_test3['USD_Notional']=broker_list_test3['USD_Notional'].astype('float')
#IF WE HAVE COMMA USE s.replace(',','.')
label = broker_list_test3.index.tolist() #pull out all index names as pie labels
data = broker_list_test3.values.tolist() # pie data
data = reduce(lambda x,y: x+y,data) #break list of lists into one list
data_float=[float(x) for x in data] #convert string to float
sum_algo=0
for x in data_float:
   sum_algo+=x
with out_algo:
    plt.pie(data_float,labels=label,autopct="%0.f%%",radius=2.4)
    plt.title("Algo Usage Notional Breakdown in USD\n"+'{:,.0f}'.format(sum_algo),position=(0.5,1.5))
    plt.show()
</code>```

In the above code snippet, If I dont use ipywidgets, I am able to generate the Pie chart fine, but if I want to put this pie chart inside a ipywidget Tab, I dont see any results, do you think there is another way to get around this? I am using Jupyter Notebook

答:
on plt.show

plt.show(fig) in the answer above from Wayne is now deprecated:

```<code>In [1]: import matplotlib.pyplot as plt

In [2]: fig = plt.figure()

In [3]: plt.show(fig)
<ipython-input-3-d1fd62acb551>:1: MatplotlibDeprecationWarning: Passing the
block parameter of show() positionally is deprecated since Matplotlib 3.1; the
parameter will become keyword-only in 3.3.
    plt.show(fig)
</code>```

plt.show(block=True) (or plt.show(block=False)) is the keyword-only call.

Therefore display(fig) seems to be the only valid option in the near future.

on %matplotlib inline

One could look at other options of matplotlib graphs embedding in notebooks:

%matplotlib notebook

note: display is usually not needed or gives 2 figure outputs

%matplotlib widget

note: requires ipympl, see matplotlib/ipympl on Github

Body:
My code result currently, but I want the Pie chart to show up under the Algo Tab

My code

out_algo = widgets.Output()
out_ht = widgets.Output()
outioi_trd = widgets.Output()
out_adv = widgets.Output()
out_fundexp = widgets.Output()
out_stratexp = widgets.Output()

tab = widgets.Tab(children = [out_algo,out_ht,outioi_trd,out_adv,out_fundexp,out_stratexp])
tab.set_title(0,'Algo Trades')
tab.set_title(1,'HT Trades')
tab.set_title(2,'IOI Trades')
tab.set_title(3,'Top 20 ADV Trades')
tab.set_title(4,'Fund Exposure')
tab.set_title(5,'Strategy Exposure')
display(tab)

broker_list_test = broker_list_test.set_index('Broker')
#drop columns not needed
broker_list_test = broker_list_test.drop(['Direction', 'Investment_Team', 'portfolio_name', 'full_name','Desk', 'trader', 'trade_date', 'pct_adv_1m', 'trade_qty', 'price'],axis=1)
#group by broker and USD notional sum
broker_list_test2 = broker_list_test.groupby('Broker')
broker_list_test3 = broker_list_test2.sum() #group by value per broker
broker_list_test3['USD_Notional']=broker_list_test3['USD_Notional'].astype('float')
#IF WE HAVE COMMA USE s.replace(',','.')
label = broker_list_test3.index.tolist() #pull out all index names as pie labels
data = broker_list_test3.values.tolist() # pie data
data = reduce(lambda x,y: x+y,data) #break list of lists into one list
data_float=[float(x) for x in data] #convert string to float
sum_algo=0
for x in data_float:
   sum_algo+=x
with out_algo:
    plt.pie(data_float,labels=label,autopct="%0.f%%",radius=2.4)
    plt.title("Algo Usage Notional Breakdown in USD\n"+'{:,.0f}'.format(sum_algo),position=(0.5,1.5))
    plt.show()

In the above code snippet, If I dont use ipywidgets, I am able to generate the Pie chart fine, but if I want to put this pie chart inside a ipywidget Tab, I dont see any results, do you think there is another way to get around this? I am using Jupyter Notebook

Body:
on plt.show

plt.show(fig) in the answer above from Wayne is now deprecated:

In [1]: import matplotlib.pyplot as plt

In [2]: fig = plt.figure()

In [3]: plt.show(fig)
<ipython-input-3-d1fd62acb551>:1: MatplotlibDeprecationWarning: Passing the
block parameter of show() positionally is deprecated since Matplotlib 3.1; the
parameter will become keyword-only in 3.3.
    plt.show(fig)

plt.show(block=True) (or plt.show(block=False)) is the keyword-only call.

Therefore display(fig) seems to be the only valid option in the near future.

on %matplotlib inline

One could look at other options of matplotlib graphs embedding in notebooks:

%matplotlib notebook

note: display is usually not needed or gives 2 figure outputs

%matplotlib widget

note: requires ipympl, see matplotlib/ipympl on Github


问:
How to read parameters from GET request in CherryPy?
How to read parameters from GET request in CherryPy ? I generate request from JQuery like

```<code>$.get(
    "http://localhost:8080/temp",
    "{a:10}",
    function(data) { alert(data); },
    "html"
);
</code>```

and I have class temp with @cherrypy.expose function index(self). How to extract data from GET request ?

答:
As virhilo mentioned, you can take named parameters in with your method.

Also, you can read cherrypy.request.params.

Body:
How to read parameters from GET request in CherryPy ? I generate request from JQuery like

$.get(
    "http://localhost:8080/temp",
    "{a:10}",
    function(data) { alert(data); },
    "html"
);

and I have class temp with @cherrypy.expose function index(self). How to extract data from GET request ?


问:
Read in CSV-file with multiple inputs and outputs
I have the following table and would like to find out the relationship between inputs and outputs in order to make predictions.

Later I want enter input values for heater_power, voltage, heater_efficiency and heater_mass and generate a prediction for the outputs.

In the table you can see that I have 4 input parameters and 3 output parameters.

table

I have created a code. The values for input and output are manually written to an array.

Import

```<code>import tensorflow as tf
import numpy as np
</code>```

Set up training data

```<code>inputMatrix = np.array([(100,230,0.95,100),
                        (200,245,0.99,121),
                        ( 40,250,0.91,123)],dtype=float)
outputMatrix = np.array([(120, 5,120),
                         (123,24,100),
                         (154, 3,121)],dtype=float)
for i,c in enumerate(inputMatrix):
print("{}Input Matrix={}Output Matrix".format(c,outputMatrix[i]))
</code>```

Create the Model

```<code>l0 = tf.keras.layers.Dense(units = 4, input_shape = [4])
l1 = tf.keras.layers.Dense(units = 64)
l2 = tf.keras.layers.Dense(units = 128)
l3 = tf.keras.layers.Dense(units = 3)

model = tf.keras.Sequential([l0,l1,l2,l3])
</code>```

Compile the Model

```<code>model.compile(loss='mean_squared_error', optimizer=tf.keras.optimizers.Adam(0.1))
</code>```

Train the model

```<code>history = model.fit(inputMatrix,outputMatrix,epochs=500,verbose=False)
print("Finished training the model!")
</code>```

Display training statistics

```<code>import matplotlib.pyplot as plt
plt.xlabel('Epoch Number')
plt.ylabel('Loss Magnitude')
plt.plot(history.history['loss'])
</code>```

Use the model to predict values

```<code>print(model.predict(np.array([120,260,0.98,110]).reshape(1,4)))
</code>```

I now want to read the table automatically from a csv file. The data should be separated according to input and output and read in.

How do I do this? Does it make sense to work with arrays here or are there better possibilities?

I have some doubts that my approach is basically correct. My code seems to be so short.   Or do I have to choose a different approach for my problem?

答:
You need to load the DataFrame using MultiIndex since you are having both Input, Output, and all the Features in different levels.

Below is the code to do so, I have used column names like A,B,C etc, change it according to your data.

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

index = pd.MultiIndex.from_tuples([("Input","B"),("Input","C"),("Input","D"),("Input","E"),("Output","F"),("Output","G"),("Output","H")])
df = pd.read_csv("sample_csv.csv",header=[0,1],index_col=0)
df.columns = index
</code>```

df:

df.columns

```<code>MultiIndex([( 'Input', 'B'),
            ( 'Input', 'C'),
            ( 'Input', 'D'),
            ( 'Input', 'E'),
            ('Output', 'F'),
            ('Output', 'G'),
            ('Output', 'H')],
           )
input_data = df[[( 'Input', 'B'),
            ( 'Input', 'C'),
            ( 'Input', 'D'),
            ( 'Input', 'E')]].values

input_data = list(map(lambda x:tuple(x),input_data))

#Input_data

[(100.0, 230.0, 0.95, 100.0),
 (200.0, 245.0, 0.99, 121.0),
 (40.0, 250.0, 0.91, 123.0)]

output_data = df[[('Output', 'F'),
            ('Output', 'G'),
            ('Output', 'H')]].values

output_data = list(map(lambda x:tuple(x),output_data))

#Ouput_data

[(120, 5, 120), (123, 24, 100), (154, 3, 121)]
</code>```

Body:
I have the following table and would like to find out the relationship between inputs and outputs in order to make predictions.

Later I want enter input values for heater_power, voltage, heater_efficiency and heater_mass and generate a prediction for the outputs.

In the table you can see that I have 4 input parameters and 3 output parameters.

table

I have created a code. The values for input and output are manually written to an array.

Import

import tensorflow as tf
import numpy as np

Set up training data

inputMatrix = np.array([(100,230,0.95,100),
                        (200,245,0.99,121),
                        ( 40,250,0.91,123)],dtype=float)
outputMatrix = np.array([(120, 5,120),
                         (123,24,100),
                         (154, 3,121)],dtype=float)
for i,c in enumerate(inputMatrix):
print("{}Input Matrix={}Output Matrix".format(c,outputMatrix[i]))

Create the Model

l0 = tf.keras.layers.Dense(units = 4, input_shape = [4])
l1 = tf.keras.layers.Dense(units = 64)
l2 = tf.keras.layers.Dense(units = 128)
l3 = tf.keras.layers.Dense(units = 3)

model = tf.keras.Sequential([l0,l1,l2,l3])

Compile the Model

model.compile(loss='mean_squared_error', optimizer=tf.keras.optimizers.Adam(0.1))

Train the model

history = model.fit(inputMatrix,outputMatrix,epochs=500,verbose=False)
print("Finished training the model!")

Display training statistics

import matplotlib.pyplot as plt
plt.xlabel('Epoch Number')
plt.ylabel('Loss Magnitude')
plt.plot(history.history['loss'])

Use the model to predict values

print(model.predict(np.array([120,260,0.98,110]).reshape(1,4)))

I now want to read the table automatically from a csv file. The data should be separated according to input and output and read in.

How do I do this? Does it make sense to work with arrays here or are there better possibilities?

I have some doubts that my approach is basically correct. My code seems to be so short.   Or do I have to choose a different approach for my problem?

Body:
You need to load the DataFrame using MultiIndex since you are having both Input, Output, and all the Features in different levels.

Below is the code to do so, I have used column names like A,B,C etc, change it according to your data.

import pandas as pd
import numpy as np

index = pd.MultiIndex.from_tuples([("Input","B"),("Input","C"),("Input","D"),("Input","E"),("Output","F"),("Output","G"),("Output","H")])
df = pd.read_csv("sample_csv.csv",header=[0,1],index_col=0)
df.columns = index

df:

df.columns

MultiIndex([( 'Input', 'B'),
            ( 'Input', 'C'),
            ( 'Input', 'D'),
            ( 'Input', 'E'),
            ('Output', 'F'),
            ('Output', 'G'),
            ('Output', 'H')],
           )
input_data = df[[( 'Input', 'B'),
            ( 'Input', 'C'),
            ( 'Input', 'D'),
            ( 'Input', 'E')]].values

input_data = list(map(lambda x:tuple(x),input_data))

#Input_data

[(100.0, 230.0, 0.95, 100.0),
 (200.0, 245.0, 0.99, 121.0),
 (40.0, 250.0, 0.91, 123.0)]

output_data = df[[('Output', 'F'),
            ('Output', 'G'),
            ('Output', 'H')]].values

output_data = list(map(lambda x:tuple(x),output_data))

#Ouput_data

[(120, 5, 120), (123, 24, 100), (154, 3, 121)]


问:
Access state of namespaced module inside router
I'm having trouble accessing the state of one of my namespaced modules inside my router. I imported my store

```<code>import store from "../store"
</code>```

and acessing my getters like this works fine

```<code>let loggedIn = store.getters['auth/isLoggedIn'];
</code>```

but this only gives me back undefined:

```<code>let loggedIn = store.state['auth/user'];
</code>```

How do I access my store?

答:
For direct access to store state:</p>

```<code>let loggedIn = store.state.auth.user;
</code>```

Body:
I'm having trouble accessing the state of one of my namespaced modules inside my router. I imported my store

import store from "../store"

and acessing my getters like this works fine

let loggedIn = store.getters['auth/isLoggedIn'];

but this only gives me back undefined:

let loggedIn = store.state['auth/user'];

How do I access my store?

Body:
For direct access to store state:

let loggedIn = store.state.auth.user;


问:
Random Iteration order from Set.of(...)
Hi I am learning the new features of Java 9  and was reading new Collections API's . I am not sure why I am getting random iteration order while creating an immutable set from two instances of JDK .

```<code>JDK 1: jshell> Set.of("a","b","c")
       $96 ==> [a, b, c]

JDK2 : jshell> Set.of("a","b","c")
       $68 ==> [a, c, b]
</code>```

I don't see the same for List.of() overloads.Can I do some customisation like changing some system properties to guarantee a consistent ordering here ?

答:
Arbitrary Set implementations have no ordering, so any iteration order encountered when iterating over the elements of a Set returned by Set.of() is correct, and you shouldn't rely on it. It's an implementation detail, and different JDK versions can produce different iteration orders.

If you require a consistent ordering, either don't use Sets, or use Sets that guarantee order, such as TreeSet.

List.of() has a different behavior, since Lists have ordering. In the List returned by List.of("a","b","c"), "a" will always be the first element, "b" the second element and "c" the third.

Title: Random Iteration order from Set.of(...)

Body:
Hi I am learning the new features of Java 9  and was reading new Collections API's . I am not sure why I am getting random iteration order while creating an immutable set from two instances of JDK .

JDK 1: jshell> Set.of("a","b","c")
       $96 ==> [a, b, c]

JDK2 : jshell> Set.of("a","b","c")
       $68 ==> [a, c, b]

I don't see the same for List.of() overloads.Can I do some customisation like changing some system properties to guarantee a consistent ordering here ?


问:
How to make a API call using requests in Python
I'm a newbie in python and I'm dealing with this problem, I want to make an API POST request by using Python but I can't send a request with this. Can anyone help me figure it out? This is what I have:

```<code>import requests

headers = {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
data =
{
    "token": "TokenStaging",
    "OrderCode": "23FNQY46"
}
r = requests.post('https://dev-online-gateway.ghn.vn/apiv3-api/api/v1/apiv3/OrderInfo',
    headers=headers, data=data)
</code>```

API document link: https://api.ghn.vn/home/docs/detail?id=29#parameter-examples-APIV3-OrderInfo-1_0_0-0

答:
After some research and testing, i finally can call that API with this :

```<code>import requests

r = requests.post('https://console.ghn.vn/api/v1/apiv3/OrderInfo',
 json={
  "token": "TokenStaging",
  "OrderCode": "23FNQY46"
})
</code>```

Thank you guys for all your support

Body:
I'm a newbie in python and I'm dealing with this problem, I want to make an API POST request by using Python but I can't send a request with this. Can anyone help me figure it out? This is what I have:

import requests

headers = {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
data =
{
    "token": "TokenStaging",
    "OrderCode": "23FNQY46"
}
r = requests.post('https://dev-online-gateway.ghn.vn/apiv3-api/api/v1/apiv3/OrderInfo',
    headers=headers, data=data)

API document link: https://api.ghn.vn/home/docs/detail?id=29#parameter-examples-APIV3-OrderInfo-1_0_0-0

Body:
After some research and testing, i finally can call that API with this :

import requests

r = requests.post('https://console.ghn.vn/api/v1/apiv3/OrderInfo',
 json={
  "token": "TokenStaging",
  "OrderCode": "23FNQY46"
})

Thank you guys for all your support


问:
.htaccess redirect leads to all browsers saying "privacy error, connection not private"
So I want to redirect one of my websites including every single page to the root of another one. I did so by doing this:

```<code>Options +FollowSymLinks
RewriteEngine on
RewriteRule (.*) https://www.newdomain.com/ [R=301,L]
</code>```

Now when I go to any link of my old website, I get this security warning in the  browser:

NET::ERR_CERT_AUTHORITY_INVALID

  Attackers might be trying to steal your information from www.olddomain.com (for example, passwords, messages or credit cards).

The old website was http and the new one is https if that might help?

答:
Try this : </p>

```<code>RewriteOptions inherit
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteBase /
RewriteRule ^index</span>.php$ - [L]
</IfModule>

RewriteEngine On
RewriteBase /

# Redirect Trailing Slashes...
RewriteRule ^(.*)/$ /$1 [L,R=301]

# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</code>```

Body:
So I want to redirect one of my websites including every single page to the root of another one. I did so by doing this:

Options +FollowSymLinks
RewriteEngine on
RewriteRule (.*) https://www.newdomain.com/ [R=301,L]

Now when I go to any link of my old website, I get this security warning in the  browser:

NET::ERR_CERT_AUTHORITY_INVALID

  Attackers might be trying to steal your information from www.olddomain.com (for example, passwords, messages or credit cards).

The old website was http and the new one is https if that might help?

Body:
Try this :

RewriteOptions inherit
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteBase /
RewriteRule ^index</span>.php$ - [L]
</IfModule>

RewriteEngine On
RewriteBase /

# Redirect Trailing Slashes...
RewriteRule ^(.*)/$ /$1 [L,R=301]

# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]


问:
How to globally catch unhandled Future errors?
Best practice is of course to always attach an error handler to a Future using catchError() (or using await and try/catch). But suppose I forgot, or suppose that this error is serious enough that we want it to crash the entire application (as we could do with synchronous exceptions), or that I want to log the error, or report it to some service like Crashlytics to make me aware of my sins.

Dart's Futures are practically the same as JavaScript's Promises. In NodeJS, we can attach a handler to the global unhandledRejection event to add custom behaviour.

Does Dart offer something similar? I looked through the async and Future documentation, but couldn't find anything relevant.

答:
Take a look at the runZonedGuarded static method. It will executing a given method in its own Zone which makes it possible to attach a method to handle any uncaught errors.

I have made a simple example here which shows what happens if a async error are throw without any handling of the error:

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

void main() {
  runZonedGuarded(program, errorHandler);
}

Future<void> program() async {
  final file = File('missing_file.txt');
  await file.openRead().forEach(print);
}

void errorHandler(Object error, StackTrace stack) {
  print('OH NO AN ERROR: $error');
}
</code>```

Which returns:

OH NO AN ERROR: FileSystemException: Cannot open file, path = 'missing_file.txt'...
```

Body:
Take a look at the runZonedGuarded static method. It will executing a given method in its own Zone which makes it possible to attach a method to handle any uncaught errors.

I have made a simple example here which shows what happens if a async error are throw without any handling of the error:

import 'dart:async';
import 'dart:io';

void main() {
  runZonedGuarded(program, errorHandler);
}

Future<void> program() async {
  final file = File('missing_file.txt');
  await file.openRead().forEach(print);
}

void errorHandler(Object error, StackTrace stack) {
  print('OH NO AN ERROR: $error');
}

Which returns:

OH NO AN ERROR: FileSystemException: Cannot open file, path = 'missing_file.txt'...


问:
Combined form input values in component state
Need help for combining two inputs values at one state key.
When make change at Arrival date input can read the new value at data.arrivalDate and respectively when make change to Arrival time input can read it's value from data.arrivalTime.

What I want to do is, when click on the Submit button - before send the data - to combine results from both inputs in a single state field arrivesAt so to recieve string like 2020-01-01/09:05, so I don't need the old state keys data.fromDate & data.fromTime in my data object at all.

Here goes my code:
https://codesandbox.io/s/blue-tdd-xesmm?file=/src/App.js

答:
On submit action in handleSubmit, you can just set state with arrivalAt value using template literals like

```<code>  const handleSubmit = event => {
    event.preventDefault();
    setData(prev => ({
      arriveAt: `${prev.fromDate}/${prev.fromTime}`,
    }));
  };
</code>```

Body:
On submit action in handleSubmit, you can just set state with arrivalAt value using template literals like

  const handleSubmit = event => {
    event.preventDefault();
    setData(prev => ({
      arriveAt: `${prev.fromDate}/${prev.fromTime}`,
    }));
  };


问:
'Concatenate' a struct into a char array
I have a struct that's used in my internet application, which looks like:

```<code>struct query {
     ushort trans_id;
     ushort flags;
     ushort opcode;
     ushort content_length;
     char content[512];
};
</code>```

Basically, I'm just trying to take this structure and turn it into a "packet" to be sent. It must have the corresponding length and everything. So; if I could I would have like:
struct query q;

```<code>q.trans_id = 0x5544;
q.flags = 0x0000;
q.opcode = 0x0010;
q.content_length = 0x0001;
q.content[0] = '\0'; //I would want my packet to end up looking like this, when outputted to the socket:
//\x55\x44\x00\x00\x00\x10\x00\x01\x00
//and yes, it's going to be stored in a char buffer, but I'm not using any functions that will trim off any of the things past the null!
</code>```

I feel like it's a relatively simple question that can probably be answered by casting my data types, but I think it's a bit harder than that.

I also did try using sprintf, but it would turn my nulls into actual 0s, so 0x0000 would become 2 '0' ASCII characters!

答:
You can indeed simply cast the pointer to your struct to a char *, such as:

```<code>#include <stdlib.h> /* for size_t */

....

struct query q;
/* fill in the struct ... */
char *packet = (char *)(&q);
size_t packet_size = sizeof(struct query);
</code>```

If you want the packet size to trim the content of the query struct, you'll have to calculate the difference (by using strnlen for example on the content and subtracting the difference)

EDIT: Alternatively for trimming you can do:

```<code>int packet_size = (&(q.content[0]) + strnlen(q.content, 512)) - &q;
</code>```

Body:
I have a struct that's used in my internet application, which looks like:

struct query {
     ushort trans_id;
     ushort flags;
     ushort opcode;
     ushort content_length;
     char content[512];
};

Basically, I'm just trying to take this structure and turn it into a "packet" to be sent. It must have the corresponding length and everything. So; if I could I would have like:
struct query q;

q.trans_id = 0x5544;
q.flags = 0x0000;
q.opcode = 0x0010;
q.content_length = 0x0001;
q.content[0] = '\0'; //I would want my packet to end up looking like this, when outputted to the socket:
//\x55\x44\x00\x00\x00\x10\x00\x01\x00
//and yes, it's going to be stored in a char buffer, but I'm not using any functions that will trim off any of the things past the null!

I feel like it's a relatively simple question that can probably be answered by casting my data types, but I think it's a bit harder than that.

I also did try using sprintf, but it would turn my nulls into actual 0s, so 0x0000 would become 2 '0' ASCII characters!

Body:
You can indeed simply cast the pointer to your struct to a char *, such as:

#include <stdlib.h> /* for size_t */

....

struct query q;
/* fill in the struct ... */
char *packet = (char *)(&q);
size_t packet_size = sizeof(struct query);

If you want the packet size to trim the content of the query struct, you'll have to calculate the difference (by using strnlen for example on the content and subtracting the difference)

EDIT: Alternatively for trimming you can do:

int packet_size = (&(q.content[0]) + strnlen(q.content, 512)) - &q;


问:
how to configure convertrecord processor in Apache nifi so that it convert JSON to AVRO format
not able to figure out how to configure this processor to convert the incoming JSON twitter data to Avro to Put that data into a hive table

plz help

Thank you in advance.

答:
@RishiPandey

ConvertJsonToAvro is the processor you need.


问:
I have a error in my e-commerce website, "'X' is not defined no-undef"
Error:

```<code>./src/reducers/productReducers.js
  Line 3:10:  'PRODUCT_LIST_REQUEST' is not defined  no-undef
  Line 5:10:  'PRODUCT_LIST_SUCCESS' is not defined  no-undef
  Line 7:10:  'PRODUCT_LIST_FAIL' is not defined     no-undef
</code>```

And my code down below

```<code>function productListReducer(state = { products: [] }, action) {
  switch (action.type) {
    case PRODUCT_LIST_REQUEST:
      return { loading: true, products: [] };
    case PRODUCT_LIST_SUCCESS:
      return { loading: false, products: action.payload };
    case PRODUCT_LIST_FAIL:
      return { loading: false, error: action.payload };
    default:
      return state;
  }
}
export { productListReducer };
</code>```

答:
did you import your types? like this

types.js

export TYPE_1 = "TYPE_1"
export TYPE_2 = "TYPE_2"

Reducers.js:

import {TYPE_1, TYPE_1}

...your codes

Body:
Error:

./src/reducers/productReducers.js
  Line 3:10:  'PRODUCT_LIST_REQUEST' is not defined  no-undef
  Line 5:10:  'PRODUCT_LIST_SUCCESS' is not defined  no-undef
  Line 7:10:  'PRODUCT_LIST_FAIL' is not defined     no-undef

And my code down below

function productListReducer(state = { products: [] }, action) {
  switch (action.type) {
    case PRODUCT_LIST_REQUEST:
      return { loading: true, products: [] };
    case PRODUCT_LIST_SUCCESS:
      return { loading: false, products: action.payload };
    case PRODUCT_LIST_FAIL:
      return { loading: false, error: action.payload };
    default:
      return state;
  }
}
export { productListReducer };


问:
Result type of a polyvariadic function in haskell
While studying polyvariadic functions in Haskell I stumbled across the following SO questions:

How to create a polyvariadic haskell function?

Haskell, polyvariadic function and type inference

and thought I will give it a try by implementing a function which takes a variable number of strings and concatenates/merges them into a single string:

{-# LANGUAGE FlexibleInstances #-}

class MergeStrings r where
    merge :: String -> r
instance MergeStrings String where
    merge = id
instance (MergeStrings r) => MergeStrings (String -> r) where
    merge acc = merge . (acc ++)

```

<p>This works so far if I call merge with at least one string argument and if I provide the final type.</p>

<pre class="lang-hs prettyprint-override"><code>foo :: String
foo = merge "a" "b" "c"
</code>```

Omitting the final type results in an error, i.e., compiling the following

bar = merge "a" "b" "c"
```

<p>results in</p>

```test.hs:12:7: error:
    • Ambiguous type variable ‘t0’ arising from a use of ‘merge’
      prevents the constraint ‘(MergeStrings t0)’ from being solved.
      Relevant bindings include bar :: t0 (bound at test.hs:12:1)
      Probable fix: use a type annotation to specify what ‘t0’ should be.
      These potential instances exist:
        instance MergeStrings r => MergeStrings (String -> r)
          -- Defined at test.hs:6:10
        instance MergeStrings String -- Defined at test.hs:4:10
    • In the expression: merge "a" "b" "c"
      In an equation for ‘bar’: bar = merge "a" "b" "c"
   |
12 | bar = merge "a" "b" "c"
   |
```

<p>The error message makes perfect sense since I could easily come up with, for example</p>

```bar :: String -> String
bar = merge "a" "b" "c"

baz = bar "d"
```

rendering bar not into a single string but into a function which takes and returns one string.

Is there a way to tell Haskell that the result type must be of type String? For example, Text.Printf.printf "hello world" evaluates to type String without explicitly defining.

答:
printf works without type annotation because of type defaulting in GHCi. The same mechanism that allows you to eval show $ 1 + 2 without specifying concrete types.

GHCi tries to evaluate expressions of type IO a, so you just need to add appropriate instance for MergeStrings:

```<code>instance (a ~ ()) => MergeStrings (IO a) where
    merge = putStrLn
</code>```

Body:
While studying polyvariadic functions in Haskell I stumbled across the following SO questions:

How to create a polyvariadic haskell function?

Haskell, polyvariadic function and type inference

and thought I will give it a try by implementing a function which takes a variable number of strings and concatenates/merges them into a single string:

{-# LANGUAGE FlexibleInstances #-}

class MergeStrings r where
    merge :: String -> r
instance MergeStrings String where
    merge = id
instance (MergeStrings r) => MergeStrings (String -> r) where
    merge acc = merge . (acc ++)

This works so far if I call merge with at least one string argument and if I provide the final type.

foo :: String
foo = merge "a" "b" "c"

Omitting the final type results in an error, i.e., compiling the following

bar = merge "a" "b" "c"

results in

test.hs:12:7: error:
    • Ambiguous type variable ‘t0’ arising from a use of ‘merge’
      prevents the constraint ‘(MergeStrings t0)’ from being solved.
      Relevant bindings include bar :: t0 (bound at test.hs:12:1)
      Probable fix: use a type annotation to specify what ‘t0’ should be.
      These potential instances exist:
        instance MergeStrings r => MergeStrings (String -> r)
          -- Defined at test.hs:6:10
        instance MergeStrings String -- Defined at test.hs:4:10
    • In the expression: merge "a" "b" "c"
      In an equation for ‘bar’: bar = merge "a" "b" "c"
   |
12 | bar = merge "a" "b" "c"
   |

The error message makes perfect sense since I could easily come up with, for example

bar :: String -> String
bar = merge "a" "b" "c"

baz = bar "d"

rendering bar not into a single string but into a function which takes and returns one string.

Is there a way to tell Haskell that the result type must be of type String? For example, Text.Printf.printf "hello world" evaluates to type String without explicitly defining.

Body:
printf works without type annotation because of type defaulting in GHCi. The same mechanism that allows you to eval show $ 1 + 2 without specifying concrete types.

GHCi tries to evaluate expressions of type IO a, so you just need to add appropriate instance for MergeStrings:

instance (a ~ ()) => MergeStrings (IO a) where
    merge = putStrLn


问:
In Excel VBA, how can I test if an Excel.Range object variable loses its reference without raising runtime error 424..?
In Excel VBA, if a variable is Excel.Range, and the range it refers to is deleted, it loses its reference. Any attempt to access the variable results in Runtime Error 424: object required.

```<code>Dim rng As Range
Set rng = Sheet1Range("A1")
Sheet1.Rows(1).Delete       'Range has been deleted.
Debug.Print rng.Address()   'Any access attempt now raises runtime error 424.
</code>```

Is there a way to test for this state of "lost reference" without an error handler..?

Testing Nothing, Vartype(), and Typename() were all not useful because the variable is still a Range. I literally read through all of Excel.Application in the Object browser, but found nothing. Perhaps there's something I'm overlooking..? Such as one of those strange vestigial functions from prehistoric versions of Excel, like ExecuteExcel4Macro()..?

I've searched Google for the answer to this question, but didn't find anything helpful.

EDIT:

Some have asked why I'm trying to avoid an error handler. This is my normal programming philosophy for a couple reasons:

I do recognize that sometimes an error handler is the quickest way, or the only way. But it's not the most elegant way. It just seems, well...crude to me. It's like the difference between white-washing a picket fence and painting a portrait of my cat. =-)

The other reason I avoid error handlers is education. Many times when searching for an alternative, I'll discover properties, procedures, objects, or even entire libraries that I never knew before. And in doing so I find more armor with which to bulletproof my code.

答:
Just in case someone needs a solution for this problem and doesn't mind using the error handler.</p>

```<code>Option Explicit

Public Sub Example()
    Dim rng1 As Range, rng2 As Range

    Set rng1 = Range("A1")
    Set rng2 = Range("A2")
    ActiveSheet.Rows(1).Delete ' rng1 will loose its reference

    Debug.Print "rng1 has reference? : " & RangeHasReference(rng1)
    Debug.Print "rng2 has reference? : " & RangeHasReference(rng2)
End Sub

Private Function RangeHasReference(rng As Range) As Boolean
    Dim Creator As Long
    On Error Resume Next
    Creator = rng.Creator ' try access some property
    RangeHasReference = (Err.Number <> 424)
End Function
</code>```

Body:
In Excel VBA, if a variable is Excel.Range, and the range it refers to is deleted, it loses its reference. Any attempt to access the variable results in Runtime Error 424: object required.

Dim rng As Range
Set rng = Sheet1Range("A1")
Sheet1.Rows(1).Delete       'Range has been deleted.
Debug.Print rng.Address()   'Any access attempt now raises runtime error 424.

Is there a way to test for this state of "lost reference" without an error handler..?

Testing Nothing, Vartype(), and Typename() were all not useful because the variable is still a Range. I literally read through all of Excel.Application in the Object browser, but found nothing. Perhaps there's something I'm overlooking..? Such as one of those strange vestigial functions from prehistoric versions of Excel, like ExecuteExcel4Macro()..?

I've searched Google for the answer to this question, but didn't find anything helpful.

EDIT:

Some have asked why I'm trying to avoid an error handler. This is my normal programming philosophy for a couple reasons:

I do recognize that sometimes an error handler is the quickest way, or the only way. But it's not the most elegant way. It just seems, well...crude to me. It's like the difference between white-washing a picket fence and painting a portrait of my cat. =-)

The other reason I avoid error handlers is education. Many times when searching for an alternative, I'll discover properties, procedures, objects, or even entire libraries that I never knew before. And in doing so I find more armor with which to bulletproof my code.

Body:
Just in case someone needs a solution for this problem and doesn't mind using the error handler.

Option Explicit

Public Sub Example()
    Dim rng1 As Range, rng2 As Range

    Set rng1 = Range("A1")
    Set rng2 = Range("A2")
    ActiveSheet.Rows(1).Delete ' rng1 will loose its reference

    Debug.Print "rng1 has reference? : " & RangeHasReference(rng1)
    Debug.Print "rng2 has reference? : " & RangeHasReference(rng2)
End Sub

Private Function RangeHasReference(rng As Range) As Boolean
    Dim Creator As Long
    On Error Resume Next
    Creator = rng.Creator ' try access some property
    RangeHasReference = (Err.Number <> 424)
End Function


问:
How to restart a sockets program?
I need my server to stay connected to the server.  Does anyone know how to do this?  Or post links tutorials anything?

Also it says when it restarts 'could not accept client' so how would I clear everything and make it accept it?

答:
Server code:

For your server side code, do a loop wrapping the accept call.  For the accepted socket that is created create a new thread, so that the next accept will be called right away.

On server startup you may also want to use the SO_REUSEADDR flag.  That way if you had a crash, or even a fast restart of the program, then your server will be able to use the same port again without a problem.

Client code:

For your client code you would just check for a socket error and if that occurs just establish a new connection.

Other resources:

Beej's guide to network programming is a great resource for learning socket programming.

Frostbytes.com also has a great tutorial on socket programming.

If you want something more in depth, check out Unix Network Programming 3rd Edition by W. Richard Stevens.

Other options:

Instead of plain bsd-style sockets, you could also try using boost asio for easier socket programming.  You could check out their examples page.

ContentLicense: CC BY-SA 2.5

Title: How to restart a sockets program?

LastEditorDisplayName: Brian R. Bondy

OwnerDisplayName: Brian R. Bondy

LastEditorDisplayName: Jonathan Leffler


问:
Using constants defined in header file
I'm trying to translate a X11/OpenGL demo into Java and I'm not sure how to use the constants OpenGL defines.  The only method I can think of is digging into the OpenGL headers and copying the constants to my program but is that the proper way to do it?  I imagine that there is no guarantee that those constants will be the same in a different environment.</p>

答:
I can't use this method to do what I want because I'm actually trying to get a preprocessor definition but it does answer my question.

You use the NativeLibrary class like so.

NativeLibrary library = NativeLibrary.getInstance("LIBRARY_NAME");
library.getGlobalVariableAddress("VARIABLE_NAME");

Edit: I feel like I should admit that it does not make sense to access a preprocessor definition, I ended up just copying the definitions into my program.

Title: Using constants defined in header file


问:
How to fetch multiple data from mysql database with only one query?
I am working on a PHP project, I have a table Attendee with profession column in it, I am trying to make a chart of the percentage of profession of the attendees, select count(*) from Attendee where Profession = 'Nurse' for example, but I have like 10 professions so is there a better way to do it?

答:
Look at the group by SQL functionality.  E.g.</p>

```<code>select Profession , count(*) num
from Attendee
group by Profession;
</code>```

Body:
Look at the group by SQL functionality.  E.g.

select Profession , count(*) num
from Attendee
group by Profession;


问:
Getting Error While Using request.getRealPath("/") in JSP Page
I am trying to use the request.getRealPath("/") to get the Path for the resource files in JSP page. But i get below error when i try to run the page in Eclipse.

```<code><jsp:setProperty name="LIILLog" property="configPath" value="<%=request.getRealPath("/")%>"/>
</code>```

The error which i  get is as below:

```<code>May 31, 2020 7:58:03 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [jsp] in context with path [/LHC] threw exception [/lhc_admin_login.jsp (line: [28], column: [64]) Attribute value [request.getRealPath("/")] is quoted with ["] which must be escaped when used within the value] with root cause
org.apache.jasper.JasperException: /lhc_admin_login.jsp (line: [28], column: [64]) Attribute value [request.getRealPath("/")] is quoted with ["] which must be escaped when used within the value
    at org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:41)
    at org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:291)
    at org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.java:97)
    at org.apache.jasper.compiler.Parser.parseAttributeValue(Parser.java:303)
    at org.apache.jasper.compiler.Parser.parseAttribute(Parser.java:247)
    at org.apache.jasper.compiler.Parser.parseAttributes(Parser.java:168)
</code>```

I am using a Maven Project in Eclipse and Tomcat 8.5 server.

答:
Your problem is exactly what the error says, you need to escape the quotes or use single quotes:

Do this:

value='<%=request.getRealPath("/")%>'

or (don't) do this (it is ugly):

value="<%=request.getRealPath(\"/\")%>"

Body:
I am trying to use the request.getRealPath("/") to get the Path for the resource files in JSP page. But i get below error when i try to run the page in Eclipse.

<jsp:setProperty name="LIILLog" property="configPath" value="<%=request.getRealPath("/")%>"/>

The error which i  get is as below:

May 31, 2020 7:58:03 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [jsp] in context with path [/LHC] threw exception [/lhc_admin_login.jsp (line: [28], column: [64]) Attribute value [request.getRealPath("/")] is quoted with ["] which must be escaped when used within the value] with root cause
org.apache.jasper.JasperException: /lhc_admin_login.jsp (line: [28], column: [64]) Attribute value [request.getRealPath("/")] is quoted with ["] which must be escaped when used within the value
    at org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:41)
    at org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:291)
    at org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.java:97)
    at org.apache.jasper.compiler.Parser.parseAttributeValue(Parser.java:303)
    at org.apache.jasper.compiler.Parser.parseAttribute(Parser.java:247)
    at org.apache.jasper.compiler.Parser.parseAttributes(Parser.java:168)

I am using a Maven Project in Eclipse and Tomcat 8.5 server.