问:
How to unfreeze a user's memory limit?
For these two days, I have met a weird question.

STAR from https://github.com/alexdobin/STAR is a program used to build suffix array indexes. I have been used this program for years. It works OK until recently.

For these days, when I run STAR, it will always be killed.

```<code>root@localhost:STAR --runMode genomeGenerate --runThreadN 10  --limitGenomeGenerateRAM 31800833920 --genomeDir star_GRCh38 --genomeFastaFiles GRCh38.fa --sjdbGTFfile GRCh38.gtf --sjdbOverhang 100
.
.
.
Killed

root@localhost:STAR --runMode genomeGenerate --runThreadN 10 --genomeDir star_GRCh38 --genomeFastaFiles GRCh38.fa --sjdbGTFfile GRCh38.gtf --sjdbOverhang 100
Jun 03 10:15:08 ..... started STAR run
Jun 03 10:15:08 ... starting to generate Genome files
Jun 03 10:17:24 ... starting to sort Suffix Array. This may take a long time...
Jun 03 10:17:51 ... sorting Suffix Array chunks and saving them to disk...
Killed
</code>```

A month ago, the same command with same inputs and same parameters runs OK. It does cost some memory, but not a lot.

I have tried 3 recently released version of this program, all failed. So I do not think it is the question of STAR program but my sever configuration.

I also tried to run this program as both root and normal user, no lucky for each.

I suspect there is a limitation of memory usage in my server.

But I do not know how the memory is limited? I wonder if some one can give me some hints.

Thanks!

Tong

The following is my debug process and system info.

Command dmesg -T| grep -E -i -B5 'killed process' showing it is Out of memory problem.

But before the STAR program is killed, top command showing only 5% mem is occupied by this porgram.

```<code>[一 6  1 23:43:00 2020] [40479]  1002 40479   101523    18680     112      487             0 /anaconda2/bin/
[一 6  1 23:43:00 2020] [40480]  1002 40480   101526    18681     112      486             0 /anaconda2/bin/
[一 6  1 23:43:00 2020] [40481]  1002 40481   101529    18682     112      485             0 /anaconda2/bin/
[一 6  1 23:43:00 2020] [40482]  1002 40482   101531    18673     111      493             0 /anaconda2/bin/
[一 6  1 23:43:00 2020] Out of memory: Kill process 33822 (STAR) score 36 or sacrifice child
[一 6  1 23:43:00 2020] Killed process 33822 (STAR) total-vm:23885188kB, anon-rss:10895128kB, file-rss:4kB, shmem-rss:0kB

[三 6  3 10:02:13 2020] [12296]  1002 12296   101652    18681     113      486             0 /anaconda2/bin/
[三 6  3 10:02:13 2020] [12330]  1002 12330   101679    18855     112      486             0 /anaconda2/bin/
[三 6  3 10:02:13 2020] [12335]  1002 12335   101688    18682     112      486             0 /anaconda2/bin/
[三 6  3 10:02:13 2020] [12365]  1349 12365    30067     1262      11        0             0 bash
[三 6  3 10:02:13 2020] Out of memory: Kill process 7713 (STAR) score 40 or sacrifice child
[三 6  3 10:02:13 2020] Killed process 7713 (STAR) total-vm:19751792kB, anon-rss:12392428kB, file-rss:0kB, shmem-rss:0kB
--
[三 6月  3 10:42:17 2020] [ 4697]  1002  4697   101526    18681     112      486             0 /anaconda2/bin/
[三 6月  3 10:42:17 2020] [ 4698]  1002  4698   101529    18682     112      485             0 /anaconda2/bin/
[三 6月  3 10:42:17 2020] [ 4699]  1002  4699   101532    18680     112      487             0 /anaconda2/bin/
[三 6月  3 10:42:17 2020] [ 4701]  1002  4701   101534    18673     110      493             0 /anaconda2/bin/
[三 6月  3 10:42:17 2020] Out of memory: Kill process 21097 (STAR) score 38 or sacrifice child
[三 6月  3 10:42:17 2020] Killed process 21097 (STAR) total-vm:19769500kB, anon-rss:11622928kB, file-rss:884kB, shmem-rss:0kB
</code>```

Command free -hl showing I have enough memory.

```<code>              total        used        free      shared  buff/cache   available
Mem:           251G         10G         11G        227G        229G         12G
Low:           251G        240G         11G
High:            0B          0B          0B
Swap:           29G         29G          0B
</code>```

Also as showed by ulimit -a, no virtual memory limitation is set.

```<code>core file size          (blocks, -c) 0
data seg size           (kbytes, -d) unlimited
scheduling priority             (-e) 0
file size               (blocks, -f) unlimited
pending signals                 (-i) 1030545
max locked memory       (kbytes, -l) 64
max memory size         (kbytes, -m) unlimited
open files                      (-n) 65536
pipe size            (512 bytes, -p) 8
POSIX message queues     (bytes, -q) 819200
real-time priority              (-r) 0
stack size              (kbytes, -s) 8192
cpu time               (seconds, -t) unlimited
max user processes              (-u) 1030545
virtual memory          (kbytes, -v) unlimited
file locks                      (-x) unlimited
</code>```

Here is the version of my Centos and Kernel (output by hostnamectl):

```<code>hostnamectl
   Static hostname: localhost.localdomain
         Icon name: computer-server
           Chassis: server
  Operating System: CentOS Linux 7 (Core)
       CPE OS Name: cpe:/o:centos:centos:7
            Kernel: Linux 3.10.0-514.26.2.el7.x86_64
      Architecture: x86-64
</code>```

Here shows the content of cat /etc/security/limits.conf:

```<code>#*               soft    core            0
#*               hard    rss             10000
#@student        hard    nproc           20
#@faculty        soft    nproc           20
#@faculty        hard    nproc           50
#ftp             hard    nproc           0
#@student        -       maxlogins       4
* soft nofile 65536
* hard nofile 65536

#@intern    hard    as 162400000
#@intern    hard    nproc 150

# End of file
</code>```

As suggested, I have updated the output of df -h:

```<code>Filesystem            All  Used  Available (Used)% Mount
devtmpfs             126G     0  126G    0% /dev
tmpfs                126G  1.3M  126G    1% /dev/shm
tmpfs                126G  4.0G  122G    4% /run
tmpfs                126G     0  126G    0% /sys/fs/cgroup
/dev/mapper/cl-root  528G  271G  257G   52% /
/dev/sda1            492M  246M  246M   51% /boot
tmpfs                 26G     0   26G    0% /run/user/0
tmpfs                 26G     0   26G    0% /run/user/1002
tmpfs                 26G     0   26G    0% /run/user/1349
tmpfs                 26G     0   26G    0% /run/user/1855
</code>```

```<code>ls -a /dev/shm/
.  ..
</code>```

```<code>grep Shmem /proc/meminfo
Shmem:          238640272 kB
</code>```

Several tmpfs costs 126G memory. I am googleing this, but still not sure what should be done?

That is the problem of shared memory due to program terminated abnormally.

ipcrm is used to clear all shared memory and then STAR running is fine.

```<code>$ ipcrm
.....
$ free -h
              total        used        free      shared  buff/cache   available
Mem:           251G         11G        226G        3.9G         14G        235G
Swap:           29G        382M         29G
</code>```

答:
When I run a program called STAR, it will always be killed.

It probably has some memory leak. Even old programs may have residual bugs, and they could appear in some very particular cases.

Check with strace(1) or ltrace(1) and pmap(1). Learn also to query /proc/, see proc(5), top(1), htop(1). See LinuxAteMyRam and read about memory over-commitment and virtual address space and perhaps a textbook on operating systems.

If you have access to the source code of your STAR, consider recompiling it with all warnings and debug info (with GCC, you would pass -Wall -Wextra -g to gcc or g++) then use valgrind and/or some address sanitizer. If you don't have legal access to the source code of STAR, contact the entity (person or organization) which provided it to you.

You could be interested in that draft report and by the Clang static analyzer or Frama-C (or coding your own GCC plugin).

So I do not think it is the question of STAR program but my server configuration.

I recommend using valgrind or gdb and inspect your /proc/ to validate that optimistic hypothesis.

Title: How to unfreeze a user's memory limit?

Body:
For these two days, I have met a weird question.

STAR from https://github.com/alexdobin/STAR is a program used to build suffix array indexes. I have been used this program for years. It works OK until recently.

For these days, when I run STAR, it will always be killed.

root@localhost:STAR --runMode genomeGenerate --runThreadN 10  --limitGenomeGenerateRAM 31800833920 --genomeDir star_GRCh38 --genomeFastaFiles GRCh38.fa --sjdbGTFfile GRCh38.gtf --sjdbOverhang 100
.
.
.
Killed

root@localhost:STAR --runMode genomeGenerate --runThreadN 10 --genomeDir star_GRCh38 --genomeFastaFiles GRCh38.fa --sjdbGTFfile GRCh38.gtf --sjdbOverhang 100
Jun 03 10:15:08 ..... started STAR run
Jun 03 10:15:08 ... starting to generate Genome files
Jun 03 10:17:24 ... starting to sort Suffix Array. This may take a long time...
Jun 03 10:17:51 ... sorting Suffix Array chunks and saving them to disk...
Killed

A month ago, the same command with same inputs and same parameters runs OK. It does cost some memory, but not a lot.

I have tried 3 recently released version of this program, all failed. So I do not think it is the question of STAR program but my sever configuration.

I also tried to run this program as both root and normal user, no lucky for each.

I suspect there is a limitation of memory usage in my server.

But I do not know how the memory is limited? I wonder if some one can give me some hints.

Thanks!

Tong

The following is my debug process and system info.

Command dmesg -T| grep -E -i -B5 'killed process' showing it is Out of memory problem.

But before the STAR program is killed, top command showing only 5% mem is occupied by this porgram.

[一 6  1 23:43:00 2020] [40479]  1002 40479   101523    18680     112      487             0 /anaconda2/bin/
[一 6  1 23:43:00 2020] [40480]  1002 40480   101526    18681     112      486             0 /anaconda2/bin/
[一 6  1 23:43:00 2020] [40481]  1002 40481   101529    18682     112      485             0 /anaconda2/bin/
[一 6  1 23:43:00 2020] [40482]  1002 40482   101531    18673     111      493             0 /anaconda2/bin/
[一 6  1 23:43:00 2020] Out of memory: Kill process 33822 (STAR) score 36 or sacrifice child
[一 6  1 23:43:00 2020] Killed process 33822 (STAR) total-vm:23885188kB, anon-rss:10895128kB, file-rss:4kB, shmem-rss:0kB

[三 6  3 10:02:13 2020] [12296]  1002 12296   101652    18681     113      486             0 /anaconda2/bin/
[三 6  3 10:02:13 2020] [12330]  1002 12330   101679    18855     112      486             0 /anaconda2/bin/
[三 6  3 10:02:13 2020] [12335]  1002 12335   101688    18682     112      486             0 /anaconda2/bin/
[三 6  3 10:02:13 2020] [12365]  1349 12365    30067     1262      11        0             0 bash
[三 6  3 10:02:13 2020] Out of memory: Kill process 7713 (STAR) score 40 or sacrifice child
[三 6  3 10:02:13 2020] Killed process 7713 (STAR) total-vm:19751792kB, anon-rss:12392428kB, file-rss:0kB, shmem-rss:0kB
--
[三 6月  3 10:42:17 2020] [ 4697]  1002  4697   101526    18681     112      486             0 /anaconda2/bin/
[三 6月  3 10:42:17 2020] [ 4698]  1002  4698   101529    18682     112      485             0 /anaconda2/bin/
[三 6月  3 10:42:17 2020] [ 4699]  1002  4699   101532    18680     112      487             0 /anaconda2/bin/
[三 6月  3 10:42:17 2020] [ 4701]  1002  4701   101534    18673     110      493             0 /anaconda2/bin/
[三 6月  3 10:42:17 2020] Out of memory: Kill process 21097 (STAR) score 38 or sacrifice child
[三 6月  3 10:42:17 2020] Killed process 21097 (STAR) total-vm:19769500kB, anon-rss:11622928kB, file-rss:884kB, shmem-rss:0kB

