问:
Example for tf. group_by_reducer?
Can someone show me an example of tf.data.experimental.group_by_reducer? I find the documentation tricky and couldn't understand fully.

How can I use it for calculating average?

答:
Say we are provided with a dataset with ['ids', 'features'] and we want to group the data by adding 'features' corresponding to same 'ids'. We can use tf.group_by_reducer(key_func, reducer) to achieve this.

Raw data

```<code>ids | features
--------------
1   | 1
2   | 2.2
3   | 7
1   | 3.0
2   | 2
3   | 3
</code>```

Desired data

```<code>ids | features
--------------
1   | 4
2   | 4.2
3   | 10
</code>```

TensorFlow Code:

```<code>import tensorflow as tf
tf.enable_eager_execution()

ids = [1, 2, 3, 1, 2, 3]
features = [1, 2.2, 7, 3.0, 2, 3]

# Define reducer
# Reducer requires 3 functions - init_func, reduce_func, finalize_func.
# init_func - to define initial value
# reducer_func - operation to perform on values with same key
# finalize_func - value to return in the end.
def init_func(_):
    return 0.0

def reduce_func(state, value):
    return state + value['features']

def finalize_func(state):
    return state

reducer = tf.contrib.data.Reducer(init_func, reduce_func, finalize_func)

# Group by reducer
# Group the data by id
def key_f(row):
return tf.to_int64(row['ids'])

t = tf.contrib.data.group_by_reducer(
        key_func = key_f,
        reducer = reducer)

ds = tf.data.Dataset.from_tensor_slices({'ids':ids, 'features' : features})
ds = ds.apply(t)
ds = ds.batch(6)

iterator = ds.make_one_shot_iterator()
data = iterator.get_next()
print(data)
</code>```

Consider ids == 1. We set our initial value to 0 using init_func. The reducer_func will perform 0 + 1 and 1 + 3.0 operation and finalize_func will return 4.0.

In group_by_reducer function, key_func is a function which returns a key for that data row. Key should be Int64. In our case, we use 'ids' as our key.

Title: Example for tf. group_by_reducer?

Body:
Say we are provided with a dataset with ['ids', 'features'] and we want to group the data by adding 'features' corresponding to same 'ids'. We can use tf.group_by_reducer(key_func, reducer) to achieve this.

Raw data

ids | features
--------------
1   | 1
2   | 2.2
3   | 7
1   | 3.0
2   | 2
3   | 3

Desired data

ids | features
--------------
1   | 4
2   | 4.2
3   | 10

TensorFlow Code:

import tensorflow as tf
tf.enable_eager_execution()

ids = [1, 2, 3, 1, 2, 3]
features = [1, 2.2, 7, 3.0, 2, 3]

# Define reducer
# Reducer requires 3 functions - init_func, reduce_func, finalize_func.
# init_func - to define initial value
# reducer_func - operation to perform on values with same key
# finalize_func - value to return in the end.
def init_func(_):
    return 0.0

def reduce_func(state, value):
    return state + value['features']

def finalize_func(state):
    return state

reducer = tf.contrib.data.Reducer(init_func, reduce_func, finalize_func)

# Group by reducer
# Group the data by id
def key_f(row):
return tf.to_int64(row['ids'])

t = tf.contrib.data.group_by_reducer(
        key_func = key_f,
        reducer = reducer)

ds = tf.data.Dataset.from_tensor_slices({'ids':ids, 'features' : features})
ds = ds.apply(t)
ds = ds.batch(6)

iterator = ds.make_one_shot_iterator()
data = iterator.get_next()
print(data)

Consider ids == 1. We set our initial value to 0 using init_func. The reducer_func will perform 0 + 1 and 1 + 3.0 operation and finalize_func will return 4.0.

In group_by_reducer function, key_func is a function which returns a key for that data row. Key should be Int64. In our case, we use 'ids' as our key.


来源: stackexchange

问:
Cannot SSH into Amazon EC2 instance
I have spent almost 24hours trying to figure out what I'm doing wrong, but I can't figure this out. Starting to feel there is something wrong with my local setup.

I've made sure to chmod 400 erik-keypair.pem

I've stored erik-keypair.pem in my user .ssh folder, AND relocated the other id_rsa files just so they don't interfere (trying to remove any variables)

Ec2 instance security has ssh enabled

Here's the response

```<code>$ ssh -v -v -i erik-keypair.pem root@ec2-XX-XX-XX-XXX.compute-1.amazonaws.com
OpenSSH_5.2p1, OpenSSL 0.9.8l 5 Nov 2009
debug1: Reading configuration data /etc/ssh_config
debug2: ssh_connect: needpriv 0
debug1: Connecting to ec2-XX-XX-XX-XXX.compute-1.amazonaws.com [XX.XX.XX.XXX] port 22.
debug1: Connection established.
debug2: key_type_from_name: unknown key type '-----BEGIN'
debug2: key_type_from_name: unknown key type '-----END'
debug1: identity file erik-keypair.pem type -1
debug1: Remote protocol version 2.0, remote software version OpenSSH_5.1p1 Debian-5ubuntu1
debug1: match: OpenSSH_5.1p1 Debian-5ubuntu1 pat OpenSSH*
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_5.2
debug2: fd 3 setting O_NONBLOCK
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug2: kex_parse_kexinit: diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1
debug2: kex_parse_kexinit: ssh-rsa,ssh-dss
debug2: kex_parse_kexinit: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,rijndael-cbc@lysator.liu.se
debug2: kex_parse_kexinit: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,rijndael-cbc@lysator.liu.se
debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,umac-64@openssh.com,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96
debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,umac-64@openssh.com,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96
debug2: kex_parse_kexinit: none,zlib@openssh.com,zlib
debug2: kex_parse_kexinit: none,zlib@openssh.com,zlib
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit: first_kex_follows 0
debug2: kex_parse_kexinit: reserved 0
debug2: kex_parse_kexinit: diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1
debug2: kex_parse_kexinit: ssh-rsa,ssh-dss
debug2: kex_parse_kexinit: aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,arcfour128,arcfour256,arcfour,aes192-cbc,aes256-cbc,rijndael-cbc@lysator.liu.se,aes128-ctr,aes192-ctr,aes256-ctr
debug2: kex_parse_kexinit: aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,arcfour128,arcfour256,arcfour,aes192-cbc,aes256-cbc,rijndael-cbc@lysator.liu.se,aes128-ctr,aes192-ctr,aes256-ctr
debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,umac-64@openssh.com,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96
debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,umac-64@openssh.com,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96
debug2: kex_parse_kexinit: none,zlib@openssh.com
debug2: kex_parse_kexinit: none,zlib@openssh.com
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit: first_kex_follows 0
debug2: kex_parse_kexinit: reserved 0
debug2: mac_setup: found hmac-md5
debug1: kex: server->client aes128-ctr hmac-md5 none
debug2: mac_setup: found hmac-md5
debug1: kex: client->server aes128-ctr hmac-md5 none
debug1: SSH2_MSG_KEX_DH_GEX_REQUEST(1024<1024<8192) sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_GROUP
debug2: dh_gen_key: priv key bits set: 124/256
debug2: bits set: 502/1024
debug1: SSH2_MSG_KEX_DH_GEX_INIT sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_REPLY
debug1: Host 'ec2-XX-XX-XX-XXX.compute-1.amazonaws.com' is known and matches the RSA host key.
debug1: Found key in /Users/erik/.ssh/known_hosts:1
debug2: bits set: 523/1024
debug1: ssh_rsa_verify: signature correct
debug2: kex_derive_keys
debug2: set_newkeys: mode 1
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug2: set_newkeys: mode 0
debug1: SSH2_MSG_NEWKEYS received
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug2: service_accept: ssh-userauth
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug2: key: erik-keypair.pem (0x0)
debug1: Authentications that can continue: publickey
debug1: Next authentication method: publickey
debug1: Trying private key: erik-keypair.pem
debug1: read PEM private key done: type RSA
debug2: we sent a publickey packet, wait for reply
debug1: Authentications that can continue: publickey
debug2: we did not send a packet, disable method
debug1: No more authentication methods to try.
Permission denied (publickey).
</code>```

Does anyone spot what I'm doing wrong?

答: Rodney Quillo's answer is very likely correct. I would expand it by saying that the official Ubuntu distributions also have the default user as ubuntu.</p>

ContentLicense: CC BY-SA 3.0

Title: Cannot SSH into Amazon EC2 instance

Body:
I have spent almost 24hours trying to figure out what I'm doing wrong, but I can't figure this out. Starting to feel there is something wrong with my local setup.

I've made sure to chmod 400 erik-keypair.pem

I've stored erik-keypair.pem in my user .ssh folder, AND relocated the other id_rsa files just so they don't interfere (trying to remove any variables)

Ec2 instance security has ssh enabled

Here's the response

