问:
Aerospike - No improvements in latency on moving to in-memory cluster from on-disk cluster
To begin with, we had an aerospike cluster having 5 nodes of i2.2xlarge type in AWS, which our production fleet of around 200 servers was using to store/retrieve data. The aerospike config of the cluster was as follows -

```<code>service {
        user root
        group root
        paxos-single-replica-limit 1 # Number of nodes where the replica count is automatically reduced to 1.
        pidfile /var/run/aerospike/asd.pid
        service-threads 8
        transaction-queues 8
        transaction-threads-per-queue 4
        fabric-workers 8
        transaction-pending-limit 100
        proto-fd-max 25000
}

logging {
        # Log file must be an absolute path.
        file /var/log/aerospike/aerospike.log {
                context any info
        }
}

network {
        service {
                address any
                port 3000
        }

        heartbeat {
                mode mesh
                port 3002 # Heartbeat port for this node.

                # List one or more other nodes, one ip-address & port per line:
                mesh-seed-address-port <IP> 3002
                mesh-seed-address-port <IP> 3002
                mesh-seed-address-port <IP> 3002
                mesh-seed-address-port <IP> 3002
               # mesh-seed-address-port <IP> 3002
                interval 250
                timeout 10
        }

        fabric {
                port 3001
        }

        info {
                port 3003
        }
}

namespace FC {
        replication-factor 2
        memory-size 7G
        default-ttl 30d # 30 days, use 0 to never expire/evict.

        high-water-disk-pct 80    # How full may the disk become before the server begins eviction
            high-water-memory-pct 70 # Evict non-zero TTL data if capacity exceeds # 70% of 15GB
               stop-writes-pct 90       # Stop writes if capacity exceeds 90% of 15GB

                  storage-engine device {
                  device /dev/xvdb1
                  write-block-size 256K
                      }

}
</code>```

It was properly handling the traffic corresponding to the namespace "FC", with latencies within 14 ms, as shown in the following graph plotted using graphite -

However, on turning on another namespace, with much higher traffic on the same cluster, it started to give a lot of timeouts and higher latencies, as we scaled up the number of servers using the same cluster of 5 nodes (increasing number of servers step by step from 20 to 40 to 60) with the following namespace configuration -

```<code>namespace HEAVYNAMESPACE {
        replication-factor 2
        memory-size 35G
        default-ttl 30d # 30 days, use 0 to never expire/evict.

 high-water-disk-pct 80    # How full may the disk become before the server begins eviction
    high-water-memory-pct 70 # Evict non-zero TTL data if capacity exceeds # 70% of 35GB
   stop-writes-pct 90       # Stop writes if capacity exceeds 90% of 35GB

   storage-engine device {
device /dev/xvdb8
write-block-size 256K
    }

}
</code>```

Following were the observations -

----FC Namespace----

```<code>20 - servers, 6k Write TPS, 16K Read TPS
set latency = 10ms
set timeouts = 1
get latency = 15ms
get timeouts = 3

40 - servers, 12k Write TPS, 17K Read TPS
set latency = 12ms
set timeouts = 1
get latency = 20ms
get timeouts = 5

60 - servers, 17k Write TPS, 18K Read TPS
set latency = 25ms
set timeouts = 5
get latency = 30ms
get timeouts = 10-50 (fluctuating)
</code>```

----HEAVYNAMESPACE----

```<code>20 - del servers, 6k Write TPS, 16K Read TPS
set latency = 7ms
set timeouts = 1
get latency = 5ms
get timeouts = 0
no of keys = 47 million x 2
disk usage = 121 gb
ram usage = 5.62 gb

40 - del servers, 12k Write TPS, 17K Read TPS
set latency = 15ms
set timeouts = 5
get latency = 12ms
get timeouts = 2

60 - del servers, 17k Write TPS, 18K Read TPS
set latency = 25ms
set timeouts = 25-75 (fluctuating)
get latency = 25ms
get timeouts = 2-15 (fluctuating)
</code>```

* Set latency refers to latency in setting aerospike cache keys and similarly get for getting keys.

We had to turn off the namespace "HEAVYNAMESPACE" after reaching 60 servers.