Command free -hl showing I have enough memory.

              total        used        free      shared  buff/cache   available
Mem:           251G         10G         11G        227G        229G         12G
Low:           251G        240G         11G
High:            0B          0B          0B
Swap:           29G         29G          0B

Also as showed by ulimit -a, no virtual memory limitation is set.

core file size          (blocks, -c) 0
data seg size           (kbytes, -d) unlimited
scheduling priority             (-e) 0
file size               (blocks, -f) unlimited
pending signals                 (-i) 1030545
max locked memory       (kbytes, -l) 64
max memory size         (kbytes, -m) unlimited
open files                      (-n) 65536
pipe size            (512 bytes, -p) 8
POSIX message queues     (bytes, -q) 819200
real-time priority              (-r) 0
stack size              (kbytes, -s) 8192
cpu time               (seconds, -t) unlimited
max user processes              (-u) 1030545
virtual memory          (kbytes, -v) unlimited
file locks                      (-x) unlimited

Here is the version of my Centos and Kernel (output by hostnamectl):

hostnamectl
   Static hostname: localhost.localdomain
         Icon name: computer-server
           Chassis: server
  Operating System: CentOS Linux 7 (Core)
       CPE OS Name: cpe:/o:centos:centos:7
            Kernel: Linux 3.10.0-514.26.2.el7.x86_64
      Architecture: x86-64

Here shows the content of cat /etc/security/limits.conf:

#*               soft    core            0
#*               hard    rss             10000
#@student        hard    nproc           20
#@faculty        soft    nproc           20
#@faculty        hard    nproc           50
#ftp             hard    nproc           0
#@student        -       maxlogins       4
* soft nofile 65536
* hard nofile 65536

#@intern    hard    as 162400000
#@intern    hard    nproc 150

# End of file

As suggested, I have updated the output of df -h:

Filesystem            All  Used  Available (Used)% Mount
devtmpfs             126G     0  126G    0% /dev
tmpfs                126G  1.3M  126G    1% /dev/shm
tmpfs                126G  4.0G  122G    4% /run
tmpfs                126G     0  126G    0% /sys/fs/cgroup
/dev/mapper/cl-root  528G  271G  257G   52% /
/dev/sda1            492M  246M  246M   51% /boot
tmpfs                 26G     0   26G    0% /run/user/0
tmpfs                 26G     0   26G    0% /run/user/1002
tmpfs                 26G     0   26G    0% /run/user/1349
tmpfs                 26G     0   26G    0% /run/user/1855

ls -a /dev/shm/
.  ..

grep Shmem /proc/meminfo
Shmem:          238640272 kB

Several tmpfs costs 126G memory. I am googleing this, but still not sure what should be done?

That is the problem of shared memory due to program terminated abnormally.

ipcrm is used to clear all shared memory and then STAR running is fine.

$ ipcrm
.....
$ free -h
              total        used        free      shared  buff/cache   available
Mem:           251G         11G        226G        3.9G         14G        235G
Swap:           29G        382M         29G


来源: stackexchange

问:
How can I change Environments variables in Electron between production and stage
I want to change API URL depending on the environments.
for example

```<code>production: https://example.com
stage: https://stage.example.com
local: https://localhost:3001
</code>```

In Electron, How can I set Environment variables?

I tried to change production name when I build but it was useless

答:
With node you can use process.env.

In your code:

```<code>if(process.env.NODE_ENV === 'production') {
 // use production api
 const api = 'https://example.com';
}
</code>```

or use a switch case:

```<code>switch (process.env.NODE_ENV) {
 case 'production':
  // use production api
  const api = 'https://example.com';
  break;
 case 'stage':
  // use stage api
  const api = 'https://stage.example.com';
  break;
 case 'local':
  // use local api
  const api = 'https://localhost:3001';
  break;
 default:
  // use a default this api
}
</code>```

And in your terminal when using Electron:

```<code>$ NODE_ENV=production electron index.js
</code>```

Or add it as script in your Package.json

```<code>"production": "NODE_ENV=production electron index.js",
"stage": "NODE_ENV=stage electron index.js",
"local": "NODE_ENV=local electron index.js"
</code>```

Then you can use it:

```<code>$ npm run production
$ npm run stage
$ npm run local
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to change API URL depending on the environments.
for example

production: https://example.com
stage: https://stage.example.com
local: https://localhost:3001

In Electron, How can I set Environment variables?

I tried to change production name when I build but it was useless

Body:
With node you can use process.env.

In your code:

if(process.env.NODE_ENV === 'production') {
 // use production api
 const api = 'https://example.com';
}

or use a switch case:

switch (process.env.NODE_ENV) {
 case 'production':
  // use production api
  const api = 'https://example.com';
  break;
 case 'stage':
  // use stage api
  const api = 'https://stage.example.com';
  break;
 case 'local':
  // use local api
  const api = 'https://localhost:3001';
  break;
 default:
  // use a default this api
}

And in your terminal when using Electron:

$ NODE_ENV=production electron index.js

Or add it as script in your Package.json

"production": "NODE_ENV=production electron index.js",
"stage": "NODE_ENV=stage electron index.js",
"local": "NODE_ENV=local electron index.js"

Then you can use it:

$ npm run production
$ npm run stage
$ npm run local


问:
Apache camel not fwding all the message to AMQ, if using delay
I am trying to read message from activemq queue "AMQ:ORIGIN" using apache camel. After reading the message need to pass it to two different "AMQ queue's". But condition is following.

Message should pass to queue "AMQ:A" Immediately.

Message should pass to queue "AMQ:B" After one minute delay.

To Achieve above  i created two routes. In first route i am reading from AMQ queue, and doing multicast to "AMQ:A" and "seda:delay" queue. In second route, i am reading from "seda:delay" queue,  delaying for one minute and then passing to "AMQ:B" queue.

Work fine if pass with 1 or 10 messages to "AMQ:ORIGIN"

If i send 100 messages same time to "AMQ:ORIGIN" queue, then

All 100 messages are delivered to "AMQ:A" queue

Only 10 or 12 messages are delivered to "AMQ:B" queue. Rest is stuck in route only.

Following are my routes.

```<code>        <route id="read-origin">
            <from uri="activemq:ORIGIN"/>
            <multicast stopOnException="true">
                <to uri="activemq:A"/>
                <to uri="seda:delay-route"/>
            </multicast>
        </route>

        <route id="delay-route">
            <from uri="seda:delay-route"/>
            <delay asyncDelayed="true">
                <constant>60000</constant>
            </delay>
            <to uri="activemq:B"/>
        </route>
</code>```

Please suggest the changes to achieve above.

Thanks,

答:
That seems to be obvious since you delay every message for 1 minute.

If you send 100 messages to the ORIGIN queue, it takes 100 minutes until all these messages arrive at queue B.

The first message is consumed immediately, and delayed for 1 minute. The second is taken when the first is delivered (assuming 1 consumer on seda queue) and also delayed for one minute and so on...

I assume you want that a message that already waited for 1 minute in the queue, can be delivered immediately when consumed.

You can easily reach this making the delay dynamic.

Implement a bean that calculates the difference between the JMSTimestamp header (enqueue time) of a message and the current time.

currentTime - JMSTimestamp = alreadyWaited

Your minimal delay - alreadyWaited = time to wait before delivery (take 0 for negative values of messages that where queued for more than the delay)

Use this difference as value for the delay (I use Java DSL because I know it better).

```<code>from("seda:delay-route").routeId("delay-route")
    .delay().expression(method(YourDelayCalculationBean.class))
    .to("activemq:B");