$ ssh -v -v -i erik-keypair.pem root@ec2-XX-XX-XX-XXX.compute-1.amazonaws.com
OpenSSH_5.2p1, OpenSSL 0.9.8l 5 Nov 2009
debug1: Reading configuration data /etc/ssh_config
debug2: ssh_connect: needpriv 0
debug1: Connecting to ec2-XX-XX-XX-XXX.compute-1.amazonaws.com [XX.XX.XX.XXX] port 22.
debug1: Connection established.
debug2: key_type_from_name: unknown key type '-----BEGIN'
debug2: key_type_from_name: unknown key type '-----END'
debug1: identity file erik-keypair.pem type -1
debug1: Remote protocol version 2.0, remote software version OpenSSH_5.1p1 Debian-5ubuntu1
debug1: match: OpenSSH_5.1p1 Debian-5ubuntu1 pat OpenSSH*
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_5.2
debug2: fd 3 setting O_NONBLOCK
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug2: kex_parse_kexinit: diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1
debug2: kex_parse_kexinit: ssh-rsa,ssh-dss
debug2: kex_parse_kexinit: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,rijndael-cbc@lysator.liu.se
debug2: kex_parse_kexinit: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,rijndael-cbc@lysator.liu.se
debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,umac-64@openssh.com,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96
debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,umac-64@openssh.com,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96
debug2: kex_parse_kexinit: none,zlib@openssh.com,zlib
debug2: kex_parse_kexinit: none,zlib@openssh.com,zlib
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit: first_kex_follows 0
debug2: kex_parse_kexinit: reserved 0
debug2: kex_parse_kexinit: diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1
debug2: kex_parse_kexinit: ssh-rsa,ssh-dss
debug2: kex_parse_kexinit: aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,arcfour128,arcfour256,arcfour,aes192-cbc,aes256-cbc,rijndael-cbc@lysator.liu.se,aes128-ctr,aes192-ctr,aes256-ctr
debug2: kex_parse_kexinit: aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,arcfour128,arcfour256,arcfour,aes192-cbc,aes256-cbc,rijndael-cbc@lysator.liu.se,aes128-ctr,aes192-ctr,aes256-ctr
debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,umac-64@openssh.com,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96
debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,umac-64@openssh.com,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96
debug2: kex_parse_kexinit: none,zlib@openssh.com
debug2: kex_parse_kexinit: none,zlib@openssh.com
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit: first_kex_follows 0
debug2: kex_parse_kexinit: reserved 0
debug2: mac_setup: found hmac-md5
debug1: kex: server->client aes128-ctr hmac-md5 none
debug2: mac_setup: found hmac-md5
debug1: kex: client->server aes128-ctr hmac-md5 none
debug1: SSH2_MSG_KEX_DH_GEX_REQUEST(1024<1024<8192) sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_GROUP
debug2: dh_gen_key: priv key bits set: 124/256
debug2: bits set: 502/1024
debug1: SSH2_MSG_KEX_DH_GEX_INIT sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_REPLY
debug1: Host 'ec2-XX-XX-XX-XXX.compute-1.amazonaws.com' is known and matches the RSA host key.
debug1: Found key in /Users/erik/.ssh/known_hosts:1
debug2: bits set: 523/1024
debug1: ssh_rsa_verify: signature correct
debug2: kex_derive_keys
debug2: set_newkeys: mode 1
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug2: set_newkeys: mode 0
debug1: SSH2_MSG_NEWKEYS received
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug2: service_accept: ssh-userauth
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug2: key: erik-keypair.pem (0x0)
debug1: Authentications that can continue: publickey
debug1: Next authentication method: publickey
debug1: Trying private key: erik-keypair.pem
debug1: read PEM private key done: type RSA
debug2: we sent a publickey packet, wait for reply
debug1: Authentications that can continue: publickey
debug2: we did not send a packet, disable method
debug1: No more authentication methods to try.
Permission denied (publickey).

Does anyone spot what I'm doing wrong?


问:
Stop Ansible playbook if docker install with amazon-linux-extras does not succeed

What specific changes need to be made to the code below so that the ansible playbook will fail if the "Install docker" task below does not succeed?

Currently, the playbook reports "changed" as the result of the "Install docker" task below, and thus the playbook continues into subsequent tasks whether or not the installation of docker has been successful.

```<code>---
- name: Install some stuff.
  hosts: firstgroup, secondgroup
  remote_user: someuser
  become: true
  become_method: sudo
  become_user: root

  tasks:

     - name: Install docker
       command: amazon-linux-extras install -y docker
</code>```

As you can see, this is running in Amazon Linux 2, and the installation is being done using amazon-linux-extras.

答:
you can try below code:

```<code>---
- name: Install some stuff.
  hosts: firstgroup, secondgroup
  remote_user: someuser
  become: yes

  tasks:

     - name: Install docker
       command: amazon-linux-extras install -y docker
       register: result
       failed_when: result.rc != 0
</code>```

you can add register option and get return code for that command. if its zero, then it will proceed else it will fail.
other thing about user, just put "become: yes" will be sufficient to run as root

ContentLicense: CC BY-SA 4.0

Body:
What specific changes need to be made to the code below so that the ansible playbook will fail if the "Install docker" task below does not succeed?

Currently, the playbook reports "changed" as the result of the "Install docker" task below, and thus the playbook continues into subsequent tasks whether or not the installation of docker has been successful.

---
- name: Install some stuff.
  hosts: firstgroup, secondgroup
  remote_user: someuser
  become: true
  become_method: sudo
  become_user: root

  tasks:

     - name: Install docker
       command: amazon-linux-extras install -y docker

As you can see, this is running in Amazon Linux 2, and the installation is being done using amazon-linux-extras.

Body:
you can try below code:

---
- name: Install some stuff.
  hosts: firstgroup, secondgroup
  remote_user: someuser
  become: yes

  tasks:

     - name: Install docker
       command: amazon-linux-extras install -y docker
       register: result
       failed_when: result.rc != 0

you can add register option and get return code for that command. if its zero, then it will proceed else it will fail.
other thing about user, just put "become: yes" will be sufficient to run as root


问:
Determining if there are repeated elements in a list in Haskell
I'm trying to test lists for duplicates but when I compile and enter

```<code>repeated [1,2,3,4]
</code>```

it outputs True. What's wrong?

```<code>belongs :: Eq a => a -> [a] -> Bool
belongs n [] = False
belongs n (x:xs) | n == x = True
                 | otherwise = belongs n xs

repeated :: [Integer] -> Bool
repeated [] = False
repeated (x:xs) | belongs x xs = True
                | otherwise = belongs (head xs) xs
</code>```

答:
You want </p>

```<code>repeated :: [Integer] -> Bool
repeated [] = False
repeated (x:xs) | belongs x xs = True
                | otherwise = repeated xs
</code>```

Body:
I'm trying to test lists for duplicates but when I compile and enter

repeated [1,2,3,4]

it outputs True. What's wrong?

belongs :: Eq a => a -> [a] -> Bool
belongs n [] = False
belongs n (x:xs) | n == x = True
                 | otherwise = belongs n xs

repeated :: [Integer] -> Bool
repeated [] = False
repeated (x:xs) | belongs x xs = True
                | otherwise = belongs (head xs) xs

Body:
You want

repeated :: [Integer] -> Bool
repeated [] = False
repeated (x:xs) | belongs x xs = True
                | otherwise = repeated xs


问:
Query gets data from two different users when I try to get data just from just one user
I want to get data just from only one specific user but I get data from both users. Why is that? I don't understand. How can I solve this?.

I have three tables:

```<code>/*User*/

    CREATE TABLE `User` (
    `IDUser` INT NOT NULL AUTO_INCREMENT,
    `Name` VARCHAR(50) NOT NULL,
    PRIMARY KEY (`IDUser`)
);

/*Category*/

     CREATE TABLE `Category` (
      `IDCategory` CHAR(3) NOT NULL,
      `FK_User` INT NOT NULL,
      `CategoryName` VARCHAR(40) NOT NULL,
      PRIMARY KEY (`IDCategory`, `FK_User`)
    );

/*Product*/

    CREATE TABLE `Product` (
        `IDProduct` VARCHAR(18) NOT NULL,
        `FK_User` INT NOT NULL,
        `ProductName` VARCHAR(150) NOT NULL,
        `FK_Category` CHAR(3) NOT NULL,
        PRIMARY KEY (`IDProduct`, `FK_User`)
    );

ALTER TABLE `Product` ADD FOREIGN KEY (`FK_User`) REFERENCES `User`(`IDUser`);
ALTER TABLE `Product` ADD FOREIGN KEY (`FK_Category`) REFERENCES `Category`(`IDCategory`);
ALTER TABLE `Category` ADD FOREIGN KEY (`FK_User`) REFERENCES `User`(`IDUser`);

insert into User(Name) values('User1');
insert into User(Name) values('User2');

insert into Category(IDCategory,FK_User,CategoryName) values('CT1',1,'Category1User1');
insert into Category(IDCategory,FK_User,CategoryName) values('CT1',2,'Category1User2');
</code>```

If two different users insert both the same product with the same ID:

```<code>insert into Product values('001',1,'shoe','CT1');
insert into Product values('001',2,'shoe','CT1');
</code>```

Why do I keep getting data from both users if I try a query like this one:

```<code>SELECT P.IDProduct,P.ProductName,P.FK_Category,C.CategoryName
FROM Product P inner join Category C on P.FK_Category=C.IDCategory
WHERE P.FK_User=1
</code>```

this is the result I get:

答:
You are getting two rows because both categories have the same IDCategory value which is the value you are JOINing on. You need to also JOIN on the FK_User values so that you don't also get User2's category values:

```<code>SELECT P.IDProduct,P.ProductName,P.FK_Category,C.CategoryName
FROM Product P
INNER JOIN Category C ON P.FK_Category=C.IDCategory AND P.FK_User = C.FK_User
WHERE P.FK_User=1
</code>```

Body:
I want to get data just from only one specific user but I get data from both users. Why is that? I don't understand. How can I solve this?.

I have three tables:

/*User*/

    CREATE TABLE `User` (
    `IDUser` INT NOT NULL AUTO_INCREMENT,
    `Name` VARCHAR(50) NOT NULL,
    PRIMARY KEY (`IDUser`)
);

/*Category*/

     CREATE TABLE `Category` (
      `IDCategory` CHAR(3) NOT NULL,
      `FK_User` INT NOT NULL,
      `CategoryName` VARCHAR(40) NOT NULL,
      PRIMARY KEY (`IDCategory`, `FK_User`)
    );

/*Product*/

    CREATE TABLE `Product` (
        `IDProduct` VARCHAR(18) NOT NULL,
        `FK_User` INT NOT NULL,
        `ProductName` VARCHAR(150) NOT NULL,
        `FK_Category` CHAR(3) NOT NULL,
        PRIMARY KEY (`IDProduct`, `FK_User`)
    );

ALTER TABLE `Product` ADD FOREIGN KEY (`FK_User`) REFERENCES `User`(`IDUser`);
ALTER TABLE `Product` ADD FOREIGN KEY (`FK_Category`) REFERENCES `Category`(`IDCategory`);
ALTER TABLE `Category` ADD FOREIGN KEY (`FK_User`) REFERENCES `User`(`IDUser`);

insert into User(Name) values('User1');
insert into User(Name) values('User2');

insert into Category(IDCategory,FK_User,CategoryName) values('CT1',1,'Category1User1');
insert into Category(IDCategory,FK_User,CategoryName) values('CT1',2,'Category1User2');

If two different users insert both the same product with the same ID:

insert into Product values('001',1,'shoe','CT1');
insert into Product values('001',2,'shoe','CT1');

Why do I keep getting data from both users if I try a query like this one:

SELECT P.IDProduct,P.ProductName,P.FK_Category,C.CategoryName
FROM Product P inner join Category C on P.FK_Category=C.IDCategory
WHERE P.FK_User=1

this is the result I get:

Body:
You are getting two rows because both categories have the same IDCategory value which is the value you are JOINing on. You need to also JOIN on the FK_User values so that you don't also get User2's category values:

SELECT P.IDProduct,P.ProductName,P.FK_Category,C.CategoryName
FROM Product P
INNER JOIN Category C ON P.FK_Category=C.IDCategory AND P.FK_User = C.FK_User
WHERE P.FK_User=1


答:
You need to add p.FK_User=C.Fk_User this condition in your join clause