We then started a fresh POC with a cluster having nodes which were r3.4xlarge instances of AWS (find details here https://aws.amazon.com/ec2/instance-types/), with the key difference in aerospike configuration being the usage of memory only for caching, hoping that it would give better performance. Here is the aerospike.conf file -

```<code>service {
        user root
        group root
        paxos-single-replica-limit 1 # Number of nodes where the replica count is automatically reduced to 1.
        pidfile /var/run/aerospike/asd.pid
        service-threads 16
        transaction-queues 16
        transaction-threads-per-queue 4
        proto-fd-max 15000
}

logging {
        # Log file must be an absolute path.
        file /var/log/aerospike/aerospike.log {
                context any info
        }
}

network {
        service {
                address any
                port 3000
        }

        heartbeat {
                mode mesh
                port 3002 # Heartbeat port for this node.

                # List one or more other nodes, one ip-address & port per line:
                mesh-seed-address-port <IP> 3002
                mesh-seed-address-port <IP> 3002
                mesh-seed-address-port <IP> 3002
                mesh-seed-address-port <IP> 3002
                mesh-seed-address-port <IP> 3002

                interval 250
                timeout 10
        }

        fabric {
                port 3001
        }

        info {
                port 3003
        }
}

namespace FC {
        replication-factor 2
        memory-size 30G
        storage-engine memory
                default-ttl 30d # 30 days, use 0 to never expire/evict.

        high-water-memory-pct 80 # Evict non-zero TTL data if capacity exceeds # 70% of 15GB
        stop-writes-pct 90       # Stop writes if capacity exceeds 90% of 15GB

}
</code>```

We began with the FC namespace only, and decided to go ahead with the HEAVYNAMESPACE only if we saw significant improvements with the FC namespace, but we didn't. Here are the current observations with different combinations of node count and server count -

Current stats

Observation Point 1 - 4 nodes serving 130 servers.
Point 2 - 5 nodes serving 80 servers.
Point 3 - 5 nodes serving 100 servers.

These observation points are highlighted in the graphs below -

Get latency -

Set successes (giving a measure of the load handled by the cluster) -

We also observed that -

Total memory usage across cluster is 5.52 GB of 144 GB. Node-wise memory usage is ~ 1.10 GB out of 28.90 GB.

There were no observed write failures yet.

There were occasional get/set timeouts which looked fine.

No evicted objects.

Conclusion

We are not seeing the improvements we had expected, by using the memory-only configuration. We would like to get some pointers to be able to scale up with the same cost -
 - via tweaking the aerospike configurations
 - or by using some more suitable AWS instance type (even if that would lead to cost cutting).

Update

Output of top command on one of the aerospike servers, to show SI (Pointed out by @Sunil in his answer) -

```<code>$ top
top - 08:02:21 up 188 days, 48 min,  1 user,  load average: 0.07, 0.07, 0.02
Tasks: 179 total,   1 running, 178 sleeping,   0 stopped,   0 zombie
Cpu(s):  0.3%us,  0.1%sy,  0.0%ni, 99.4%id,  0.0%wa,  0.0%hi,  0.2%si,  0.0%st
Mem:  125904196k total,  2726964k used, 123177232k free,   148612k buffers
Swap:        0k total,        0k used,        0k free,   445968k cached

   PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND
 63421 root      20   0 5217m 1.6g 4340 S  6.3  1.3 461:08.83 asd
</code>```

If I am not wrong, the SI appears to be 0.2%. I checked the same on all the nodes of the cluster and it is 0.2% on one and 0.1% on the rest of the three.

Also, here is the output of the network stats on the same node -

```<code>$ sar -n DEV 10 10
Linux 4.4.30-32.54.amzn1.x86_64 (ip-10-111-215-72)      07/10/17        _x86_64_        (16 CPU)

08:09:16        IFACE   rxpck/s   txpck/s    rxkB/s    txkB/s   rxcmp/s   txcmp/s  rxmcst/s   %ifutil
08:09:26           lo     12.20     12.20      5.61      5.61      0.00      0.00      0.00      0.00
08:09:26         eth0   2763.60   1471.60    299.24    233.08      0.00      0.00      0.00      0.00

08:09:26        IFACE   rxpck/s   txpck/s    rxkB/s    txkB/s   rxcmp/s   txcmp/s  rxmcst/s   %ifutil
08:09:36           lo     12.00     12.00      5.60      5.60      0.00      0.00      0.00      0.00
08:09:36         eth0   2772.60   1474.50    300.08    233.48      0.00      0.00      0.00      0.00

08:09:36        IFACE   rxpck/s   txpck/s    rxkB/s    txkB/s   rxcmp/s   txcmp/s  rxmcst/s   %ifutil
08:09:46           lo     17.90     17.90     15.21     15.21      0.00      0.00      0.00      0.00
08:09:46         eth0   2802.80   1491.90    304.63    245.33      0.00      0.00      0.00      0.00

08:09:46        IFACE   rxpck/s   txpck/s    rxkB/s    txkB/s   rxcmp/s   txcmp/s  rxmcst/s   %ifutil
08:09:56           lo     12.00     12.00      5.60      5.60      0.00      0.00      0.00      0.00
08:09:56         eth0   2805.20   1494.30    304.37    237.51      0.00      0.00      0.00      0.00

08:09:56        IFACE   rxpck/s   txpck/s    rxkB/s    txkB/s   rxcmp/s   txcmp/s  rxmcst/s   %ifutil
08:10:06           lo      9.40      9.40      5.05      5.05      0.00      0.00      0.00      0.00
08:10:06         eth0   3144.10   1702.30    342.54    255.34      0.00      0.00      0.00      0.00

08:10:06        IFACE   rxpck/s   txpck/s    rxkB/s    txkB/s   rxcmp/s   txcmp/s  rxmcst/s   %ifutil
08:10:16           lo     12.00     12.00      5.60      5.60      0.00      0.00      0.00      0.00
08:10:16         eth0   2862.70   1522.20    310.15    238.32      0.00      0.00      0.00      0.00

08:10:16        IFACE   rxpck/s   txpck/s    rxkB/s    txkB/s   rxcmp/s   txcmp/s  rxmcst/s   %ifutil
08:10:26           lo     12.00     12.00      5.60      5.60      0.00      0.00      0.00      0.00
08:10:26         eth0   2738.40   1453.80    295.85    231.47      0.00      0.00      0.00      0.00

08:10:26        IFACE   rxpck/s   txpck/s    rxkB/s    txkB/s   rxcmp/s   txcmp/s  rxmcst/s   %ifutil
08:10:36           lo     11.79     11.79      5.59      5.59      0.00      0.00      0.00      0.00
08:10:36         eth0   2758.14   1464.14    297.59    231.47      0.00      0.00      0.00      0.00

08:10:36        IFACE   rxpck/s   txpck/s    rxkB/s    txkB/s   rxcmp/s   txcmp/s  rxmcst/s   %ifutil
08:10:46           lo     12.00     12.00      5.60      5.60      0.00      0.00      0.00      0.00
08:10:46         eth0   3100.40   1811.30    328.31    289.92      0.00      0.00      0.00      0.00

08:10:46        IFACE   rxpck/s   txpck/s    rxkB/s    txkB/s   rxcmp/s   txcmp/s  rxmcst/s   %ifutil
08:10:56           lo      9.40      9.40      5.05      5.05      0.00      0.00      0.00      0.00
08:10:56         eth0   2753.40   1460.80    297.15    231.98      0.00      0.00      0.00      0.00

Average:        IFACE   rxpck/s   txpck/s    rxkB/s    txkB/s   rxcmp/s   txcmp/s  rxmcst/s   %ifutil
Average:           lo     12.07     12.07      6.45      6.45      0.00      0.00      0.00      0.00
Average:         eth0   2850.12   1534.68    307.99    242.79      0.00      0.00      0.00      0.00
</code>```

From the above, I think the total number of packets handled per second should be 2850.12+1534.68 = 4384.8 (sum of rxpck/s and txpck/s) which is well within 250K packets per second, as mentioned in The Amazon EC2 deployment guide on the Aerospike site which is referred in @RonenBotzer's answer.

Update 2

I ran the asadm command followed by show latency on one of the nodes of the cluster and from the output, it appears that there is no latency beyond 1 ms for both reads and writes -

```<code>Admin> show latency
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~read Latency~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
                               Node                 Time   Ops/Sec   >1Ms   >8Ms   >64Ms
                                  .                 Span         .      .      .       .
ip-10-111-215-72.ec2.internal:3000    11:35:01->11:35:11    1242.1    0.0    0.0     0.0
ip-10-13-215-20.ec2.internal:3000     11:34:57->11:35:07    1297.5    0.0    0.0     0.0
ip-10-150-147-167.ec2.internal:3000   11:35:04->11:35:14    1147.7    0.0    0.0     0.0
ip-10-165-168-246.ec2.internal:3000   11:34:59->11:35:09    1342.2    0.0    0.0     0.0
ip-10-233-158-213.ec2.internal:3000   11:35:00->11:35:10    1218.0    0.0    0.0     0.0
Number of rows: 5

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~write Latency~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
                               Node                 Time   Ops/Sec   >1Ms   >8Ms   >64Ms
                                  .                 Span         .      .      .       .
ip-10-111-215-72.ec2.internal:3000    11:35:01->11:35:11      33.0    0.0    0.0     0.0
ip-10-13-215-20.ec2.internal:3000     11:34:57->11:35:07      37.2    0.0    0.0     0.0
ip-10-150-147-167.ec2.internal:3000   11:35:04->11:35:14      36.4    0.0    0.0     0.0
ip-10-165-168-246.ec2.internal:3000   11:34:59->11:35:09      36.9    0.0    0.0     0.0
ip-10-233-158-213.ec2.internal:3000   11:35:00->11:35:10      33.9    0.0    0.0     0.0
Number of rows: 5
</code>```

答:
Aerospike has several modes for storage that you can configure:

Data in memory with no persistence

Data in memory, persisted to disk

Data on SSD, primary index in memory (AKA Hybrid Memory architecture)

In-Memory Optimizations

Release 3.11 and release 3.12 of
Aerospike include several big  performance improvements for in-memory namespaces.

Among these are a change to how partitions are represented, from a single red-black tree to sprigs (many sub-trees). The new config parameters partition-tree-sprigs and partition-tree-locks should be used appropriately. In your case, as r3.4xlarge instances have 122G of DRAM, you can afford the 311M of overhead associated with setting partition-tree-sprigs to the max value of 4096.

You should also consider the auto-pin=cpu setting, as well. This option does require Linux Kernal >= 3.19 which is part of Ubuntu >= 15.04 (but not many others yet).

Clustering Improvements

The recent releases 3.13 and 3.14 include a rewrite of the cluster manager. In general you should consider using the latest version, but I'm pointing out the aspects that will directly affect your performance.

EC2 Networking and Aerospike

You don't show the latency numbers of the cluster itself, so I suspect the problem is with the networking, rather than the nodes.

Older instance family types, such as the r3, c3, i2, come with ENIs - NICs which have a single transmit/receive queue. The software interrupts of cores accessing this queue may become a bottleneck as the number of CPUs increases, all of which need to wait for their turn to use the NIC. There's a knowledge base article in the Aerospike community discussion forum on using multiple ENIs with Aerospike to get around the limited performance capacity of the single ENI you initially get with such an instance. The Amazon EC2 deployment guide on the Aerospike site talks about using RPS to maximize TPS when you're in an instance that uses ENIs.

Alternatively, you should consider moving to the newer instances (r4, i3, etc) which come with multiqueue ENAs. These do not require RPS, and support higher TPS without adding extra cards. They also happen to have better chipsets, and cost significantly less than their older siblings (r4 is roughly 30% cheaper than r3, i3 is about 1/3 the price of the i2).

Body:
To begin with, we had an aerospike cluster having 5 nodes of i2.2xlarge type in AWS, which our production fleet of around 200 servers was using to store/retrieve data. The aerospike config of the cluster was as follows -

service {
        user root
        group root
        paxos-single-replica-limit 1 # Number of nodes where the replica count is automatically reduced to 1.
        pidfile /var/run/aerospike/asd.pid
        service-threads 8
        transaction-queues 8
        transaction-threads-per-queue 4
        fabric-workers 8
        transaction-pending-limit 100
        proto-fd-max 25000
}

logging {
        # Log file must be an absolute path.
        file /var/log/aerospike/aerospike.log {
                context any info
        }
}

network {
        service {
                address any
                port 3000
        }

        heartbeat {
                mode mesh
                port 3002 # Heartbeat port for this node.

                # List one or more other nodes, one ip-address & port per line:
                mesh-seed-address-port <IP> 3002
                mesh-seed-address-port <IP> 3002
                mesh-seed-address-port <IP> 3002
                mesh-seed-address-port <IP> 3002
               # mesh-seed-address-port <IP> 3002
                interval 250
                timeout 10
        }

        fabric {
                port 3001
        }

        info {
                port 3003
        }
}

namespace FC {
        replication-factor 2
        memory-size 7G
        default-ttl 30d # 30 days, use 0 to never expire/evict.

        high-water-disk-pct 80    # How full may the disk become before the server begins eviction
            high-water-memory-pct 70 # Evict non-zero TTL data if capacity exceeds # 70% of 15GB
               stop-writes-pct 90       # Stop writes if capacity exceeds 90% of 15GB

                  storage-engine device {
                  device /dev/xvdb1
                  write-block-size 256K
                      }

}

It was properly handling the traffic corresponding to the namespace "FC", with latencies within 14 ms, as shown in the following graph plotted using graphite -

However, on turning on another namespace, with much higher traffic on the same cluster, it started to give a lot of timeouts and higher latencies, as we scaled up the number of servers using the same cluster of 5 nodes (increasing number of servers step by step from 20 to 40 to 60) with the following namespace configuration -

namespace HEAVYNAMESPACE {
        replication-factor 2
        memory-size 35G
        default-ttl 30d # 30 days, use 0 to never expire/evict.

 high-water-disk-pct 80    # How full may the disk become before the server begins eviction
    high-water-memory-pct 70 # Evict non-zero TTL data if capacity exceeds # 70% of 35GB
   stop-writes-pct 90       # Stop writes if capacity exceeds 90% of 35GB

   storage-engine device {
device /dev/xvdb8
write-block-size 256K
    }

}

Following were the observations -

----FC Namespace----

20 - servers, 6k Write TPS, 16K Read TPS
set latency = 10ms
set timeouts = 1
get latency = 15ms
get timeouts = 3

40 - servers, 12k Write TPS, 17K Read TPS
set latency = 12ms
set timeouts = 1
get latency = 20ms
get timeouts = 5

60 - servers, 17k Write TPS, 18K Read TPS
set latency = 25ms
set timeouts = 5
get latency = 30ms
get timeouts = 10-50 (fluctuating)

----HEAVYNAMESPACE----

20 - del servers, 6k Write TPS, 16K Read TPS
set latency = 7ms
set timeouts = 1
get latency = 5ms
get timeouts = 0
no of keys = 47 million x 2
disk usage = 121 gb
ram usage = 5.62 gb

40 - del servers, 12k Write TPS, 17K Read TPS
set latency = 15ms
set timeouts = 5
get latency = 12ms
get timeouts = 2

60 - del servers, 17k Write TPS, 18K Read TPS
set latency = 25ms
set timeouts = 25-75 (fluctuating)
get latency = 25ms
get timeouts = 2-15 (fluctuating)

* Set latency refers to latency in setting aerospike cache keys and similarly get for getting keys.

We had to turn off the namespace "HEAVYNAMESPACE" after reaching 60 servers.

We then started a fresh POC with a cluster having nodes which were r3.4xlarge instances of AWS (find details here https://aws.amazon.com/ec2/instance-types/), with the key difference in aerospike configuration being the usage of memory only for caching, hoping that it would give better performance. Here is the aerospike.conf file -

service {
        user root
        group root
        paxos-single-replica-limit 1 # Number of nodes where the replica count is automatically reduced to 1.
        pidfile /var/run/aerospike/asd.pid
        service-threads 16
        transaction-queues 16
        transaction-threads-per-queue 4
        proto-fd-max 15000
}

logging {
        # Log file must be an absolute path.
        file /var/log/aerospike/aerospike.log {
                context any info
        }
}

network {
        service {
                address any
                port 3000
        }

        heartbeat {
                mode mesh
                port 3002 # Heartbeat port for this node.

                # List one or more other nodes, one ip-address & port per line:
                mesh-seed-address-port <IP> 3002
                mesh-seed-address-port <IP> 3002
                mesh-seed-address-port <IP> 3002
                mesh-seed-address-port <IP> 3002
                mesh-seed-address-port <IP> 3002

                interval 250
                timeout 10
        }

        fabric {
                port 3001
        }

        info {
                port 3003
        }
}

namespace FC {
        replication-factor 2
        memory-size 30G
        storage-engine memory
                default-ttl 30d # 30 days, use 0 to never expire/evict.

        high-water-memory-pct 80 # Evict non-zero TTL data if capacity exceeds # 70% of 15GB
        stop-writes-pct 90       # Stop writes if capacity exceeds 90% of 15GB

}

We began with the FC namespace only, and decided to go ahead with the HEAVYNAMESPACE only if we saw significant improvements with the FC namespace, but we didn't. Here are the current observations with different combinations of node count and server count -

Current stats

Observation Point 1 - 4 nodes serving 130 servers.
Point 2 - 5 nodes serving 80 servers.
Point 3 - 5 nodes serving 100 servers.

These observation points are highlighted in the graphs below -

Get latency -

Set successes (giving a measure of the load handled by the cluster) -

We also observed that -

Total memory usage across cluster is 5.52 GB of 144 GB. Node-wise memory usage is ~ 1.10 GB out of 28.90 GB.

There were no observed write failures yet.

There were occasional get/set timeouts which looked fine.

No evicted objects.

Conclusion

We are not seeing the improvements we had expected, by using the memory-only configuration. We would like to get some pointers to be able to scale up with the same cost -
 - via tweaking the aerospike configurations
 - or by using some more suitable AWS instance type (even if that would lead to cost cutting).

Update

Output of top command on one of the aerospike servers, to show SI (Pointed out by @Sunil in his answer) -

$ top
top - 08:02:21 up 188 days, 48 min,  1 user,  load average: 0.07, 0.07, 0.02
Tasks: 179 total,   1 running, 178 sleeping,   0 stopped,   0 zombie
Cpu(s):  0.3%us,  0.1%sy,  0.0%ni, 99.4%id,  0.0%wa,  0.0%hi,  0.2%si,  0.0%st
Mem:  125904196k total,  2726964k used, 123177232k free,   148612k buffers
Swap:        0k total,        0k used,        0k free,   445968k cached

   PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND
 63421 root      20   0 5217m 1.6g 4340 S  6.3  1.3 461:08.83 asd

If I am not wrong, the SI appears to be 0.2%. I checked the same on all the nodes of the cluster and it is 0.2% on one and 0.1% on the rest of the three.

Also, here is the output of the network stats on the same node -

$ sar -n DEV 10 10
Linux 4.4.30-32.54.amzn1.x86_64 (ip-10-111-215-72)      07/10/17        _x86_64_        (16 CPU)

08:09:16        IFACE   rxpck/s   txpck/s    rxkB/s    txkB/s   rxcmp/s   txcmp/s  rxmcst/s   %ifutil
08:09:26           lo     12.20     12.20      5.61      5.61      0.00      0.00      0.00      0.00
08:09:26         eth0   2763.60   1471.60    299.24    233.08      0.00      0.00      0.00      0.00

08:09:26        IFACE   rxpck/s   txpck/s    rxkB/s    txkB/s   rxcmp/s   txcmp/s  rxmcst/s   %ifutil
08:09:36           lo     12.00     12.00      5.60      5.60      0.00      0.00      0.00      0.00
08:09:36         eth0   2772.60   1474.50    300.08    233.48      0.00      0.00      0.00      0.00

08:09:36        IFACE   rxpck/s   txpck/s    rxkB/s    txkB/s   rxcmp/s   txcmp/s  rxmcst/s   %ifutil
08:09:46           lo     17.90     17.90     15.21     15.21      0.00      0.00      0.00      0.00
08:09:46         eth0   2802.80   1491.90    304.63    245.33      0.00      0.00      0.00      0.00

08:09:46        IFACE   rxpck/s   txpck/s    rxkB/s    txkB/s   rxcmp/s   txcmp/s  rxmcst/s   %ifutil
08:09:56           lo     12.00     12.00      5.60      5.60      0.00      0.00      0.00      0.00
08:09:56         eth0   2805.20   1494.30    304.37    237.51      0.00      0.00      0.00      0.00

08:09:56        IFACE   rxpck/s   txpck/s    rxkB/s    txkB/s   rxcmp/s   txcmp/s  rxmcst/s   %ifutil
08:10:06           lo      9.40      9.40      5.05      5.05      0.00      0.00      0.00      0.00
08:10:06         eth0   3144.10   1702.30    342.54    255.34      0.00      0.00      0.00      0.00

08:10:06        IFACE   rxpck/s   txpck/s    rxkB/s    txkB/s   rxcmp/s   txcmp/s  rxmcst/s   %ifutil
08:10:16           lo     12.00     12.00      5.60      5.60      0.00      0.00      0.00      0.00
08:10:16         eth0   2862.70   1522.20    310.15    238.32      0.00      0.00      0.00      0.00

08:10:16        IFACE   rxpck/s   txpck/s    rxkB/s    txkB/s   rxcmp/s   txcmp/s  rxmcst/s   %ifutil
08:10:26           lo     12.00     12.00      5.60      5.60      0.00      0.00      0.00      0.00
08:10:26         eth0   2738.40   1453.80    295.85    231.47      0.00      0.00      0.00      0.00

08:10:26        IFACE   rxpck/s   txpck/s    rxkB/s    txkB/s   rxcmp/s   txcmp/s  rxmcst/s   %ifutil
08:10:36           lo     11.79     11.79      5.59      5.59      0.00      0.00      0.00      0.00
08:10:36         eth0   2758.14   1464.14    297.59    231.47      0.00      0.00      0.00      0.00

08:10:36        IFACE   rxpck/s   txpck/s    rxkB/s    txkB/s   rxcmp/s   txcmp/s  rxmcst/s   %ifutil
08:10:46           lo     12.00     12.00      5.60      5.60      0.00      0.00      0.00      0.00
08:10:46         eth0   3100.40   1811.30    328.31    289.92      0.00      0.00      0.00      0.00

08:10:46        IFACE   rxpck/s   txpck/s    rxkB/s    txkB/s   rxcmp/s   txcmp/s  rxmcst/s   %ifutil
08:10:56           lo      9.40      9.40      5.05      5.05      0.00      0.00      0.00      0.00
08:10:56         eth0   2753.40   1460.80    297.15    231.98      0.00      0.00      0.00      0.00

Average:        IFACE   rxpck/s   txpck/s    rxkB/s    txkB/s   rxcmp/s   txcmp/s  rxmcst/s   %ifutil
Average:           lo     12.07     12.07      6.45      6.45      0.00      0.00      0.00      0.00
Average:         eth0   2850.12   1534.68    307.99    242.79      0.00      0.00      0.00      0.00

From the above, I think the total number of packets handled per second should be 2850.12+1534.68 = 4384.8 (sum of rxpck/s and txpck/s) which is well within 250K packets per second, as mentioned in The Amazon EC2 deployment guide on the Aerospike site which is referred in @RonenBotzer's answer.

Update 2

I ran the asadm command followed by show latency on one of the nodes of the cluster and from the output, it appears that there is no latency beyond 1 ms for both reads and writes -

Admin> show latency
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~read Latency~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
                               Node                 Time   Ops/Sec   >1Ms   >8Ms   >64Ms
                                  .                 Span         .      .      .       .
ip-10-111-215-72.ec2.internal:3000    11:35:01->11:35:11    1242.1    0.0    0.0     0.0
ip-10-13-215-20.ec2.internal:3000     11:34:57->11:35:07    1297.5    0.0    0.0     0.0
ip-10-150-147-167.ec2.internal:3000   11:35:04->11:35:14    1147.7    0.0    0.0     0.0
ip-10-165-168-246.ec2.internal:3000   11:34:59->11:35:09    1342.2    0.0    0.0     0.0
ip-10-233-158-213.ec2.internal:3000   11:35:00->11:35:10    1218.0    0.0    0.0     0.0
Number of rows: 5

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~write Latency~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
                               Node                 Time   Ops/Sec   >1Ms   >8Ms   >64Ms
                                  .                 Span         .      .      .       .
ip-10-111-215-72.ec2.internal:3000    11:35:01->11:35:11      33.0    0.0    0.0     0.0
ip-10-13-215-20.ec2.internal:3000     11:34:57->11:35:07      37.2    0.0    0.0     0.0
ip-10-150-147-167.ec2.internal:3000   11:35:04->11:35:14      36.4    0.0    0.0     0.0
ip-10-165-168-246.ec2.internal:3000   11:34:59->11:35:09      36.9    0.0    0.0     0.0
ip-10-233-158-213.ec2.internal:3000   11:35:00->11:35:10      33.9    0.0    0.0     0.0
Number of rows: 5


来源: stackexchange

问:
Angular 4 PipeTransform not applied
My custom pipe to shorten a string isn't working. I have included it in my app.module declarations and imported it in my component. The code is below.

 import { Pipe, PipeTransform } from '@angular/core';
/*
  Takes a string and replaces it with a shortend version based on the length you give it if its greater than 14 char for Example
  someString = "hey whats up my name is Bob and im from Bob town"
  {{value | shortString : length of new string}}
  {{someString | shortString: 10}}
*/
@Pipe({name: 'shortString'})
export class shortString implements PipeTransform {
  transform(value: any, length: number): string {
    console.log('expected new string '+value.slice(0,length)+'...');
    return (value.length()>14)?value.slice(0,length)+'...': value;
  }
}`
```

答:
Your pipe itself looks fine, but in order to use it, you have to import it into your module, and declare and export it so it's available in your component.

import { shortString } from './shortString.pipe';

@NgModule({
    imports: [
    ],
    declarations: [
        shortString
    ],
    exports: [
        shortString
    ],
    providers: [
    ]

})
export class SharedModule { }
```

Add this to whichever module is appropriate for your setup, I put all my pipes in a SharedModule, so that's why this is exporting SharedModule, but you may have this in MainModule or something else.

ContentLicense: CC BY-SA 4.0

Title: Angular 4 PipeTransform not applied

Body:
Your pipe itself looks fine, but in order to use it, you have to import it into your module, and declare and export it so it's available in your component.

import { shortString } from './shortString.pipe';

@NgModule({
    imports: [
    ],
    declarations: [
        shortString
    ],
    exports: [
        shortString
    ],
    providers: [
    ]

})
export class SharedModule { }

Add this to whichever module is appropriate for your setup, I put all my pipes in a SharedModule, so that's why this is exporting SharedModule, but you may have this in MainModule or something else.


问:
Return duplicate min values
See the table below for reference. I need to return duplicate rows containing the min value.

In this example I want to show only the 2 rows that have SLAT_LEN = 30 or rather the min SLAT_LEN. I tried rank but when I do it does a consecutive rank.  I want the duplicate sizes to have the same rank and to rank consecutively by size.

The sizes change so I can't just use a condition like SLAT_LEN = 30.

Or is there a different approach that I should take?

```<code>   select *
   from(
    select lg.wd_demand_id,wm.slat_len, wm.prof_size, wm.wd_material_id, wm.color, rank() over ( partition by wm.slat_len order by lg.wd_demand_id) as rank
    from wd_demand_log lg, wd_bins wb, wd_material wm, wd_bins_material wbm
    where lg.wd_bins_id = wb.wd_bins_id
    and lg.wd_material_id = wm.wd_material_id
    and lg.wd_bins_id = wbm.wd_bins_id
    and lg.wd_material_id = wbm.wd_material_id
    AND lg.plant_id = 44 AND lg.dept_id = 220 AND wb.plant_id = 44 AND wb.dept_id = 220
    AND NOT EXISTS(SELECT dmpln.wd_demand_id  FROM wd_demnd_pln_inv dmpln WHERE dmpln.wd_demand_id = lg.wd_demand_id)
    AND wm.prof_size = '2' AND wm.color = 450
    AND lg.wd_po_error is null)
</code>```

答:
Perhaps I am not understanding the problem correctly, but here is my potential solution:</p>

```<code>WITH aset
     AS (SELECT lg.wd_demand_id
              , wm.slat_len
              , wm.prof_size
              , wm.wd_material_id
              , wm.color
           FROM wd_demand_log lg, wd_bins wb, wd_material wm
              , wd_bins_material wbm
          WHERE lg.wd_bins_id = wb.wd_bins_id
            AND lg.wd_material_id = wm.wd_material_id
            AND lg.wd_bins_id = wbm.wd_bins_id
            AND lg.wd_material_id = wbm.wd_material_id
            AND lg.plant_id = 44
            AND lg.dept_id = 220
            AND wb.plant_id = 44
            AND wb.dept_id = 220
            AND NOT EXISTS
                    (SELECT dmpln.wd_demand_id
                       FROM wd_demnd_pln_inv dmpln
                      WHERE dmpln.wd_demand_id = lg.wd_demand_id)
            AND wm.prof_size = '2'
            AND wm.color = 450
            AND lg.wd_po_error IS NULL)
SELECT *
  FROM aset
 WHERE slat_len = (SELECT MIN (slat_len)
                     FROM aset)
</code>```

ContentLicense: CC BY-SA 3.0

Title: Return duplicate min values

Body:
See the table below for reference. I need to return duplicate rows containing the min value.

In this example I want to show only the 2 rows that have SLAT_LEN = 30 or rather the min SLAT_LEN. I tried rank but when I do it does a consecutive rank.  I want the duplicate sizes to have the same rank and to rank consecutively by size.

The sizes change so I can't just use a condition like SLAT_LEN = 30.

Or is there a different approach that I should take?

   select *
   from(
    select lg.wd_demand_id,wm.slat_len, wm.prof_size, wm.wd_material_id, wm.color, rank() over ( partition by wm.slat_len order by lg.wd_demand_id) as rank
    from wd_demand_log lg, wd_bins wb, wd_material wm, wd_bins_material wbm
    where lg.wd_bins_id = wb.wd_bins_id
    and lg.wd_material_id = wm.wd_material_id
    and lg.wd_bins_id = wbm.wd_bins_id
    and lg.wd_material_id = wbm.wd_material_id
    AND lg.plant_id = 44 AND lg.dept_id = 220 AND wb.plant_id = 44 AND wb.dept_id = 220
    AND NOT EXISTS(SELECT dmpln.wd_demand_id  FROM wd_demnd_pln_inv dmpln WHERE dmpln.wd_demand_id = lg.wd_demand_id)
    AND wm.prof_size = '2' AND wm.color = 450
    AND lg.wd_po_error is null)

Body:
Perhaps I am not understanding the problem correctly, but here is my potential solution:

WITH aset
     AS (SELECT lg.wd_demand_id
              , wm.slat_len
              , wm.prof_size
              , wm.wd_material_id
              , wm.color
           FROM wd_demand_log lg, wd_bins wb, wd_material wm
              , wd_bins_material wbm
          WHERE lg.wd_bins_id = wb.wd_bins_id
            AND lg.wd_material_id = wm.wd_material_id
            AND lg.wd_bins_id = wbm.wd_bins_id
            AND lg.wd_material_id = wbm.wd_material_id
            AND lg.plant_id = 44
            AND lg.dept_id = 220
            AND wb.plant_id = 44
            AND wb.dept_id = 220
            AND NOT EXISTS
                    (SELECT dmpln.wd_demand_id
                       FROM wd_demnd_pln_inv dmpln
                      WHERE dmpln.wd_demand_id = lg.wd_demand_id)
            AND wm.prof_size = '2'
            AND wm.color = 450
            AND lg.wd_po_error IS NULL)
SELECT *
  FROM aset
 WHERE slat_len = (SELECT MIN (slat_len)
                     FROM aset)


问:
Can recursion be used to guarantee an object gets saved to the DB in Ruby?
I am making payouts to my sub-merchants and wanted to know if I could use recursion to guarantee that when a payout is made to them, we save that data to our DB.

Example:

```<code>def make_payout
  result = object.process_payout_through_gateway
  if result.success?
    payout = Payout.new
    payout[:paid] = true
    save_payout(payout)
  end
end

def save_payout(payout)
  begin
    payout.save!
  rescue e
    save_payout(payout)
  end
end
</code>```

答:
If you want to gaunrentee it gets saved without validating the object:

payout.save(validate: false)

Body:
I am making payouts to my sub-merchants and wanted to know if I could use recursion to guarantee that when a payout is made to them, we save that data to our DB.

Example:

def make_payout
  result = object.process_payout_through_gateway
  if result.success?
    payout = Payout.new
    payout[:paid] = true
    save_payout(payout)
  end
end

def save_payout(payout)
  begin
    payout.save!
  rescue e
    save_payout(payout)
  end
end


问:
Error using sub2ind (line 52) Out of range subscript Matlab
I used the same code for two  different input matrices,
In both cases i will call it "the input matrix A"

The first case is a 7000X4

The second case is a 29500X12

I need to split a selected column in windows
and then for each window
i need to calculate the std and store the value inside a std_vals  matrix

I took care to change the value of my input variables.

In the first case my goal was to analyze the 4th column,
in the second case my goal was to analyze the 12th column

In the first case the code worked

In the second case the code returned me an error message

I tried to analyze all the steps in the code, but i dind't find the error.

Could you please help me to understand better?

```<code>column_length=size(A,1);
Amod= mod(column_length,100);
if Amod~=0
    A=A(1:(size(A,1)-Amod),:);
    end
newlenght=size(A);

%selected column vector to analyze
columnselected=4;
%window dimension
window_size=200;

%overlap between two windows
overlap=0;

%increment needed
step=window_size - overlap;

%std threshold
soglia=2;
std_vals= NaN(size(A,1),1);
devstd=std(A(:,4));

stdInds=bsxfun(@plus,1:step:(size(A,1)-overlap),(0:(window_size-1)).');

%In the first case size(stdInds)=200X35
%In the second case size(stdInds)=200X148
%In the first case size(repmat(columnselected,size(stdInds))=   200X35
%In the second case size(repmat(columnselected,size(stdInds))=  200X148
%In the first case size(A)=7000X4
%In the second case size(A)=29500X12
  std_vals=std(A(sub2ind(size(A),stdInds,repmat(columnselected,size(stdInds)))));

highStdWindows=find(std_vals>soglia);
</code>```

I am self taught. To understand better my error first i rewrite on a piece of paper the code, then i analyzed every step, and studied the output. I took me more than 4 hours.

I also tried to put in the second case a 7000X12 vector, but the code returned me the same error.

I think my method is not very efficent.

答:
Since your overlap for the windows is zero, the code below should work for any input array A. Change the COLUMN_INDEX and WINDOW_SIZE variables to your desired column and window size.

The idea is to reshape the desired column to be WINDOW_SIZE x N. Then simply call the std function which operates on the columns of this reshaped array.

```<code>COLUMN_INDEX = 4;
WINDOW_SIZE  = 200;

windowCount = floor( size( A, 1 ) / WINDOW_SIZE );
windowedColumn = reshape( A(1:WINDOW_SIZE*windowCount,COLUMN_INDEX), WINDOW_SIZE, windowCount );
stdVals = std( windowedColumn );
</code>```

Body:
I used the same code for two  different input matrices,
In both cases i will call it "the input matrix A"

The first case is a 7000X4

The second case is a 29500X12

I need to split a selected column in windows
and then for each window
i need to calculate the std and store the value inside a std_vals  matrix

I took care to change the value of my input variables.

In the first case my goal was to analyze the 4th column,
in the second case my goal was to analyze the 12th column

In the first case the code worked

In the second case the code returned me an error message

I tried to analyze all the steps in the code, but i dind't find the error.

Could you please help me to understand better?

column_length=size(A,1);
Amod= mod(column_length,100);
if Amod~=0
    A=A(1:(size(A,1)-Amod),:);
    end
newlenght=size(A);

%selected column vector to analyze
columnselected=4;
%window dimension
window_size=200;

%overlap between two windows
overlap=0;

%increment needed
step=window_size - overlap;

%std threshold
soglia=2;
std_vals= NaN(size(A,1),1);
devstd=std(A(:,4));

stdInds=bsxfun(@plus,1:step:(size(A,1)-overlap),(0:(window_size-1)).');

%In the first case size(stdInds)=200X35
%In the second case size(stdInds)=200X148
%In the first case size(repmat(columnselected,size(stdInds))=   200X35
%In the second case size(repmat(columnselected,size(stdInds))=  200X148
%In the first case size(A)=7000X4
%In the second case size(A)=29500X12
  std_vals=std(A(sub2ind(size(A),stdInds,repmat(columnselected,size(stdInds)))));

highStdWindows=find(std_vals>soglia);

I am self taught. To understand better my error first i rewrite on a piece of paper the code, then i analyzed every step, and studied the output. I took me more than 4 hours.

I also tried to put in the second case a 7000X12 vector, but the code returned me the same error.

I think my method is not very efficent.

Body:
Since your overlap for the windows is zero, the code below should work for any input array A. Change the COLUMN_INDEX and WINDOW_SIZE variables to your desired column and window size.

The idea is to reshape the desired column to be WINDOW_SIZE x N. Then simply call the std function which operates on the columns of this reshaped array.

COLUMN_INDEX = 4;
WINDOW_SIZE  = 200;

windowCount = floor( size( A, 1 ) / WINDOW_SIZE );
windowedColumn = reshape( A(1:WINDOW_SIZE*windowCount,COLUMN_INDEX), WINDOW_SIZE, windowCount );
stdVals = std( windowedColumn );


问:
Git: Creating branch out another branch showing on main level
I have created a new branch out another branch:

master
   ---develpment
         ---------FeatureA

But if I check the branch structure it shows FeatureA branch at the same level as develpment:

```<code> git branch -a
  development
* FeatureA
  master
  remotes/origin/development
  remotes/origin/FeatureA
  remotes/origin/master
</code>```

My question to guys is guy FeatureA is not showing as sub-branch of development?

I'll really appreciate your help.

答:
In git, branches are just pointers to commits. After a branch is created, it does not remember from which branch it was created (in fact, a new branch is not necessarily created from any other branch, it can be created from any arbitrary commit) and has no relation to other branches.

See corresponding chapter in a git book.

There are various GUIs that can help you visualize the repository tree and relation between commits and branches.

Body:
I have created a new branch out another branch:

master
   ---develpment
         ---------FeatureA

But if I check the branch structure it shows FeatureA branch at the same level as develpment:

 git branch -a
  development
* FeatureA
  master
  remotes/origin/development
  remotes/origin/FeatureA
  remotes/origin/master

My question to guys is guy FeatureA is not showing as sub-branch of development?

I'll really appreciate your help.


问:
How to return multiple values within a group of rows.
I have tried to use Max(), subqueries, and joins, but my knowledge is limited enough that I am not sure how to organize them. I was willing to just use several nested select statements, knowing it could be resource intensive, but I can't get it to work.

I need to return any nulls, as well as the highest ConfigID for each Location.

```<code>TABLE
ID     Location     ConfigID
1      AA           NULL
2      AA           2
3      AA           1
4      BB           5
5      BB           4
6      BB           3
7      CC           NULL
8      CC           6
</code>```

I want to see the results:

```<code>ID     Location     ConfigID
1      AA           NULL
2      AA           2
4      BB           5
7      CC           NULL
8      CC           6
</code>```

I have tried:

```<code>select ID, Location, ConfigID
from Table
where ConfigID is null
      or configID = (select ConfigID
                     from table
                     where Location in (select distinct Location
                                        from Table
                                        order by ConfigID desc
                                        )
                     )
</code>```

SQL server didn't like that because I cannot have an order by in a subquery unless Top is used. Now that I am looking at it again, I don't think that the order by is even within the correct subquery. It was as close as I could get. I was hopeful when I saw Select Max from each subset, but that was a dead-end, I think. Also, I don't believe that a self-join will work because the data I would self-join on is all in one column.

答:
I would use one query to get the NULL entries and then a second query with PARTITION BY to get the top ConfigID row for each location. Finally do a UNION ALL to get the final result set and sort. Here's the fiddle: http://sqlfiddle.com/#!6/dab30/2/0. Query is below:

```<code>SELECT
    *
FROM
(
    -- This query gets the NULL ConfigID entries.
    SELECT
        TestTable.ID,
        TestTable.[Location],
        TestTable.ConfigID
    FROM
        TestTable
    WHERE
        TestTable.ConfigID IS NULL

    UNION ALL

    -- This query utilizes the PARTITION BY to get the max ConfigID for each group.
    SELECT
        TestTablePartitioned.ID,
        TestTablePartitioned.[Location],
        TestTablePartitioned.ConfigID
    FROM
    (
        SELECT
            ROW_NUMBER() OVER
            (
                PARTITION BY
                    [Location] -- The column to group the partition by.
                ORDER BY
                    ConfigID DESC -- The column used to determine partition order.
            ) AS PartitionIndex,
            TestTable.ID,
            TestTable.[Location],
            TestTable.ConfigID
        FROM
            TestTable
        WHERE
            TestTable.ConfigID IS NOT NULL
    ) AS TestTablePartitioned
    WHERE
        TestTablePartitioned.PartitionIndex = 1 -- Gets the top entry (max ConfigID) for each location.
) AS TestTableUnion
ORDER BY
    TestTableUnion.[Location],
    TestTableUnion.ConfigID
</code>```

Body:
I have tried to use Max(), subqueries, and joins, but my knowledge is limited enough that I am not sure how to organize them. I was willing to just use several nested select statements, knowing it could be resource intensive, but I can't get it to work.

I need to return any nulls, as well as the highest ConfigID for each Location.

TABLE
ID     Location     ConfigID
1      AA           NULL
2      AA           2
3      AA           1
4      BB           5
5      BB           4
6      BB           3
7      CC           NULL
8      CC           6

I want to see the results:

ID     Location     ConfigID
1      AA           NULL
2      AA           2
4      BB           5
7      CC           NULL
8      CC           6

I have tried:

select ID, Location, ConfigID
from Table
where ConfigID is null
      or configID = (select ConfigID
                     from table
                     where Location in (select distinct Location
                                        from Table
                                        order by ConfigID desc
                                        )
                     )

SQL server didn't like that because I cannot have an order by in a subquery unless Top is used. Now that I am looking at it again, I don't think that the order by is even within the correct subquery. It was as close as I could get. I was hopeful when I saw Select Max from each subset, but that was a dead-end, I think. Also, I don't believe that a self-join will work because the data I would self-join on is all in one column.

Body:
I would use one query to get the NULL entries and then a second query with PARTITION BY to get the top ConfigID row for each location. Finally do a UNION ALL to get the final result set and sort. Here's the fiddle: http://sqlfiddle.com/#!6/dab30/2/0. Query is below:

SELECT
    *
FROM
(
    -- This query gets the NULL ConfigID entries.
    SELECT
        TestTable.ID,
        TestTable.[Location],
        TestTable.ConfigID
    FROM
        TestTable
    WHERE
        TestTable.ConfigID IS NULL

    UNION ALL

    -- This query utilizes the PARTITION BY to get the max ConfigID for each group.
    SELECT
        TestTablePartitioned.ID,
        TestTablePartitioned.[Location],
        TestTablePartitioned.ConfigID
    FROM
    (
        SELECT
            ROW_NUMBER() OVER
            (
                PARTITION BY
                    [Location] -- The column to group the partition by.
                ORDER BY
                    ConfigID DESC -- The column used to determine partition order.
            ) AS PartitionIndex,
            TestTable.ID,
            TestTable.[Location],
            TestTable.ConfigID
        FROM
            TestTable
        WHERE
            TestTable.ConfigID IS NOT NULL
    ) AS TestTablePartitioned
    WHERE
        TestTablePartitioned.PartitionIndex = 1 -- Gets the top entry (max ConfigID) for each location.
) AS TestTableUnion
ORDER BY
    TestTableUnion.[Location],
    TestTableUnion.ConfigID


答:
There is no such thing as a "subbranch". All branches are equal. But you can use different tools to view relations between branches. Try</p>

```<code>git show-branch
git log --all --decorate --graph
gitk --all
</code>```

Title: Git: Creating branch out another branch showing on main level

Body:
There is no such thing as a "subbranch". All branches are equal. But you can use different tools to view relations between branches. Try

git show-branch
git log --all --decorate --graph
gitk --all


问:
how do i reference an id with concatenated variable in jquery appendTo()?
I am appending html code to a div using jquery. Part of that code references a div's id using a concatenated variable from a loop.

```<code>$(... +
    '<div class="recommendations filter" id="recCards-'+ i +'">' +
    '<div><h5>Recommended Cards</h5></div>' +
        '<ul></ul>' +
    '</div>' +
  ...
 ).appendTo('.someDiv');
</code>```

I'm then trying to append code from another loop into the ul by referencing the ".recommendations" div's ID like so...

```<code>var recCardsList = $(div).attr('id', '.recCards-'"+i+"' ul');

$('<div>'+recCardName+'</div>').appendTo(recCardsList);
</code>```

I've tried every combination of quotation marks that i can think of, but nothing grabs the div correctly to append the new content

答:
Actually your code doesn't append the new created content to the div, because it has some errors:

```<code>var recCardsList = $(div).attr('id', '.recCards-'"+i+"' ul');
$('<div>'+recCardName+'</div>').appendTo(recCardsList);
</code>```

By writing .attr('id', '.recCards-'"+i+"' ul') you are not getting the list from the div but, you are trying to update its id.

Actually if we pass two arguments to .attr(), the first will be the targeted attribute and the second one is its new value.

So to get the div you should just use $('#recCards-'+i+' ul') in your loop it will gets the respective lists, so your code would look like:

```<code>var recCardsList = $('#recCards-'+i+' ul');
$('<div>'+recCardName+'</div>').appendTo(recCardsList);
</code>```

Here using $("#someId") will get the element with the id="someId" from the page.

Body:
I am appending html code to a div using jquery. Part of that code references a div's id using a concatenated variable from a loop.

$(... +
    '
' +
    '

Recommended Cards

' +
        '

' +
    '
' +
  ...
 ).appendTo('.someDiv');

I'm then trying to append code from another loop into the ul by referencing the ".recommendations" div's ID like so...

var recCardsList = $(div).attr('id', '.recCards-'"+i+"' ul');

$('
'+recCardName+'
').appendTo(recCardsList);

I've tried every combination of quotation marks that i can think of, but nothing grabs the div correctly to append the new content

Body:
Actually your code doesn't append the new created content to the div, because it has some errors:

var recCardsList = $(div).attr('id', '.recCards-'"+i+"' ul');
$('<div>'+recCardName+'</div>').appendTo(recCardsList);

By writing .attr('id', '.recCards-'"+i+"' ul') you are not getting the list from the div but, you are trying to update its id.

Actually if we pass two arguments to .attr(), the first will be the targeted attribute and the second one is its new value.

So to get the div you should just use $('#recCards-'+i+' ul') in your loop it will gets the respective lists, so your code would look like:

var recCardsList = $('#recCards-'+i+' ul');
$('<div>'+recCardName+'</div>').appendTo(recCardsList);

Here using $("#someId") will get the element with the id="someId" from the page.


问:
Parse local datastore doesn't work - Swift 2
I am currently using the latest version of Parse 1.14.2 and Bolts 1.8.4.Parse is implemented correctly and I have been using it for a long time now. The problem I'm facing now is when I try to use Parse's local datastore. I have the following code in my AppDelegate.swift:

```<code>Parse.enableLocalDatastore()
                Parse.setApplicationId("ID",
                clientKey: "Client_Key")
</code>```

I have the following code to create and save a string named firstName in a class named contact:

```<code>let contact = PFObject(className: "contact")
                        contact["firstName"] = "Jack"
                        contact.pinInBackground()
</code>```

Here is the code to retrieve objects from the created class:

```<code>                            let query = PFQuery(className: "contact")
                        query.fromLocalDatastore()
                        query.getFirstObjectInBackgroundWithBlock({ (object, error) -> Void in
                            if error == nil {
                                if let contact = object {
                                    print(contact.objectForKey("firstName"))

                                }
                            }
                        })
</code>```

I have added libsqlite3.dylib to my project. My app doesn't crash when I run this code but it simply gives me the following message when I try to retrieve objects:

```<code>    2016-08-29 11:31:38.049 App_Demo[14436:3504319] [Bolts] Warning: `BFTask` caught an exception in the continuation block.
This behavior is discouraged and will be removed in a future release.
Caught Exception: Method requires Pinning enabled.
</code>```

Can anyone help me to work around this issue? I am guessing the issue is that this version of Bolts cannot pin Parse objects in the background and I need to work my way around this bug. Any help would be appreciated as I have been stuck at this for a while and can't find too much info online.

Edited: I have tried downgrading Bolts, but then Parse downgrades with it in Cocoapod and it causes errors in Xcode.

答:
it's not objectforkey.
You need to call object["UsedName"] "UsedName" being the key. Hope that helps. </p>

Body:
I am currently using the latest version of Parse 1.14.2 and Bolts 1.8.4.Parse is implemented correctly and I have been using it for a long time now. The problem I'm facing now is when I try to use Parse's local datastore. I have the following code in my AppDelegate.swift:

Parse.enableLocalDatastore()
                Parse.setApplicationId("ID",
                clientKey: "Client_Key")

I have the following code to create and save a string named firstName in a class named contact:

let contact = PFObject(className: "contact")
                        contact["firstName"] = "Jack"
                        contact.pinInBackground()

Here is the code to retrieve objects from the created class:

                            let query = PFQuery(className: "contact")
                        query.fromLocalDatastore()
                        query.getFirstObjectInBackgroundWithBlock({ (object, error) -> Void in
                            if error == nil {
                                if let contact = object {
                                    print(contact.objectForKey("firstName"))

                                }
                            }
                        })

I have added libsqlite3.dylib to my project. My app doesn't crash when I run this code but it simply gives me the following message when I try to retrieve objects:

    2016-08-29 11:31:38.049 App_Demo[14436:3504319] [Bolts] Warning: `BFTask` caught an exception in the continuation block.
This behavior is discouraged and will be removed in a future release.
Caught Exception: Method requires Pinning enabled.

Can anyone help me to work around this issue? I am guessing the issue is that this version of Bolts cannot pin Parse objects in the background and I need to work my way around this bug. Any help would be appreciated as I have been stuck at this for a while and can't find too much info online.

Edited: I have tried downgrading Bolts, but then Parse downgrades with it in Cocoapod and it causes errors in Xcode.


问:
Sending string as byte array from C# to Java via socket
I am trying the following:

C# Client:

```<code>    string stringToSend = "Hello man";
    BinaryWriter writer = new BinaryWriter(mClientSocket.GetStream(),Encoding.UTF8);

    //write number of bytes:
    byte[] headerBytes = BitConverter.GetBytes(stringToSend.Length);
    mClientSocket.GetStream().Write(headerBytes, 0, headerBytes.Length);
    //write text:
    byte[] textBytes = System.Text.Encoding.UTF8.GetBytes(stringToSend);
    writer.Write(textBytes, 0, textBytes.Length);
</code>```

Java Server:

```<code>   Charset utf8 = Charset.forName("UTF-8");
   BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream(), utf8));

   while (true) {
       //we read header first
      int headerSize = in.read();
      int bytesRead = 0;
      char[] input = new char[headerSize];

      while (bytesRead < headerSize)
      {
         bytesRead += in.read(input, bytesRead, headerSize - bytesRead);
      }
            String resString = new String(input);
            System.out.println(resString);

       if (resString.equals("!$$$")) {
                break;
       }
   }
</code>```

The string size equals 9.That's correct on both sides.But, when I am reading the string iteself on the Java side, the data looks wrong.The char buffer ('input' variable)content looks like this:

",",",'H','e','l','l','o',''

I tried to change endianness with reversing the byte array.Also tried changing string encoding format between ASCII and UTF-8.I still feel like it relates to the endianness problem,but can not figure out how to solve it.I know I can use other types of writers in order to write text data to the steam,but I am trying using raw byte arrays for the sake of learning.

答:
At first glance it appears you have a problem with your indexes.

You C# code is sending an integer converted to 4 bytes.

But you Java Code is only reading a single byte as the length of the string.

The next 3 bytes sent from C# are going to the three zero bytes from your string length.

You Java code is reading those 3 zero bytes and converting them to empty characters which represent the first 3 empty characters of your input[] array.

C# Client:

```<code>string stringToSend = "Hello man";
BinaryWriter writer = new BinaryWriter(mClientSocket.GetStream(),Encoding.UTF8);

//write number of bytes: Original line was sending the entire string here. Optionally if you string is longer than 255 characters, you'll need to send another data type, perhaps an integer converted to 4 bytes.
byte[] textBytes = System.Text.Encoding.UTF8.GetBytes(stringToSend);
mClientSocket.GetStream().Write((byte)textBytes.Length);
//write text the entire buffer

writer.Write(textBytes, 0, textBytes.Length);
</code>```

Java Server:

```<code>Charset utf8 = Charset.forName("UTF-8");
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream(), utf8));

while (true) {
    //we read header first
    // original code was sending an integer as 4 bytes but was only reading a single char here.
    int headerSize = in.read();// read a single byte from the input
    int bytesRead = 0;
    char[] input = new char[headerSize];

    // no need foe a while statement here:
    bytesRead = in.read(input, 0, headerSize);

    // if you are going to use a while statement, then in each loop
    // you should be processing the input but because it will get overwritten on the next read.
    String resString = new String(input, utf8);
    System.out.println(resString);

    if (resString.equals("!$$$")) {
        break;
    }
}
</code>```

Body:
I am trying the following:

C# Client:

    string stringToSend = "Hello man";
    BinaryWriter writer = new BinaryWriter(mClientSocket.GetStream(),Encoding.UTF8);

    //write number of bytes:
    byte[] headerBytes = BitConverter.GetBytes(stringToSend.Length);
    mClientSocket.GetStream().Write(headerBytes, 0, headerBytes.Length);
    //write text:
    byte[] textBytes = System.Text.Encoding.UTF8.GetBytes(stringToSend);
    writer.Write(textBytes, 0, textBytes.Length);

Java Server:

   Charset utf8 = Charset.forName("UTF-8");
   BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream(), utf8));

   while (true) {
       //we read header first
      int headerSize = in.read();
      int bytesRead = 0;
      char[] input = new char[headerSize];

      while (bytesRead < headerSize)
      {
         bytesRead += in.read(input, bytesRead, headerSize - bytesRead);
      }
            String resString = new String(input);
            System.out.println(resString);

       if (resString.equals("!$$$")) {
                break;
       }
   }

The string size equals 9.That's correct on both sides.But, when I am reading the string iteself on the Java side, the data looks wrong.The char buffer ('input' variable)content looks like this:

",",",'H','e','l','l','o',''

I tried to change endianness with reversing the byte array.Also tried changing string encoding format between ASCII and UTF-8.I still feel like it relates to the endianness problem,but can not figure out how to solve it.I know I can use other types of writers in order to write text data to the steam,but I am trying using raw byte arrays for the sake of learning.

Body:
At first glance it appears you have a problem with your indexes.

You C# code is sending an integer converted to 4 bytes.

But you Java Code is only reading a single byte as the length of the string.

The next 3 bytes sent from C# are going to the three zero bytes from your string length.

You Java code is reading those 3 zero bytes and converting them to empty characters which represent the first 3 empty characters of your input[] array.

C# Client:

string stringToSend = "Hello man";
BinaryWriter writer = new BinaryWriter(mClientSocket.GetStream(),Encoding.UTF8);

//write number of bytes: Original line was sending the entire string here. Optionally if you string is longer than 255 characters, you'll need to send another data type, perhaps an integer converted to 4 bytes.
byte[] textBytes = System.Text.Encoding.UTF8.GetBytes(stringToSend);
mClientSocket.GetStream().Write((byte)textBytes.Length);
//write text the entire buffer

writer.Write(textBytes, 0, textBytes.Length);

Java Server:

Charset utf8 = Charset.forName("UTF-8");
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream(), utf8));

while (true) {
    //we read header first
    // original code was sending an integer as 4 bytes but was only reading a single char here.
    int headerSize = in.read();// read a single byte from the input
    int bytesRead = 0;
    char[] input = new char[headerSize];

    // no need foe a while statement here:
    bytesRead = in.read(input, 0, headerSize);

    // if you are going to use a while statement, then in each loop
    // you should be processing the input but because it will get overwritten on the next read.
    String resString = new String(input, utf8);
    System.out.println(resString);

    if (resString.equals("!$$$")) {
        break;
    }
}


问:
PyQt Set column widths
I've got a simple QTableView and I essentially want to emulate this:

```<code>view.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)
</code>```

However, I cannot actually use this, since this calls sizeHint on every single row, which is unacceptable in my case, since the widget needs to be responsive on startup and the calculations take a long time for all the rows. Therefore this is not an option.

I know what the size of a single column, which is always the same, and is always the one with largest height. However, the width of this cell may not always be the widest of all the cells in a row. I've made those cells the correct size by doing this, but this obviously makes all the cells the same size, and many are now far too wide.

```<code>view.horizontalHeader().setDefaultSectionSize(200)
view.verticalHeader().setDefaultSectionSize(100)
</code>```

I've also tried to set individual column widths, but that seems to have no effect at all on the widths, like this:

```<code>view.setColumnWidth(0, 5)
</code>```

Also, setting individual column widths isn't that great, since I can't know in advance how wide they're going to be.

Is there any way to use (or emulate) the ResizeToContents approach (as shown above), but in a way that wouldn't require checking all the cell sizes?

答:
Have you tried to optimize the ResizeToContents mode with setResizeContentsPrecision ?

Sets how precise QHeaderView should calculate the size when ResizeToContents is used. A low value will provide a less accurate but fast auto resize while a higher value will provide a more accurate resize that however can be slow.

The number precision specifies how many sections that should be consider when calculating the preferred size.

The default value is 1000 meaning that a horizontal column with auto-resize will look at maximum 1000 rows on calculating when doing an auto resize.

Special value 0 means that it will look at only the visible area. Special value -1 will imply looking at all elements.

Title: PyQt Set column widths

Body:
I've got a simple QTableView and I essentially want to emulate this:

view.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)

However, I cannot actually use this, since this calls sizeHint on every single row, which is unacceptable in my case, since the widget needs to be responsive on startup and the calculations take a long time for all the rows. Therefore this is not an option.

I know what the size of a single column, which is always the same, and is always the one with largest height. However, the width of this cell may not always be the widest of all the cells in a row. I've made those cells the correct size by doing this, but this obviously makes all the cells the same size, and many are now far too wide.

view.horizontalHeader().setDefaultSectionSize(200)
view.verticalHeader().setDefaultSectionSize(100)

I've also tried to set individual column widths, but that seems to have no effect at all on the widths, like this:

view.setColumnWidth(0, 5)

Also, setting individual column widths isn't that great, since I can't know in advance how wide they're going to be.

Is there any way to use (or emulate) the ResizeToContents approach (as shown above), but in a way that wouldn't require checking all the cell sizes?


问:
Deploy docker on AWS beanstalk with docker composer
I'm trying to deploy multiple node.js micro services on AWS beanstalk, and I want them to be deployed on the same instance. It's my first time to deploy multiple services, so there're some failures I need someone to help me out. So, I tried to package them in a docker container first. Meanwhile I'm using docker composer to manage the structure. It's up and running locally in my virtual machine, but when I deployed it on to beanstalk, I met a few problems.

What I know:

I know I have to choose to deploy as multi-container docker.

The best practice to manage multiple node.js services is using docker composer.

I need a dockerrun.aws.json for node.js app.

I need to create task definition for that ecs instance.

Where I have problems:

I can only find dockerrun.aws.json and task_definition.json
template for php, so I can't verify if my configuration for node.js
in those two json files are in correct shape.

It seems like docker-compose.yml, dockerrun.aws.json and task_definition.json are doing similar jobs. I must keep
task_definition, but do I still need dockerrun.aws.json?

I tried to run the task in ecs, but it stopped right away. How can I check the log for the task?

I got:

No ecs task definition (or empty definition file) found in environment

because my task will always stop immediately. If I can check the log, it will be much easier for me to do trouble shooting.

Here is my task_definition.json:

```<code>{
  "requiresAttributes": [],
  "taskDefinitionArn": "arn:aws:ecs:us-east-1:231440562752:task-definition/ComposerExample:1",
  "status": "ACTIVE",
  "revision": 1,
  "containerDefinitions": [
    {
      "volumesFrom": [],
      "memory": 100,
      "extraHosts": null,
      "dnsServers": null,
      "disableNetworking": null,
      "dnsSearchDomains": null,
      "portMappings": [
        {
          "hostPort": 80,
          "containerPort": 80,
          "protocol": "tcp"
        }
      ],
      "hostname": null,
      "essential": true,
      "entryPoint": null,
      "mountPoints": [
        {
          "containerPath": "/usr/share/nginx/html",
          "sourceVolume": "webdata",
          "readOnly": true
        }
      ],
      "name": "nginxexpressredisnodemon_nginx_1",
      "ulimits": null,
      "dockerSecurityOptions": null,
      "environment": [],
      "links": null,
      "workingDirectory": null,
      "readonlyRootFilesystem": null,
      "image": "nginxexpressredisnodemon_nginx",
      "command": null,
      "user": null,
      "dockerLabels": null,
      "logConfiguration": null,
      "cpu": 99,
      "privileged": null
    }
  ],
  "volumes": [
    {
      "host": {
        "sourcePath": "/ecs/webdata"
      },
      "name": "webdata"
    }
  ],
  "family": "ComposerExample"
}
</code>```

答:
For me, it was simply a case of ensuring the name of the file matched the exact casing as described in the AWS documentation.

dockerfile.aws.json had to be exactly Dockerfile.aws.json

Body:
I'm trying to deploy multiple node.js micro services on AWS beanstalk, and I want them to be deployed on the same instance. It's my first time to deploy multiple services, so there're some failures I need someone to help me out. So, I tried to package them in a docker container first. Meanwhile I'm using docker composer to manage the structure. It's up and running locally in my virtual machine, but when I deployed it on to beanstalk, I met a few problems.

What I know:

I know I have to choose to deploy as multi-container docker.

The best practice to manage multiple node.js services is using docker composer.

I need a dockerrun.aws.json for node.js app.

I need to create task definition for that ecs instance.

Where I have problems:

I can only find dockerrun.aws.json and task_definition.json
template for php, so I can't verify if my configuration for node.js
in those two json files are in correct shape.

It seems like docker-compose.yml, dockerrun.aws.json and task_definition.json are doing similar jobs. I must keep
task_definition, but do I still need dockerrun.aws.json?

I tried to run the task in ecs, but it stopped right away. How can I check the log for the task?

I got:

No ecs task definition (or empty definition file) found in environment

because my task will always stop immediately. If I can check the log, it will be much easier for me to do trouble shooting.

Here is my task_definition.json:

{
  "requiresAttributes": [],
  "taskDefinitionArn": "arn:aws:ecs:us-east-1:231440562752:task-definition/ComposerExample:1",
  "status": "ACTIVE",
  "revision": 1,
  "containerDefinitions": [
    {
      "volumesFrom": [],
      "memory": 100,
      "extraHosts": null,
      "dnsServers": null,
      "disableNetworking": null,
      "dnsSearchDomains": null,
      "portMappings": [
        {
          "hostPort": 80,
          "containerPort": 80,
          "protocol": "tcp"
        }
      ],
      "hostname": null,
      "essential": true,
      "entryPoint": null,
      "mountPoints": [
        {
          "containerPath": "/usr/share/nginx/html",
          "sourceVolume": "webdata",
          "readOnly": true
        }
      ],
      "name": "nginxexpressredisnodemon_nginx_1",
      "ulimits": null,
      "dockerSecurityOptions": null,
      "environment": [],
      "links": null,
      "workingDirectory": null,
      "readonlyRootFilesystem": null,
      "image": "nginxexpressredisnodemon_nginx",
      "command": null,
      "user": null,
      "dockerLabels": null,
      "logConfiguration": null,
      "cpu": 99,
      "privileged": null
    }
  ],
  "volumes": [
    {
      "host": {
        "sourcePath": "/ecs/webdata"
      },
      "name": "webdata"
    }
  ],
  "family": "ComposerExample"
}


问:
How can I split a URL string up into separate parts in Python?
I decided that I'll learn Python tonight :)
I know C pretty well (wrote an OS in it), so I'm not a noob in programming, so everything in Python seems pretty easy, but I don't know how to solve this problem:
let's say I have this address:

http://example.com/random/folder/path.html

Now how can I create two strings from this, one containing the "base" name of the server, so in this example it would be

http://example.com/

and another containing the thing without the last filename, so in this example it would be

http://example.com/random/folder/

Also I of course know the possibility to just find the third and last slash respectively, but is there a better way?

Also it would be cool to have the trailing slash in both cases, but I don't care since it can be added easily.
So is there a good, fast, effective solution for this? Or is there only "my" solution, finding the slashes?

答:
The urlparse module in Python 2.x (or urllib.parse in Python 3.x) would be the way to do it.

```<code>>>> from urllib.parse import urlparse
>>> url = 'http://example.com/random/folder/path.html'
>>> parse_object = urlparse(url)
>>> parse_object.netloc
'example.com'
>>> parse_object.path
'/random/folder/path.html'
>>> parse_object.scheme
'http'
>>>
</code>```

If you wanted to do more work on the path of the file under the URL, you can use the posixpath module:

```<code>>>> from posixpath import basename, dirname
>>> basename(parse_object.path)
'path.html'
>>> dirname(parse_object.path)
'/random/folder'
</code>```

After that, you can use posixpath.join to glue the parts together.

Note: Windows users will choke on the path separator in os.path. The posixpath module documentation has a special reference to URL manipulation, so all's good.

OwnerDisplayName: Language

LastEditorDisplayName: Simucal

Body:
The urlparse module in Python 2.x (or urllib.parse in Python 3.x) would be the way to do it.

>>> from urllib.parse import urlparse
>>> url = 'http://example.com/random/folder/path.html'
>>> parse_object = urlparse(url)
>>> parse_object.netloc
'example.com'
>>> parse_object.path
'/random/folder/path.html'
>>> parse_object.scheme
'http'
>>>

If you wanted to do more work on the path of the file under the URL, you can use the posixpath module:

>>> from posixpath import basename, dirname
>>> basename(parse_object.path)
'path.html'
>>> dirname(parse_object.path)
'/random/folder'

After that, you can use posixpath.join to glue the parts together.

Note: Windows users will choke on the path separator in os.path. The posixpath module documentation has a special reference to URL manipulation, so all's good.

OwnerDisplayName: sykora

LastEditorDisplayName: sykora


答:
These

```<code>byte[] headerBytes = BitConverter.GetBytes(stringToSend.Length);
</code>```

are 4 bytes. And they aren't character data so it makes no sense to read them with a BufferedReader. Just read the bytes directly.

```<code>byte[] headerBytes = new byte[4];
// shortcut, make sure 4 bytes were actually read
in.read(headerBytes);
</code>```

Now extract your text's length and allocate enough space for it

```<code>int length = ByteBuffer.wrap(headerBytes).getInt();
byte[] textBytes = new byte[length];
</code>```

Then read the text

```<code>int remaining = length;
int offset = 0;
while (remaining > 0) {
    int count = in.read(textBytes, offset, remaining);
    if (-1 == count) {
        // deal with it
        break;
    }
    remaining -= count;
    offset += count;
}
</code>```

Now decode it as UTF-8

```<code>String text = new String(textBytes, StandardCharsets.UTF_8);
</code>```

and you are done.

Endianness will have to match for those first 4 bytes. One way of ensuring that is to use "network order" (big-endian). So:

C# Client

```<code>byte[] headerBytes = BitConverter.GetBytes(IPAddress.HostToNetworkOrder(stringToSend.Length));
</code>```

Java Server

```<code>int length = ByteBuffer.wrap(headerBytes).order(ByteOrder.BIG_ENDIAN).getInt();
</code>```

Title: Sending string as byte array from C# to Java via socket

Body:
These

byte[] headerBytes = BitConverter.GetBytes(stringToSend.Length);

are 4 bytes. And they aren't character data so it makes no sense to read them with a BufferedReader. Just read the bytes directly.

byte[] headerBytes = new byte[4];
// shortcut, make sure 4 bytes were actually read
in.read(headerBytes);

Now extract your text's length and allocate enough space for it

int length = ByteBuffer.wrap(headerBytes).getInt();
byte[] textBytes = new byte[length];

Then read the text

int remaining = length;
int offset = 0;
while (remaining > 0) {
    int count = in.read(textBytes, offset, remaining);
    if (-1 == count) {
        // deal with it
        break;
    }
    remaining -= count;
    offset += count;
}

Now decode it as UTF-8

String text = new String(textBytes, StandardCharsets.UTF_8);

and you are done.

Endianness will have to match for those first 4 bytes. One way of ensuring that is to use "network order" (big-endian). So:

C# Client

byte[] headerBytes = BitConverter.GetBytes(IPAddress.HostToNetworkOrder(stringToSend.Length));

Java Server

int length = ByteBuffer.wrap(headerBytes).order(ByteOrder.BIG_ENDIAN).getInt();


问:
Generate xml fragments from a static set of rows
I have a static list of values I want to create a list of XML elements from. The values are: one, two, and three. I'm trying to avoid creating a new table just for this one special use case. The goal is to get rows with the following output from this list:

```<code><option value="one"/>
<option value="two"/>
<option value="three"/>
</code>```

I've tried the following SQL query in PostgreSQL which gets close:

```<code>SELECT xmlelement(name option, xmlattributes(s as value))
FROM (values('one'), ('two')) AS s;
</code>```

However, I end up with the following output:

```<code><option value="(one)"/>
<option value="(two)"/>
<option value="(three)"/>
</code>```

I've also tried the following query with the same results:

```<code>SELECT xmlelement(name option, xmlattributes(s as value))
FROM (SELECT unnest('{one,two}'::varchar[])) AS s;
</code>```

I believe I just need to find a way to refer to that column. I tried using ?column? but it didn't work. I'm also not sure if there is a cleaner way to write what I'm attempting.

答:
May be it's me but there should be better ways of rendering HTML select options than database... like i.e. php, ruby, node.js etc.

In any case you can simply do

SELECT format('<option value="%s"/>', value) AS option
  FROM (VALUES ('one'), ('two'), ('three')) options(value);
```