</code>```

Like this, if your messages pile up in the queue, they are probably all delivered immediately on consumption because they already waited in the queue for more than 1 minute.

Addition due to comment

OK, sorry, I did not spot the asyncDelayed.

What the docs say about asyncDelayed sounds like what you expect. But according to your comment it sounds like the Delay EIP is no more blocking the consumer, but blocks itself.

So the seda consumer takes a message, hands it over to the Delay and continues to the next message. After 10 messages (10 threads is the default thread pool size of Camel), the Delay is "full" (all threads are blocked in a fixed 1 minute delay).

Therefore the consumer becomes blocked because the Delay can take no more messages. After a minute, the Delay can deliver the first messages and it continues.

That is just wild guessing based on what you write how your route behaves.

Body:
I am trying to read message from activemq queue "AMQ:ORIGIN" using apache camel. After reading the message need to pass it to two different "AMQ queue's". But condition is following.

Message should pass to queue "AMQ:A" Immediately.

Message should pass to queue "AMQ:B" After one minute delay.

To Achieve above  i created two routes. In first route i am reading from AMQ queue, and doing multicast to "AMQ:A" and "seda:delay" queue. In second route, i am reading from "seda:delay" queue,  delaying for one minute and then passing to "AMQ:B" queue.

Work fine if pass with 1 or 10 messages to "AMQ:ORIGIN"

If i send 100 messages same time to "AMQ:ORIGIN" queue, then

All 100 messages are delivered to "AMQ:A" queue

Only 10 or 12 messages are delivered to "AMQ:B" queue. Rest is stuck in route only.

Following are my routes.

        <route id="read-origin">
            <from uri="activemq:ORIGIN"/>
            <multicast stopOnException="true">
                <to uri="activemq:A"/>
                <to uri="seda:delay-route"/>
            </multicast>
        </route>

        <route id="delay-route">
            <from uri="seda:delay-route"/>
            <delay asyncDelayed="true">
                <constant>60000</constant>
            </delay>
            <to uri="activemq:B"/>
        </route>

Please suggest the changes to achieve above.

Thanks,

Body:
That seems to be obvious since you delay every message for 1 minute.

If you send 100 messages to the ORIGIN queue, it takes 100 minutes until all these messages arrive at queue B.

The first message is consumed immediately, and delayed for 1 minute. The second is taken when the first is delivered (assuming 1 consumer on seda queue) and also delayed for one minute and so on...

I assume you want that a message that already waited for 1 minute in the queue, can be delivered immediately when consumed.

You can easily reach this making the delay dynamic.

Implement a bean that calculates the difference between the JMSTimestamp header (enqueue time) of a message and the current time.

currentTime - JMSTimestamp = alreadyWaited

Your minimal delay - alreadyWaited = time to wait before delivery (take 0 for negative values of messages that where queued for more than the delay)

Use this difference as value for the delay (I use Java DSL because I know it better).

from("seda:delay-route").routeId("delay-route")
    .delay().expression(method(YourDelayCalculationBean.class))
    .to("activemq:B");

Like this, if your messages pile up in the queue, they are probably all delivered immediately on consumption because they already waited in the queue for more than 1 minute.

Addition due to comment

OK, sorry, I did not spot the asyncDelayed.

What the docs say about asyncDelayed sounds like what you expect. But according to your comment it sounds like the Delay EIP is no more blocking the consumer, but blocks itself.

So the seda consumer takes a message, hands it over to the Delay and continues to the next message. After 10 messages (10 threads is the default thread pool size of Camel), the Delay is "full" (all threads are blocked in a fixed 1 minute delay).

Therefore the consumer becomes blocked because the Delay can take no more messages. After a minute, the Delay can deliver the first messages and it continues.

That is just wild guessing based on what you write how your route behaves.


问:
Is there a maximum limit for the value max_allowed_packet?
I am running a drupal site. I got an error in my site user warning: Got a packet bigger than 'max_allowed_packet' bytes query. I have set the value as high as 128M . Even after that same error is reported.

What is the issue here?? Why is it not working ??

Is there a maximum limit for the value max_allowed_packet ?

答:
Often this can be caused by the variables not actually taking effect- you make the configuration change, but in the wrong my.cnf, or you forget to bounce the app, etc.

An easy way to check a running mysql instance is to do something like this in a shell:

mysqladmin variables -u root -p

and enter in your root password. This will dump all of the current variables (including max_allowed_packet), and will let you verify what it's set to. If it's set to 128M and you're still choking on it, then you'll need to increase it- but it's pretty unlikely.

ContentLicense: CC BY-SA 3.0


问:
Why my recursive code is giving sigsegv error?

Given an array of non-negative integers arr, you are initially positioned at start index of the array. When you are at index i, you can jump to i + arr[i] or i - arr[i], check if you can reach to any index with value 0. (Return true or false).

```<code>Input: arr = [4,2,3,0,3,1,2], start = 5
Output: true
</code>```

Explanation: index 5 -> index 4 -> index 1 -> index 3

index 5 -> index 6 -> index 4 -> index 1 -> index 3

Notice that you can not jump outside of the array at any time.

```<code>class Solution
{
  public:
    bool canReach(vector<int>& arr, int start)
    {
        if(start<0 || start>=arr.size())
        {
            return false;
        }
        if(arr[start]==0)
        {
            return true;
        }
        bool x = canReach( arr,  start+arr[start]);
        bool y = canReach( arr,  start-arr[start]);
        return (x||y);
    }
};
</code>```

答:
Consider a case where the input vector is arr = {1, 1, 1, 1, 1} and start = 1.According to you code, in this case, there will be an infinite number of recursive calls to the function.
This can be understood as:
if we are at index 1 and do start - arr[i] we reach index 0. Then if we do start + arr[i] we again reach index 1. This leads to an infinite number of calls to the function.

index 1 -> index 0 -> index 1 -> index 0 -> index 1-> so on.

Since recursion uses stack, this may lead to stack-overflow, thus aborting the function execution.

One way to handle this case is to use an unordered_set to store the indecies which have been visited earlier. If we have visited an index earlier than we should simply return false because there is no way that it can return true now.
Here is the implementation you can try:

```<code>unordered_set<int> s;
bool canReach(vector<int>& arr, int start) {

    if(start<0 || start>=arr.size() || (s.find(start) != s.end()))
        return false;
    if(arr[start]==0)
        return true;
    s.insert(start);
    bool x = canReach( arr,  start+arr[start]);
    bool y = canReach( arr,  start-arr[start]);
    return (x||y);
}
</code>```

It should work.

Body:
Given an array of non-negative integers arr, you are initially positioned at start index of the array. When you are at index i, you can jump to i + arr[i] or i - arr[i], check if you can reach to any index with value 0. (Return true or false).

Input: arr = [4,2,3,0,3,1,2], start = 5
Output: true

Explanation: index 5 -> index 4 -> index 1 -> index 3

index 5 -> index 6 -> index 4 -> index 1 -> index 3

Notice that you can not jump outside of the array at any time.

class Solution
{
  public:
    bool canReach(vector<int>& arr, int start)
    {
        if(start<0 || start>=arr.size())
        {
            return false;
        }
        if(arr[start]==0)
        {
            return true;
        }
        bool x = canReach( arr,  start+arr[start]);
        bool y = canReach( arr,  start-arr[start]);
        return (x||y);
    }
};

Body:
Consider a case where the input vector is arr = {1, 1, 1, 1, 1} and start = 1.According to you code, in this case, there will be an infinite number of recursive calls to the function.
This can be understood as:
if we are at index 1 and do start - arr[i] we reach index 0. Then if we do start + arr[i] we again reach index 1. This leads to an infinite number of calls to the function.

index 1 -> index 0 -> index 1 -> index 0 -> index 1-> so on.

Since recursion uses stack, this may lead to stack-overflow, thus aborting the function execution.

One way to handle this case is to use an unordered_set to store the indecies which have been visited earlier. If we have visited an index earlier than we should simply return false because there is no way that it can return true now.
Here is the implementation you can try:

unordered_set<int> s;
bool canReach(vector<int>& arr, int start) {

    if(start<0 || start>=arr.size() || (s.find(start) != s.end()))
        return false;
    if(arr[start]==0)
        return true;
    s.insert(start);
    bool x = canReach( arr,  start+arr[start]);
    bool y = canReach( arr,  start-arr[start]);
    return (x||y);
}

It should work.


问:
Remove optional characters from a column in pandas
I have a column which may contain values like abc,def or abc,def,efg, or ab,12,34, etc. As you can see, some values end with a , and some don't. What I want to do is remove all such values that end with a  comma ,.

Assuming the data is loaded and a data frame is created. So this is what I do

```<code>df[c] = df[c].astype('unicode').str.replace("/,*$/", '').str.strip()
</code>```

But it doesn't do anything.

What am I doing wrong?

答:
The way you were trying to do it, would be something like this:

```<code>df[c] = df[c].str.rstrip(',')
</code>```

rstrip(',') will remove comma just from the end of the string.

strip(',') will remove it from start and end positions both.

The above will replace the text. It will not let you drop the rows from the dataframe. So you should do below:

Use str.endswith:

```<code>df[~df['col'].str.endswith(',')]
</code>```

Consider below df:

```<code>In [1547]: df
Out[1547]:
         date id  value  rolling_mean   col
0  2016-08-28  A      1           nan    a,
1  2016-08-28  B      1           nan    b
2  2016-08-29  C      2           nan    c,
3  2016-09-02  B      0          0.50    d
4  2016-09-03  A      3          2.00    ee,ff
5  2016-09-06  C      1          1.50    gg,
6  2017-01-15  B      2          1.00    i,
7  2017-01-18  C      3          2.00    j
8  2017-01-18  A      2          2.50    k,

In [1548]: df = df[~df['col'].str.endswith(',')]
In [1549]: df
Out[1549]:
         date id  value  rolling_mean    col
1  2016-08-28  B      1           nan      b
3  2016-09-02  B      0          0.50      d
4  2016-09-03  A      3          2.00  ee,ff
7  2017-01-18  C      3          2.00      j
</code>```

Body:
I have a column which may contain values like abc,def or abc,def,efg, or ab,12,34, etc. As you can see, some values end with a , and some don't. What I want to do is remove all such values that end with a  comma ,.

Assuming the data is loaded and a data frame is created. So this is what I do

df[c] = df[c].astype('unicode').str.replace("/,*$/", '').str.strip()

But it doesn't do anything.

What am I doing wrong?

Body:
The way you were trying to do it, would be something like this:

df[c] = df[c].str.rstrip(',')

rstrip(',') will remove comma just from the end of the string.

strip(',') will remove it from start and end positions both.

The above will replace the text. It will not let you drop the rows from the dataframe. So you should do below:

Use str.endswith:

df[~df['col'].str.endswith(',')]

Consider below df:

In [1547]: df
Out[1547]:
         date id  value  rolling_mean   col
0  2016-08-28  A      1           nan    a,
1  2016-08-28  B      1           nan    b
2  2016-08-29  C      2           nan    c,
3  2016-09-02  B      0          0.50    d
4  2016-09-03  A      3          2.00    ee,ff
5  2016-09-06  C      1          1.50    gg,
6  2017-01-15  B      2          1.00    i,
7  2017-01-18  C      3          2.00    j
8  2017-01-18  A      2          2.50    k,

In [1548]: df = df[~df['col'].str.endswith(',')]
In [1549]: df
Out[1549]:
         date id  value  rolling_mean    col
1  2016-08-28  B      1           nan      b
3  2016-09-02  B      0          0.50      d
4  2016-09-03  A      3          2.00  ee,ff
7  2017-01-18  C      3          2.00      j


问:
C# Console app : Read a file from disk both when ran as standalone and when ran from ASP.NET app
I want to know how to be able to read a text file from both :

when running as a standalone

and

when running from a host ASP.NET app.

I am aware of the Server.MapPath command but it only works on the ASP.NET app and I want the file loading to be done from the console application.

Let's begin with an empty project and create two projects :

First, a Console application :

Then, a ASP.NET MVC application :

Once we have our two projects, let's create a text file :

And put something in there :

Make sure it is included in the bin folder :

Now, we can finally read the file content like this :

Using the following code :

We get the desired output.

Now, as stated in the beginning of this post, I want to be able to access the file from the same project, but called from the ASP.NET app.

Let's add the console app as a project dependency of TestWebApp :

And call it's method like so :

Now I get this error :

I want to know how I would go on and be able to load the file both when running the app by itself (console app) or when running from a host web service (asp.net web server).

答:
Use AppContext.BaseDirectory. This is the directory for which the runtime checks to resolve assemblies. In your context, this is the closest to the output directory.

Now there is a difference between what it returns for the Console App vs Web App. The below common code would address both.

```<code>var appContextBase = AppContext.BaseDirectory;
var filePath = appContextBase.IndexOf("bin", StringComparison.OrdinalIgnoreCase) == -1 ? "bin/Files/File.txt" : "Files/File.txt";
var fileContent = File.ReadAllText(appContextBase + filePath);
Console.WriteLine(fileContent);
</code>```

For Console App, AppContext.BaseDirectory returns something like this - "C:\\Users\\user123\\Documents\\Visual Studio 2017\\Projects\\MySamples\\MySamples\\bin\\Debug\\"

For Web App, it returns something like this - "C:\\Users\\user123\\Documents\\Visual Studio 2017\\Projects\\MySamples\\MyWebApp\\"

That is the reason I have added the ternary operator check on the filePath.

Body:
Use AppContext.BaseDirectory. This is the directory for which the runtime checks to resolve assemblies. In your context, this is the closest to the output directory.

Now there is a difference between what it returns for the Console App vs Web App. The below common code would address both.

var appContextBase = AppContext.BaseDirectory;
var filePath = appContextBase.IndexOf("bin", StringComparison.OrdinalIgnoreCase) == -1 ? "bin/Files/File.txt" : "Files/File.txt";
var fileContent = File.ReadAllText(appContextBase + filePath);
Console.WriteLine(fileContent);

For Console App, AppContext.BaseDirectory returns something like this - "C:\\Users\\user123\\Documents\\Visual Studio 2017\\Projects\\MySamples\\MySamples\\bin\\Debug\\"

For Web App, it returns something like this - "C:\\Users\\user123\\Documents\\Visual Studio 2017\\Projects\\MySamples\\MyWebApp\\"

That is the reason I have added the ternary operator check on the filePath.


问:
Is there a way to control the order of child entity, when using one-to-many relationhips?
According to https://developer.android.com/training/data-storage/room/relationships

We can have one-to-many relationships

```<code>public class UserWithPlaylists {
    @Embedded public User user;
    @Relation(
         parentColumn = "userId",
         entityColumn = "userCreatorId"
    )
    public List<Playlist> playlists;
}