```<code>SELECT P.IDProduct,P.ProductName,P.FK_Category,C.CategoryName
FROM Product P inner join Category C
on P.FK_Category=C.IDCategory and p.FK_User=C.Fk_User
WHERE P.FK_User=1
</code>```

Title: Query gets data from two different users when I try to get data just from just one user

Body:
You need to add p.FK_User=C.Fk_User this condition in your join clause

SELECT P.IDProduct,P.ProductName,P.FK_Category,C.CategoryName
FROM Product P inner join Category C
on P.FK_Category=C.IDCategory and p.FK_User=C.Fk_User
WHERE P.FK_User=1


问:
How can I create a group by on part of a string using LINQ?
I have a list of ViewsHistory objects that's sorted by UtcNow:

```<code>var views = List<ViewHistory>
</code>```

ViewHistory Class:

```<code>public class ViewHistory
{
    [PrimaryKey]
    public string YYMMDD { get; set; }
    public int UtcNow { get; set; }
    public int Learn { get; set; }
    public int Practice { get; set; }
    public int Quiz { get; set; }
}
</code>```

Is there a way using LINQ that I can create a new list summing up the totals for Learn, Practice and Quiz by YYMM?

答:
You can achieve that with GroupBy LINQ expression:

```<code> var views = new List<ViewHistory>();
            views.Add(new ViewHistory {YYMMDD = "190530", Learn = 20, Practice = 1, Quiz = 30});
            views.Add(new ViewHistory { YYMMDD = "190531", Learn = 1, Practice = 1, Quiz = 30 });
            views.Add(new ViewHistory { YYMMDD = "190529", Learn = 2, Practice = 1, Quiz = 30 });
            views.Add(new ViewHistory { YYMMDD = "190410", Learn = 2, Practice = 1, Quiz = 30 });
            var newViews = views.GroupBy(t => t.YYMMDD.Substring(0, 4))
                .Select(t => new
                {
                    yymm = t.Key,
                    learnSum = t.Select(f => f.Learn).Sum(),
                    practiceSum = t.Select(f => f.Practice).Sum(),
                    quizSum = t.Select(f => f.Quiz).Sum()
                }).ToList();
</code>```

Result

```<code>{ yymm = "1905", learnSum = 23, practiceSum = 3, quizSum = 90 },
{ yymm = "1904", learnSum = 2, practiceSum = 1, quizSum = 30 }
</code>```

Body:
I have a list of ViewsHistory objects that's sorted by UtcNow:

var views = List<ViewHistory>

ViewHistory Class:

public class ViewHistory
{
    [PrimaryKey]
    public string YYMMDD { get; set; }
    public int UtcNow { get; set; }
    public int Learn { get; set; }
    public int Practice { get; set; }
    public int Quiz { get; set; }
}

Is there a way using LINQ that I can create a new list summing up the totals for Learn, Practice and Quiz by YYMM?

Body:
You can achieve that with GroupBy LINQ expression:

 var views = new List<ViewHistory>();
            views.Add(new ViewHistory {YYMMDD = "190530", Learn = 20, Practice = 1, Quiz = 30});
            views.Add(new ViewHistory { YYMMDD = "190531", Learn = 1, Practice = 1, Quiz = 30 });
            views.Add(new ViewHistory { YYMMDD = "190529", Learn = 2, Practice = 1, Quiz = 30 });
            views.Add(new ViewHistory { YYMMDD = "190410", Learn = 2, Practice = 1, Quiz = 30 });
            var newViews = views.GroupBy(t => t.YYMMDD.Substring(0, 4))
                .Select(t => new
                {
                    yymm = t.Key,
                    learnSum = t.Select(f => f.Learn).Sum(),
                    practiceSum = t.Select(f => f.Practice).Sum(),
                    quizSum = t.Select(f => f.Quiz).Sum()
                }).ToList();

Result

{ yymm = "1905", learnSum = 23, practiceSum = 3, quizSum = 90 },
{ yymm = "1904", learnSum = 2, practiceSum = 1, quizSum = 30 }


问:
How to calculate total number
example I've array

```<code> const b =  [ 1000, 2000]
</code>```

Here is my Main number
     const a = 1500;

I want to do something like this in for loop

```<code> const data1 =  a - b[0]  ( 500 )
 const data2 = data1 - b[1] (-1500)
</code>```

Here is my for loop data

const b =  [ 1000, 2000]
let a = 1500;
for(let i in b) {
   const bData = b[i];
   const data =  a - bData;
   console.log(data)
   // in first loop my output = 500
   // second loop my output = -500 [ Which is wrong ]
}```

答:
You can use reduce function. So pass the initial value that is a as the accumulator. Here curr will the each element from the array b

const b = [1000, 2000]
const a = 1500;

let fValue = b.reduce(function(acc, curr) {
  return acc - curr;

}, a)
console.log(fValue)```

Title: How to calculate total number

Body:
example I've array

 const b =  [ 1000, 2000]

Here is my Main number
     const a = 1500;

I want to do something like this in for loop

 const data1 =  a - b[0]  ( 500 )
 const data2 = data1 - b[1] (-1500)

Here is my for loop data

const b =  [ 1000, 2000]
let a = 1500;
for(let i in b) {
   const bData = b[i];
   const data =  a - bData;
   console.log(data)
   // in first loop my output = 500
   // second loop my output = -500 [ Which is wrong ]
}


问:
Node.js - Parsing Images from JSON Object Reference
I am parsing JSON data from a remote API. The particular endpoint I am using returns all the values I want like title, description, summary and cover. I was hoping the cover field would be a string with the jpg url, but instead returns an object reference id. If you make another request and pass the object ID, the url string is there. How can I parse the image data without making another call to a different endpoint? I am using the IGDB API and following their documentation.
Here is my code

```<code>    const axios = require('axios');
axios({
  url: "https://api-v3.igdb.com/games",
  method: 'GET',
  headers: {
      'Accept': 'application/json',
      'user-key': 'xxxx'
  },
  data: "fields name,summary,url,cover,popularity;sort popularity desc;limit 13;"
})
  .then(response => {
    /* GET home page. */
    router.get('/', (req, res, next) => {
      res.render('index', { pageId: 'index',
                        title: 'Homepage',
                        cards: homeCards
        });
    });
    //Iterate through the JSON array
    let r = response.data;
    console.log(response.data);
    for (i=0; i<r.length; ++i){
      //Store json values
        var title = r[i].name;
        var description = r[i].summary;
        var link = r[i].url;
        var imageId = r[i].cover;
        //Push values onto homeCards
        homeCards.push({
          title: title,
          link: link,
          description: description,
        });
      }

  })
  .catch(err => {
      console.error(err);
  });
</code>```

I store the cover id in a variable imageId. How can I use this to show the corresponding object reference for each game?

答:
Hello all and thanks for the help. The answer was mush easier than I though and it was my bad when reading through the documentation. All you have to do is specify the sub field in the axios function.

```<code>data: "fields name,summary,url,cover,popularity,cover.url;sort popularity desc;limit 13;"
</code>```

cover.url brings me the image url for each game

Body:
I am parsing JSON data from a remote API. The particular endpoint I am using returns all the values I want like title, description, summary and cover. I was hoping the cover field would be a string with the jpg url, but instead returns an object reference id. If you make another request and pass the object ID, the url string is there. How can I parse the image data without making another call to a different endpoint? I am using the IGDB API and following their documentation.
Here is my code

    const axios = require('axios');
axios({
  url: "https://api-v3.igdb.com/games",
  method: 'GET',
  headers: {
      'Accept': 'application/json',
      'user-key': 'xxxx'
  },
  data: "fields name,summary,url,cover,popularity;sort popularity desc;limit 13;"
})
  .then(response => {
    /* GET home page. */
    router.get('/', (req, res, next) => {
      res.render('index', { pageId: 'index',
                        title: 'Homepage',
                        cards: homeCards
        });
    });
    //Iterate through the JSON array
    let r = response.data;
    console.log(response.data);
    for (i=0; i<r.length; ++i){
      //Store json values
        var title = r[i].name;
        var description = r[i].summary;
        var link = r[i].url;
        var imageId = r[i].cover;
        //Push values onto homeCards
        homeCards.push({
          title: title,
          link: link,
          description: description,
        });
      }

  })
  .catch(err => {
      console.error(err);
  });

I store the cover id in a variable imageId. How can I use this to show the corresponding object reference for each game?

Body:
Hello all and thanks for the help. The answer was mush easier than I though and it was my bad when reading through the documentation. All you have to do is specify the sub field in the axios function.

data: "fields name,summary,url,cover,popularity,cover.url;sort popularity desc;limit 13;"

cover.url brings me the image url for each game


问:
How to verify ECDSA with Public Key?
I have the following methods for generating keys and signing the password message.

```<code>public void generateKeys() {
try {
  keyStore = KeyStore.getInstance(KEYSTORE_NAME);
  keyStore.load(null);

  if (!keyStore.containsAlias(KEY_NAME)) {
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_EC, KEYSTORE_NAME);
    keyPairGenerator.initialize(
        new KeyGenParameterSpec.Builder(KEY_NAME,
                                        KeyProperties.PURPOSE_SIGN)
            .setDigests(KeyProperties.DIGEST_SHA256)
            .setAlgorithmParameterSpec(new ECGenParameterSpec("secp256r1"))
            // Require the user to authenticate with a fingerprint to authorize
            // every use of the private key
            .setUserAuthenticationRequired(true)
            .build());
    keyPairGenerator.generateKeyPair();
  }

  loadKeys();
} catch (NoSuchAlgorithmException e) {
  e.printStackTrace();
} catch (NoSuchProviderException e) {
  e.printStackTrace();
} catch (InvalidAlgorithmParameterException e) {
  e.printStackTrace();
} catch (CertificateException e) {
  e.printStackTrace();
} catch (KeyStoreException e) {
  e.printStackTrace();
} catch (IOException e) {
  e.printStackTrace();
}
</code>```

}

```<code>public BiometricPrompt.CryptoObject getCryptoObject() {
cryptoObject = new BiometricPrompt.CryptoObject(signature);
return cryptoObject;
}

private void loadKeys() {
try {
  keyStore = KeyStore.getInstance(KEYSTORE_NAME);
  keyStore.load(null);
  if (keyStore.containsAlias(KEY_NAME)) {
    publicKey = keyStore.getCertificate(KEY_NAME).getPublicKey();
    privateKey = (PrivateKey) keyStore.getKey(KEY_NAME, null);
    signature = Signature.getInstance(Constants.SIGNATURE);
    signature.initSign(privateKey);
  }
} catch (IOException e) {
  e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
  e.printStackTrace();
} catch (CertificateException e) {
  e.printStackTrace();
} catch (KeyStoreException e) {
  e.printStackTrace();
} catch (UnrecoverableKeyException e) {
  e.printStackTrace();
} catch (InvalidKeyException e) {
  e.printStackTrace();
}
}

public String sign(String inputStr) {
try {
  Signature signature = cryptoObject.getSignature();
  signature.update(inputStr.getBytes());
  byte[] signedBytes = signature.sign();
  String result = HexManager.bytesToHex(signedBytes);
  Log.d("TAG", result);
  return result;
} catch (SignatureException e) {
  e.printStackTrace();
}
return null;
</code>```

}