<p>or</p>

<pre class="lang-sql prettyprint-override"><code>SELECT xmlelement(name "option", xmlattributes(value AS "value")) AS option
  FROM (VALUES ('one'), ('two'), ('three')) options(value);
</code>```

Output:

         option
-------------------------
 <option value="one"/>
 <option value="two"/>
 <option value="three"/>
```

Here is a dbfiddle demo

Body:
I have a static list of values I want to create a list of XML elements from. The values are: one, two, and three. I'm trying to avoid creating a new table just for this one special use case. The goal is to get rows with the following output from this list:

<option value="one"/>
<option value="two"/>
<option value="three"/>

I've tried the following SQL query in PostgreSQL which gets close:

SELECT xmlelement(name option, xmlattributes(s as value))
FROM (values('one'), ('two')) AS s;

However, I end up with the following output:

<option value="(one)"/>
<option value="(two)"/>
<option value="(three)"/>

I've also tried the following query with the same results:

SELECT xmlelement(name option, xmlattributes(s as value))
FROM (SELECT unnest('{one,two}'::varchar[])) AS s;

I believe I just need to find a way to refer to that column. I tried using ?column? but it didn't work. I'm also not sure if there is a cleaner way to write what I'm attempting.

Body:
May be it's me but there should be better ways of rendering HTML select options than database... like i.e. php, ruby, node.js etc.