@Transaction
@Query("SELECT * FROM User")
public List<UserWithPlaylists> getUsersWithPlaylists();
</code>```

In both entity User and Playlist, we have added a column named sort_key

The purpose is, when we perform query, we can do the following

```<code>@Transaction
@Query("SELECT * FROM User order by sort_key")
public List<UserWithPlaylists> getUsersWithPlaylists();
</code>```

We can control the order of List<UserWithPlaylists>.

But, how about List<Playlist> playlists child entity?

How can we define a custom query for child entity Playlist, so that we can have control over List<Playlist> playlists ordering?

答:
You can implement this functionality in two ways :

1) You could use the Hibernate-specific @Sort annotation to perform in-memory (i.e. not in the database) sorting, using natural sorting or sorting using a Comparator you supply.
For example, assume I have an MyComparator helper class that implements Comparator. Helper class can help you sort by sort_key.
You could change Playlist collection like this:

```<code>@org.hibernate.annotations.Sort(type = SortType.COMPARATOR, comparator = MyComparator)
public Set<Playlist> playlists;
</code>```

@Sort will perform sorting in-memory once the collection has been retrieved from the database.

2) You can use hibernate's @OrderBy annotation, which lets you specify a SQL fragment describing how to perform the sort.

```<code>@org.hibernate.annotations.OrderBy("sort_key")
 public Set<Playlist> playlists;
</code>```

Hope that helps..!!

Body:
According to https://developer.android.com/training/data-storage/room/relationships

We can have one-to-many relationships

public class UserWithPlaylists {
    @Embedded public User user;
    @Relation(
         parentColumn = "userId",
         entityColumn = "userCreatorId"
    )
    public List<Playlist> playlists;
}

@Transaction
@Query("SELECT * FROM User")
public List<UserWithPlaylists> getUsersWithPlaylists();

In both entity User and Playlist, we have added a column named sort_key

The purpose is, when we perform query, we can do the following

@Transaction
@Query("SELECT * FROM User order by sort_key")
public List<UserWithPlaylists> getUsersWithPlaylists();

We can control the order of List<UserWithPlaylists>.

But, how about List<Playlist> playlists child entity?

How can we define a custom query for child entity Playlist, so that we can have control over List<Playlist> playlists ordering?

Body:
You can implement this functionality in two ways :

1) You could use the Hibernate-specific @Sort annotation to perform in-memory (i.e. not in the database) sorting, using natural sorting or sorting using a Comparator you supply.
For example, assume I have an MyComparator helper class that implements Comparator. Helper class can help you sort by sort_key.
You could change Playlist collection like this:

@org.hibernate.annotations.Sort(type = SortType.COMPARATOR, comparator = MyComparator)
public Set<Playlist> playlists;

@Sort will perform sorting in-memory once the collection has been retrieved from the database.

2) You can use hibernate's @OrderBy annotation, which lets you specify a SQL fragment describing how to perform the sort.

@org.hibernate.annotations.OrderBy("sort_key")
 public Set<Playlist> playlists;

Hope that helps..!!


问:
Is there a way to monitor changes to an object?
Instead triggering an event based on user action can you just listen for changes to an object and react then?</p>

答:
Well, depending on the domain you're working with, you can use backbone.js - it has a "model" object that you can extend and connect up to callbacks that get triggered by events automatically when the model is changed - that is, you set a field on the model, and it will automatically fire an event that you can listen to. You have to define your models to extend its Model, and call a setter function instead of setting properties directly, but it's very useful, I recommend it.

Just for clarity's sake, the event is fired from the model on change, so it's fired even if you set the value of the attribute programmatically or in the console.


问:
How to wait for the end of a long process (on another thread)?
I'm writing an application (for personal use) that allows me to send a string over usb to an Arduino.

I wrote this method for sending the data:

```<code>    /**
     * Sends the data to the Arduino.
     * A new Thread is created for sending the data.
     * A transmission cool-down is started before send() method can be used again.
     * @param data the data to send to the Arduino
     */
    public void send(String data) {
        if (connected && !sending) {
            // Set 'sending' to true so only 1 Thread can be active at a time
            sending = true;
            // Create a new thread for sending the data
            Thread thread = new Thread(() -> {
                // Send the data
                PrintWriter output = new PrintWriter(chosenPort.getOutputStream());
                output.print(data);
                System.out.println("Data sended");
                output.flush();
                // Wait for the transmission cool-down and set 'sending' to false to allow for another Thread to send data
                try { Thread.sleep(transmissionCoolDown); } catch (InterruptedException interruptedException) { interruptedException.printStackTrace(); }
                sending = false;
                System.out.println("cooldown is over");
            });
            thread.start();
        }
    }
</code>```

sending is a boolean value that I use to indicate whether a Thread is sending data. The transmissionCooldown is simply to enforce a certain waiting period before data can be sent again.

And this is where the method is being used:

```<code>    @FXML
    private void sendClicked() {
        // Only do something if a connection is active and an image is selected.
        // Should be unnecessary since the send button is only enables when both are true.
        if (connected && selectedIV.getImage() != null) {
            if (!sending) {
                // Save the original text of the send button and disable the disconnect button
                String ogText = sendButton.getText();
                System.out.println(ogText);
                connectButton.setDisable(true);
                // If the data has not been saved before, get the data by formatting the image
                if (data == null) {
                    data = imgCon.toStringFormat(true);
                }
                ardComm.send(data);
                // While the ArduinoCommunicator is busy sending, change the text on the send button to indicate the data is being transmitted
                sendButton.setText("busy");
                while (ardComm.isSending()) {

                }
                // Restore the text on the send button
                sendButton.setText(ogText);
                connectButton.setDisable(false);
            }
        }
    }
</code>```

sendButton is the JavaFX Button that calls the sendClicked() method and ardCom is and instance of the class that contains the send() method. isSending() simply returns the sending attribute of the ardCom, which is set to true at the start of the send() method and set to false when the Thread is done sending.

The problem is with this piece of code:

```<code>    sendButton.setText("busy");
                while (ardComm.isSending()) {

                }
                // Restore the text on the send button
                sendButton.setText(ogText);
</code>```

I'm trying to set the sendButton's text to busy to indicate that the data is being sent, then loop until the data transmission is finished (sending is set to false) and end it with changing the text on the sendButton back to the original text. I know this is probably not the best way to achieve this, but I was playing around and could not figure out why this is not working as expected.

The problem is that for some reason, the while loop never ends.

答:
Thanks to @NomadMaker I found that making the sending variable volatile explains the problem. As far as I understand it, it seems to me that the JavaFX Thread is too busy to update the value of sending causing it to loop infinitely. Making it volatile makes sending stored in main memory instead of being cached thread-locally.

The weird thing is that when I change the loop to actually do something every iteration, like this:

```<code>    int n = 0;
    while (ardComm.isSending()) {
        System.out.println(n);
        n++;
    }
</code>```

it does not loop infinitely. (Maybe it's because println() and n++ are less memory heavy, leaving enough time or something for the sending variable to update. But don't quote me on that)

Body:
I'm writing an application (for personal use) that allows me to send a string over usb to an Arduino.

I wrote this method for sending the data:

    /**
     * Sends the data to the Arduino.
     * A new Thread is created for sending the data.
     * A transmission cool-down is started before send() method can be used again.
     * @param data the data to send to the Arduino
     */
    public void send(String data) {
        if (connected && !sending) {
            // Set 'sending' to true so only 1 Thread can be active at a time
            sending = true;
            // Create a new thread for sending the data
            Thread thread = new Thread(() -> {
                // Send the data
                PrintWriter output = new PrintWriter(chosenPort.getOutputStream());
                output.print(data);
                System.out.println("Data sended");
                output.flush();
                // Wait for the transmission cool-down and set 'sending' to false to allow for another Thread to send data
                try { Thread.sleep(transmissionCoolDown); } catch (InterruptedException interruptedException) { interruptedException.printStackTrace(); }
                sending = false;
                System.out.println("cooldown is over");
            });
            thread.start();
        }
    }

sending is a boolean value that I use to indicate whether a Thread is sending data. The transmissionCooldown is simply to enforce a certain waiting period before data can be sent again.

And this is where the method is being used:

    @FXML
    private void sendClicked() {
        // Only do something if a connection is active and an image is selected.
        // Should be unnecessary since the send button is only enables when both are true.
        if (connected && selectedIV.getImage() != null) {
            if (!sending) {
                // Save the original text of the send button and disable the disconnect button
                String ogText = sendButton.getText();
                System.out.println(ogText);
                connectButton.setDisable(true);
                // If the data has not been saved before, get the data by formatting the image
                if (data == null) {
                    data = imgCon.toStringFormat(true);
                }
                ardComm.send(data);
                // While the ArduinoCommunicator is busy sending, change the text on the send button to indicate the data is being transmitted
                sendButton.setText("busy");
                while (ardComm.isSending()) {

                }
                // Restore the text on the send button
                sendButton.setText(ogText);
                connectButton.setDisable(false);
            }
        }
    }

sendButton is the JavaFX Button that calls the sendClicked() method and ardCom is and instance of the class that contains the send() method. isSending() simply returns the sending attribute of the ardCom, which is set to true at the start of the send() method and set to false when the Thread is done sending.

The problem is with this piece of code:

    sendButton.setText("busy");
                while (ardComm.isSending()) {

                }
                // Restore the text on the send button
                sendButton.setText(ogText);

I'm trying to set the sendButton's text to busy to indicate that the data is being sent, then loop until the data transmission is finished (sending is set to false) and end it with changing the text on the sendButton back to the original text. I know this is probably not the best way to achieve this, but I was playing around and could not figure out why this is not working as expected.

The problem is that for some reason, the while loop never ends.

Body:
Thanks to @NomadMaker I found that making the sending variable volatile explains the problem. As far as I understand it, it seems to me that the JavaFX Thread is too busy to update the value of sending causing it to loop infinitely. Making it volatile makes sending stored in main memory instead of being cached thread-locally.

The weird thing is that when I change the loop to actually do something every iteration, like this:

    int n = 0;
    while (ardComm.isSending()) {
        System.out.println(n);
        n++;
    }

it does not loop infinitely. (Maybe it's because println() and n++ are less memory heavy, leaving enough time or something for the sending variable to update. But don't quote me on that)


问:
Can ANDROID_ABIS be specified in my QMake project file (.pro file)
When I open a .pro file with QtCreator 4.12.0 (with Qt 5.14.2), it runs QMake with the following arguments:

```<code>C:\Android_new\QtCreator5_14_2\5.14.2\android\bin\qmake.exe C:\dev\vobs_2019\build\tinyxml\tinyxml-2.6.2\win64\msvc142\tinyxml.pro -spec android-clang "CONFIG+=qtquickcompiler" ANDROID_ABIS="armeabi-v7a" && C:/Android_new/android_sdk/ndk-bundle/prebuilt/windows-x86_64/bin/make.exe qmake_all
</code>```

You see only "armeabi-v7a" is used by default. If I want to handle more, I have to go to project settings and check the other ABI ("arm64-v8a", "x86"...).

Is there no way to specify the ABI supported by my project in the .pro file itself (I tried to add ANDROID_ABIS="armeabi-v7a arm64-v8a" but it had no effect).

答: Click on Project in the left pane then choose Build under your Build & Run configuration. In the Build Steps, look for "qmake:". Expand it by clicking on Details and choose the target ABI.</p>

Body:
When I open a .pro file with QtCreator 4.12.0 (with Qt 5.14.2), it runs QMake with the following arguments:

C:\Android_new\QtCreator5_14_2\5.14.2\android\bin\qmake.exe C:\dev\vobs_2019\build\tinyxml\tinyxml-2.6.2\win64\msvc142\tinyxml.pro -spec android-clang "CONFIG+=qtquickcompiler" ANDROID_ABIS="armeabi-v7a" && C:/Android_new/android_sdk/ndk-bundle/prebuilt/windows-x86_64/bin/make.exe qmake_all

You see only "armeabi-v7a" is used by default. If I want to handle more, I have to go to project settings and check the other ABI ("arm64-v8a", "x86"...).

Is there no way to specify the ABI supported by my project in the .pro file itself (I tried to add ANDROID_ABIS="armeabi-v7a arm64-v8a" but it had no effect).


问:
React/Redux question about dispatching an action to add an item to an array
I am building a flashcard app and I would like to store the id of seen cards in an array so my GET_RANDOM_CARD action does not select the same card twice.

Inside my componentDidMount method, I dispatch the addSeenCard action like so:

```<code>addSeenCard(this.props.randomCard)
</code>```

Here is my portable action creator function for addSeenCard:

```<code>export function addSeenCard(randomCard) {

 return {
    type: 'ADD_SEEN_CARD',
    randomCard: randomCard
  }
}
</code>```

Here is my reducer function:

```<code> case 'ADD_SEEN_CARD':
  return {
      ...state,
     seenCard: [state.seenCard, action.randomCard.id]
    }