After that, I saved the signed password in Shared Preferences. Later, I want to verify the saved password with a new password that is verified with the fingerprint.

Here is my method to verify:

```<code>public boolean verify(String inputStr, String savedStr) {
try {
  Signature signature = cryptoObject.getSignature();
  signature.initVerify(publicKey);
  signature.update(inputStr.getBytes());
  boolean isVerified = signature.verify(savedStr.getBytes());
  return isVerified;
} catch (InvalidKeyException e) {
  e.printStackTrace();
} catch (SignatureException e) {
  e.printStackTrace();
}
return false;
}
</code>```

But it always return false.

Does anybody knows why?

答:
It looks like in your sign() method you're returning the Hex of the byte[] obtained from the signature.sign() method. If this is what you're saving as savedStr. Then the verification method should be changed to convert the Hex encoded string to a byte[]. You could use HexManager.hexToBytes() (or equivalent) if it exists to convert the savedStr to a byte[] savedStrBytes.

```<code>public boolean verify(String inputStr, String savedStr) {
    try {
        byte[] savedStrBytes = HexManager.hexToByes(savedStr);
        Signature signature = cryptoObject.getSignature();
        signature.initVerify(publicKey);
        signature.update(inputStr.getBytes());
        boolean isVerified = signature.verify(savedStrBytes);
        return isVerified;
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    } catch (SignatureException e) {
        e.printStackTrace();
    }
    return false;
}
</code>```

Title: How to verify ECDSA with Public Key?

Body:
I have the following methods for generating keys and signing the password message.

public void generateKeys() {
try {
  keyStore = KeyStore.getInstance(KEYSTORE_NAME);
  keyStore.load(null);

  if (!keyStore.containsAlias(KEY_NAME)) {
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_EC, KEYSTORE_NAME);
    keyPairGenerator.initialize(
        new KeyGenParameterSpec.Builder(KEY_NAME,
                                        KeyProperties.PURPOSE_SIGN)
            .setDigests(KeyProperties.DIGEST_SHA256)
            .setAlgorithmParameterSpec(new ECGenParameterSpec("secp256r1"))
            // Require the user to authenticate with a fingerprint to authorize
            // every use of the private key
            .setUserAuthenticationRequired(true)
            .build());
    keyPairGenerator.generateKeyPair();
  }

  loadKeys();
} catch (NoSuchAlgorithmException e) {
  e.printStackTrace();
} catch (NoSuchProviderException e) {
  e.printStackTrace();
} catch (InvalidAlgorithmParameterException e) {
  e.printStackTrace();
} catch (CertificateException e) {
  e.printStackTrace();
} catch (KeyStoreException e) {
  e.printStackTrace();
} catch (IOException e) {
  e.printStackTrace();
}

}

public BiometricPrompt.CryptoObject getCryptoObject() {
cryptoObject = new BiometricPrompt.CryptoObject(signature);
return cryptoObject;
}

private void loadKeys() {
try {
  keyStore = KeyStore.getInstance(KEYSTORE_NAME);
  keyStore.load(null);
  if (keyStore.containsAlias(KEY_NAME)) {
    publicKey = keyStore.getCertificate(KEY_NAME).getPublicKey();
    privateKey = (PrivateKey) keyStore.getKey(KEY_NAME, null);
    signature = Signature.getInstance(Constants.SIGNATURE);
    signature.initSign(privateKey);
  }
} catch (IOException e) {
  e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
  e.printStackTrace();
} catch (CertificateException e) {
  e.printStackTrace();
} catch (KeyStoreException e) {
  e.printStackTrace();
} catch (UnrecoverableKeyException e) {
  e.printStackTrace();
} catch (InvalidKeyException e) {
  e.printStackTrace();
}
}

public String sign(String inputStr) {
try {
  Signature signature = cryptoObject.getSignature();
  signature.update(inputStr.getBytes());
  byte[] signedBytes = signature.sign();
  String result = HexManager.bytesToHex(signedBytes);
  Log.d("TAG", result);
  return result;
} catch (SignatureException e) {
  e.printStackTrace();
}
return null;

}

After that, I saved the signed password in Shared Preferences. Later, I want to verify the saved password with a new password that is verified with the fingerprint.

Here is my method to verify:

public boolean verify(String inputStr, String savedStr) {
try {
  Signature signature = cryptoObject.getSignature();
  signature.initVerify(publicKey);
  signature.update(inputStr.getBytes());
  boolean isVerified = signature.verify(savedStr.getBytes());
  return isVerified;
} catch (InvalidKeyException e) {
  e.printStackTrace();
} catch (SignatureException e) {
  e.printStackTrace();
}
return false;
}

But it always return false.

Does anybody knows why?

Body:
It looks like in your sign() method you're returning the Hex of the byte[] obtained from the signature.sign() method. If this is what you're saving as savedStr. Then the verification method should be changed to convert the Hex encoded string to a byte[]. You could use HexManager.hexToBytes() (or equivalent) if it exists to convert the savedStr to a byte[] savedStrBytes.

public boolean verify(String inputStr, String savedStr) {
    try {
        byte[] savedStrBytes = HexManager.hexToByes(savedStr);
        Signature signature = cryptoObject.getSignature();
        signature.initVerify(publicKey);
        signature.update(inputStr.getBytes());
        boolean isVerified = signature.verify(savedStrBytes);
        return isVerified;
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    } catch (SignatureException e) {
        e.printStackTrace();
    }
    return false;
}


问:
How store variable after data has been passed from server to client?
After passing my server side 'data' to the client I am unable to store the 'data' into a variable and receive an undefined.

Why is this happening and how can I resolve this?

The request is made on the client side:

```<code>(function () {

    var M;
    var url = '/app/get/metafield';

    fetch(url)
        .then((response) => response.json())
        .then(function (data) {
            filter(data)
        });

    function filter(data) {
        console.log('data :', data) // 25
        M = JSON.stringify(data);

    }

        console.log('M :', M) // undefined
});
</code>```

This is ther server side code:

```<code>  app.get('/app/get/metafield', function (req, res, next) {

               function (error, response, body) {
                    var data = JSON.parse(body)
                    var M = data.metafields[0].value;
                    return res.json(M);
                })

    });
</code>```

答:
The problem here is that the fetch call is async, which means that you won't really know for sure when it's going to complete. Instead, if you want any data that depends on the result of calling fetch, you have to chain it to the callback.

You can think about it like this:

I tell my friend to go fetch a URL, but instead of waiting until he's done, I give him instructions (the callback) on what to do when he's done and then I can work on something else in the meantime. The instructions also contains an access to the variable M that he's to update when he's done.

I don't know when he's going to finish, so I can't depend on the value of M being the fetched data for anything I want to do. So if I want something that depends on the fetched data, I have to include it in the instructions.

The remedy is to attach another callback to the Promise chain. You can do this in a functional-programming style:

fetch(url)
    .then((response) => response.json())
    .then(filter)
    .then(process);

function filter(data) {
    console.log('data :', data) // 25
    return JSON.stringify(data);
}

function process(data) {
    ...
}
```

You can read more about Promise chaining here:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises#Chaining

https://javascript.info/promise-chaining

NB: It's generally not a good idea to use global variables for heavily async code. You already realized the reason; it's hard to know when the variable is going to be set to what value because there's no guarantees about the execution order of the async functions. The better way is to pass around the data that you need to use, like I did above with process(data). This is called a pure function because no variables outside the function are touched, all it does is take the input parameters and transforms it to the returns value.

Body:
After passing my server side 'data' to the client I am unable to store the 'data' into a variable and receive an undefined.

Why is this happening and how can I resolve this?

The request is made on the client side:

(function () {

    var M;
    var url = '/app/get/metafield';

    fetch(url)
        .then((response) => response.json())
        .then(function (data) {
            filter(data)
        });

    function filter(data) {
        console.log('data :', data) // 25
        M = JSON.stringify(data);

    }

        console.log('M :', M) // undefined
});

This is ther server side code:

  app.get('/app/get/metafield', function (req, res, next) {

               function (error, response, body) {
                    var data = JSON.parse(body)
                    var M = data.metafields[0].value;
                    return res.json(M);
                })

    });

Body:
The problem here is that the fetch call is async, which means that you won't really know for sure when it's going to complete. Instead, if you want any data that depends on the result of calling fetch, you have to chain it to the callback.

You can think about it like this:

I tell my friend to go fetch a URL, but instead of waiting until he's done, I give him instructions (the callback) on what to do when he's done and then I can work on something else in the meantime. The instructions also contains an access to the variable M that he's to update when he's done.

I don't know when he's going to finish, so I can't depend on the value of M being the fetched data for anything I want to do. So if I want something that depends on the fetched data, I have to include it in the instructions.

The remedy is to attach another callback to the Promise chain. You can do this in a functional-programming style:

fetch(url)
    .then((response) => response.json())
    .then(filter)
    .then(process);

function filter(data) {
    console.log('data :', data) // 25
    return JSON.stringify(data);
}

function process(data) {
    ...
}

You can read more about Promise chaining here:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises#Chaining

https://javascript.info/promise-chaining

NB: It's generally not a good idea to use global variables for heavily async code. You already realized the reason; it's hard to know when the variable is going to be set to what value because there's no guarantees about the execution order of the async functions. The better way is to pass around the data that you need to use, like I did above with process(data). This is called a pure function because no variables outside the function are touched, all it does is take the input parameters and transforms it to the returns value.


问:
Can Bing or GMaps API do a "find my nearest" style search using a supplied XML/RSS collection?
Can either Bing or Google Maps allow you to pass in a collection of points and then interrogate that collection to only plot the X nearest points?

I am asking because it may be difficult to pre-filter this data and would be much simpler to supply the entire list and filter it within the API itself.

答:
I'm just looking at doing this for a client request i've had.  As far as I can see, the best way to do it would be to use Google (or similar) to Geocode your addresses when they're entered (that is, turn a postal address into a latitude and longitude).

When you come to 'find my nearest', you'll want to get a postcode (probably) of the person searching and then geocode it, or maybe a lat-long if you're able to get the data straight out of a mobile device.

Once you have the lat-long for your fixed positions, and the same for your user, I reckon you can use a haversine formula (I say this, but I haven't actually tried it - I'm no mathematician) which is a mathematical way of calculating the distance between two points around a sphere.  The Earth isn't quite a sphere, but close enough for this sort of purpose.

This way, you're only doing one lookup to an external service to find your users location (assuming you've geocoded your fixed points when they were created, and stored them for later), and then doing the donkey work server side to calculate the distances.  You could probably even create a custom SQL function to pull it right out of the database in order.

ContentLicense: CC BY-SA 2.5


问:
Display 2 tables in 1 view
I want to display 2 tables in 1 view

like this:

```<code>{{ $match->title }}
{{ $distance->distance }}
</code>```

but I can't get it to work.

This is my controller:

```<code>public function bikeGamesMatch(Request $request){
    $matches = BikeGame::find($request->id);
    $distances = Distance::find($request->id);
    dd($matches);
    return view('bike_games.match', compact("matches","distances"));
}
</code>```

why does the $distances return to null when I dd(): it?

this is my view:

```<code><th scope="col" class="text-center"><strong>Game Title:</strong>
             @foreach($matches as $match)
             {{ $match->title }}
             @endforeach
              </th>
                <th scope="col" class="text-center"><strong>Target: Distance</strong>
              @foreach($distances as $distance)
             {{ $distance->distance }} {{ $distance->unit }}
             @endforeach