In any case you can simply do

SELECT format('<option value="%s"/>', value) AS option
  FROM (VALUES ('one'), ('two'), ('three')) options(value);

or

SELECT xmlelement(name "option", xmlattributes(value AS "value")) AS option
  FROM (VALUES ('one'), ('two'), ('three')) options(value);

Output:

         option
-------------------------
 <option value="one"/>
 <option value="two"/>
 <option value="three"/>

Here is a dbfiddle demo


问:
await async code seems to still be running sync
I'm new to async / await, and have been trying to implement it in my 4.6 web api 2 project.

```<code>public class MyController : ApiController
{
     public async Task<Thing> Search(String searchTerms)
{
    myThing = new Thing();
    myThing.FirstProperty = await doFirstPropertyAsync(searchTerms);
    myThing.SecondProperty = await doSecondPropertyAsync(searchTerms);

 return myThing;

}
}
</code>```

Basically I'm returning a class (Thing) that has two properties that take a few seconds each to populate. I'm actually loading maybe ~10 properties, but it's the same logic for all of them.

```<code>    public async Task<MyCoolSubObject> doFirstPropertyAsync(string searchTerms)
    {
        SomeController sController = new SomeController();
        Debug.WriteLine("first - starting.");

        var x = await Task.Run(()=>sController.Lookup(searchTerms));

        Debug.WriteLine("first - finishing.");
        return x;
    }

    public async Task<MyCoolSubObject> doSecondPropertyAsync(string searchTerms)
    {
        SomeOtherController sController = new SomeOtherController();
        Debug.WriteLine("second - starting.");

        var x = await Task.Run(()=>sController.Lookup(searchTerms));

        Debug.WriteLine("second - finishing.");
        return x;
    }
</code>```