</code>```

However, the Redux tool instead of showing an array with an id value shows an array with a nested empty array and a value of null.  I am learning Redux and I am blocked as to where I am going wrong in my code.

Redux state Raw

答:
You can use concat state seenCard array and new value
Here is your updated reducer function:</p>

```<code> case 'ADD_SEEN_CARD':
 return {
  ...state,
 seenCard: state.seenCard.concat(action.randomCard.id)
}
</code>```

Body:
I am building a flashcard app and I would like to store the id of seen cards in an array so my GET_RANDOM_CARD action does not select the same card twice.

Inside my componentDidMount method, I dispatch the addSeenCard action like so:

addSeenCard(this.props.randomCard)

Here is my portable action creator function for addSeenCard:

export function addSeenCard(randomCard) {

 return {
    type: 'ADD_SEEN_CARD',
    randomCard: randomCard
  }
}

Here is my reducer function:

 case 'ADD_SEEN_CARD':
  return {
      ...state,
     seenCard: [state.seenCard, action.randomCard.id]
    }

However, the Redux tool instead of showing an array with an id value shows an array with a nested empty array and a value of null.  I am learning Redux and I am blocked as to where I am going wrong in my code.

Redux state Raw

Body:
You can use concat state seenCard array and new value
Here is your updated reducer function:

 case 'ADD_SEEN_CARD':
 return {
  ...state,
 seenCard: state.seenCard.concat(action.randomCard.id)
}


问:
Cannot show json data in dropdown list jquery
I am getting json data from my php code something like this :

{2: "Robert ", 3: "Adem"}

Now i want to show it in dropdown list using jQuery I'm using the following code but 'm getting object in dropdown.

```<code>jQuery(response).each(function (index, value) {
  jQuery("#name").append(jQuery("<option>").val(value).text(value));
});
</code>```

答:
Aside from doing JSON.parse(). .each() callback should be applied on Array not an Object, just convert your response object to Array using Object.values(), here is a working snippet:

let responseStr = {2:"Robert ", 3:"Adem"}; // <----- Make sure that its an object if its not then you have to do JSON.pares().
console.log(Object.values(responseStr));
jQuery(Object.values(responseStr)).each(function(index,value){
   jQuery('#name').append(jQuery('<option>').val(value).text(value));
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="name"></select></code>```

Body:
I am getting json data from my php code something like this :

{2: "Robert ", 3: "Adem"}

Now i want to show it in dropdown list using jQuery I'm using the following code but 'm getting object in dropdown.

jQuery(response).each(function (index, value) {
  jQuery("#name").append(jQuery("<option>").val(value).text(value));
});

Body:
Aside from doing JSON.parse(). .each() callback should be applied on Array not an Object, just convert your response object to Array using Object.values(), here is a working snippet:

let responseStr = {2:"Robert ", 3:"Adem"}; // <----- Make sure that its an object if its not then you have to do JSON.pares().
console.log(Object.values(responseStr));
jQuery(Object.values(responseStr)).each(function(index,value){
   jQuery('#name').append(jQuery('<option>').val(value).text(value));
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="name"></select>


问:
Why does a String in the Resources of a Xamarin Forms application give a Missing default constructor error?
I am trying to declare a string in the Application.Resources section.  I have seen examples of this on the web, but only when the System assembly refers to mscorlib.

So if I create a WPF .Net Framework app and then in the App.xaml file have the below, this will compile successfully:

```<code><Application x:Class="WpfAppNETFrameworkTestString.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:WpfAppNETFrameworkTestString"
             xmlns:sys="clr-namespace:System;assembly=mscorlib"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
        <sys:String x:Key="myString">my string</sys:String>
    </Application.Resources>
</Application>
</code>```

But if I create a Xamarin Forms mobile app and in the App.xaml file have the below:

```<code><?xml version="1.0" encoding="utf-8" ?>
<Application xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:sys="clr-namespace:System;assembly=netstandard"
             mc:Ignorable="d"
             x:Class="XamarinFormsTestString.App">
    <Application.Resources>
        <sys:String x:Key="myString">my string</sys:String>
    </Application.Resources>
</Application>
</code>```

This then causes a compile error of "Missing default constructor for 'System.String'"

Is there any way of having a string in the resources section without getting this error?

答:
If you want to put the string to the Application.Resources in the Xamarin.Forms. You can add String tab like following code format.

```<code><Application xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             mc:Ignorable="d"
             x:Class="App24.App">
    <Application.Resources>
        <x:String x:Key="mystr">ssgsdgsdg</x:String>
    </Application.Resources>
</Application>
</code>```

Then used in other layout by StaticResource

```<code> <StackLayout>
        <!-- Place new controls here -->
        <Label Text="{StaticResource mystr}"
           HorizontalOptions="Center"
           VerticalOptions="CenterAndExpand" />
    </StackLayout>
</code>```

Here is running screenshot.

Body:
I am trying to declare a string in the Application.Resources section.  I have seen examples of this on the web, but only when the System assembly refers to mscorlib.

So if I create a WPF .Net Framework app and then in the App.xaml file have the below, this will compile successfully:

<Application x:Class="WpfAppNETFrameworkTestString.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:WpfAppNETFrameworkTestString"
             xmlns:sys="clr-namespace:System;assembly=mscorlib"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
        <sys:String x:Key="myString">my string</sys:String>
    </Application.Resources>
</Application>

But if I create a Xamarin Forms mobile app and in the App.xaml file have the below:

<?xml version="1.0" encoding="utf-8" ?>
<Application xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:sys="clr-namespace:System;assembly=netstandard"
             mc:Ignorable="d"
             x:Class="XamarinFormsTestString.App">
    <Application.Resources>
        <sys:String x:Key="myString">my string</sys:String>
    </Application.Resources>
</Application>

This then causes a compile error of "Missing default constructor for 'System.String'"

Is there any way of having a string in the resources section without getting this error?

Body:
If you want to put the string to the Application.Resources in the Xamarin.Forms. You can add String tab like following code format.

<Application xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             mc:Ignorable="d"
             x:Class="App24.App">
    <Application.Resources>
        <x:String x:Key="mystr">ssgsdgsdg</x:String>
    </Application.Resources>
</Application>

Then used in other layout by StaticResource

 <StackLayout>
        <!-- Place new controls here -->
        <Label Text="{StaticResource mystr}"
           HorizontalOptions="Center"
           VerticalOptions="CenterAndExpand" />
    </StackLayout>

Here is running screenshot.


问:
How can I check if the array of objects have all values duplicate?
```<code>var values = [
    { name: 'Car',Data:'Required',value:'Vehicle' },
    { name: 'Auto',Data:'Required',value:'Vehicle'},
    { name: 'Bike',Data:'Required',value:'Vehicle'},
    { name: 'Car',Data:'Required',value:'Vehicle' }
];
</code>```

Duplicate object will be:
                               { name: 'Car',Data:'Required',value:'Vehicle' }

答:
If you want to check all the properties of objects, you have to introduce a new function, and use it to filter your array:

var values = [
    { name: 'Car',Data:'Required',value:'Vehicle' },
    { name: 'Auto',Data:'Required',value:'Vehicle'},
    { name: 'Bike',Data:'Required',value:'Vehicle'},
    { name: 'Bike',Data:'Required',value:'Different VL'},
    { name: 'Car',Data:'Required',value:'Vehicle' }
];

Object.compare = function (obj1, obj2) {
 //Loop through properties in object 1
 for (var p in obj1) {
  //Check property exists on both objects
  if (obj1.hasOwnProperty(p) !== obj2.hasOwnProperty(p)) return false;

  switch (typeof (obj1[p])) {
   //Deep compare objects
   case 'object':
    if (!Object.compare(obj1[p], obj2[p])) return false;
    break;
   //Compare function code
   case 'function':
    if (typeof (obj2[p]) == 'undefined' || (p != 'compare' && obj1[p].toString() != obj2[p].toString())) return false;
    break;
   //Compare values
   default:
    if (obj1[p] != obj2[p]) return false;
  }
 }

 //Check object 2 for any extra properties
 for (var p in obj2) {
  if (typeof (obj1[p]) == 'undefined') return false;
 }
 return true;
};

var doubles = values.filter((x,i,a) =>a.slice(0,i).find(y=>Object.compare(x,y)))

console.log(doubles)```

Body:
var values = [
    { name: 'Car',Data:'Required',value:'Vehicle' },
    { name: 'Auto',Data:'Required',value:'Vehicle'},
    { name: 'Bike',Data:'Required',value:'Vehicle'},
    { name: 'Car',Data:'Required',value:'Vehicle' }
];

Duplicate object will be:
                               { name: 'Car',Data:'Required',value:'Vehicle' }


问:
Implementing css specificity for custom classes based on bootstrap grid breakpoints
I am trying to create my own width classes that make use bootstrap of bootstraps grid breakpoints.
These classes are named things like w-10, w-20 and would have widths of 10% and 20% respectively, or would have named like w-sm-10 w-sm-20 and would have widths of 10% & 20% on a screen that has a width larger than sm(576px), but would have their initial width on mobile.

Using this snippet I've been able to create classes that have this effect.

```<code>@import 'node_modules/bootstrap/scss/bootstrap.scss';

$i : 10;
@while $i <= 90 {
  .w-#{$i} {              //names like w-40, w-60
    width: #{"#{$i}%"};
  }
  @each $bp-name, $bp-pixels in $grid-breakpoints {   //looping through xs, sm, md, lg, xl and their pixel values
    .w-#{$bp-name}-#{$i} {  //names like w-md-40
      width: #{"#{$i}%"};
    }
    @media screen and (max-width: $bp-pixels) {       //Remove the width at the corresponding screen widths
      .w-#{$bp-name}-#{$i} {
        width: initial;
      }
    }
  }
  $i : $i + 10;
}
</code>```

This solution works as long as my elements only have one of these classes, but breaks when 2 or more are assigned because there is no precedence assigned to any of these classes

Ex. This class should have a width of 50% on screens wider than lg, 70% on screens wider than sm, and a width of 90% on all screen less wide than sm, but instead the div of this width will just always be 90%.

```<code><div class='w-lg-50 w-sm-70 w-90'></div>
</code>```

I've read a bit about css-specificity but can't quite wrap my head around it

答:
Instead of max-width use min-width in your media query, it's saying that if your element is at least this wide, then apply this attribute to it.

Also if you use 2 loops, then all the w-40, w-60 classes get defined before the w-sm-40, w-md-40... classes and the sm and md classes then take precedence over the prior classes.

In the same way, all the xs classes are defined before the sm classes, so the sm classes take precedence over the xs classes and so on through md, lg and xl

```<code>//Creates width classes like w-40, w-60 ...
$i : 10;
@while $i <= 90 {
  .w-#{$i} {              //names like w-40, w-60
    width: #{"#{$i}%"};
  }
  $i : $i + 10;
}