</th>
</code>```

If I do this the view gives me 404

```<code>$matches = BikeGame::find($request->id)->firstOrFail();
$distances = Distance::find($request->id)->firstOrFail();
</code>```

What am I doing wrong here?

答:
Try changing:

```<code>$matches = BikeGame::find($request->id);
$distances = Distance::find($request->id);
</code>```

to

```<code>$matches = BikeGame::find($request->get('id'));
$distances = Distance::find($request->get('id');
</code>```

Title: Display 2 tables in 1 view

Body:
I want to display 2 tables in 1 view

like this:

{{ $match->title }}
{{ $distance->distance }}

but I can't get it to work.

This is my controller:

public function bikeGamesMatch(Request $request){
    $matches = BikeGame::find($request->id);
    $distances = Distance::find($request->id);
    dd($matches);
    return view('bike_games.match', compact("matches","distances"));
}

why does the $distances return to null when I dd(): it?

this is my view:

Game Title:
             @foreach($matches as $match)
             {{ $match->title }}
             @endforeach

                Target: Distance
              @foreach($distances as $distance)
             {{ $distance->distance }} {{ $distance->unit }}
             @endforeach

If I do this the view gives me 404

$matches = BikeGame::find($request->id)->firstOrFail();
$distances = Distance::find($request->id)->firstOrFail();

What am I doing wrong here?

Body:
Try changing:

$matches = BikeGame::find($request->id);
$distances = Distance::find($request->id);

to

$matches = BikeGame::find($request->get('id'));
$distances = Distance::find($request->get('id');


问:
Format/parse different Date formats correctly
I receive Date in 3 formats from different APIs

UTC format: 2014-01-01T00:00:00.000Z (String)

GMTformat: Thu, 29 Nov 2018 17:30:56 GMT (String)

unixTimeStamp: 1558606726 (number)

Also the UTC format sometimes might not have Z in the end so the normal parsing will give a time difference.

```<code>function formatDate(dateString) {
  var dateTime, utcFormatRegex, zeroHourOffsetRegex;

// Some APIs return a Date in standard ISO UTC format may not have Z at the end
  utcFormatRegex = /^\d{4}-\d{2}-\d{2}T.*$/;
  zeroHourOffsetRegex = /^.*Z$/;

  if (utcFormatRegex.test(dateString) && !zeroHourOffsetRegex.test(dateString)) {
    dateString+='Z';
  }

    dateTime = new Date(dateString);

}
</code>```

Given that there are parsing functions for all of the different formats,  i need a function that determines which parsing function we should be using based on a regex and parse it accordingly. If regex is not the ideal solution then how can i approach this?

What I'm getting at is there should probably be a more robust solution than 'if there isn't a Z then add one' to get it to parse through the single date time parser. What if we get another date time format that doesn't play nicely with a Z on the end? We'll be making multiple changes at that point in time.

答:
Using a regular expression is OK, but you need to test strictly for the formats you're expecting. If you get something you don't expect, throw an error. It's one of the failings of current built–in parsers is that there's no way to specify strict parsing, e.g. where a format is supplied and the parser throws an error if the input string doesn't match.

There are libraries that can help, a search will reveal quite a few.

But if you only have to support the 3 formats in the OP, something like the following may suit:

/* Return a Date where the input may be:
**   string: ISO 8601 timestamp that should be treated as UTC
**           whether it has a trailing Z or not
**   string: Timestamp in the format (using moment.js tokens):
**           ddd, DD MMM YYYY HH:mm:ss GMT
**   nunber: UNIX time value, seconds since 1970-01-01 UTC
*/
function toDate(value) {
  // Parse the string & fail early if it fails
  let d = new Date(value);

  // Throw error if couldn't parse value
  if (isNaN(d.getTime())) {
    throw 'Invalid timestamp: ' + value;
  }

  // Otherwise, do the work
  let days = 'Sun Mon Tue Wed Thu Fri Sat'.split(' ');
  let months = 'Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'.split(' ');

  // Test for time value first as that's the easiest
  if (typeof value == 'number' && !isNaN(value)) {
    return new Date(value * 1000);

  // Test for ISO 8601 next
  } else if (/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d\d\dZ?$/.test(value)) {
    return new Date(/Z$/.test(value)? value : value + 'Z');

  // Test for random format
  } else if (/^[a-z]{3}, \d?\d [a-z]{3} \d{4} \d\d:\d\d:\d\d GMT$/i.test(value)) {
    let b = value.split(/ |:/);

    if (days.includes(b[0].substr(0,3)) && months.includes(b[2])) {
      let x = new Date(Date.UTC(
                b[3],                 // year
                months.indexOf(b[2]), // month, zero indexed
                b[1],                 // day
                b[4], b[5], b[6]      // hh:mm:ss
              ));
      // Check value was a valid date, only need to check some parts
      if (x.getUTCFullYear() == b[3] &&
          x.getUTCDate() == b[1] &&
          x.getUTCHours() == b[4] &&
          x.getUTCSeconds() == b[6]) {
        return x;
      } else {
        throw 'Invalid timestamp: ' + value;
      }
    }

  // Throw error as must be unknown format
  } else {
    throw 'Unknown format: ' + value;
  }
}

// Minimal testing
var isoString0 = '2014-01-01T00:00:00.000Z',
    isoString1 = '2014-01-01T00:00:00.000',         // no Z, parse as UTC anyway
    randomString = 'Thu, 29 Nov 2018 17:30:56 GMT',
    unixTimeValue = 1558606726,                     // Assume seconds
    invalidDate0 = '2018-02-29T00:00:00.000Z',      // no 29 Feb in 2018, fail built-in parse
    invalidDate1 = 'Thu, 29 Feb 2018 17:30:56 GMT', // no 29 Feb in 2018, fail manual parse
    invalidFormat = '6/6/2019';                     // Unknown format

[isoString0, isoString1, randomString, unixTimeValue, invalidDate0,
 invalidDate1, invalidFormat].forEach(s => {
  var result;
  try {
    result = toDate(s);
    console.log(s + ' =>\n' + result.toISOString());
  } catch (e) {
    console.log(e);
  }
});```

Body:
I receive Date in 3 formats from different APIs

UTC format: 2014-01-01T00:00:00.000Z (String)

GMTformat: Thu, 29 Nov 2018 17:30:56 GMT (String)

unixTimeStamp: 1558606726 (number)

Also the UTC format sometimes might not have Z in the end so the normal parsing will give a time difference.

function formatDate(dateString) {
  var dateTime, utcFormatRegex, zeroHourOffsetRegex;

// Some APIs return a Date in standard ISO UTC format may not have Z at the end
  utcFormatRegex = /^\d{4}-\d{2}-\d{2}T.*$/;
  zeroHourOffsetRegex = /^.*Z$/;

  if (utcFormatRegex.test(dateString) && !zeroHourOffsetRegex.test(dateString)) {
    dateString+='Z';
  }

    dateTime = new Date(dateString);

}

Given that there are parsing functions for all of the different formats,  i need a function that determines which parsing function we should be using based on a regex and parse it accordingly. If regex is not the ideal solution then how can i approach this?

What I'm getting at is there should probably be a more robust solution than 'if there isn't a Z then add one' to get it to parse through the single date time parser. What if we get another date time format that doesn't play nicely with a Z on the end? We'll be making multiple changes at that point in time.


问:
React S3 Feature Branching
So I have my react app which is hosted on S3 as a static website, I would to setup based on feature branching for a test so there is the root S3 bucket folder and then a site or folder per feature i.e. "/dev/profile-view" or "dev/new-ui" however react has issues in finding the JS files and loading index if everything is not in the root folder if I set homepage in the package file it works but then when I deploy to production it does not. The page refresh is missed up as it can't find index.html

I spoke with AWS support and they said the following

Unfortunately, the S3 Website Feature currently configured on your Bucket "au-boral-portal-development" will not support a redirection behavior as you need for your case as like prepending a prefix "/feature/*" to all requests.

I spoke to our Developer Services Team and their advice was to address this use case via code, using baseURI parameter.

答: So I was able to fix this just adding PUBLIC_URL="."  in my .env.development file. </p>

Title: React S3 Feature Branching


问:
Read a string from shared preferences in flutter
I have saved two strings using shared preferences. I want to retrieve the strings individually and display it as texts.

Write:

```<code>_nameSaver() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setString('name', nameController.text);
    prefs.setString('school', schoolController.text);
  }

RaisedButton(onPressed: () => _nameSaver(),);
</code>```

Read:

```<code>  _nameRetriever() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    final name = prefs.getString('name') ?? '';
    final school = prefs.getString('school') ?? '';

    print(name);
    print(school);
  }
</code>```

I should extract out the name and school from the shared preference and display it on the list tile respectively. Title for name and subtitle for school. However i am unsure on how to extract it this way using a method await.

```<code>ListTile(title: Text("")
         subtitle: Text(""),),
</code>```

答:
First define to variables for the texts

```<code>String nameText = '';
String schoolText = '';
</code>```

Assign these to Widgets

```<code>ListTile(title: Text(nameText)
         subtitle: Text(schoolText),),

</code>```

Now in read from sharedpref function set these

```<code> _nameRetriever() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();

setState(){
 nameText = prefs.getString('name') ?? '';
 schoolText = prefs.getString('school') ?? '';
}

    print(targetPrice);
    print(instrumentPair);
  }

</code>```

EDIT

This is just to demonstrate how it works. I have made the save function a future function just to make sure I read after saving.. It's not need if you are doing saving and reading at the same time

```<code>class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  @override
  void initState() {
    super.initState();
    _nameSaver().then((_) {
      _nameRetriever();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(body: Container());
  }

  Future<String> _nameSaver() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setString('name2', 'asdsadasd');
    prefs.setString('school2', 'asdasdas');
    return 'saved';
  }

  _nameRetriever() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    final name = prefs.getString('name2') ?? '';
    final school = prefs.getString('school2') ?? '';

    print(name);
    print(school);
  }
}

</code>```

Body:
I have saved two strings using shared preferences. I want to retrieve the strings individually and display it as texts.

Write:

_nameSaver() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setString('name', nameController.text);
    prefs.setString('school', schoolController.text);
  }