What's got my scratching my head:

When I look at the debug outputs, the first property assignment method call starts and finishes before the second completes. Again, I actually have like ten of these and no matter what order I put the property assignments in they complete in a serial fashion (ie: nothing starts until another one finishes).

These property assignments under the hood are basically doing database calls that take a while, hence I wanted them running in parallel if possible. The methods themselves ( SomeController.Lookup(string) ) contain no await/async/task stuff.

答:
Again, I actually have like ten of these and no matter what order I
  put the property assignments in they complete in a serial fashion (ie:
  nothing starts until another one finishes).

This happens because in your code you use the await keyword as soon as you kickoff the task, by doing that you prevent the method to continue to execute the next statement before the task will be done.

If you want to run your tasks in parallel you should kickoff all of them and only then await all of them using Task.WhenAll:

```<code>public async Task<Thing> Search(String searchTerms)
{
    myThing = new Thing();
    var firstTask = doFirstPropertyAsync(searchTerms);
    var secondTask = doSecondPropertyAsync(searchTerms);
    await Task.WhenAll(firstTask, secondTask);
    myThing.FirstProperty = await firstTask;
    myThing.SecondProperty = await secondTask;
    return myThing;
}
</code>```

Note that when we await every task separately after we await Task.WhenAll the tasks have already been done, we do that in order to get the result from the task, although we can use the Result property (it will not block since we know the task has already been done) I prefer to use await for consistency reasons.