@each $bp-name, $bp-pixels in $grid-breakpoints {   //looping through xs, sm, md, lg, xl and their pixel values
  $i : 10;
  @while $i <= 90 {
    @media (min-width: $bp-pixels){ //only works if the screen is wider than this
      .w-#{$bp-name}-#{$i} {  //names like w-md-40
          width: #{"#{$i}%"};
      }
    }
    $i : $i + 10;
  }
}
</code>```

Body:
I am trying to create my own width classes that make use bootstrap of bootstraps grid breakpoints.
These classes are named things like w-10, w-20 and would have widths of 10% and 20% respectively, or would have named like w-sm-10 w-sm-20 and would have widths of 10% & 20% on a screen that has a width larger than sm(576px), but would have their initial width on mobile.

Using this snippet I've been able to create classes that have this effect.

@import 'node_modules/bootstrap/scss/bootstrap.scss';

$i : 10;
@while $i <= 90 {
  .w-#{$i} {              //names like w-40, w-60
    width: #{"#{$i}%"};
  }
  @each $bp-name, $bp-pixels in $grid-breakpoints {   //looping through xs, sm, md, lg, xl and their pixel values
    .w-#{$bp-name}-#{$i} {  //names like w-md-40
      width: #{"#{$i}%"};
    }
    @media screen and (max-width: $bp-pixels) {       //Remove the width at the corresponding screen widths
      .w-#{$bp-name}-#{$i} {
        width: initial;
      }
    }
  }
  $i : $i + 10;
}

This solution works as long as my elements only have one of these classes, but breaks when 2 or more are assigned because there is no precedence assigned to any of these classes

Ex. This class should have a width of 50% on screens wider than lg, 70% on screens wider than sm, and a width of 90% on all screen less wide than sm, but instead the div of this width will just always be 90%.

I've read a bit about css-specificity but can't quite wrap my head around it

Body:
Instead of max-width use min-width in your media query, it's saying that if your element is at least this wide, then apply this attribute to it.

Also if you use 2 loops, then all the w-40, w-60 classes get defined before the w-sm-40, w-md-40... classes and the sm and md classes then take precedence over the prior classes.

In the same way, all the xs classes are defined before the sm classes, so the sm classes take precedence over the xs classes and so on through md, lg and xl

//Creates width classes like w-40, w-60 ...
$i : 10;
@while $i <= 90 {
  .w-#{$i} {              //names like w-40, w-60
    width: #{"#{$i}%"};
  }
  $i : $i + 10;
}

@each $bp-name, $bp-pixels in $grid-breakpoints {   //looping through xs, sm, md, lg, xl and their pixel values
  $i : 10;
  @while $i <= 90 {
    @media (min-width: $bp-pixels){ //only works if the screen is wider than this
      .w-#{$bp-name}-#{$i} {  //names like w-md-40
          width: #{"#{$i}%"};
      }
    }
    $i : $i + 10;
  }
}


问:
How to insert a titles row into a csv file
I have a .csv file which has data but not the column headers. I can able to create new .csv file with oldcsv file's content. But I need to add column headers in first row and from second row the existing data should appear.

Here is the code I have written:

```<code> Dim ioFile As New System.IO.StreamReader("C:\sample.csv")
 Dim ioLine As String      Dim ioLines As String
 ioLine = ioFile.ReadLine
 ioLines = ioLine
 While Not ioLine = ""
    ioLine = ioFile.ReadLine
    ioLines = ioLines & vbCrLf & ioLine
 End While
 Dim ioWriter As New System.IO.StreamWriter("C:\new.csv")
 ioWriter.WriteLine(ioLines)
 ioFile.Close()
 ioWriter.Close()
</code>```

Now i need to add column headers in new.csv as "ID","Name","Number","Amount"

答:
Try this:</p>

```<code>Dim ioFile As New System.IO.StreamReader("C:\sample.csv")
 Dim ioLine As String      Dim ioLines As String
 ioLine = ioFile.ReadLine
 ioLines = """ID"",""Name"",""Number"",""Amount"""
 ioLines &= vbCrLf & ioLine
 While Not ioLine = ""
    ioLine = ioFile.ReadLine
    ioLines = ioLines & vbCrLf & ioLine
 End While
 Dim ioWriter As New System.IO.StreamWriter("C:\new.csv")
 ioWriter.WriteLine(ioLines)
 ioFile.Close()
 ioWriter.Close()
</code>```

Body:
I have a .csv file which has data but not the column headers. I can able to create new .csv file with oldcsv file's content. But I need to add column headers in first row and from second row the existing data should appear.

Here is the code I have written:

 Dim ioFile As New System.IO.StreamReader("C:\sample.csv")
 Dim ioLine As String      Dim ioLines As String
 ioLine = ioFile.ReadLine
 ioLines = ioLine
 While Not ioLine = ""
    ioLine = ioFile.ReadLine
    ioLines = ioLines & vbCrLf & ioLine
 End While
 Dim ioWriter As New System.IO.StreamWriter("C:\new.csv")
 ioWriter.WriteLine(ioLines)
 ioFile.Close()
 ioWriter.Close()

Now i need to add column headers in new.csv as "ID","Name","Number","Amount"

Body:
Try this:

Dim ioFile As New System.IO.StreamReader("C:\sample.csv")
 Dim ioLine As String      Dim ioLines As String
 ioLine = ioFile.ReadLine
 ioLines = """ID"",""Name"",""Number"",""Amount"""
 ioLines &= vbCrLf & ioLine
 While Not ioLine = ""
    ioLine = ioFile.ReadLine
    ioLines = ioLines & vbCrLf & ioLine
 End While
 Dim ioWriter As New System.IO.StreamWriter("C:\new.csv")
 ioWriter.WriteLine(ioLines)
 ioFile.Close()
 ioWriter.Close()


问:
Bundling angularjs html files .net core
Can I bundle html files in .net core? I was able to bundle and minify JS and CSS files. but I am not sure if i could bundle html file or not. </p>

答:
Of course, angularjs and .net core can be used in combination.

Here is a detailed tutorial how to build an Angular Application with ASP.NET Core, please refer to this.

Title: Bundling angularjs html files .net core


问:
Jquery / JavaScript get value from a td of table which is inside a div with id

                Firstname

                Secondname

                name1

                name2

```

This is my HTML structure and I need to get the values 'Firstname' and 'name1' from the table using Jquery or Javascript. Only the outer div has the id. Can someone help.

答:
hi try this i used class name here

                Firstname

                Secondname

                name1

                name2

```

<p>and jquery here</p>

<pre class="lang-js prettyprint-override"><code>alert($('#myDiv td.first, td.name').text());
</code>```

and here is
fiddle

Body:
                Firstname

                Secondname

                name1

                name2

This is my HTML structure and I need to get the values 'Firstname' and 'name1' from the table using Jquery or Javascript. Only the outer div has the id. Can someone help.

Body:
hi try this i used class name here

<div id="myDiv">
    <table>
        <tr>
            <td class="first">
                Firstname
            </td>
            <td>
                Secondname
            </td>
        </tr>
        <tr>
            <td class="name">
                name1
            </td>
            <td>
                name2
            </td>
        </tr>
    </table>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"
    integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>

and jquery here

alert($('#myDiv td.first, td.name').text());

and here is
fiddle


问:
MQHeaderList size is 0, but reading a specific MQRFH2 works
I am wring custom java code to read messages from Websphere MQ (version 8) and read all the headers from the MQ message.

When I use the MQHeaderList to parse all the headers the list size is 0:

```<code>MQMessage message = new MQMessage();
queue.get(message, getOptions);
DataInput in = new DataInputStream (new ByteArrayInputStream (b));
MQHeaderList headersfoundlist = null;
headersfoundlist = new MQHeaderList (in);
System.out.println("headersfoundlist size: " + headersfoundlist.size());
</code>```

However, I read only a specific MQRFH2 it works

```<code>MQMessage message = new MQMessage();
queue.get(message, getOptions);
DataInput in = new DataInputStream (new ByteArrayInputStream (b));
MQRFH2 rfh2 = new MQRFH2(in);
Element usrfolder = rfh2.getFolder("usr", false);
System.out.println("usr folder" + usrfolder);
</code>```

How can I parse all the headers of the MQ Message?

答:
```<code>DataInput in = new DataInputStream (new ByteArrayInputStream (b));
</code>```

What's that about?  Not sure why you want to do that.

It should just be:

```<code>MQMessage message = new MQMessage();
queue.get(message, getOptions);
MQHeaderList headersfoundlist = new MQHeaderList(message);
System.out.println("headersfoundlist size: " + headersfoundlist.size());
</code>```

Read more here.

Update:

@anshu's comment about it not working, well, I've always found MQHeaderList class to be very buggy.  Hence, that is why I don't use it.

Also, 99.99% messages in MQ will only ever have 1 embedded MQ header (i.e. MQRFH2).  Note: A JMS message == MQRFH2 message.  The only case where you will find 2 embedded MQ headers are for messages on the Dead Letter Queue.

i.e.

{MQDLH}{MQRFH2}{message payload}

Is there a real need for your application to process multiple embedded MQ headers?  Is your application putting/getting JMS messages (aka MQRFH2 messages)?

If so then you should do something like the following:

```<code>queue.get(receiveMsg, gmo);

if (CMQC.MQFMT_RF_HEADER_2.equals(receiveMsg.format))
{
   receiveMsg.seek(0);
   MQRFH2 rfh2 = new MQRFH2(receiveMsg);

   int strucLen = rfh2.getStrucLength();
   int encoding = rfh2.getEncoding();
   int CCSID    = rfh2.getCodedCharSetId();
   String format= rfh2.getFormat();
   int flags    = rfh2.getFlags();
   int nameValueCCSID = rfh2.getNameValueCCSID();

   String[] folderStrings = rfh2.getFolderStrings();
   for (String folder : folderStrings)
      System.out.println.logger("Folder: "+folder);

   if (CMQC.MQFMT_STRING.equals(format))
   {
      String msgStr = receiveMsg.readStringOfByteLength(receiveMsg.getDataLength());
      System.out.println.logger("Data: "+msgStr);
   }
   else if (CMQC.MQFMT_NONE.equals(format))
   {
      byte[] b = new byte[receiveMsg.getDataLength()];
      receiveMsg.readFully(b);
      System.out.println.logger("Data: "+new String(b));
   }
}
else if ( (CMQC.MQFMT_STRING.equals(receiveMsg.format)) ||
          (CMQC.MQFMT_NONE.equals(receiveMsg.format))    )
{
   Enumeration<String> props = receiveMsg.getPropertyNames("%");
   if (props != null)
   {
      System.out.println.logger("Named Properties:");
      while (props.hasMoreElements())
      {
         String propName = props.nextElement();
         Object o = receiveMsg.getObjectProperty(propName);
         System.out.println.logger("   Name="+propName+" : Value="+o);
      }
   }

   if (CMQC.MQFMT_STRING.equals(receiveMsg.format))
   {
      String msgStr = receiveMsg.readStringOfByteLength(receiveMsg.getMessageLength());
      System.out.println.logger("Data: "+msgStr);
   }
   else
   {
      byte[] b = new byte[receiveMsg.getMessageLength()];
      receiveMsg.readFully(b);
      System.out.println.logger("Data: "+new String(b));
   }
}
else
{
   byte[] b = new byte[receiveMsg.getMessageLength()];
   receiveMsg.readFully(b);
   System.out.println.logger("Data: "+new String(b));
}
</code>```

Body:
I am wring custom java code to read messages from Websphere MQ (version 8) and read all the headers from the MQ message.

