问:
Ruby: Chaining methods give different results: .chars.pop
I want to make an iteration loop where at each step the string "***" would have a sign disappearing (iteration 2 : "**", iteration 3: "*"). I tried in irb different ways to do so and results seems to be all over the place !

```<code>[14] pry(main)> a="***".chars.pop
=> "*"
[15] pry(main)> a
=> "*"
[16] pry(main)> a="***".chars
=> ["*", "*", "*"]
[17] pry(main)> a.pop
=> "*"
[18] pry(main)> a
=> ["*", "*"]
[19] pry(main)> a="***"
=> "***"
[20] pry(main)> a.chars.pop
=> "*"
[21] pry(main)> a
=> "***"
</code>```

So sometimes I have "*", sometimes ["*","*"], or even "***"... What the heck ? could you please explain what is happening here and what would be the best way to achieve what I'm trying to do? Thanks a million!

答:
```<code>a = "***".chars.pop
# => "*"
a
# => "*"
</code>```

Here, you take the string "***", and gather an array of its characters with "***".chars. The array of characters (i.e. one-character strings) is in no way connected to the original string.

Then, you pop the last element from the character array. Array#pop now modofies the original array (to remove the last element) and returns this element. Since you are assigning the result of this method to your a variable, you effectively set a = "*". The intermediate array of characters as well as the initial string are thrown away.

```<code>a = "***".chars
# => ["*", "*", "*"]
</code>```

Here, you assign the array of characters to the a variable (and throw away the initial string).

```<code>a.pop
# => "*"
</code>```

As explained above, Array#pop return the last element of the array...

```<code>a
# => ["*", "*"]
</code>```

... and it modifies the array it is called on to remove the last element (i.e. the one returned). Thus, a now has only 2 elements, all but the last one poped off.

```<code>a = "***"
# => "***"
</code>```

Here, you assign a string "***" to the a variabe.

```<code>a.chars.pop
# => "*"
</code>```

As before, you get an array of chartacters from the string (which again is not connected to the original string in any way) and remove the last element which is returned. The intermediate array returned by a.chars is thrown away.

```<code>a
# => "***"
</code>```

Since you have only modified the intermediate array but not the original string, a is unchanged.

Now, it apears that you intially want to just remove the last character of a string. This can be done by:

```<code>a = "***"
b = a[0,-2]
</code>```

Here, you get a new string b which is basically a copy of the string a with the last character removed.

If you want to modify the original string in place (which often is not desireable), you could e.g. use:

```<code>a = "***"
a.chop!
a
# => "**"
</code>```