Body:
I'm new to async / await, and have been trying to implement it in my 4.6 web api 2 project.

public class MyController : ApiController
{
     public async Task<Thing> Search(String searchTerms)
{
    myThing = new Thing();
    myThing.FirstProperty = await doFirstPropertyAsync(searchTerms);
    myThing.SecondProperty = await doSecondPropertyAsync(searchTerms);

 return myThing;

}
}

Basically I'm returning a class (Thing) that has two properties that take a few seconds each to populate. I'm actually loading maybe ~10 properties, but it's the same logic for all of them.

    public async Task<MyCoolSubObject> doFirstPropertyAsync(string searchTerms)
    {
        SomeController sController = new SomeController();
        Debug.WriteLine("first - starting.");

        var x = await Task.Run(()=>sController.Lookup(searchTerms));

        Debug.WriteLine("first - finishing.");
        return x;
    }

    public async Task<MyCoolSubObject> doSecondPropertyAsync(string searchTerms)
    {
        SomeOtherController sController = new SomeOtherController();
        Debug.WriteLine("second - starting.");

        var x = await Task.Run(()=>sController.Lookup(searchTerms));

        Debug.WriteLine("second - finishing.");
        return x;
    }

What's got my scratching my head:

When I look at the debug outputs, the first property assignment method call starts and finishes before the second completes. Again, I actually have like ten of these and no matter what order I put the property assignments in they complete in a serial fashion (ie: nothing starts until another one finishes).