RaisedButton(onPressed: () => _nameSaver(),);

Read:

  _nameRetriever() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    final name = prefs.getString('name') ?? '';
    final school = prefs.getString('school') ?? '';

    print(name);
    print(school);
  }

I should extract out the name and school from the shared preference and display it on the list tile respectively. Title for name and subtitle for school. However i am unsure on how to extract it this way using a method await.

ListTile(title: Text("")
         subtitle: Text(""),),

Body:
First define to variables for the texts

String nameText = '';
String schoolText = '';

Assign these to Widgets

ListTile(title: Text(nameText)
         subtitle: Text(schoolText),),

Now in read from sharedpref function set these

 _nameRetriever() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();

setState(){
 nameText = prefs.getString('name') ?? '';
 schoolText = prefs.getString('school') ?? '';
}

    print(targetPrice);
    print(instrumentPair);
  }

EDIT

This is just to demonstrate how it works. I have made the save function a future function just to make sure I read after saving.. It's not need if you are doing saving and reading at the same time

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  @override
  void initState() {
    super.initState();
    _nameSaver().then((_) {
      _nameRetriever();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(body: Container());
  }

  Future<String> _nameSaver() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setString('name2', 'asdsadasd');
    prefs.setString('school2', 'asdasdas');
    return 'saved';
  }

  _nameRetriever() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    final name = prefs.getString('name2') ?? '';
    final school = prefs.getString('school2') ?? '';

    print(name);
    print(school);
  }
}


问:
Updating the PATH environment variable in Windows using C++
I am trying to launch a new process from my current process. I am using CreateProcess() to launch it. The issue is that I need to have certain directories in my PATH to successfully do so. Here is my current implementation but it doesn't work. What am I doing wrong?

```<code>// Environment variables
char *env = new char[2048];
char *ptr = env;

char temp[MAX_PATH] = "PATH=";
strcpy(ptr, strcat(temp, plugin_path));
ptr += strlen(ptr) + 1;

char  temp2[MAX_PATH] = "PATH=";
strcpy(ptr, strcat(temp, lib_path));
ptr += strlen(ptr) + 1;
*ptr = '\0';

 // Execute
STARTUPINFO si;
PROCESS_INFORMATION pi;

ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
ZeroMemory(&pi, sizeof(pi));

// error checking required
if(!CreateProcess(
    NULL,             // application name
    command_path,   // app.exe
    NULL,
    NULL,
    TRUE,
    0,
    env,           // environment
    NULL,
    &si,
    &pi)) {
    std::cout << GetLastError();
    return 1;
}

WaitForSingleObject(pi.hProcess, INFINITE);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
std::cout << "Process Started!";
</code>```

Please let me know if anything else is required.

EDIT: Somebody mentioned below that I need to be a little more specific. It doesn't work in the sense that the environment variables don't get passed. It fails because the library path is not in PATH. The createProcess does actually launch it though.

EDIT2: Here's the updated code. Same problem. Further, CreateProcess throws error 1087 which doesn't seem to exist in the docs.

```<code>// Environment variables
char env[2048];
char *ptr = env;
char *path_path = getenv("PATH");

// copy original path
memcpy(ptr, path_path, strlen(path_path));
ptr += strlen(ptr) + 1;
memcpy(ptr, ";", 1);
ptr++;

// copy plugin path
memcpy(ptr, plugin_path, strlen(plugin_path));
ptr += strlen(plugin_path) + 1;
memcpy(ptr, ";", 1);
ptr++;

// copy libpath
memcpy(ptr, lib_path, strlen(lib_path));
ptr += strlen(lib_path) + 1;
memcpy(ptr, ";", 1);
ptr++;

// double null terminated
memcpy(ptr, "\0\0", 2);

std::cout << "ENV : " << env << std::endl;

// error checking required
if(!CreateProcess(
    NULL,             // application name
    command_path,   // app.exe
    NULL,
    NULL,
    TRUE,
    0,
    env,           // environment
    NULL,
    &si,
    &pi)) {
    std::cout << GetLastError();
    return 1;
}

WaitForSingleObject(pi.hProcess, INFINITE);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
std::cout << "Process Started!";
</code>```

答:
```<code>#include <iostream>
#include <windows.h>
#include <cstring>
#include "tchar.h"

void SetUserVariablePath(){
    HKEY hkey;
    long regOpenResult;
    const char key_name[] = "Environment";
    const char path[]="D:/custom_command";                                               //new_value path need to update
    regOpenResult = RegOpenKeyEx(HKEY_CURRENT_USER,key_name, 0, KEY_ALL_ACCESS, &hkey);
    LPCSTR stuff = "VVS_LOGGING_PATH";                                                   //Variable Name
    RegSetValueEx(hkey,stuff,0,REG_SZ,(BYTE*) path, strlen(path));
    RegCloseKey(hkey);
}

void GetUserVariablePath(){
    static const char path[] = "VVS_LOGGING_PATH" ;                                      //Variable Name
    static BYTE buffer1[1000000] ;
    DWORD buffsz1 = sizeof(buffer1) ;
    {
        //HKEY_CURRENT_USER\Environment
        const char key_name[] = "Environment";
        HKEY key ;

        if( RegOpenKeyExA( HKEY_CURRENT_USER, key_name, 0, KEY_QUERY_VALUE, std::addressof(key) ) == 0 &&
            RegQueryValueExA( key, path, nullptr, nullptr, buffer1, std::addressof(buffsz1) ) == 0 )
        {
            std::cout << "The updated value of the user variable is :  " << reinterpret_cast<const char*>(buffer1) << '\n' ;
        }
    }
}

int main()
{
    SetUserVariablePath();
    GetUserVariablePath();
    return 0;
}
</code>```

Body:
I am trying to launch a new process from my current process. I am using CreateProcess() to launch it. The issue is that I need to have certain directories in my PATH to successfully do so. Here is my current implementation but it doesn't work. What am I doing wrong?

// Environment variables
char *env = new char[2048];
char *ptr = env;

char temp[MAX_PATH] = "PATH=";
strcpy(ptr, strcat(temp, plugin_path));
ptr += strlen(ptr) + 1;

char  temp2[MAX_PATH] = "PATH=";
strcpy(ptr, strcat(temp, lib_path));
ptr += strlen(ptr) + 1;
*ptr = '\0';

 // Execute
STARTUPINFO si;
PROCESS_INFORMATION pi;

ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
ZeroMemory(&pi, sizeof(pi));

// error checking required
if(!CreateProcess(
    NULL,             // application name
    command_path,   // app.exe
    NULL,
    NULL,
    TRUE,
    0,
    env,           // environment
    NULL,
    &si,
    &pi)) {
    std::cout << GetLastError();
    return 1;
}

WaitForSingleObject(pi.hProcess, INFINITE);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
std::cout << "Process Started!";

Please let me know if anything else is required.

EDIT: Somebody mentioned below that I need to be a little more specific. It doesn't work in the sense that the environment variables don't get passed. It fails because the library path is not in PATH. The createProcess does actually launch it though.

EDIT2: Here's the updated code. Same problem. Further, CreateProcess throws error 1087 which doesn't seem to exist in the docs.

// Environment variables
char env[2048];
char *ptr = env;
char *path_path = getenv("PATH");

// copy original path
memcpy(ptr, path_path, strlen(path_path));
ptr += strlen(ptr) + 1;
memcpy(ptr, ";", 1);
ptr++;

// copy plugin path
memcpy(ptr, plugin_path, strlen(plugin_path));
ptr += strlen(plugin_path) + 1;
memcpy(ptr, ";", 1);
ptr++;

// copy libpath
memcpy(ptr, lib_path, strlen(lib_path));
ptr += strlen(lib_path) + 1;
memcpy(ptr, ";", 1);
ptr++;

// double null terminated
memcpy(ptr, "\0\0", 2);

std::cout << "ENV : " << env << std::endl;

// error checking required
if(!CreateProcess(
    NULL,             // application name
    command_path,   // app.exe
    NULL,
    NULL,
    TRUE,
    0,
    env,           // environment
    NULL,
    &si,
    &pi)) {
    std::cout << GetLastError();
    return 1;
}

WaitForSingleObject(pi.hProcess, INFINITE);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
std::cout << "Process Started!";


问:
ESP8266 stack trace: find position of "last failed alloc call" in code
I'm trying to debug a large sketch, I'm occasionally getting a crash related to the web interface, and am trying to find out where exactly this is going wrong.

The stack trace ends with:

```<code>last failed alloc call: 4022D552(1480)
</code>```

This particular address is not present in the decode stack trace itself, but may hold the key to finding the source of the problem. Any suggestions on how to track this one down?