(Note though that Array#chop! also returns a trailing newline if present. See the documentation for details and note the difference between String#chop and String#chop!.

Body:
I want to make an iteration loop where at each step the string "***" would have a sign disappearing (iteration 2 : "**", iteration 3: "*"). I tried in irb different ways to do so and results seems to be all over the place !

[14] pry(main)> a="***".chars.pop
=> "*"
[15] pry(main)> a
=> "*"
[16] pry(main)> a="***".chars
=> ["*", "*", "*"]
[17] pry(main)> a.pop
=> "*"
[18] pry(main)> a
=> ["*", "*"]
[19] pry(main)> a="***"
=> "***"
[20] pry(main)> a.chars.pop
=> "*"
[21] pry(main)> a
=> "***"

So sometimes I have "*", sometimes ["*","*"], or even "***"... What the heck ? could you please explain what is happening here and what would be the best way to achieve what I'm trying to do? Thanks a million!

Body:
a = "***".chars.pop
# => "*"
a
# => "*"

Here, you take the string "***", and gather an array of its characters with "***".chars. The array of characters (i.e. one-character strings) is in no way connected to the original string.

Then, you pop the last element from the character array. Array#pop now modofies the original array (to remove the last element) and returns this element. Since you are assigning the result of this method to your a variable, you effectively set a = "*". The intermediate array of characters as well as the initial string are thrown away.

a = "***".chars
# => ["*", "*", "*"]

Here, you assign the array of characters to the a variable (and throw away the initial string).

a.pop
# => "*"

As explained above, Array#pop return the last element of the array...

a
# => ["*", "*"]

... and it modifies the array it is called on to remove the last element (i.e. the one returned). Thus, a now has only 2 elements, all but the last one poped off.

a = "***"
# => "***"

Here, you assign a string "***" to the a variabe.

a.chars.pop
# => "*"

As before, you get an array of chartacters from the string (which again is not connected to the original string in any way) and remove the last element which is returned. The intermediate array returned by a.chars is thrown away.

a
# => "***"

Since you have only modified the intermediate array but not the original string, a is unchanged.

Now, it apears that you intially want to just remove the last character of a string. This can be done by:

a = "***"
b = a[0,-2]

Here, you get a new string b which is basically a copy of the string a with the last character removed.

If you want to modify the original string in place (which often is not desireable), you could e.g. use:

a = "***"
a.chop!
a
# => "**"

(Note though that Array#chop! also returns a trailing newline if present. See the documentation for details and note the difference between String#chop and String#chop!.


来源: stackexchange

问:
Regex for checking address house number
I'm using the following expression to validate a house number:

```<code>^\d{1,4}([a-zA-Z]{1,2}\d{1,3}|[a-zA-Z]{1,2}|)$
</code>```

Now the requirement has changed to the following constraints:

one number (25)

one number w/ one letter (25A)

one number w/ a second one divided by a hyphen (25-32)

one number w/ a second one divided by a hyphen and one letter w/ blank (25-32 A)

How do I validate these w/ changes to the regex above?

答:
If you only want to match those values, you might use a pattern to match 1 or more digits followed by an optional part that matches either A-Z OR a hyphen and 1+ digits optionally followed by a space and a char A-Z

```<code>^\d+(?:[A-Z]|-\d+(?: [A-Z])?)?$
</code>```

^ Start of string

\d+ Match 1+ digits

(?: Non capture group

[A-Z] Match a char A-Z

| Or

-\d+ Match

(?: [A-Z])?

)? Close group and make it optional

$ End of string

Regex demo

ContentLicense: CC BY-SA 4.0

Title: Regex for checking address house number

Body:
I'm using the following expression to validate a house number:

^\d{1,4}([a-zA-Z]{1,2}\d{1,3}|[a-zA-Z]{1,2}|)$

Now the requirement has changed to the following constraints:

one number (25)

one number w/ one letter (25A)

one number w/ a second one divided by a hyphen (25-32)

one number w/ a second one divided by a hyphen and one letter w/ blank (25-32 A)

How do I validate these w/ changes to the regex above?

Body:
If you only want to match those values, you might use a pattern to match 1 or more digits followed by an optional part that matches either A-Z OR a hyphen and 1+ digits optionally followed by a space and a char A-Z

^\d+(?:[A-Z]|-\d+(?: [A-Z])?)?$

^ Start of string

\d+ Match 1+ digits

(?: Non capture group

[A-Z] Match a char A-Z

| Or

-\d+ Match

(?: [A-Z])?

)? Close group and make it optional

$ End of string

Regex demo


问:
XCode 4 pinwheeling while trying to debug
It seems whenever I go to use the debugger in my project xcode decides to get caught and shows the pinwheel indefinitely. (haven't waited more than 5 minutes.) The strange thing is that this is only happening with one of my projects, the other ones are working fine. I can mouse over a variable and it will give me the information and everything, but in my one application, not such luck.

Is there a programming error that would cause such an issue? Or is there a possible solution to this problem? Thanks in advance for any help!

答: I honestly have no clue what the problem was, it stopped doing it all of a sudden, then I did an update to xcode and it has not done it since. It probably just caught a hitch somewhere. whatever. Thanks for your help!</p>

ContentLicense: CC BY-SA 3.0


问:
How to convert the SQL query to ElasticSearch style?
I have this complex query for MySQL which counts unique visits for each day. I want to make it faster using ElasticSearch.

Imagine a table like this:

id | site_id | created_at ________ | stat_cookie_hash

10 | 12346 | 2019-11-11 15:42:24 | sf2f2eghasdh2nvr

11 | 12346 | 2019-10-26 09:41:09 | jk67j97jkhjghklj

12 | 12346 | 2019-10-26 14:25:01 | vnuoi96iyoui60yu

13 | 12346 | 2019-09-01 18:12:54 | zxcqscgscv1vcdcv

Result of the query would be like:

2019-11-11 | 1

2019-10-26 | 2

2019-09-01 | 1

The SQL query itself:

    SELECT day, COUNT(*) as cnt
    FROM (SELECT DISTINCT stat_cookie_hash, DATE(DATE_ADD(created_at, INTERVAL :timezone MINUTE)) as day
        FROM stat_visitor
        WHERE site_id=:site_id) AS T
    GROUP BY day
    ORDER BY day DESC
```

<p>:timezone is an integer like 180</p>

<p>:site_id is an integer like 40</p>

<p><strong>The same one but with substitution:</strong></p>

<pre class="lang-sql prettyprint-override"><code>    SELECT day, COUNT(*) as cnt
    FROM (SELECT DISTINCT stat_cookie_hash, DATE(DATE_ADD(created_at, INTERVAL 180 MINUTE)) as day
        FROM stat_visitor
        WHERE site_id=40) AS T
    GROUP BY day
    ORDER BY day DESC
</code>```

ElasticSearch version:

```<code>{
    "version" : {
        "number" : "7.4.1",
        "build_flavor" : "default",
        "build_type" : "rpm",
        "build_hash" : "fc0eeb6e2c25915d63d871d344e3d0b45ea0ea1e",
        "build_date" : "2019-10-22T17:16:35.176724Z",
        "build_snapshot" : false,
        "lucene_version" : "8.2.0",
        "minimum_wire_compatibility_version" : "6.8.0",
        "minimum_index_compatibility_version" : "6.0.0-beta1"
      }
}
</code>```

I'm completely new to ElasticSearch, so I don't know how to manage it. Help me, please!

It would be great if you know Yii2 Framework and could show me how to rewrite the SQL query with yii2-elasticsearch extension.

答:
I've found a soultion.

First of all, I removed timezone and DATE, DATE_ADD functions from the query.

Then I converted it to ElasticSearch format. It's integrated PHP version:

```<code>    public static function elasticSearch($site_id, $page_id=null, $markup_id=null, $started_at=null, $group_by='created_day')
    {
        $index = 'stat_visitor';

        $client = ClientBuilder::create()
            ->setSelector('\Elasticsearch\ConnectionPool\Selectors\RoundRobinSelector')
            ->build();

        $params = [
            'index' => $index,
            'size' => 0,
            'body' => [
                'aggs' => [
                    'cnt' => [
                        'terms' => [
                            'field' => $group_by,
                            'size' => 9999,
                            'order' => ['_term' => 'desc'],
                        ],
                        'aggs' => [
                            'unique_hashes' => [
                                'cardinality' => [
                                    'field' => 'stat_cookie_hash'
                                ]
                            ]
                        ]
                    ]
                ],
                'query' => [
                    'bool' => [
                        'must' => [
                            ['term' => ['site_id' => $site_id]],
                        ],
                    ],
                ],
                'sort' => ['created_day' => 'desc'],
            ]
        ];

        if ($page_id) {
            $params['body']['query']['bool']['must'][] = ['term' => ['page_id' => $page_id]];
        }

        if ($markup_id) {
            $params['body']['query']['bool']['must'][] = ['term' => ['markup_id' => $markup_id]];
        }

        if ($started_at) {
            $params['body']['query']['bool']['filter'][] = ['range' => ['created_at' => [ 'gte' => $started_at]]];
        }

        $response = $client->search($params);

        $result = [];
        foreach ($response['aggregations']['cnt']['buckets'] as $bucket) {
            $result[$bucket['key_as_string']] = $bucket['unique_hashes']['value'];
        }

        return $result;
    }
</code>```

Body:
I have this complex query for MySQL which counts unique visits for each day. I want to make it faster using ElasticSearch.

Imagine a table like this:

id | site_id | created_at ________ | stat_cookie_hash

10 | 12346 | 2019-11-11 15:42:24 | sf2f2eghasdh2nvr

11 | 12346 | 2019-10-26 09:41:09 | jk67j97jkhjghklj

12 | 12346 | 2019-10-26 14:25:01 | vnuoi96iyoui60yu

13 | 12346 | 2019-09-01 18:12:54 | zxcqscgscv1vcdcv

Result of the query would be like:

2019-11-11 | 1

2019-10-26 | 2

2019-09-01 | 1

The SQL query itself:

    SELECT day, COUNT(*) as cnt
    FROM (SELECT DISTINCT stat_cookie_hash, DATE(DATE_ADD(created_at, INTERVAL :timezone MINUTE)) as day
        FROM stat_visitor
        WHERE site_id=:site_id) AS T
    GROUP BY day
    ORDER BY day DESC

:timezone is an integer like 180

:site_id is an integer like 40

The same one but with substitution:

    SELECT day, COUNT(*) as cnt
    FROM (SELECT DISTINCT stat_cookie_hash, DATE(DATE_ADD(created_at, INTERVAL 180 MINUTE)) as day
        FROM stat_visitor
        WHERE site_id=40) AS T
    GROUP BY day
    ORDER BY day DESC

ElasticSearch version:

{
    "version" : {
        "number" : "7.4.1",
        "build_flavor" : "default",
        "build_type" : "rpm",
        "build_hash" : "fc0eeb6e2c25915d63d871d344e3d0b45ea0ea1e",
        "build_date" : "2019-10-22T17:16:35.176724Z",
        "build_snapshot" : false,
        "lucene_version" : "8.2.0",
        "minimum_wire_compatibility_version" : "6.8.0",
        "minimum_index_compatibility_version" : "6.0.0-beta1"
      }
}

I'm completely new to ElasticSearch, so I don't know how to manage it. Help me, please!

It would be great if you know Yii2 Framework and could show me how to rewrite the SQL query with yii2-elasticsearch extension.

Body:
I've found a soultion.

First of all, I removed timezone and DATE, DATE_ADD functions from the query.

Then I converted it to ElasticSearch format. It's integrated PHP version:

    public static function elasticSearch($site_id, $page_id=null, $markup_id=null, $started_at=null, $group_by='created_day')
    {
        $index = 'stat_visitor';

        $client = ClientBuilder::create()
            ->setSelector('\Elasticsearch\ConnectionPool\Selectors\RoundRobinSelector')
            ->build();

        $params = [
            'index' => $index,
            'size' => 0,
            'body' => [
                'aggs' => [
                    'cnt' => [
                        'terms' => [
                            'field' => $group_by,
                            'size' => 9999,
                            'order' => ['_term' => 'desc'],
                        ],
                        'aggs' => [
                            'unique_hashes' => [
                                'cardinality' => [
                                    'field' => 'stat_cookie_hash'
                                ]
                            ]
                        ]
                    ]
                ],
                'query' => [
                    'bool' => [
                        'must' => [
                            ['term' => ['site_id' => $site_id]],
                        ],
                    ],
                ],
                'sort' => ['created_day' => 'desc'],
            ]
        ];

        if ($page_id) {
            $params['body']['query']['bool']['must'][] = ['term' => ['page_id' => $page_id]];
        }

        if ($markup_id) {
            $params['body']['query']['bool']['must'][] = ['term' => ['markup_id' => $markup_id]];
        }

        if ($started_at) {
            $params['body']['query']['bool']['filter'][] = ['range' => ['created_at' => [ 'gte' => $started_at]]];
        }

        $response = $client->search($params);

        $result = [];
        foreach ($response['aggregations']['cnt']['buckets'] as $bucket) {
            $result[$bucket['key_as_string']] = $bucket['unique_hashes']['value'];
        }

        return $result;
    }


问:
How to slice a list from an element n to the end in python?
I'm having some trouble figuring out how to slice python lists, it is illustrated as follows:

```<code>>>> test = range(10)
>>> test
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> test[3:-1]
[3, 4, 5, 6, 7, 8]
>>> test[3:0]
[]
>>> test[3:1]
[]
>>> test
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
</code>```

To my understanding, python slice means lst[start:end], and including start, excluding end. So how would i go about finding the "rest" of a list starting from an element n?

Thanks a lot for all your help!

答:
If you're using a variable as the range endpoint, you can use None.

```<code> start = 4
 end = None
 test[start:end]
</code>```

OwnerDisplayName: FurtiveFelon

ContentLicense: CC BY-SA 2.5

Body:
I'm having some trouble figuring out how to slice python lists, it is illustrated as follows:

>>> test = range(10)
>>> test
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> test[3:-1]
[3, 4, 5, 6, 7, 8]
>>> test[3:0]
[]
>>> test[3:1]
[]
>>> test
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

To my understanding, python slice means lst[start:end], and including start, excluding end. So how would i go about finding the "rest" of a list starting from an element n?

Thanks a lot for all your help!

Body:
If you're using a variable as the range endpoint, you can use None.

 start = 4
 end = None
 test[start:end]

OwnerDisplayName: recursive


问:
jQuery code - IE8 problem
I have this code that changes input fields name attribute value, works great in all major browsers except IE8, IE7 and IE6. For IE the name just stay name="participant_name[{i}]", should be name="participant_name[1]".

```<code>var i = 1;
var input_name = null;
$('.dubl input').each(function () {
   var new_input_name = $(this).attr('name').substring(0, $(this).attr('name').indexOf('['));
   if (input_name !== new_input_name) {
       input_name = new_input_name;
       i = 1;
   }
   $(this).attr('name', input_name + '[' + i + ']');
   i++;
});
</code>```

HTML

```<code><input type="text" name="participant_name[{i}]">
</code>```

答:
It is in fact changing the attribute name correctly in IE as well. However, I think the problem you may be experiencing is that when you submit the form, it isn't the updated field name.

IE doesn't take into account that name change and as such, when the form is sent, it is still using the same name as it was when it was created. To fix this, you can either re-add it to the DOM the form/element when you change the name attribute.

http://jsfiddle.net/niklasvh/wbnhS/ you can test it there, the attribute does change or if you inspect the DOM in IE.

Title: jQuery code - IE8 problem

Body:
I have this code that changes input fields name attribute value, works great in all major browsers except IE8, IE7 and IE6. For IE the name just stay name="participant_name[{i}]", should be name="participant_name[1]".

var i = 1;
var input_name = null;
$('.dubl input').each(function () {
   var new_input_name = $(this).attr('name').substring(0, $(this).attr('name').indexOf('['));
   if (input_name !== new_input_name) {
       input_name = new_input_name;
       i = 1;
   }
   $(this).attr('name', input_name + '[' + i + ']');
   i++;
});

HTML

<input type="text" name="participant_name[{i}]">


问:
memset large memory region allocated by shm_open/ftruncate/mmap crashes with bus error
I have a demo program which uses shm_open/ftruncate/mmap to allocate memory:

```<code>#include <unistd.h>
#include <sys/stat.h>
#include <sys/file.h>
#include <sys/mman.h>
#include <string.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>

void shm_alloc(const char* path, size_t size) {
    int shmfd = shm_open(path, O_CREAT | O_EXCL | O_TRUNC | O_RDWR, 0666);
    if (shmfd == -1) {
        perror("shm_open");
        exit(1);
    }
    printf("shm_open success, path: %s, fd: %d\n", path, shmfd);

    int ret = ftruncate(shmfd, size);
    if (ret != 0) {
        perror("ftruncate");
        exit(1);
    }
    printf("ftruncate success, fd: %d, size: %#lx\n", shmfd, size);

    void* addr = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, shmfd, 0);
    if (addr == MAP_FAILED) {
        perror("mmap");
        exit(1);
    }
    printf("mmap success, fd: %d, size: %#lx, addr: %p\n", shmfd, size, addr);

    close(shmfd);
    memset(addr, 0x00, size); // <===== Crashes here
    printf("memset success, size: %#lx, addr: %p\n", size, addr);
}

int main() {
    shm_alloc("/a", 0x100000000); // 4GB
    shm_alloc("/b", 0x100000000); // 4GB, crashes at the `memset` in this call
    return 0;
}
</code>```

The program creates two 4GB shared memory regions and memset them. Run the program it outputs the following and then crashes:

```<code>shm_open success, path: /a, fd: 3
ftruncate success, fd: 3, size: 0x100000000
mmap success, fd: 3, size: 0x100000000, addr: 0x7f4c15625000
memset success, size: 0x100000000, addr: 0x7f4c15625000
shm_open success, path: /b, fd: 3
ftruncate success, fd: 3, size: 0x100000000
mmap success, fd: 3, size: 0x100000000, addr: 0x7f4b15625000
[1]    1250849 bus error (core dumped)  ./a.out
</code>```

As you see, the first memset succeeds, and the second crashes, I gdbed the program, and it shows the second region mmaped at 0x7f4b15625000 does not have enough space (4GB) (execute p (char*)addr + 0xFFFFFFFF in gdb produces Cannot access memory error), but it do have space smaller than 4GB (might be 2GB or 3GB, I didn't test for the accurate size).

I am running on Debian 9 and the physical memory is 16GB without a swap space, so it seems not to be a no-enough-memory problem, anyone has any idea? Shouldn't I trust the ftruncate/mmap calls?

EDIT: Running df -h shows the size of /dev/shm is 7.8G, so it might be the root cause. However, why ftruncate succeeds even there is no enough space in /dev/shm? And why when I ls -alh /dev/shm, it shows two files "a" and "b" both with size 4.0GB?

Output of free -h:

```<code># before running the program:
              total        used        free      shared  buff/cache   available
Mem:            15G        701M        9.0G        161M        5.7G         14G
Swap:            0B          0B          0B

# after running the program:
              total        used        free      shared  buff/cache   available
Mem:            15G        702M        1.4G        7.8G         13G        6.6G
Swap:            0B          0B          0B
</code>```

Output of ulimit -a:

```<code>-t: cpu time (seconds)              unlimited
-f: file size (blocks)              unlimited
-d: data seg size (kbytes)          unlimited
-s: stack size (kbytes)             8192
-c: core file size (blocks)         unlimited
-m: resident set size (kbytes)      unlimited
-u: processes                       65535
-n: file descriptors                1024768
-l: locked-in-memory size (kbytes)  64
-v: address space (kbytes)          unlimited
-x: file locks                      unlimited
-i: pending signals                 63053
-q: bytes in POSIX msg queues       819200
-e: max nice                        0
-r: max rt priority                 0
-N 15:                              unlimited
</code>```

答:
I have reproduced this issue with a 16GB Ubuntu VM which has also 8 GB by default for /dev/shm.

After increasing /dev/shm to 9GB it works:

```<code>$ ./tm
shm_open success, path: /a, fd: 3
ftruncate success, fd: 3, size: 0x100000000
mmap success, fd: 3, size: 0x100000000, addr: 0x7ff849486000
memset success, size: 0x100000000, addr: 0x7ff849486000
shm_open success, path: /b, fd: 3
ftruncate success, fd: 3, size: 0x100000000
mmap success, fd: 3, size: 0x100000000, addr: 0x7ff749486000
memset success, size: 0x100000000, addr: 0x7ff749486000
$ df /dev/shm -h
Filesystem      Size  Used Avail Use% Mounted on
tmpfs           9.0G  8.1G  1.0G  89% /dev/shm
$
</code>```

I cannot answer questions about ftruncate and file size in /dev/shm but it works.

Body:
I have a demo program which uses shm_open/ftruncate/mmap to allocate memory:

#include <unistd.h>
#include <sys/stat.h>
#include <sys/file.h>
#include <sys/mman.h>
#include <string.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>

void shm_alloc(const char* path, size_t size) {
    int shmfd = shm_open(path, O_CREAT | O_EXCL | O_TRUNC | O_RDWR, 0666);
    if (shmfd == -1) {
        perror("shm_open");
        exit(1);
    }
    printf("shm_open success, path: %s, fd: %d\n", path, shmfd);

    int ret = ftruncate(shmfd, size);
    if (ret != 0) {
        perror("ftruncate");
        exit(1);
    }
    printf("ftruncate success, fd: %d, size: %#lx\n", shmfd, size);

    void* addr = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, shmfd, 0);
    if (addr == MAP_FAILED) {
        perror("mmap");
        exit(1);
    }
    printf("mmap success, fd: %d, size: %#lx, addr: %p\n", shmfd, size, addr);

    close(shmfd);
    memset(addr, 0x00, size); // <===== Crashes here
    printf("memset success, size: %#lx, addr: %p\n", size, addr);
}

int main() {
    shm_alloc("/a", 0x100000000); // 4GB
    shm_alloc("/b", 0x100000000); // 4GB, crashes at the `memset` in this call
    return 0;
}

The program creates two 4GB shared memory regions and memset them. Run the program it outputs the following and then crashes:

shm_open success, path: /a, fd: 3
ftruncate success, fd: 3, size: 0x100000000
mmap success, fd: 3, size: 0x100000000, addr: 0x7f4c15625000
memset success, size: 0x100000000, addr: 0x7f4c15625000
shm_open success, path: /b, fd: 3
ftruncate success, fd: 3, size: 0x100000000
mmap success, fd: 3, size: 0x100000000, addr: 0x7f4b15625000
[1]    1250849 bus error (core dumped)  ./a.out

As you see, the first memset succeeds, and the second crashes, I gdbed the program, and it shows the second region mmaped at 0x7f4b15625000 does not have enough space (4GB) (execute p (char*)addr + 0xFFFFFFFF in gdb produces Cannot access memory error), but it do have space smaller than 4GB (might be 2GB or 3GB, I didn't test for the accurate size).

I am running on Debian 9 and the physical memory is 16GB without a swap space, so it seems not to be a no-enough-memory problem, anyone has any idea? Shouldn't I trust the ftruncate/mmap calls?

EDIT: Running df -h shows the size of /dev/shm is 7.8G, so it might be the root cause. However, why ftruncate succeeds even there is no enough space in /dev/shm? And why when I ls -alh /dev/shm, it shows two files "a" and "b" both with size 4.0GB?

Output of free -h:

# before running the program:
              total        used        free      shared  buff/cache   available
Mem:            15G        701M        9.0G        161M        5.7G         14G
Swap:            0B          0B          0B

# after running the program:
              total        used        free      shared  buff/cache   available
Mem:            15G        702M        1.4G        7.8G         13G        6.6G
Swap:            0B          0B          0B

Output of ulimit -a:

-t: cpu time (seconds)              unlimited
-f: file size (blocks)              unlimited
-d: data seg size (kbytes)          unlimited
-s: stack size (kbytes)             8192
-c: core file size (blocks)         unlimited
-m: resident set size (kbytes)      unlimited
-u: processes                       65535
-n: file descriptors                1024768
-l: locked-in-memory size (kbytes)  64
-v: address space (kbytes)          unlimited
-x: file locks                      unlimited
-i: pending signals                 63053
-q: bytes in POSIX msg queues       819200
-e: max nice                        0
-r: max rt priority                 0
-N 15:                              unlimited

Body:
I have reproduced this issue with a 16GB Ubuntu VM which has also 8 GB by default for /dev/shm.

After increasing /dev/shm to 9GB it works:

$ ./tm
shm_open success, path: /a, fd: 3
ftruncate success, fd: 3, size: 0x100000000
mmap success, fd: 3, size: 0x100000000, addr: 0x7ff849486000
memset success, size: 0x100000000, addr: 0x7ff849486000
shm_open success, path: /b, fd: 3
ftruncate success, fd: 3, size: 0x100000000
mmap success, fd: 3, size: 0x100000000, addr: 0x7ff749486000
memset success, size: 0x100000000, addr: 0x7ff749486000
$ df /dev/shm -h
Filesystem      Size  Used Avail Use% Mounted on
tmpfs           9.0G  8.1G  1.0G  89% /dev/shm
$

I cannot answer questions about ftruncate and file size in /dev/shm but it works.


问:
How can I send a web request to the b2clogin domain from my own custom domain?
I am attempting to make a web request to an Azure App Service (Azure Function) which is secured with Azure Active Directory Authentication (B2C Application Registration details used). The web request is being made from a web application (Portal) via simple JavaScript calls (I do not have access to the portals source code.

The web application (Portal) and Azure App Service (Azure Function) are secured using Azure B2C and require users to login with their Azure AD B2C accounts. This is working fine.

Requests made to the Azure Function from the Portal surface the following error in the browser console:

```<code>Access to XMLHttpRequest at 'https://XXX.b2clogin.com/XXX.onmicrosoft.com/b2c_1_signupsignin/oauth2/v2.0/authorize?...' (redirected from 'https://YYY.azurewebsites.net/api/MyMethod') from origin 'https://ZZZ.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
</code>```

The same web request made made in a new browser tab successfully shows the secured resource (assuming an active B2C session exists in the browser).

I have spent a significant amount of time reading through the Azure B2C documentation, making multiple requests for tokens etc, all to no resolve.

I believe the harsh truth of the matter is outlined in this answer here, but how can this be architected differently to circumvent this pitfall?

Currently the .b2clogin.com domain doesn't allow any cross-origin requests from any other domain.

While this appears true based on the CORS issues being surfaced here, how can I send a web request from my Portal domain (XXX.com), to my Azure Function (YYY.azurewebsites.net), which are both secured using my B2C tenant/application registration.

EDIT: I am aware (based on the error I am receiving above) that the Azure Function is redirecting to the to the B2C login page when the initial call is made form the Portal to the Azure Function.

I am including my current setup below - previously I have only secured App Services using Azure AD authentication and access by obtaining bearer tokens. Not possible in this scenario as I do not have access to the Portal code for secure storage of private keys/secrets - I am dependent on the SSO experience - calls must be made in JavaScript.

App Service - Authentication (Azure Function)

Log in with Azure Active Directory

Client ID: Azure AD B2C application registraion ID

Issuer Url: Taken from my Signin/Signup user flow

Azure AD B2C Tenant - App Registration

Include web app / web API: Yes

Allow implicit flow: Yes

Client side code calling Azure Function

```<code>$.ajax({
      type: 'POST',
      url: "https://YYY.azurewebsites.net/api/MyMethod",
      success: function(response) {
        console.log(response);
      },
      error: function(request, status, error) {
        console.log(request.responseText);
      },
    });
</code>```

Some guidance on this would be greatly appreaciated.

答:
The solution to my scenario was to make use of single sign-on with MSAL.js using impicit flow (which is taken care of by the MSAL).

Specifically, SSO without MSAL.js login, whereby I do not have to log in again to access the Azure Function, as the user would have already been logged in via the Portal and have an active Azure AD B2C session.

Instead, I call the acquireTokenSilent method, passing in the required parameters to obtain a Bearer access token that can be used to access my secured Azure Function.

A working example of this scenario (SPA calling an Azure App Service), can be found here in Microsofts GitHub repo. My setup was complete in so far as I only had to configure the sample with my tenant/app specific details.

Body:
I am attempting to make a web request to an Azure App Service (Azure Function) which is secured with Azure Active Directory Authentication (B2C Application Registration details used). The web request is being made from a web application (Portal) via simple JavaScript calls (I do not have access to the portals source code.

The web application (Portal) and Azure App Service (Azure Function) are secured using Azure B2C and require users to login with their Azure AD B2C accounts. This is working fine.

Requests made to the Azure Function from the Portal surface the following error in the browser console:

Access to XMLHttpRequest at 'https://XXX.b2clogin.com/XXX.onmicrosoft.com/b2c_1_signupsignin/oauth2/v2.0/authorize?...' (redirected from 'https://YYY.azurewebsites.net/api/MyMethod') from origin 'https://ZZZ.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

The same web request made made in a new browser tab successfully shows the secured resource (assuming an active B2C session exists in the browser).

I have spent a significant amount of time reading through the Azure B2C documentation, making multiple requests for tokens etc, all to no resolve.

I believe the harsh truth of the matter is outlined in this answer here, but how can this be architected differently to circumvent this pitfall?

Currently the .b2clogin.com domain doesn't allow any cross-origin requests from any other domain.

While this appears true based on the CORS issues being surfaced here, how can I send a web request from my Portal domain (XXX.com), to my Azure Function (YYY.azurewebsites.net), which are both secured using my B2C tenant/application registration.

EDIT: I am aware (based on the error I am receiving above) that the Azure Function is redirecting to the to the B2C login page when the initial call is made form the Portal to the Azure Function.

I am including my current setup below - previously I have only secured App Services using Azure AD authentication and access by obtaining bearer tokens. Not possible in this scenario as I do not have access to the Portal code for secure storage of private keys/secrets - I am dependent on the SSO experience - calls must be made in JavaScript.

App Service - Authentication (Azure Function)

Log in with Azure Active Directory

Client ID: Azure AD B2C application registraion ID

Issuer Url: Taken from my Signin/Signup user flow

Azure AD B2C Tenant - App Registration

Include web app / web API: Yes

Allow implicit flow: Yes

Client side code calling Azure Function

$.ajax({
      type: 'POST',
      url: "https://YYY.azurewebsites.net/api/MyMethod",
      success: function(response) {
        console.log(response);
      },
      error: function(request, status, error) {
        console.log(request.responseText);
      },
    });

Some guidance on this would be greatly appreaciated.


问:
MSAL iOS integration issue
I am installing MSAL pod to integrate AZURE AD into my iOS project.

pod install works fine and it installed MSAL 1.1.2. But when I open my project and trying to build it, it's showing 6 compile time errors.

Use of undeclared identifier 'MSIDSSOExtensionGetAccountsRequest'

All errors are related to above.
Please suggest what's wrong with my project.

I am using Xcode 10.3(due to some project dependencies). MSAL sample project itself is not working on Xcode 10.3 but working on Xcode 11.3
Is there any specific version of MSAL I need to use with Xcode 10.3?

答:
Versions of MSAL for iOS after 1.0.7 require the iOS 13 SDK.

Since you are limited to the iOS 12 SDK, you will need to specify version 1.0.7 in your Podfile.

Title: MSAL iOS integration issue


问:
NHibernate Linq property-ref behavior
NHibernate Linq is producing an unexcepted query. Here are my class mappings:

```<code>public class OrderClassMap : ClassMap<Order> {
    public OrderClassMap() {
        Id(x => x.PersistenceId).Column("RowId").GeneratedBy.Assigned();
        Version(x => x.PersistenceVersion).Column("RowVersion");
        Map(x => x.OrderId).Generated.Insert().Not.Update();
        Map(x => x.OrderDate);
        References(x => x.Overseer).Column("OverseerId").PropertyRef(x => x.OverseerId);
        References(x => x.Overseer2).Column("OverseerId2").PropertyRef(x => x.OverseerId2);
    }
}

public class OverseerClassMap : ClassMap<Overseer> {
    public OverseerClassMap() {
        Id(x => x.PersistenceId).Column("RowId").Generated.Assigned();
        Version(x => x.PersistenceVersion).Column("RowVersion");
        Map(x => x.OverseerId).Generated.Insert().Not.Update();
        Map(x => x.Name);
        Map(x => x.Email);
    }
}
</code>```

Here is the Linq query I have:

```<code>var orders = session.Query<Order>()
                    .Where(o => ((o.Overseer.OverseerId == 1) || (o.Overseer.OverseerId == 2)))
                    .Fetch(o => o.Overseer)
                    .Fetch(o => o.Overseer2);
</code>```

The SQL query that is generated is not what I would expect. Instead of doing a left outer join, it does a cartesian join. Here is a shortened example of the query NHibernate produces:

```<code>SELECT ...
FROM Orders o LEFT OUTER JOIN
     Overseers v1 ON o.OverseerId = v1.OverseerId LEFT OUTER JOIN
     Overseers v2 ON o.OverseerId2 = v1.OverseerId,
     Overseers v3,
     Overseers v4
WHERE o.OverseerId = v3.OverseerId AND
      o.OverseerId2 = v4.OverseerId AND
      (v3.OverseerId = 1 OR v4.OverseerId = 1)
</code>```

The query I expected would be like:

```<code>SELECT ...
FROM Orders o LEFT OUTER JOIN
     Overseers v1 ON o.OverseerId = v1.OverseerId LEFT OUTER JOIN
     Overseers v2 ON o.OverseerId2 = v1.OverseerId
WHERE (v1.OverseerId = 1 OR v2.OverseerId = 1)
</code>```

I think it is doing this because I have a legacy database and am using PropertyRef in my mapping. Is there any way to fix this unexpected behavior? Why does NHibernate behave this way? It doesn't make sense to me because by specifying PropertyRef, I'm saying "Use this key instead of the primary key".

答:
I'm not enirely sure I understand what you are trying to achieve here but it seems to me you got the PropertyRef mappings wrong.

If you want the OverseerId and OverseerId2 in Order to the OvreseerId column in the Overseers table, then your property-ref shold be OverseerId in both cases:

```<code>References(x => x.Overseer).Column("OverseerId").PropertyRef(x => x.OverseerId);
References(x => x.Overseer2).Column("OverseerId2").PropertyRef(x => x.OverseerId);
</code>```

Title: NHibernate Linq property-ref behavior

Body:
NHibernate Linq is producing an unexcepted query. Here are my class mappings:

public class OrderClassMap : ClassMap<Order> {
    public OrderClassMap() {
        Id(x => x.PersistenceId).Column("RowId").GeneratedBy.Assigned();
        Version(x => x.PersistenceVersion).Column("RowVersion");
        Map(x => x.OrderId).Generated.Insert().Not.Update();
        Map(x => x.OrderDate);
        References(x => x.Overseer).Column("OverseerId").PropertyRef(x => x.OverseerId);
        References(x => x.Overseer2).Column("OverseerId2").PropertyRef(x => x.OverseerId2);
    }
}

public class OverseerClassMap : ClassMap<Overseer> {
    public OverseerClassMap() {
        Id(x => x.PersistenceId).Column("RowId").Generated.Assigned();
        Version(x => x.PersistenceVersion).Column("RowVersion");
        Map(x => x.OverseerId).Generated.Insert().Not.Update();
        Map(x => x.Name);
        Map(x => x.Email);
    }
}

Here is the Linq query I have:

var orders = session.Query<Order>()
                    .Where(o => ((o.Overseer.OverseerId == 1) || (o.Overseer.OverseerId == 2)))
                    .Fetch(o => o.Overseer)
                    .Fetch(o => o.Overseer2);

The SQL query that is generated is not what I would expect. Instead of doing a left outer join, it does a cartesian join. Here is a shortened example of the query NHibernate produces:

SELECT ...
FROM Orders o LEFT OUTER JOIN
     Overseers v1 ON o.OverseerId = v1.OverseerId LEFT OUTER JOIN
     Overseers v2 ON o.OverseerId2 = v1.OverseerId,
     Overseers v3,
     Overseers v4
WHERE o.OverseerId = v3.OverseerId AND
      o.OverseerId2 = v4.OverseerId AND
      (v3.OverseerId = 1 OR v4.OverseerId = 1)

The query I expected would be like:

SELECT ...
FROM Orders o LEFT OUTER JOIN
     Overseers v1 ON o.OverseerId = v1.OverseerId LEFT OUTER JOIN
     Overseers v2 ON o.OverseerId2 = v1.OverseerId
WHERE (v1.OverseerId = 1 OR v2.OverseerId = 1)

I think it is doing this because I have a legacy database and am using PropertyRef in my mapping. Is there any way to fix this unexpected behavior? Why does NHibernate behave this way? It doesn't make sense to me because by specifying PropertyRef, I'm saying "Use this key instead of the primary key".

Body:
I'm not enirely sure I understand what you are trying to achieve here but it seems to me you got the PropertyRef mappings wrong.

If you want the OverseerId and OverseerId2 in Order to the OvreseerId column in the Overseers table, then your property-ref shold be OverseerId in both cases:

References(x => x.Overseer).Column("OverseerId").PropertyRef(x => x.OverseerId);
References(x => x.Overseer2).Column("OverseerId2").PropertyRef(x => x.OverseerId);


问:
Adding two numbers through recursion C++
```<code>#include <iostream>

int sum(int a, int b) {
  if (b != 1) {
    sum(a, b - 1);
  }
  a = a + 1;
  return a;
}

int main() {
  int a = sum(10, 12);
  std::cout << a;
}
</code>```

Basically I am adding two numbers through recursion, so I am recursively calling function by decreasing number b and incrementing number a that much times, but result I get is 11.

答: Evalute the return value of the recursivly called function a = sum(a, b - 1);. Additonally, make sure that no value less than 1 is entered as b with this implementation. A call with b=0 will also fail.

Body:
#include <iostream>

int sum(int a, int b) {
  if (b != 1) {
    sum(a, b - 1);
  }
  a = a + 1;
  return a;
}

int main() {
  int a = sum(10, 12);
  std::cout << a;
}

Basically I am adding two numbers through recursion, so I am recursively calling function by decreasing number b and incrementing number a that much times, but result I get is 11.


问:
Regex for Telugu String in Android?
I am able to fetch the following Telugu string from the OCR results. I need to apply regular expressions for that string. Could anyone please help to how to fetch Gender, Name, Address

```<code>customStr = "డివిజన్: షాద్ నగర్\n(గ్రామం: వెలిజర్ల -1\n\n \n  \n \n\n \n\n \n\n||\n\n(|\n\n|||\n\n|||\n\nఖాతానెం.: 783\n\n  \n\n' 1. పట్టాదారు పేరు ఇంటిపేరుతో : చతుర్వేదుల భార్గవి\n., 2. తండ్రి / భర్తపేరు : శ్రీధర కేదార్ నాథ్\n\n౩. స్త్రీ / పురుషుడు : Female\n, 4. చిరునామా : వెలిజర్ల -1\n5. కులము : General\n6. ఆధార్ సంఖ్య : XXXXXXXX8381\n\n7. పట్టాదారు సంతకం ఎడమ /కుడి చేతి వేలిముద్ర\n\nతహశీల్దార్ సంత!\n\n \n\nith CamScanner"
</code>```

I am using the following source code but no result.

```<code>String[] lines = customStr.split("\\r?\\n", -1);

        for(String line : lines) {

                if (customStr.contains("స్త్రీ / పురుషుడు")){
                    text4.setText(line);
                }
                else{
                    System.out.printf("ok");
                }

            }
</code>```

答:
Use Regex with Pattern and Matcher to fetch Gender, Name and Address.
Refer the below example:</p>

```<code>    Pattern genderPattern = Pattern.compile("౩. స్త్రీ / పురుషుడు : (.*?)\n,");
    Pattern addressPattern = Pattern.compile("4. చిరునామా : (.*?)\n5.");
    Pattern namePattern  = Pattern.compile("1. పట్టాదారు పేరు ఇంటిపేరుతో : (.*?)\n.,");
    Matcher m;
    m=genderPattern.matcher(customStr);
    if(m.find())
        gender = m.group(1));
    m=addressPattern.matcher(customStr);
    if(m.find())
        address = m.group(1));
    m=namePattern.matcher(customStr);
    if(m.find())
        name = m.group(1));
</code>```

Title: Regex for Telugu String in Android?

Body:
I am able to fetch the following Telugu string from the OCR results. I need to apply regular expressions for that string. Could anyone please help to how to fetch Gender, Name, Address

customStr = "డివిజన్: షాద్ నగర్\n(గ్రామం: వెలిజర్ల -1\n\n \n  \n \n\n \n\n \n\n||\n\n(|\n\n|||\n\n|||\n\nఖాతానెం.: 783\n\n  \n\n' 1. పట్టాదారు పేరు ఇంటిపేరుతో : చతుర్వేదుల భార్గవి\n., 2. తండ్రి / భర్తపేరు : శ్రీధర కేదార్ నాథ్\n\n౩. స్త్రీ / పురుషుడు : Female\n, 4. చిరునామా : వెలిజర్ల -1\n5. కులము : General\n6. ఆధార్ సంఖ్య : XXXXXXXX8381\n\n7. పట్టాదారు సంతకం ఎడమ /కుడి చేతి వేలిముద్ర\n\nతహశీల్దార్ సంత!\n\n \n\nith CamScanner"

I am using the following source code but no result.

String[] lines = customStr.split("\\r?\\n", -1);

        for(String line : lines) {

                if (customStr.contains("స్త్రీ / పురుషుడు")){
                    text4.setText(line);
                }
                else{
                    System.out.printf("ok");
                }

            }

Body:
Use Regex with Pattern and Matcher to fetch Gender, Name and Address.
Refer the below example:

    Pattern genderPattern = Pattern.compile("౩. స్త్రీ / పురుషుడు : (.*?)\n,");
    Pattern addressPattern = Pattern.compile("4. చిరునామా : (.*?)\n5.");
    Pattern namePattern  = Pattern.compile("1. పట్టాదారు పేరు ఇంటిపేరుతో : (.*?)\n.,");
    Matcher m;
    m=genderPattern.matcher(customStr);
    if(m.find())
        gender = m.group(1));
    m=addressPattern.matcher(customStr);
    if(m.find())
        address = m.group(1));
    m=namePattern.matcher(customStr);
    if(m.find())
        name = m.group(1));


问:
Get some elements by jquery
I have some html elements, like that:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

```
</div>
</div>
</p>

<p>How to get these items. Result should be like that:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>[
{start:1,end:4},
{start:7,end:10},
{start:14,end:18},
]</code>```

So i need get only first and last elements between elements with class

答:
Using map() and nextUntil()

const res = $('li:not(".choosed"):first-child, li.choosed + li:not(".choosed")').map(function() {
  let start = +$(this).text()
  let end = +$(this).nextUntil('.choosed').last().text()
  return { start, end }
}).get()

console.log(res)```
<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>
<ul>
  <li>1</li>
  <!-- Needed -->
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <!-- Needed -->
  <li class="choosed">5</li>
  <li class="choosed">6</li>
  <li>7</li>
  <!-- Needed -->
  <li>8</li>
  <li>9</li>
  <li>10</li>
  <!-- Needed -->
  <li class="choosed">11</li>
  <li class="choosed">12</li>
  <li class="choosed">13</li>
  <li>14</li>
  <!-- Needed -->
  <li>15</li>
  <li>16</li>
  <li>17</li>
  <li>18</li>
  <!-- Needed -->
</ul></code>```

Title: Get some elements by jquery

Body:
I have some html elements, like that:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

How to get these items. Result should be like that:

[
{start:1,end:4},
{start:7,end:10},
{start:14,end:18},
]

So i need get only first and last elements between elements with class

Body:
Using map() and nextUntil()

const res = $('li:not(".choosed"):first-child, li.choosed + li:not(".choosed")').map(function() {
  let start = +$(this).text()
  let end = +$(this).nextUntil('.choosed').last().text()
  return { start, end }
}).get()

console.log(res)

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <li>1</li>
  <!-- Needed -->
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <!-- Needed -->
  <li class="choosed">5</li>
  <li class="choosed">6</li>
  <li>7</li>
  <!-- Needed -->
  <li>8</li>
  <li>9</li>
  <li>10</li>
  <!-- Needed -->
  <li class="choosed">11</li>
  <li class="choosed">12</li>
  <li class="choosed">13</li>
  <li>14</li>
  <!-- Needed -->
  <li>15</li>
  <li>16</li>
  <li>17</li>
  <li>18</li>
  <!-- Needed -->
</ul>


问:
How to insert values into an SQL view which has columns from multiple tables?
I have an SQL view created by joining columns of two separate tables.

I need to know how to insert a record into this view.

Here's the code I tried,

```<code>create view P_Order
as
select Product.Pname, Product.Pdesc, Product.Pprice, Order1.Onumber, Order1.Oqty
from Product
join Order1
on Order1.Procode=Product.Pcode;

select * from P_Order;

insert into P_Order (Pname, Pdesc, Pprice, Onumber, Oqty) values('Toshiba','Television',48000.00,10023,25);
</code>```

It generated an error saying,

```<code>View or function 'P_Order' is not updatable because the modification affects multiple base tables.
</code>```

How can I fix this?

答:
Inserting Records into a VIEW with two table in Join Condition in not advisable it leads to multiple changes in the both tables.

So Instead of inserting them into the View, you can insert the records into separate tables.

Body:
I have an SQL view created by joining columns of two separate tables.

I need to know how to insert a record into this view.

Here's the code I tried,

create view P_Order
as
select Product.Pname, Product.Pdesc, Product.Pprice, Order1.Onumber, Order1.Oqty
from Product
join Order1
on Order1.Procode=Product.Pcode;

select * from P_Order;

insert into P_Order (Pname, Pdesc, Pprice, Onumber, Oqty) values('Toshiba','Television',48000.00,10023,25);

It generated an error saying,

View or function 'P_Order' is not updatable because the modification affects multiple base tables.

How can I fix this?


问:
Loop over NxN grid cells based of proximity to a certain cell
I have a N by N grid. I have a certain grid cell labeled with 0:

I intend to loop over grid cells, starting with 0 cell, in this order:

Start with cell labeled 0

Next cells are labeled 1

Next cells are labeled 2

...

Until the grid boundary is reached

How can I compose the loop?

I tried to follow this post. But I cannot adapt it to suit my situation.

答:
You can fill the entire grid using a Breadth First Search: Starting with the cell with value zero, it will expand in concentric waves, adding one to each subsequent layer further away from the center.

Here is an example in Python3

```<code>from collections import deque
from typing import List, Tuple

class Grid:
    """represents a grid of cells indexed like a matrix:
    rows first, then columns
    rows, cols, r, c, row, col, cr, cc are ints
    rowcol = tuple of ints
    """
    eight_offsets = [(1, 1), (1, 0), (1, -1), (0, 1), (0, -1), (-1, 1), (-1, 0), (-1, -1)]

    def __init__(self, rows: int, cols: int):
        self.rows = rows
        self.cols = cols
        self.cells = [[None for col in range(cols)] for row in range(rows)]

    def fill_grid_BFS(self, rowcol: Tuple[int, int]) -> None:
        """fills each cell with its distance from the cell at rowcol which is zero
        """
        row, col = rowcol
        self.cells[row][col] = 0
        queue = deque([rowcol])
        visited = set()
        while queue:
            current = queue.popleft()
            cr, cc = current
            rank = self.cells[cr][cc] + 1
            visited.add(current)
            for neigh in self.get_eight_neighbors(current):
                if neigh in visited:
                    continue
                r, c = neigh
                self.cells[r][c] = rank
                queue.append(neigh)
        print(self)

    def get_eight_neighbors(self, rowcol: Tuple[int, int]) -> List[Tuple[int, int]]:
        """returns the valid Moore's neighbors that have not been assigned a value yet
        """
        row, col = rowcol
        neighbors = []
        for dr, dc in Grid.eight_offsets:
            r, c = row + dr, col + dc
            try:
                if self.cells[r][c] is None:
                    neighbors.append((r, c))
            except IndexError:
                pass
        return neighbors

    def __str__(self) -> str:
        res = []
        for row in self.cells:
            res.append(' '.join(str(elt) for elt in row))
            res.append('\n')
        return ''.join(res)

g = Grid(8, 8)
g.fill_grid_BFS((5, 5))
</code>```

output:

```<code>5 5 5 5 5 5 5 5
5 4 4 4 4 4 4 4
5 4 3 3 3 3 3 3
5 4 3 2 2 2 2 2
5 4 3 2 1 1 1 2
5 4 3 2 1 0 1 2
5 4 3 2 1 1 1 2
5 4 3 2 2 2 2 2
</code>```

Body:
You can fill the entire grid using a Breadth First Search: Starting with the cell with value zero, it will expand in concentric waves, adding one to each subsequent layer further away from the center.

Here is an example in Python3

from collections import deque
from typing import List, Tuple

class Grid:
    """represents a grid of cells indexed like a matrix:
    rows first, then columns
    rows, cols, r, c, row, col, cr, cc are ints
    rowcol = tuple of ints
    """
    eight_offsets = [(1, 1), (1, 0), (1, -1), (0, 1), (0, -1), (-1, 1), (-1, 0), (-1, -1)]

    def __init__(self, rows: int, cols: int):
        self.rows = rows
        self.cols = cols
        self.cells = [[None for col in range(cols)] for row in range(rows)]

    def fill_grid_BFS(self, rowcol: Tuple[int, int]) -> None:
        """fills each cell with its distance from the cell at rowcol which is zero
        """
        row, col = rowcol
        self.cells[row][col] = 0
        queue = deque([rowcol])
        visited = set()
        while queue:
            current = queue.popleft()
            cr, cc = current
            rank = self.cells[cr][cc] + 1
            visited.add(current)
            for neigh in self.get_eight_neighbors(current):
                if neigh in visited:
                    continue
                r, c = neigh
                self.cells[r][c] = rank
                queue.append(neigh)
        print(self)

    def get_eight_neighbors(self, rowcol: Tuple[int, int]) -> List[Tuple[int, int]]:
        """returns the valid Moore's neighbors that have not been assigned a value yet
        """
        row, col = rowcol
        neighbors = []
        for dr, dc in Grid.eight_offsets:
            r, c = row + dr, col + dc
            try:
                if self.cells[r][c] is None:
                    neighbors.append((r, c))
            except IndexError:
                pass
        return neighbors

    def __str__(self) -> str:
        res = []
        for row in self.cells:
            res.append(' '.join(str(elt) for elt in row))
            res.append('\n')
        return ''.join(res)

g = Grid(8, 8)
g.fill_grid_BFS((5, 5))

output:

5 5 5 5 5 5 5 5
5 4 4 4 4 4 4 4
5 4 3 3 3 3 3 3
5 4 3 2 2 2 2 2
5 4 3 2 1 1 1 2
5 4 3 2 1 0 1 2
5 4 3 2 1 1 1 2
5 4 3 2 2 2 2 2


问:
Qt designer how to set style?
I made an application in Qt designer and I can also preview it in "fusion" style.

How can I make it always look like in the "fusion" style? I mean like set it as the standard design. (I'm using Python)

答:
set the style to the app</p>

```<code>....
app = QApplication([])
app.setStyle('Fusion')
</code>```

Title: Qt designer how to set style?

Body:
set the style to the app

....
app = QApplication([])
app.setStyle('Fusion')


问:
How-to parse XML key:value pair
I have a clients server returning the following (strange) XML response; how do I access each key:value pair?

```<code>$xml = '<?xml version="1.0"?>
  <response>
    <string key="__status">success</string>
    <string key="id">1000</string>
    <string key="mask">9999</string>
</response>';
</code>```

I was hoping that the following would work, but it appears not.

```<code>$test = new SimpleXMLElement($xml);
echo "Mask: " . $xml->response->mask; // Mask: 9999
</code>```

答:
If you want a specific element, you can use XPath:

```<code>$matches = $test->xpath('//string[@key="mask"]');
</code>```

(this requires PHP 5.2)

This would give you:

```<code>Array
(
    [0] => SimpleXMLElement Object
        (
            [@attributes] => Array
                (
                    [key] => mask
                )

            [0] => 9999
        )
)
</code>```

If you want all elements, you have to iterate over all string elements and access their text and key attribute:

```<code>$items = array();

foreach($test->string as $item) {
    $items[(string) $item->attributes()->key] = (string) $item;
}
</code>```

gives:

```<code>Array
(
    [__status] => success
    [id] => 1000
    [mask] => 9999
)
</code>```

Title: How-to parse XML key:value pair

Body:
I have a clients server returning the following (strange) XML response; how do I access each key:value pair?

$xml = '<?xml version="1.0"?>
  <response>
    <string key="__status">success</string>
    <string key="id">1000</string>
    <string key="mask">9999</string>
</response>';

I was hoping that the following would work, but it appears not.

$test = new SimpleXMLElement($xml);
echo "Mask: " . $xml->response->mask; // Mask: 9999

Body:
If you want a specific element, you can use XPath:

$matches = $test->xpath('//string[@key="mask"]');

(this requires PHP 5.2)

This would give you:

Array
(
    [0] => SimpleXMLElement Object
        (
            [@attributes] => Array
                (
                    [key] => mask
                )

            [0] => 9999
        )
)

If you want all elements, you have to iterate over all string elements and access their text and key attribute:

$items = array();

foreach($test->string as $item) {
    $items[(string) $item->attributes()->key] = (string) $item;
}

gives:

Array
(
    [__status] => success
    [id] => 1000
    [mask] => 9999
)


问:
Decimal values in QProgressBar
I have a QProgressBar to display a realtime reading of a sensor. The sensor can take values from 0 to 2. How do I enable the QProgressBar to display all the decimal values from 0 - 2.

I tried this:

```<code> ui->progressBar->setRange(0, 2);
</code>```

but this just show integer values (display when the value crosses 1)

答:
I guess the sensor gives you decimal values.
Since the QProgressBar uses integer values you will have to scale the values you receive from the sensor.

For example using a factor of 100:

```<code>ui->progressBar->setRange(0, <maxSensorValue> * 100);

ui->progressBar->setValue(  <receivedSensorValue> * 100 );
</code>```

Title: Decimal values in QProgressBar

Body:
I have a QProgressBar to display a realtime reading of a sensor. The sensor can take values from 0 to 2. How do I enable the QProgressBar to display all the decimal values from 0 - 2.

I tried this:

 ui->progressBar->setRange(0, 2);

but this just show integer values (display when the value crosses 1)

Body:
I guess the sensor gives you decimal values.
Since the QProgressBar uses integer values you will have to scale the values you receive from the sensor.

For example using a factor of 100:

ui->progressBar->setRange(0, <maxSensorValue> * 100);

ui->progressBar->setValue(  <receivedSensorValue> * 100 );


问:
Drop down list values from Database (PHP/SQL)
Im just wondering wether the code below is the most efficient for populating a drop down list with information from the Database in php/sql.</p>

```<code>                //GET ALL SONGS FROM DATABASE
                $query = $dbConn->query("SELECT track_id, track_title FROM track");

                echo '<select class="feild" name="songDrop">';//MAKE THE DROPDOWN

                echo '<option value="none">Choose the Song to add</option>';

                // Loop through the query results, displaying the options one by one
                while ($row = $query->fetch_assoc()) {
                     echo '<option value="'.$row['track_id'].'">'.$row['track_title'].'</option>';
                }

                echo '</select>';
</code>```

答:
try this :</p>

```<code>                //GET ALL SONGS FROM DATABASE
            $query = $dbConn->query("SELECT track_id, track_title FROM track");

            echo '<select class="feild" name="songDrop">';//MAKE THE DROPDOWN

            echo '<option value="none">Choose the Song to add</option>';

            // Loop through the query results, displaying the options one by one
            while ($row = mysqli_fetch_array($query)) {
                 echo '<option value="'.$row['track_id'].'">'.$row['track_title'].'</option>';
            }

            echo '</select>';
</code>```

Body:
Im just wondering wether the code below is the most efficient for populating a drop down list with information from the Database in php/sql.

                //GET ALL SONGS FROM DATABASE
                $query = $dbConn->query("SELECT track_id, track_title FROM track");

                echo '<select class="feild" name="songDrop">';//MAKE THE DROPDOWN

                echo '<option value="none">Choose the Song to add</option>';

                // Loop through the query results, displaying the options one by one
                while ($row = $query->fetch_assoc()) {
                     echo '<option value="'.$row['track_id'].'">'.$row['track_title'].'</option>';
                }

                echo '</select>';

Body:
try this :

                //GET ALL SONGS FROM DATABASE
            $query = $dbConn->query("SELECT track_id, track_title FROM track");

            echo '<select class="feild" name="songDrop">';//MAKE THE DROPDOWN

            echo '<option value="none">Choose the Song to add</option>';

            // Loop through the query results, displaying the options one by one
            while ($row = mysqli_fetch_array($query)) {
                 echo '<option value="'.$row['track_id'].'">'.$row['track_title'].'</option>';
            }

            echo '</select>';


问:
How to diff different files in two different directories and store the different files in a new directory
I have two directories, dir1 and dir2 with m and n files in them, respectively. the condition may be either m>n or m

I want to diff the files in both the directories and want to store the diffed files in a new directory, diffdir.

So the diffdir should have only files that differs in both the dir.

I used

```<code>diff -r dir1 dir2 |  grep dir2
</code>```

It gives me the files that are different in both the directories

```<code>diff -r dir1/DISP.case_sc.in.XXX dir2/**DISP.case_sc.in.XXX**
</code>```

where XXX may varies from 001 to 999 (I have manually added ** here to make the name bold).
I need only files (bold one) in diffdir

as  number of files in both the directories are not same so in case of m>n it also gives  as the output of above command (diff -r dir1 dir2 |  grep dir2)

```<code>Only in dir2: DISP.case_sc.in.YYY
</code>```

I also want these DISP.case_sc.in.YYY  files in diffdir. Here YYY are the number of files that are equal to the difference m-n. Example if m=020 and n=010 so this YYY will vary from 011 to 020.

In both the dirs (1&2) some files will be exactly same that are not printed with the diff command, I need those files in a another directory name nodiffdir.

Sample input with files named to indicate their relationship to each other:

```<code>dir1
    dir1_only
    comm_diff
    comm_same

dir2
    dir2_only
    comm_diff
    comm_same
</code>```

Expected output (dir1 and dir2 left unchanged):

```<code>samedir
    comm_same   # copied as-is from dir1 or dir2

diffdir
    comm_diff   # output of "diff dir1/comm_diff dir2/comm_diff"
    dir1_only   # copied as-is from dir1
    dir2_only   # copied as-is from dir2
</code>```

答:
```<code>$ cat tst.sh
#!/usr/bin/env bash

mkdir -p samedir &&
cp -r dir1 diffdir &&
cp dir2/* diffdir &&
for f1 in dir1/*; do
    fname="${f1##*/}"
    f2="dir2/${fname}"
    if [ -f "$f2" ]; then
        if diff -- "$f1" "$f2" > "diffdir/${fname}"; then
            cp -- "$f1" samedir &&
            rm "diffdir/${fname}"
        fi
    fi
done
</code>```

.

```<code>$ mkdir dir1
$ mkdir dir2
$ echo 'a' > dir1/dir1_only
$ echo 'a' > dir2/dir2_only
$ echo 'b' > dir1/comm_same
$ echo 'b' > dir2/comm_same
$ echo 'c' > dir1/comm_diff
$ echo 'd' > dir2/comm_diff
</code>```

.

```<code>$ ls *
tst.sh

dir1:
comm_diff   comm_same   dir1_only

dir2:
comm_diff   comm_same   dir2_only
</code>```

.

```<code>$ ./tst.sh
</code>```

.

```<code>$ ls *
tst.sh

diffdir:
comm_diff   dir1_only   dir2_only

dir1:
comm_diff   comm_same   dir1_only

dir2:
comm_diff   comm_same   dir2_only

samedir:
comm_same
</code>```

.

```<code>$ awk 'FNR==1{print ORS FILENAME} 1' samedir/* diffdir/*

samedir/comm_same
b

diffdir/comm_diff
1c1
< c
---
> d

diffdir/dir1_only
a

diffdir/dir2_only
a
</code>```

Body:
I have two directories, dir1 and dir2 with m and n files in them, respectively. the condition may be either m>n or m

I want to diff the files in both the directories and want to store the diffed files in a new directory, diffdir.

So the diffdir should have only files that differs in both the dir.

I used

diff -r dir1 dir2 |  grep dir2

It gives me the files that are different in both the directories

diff -r dir1/DISP.case_sc.in.XXX dir2/**DISP.case_sc.in.XXX**

where XXX may varies from 001 to 999 (I have manually added ** here to make the name bold).
I need only files (bold one) in diffdir

as  number of files in both the directories are not same so in case of m>n it also gives  as the output of above command (diff -r dir1 dir2 |  grep dir2)

Only in dir2: DISP.case_sc.in.YYY

I also want these DISP.case_sc.in.YYY  files in diffdir. Here YYY are the number of files that are equal to the difference m-n. Example if m=020 and n=010 so this YYY will vary from 011 to 020.

In both the dirs (1&2) some files will be exactly same that are not printed with the diff command, I need those files in a another directory name nodiffdir.

Sample input with files named to indicate their relationship to each other:

dir1
    dir1_only
    comm_diff
    comm_same

dir2
    dir2_only
    comm_diff
    comm_same

Expected output (dir1 and dir2 left unchanged):

samedir
    comm_same   # copied as-is from dir1 or dir2

diffdir
    comm_diff   # output of "diff dir1/comm_diff dir2/comm_diff"
    dir1_only   # copied as-is from dir1
    dir2_only   # copied as-is from dir2

Body:
$ cat tst.sh
#!/usr/bin/env bash

mkdir -p samedir &&
cp -r dir1 diffdir &&
cp dir2/* diffdir &&
for f1 in dir1/*; do
    fname="${f1##*/}"
    f2="dir2/${fname}"
    if [ -f "$f2" ]; then
        if diff -- "$f1" "$f2" > "diffdir/${fname}"; then
            cp -- "$f1" samedir &&
            rm "diffdir/${fname}"
        fi
    fi
done

.

$ mkdir dir1
$ mkdir dir2
$ echo 'a' > dir1/dir1_only
$ echo 'a' > dir2/dir2_only
$ echo 'b' > dir1/comm_same
$ echo 'b' > dir2/comm_same
$ echo 'c' > dir1/comm_diff
$ echo 'd' > dir2/comm_diff

.

$ ls *
tst.sh

dir1:
comm_diff   comm_same   dir1_only

dir2:
comm_diff   comm_same   dir2_only

.

$ ./tst.sh

.

$ ls *
tst.sh

diffdir:
comm_diff   dir1_only   dir2_only

dir1:
comm_diff   comm_same   dir1_only

dir2:
comm_diff   comm_same   dir2_only

samedir:
comm_same

.

$ awk 'FNR==1{print ORS FILENAME} 1' samedir/* diffdir/*

samedir/comm_same
b

diffdir/comm_diff
1c1
< c
---
> d

diffdir/dir1_only
a

diffdir/dir2_only
a


问:
IPython %timeit what is loop and iteration in the options?
I am wondering about the %timeit command in IPython

From the docs:

```<code>%timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] setup_code
</code>```

Options:

-n: execute the given statement  times in a loop. If this value is not given, a fitting value is chosen.

-r: repeat the loop iteration  times and take the best result. Default: 3

For example, if I write:

```<code>%timeit -n 250 -r 2 [i+1 for i in range(5000)]
</code>```

So, -n 250 executes [i+1 for i in range(5000)] 250 times? Then what does -r 2?

答: A more statistical way of  explaining is as the bootstrapping estimation of the distribution of some statistics (specifically, its mean and standard deviation), in such context:  "r" can be seen as the number of samples and "n" as the size of each sample.</p>

Body:
I am wondering about the %timeit command in IPython

From the docs:

%timeit [-n<N> -r<R> [-t|-c] -q -p
 -o] setup_code

Options:

-n: execute the given statement  times in a loop. If this value is not given, a fitting value is chosen.

-r: repeat the loop iteration  times and take the best result. Default: 3

For example, if I write:

%timeit -n 250 -r 2 [i+1 for i in range(5000)]

So, -n 250 executes [i+1 for i in range(5000)] 250 times? Then what does -r 2?


问:
ElementTree : insert method and bad indentation output
I use this code to insert a new node in the original .xml (file taken from the ElementTree documentation) :

```<code>import xml.etree.ElementTree as ET

tree = ET.parse('country_data.xml')
root = tree.getroot()

my_xml = """
    <country name="Togo">
        <rank updated="yes">2</rank>
        <year>2000</year>
        <gdppc>3</gdppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
"""

new_contry = ET.fromstring(my_xml)
root.insert(1,new_contry)

tree.write('essai_insert_output.xml')

root = tree.getroot()
</code>```

But the result destroys the right indentation between the new node and the next one :

```<code><data>
    <country name="Liechtenstein">
        <rank>1</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E" />
        <neighbor name="Switzerland" direction="W" />
    </country>
    <country name="Togo">
        <rank updated="yes">2</rank>
        <year>2000</year>
        <gdppc>3</gdppc>
        <neighbor name="Austria" direction="E" />
        <neighbor name="Switzerland" direction="W" />
    </country><country name="Singapore">
        <rank>4</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N" />
    </country>
    <country name="Panama">
        <rank>68</rank>
        <year>2011</year>
        <gdppc>13600</gdppc>
        <neighbor name="Costa Rica" direction="W" />
        <neighbor name="Colombia" direction="E" />
    </country>
</data>
</code>```

The new node <country name="Togo">is well placed but at the end of it, we have this collision :

```<code></country><country name="Singapore">
</code>```

How to cure this effect?

答:
Format output.</p>

```<code>from xml.dom import minidom

dom = minidom.parse('country_data.xml')
with open('dom_write.xml', 'w', encoding='UTF-8') as fh:
    dom.writexml(fh, indent='', addindent='\t', newl='', encoding='UTF-8')
</code>```

Body:
I use this code to insert a new node in the original .xml (file taken from the ElementTree documentation) :

import xml.etree.ElementTree as ET

tree = ET.parse('country_data.xml')
root = tree.getroot()

my_xml = """
    <country name="Togo">
        <rank updated="yes">2</rank>
        <year>2000</year>
        <gdppc>3</gdppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
"""

new_contry = ET.fromstring(my_xml)
root.insert(1,new_contry)

tree.write('essai_insert_output.xml')

root = tree.getroot()

But the result destroys the right indentation between the new node and the next one :

<data>
    <country name="Liechtenstein">
        <rank>1</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E" />
        <neighbor name="Switzerland" direction="W" />
    </country>
    <country name="Togo">
        <rank updated="yes">2</rank>
        <year>2000</year>
        <gdppc>3</gdppc>
        <neighbor name="Austria" direction="E" />
        <neighbor name="Switzerland" direction="W" />
    </country><country name="Singapore">
        <rank>4</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N" />
    </country>
    <country name="Panama">
        <rank>68</rank>
        <year>2011</year>
        <gdppc>13600</gdppc>
        <neighbor name="Costa Rica" direction="W" />
        <neighbor name="Colombia" direction="E" />
    </country>
</data>

The new node <country name="Togo">is well placed but at the end of it, we have this collision :

</country><country name="Singapore">

How to cure this effect?

Body:
Format output.

from xml.dom import minidom

dom = minidom.parse('country_data.xml')
with open('dom_write.xml', 'w', encoding='UTF-8') as fh:
    dom.writexml(fh, indent='', addindent='\t', newl='', encoding='UTF-8')


问:
How to extract fields from JSON string in Splunk
In Splunk after searching I am getting below result-

FINISH  OnDemandModel - Model: Application:GVAP RequestID:test_manifest_0003 Project:AMPS EMRid:j-XHFRN0A4M3QQ status:success

I want to extract fields like Application, RequestID, Project, EMRid and status as columns and corresponding values as those columns' values.

I am new to Splunk and not sure how to use spath or other search commands.

答:
Use the rex command:

```<code><search>
rex field=yourfield "Application:(?<application>\w+)\sRequestID:(?<requestid>\w+)\sProject:(?<project>\w+)\sEMRid:(?<emrid>\w+)\sstatus:(?<status>\w+)"
</code>```

Fine-tune your regexes over at regex101.com

Body:
Use the rex command:

<search>
rex field=yourfield "Application:(?<application>\w+)\sRequestID:(?<requestid>\w+)\sProject:(?<project>\w+)\sEMRid:(?<emrid>\w+)\sstatus:(?<status>\w+)"

Fine-tune your regexes over at regex101.com


问:
LinearState with OneToMany mappings
I have a state which derives from LinearState and QueryableState. The state has a OneToMany mapping with one of the attributes in the sate. Adding a OneToMany marks the key with a Unique constraint.

When i try to consume and create a new such state (keeping linearId same), this Unique key is violated as corda stores all consumed & unconsumed states in the same table.

How can this be modelled in corda?

答:
You could use JoinColumns with output_index and transaction_id as shown below. These values will always be different since any update will require a new transaction.

```<code>@JoinColumns({
        @JoinColumn(name = "output_index", referencedColumnName = "output_index"),
        @JoinColumn(name = "transaction_id", referencedColumnName = "transaction_id"),
})
</code>```

Here is a blog explaining hierarchical relationships in Corda.

https://medium.com/corda/implementing-hierarchical-relationship-with-corda-queryablestate-15049fed5934

Title: LinearState with OneToMany mappings

Body:
You could use JoinColumns with output_index and transaction_id as shown below. These values will always be different since any update will require a new transaction.

@JoinColumns({
        @JoinColumn(name = "output_index", referencedColumnName = "output_index"),
        @JoinColumn(name = "transaction_id", referencedColumnName = "transaction_id"),
})

Here is a blog explaining hierarchical relationships in Corda.

https://medium.com/corda/implementing-hierarchical-relationship-with-corda-queryablestate-15049fed5934


问:
In Laravel 7 How to orderBy Roles->name?
I have User Model  with Roles relationships like so :

```<code>public function users(){

        return $this->belongsToMany(User::class)->withTimestamps();

    }
</code>```

And Role Model with user relationships :

```<code>public function roles(){

            return $this->belongsToMany(Role::class)->withTimestamps();
        }
</code>```

And of course Pivot Table   "role_user" contains id, user_id, role_id and timestamps

I try to get users ordered By  roles name like so :

```<code>$users = App\Models\User::with('roles')->orderBy('roles.name', 'desc')->get();
</code>```

but i have this error :

```<code>Illuminate\Database\QueryException
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'roles.name' in 'order clause' (SQL: select * from `users` where `users`.`deleted_at` is null order by `roles`.`name` desc)
http://localhost:8000/users
</code>```

Please, some helps .

答:
Try Like this:

```<code>$users = App\Models\User::with('roles')->get();
// order of the roles
$array = ['User','Admin','Doctor', 'Manager'];
$sorted = $users->sortBy(function($model) use ($array) {
    return array_search($model['roles'], $array);
});
</code>```

Hope it will help you!

Body:
I have User Model  with Roles relationships like so :

public function users(){

        return $this->belongsToMany(User::class)->withTimestamps();

    }

And Role Model with user relationships :

public function roles(){

            return $this->belongsToMany(Role::class)->withTimestamps();
        }

And of course Pivot Table   "role_user" contains id, user_id, role_id and timestamps

I try to get users ordered By  roles name like so :

$users = App\Models\User::with('roles')->orderBy('roles.name', 'desc')->get();

but i have this error :

Illuminate\Database\QueryException
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'roles.name' in 'order clause' (SQL: select * from `users` where `users`.`deleted_at` is null order by `roles`.`name` desc)
http://localhost:8000/users

Please, some helps .

Body:
Try Like this:

$users = App\Models\User::with('roles')->get();
// order of the roles
$array = ['User','Admin','Doctor', 'Manager'];
$sorted = $users->sortBy(function($model) use ($array) {
    return array_search($model['roles'], $array);
});

Hope it will help you!


问:
Play mp3 on iPad Safari
Is it possible to play embedded MP3 on iPad Safari (the way you do on normal desktop browsers) ?

If yes, do we need to code separately for iPad Safari ?

The reason I am asking is bcoz in my app, the desktop code for mp3 is not working on iPad..
The code for desktop is

```<code><EMBED src="'+audioUrl+'" autostart=true loop=false volume=100 hidden=true>
</code>```

答: To add to the excellent answers of Blindy and John, the IPad should be HTML5 compliant which means that you can use the HTML5 audio and vido tags. You can read more about this at The Safari Developer Library.</p>

Title: Play mp3 on iPad Safari

Body:
Is it possible to play embedded MP3 on iPad Safari (the way you do on normal desktop browsers) ?

If yes, do we need to code separately for iPad Safari ?

The reason I am asking is bcoz in my app, the desktop code for mp3 is not working on iPad..
The code for desktop is

<EMBED src="'+audioUrl+'" autostart=true loop=false volume=100 hidden=true>


问:
Update SQL from PHP with textbox and button
I am simply trying to create a home webpage to where we can enter the mileage hit update which grabs the vehicle, and current date then pushes it to the DB.

The code I have below displays correctly other than maybe formatting the number to have a , but that wouldn't be a necessity.

When I hit update I get Notice: Undefined variable: mileage in /var/www/html/Oil/cars.php on line 60

```<code><link href="status.css" rel="stylesheet">
<body bgcolor = #000000>
<font color = "white">

<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
 <META HTTP-EQUIV="refresh" CONTENT="86400"><style>
        body {
            animation: fadeInAnimation ease 3s;
            animation-iteration-count: 1;
            animation-fill-mode: forwards;
        }
        @keyframes fadeInAnimation {
            0% {
                opacity: 0;
            }
            100% {
                opacity: 1;
            }
        }
    </style>
</head>

<center>
<font color = "red">

<?php
try {

    $db = new PDO("sqlite:/var/www/html/Oil/Vehicles.db");
    print "<center><table border=10 bordercolorlight=#383838 bordercolordark=Gray>";
    print "<tr><td class='toprow'><u>Vehicle</u></td><td class='toprow'><u>Mileage</u></td><td class='toprow'><u>Filter Size</u></td><td class='toprow'><u>Oil Capacity</u></td><td class='toprow'><u>Oil Type</u></td><td class='toprow'><u>Change Date</u></td><td class='toprow'><u>New Miles</u></td><td class='toprow'><u>Update</u></td></tr>";
    $result2 = $db->query('SELECT * FROM Cars');

    foreach ($result2 as $row) {

        print '<tr><td>' . $row['vehicle'] .'</td>';
        print "<td>" . $row['mileage'] . "</td>";
        print '<td>' . $row['filter'] .'</td>';
        print '<td>' . $row['oilCap'] .'</td>';
        print '<td>' . $row['oilType'] .'</td>';
        print '<td>' . $row['changeDate'] .'</td>';
    print '<td><form action="" method="POST"><input type="Text" name= "mileage"/><input type="hidden" name="vehicle" value="' .$row['vehicle']. '"/></td>';
    print '<td><button class="btn btn-default" type="submit" name="update">Update</button></form></td></tr>';
    }
    print "</table></center>";

} catch (PDOException $e) {
    echo $e->getMessage();
}
if (isset($_POST['update'])) {
    ini_set('display_errors', 1);
    error_reporting(E_ALL);

    $mileage = $_POST['mileage'];
    print $mileage;
    $vehicle = $_POST['vehicle'];
    print $vehicle;
    $change = date("m/d/Y");
    print $change;

    $sql = "UPDATE cars SET mileage = :mileage, chageDate = :change WHERE vehicle = :vehicle";

    try{
            $db2 = new PDO("sqlite:/var/www/html/Oil/Vehicles.db");
        if (!($results = $db2->prepare($sql))){
            echo "Prepare failed: (" . $db->errorInfo() . ") " . $db->errorCode();
        }elseif (!$results->bindValue(':mileage', $mileage)){
            echo "Binding parameters failed: (" . $results->errorInfo() . ") " . $results->errorCode();
        }elseif (!$results->bindValue(':change', $change)){
            echo "Binding parameters failed: (" . $results->errorInfo() . ") " . $results->errorCode();
        }elseif (!$results->bindValue(':vehicle', $vehicle)){
            echo "Binding parameters failed: (" . $results->errorInfo() . ") " . $results->errorCode();
        }elseif (!$results->execute()) {
            echo "Execute failed:\n";
            print_r($results->errorInfo());
        }else{
            $count = $results ->rowCount();
            if($results ->rowCount() == 0)
                echo 'Error';
            else
                echo 'Changed!';
        }

        } catch (PDOException $e) {
            echo $e->getMessage();
        }

}

?>

</code>```

Maybe I'm not passing mileage correctly?

答: You are not providing an actual value='' in <input type="Text" name= "mileage"/>, so when Submitting $_POST['mileage']; is empty, and you get the notice.

Body:
I am simply trying to create a home webpage to where we can enter the mileage hit update which grabs the vehicle, and current date then pushes it to the DB.

The code I have below displays correctly other than maybe formatting the number to have a , but that wouldn't be a necessity.

When I hit update I get Notice: Undefined variable: mileage in /var/www/html/Oil/cars.php on line 60

<link href="status.css" rel="stylesheet">

<meta name="viewport" content="width=device-width, initial-scale=1.0">
 <META HTTP-EQUIV="refresh" CONTENT="86400">

<?php
try {

    $db = new PDO("sqlite:/var/www/html/Oil/Vehicles.db");
    print "
";
    print "
Vehicle	Mileage	Filter Size	Oil Capacity	Oil Type	Change Date	New Miles	Update
";
    $result2 = $db->query('SELECT * FROM Cars');

    foreach ($result2 as $row) {

        print '
' . $row['vehicle'] .'	';
        print "" . $row['mileage'] . "	";
        print '' . $row['filter'] .'	';
        print '' . $row['oilCap'] .'	';
        print '' . $row['oilType'] .'	';
        print '' . $row['changeDate'] .'	';
    print '<form action="" method="POST"><input type="Text" name= "mileage"/><input type="hidden" name="vehicle" value="' .$row['vehicle']. '"/>	';
    print '<button class="btn btn-default" type="submit" name="update">Update</button></form>
';
    }
    print "
";

} catch (PDOException $e) {
    echo $e->getMessage();
}
if (isset($_POST['update'])) {
    ini_set('display_errors', 1);
    error_reporting(E_ALL);

    $mileage = $_POST['mileage'];
    print $mileage;
    $vehicle = $_POST['vehicle'];
    print $vehicle;
    $change = date("m/d/Y");
    print $change;

    $sql = "UPDATE cars SET mileage = :mileage, chageDate = :change WHERE vehicle = :vehicle";

    try{
            $db2 = new PDO("sqlite:/var/www/html/Oil/Vehicles.db");
        if (!($results = $db2->prepare($sql))){
            echo "Prepare failed: (" . $db->errorInfo() . ") " . $db->errorCode();
        }elseif (!$results->bindValue(':mileage', $mileage)){
            echo "Binding parameters failed: (" . $results->errorInfo() . ") " . $results->errorCode();
        }elseif (!$results->bindValue(':change', $change)){
            echo "Binding parameters failed: (" . $results->errorInfo() . ") " . $results->errorCode();
        }elseif (!$results->bindValue(':vehicle', $vehicle)){
            echo "Binding parameters failed: (" . $results->errorInfo() . ") " . $results->errorCode();
        }elseif (!$results->execute()) {
            echo "Execute failed:\n";
            print_r($results->errorInfo());
        }else{
            $count = $results ->rowCount();
            if($results ->rowCount() == 0)
                echo 'Error';
            else
                echo 'Changed!';
        }

        } catch (PDOException $e) {
            echo $e->getMessage();
        }

}

?>

Maybe I'm not passing mileage correctly?


问:
Vue Js: How to store image in localStorage and show it on the webpage in vue js
I am trying to add data in localstorage when any data is entered in textbox. my question is that how can i add a image in localstorage in Vue js.</p>

答:
You can convert the image to Base64 and store it like a string on local storage;

this link will help you to do that : How can I convert an image into Base64 string using JavaScript?

and when you want to get the image back you will do the opposite process,
you need to convert the base64 string to image element,
and actually it is very easy, you can put the base64 string as a src of image.

and this a link can help you to do that : convert base64 to image in javascript/jquery


问:
Aggregate data inside case statement
I want to create 4 groups based on submit_volume and then calculate percentage of each group over total number of submit_volume

So far I used this query

```<code>SELECT CASE
           WHEN submit_volume <= 60 then '60 Request'
           WHEN submit_volume > 60
                AND submit_volume <= 150 then '60-150 Request'
           WHEN submit_volume > 150
                AND submit_volume <= 1000 then '150-1K Request'
           WHEN submit_volume > 1000 then 'Over 1K Request'
       END,
       sum(CASE
               WHEN submit_volume <= 60 then submit_volume
               WHEN submit_volume > 60
                    AND submit_volume <= 150 then submit_volume
               WHEN submit_volume > 150
                    AND submit_volume <= 1000 then submit_volume
               WHEN submit_volume > 1000 then submit_volume
           END)
FROM mydatabase.submit_volume
GROUP BY 1
</code>```

And got this table

```<code>| group| sum|
| 60-150 Request   | 87247    |
| 60 Request       | 105934   |
| Over 1K Request  | 2385947  |
| 150-1K Request   | 777186   |
</code>```

So can I have the percentage of each group without using subquery? I tried this but I got the same 100% for all groups

```<code>sum(CASE
   WHEN submit_volume <= 60 then submit_volume
   WHEN submit_volume > 60
      AND submit_volume <= 150 then submit_volume
   WHEN submit_volume > 150
      AND submit_volume <= 1000 then submit_volume
   WHEN submit_volume > 1000 then submit_volume
END) / sum(submit_volume) * 100.0 as percentage
</code>```

答:
The CASE expression that you use to group can be simplified and the SUM() needs only submit_volume.

Cross join to the table a query that returns the total submit_volume of the table and use it to get the percentage:

```<code>SELECT CASE
           WHEN sv.submit_volume <= 60 then '60 Request'
           WHEN sv.submit_volume <= 150 then '60-150 Request'
           WHEN sv.submit_volume <= 1000 then '150-1K Request'
           WHEN sv.submit_volume > 1000 then 'Over 1K Request' -- or ELSE 'Over 1K Request'
       END request,
       SUM(sv.submit_volume) / MAX(t.total) * 100.0 percentage
FROM mydatabase.submit_volume sv
CROSS JOIN (SELECT SUM(submit_volume) total FROM mydatabase.submit_volume) t
GROUP BY request
</code>```

For MySql 8.0+ it's easier with SUM() window function:

```<code>SELECT CASE
           WHEN submit_volume <= 60 then '60 Request'
           WHEN submit_volume <= 150 then '60-150 Request'
           WHEN submit_volume <= 1000 then '150-1K Request'
           WHEN submit_volume > 1000 then 'Over 1K Request' -- or ELSE 'Over 1K Request'
       END request,
       SUM(submit_volume) / SUM(SUM(submit_volume)) OVER () * 100.0 percentage
FROM submit_volume
GROUP BY request
</code>```

See a simplified demo.

Title: Aggregate data inside case statement

Body:
I want to create 4 groups based on submit_volume and then calculate percentage of each group over total number of submit_volume

So far I used this query

SELECT CASE
           WHEN submit_volume <= 60 then '60 Request'
           WHEN submit_volume > 60
                AND submit_volume <= 150 then '60-150 Request'
           WHEN submit_volume > 150
                AND submit_volume <= 1000 then '150-1K Request'
           WHEN submit_volume > 1000 then 'Over 1K Request'
       END,
       sum(CASE
               WHEN submit_volume <= 60 then submit_volume
               WHEN submit_volume > 60
                    AND submit_volume <= 150 then submit_volume
               WHEN submit_volume > 150
                    AND submit_volume <= 1000 then submit_volume
               WHEN submit_volume > 1000 then submit_volume
           END)
FROM mydatabase.submit_volume
GROUP BY 1

And got this table

| group| sum|
| 60-150 Request   | 87247    |
| 60 Request       | 105934   |
| Over 1K Request  | 2385947  |
| 150-1K Request   | 777186   |

So can I have the percentage of each group without using subquery? I tried this but I got the same 100% for all groups

sum(CASE
   WHEN submit_volume <= 60 then submit_volume
   WHEN submit_volume > 60
      AND submit_volume <= 150 then submit_volume
   WHEN submit_volume > 150
      AND submit_volume <= 1000 then submit_volume
   WHEN submit_volume > 1000 then submit_volume
END) / sum(submit_volume) * 100.0 as percentage

Body:
The CASE expression that you use to group can be simplified and the SUM() needs only submit_volume.

Cross join to the table a query that returns the total submit_volume of the table and use it to get the percentage:

SELECT CASE
           WHEN sv.submit_volume <= 60 then '60 Request'
           WHEN sv.submit_volume <= 150 then '60-150 Request'
           WHEN sv.submit_volume <= 1000 then '150-1K Request'
           WHEN sv.submit_volume > 1000 then 'Over 1K Request' -- or ELSE 'Over 1K Request'
       END request,
       SUM(sv.submit_volume) / MAX(t.total) * 100.0 percentage
FROM mydatabase.submit_volume sv
CROSS JOIN (SELECT SUM(submit_volume) total FROM mydatabase.submit_volume) t
GROUP BY request

For MySql 8.0+ it's easier with SUM() window function:

SELECT CASE
           WHEN submit_volume <= 60 then '60 Request'
           WHEN submit_volume <= 150 then '60-150 Request'
           WHEN submit_volume <= 1000 then '150-1K Request'
           WHEN submit_volume > 1000 then 'Over 1K Request' -- or ELSE 'Over 1K Request'
       END request,
       SUM(submit_volume) / SUM(SUM(submit_volume)) OVER () * 100.0 percentage
FROM submit_volume
GROUP BY request

See a simplified demo.