These property assignments under the hood are basically doing database calls that take a while, hence I wanted them running in parallel if possible. The methods themselves ( SomeController.Lookup(string) ) contain no await/async/task stuff.

Body:
Again, I actually have like ten of these and no matter what order I
  put the property assignments in they complete in a serial fashion (ie:
  nothing starts until another one finishes).

This happens because in your code you use the await keyword as soon as you kickoff the task, by doing that you prevent the method to continue to execute the next statement before the task will be done.

If you want to run your tasks in parallel you should kickoff all of them and only then await all of them using Task.WhenAll:

public async Task<Thing> Search(String searchTerms)
{
    myThing = new Thing();
    var firstTask = doFirstPropertyAsync(searchTerms);
    var secondTask = doSecondPropertyAsync(searchTerms);
    await Task.WhenAll(firstTask, secondTask);
    myThing.FirstProperty = await firstTask;
    myThing.SecondProperty = await secondTask;
    return myThing;
}

Note that when we await every task separately after we await Task.WhenAll the tasks have already been done, we do that in order to get the result from the task, although we can use the Result property (it will not block since we know the task has already been done) I prefer to use await for consistency reasons.


问:
Approximate pi using finitie series
Given the equation to approximate pi

I need to the number of terms (n) that are needed to obtain an approximation that is within 10^(-12) of the actual value of pi. The code I have to find the n looks like this:

The while loop statement I have seems to never end, so I feel like my code must be wrong.

答:
Try something along these lines (transcribed from your image), incrementing the number of approximation terms n inside your infinite while loop:

```<code>s = 1
n = 1
while true
    s = abs(pi - approximate_pi(n))
    if s <= 0.001
        break
    end
    n = n + 1
end
</code>```

On a related note, this calculation is a little bit pointless if you know the value of pi beforehand. Termination condition should be on the absolute magnitude of the n-th term.

The way you're doing it makes sense only if you're trying to find out minimum n for which your approximation series produces the result within some margin of error.

Edit. So, normally you would do it like this:

```<code>n = 1;
sum_running = 0
sum_target = (pi^2 - 8) / 16;
while true
    sum_running += 1 / ((2*n-1)^2 * (2*n+1)^2);
    if abs(sum_target - sum_running) <= 10e-12
        break
    end
    n += 1;
end
pi_approx = sqrt(16*sum_running + 8)
</code>```

There's no need to keep recalculating pi approximation up to n terms, for each new n. This is has O(n) complexity, while your initial solution had O(n^2), so it's much faster for large n.

Title: Approximate pi using finitie series

Body:
Try something along these lines (transcribed from your image), incrementing the number of approximation terms n inside your infinite while loop:

s = 1
n = 1
while true
    s = abs(pi - approximate_pi(n))
    if s <= 0.001
        break
    end
    n = n + 1
end

On a related note, this calculation is a little bit pointless if you know the value of pi beforehand. Termination condition should be on the absolute magnitude of the n-th term.

The way you're doing it makes sense only if you're trying to find out minimum n for which your approximation series produces the result within some margin of error.

Edit. So, normally you would do it like this:

n = 1;
sum_running = 0
sum_target = (pi^2 - 8) / 16;
while true
    sum_running += 1 / ((2*n-1)^2 * (2*n+1)^2);
    if abs(sum_target - sum_running) <= 10e-12
        break
    end
    n += 1;
end
pi_approx = sqrt(16*sum_running + 8)

There's no need to keep recalculating pi approximation up to n terms, for each new n. This is has O(n) complexity, while your initial solution had O(n^2), so it's much faster for large n.


问:
How to create a custom middleware while using rails 5 in api-mode?
I'm trying to create a custom middleware in rails 5 in api-mode where for only routes that don't start with /api/... it will add back in

```<code>middleware.use ActionDispatch::Cookies
middleware.use ActionDispatch::Cookies::Session
</code>```

This post shows how to do it in rails 4:
OmniAuth::NoSessionError - You must provide a session to use OmniAuth. (configured in devise)

I'm trying to create a middleware like the accepted answer in the above post but when adding the

```<code>config.middleware.insert_before ActionDispatch::ParamsParser, "SelectiveStack"
</code>```

to application.rb it throws an error saying it can't find SelectiveStack.

It also won't let me add a require or includes in the application.rb to access it, so I was wondering if anyone come across this or had any ideas?

I may just have the format wrong or have it in the wrong path.

答:
It turns out that ActionDispatch::ParamsParser from the other stackoverflow post middleware doesn't actually exist and the wording of the error was a bit confusing.

So basically to get it working you can either put your middleware before an actual existing middleware or just use

```<code>config.middleware.use
</code>```

instead of

```<code>config.middleware.insert_before
</code>```

Body:
I'm trying to create a custom middleware in rails 5 in api-mode where for only routes that don't start with /api/... it will add back in

middleware.use ActionDispatch::Cookies
middleware.use ActionDispatch::Cookies::Session

This post shows how to do it in rails 4:
OmniAuth::NoSessionError - You must provide a session to use OmniAuth. (configured in devise)

I'm trying to create a middleware like the accepted answer in the above post but when adding the

config.middleware.insert_before ActionDispatch::ParamsParser, "SelectiveStack"

to application.rb it throws an error saying it can't find SelectiveStack.

It also won't let me add a require or includes in the application.rb to access it, so I was wondering if anyone come across this or had any ideas?

I may just have the format wrong or have it in the wrong path.

Body:
It turns out that ActionDispatch::ParamsParser from the other stackoverflow post middleware doesn't actually exist and the wording of the error was a bit confusing.

So basically to get it working you can either put your middleware before an actual existing middleware or just use

config.middleware.use

instead of

config.middleware.insert_before


问:
weather api, api for iphone, api for php
can any buddy have any code in which with the help of api I can see the weather updates for one week, if any buddy have any tutorial then plz given it to me..

either it is implemented for iphone or for php

thnks

答:
use google whether in php

see the link
http://komunitasweb.com/2009/09/showing-the-weather-with-php-and-google-weather-api/

to iphone see old question in so :

https://stackoverflow.com/questions/1305127/free-weather-api

ContentLicense: CC BY-SA 2.5