```<code>Decoding 36 results
0x402222c5: BearSSL::WiFiClientSecure::_installClientX509Validator() at /home/wouter/.arduino15/packages/esp8266/tools/xtensa-lx106-elf-gcc/2.5.0-3-20ed2b9/xtensa-lx106-elf/include/c++/4.8.2/bits/shared_ptr_base.h line 986
:  (inlined by) ?? at /home/wouter/.arduino15/packages/esp8266/tools/xtensa-lx106-elf-gcc/2.5.0-3-20ed2b9/xtensa-lx106-elf/include/c++/4.8.2/bits/shared_ptr.h line 316
:  (inlined by) ?? at /home/wouter/.arduino15/packages/esp8266/tools/xtensa-lx106-elf-gcc/2.5.0-3-20ed2b9/xtensa-lx106-elf/include/c++/4.8.2/bits/shared_ptr.h line 598
:  (inlined by) ?? at /home/wouter/.arduino15/packages/esp8266/tools/xtensa-lx106-elf-gcc/2.5.0-3-20ed2b9/xtensa-lx106-elf/include/c++/4.8.2/bits/shared_ptr.h line 614
:  (inlined by) BearSSL::WiFiClientSecure::_installClientX509Validator() at /home/wouter/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/libraries/ESP8266WiFi/src/WiFiClientSecureBearSSL.cpp line 877
0x40222cfc: BearSSL::WiFiClientSecure::_connectSSL(char const*) at /home/wouter/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/libraries/ESP8266WiFi/src/WiFiClientSecureBearSSL.cpp line 962
0x40219c70: esp_yield at /home/wouter/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/core_esp8266_main.cpp line 91
0x4021a8c3: delay at /home/wouter/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/core_esp8266_wiring.cpp line 54
0x40206d6d: WiFiClient::connect(IPAddress, unsigned short) at /home/wouter/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/libraries/ESP8266WiFi/src/include/ClientContext.h line 136
:  (inlined by) WiFiClient::connect(IPAddress, unsigned short) at /home/wouter/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/libraries/ESP8266WiFi/src/WiFiClient.cpp line 170
0x40222eed: BearSSL::WiFiClientSecure::connect(char const*, unsigned short) at /home/wouter/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/libraries/ESP8266WiFi/src/WiFiClientSecureBearSSL.cpp line 231
0x40225230: BearSSL::PrivateKey::getEC() const at ?? line ?
0x40225230: BearSSL::PrivateKey::getEC() const at ?? line ?
0x40216b5c: HTTPClient::connect() at /home/wouter/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/libraries/ESP8266HTTPClient/src/ESP8266HTTPClient.cpp line 1165
0x4021c16e: uart_write at /home/wouter/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/uart.cpp line 498
0x40217820: HTTPClient::sendRequest(char const*, unsigned char*, unsigned int) at /home/wouter/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/libraries/ESP8266HTTPClient/src/ESP8266HTTPClient.cpp line 655
0x40217d98: HardwareSerial::write(unsigned char const*, unsigned int) at /home/wouter/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/HardwareSerial.h line 158
0x40273eba: sleep_reset_analog_rtcreg_8266 at ?? line ?
0x402180a5: Print::write(char const*) at /home/wouter/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/Print.h line 60
0x40217d83: HardwareSerial::write(unsigned char) at /home/wouter/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/HardwareSerial.h line 154
0x402179ba: HTTPClient::GET() at /home/wouter/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/libraries/ESP8266HTTPClient/src/ESP8266HTTPClient.cpp line 575
0x402118e8: HydroMonitorLogging::sendPostData(char*) at /home/wouter/Arduino/libraries/HydroMonitor/src/HydroMonitorLogging.cpp line 730
0x40225470: BearSSL::PrivateKey::getEC() const at ?? line ?
0x4022c4c0: _vsprintf_r at /home/earle/src/esp-quick-toolchain/repo/newlib/newlib/libc/stdio/vsprintf.c line 65
0x40217d98: HardwareSerial::write(unsigned char const*, unsigned int) at /home/wouter/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/HardwareSerial.h line 158
0x4022000a: spiffs_object_truncate at /home/wouter/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/spiffs/spiffs_nucleus.cpp line 1727
0x40211d41: HydroMonitorLogging::transmitMessages() at /home/wouter/Arduino/libraries/HydroMonitor/src/HydroMonitorLogging.cpp line 337
0x40211caa: HydroMonitorLogging::transmitMessages() at /home/wouter/Arduino/libraries/HydroMonitor/src/HydroMonitorLogging.cpp line 326
0x40204dab: handleAPI() at /home/wouter/Arduino/Williams_fridge/Fridge_control/webAPI.ino line 149
0x402251c8: BearSSL::PrivateKey::getEC() const at ?? line ?
0x40217d98: HardwareSerial::write(unsigned char const*, unsigned int) at /home/wouter/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/HardwareSerial.h line 158
0x40218130: Print::println() at /home/wouter/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/Print.cpp line 178
0x402121b5: HydroMonitorLogging::logData() at /home/wouter/Arduino/libraries/HydroMonitor/src/HydroMonitorLogging.cpp line 250
0x40217d83: HardwareSerial::write(unsigned char) at /home/wouter/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/HardwareSerial.h line 154
0x40224948: Print::write(char) at /home/wouter/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/Print.h line 73
0x40218114: Print::print(char) at /home/wouter/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/Print.cpp line 126
0x402106f4: HydroMonitorIsolatedSensorBoard::readSensor(bool) at /home/wouter/Arduino/libraries/HydroMonitor/src/HydroMonitorIsolatedSensorBoard.cpp line 36
0x40207a07: TwoWire::requestFrom(int, int) at /home/wouter/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/libraries/Wire/Wire.cpp line 134
0x402042f9: loop at /home/wouter/Arduino/Williams_fridge/Fridge_control/loop.ino line 36
0x40219d20: loop_wrapper() at /home/wouter/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/core_esp8266_main.cpp line 125
0x401015d5: cont_wrapper at /home/wouter/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/cont.S line 81
</code>```

Note: I also asked on the esp8266 forum, and opened an issue on github about the same.

答:
I tested the free heap and got around 32 kB. So didn't expect any memory issues.

Turns out, 32 kB is less than 17 kB + 5 kB - for clientSecure and server respectively. And that's what caused the crashes. Dropping SSL encryption completely solved the problem. The development team mentioned it must be contiguous memory - which for whatever reason that 32 kB of mine apparently isn't.

Simple conclusion: you can not run the server (just http - no encryption) AND have a secure client in the same program.

No AJAX, by the way. Haven't gotten around to that level yet.

Body:
I'm trying to debug a large sketch, I'm occasionally getting a crash related to the web interface, and am trying to find out where exactly this is going wrong.

The stack trace ends with:

last failed alloc call: 4022D552(1480)

This particular address is not present in the decode stack trace itself, but may hold the key to finding the source of the problem. Any suggestions on how to track this one down?

Decoding 36 results
0x402222c5: BearSSL::WiFiClientSecure::_installClientX509Validator() at /home/wouter/.arduino15/packages/esp8266/tools/xtensa-lx106-elf-gcc/2.5.0-3-20ed2b9/xtensa-lx106-elf/include/c++/4.8.2/bits/shared_ptr_base.h line 986
:  (inlined by) ?? at /home/wouter/.arduino15/packages/esp8266/tools/xtensa-lx106-elf-gcc/2.5.0-3-20ed2b9/xtensa-lx106-elf/include/c++/4.8.2/bits/shared_ptr.h line 316
:  (inlined by) ?? at /home/wouter/.arduino15/packages/esp8266/tools/xtensa-lx106-elf-gcc/2.5.0-3-20ed2b9/xtensa-lx106-elf/include/c++/4.8.2/bits/shared_ptr.h line 598
:  (inlined by) ?? at /home/wouter/.arduino15/packages/esp8266/tools/xtensa-lx106-elf-gcc/2.5.0-3-20ed2b9/xtensa-lx106-elf/include/c++/4.8.2/bits/shared_ptr.h line 614
:  (inlined by) BearSSL::WiFiClientSecure::_installClientX509Validator() at /home/wouter/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/libraries/ESP8266WiFi/src/WiFiClientSecureBearSSL.cpp line 877
0x40222cfc: BearSSL::WiFiClientSecure::_connectSSL(char const*) at /home/wouter/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/libraries/ESP8266WiFi/src/WiFiClientSecureBearSSL.cpp line 962
0x40219c70: esp_yield at /home/wouter/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/core_esp8266_main.cpp line 91
0x4021a8c3: delay at /home/wouter/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/core_esp8266_wiring.cpp line 54
0x40206d6d: WiFiClient::connect(IPAddress, unsigned short) at /home/wouter/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/libraries/ESP8266WiFi/src/include/ClientContext.h line 136
:  (inlined by) WiFiClient::connect(IPAddress, unsigned short) at /home/wouter/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/libraries/ESP8266WiFi/src/WiFiClient.cpp line 170
0x40222eed: BearSSL::WiFiClientSecure::connect(char const*, unsigned short) at /home/wouter/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/libraries/ESP8266WiFi/src/WiFiClientSecureBearSSL.cpp line 231
0x40225230: BearSSL::PrivateKey::getEC() const at ?? line ?
0x40225230: BearSSL::PrivateKey::getEC() const at ?? line ?
0x40216b5c: HTTPClient::connect() at /home/wouter/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/libraries/ESP8266HTTPClient/src/ESP8266HTTPClient.cpp line 1165
0x4021c16e: uart_write at /home/wouter/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/uart.cpp line 498
0x40217820: HTTPClient::sendRequest(char const*, unsigned char*, unsigned int) at /home/wouter/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/libraries/ESP8266HTTPClient/src/ESP8266HTTPClient.cpp line 655
0x40217d98: HardwareSerial::write(unsigned char const*, unsigned int) at /home/wouter/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/HardwareSerial.h line 158
0x40273eba: sleep_reset_analog_rtcreg_8266 at ?? line ?
0x402180a5: Print::write(char const*) at /home/wouter/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/Print.h line 60
0x40217d83: HardwareSerial::write(unsigned char) at /home/wouter/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/HardwareSerial.h line 154
0x402179ba: HTTPClient::GET() at /home/wouter/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/libraries/ESP8266HTTPClient/src/ESP8266HTTPClient.cpp line 575
0x402118e8: HydroMonitorLogging::sendPostData(char*) at /home/wouter/Arduino/libraries/HydroMonitor/src/HydroMonitorLogging.cpp line 730
0x40225470: BearSSL::PrivateKey::getEC() const at ?? line ?
0x4022c4c0: _vsprintf_r at /home/earle/src/esp-quick-toolchain/repo/newlib/newlib/libc/stdio/vsprintf.c line 65
0x40217d98: HardwareSerial::write(unsigned char const*, unsigned int) at /home/wouter/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/HardwareSerial.h line 158
0x4022000a: spiffs_object_truncate at /home/wouter/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/spiffs/spiffs_nucleus.cpp line 1727
0x40211d41: HydroMonitorLogging::transmitMessages() at /home/wouter/Arduino/libraries/HydroMonitor/src/HydroMonitorLogging.cpp line 337
0x40211caa: HydroMonitorLogging::transmitMessages() at /home/wouter/Arduino/libraries/HydroMonitor/src/HydroMonitorLogging.cpp line 326
0x40204dab: handleAPI() at /home/wouter/Arduino/Williams_fridge/Fridge_control/webAPI.ino line 149
0x402251c8: BearSSL::PrivateKey::getEC() const at ?? line ?
0x40217d98: HardwareSerial::write(unsigned char const*, unsigned int) at /home/wouter/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/HardwareSerial.h line 158
0x40218130: Print::println() at /home/wouter/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/Print.cpp line 178
0x402121b5: HydroMonitorLogging::logData() at /home/wouter/Arduino/libraries/HydroMonitor/src/HydroMonitorLogging.cpp line 250
0x40217d83: HardwareSerial::write(unsigned char) at /home/wouter/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/HardwareSerial.h line 154
0x40224948: Print::write(char) at /home/wouter/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/Print.h line 73
0x40218114: Print::print(char) at /home/wouter/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/Print.cpp line 126
0x402106f4: HydroMonitorIsolatedSensorBoard::readSensor(bool) at /home/wouter/Arduino/libraries/HydroMonitor/src/HydroMonitorIsolatedSensorBoard.cpp line 36
0x40207a07: TwoWire::requestFrom(int, int) at /home/wouter/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/libraries/Wire/Wire.cpp line 134
0x402042f9: loop at /home/wouter/Arduino/Williams_fridge/Fridge_control/loop.ino line 36
0x40219d20: loop_wrapper() at /home/wouter/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/core_esp8266_main.cpp line 125
0x401015d5: cont_wrapper at /home/wouter/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/cont.S line 81