When I use the MQHeaderList to parse all the headers the list size is 0:

MQMessage message = new MQMessage();
queue.get(message, getOptions);
DataInput in = new DataInputStream (new ByteArrayInputStream (b));
MQHeaderList headersfoundlist = null;
headersfoundlist = new MQHeaderList (in);
System.out.println("headersfoundlist size: " + headersfoundlist.size());

However, I read only a specific MQRFH2 it works

MQMessage message = new MQMessage();
queue.get(message, getOptions);
DataInput in = new DataInputStream (new ByteArrayInputStream (b));
MQRFH2 rfh2 = new MQRFH2(in);
Element usrfolder = rfh2.getFolder("usr", false);
System.out.println("usr folder" + usrfolder);

How can I parse all the headers of the MQ Message?

Body:
DataInput in = new DataInputStream (new ByteArrayInputStream (b));

What's that about?  Not sure why you want to do that.

It should just be:

MQMessage message = new MQMessage();
queue.get(message, getOptions);
MQHeaderList headersfoundlist = new MQHeaderList(message);
System.out.println("headersfoundlist size: " + headersfoundlist.size());

Read more here.

Update:

@anshu's comment about it not working, well, I've always found MQHeaderList class to be very buggy.  Hence, that is why I don't use it.

Also, 99.99% messages in MQ will only ever have 1 embedded MQ header (i.e. MQRFH2).  Note: A JMS message == MQRFH2 message.  The only case where you will find 2 embedded MQ headers are for messages on the Dead Letter Queue.

i.e.

{MQDLH}{MQRFH2}{message payload}

Is there a real need for your application to process multiple embedded MQ headers?  Is your application putting/getting JMS messages (aka MQRFH2 messages)?

If so then you should do something like the following:

queue.get(receiveMsg, gmo);

if (CMQC.MQFMT_RF_HEADER_2.equals(receiveMsg.format))
{
   receiveMsg.seek(0);
   MQRFH2 rfh2 = new MQRFH2(receiveMsg);

   int strucLen = rfh2.getStrucLength();
   int encoding = rfh2.getEncoding();
   int CCSID    = rfh2.getCodedCharSetId();
   String format= rfh2.getFormat();
   int flags    = rfh2.getFlags();
   int nameValueCCSID = rfh2.getNameValueCCSID();

   String[] folderStrings = rfh2.getFolderStrings();
   for (String folder : folderStrings)
      System.out.println.logger("Folder: "+folder);

   if (CMQC.MQFMT_STRING.equals(format))
   {
      String msgStr = receiveMsg.readStringOfByteLength(receiveMsg.getDataLength());
      System.out.println.logger("Data: "+msgStr);
   }
   else if (CMQC.MQFMT_NONE.equals(format))
   {
      byte[] b = new byte[receiveMsg.getDataLength()];
      receiveMsg.readFully(b);
      System.out.println.logger("Data: "+new String(b));
   }
}
else if ( (CMQC.MQFMT_STRING.equals(receiveMsg.format)) ||
          (CMQC.MQFMT_NONE.equals(receiveMsg.format))    )
{
   Enumeration<String> props = receiveMsg.getPropertyNames("%");
   if (props != null)
   {
      System.out.println.logger("Named Properties:");
      while (props.hasMoreElements())
      {
         String propName = props.nextElement();
         Object o = receiveMsg.getObjectProperty(propName);
         System.out.println.logger("   Name="+propName+" : Value="+o);
      }
   }

   if (CMQC.MQFMT_STRING.equals(receiveMsg.format))
   {
      String msgStr = receiveMsg.readStringOfByteLength(receiveMsg.getMessageLength());
      System.out.println.logger("Data: "+msgStr);
   }
   else
   {
      byte[] b = new byte[receiveMsg.getMessageLength()];
      receiveMsg.readFully(b);
      System.out.println.logger("Data: "+new String(b));
   }
}
else
{
   byte[] b = new byte[receiveMsg.getMessageLength()];
   receiveMsg.readFully(b);
   System.out.println.logger("Data: "+new String(b));
}


问:
Regex expression to extract From & To Date?
I am trying to extract from and to year in separate group using regex but not able to extract because of different format as shown below.
Applied Regex : ([0-9]+)-?([0-9a-z]+)

Below is the complete data that need to be extracted:

```<code>['165-180 A.D.',
 '1520-unknown',
 '1665',
 '1817-1923',
 'Late 1800s',
 '1918-1920',
 '1957-1958',
 '2009']
</code>```

The above regex extracts 165,1520,166 in group 1 and 2019,unknown,5 in group 2. Need to put 1665 in group1 and blank field in group2 regex.
Similarly Late 1800s in group1

```<code>wp_page = requests.get("https://www.washingtonpost.com/graphics/2020/local/retropolis/coronavirus-deadliest-pandemics/")
wp_soup = bs(wp_page.content, 'html.parser')

[names.get_text() for  names in wp_soup.find_all('h5')][0:-2]

wp_year_from_list=[]
wp_year_to_list=[]
wp_year_regex=re.compile('([0-9]+)-?([0-9a-z]+)')
for names in wp_soup.find_all('h5'):
    if (wp_year_regex.search(names.text)!= None):
        wp_year_from_list.append(wp_year_regex.search(names.text).group(1))
        wp_year_to_list.append(wp_year_regex.search(names.text).group(2))```
```

答:
using * in the second group to get your required result.

```<code>([0-9]+)-?([0-9a-z]+)*
                     ^^
</code>```

Body:
I am trying to extract from and to year in separate group using regex but not able to extract because of different format as shown below.
Applied Regex : ([0-9]+)-?([0-9a-z]+)

Below is the complete data that need to be extracted:

['165-180 A.D.',
 '1520-unknown',
 '1665',
 '1817-1923',
 'Late 1800s',
 '1918-1920',
 '1957-1958',
 '2009']

The above regex extracts 165,1520,166 in group 1 and 2019,unknown,5 in group 2. Need to put 1665 in group1 and blank field in group2 regex.
Similarly Late 1800s in group1

wp_page = requests.get("https://www.washingtonpost.com/graphics/2020/local/retropolis/coronavirus-deadliest-pandemics/")
wp_soup = bs(wp_page.content, 'html.parser')

[names.get_text() for  names in wp_soup.find_all('h5')][0:-2]

wp_year_from_list=[]
wp_year_to_list=[]
wp_year_regex=re.compile('([0-9]+)-?([0-9a-z]+)')
for names in wp_soup.find_all('h5'):
    if (wp_year_regex.search(names.text)!= None):
        wp_year_from_list.append(wp_year_regex.search(names.text).group(1))
        wp_year_to_list.append(wp_year_regex.search(names.text).group(2))```

Body:
using * in the second group to get your required result.

([0-9]+)-?([0-9a-z]+)*
                     ^^


答:
For your requirement you need to add ? quantifier for your second group. So your regex will look like:

```<code>([0-9]+)-?([0-9a-z]+)?
                     ^^
</code>```

Explanation of the above regex:

([0-9]+) - Capturing group which captures digits 1 or more time.

-? - Matches a hyphen literally zero or 1 time.

([0-9a-z]+)? - Second capturing group capturing digits and letters 1 or more times and the group can appear 0 or 1 time.

You can find the demo of the above regex in here.

Title: Regex expression to extract From & To Date?

Body:
For your requirement you need to add ? quantifier for your second group. So your regex will look like:

([0-9]+)-?([0-9a-z]+)?
                     ^^

Explanation of the above regex:

([0-9]+) - Capturing group which captures digits 1 or more time.

-? - Matches a hyphen literally zero or 1 time.

([0-9a-z]+)? - Second capturing group capturing digits and letters 1 or more times and the group can appear 0 or 1 time.

You can find the demo of the above regex in here.


问:
Deleting Specific Cache Files
As you know, ezSql has a useful caching feature.
I'm newly using this but when i edit anything on database, i'm deleting all cached files, and waiting for caching them again.