Note: I also asked on the esp8266 forum, and opened an issue on github about the same.


问:
How can I create Nginx IIS LoadBalancer by using Powershell over Octopus?
How can I create Nginx load balancer with IIS? This question is not easy to describe for me. So I separated 2 phases about my problem.

1)there is  1 Nginx server(app.xyz.com) infront of IIS Websites (app1.xyz.com,app2.xyz.com,app3.xyz.com ) All requests are sent to app.xyz.com because it is a load balancer. Is it easy to do that?  How can I do that by using Octopus with powershell.

2) I have to stop app1.xyz.com by deploying while app2.xyz.com and app3.xyz.co. working.

When

```<code> app1.xyz.com (DOWN)    app1.xyz.com (UP)     app1.xyz.com (UP)
 app1.xyz.com (UP)      app1.xyz.com (DOWN)   app1.xyz.com (UP)
 app1.xyz.com (UP)      app1.xyz.com (UP)     app1.xyz.com (DOWN)
</code>```

step by step deploying without stopping all web apps. Please look at below pictures What I draw:

nginx.conf:

worker_processes  4;

events {
    worker_connections  1024;
}

http {
    client_max_body_size 100M;
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;

 upstream loadbalancer.xyz.com {
    server staging1.xyz.com:996;
    server staging2.xyz.com:997;
    keepalive 15;
  }

server {
    listen 999;

    location / {

      proxy_pass https://loadbalancer.xyz.com;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header X-Forwarded-Proto $scheme;
      proxy_set_header Host $http_host;
      proxy_set_header X-NginX-Proxy true;
    }

  }
}

```

答: If you aren't completely sold on using nginx for the load balancer i've done the same thing you are describing with using IIS as a proxy / load balancer which routes to the application IIS servers behind it. You can then use windows network load balancer to make your proxy / load balancers for your proxies (assuming you make more than 1) for high availability too if you desire. If that is something you are interested in I can help you out with that but using nginx i'm not the best with for load balancers. I'd comment but i'm new to stack overflow... Sorry...</p>

Body:
How can I create Nginx load balancer with IIS? This question is not easy to describe for me. So I separated 2 phases about my problem.

1)there is  1 Nginx server(app.xyz.com) infront of IIS Websites (app1.xyz.com,app2.xyz.com,app3.xyz.com ) All requests are sent to app.xyz.com because it is a load balancer. Is it easy to do that?  How can I do that by using Octopus with powershell.

2) I have to stop app1.xyz.com by deploying while app2.xyz.com and app3.xyz.co. working.

When

 app1.xyz.com (DOWN)    app1.xyz.com (UP)     app1.xyz.com (UP)
 app1.xyz.com (UP)      app1.xyz.com (DOWN)   app1.xyz.com (UP)
 app1.xyz.com (UP)      app1.xyz.com (UP)     app1.xyz.com (DOWN)

step by step deploying without stopping all web apps. Please look at below pictures What I draw:

nginx.conf:

worker_processes  4;

events {
    worker_connections  1024;
}

http {
    client_max_body_size 100M;
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;

 upstream loadbalancer.xyz.com {
    server staging1.xyz.com:996;
    server staging2.xyz.com:997;
    keepalive 15;
  }

server {
    listen 999;

    location / {

      proxy_pass https://loadbalancer.xyz.com;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header X-Forwarded-Proto $scheme;
      proxy_set_header Host $http_host;
      proxy_set_header X-NginX-Proxy true;
    }

  }
}


问:
How can I properly change the title of react-bootstrap DropdownButton on click?
I am trying to change the displayed text/title in the DropdownButton upon clicking on a Dropdown.Item.

I've tried to pass various parameters into the changeValue method/function but to no solution as of yet. Using this approach, text the parameter in the function appears to be empty. Therefore the state property, dropDownValue is becoming empty, thus leaving me with no title in the drop down after click on an item.

```<code>import React from 'react';
import './App.css';
import DropdownButton from 'react-bootstrap/DropdownButton';
import Dropdown from 'react-bootstrap/Dropdown';

class App extends React.Component {
  constructor() {
    super();

    this.state = {
      dropDownValue: "Select an item"
    }
  }

  changeValue(text) {
    this.setState({dropDownValue: text})
  }

  render() {
    return (
      <div className="App">
        <header className="App-header">
        </header>
        <div>
        <DropdownButton id="dropdown-item-button" title={this.state.dropDownValue} className="format">
          <Dropdown.Item as="button"><div onClick={() => this.changeValue(this.textContent)}>Item #1</div></Dropdown.Item>
          <Dropdown.Item as="button"><div onClick={() => this.changeValue(this.textContent)}>Item #2</div></Dropdown.Item>
          <Dropdown.Item as="button"><div onClick={() => this.changeValue(this.textContent)}>Item #3</div></Dropdown.Item>
        </DropdownButton>
        </div>
      </div>
    );
  }
}

export default App;
</code>```

答:
Just change this,

```<code><Dropdown.Item as="button"><div onClick={() => this.changeValue(this.textContent)}>Item #1</div></Dropdown.Item>
</code>```

with this,

```<code><Dropdown.Item as="button"><div onClick={(e) => this.changeValue(e.target.textContent)}>Item #1</div></Dropdown.Item>
</code>```

Body:
I am trying to change the displayed text/title in the DropdownButton upon clicking on a Dropdown.Item.

I've tried to pass various parameters into the changeValue method/function but to no solution as of yet. Using this approach, text the parameter in the function appears to be empty. Therefore the state property, dropDownValue is becoming empty, thus leaving me with no title in the drop down after click on an item.

import React from 'react';
import './App.css';
import DropdownButton from 'react-bootstrap/DropdownButton';
import Dropdown from 'react-bootstrap/Dropdown';

class App extends React.Component {
  constructor() {
    super();

    this.state = {
      dropDownValue: "Select an item"
    }
  }

  changeValue(text) {
    this.setState({dropDownValue: text})
  }

  render() {
    return (

        <DropdownButton id="dropdown-item-button" title={this.state.dropDownValue} className="format">
          <Dropdown.Item as="button">
 this.changeValue(this.textContent)}>Item #1
</Dropdown.Item>
          <Dropdown.Item as="button">
 this.changeValue(this.textContent)}>Item #2
</Dropdown.Item>
          <Dropdown.Item as="button">
 this.changeValue(this.textContent)}>Item #3
</Dropdown.Item>
        </DropdownButton>

    );
  }
}

export default App;

Body:
Just change this,

<Dropdown.Item as="button"><div onClick={() => this.changeValue(this.textContent)}>Item #1</div></Dropdown.Item>

with this,

<Dropdown.Item as="button"><div onClick={(e) => this.changeValue(e.target.textContent)}>Item #1</div></Dropdown.Item>


问:
How can XMonad spawn a process with a specified working directory?
I am using (and loving!) XMonad as a window manager. However, I'm not sure how to implement a keyboard shortcut that can spawn a new process/window with the working directory of the current window.

I'm thinking there are two parts to this problem: Determining the working directory of the currently-active window, and spawning a process with a given working directory.

For process spawning, I'm currently using a hack where I spawn /bin/sh, that cd's to the desired location then starts the program. Is there a more elegant way to do this?

For determining the working directory of the current window, I have no idea how to do this. A quick search of xmonad-contrib didn't show anything, though I might have missed something. Is this an attribute that X makes available to the window manager? Maybe I could do something with the /proc tree?

答:
spawn already calls out to /bin/sh, so you can just shove the cd into the thing you spawn, as in spawn "cd /very/good/directory && very-good-executable --very --good --arguments".

There is not even a reliable way to detect which process is associated with a given window -- and even if you could it may not even be running on this machine! -- let alone its working directory. But see also the _NET_WM_PID atom which is occasionally available and this question on the Unix stackexchange.


问:
Sample code that takes a full resolution pciture
I've tried and tried and tried to find example code that takes a full E.g 5MP - not 800x480 preview sized picture but failed miserably.  Has anyone got any working code please?</p>

答: Since posting, I've managed to find this source github.com/commonsguy/cw-advandroid/tree/master/Camera/Picture which seems to work (I added in parameters.setPictureSize(2048,1536)in PictureDemo.java and it returned a jpeg with that size so it looks like a good basis to work with</p>


问:
Check if a class element exists depending the class attribute using Xpath
I need to get the ratings(stars) of a particular company using Xpath .Below is the block of div element from which I need to decide if its a 5 star , 4 star , 3 star etc depending the class attribute

div class="star-rating star-rating-4 star-rating--medium" div

"star-rating star-rating-4 star-rating--medium" , if this is class with 4 star rating  I need to return 4 , 5 if its a 5 star rating and so on .One way I can do this is try to get Xpath of all variants(3,4,5 star rating) and whichever doesn't turn up as null return that .Is there any better way to achieve  this ?

答:
Here is the xpath
Based on the class of div:

```<code> //div[@class='star-rating star-rating-4 star-rating--medium']/substring(@class,string-length('star-rating star-rating-')+1,1)
</code>```

OutPut: 4

Based on index of the rating div:

```<code>  //div[starts-with(@class,'star-rating star-rating-')][2]/substring(@class,string-length('star-rating star-rating-')+1,1)
</code>```

This will return the rating of 2nd div with class name that starts with star-rating star-rating-

Body:
Here is the xpath
Based on the class of div:

 //div[@class='star-rating star-rating-4 star-rating--medium']/substring(@class,string-length('star-rating star-rating-')+1,1)

OutPut: 4

Based on index of the rating div:

  //div[starts-with(@class,'star-rating star-rating-')][2]/substring(@class,string-length('star-rating star-rating-')+1,1)

This will return the rating of 2nd div with class name that starts with star-rating star-rating-