I'll explain it with an example,
There is a page (http://domain.com/user.php?u=username) which listing user's datas (username, city, phone etc..) .

I'm caching all queries on user.php file and all users' datas caching seperately. When some user (John) update own datas. When this happened, i'm deleting all cache files, so i'm deleting all user's cached datas. Are there any way to deleted (or refresh) only John's datas cache?

What do you think, is it possible ? You know cache files names is hashed (like this: 6f3b84011a8693ad7e5b86c6dff3d27d )

答: I don't believe so. The caching scheme in ezSQL is very limited. However, if you set up a separate directory for each set of queries you want to cache, you could only delete those that are specific.</p>

Title: Deleting Specific Cache Files


问:
Changing amount of questions based on what the user says in Python
I am trying to have a Python script that asks you how many URLs you want to input, then asks for that amount of URL. So if you say that you have 5 URLs, then it would ask you for a URL 5 times.

So it asks for URLs, you say you have X amount of URLs, so it asks for X amount of different URLs.

The only thing i can think of is the following.

```<code>while True:
    if amount > 1:
        url1 = input("Whats your first url? ")
        continue
    if amount > 2:
        url2 = input("Whats your second url? ")
        continue
</code>```

Above is the only thing i can think of as, I'm relatively uninformed regarding coding and python as a language. If you have a better way of doing this, please let me know and tell me what libraries i need to either install or import, sorry if im asking alot but once again, i'm not the greatest at coding, Thanks in advance.

答:
You could do something like this:

```<code>urlnum = int(input("How many urls?"))
urllist = []

for e in range(urlnum):
    urllist.append(input("Type URL %s" % str(e+1)))
</code>```

then to get a url, you would use urllist[0] to get the first one, urllist[1] to get the second, etc.

Body:
I am trying to have a Python script that asks you how many URLs you want to input, then asks for that amount of URL. So if you say that you have 5 URLs, then it would ask you for a URL 5 times.

So it asks for URLs, you say you have X amount of URLs, so it asks for X amount of different URLs.

The only thing i can think of is the following.

while True:
    if amount > 1:
        url1 = input("Whats your first url? ")
        continue
    if amount > 2:
        url2 = input("Whats your second url? ")
        continue

Above is the only thing i can think of as, I'm relatively uninformed regarding coding and python as a language. If you have a better way of doing this, please let me know and tell me what libraries i need to either install or import, sorry if im asking alot but once again, i'm not the greatest at coding, Thanks in advance.

Body:
You could do something like this:

urlnum = int(input("How many urls?"))
urllist = []

for e in range(urlnum):
    urllist.append(input("Type URL %s" % str(e+1)))

then to get a url, you would use urllist[0] to get the first one, urllist[1] to get the second, etc.


问:
Stackdriver agent installation failed
I am trying to install Stackdriver Agent. I am using the Google cloud instance (os Ubuntu) and followed the instruction given at google cloud docs for monitoring. Here, are the logs from my server console.</p>

```<code>root@instance-1:~/opt# sudo bash stack-install.sh --write-gcm
Installing agents for Debian or Ubuntu.
curl: (22) The requested URL returned error: 404 Not Found
OK
Hit:1 http://asia-east1.gce.archive.ubuntu.com/ubuntu yakkety InRelease
Hit:2 http://asia-east1.gce.archive.ubuntu.com/ubuntu yakkety-updates     InRelease
Get:3 http://asia-east1.gce.archive.ubuntu.com/ubuntu yakkety-backports     InRelease [102 kB]
Ign:4 http://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.2 InRelease
Hit:5 http://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.2 Release
Hit:6 http://security.ubuntu.com/ubuntu yakkety-security InRelease
Hit:8 http://archive.canonical.com/ubuntu yakkety InRelease
Hit:9 https://deb.nodesource.com/node_6.x yakkety InRelease
Fetched 102 kB in 0s (111 kB/s)
Reading package lists...
Reading package lists...
Building dependency tree...
Reading state information...
E: Unable to locate package stackdriver-agent
Installation failed.
root@instance-1:~/opt#
</code>```

答:
First you need to type this:

```<code>sudo apt-cache madison stackdriver-agent
</code>```

To show the list of available versions of the agent in order to select which version to install.

Results:

stackdriver-agent | 6.0.2-1.bionic |
  http://packages.cloud.google.com/apt
  google-cloud-monitoring-bionic-all/main amd64 Packages

stackdriver-agent | 6.0.1-1.bionic |
  http://packages.cloud.google.com/apt
  google-cloud-monitoring-bionic-all/main amd64 Packages

stackdriver-agent | 6.0.0-1.bionic |
  http://packages.cloud.google.com/apt
  google-cloud-monitoring-bionic-all/main amd64 Packages

stackdriver-agent | 5.5.2-1002.bionic |
  http://packages.cloud.google.com/apt
  google-cloud-monitoring-bionic-all/main amd64 Packages

stackdriver-agent | 5.5.2-1001.bionic |
  http://packages.cloud.google.com/apt
  google-cloud-monitoring-bionic-all/main amd64 Packages

Then:

```<code>sudo apt-get install -y 'stackdriver-agent=[MAJOR_VERSION].*'
</code>```

For example, to pin to the 6.0.2-1 bionic of the agent, run:

```<code>sudo apt-get install -y 'stackdriver-agent=6.0.2-1.bionic*'
</code>```

Title: Stackdriver agent installation failed

Body:
I am trying to install Stackdriver Agent. I am using the Google cloud instance (os Ubuntu) and followed the instruction given at google cloud docs for monitoring. Here, are the logs from my server console.

root@instance-1:~/opt# sudo bash stack-install.sh --write-gcm
Installing agents for Debian or Ubuntu.
curl: (22) The requested URL returned error: 404 Not Found
OK
Hit:1 http://asia-east1.gce.archive.ubuntu.com/ubuntu yakkety InRelease
Hit:2 http://asia-east1.gce.archive.ubuntu.com/ubuntu yakkety-updates     InRelease
Get:3 http://asia-east1.gce.archive.ubuntu.com/ubuntu yakkety-backports     InRelease [102 kB]
Ign:4 http://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.2 InRelease
Hit:5 http://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.2 Release
Hit:6 http://security.ubuntu.com/ubuntu yakkety-security InRelease
Hit:8 http://archive.canonical.com/ubuntu yakkety InRelease
Hit:9 https://deb.nodesource.com/node_6.x yakkety InRelease
Fetched 102 kB in 0s (111 kB/s)
Reading package lists...
Reading package lists...
Building dependency tree...
Reading state information...
E: Unable to locate package stackdriver-agent
Installation failed.
root@instance-1:~/opt#

Body:
First you need to type this:

sudo apt-cache madison stackdriver-agent

To show the list of available versions of the agent in order to select which version to install.

Results:

stackdriver-agent | 6.0.2-1.bionic |
  http://packages.cloud.google.com/apt
  google-cloud-monitoring-bionic-all/main amd64 Packages

stackdriver-agent | 6.0.1-1.bionic |
  http://packages.cloud.google.com/apt
  google-cloud-monitoring-bionic-all/main amd64 Packages

stackdriver-agent | 6.0.0-1.bionic |
  http://packages.cloud.google.com/apt
  google-cloud-monitoring-bionic-all/main amd64 Packages

stackdriver-agent | 5.5.2-1002.bionic |
  http://packages.cloud.google.com/apt
  google-cloud-monitoring-bionic-all/main amd64 Packages

stackdriver-agent | 5.5.2-1001.bionic |
  http://packages.cloud.google.com/apt
  google-cloud-monitoring-bionic-all/main amd64 Packages

Then:

sudo apt-get install -y 'stackdriver-agent=[MAJOR_VERSION].*'

For example, to pin to the 6.0.2-1 bionic of the agent, run:

sudo apt-get install -y 'stackdriver-agent=6.0.2-1.bionic*'


问:
Orika - list to list conversion
This is probably an easy one, but I cant find it in the docs.
I have a person class

```<code>class BasicPerson {
   private String name;
   private int age;
   private Date birthDate;
   // getters/setters omitted
}
</code>```

and a list of it

```<code>ArrayList<Person>
</code>```

I want to change them to change them to

```<code>ArrayList<PersonDTO>
</code>```

but with out an explicit loop.
Is there a way to use MapperFacade.map for a list to list one line conversion ?

答:
If you use the MapperFacade interface, Orika can perform the mapping multiple times on the collection:

```<code>final MapperFacade mapperFacade = mapperFactory.getMapperFacade();
final List<Person> people = // Get the person instances
final List<PersonDto> personDtos = mapperFacade.mapAsList(people, PersonDto.class);
</code>```

On the other hand, if you use the BoundMapperFacade interface, it doesn't contain such a convenience method.

And lastly, if you choose to use the ConfigurableMapper approach, it also includes a mapAsList method which in fact delegates to the MapperFacade.mapAsList method.

Title: Orika - list to list conversion

Body:
This is probably an easy one, but I cant find it in the docs.
I have a person class

class BasicPerson {
   private String name;
   private int age;
   private Date birthDate;
   // getters/setters omitted
}

and a list of it

ArrayList<Person>

I want to change them to change them to

ArrayList<PersonDTO>

but with out an explicit loop.
Is there a way to use MapperFacade.map for a list to list one line conversion ?

Body:
If you use the MapperFacade interface, Orika can perform the mapping multiple times on the collection:

final MapperFacade mapperFacade = mapperFactory.getMapperFacade();
final List<Person> people = // Get the person instances
final List<PersonDto> personDtos = mapperFacade.mapAsList(people, PersonDto.class);

On the other hand, if you use the BoundMapperFacade interface, it doesn't contain such a convenience method.

And lastly, if you choose to use the ConfigurableMapper approach, it also includes a mapAsList method which in fact delegates to the MapperFacade.mapAsList method.


问:
Getting TinyUrl in Javascript
```<code>function ShortUrl(bigurl)
{
$.getJSON(
  "http://tinyurl.com/api-create.php",
   url: 'http://dfsghdsvfbjvjd.com',
  function(data){
   alert(data);
  });
}
</code>```

Not Working

```<code>$['getJSON']('http://tinyurl.com/api-create.php?url=http://xxxxxxx.com/', function (a) {
                         h = a;
alert (h);

                     });
</code>```

This Call is Also Not Working.
Tried Various calls but not getting tinyurl.

答:
Calling the TinyUrl API directly in the browser would lead you to CORS issue, one of the workaround is to use cors-anywhere service. I usually use the tinyurl-client npm package to shorten url on the browser, here is how to use it

Install it in your terminal

npm install @kulkul/tinyurl-client
```

<ol start="2">
<li>Use it on your javascript</li>
</ol>

<pre class="lang-js prettyprint-override"><code>import shortenUrl from "@kulkul/tinyurl-client";

shortenUrl("https://kulkul.tech").then((result) => {
    console.log({ result }); // https://tinyurl.com/<slug>
});
</code>```

P.S. I'm the creator of the npm package, if you have any issue, you can post it here https://github.com/kulkultech/tinyurl-client

Title: Getting TinyUrl in Javascript

Body:
function ShortUrl(bigurl)
{
$.getJSON(
  "http://tinyurl.com/api-create.php",
   url: 'http://dfsghdsvfbjvjd.com',
  function(data){
   alert(data);
  });
}

Not Working

$['getJSON']('http://tinyurl.com/api-create.php?url=http://xxxxxxx.com/', function (a) {
                         h = a;
alert (h);

                     });

This Call is Also Not Working.
Tried Various calls but not getting tinyurl.

Body:
Calling the TinyUrl API directly in the browser would lead you to CORS issue, one of the workaround is to use cors-anywhere service. I usually use the tinyurl-client npm package to shorten url on the browser, here is how to use it

Install it in your terminal

npm install @kulkul/tinyurl-client

Use it on your javascript

import shortenUrl from "@kulkul/tinyurl-client";

shortenUrl("https://kulkul.tech").then((result) => {
    console.log({ result }); // https://tinyurl.com/<slug>
});

P.S. I'm the creator of the npm package, if you have any issue, you can post it here https://github.com/kulkultech/tinyurl-client


问:
CPAN first launch (Proxy Configuration)
i need to run cpan trough proxy but when i try to configure i got errors and cant enter to cpan for the first time

```<code>root@srv-linux01:~# cpan

CPAN.pm requires configuration, but most of it can be done automatically.
If you answer 'no' below, you will enter an interactive dialog for each
configuration option instead.

Would you like to configure as much as possible automatically? [yes] no
</code>```

On proxy settings:

```<code>If you're accessing the net via proxies, you can specify them in the
CPAN configuration or via environment variables. The variable in
the $CPAN::Config takes precedence.

 <ftp_proxy>
Your ftp_proxy? [] http://username:password@proxyIP:Port/  <---- is ok the information?

 <http_proxy>
Your http_proxy? [] http://username:password@proxyIP:Port/  <---- is ok the information?

 <no_proxy>
Your no_proxy? []

If your proxy is an authenticating proxy, you can store your username
permanently. If you do not want that, just press ENTER. You will then
be asked for your username in every future session.

Your proxy user id? []     <---- username is needed again?

Your password for the authenticating proxy can also be stored
permanently on disk. If this violates your security policy, just press
ENTER. You will then be asked for the password in every future
session.

Your proxy password?
</code>```

And before that i get this.

```<code>Fetching with HTTP::Tiny:
http://www.perl.org/CPAN/MIRRORED.BY.gz
Error downloading with HTTP::Tiny: Not a CODE reference at /usr/share/perl/5.18/CPAN/HTTP/Client.pm line 112, <STDIN> line 65.
</code>```

Im using Ubuntu Server 14.04 LTS and Perl 5.18.2

Thanks

答:
what I did to overcome cpan proxy behavour is to prefix the command with proxychains command.

Details about proxychains: https://github.com/haad/proxychains

Title: CPAN first launch (Proxy Configuration)

Body:
i need to run cpan trough proxy but when i try to configure i got errors and cant enter to cpan for the first time

root@srv-linux01:~# cpan

CPAN.pm requires configuration, but most of it can be done automatically.
If you answer 'no' below, you will enter an interactive dialog for each
configuration option instead.

Would you like to configure as much as possible automatically? [yes] no

On proxy settings:

If you're accessing the net via proxies, you can specify them in the
CPAN configuration or via environment variables. The variable in
the $CPAN::Config takes precedence.

 <ftp_proxy>
Your ftp_proxy? [] http://username:password@proxyIP:Port/  <---- is ok the information?

 <http_proxy>
Your http_proxy? [] http://username:password@proxyIP:Port/  <---- is ok the information?

 <no_proxy>
Your no_proxy? []

If your proxy is an authenticating proxy, you can store your username
permanently. If you do not want that, just press ENTER. You will then
be asked for your username in every future session.

Your proxy user id? []     <---- username is needed again?

Your password for the authenticating proxy can also be stored
permanently on disk. If this violates your security policy, just press
ENTER. You will then be asked for the password in every future
session.

Your proxy password?

And before that i get this.

Fetching with HTTP::Tiny:
http://www.perl.org/CPAN/MIRRORED.BY.gz
Error downloading with HTTP::Tiny: Not a CODE reference at /usr/share/perl/5.18/CPAN/HTTP/Client.pm line 112, <STDIN> line 65.

Im using Ubuntu Server 14.04 LTS and Perl 5.18.2

Thanks