问:
Regex two separate nested capturing groups
I have a regex and test case on

https://regex101.com/r/5Z5Lop/1

```<code>^(?<KEY>CONF|ESD|TRACKING)[:;'\s]\s*(?<DATA>.*?)\s*(?:L[:;'\s]\s*\K(?<LINE_DATA>.*?))?(?<INITIALS>\*[a-zA-Z]+)?\s*$
</code>```

See the LINE_DATA named group.

Is it possible to split that group up into two separate groups?

I want one group LINE_NUMBERS to hold all integers not contained in parentheses.
Then, 1 group called QTYS to hold all integers that are contained in parentheses.

So currently LINE_NUMBERS yields "1,2,3(4),5(12)   "

Is it possible to have a LINE_NUMBERS be [1,2,3,4] (either array or some kinda string)
and then QTYS to be [(4),(12)] Note: I do still want to capture the parentheses.

I would like to do this in the current regex if it's possible and doesn't overly complicate what I currently have.

Right now, I'm obtaining this data through post-processing with separate regexes. I'm using php

preg_match_all('/\d+(?!\s*\))/i', $ret_data['LINE_DATA'], $ret_data['LINE_NUMBERS']);

Thanks!
preg_match_all('/\(\s*\d\s*\)/i', $ret_data['LINE_DATA'], $ret_data['QUANTITIES']);

答:
You can use a single pattern in the post-processing for the QUANTITIES and the LINE_NUMBERS using an alternation | and removing the empty entries from the result.

```<code>$re = '/^(?<KEY>CONF|ESD|TRACKING)[:;\'\s]\s*(?<DATA>.*?)\s*(?:L[:;\'\s]\s*\K(?<LINE_DATA>.*?))?(?<INITIALS>\*[a-zA-Z]+)?\s*$/i';
$str = 'esd:      here is my data      L:       1,2,3(4),5(12)   *sm          ';
preg_match($re, $str, $matches);

preg_match_all('/(?<QUANTITIES>\(\d+\))|(?<LINE_NUMBERS>\d+)/', $matches["LINE_DATA"], $numbers);

print_r(array_filter($numbers["QUANTITIES"]));
print_r(array_filter($numbers["LINE_NUMBERS"]));
</code>```

Output

```<code>Array
(
    [3] => (4)
    [5] => (12)
)
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [4] => 5
)
</code>```

There could be an option to use the \G anchor to get 2 separate groups for the given example data, but it will make the INITIALS part after it optional:

```<code>^(?<KEY>CONF|ESD|TRACKING)[:;'\s]\s*(?<DATA>.*?)\s*L[:;'\s]\s*|\G(?!^)(?:(?<QUANTITIES>\(\d+\))|(?<LINE_NUMBERS>\d+)),?(?:\s*(?<INITIALS>\*[a-zA-Z]+)\s*$)?
</code>```

^ Start of string

(?<KEY>CONF|ESD|TRACKING)[:;'\s]\s* The KEY group with alternatives, and match a single char listed in the character class and optional whitspace chars

(?<DATA>.*?)\s* Match the DATA group, any char non greedy  followed by optional whitespace chars

L[:;'\s]\s* Match L the any of the list chars and optional whitespace chars

| Or

\G(?!^) Assert the position at the end of the previous match, not at the start

(?: Non capture group

(?<QUANTITIES>\(\d+\)) Group QUANTITIES, match 1+ digits between parenthesis

| Or

(?<LINE_NUMBERS>\d+) Group LINE_NUMBERS, match 1+ digits

) Close non capture group

,? Match an optional comma

(?:\s*(?<INITIALS>\*[a-zA-Z]+)\s*$)? Optional non capture group with group INITIALS

Regex demo | PHP demo

Body:
I have a regex and test case on

https://regex101.com/r/5Z5Lop/1

^(?<KEY>CONF|ESD|TRACKING)[:;'\s]\s*(?<DATA>.*?)\s*(?:L[:;'\s]\s*\K(?<LINE_DATA>.*?))?(?<INITIALS>\*[a-zA-Z]+)?\s*$

See the LINE_DATA named group.

Is it possible to split that group up into two separate groups?

I want one group LINE_NUMBERS to hold all integers not contained in parentheses.
Then, 1 group called QTYS to hold all integers that are contained in parentheses.

So currently LINE_NUMBERS yields "1,2,3(4),5(12)   "

Is it possible to have a LINE_NUMBERS be [1,2,3,4] (either array or some kinda string)
and then QTYS to be [(4),(12)] Note: I do still want to capture the parentheses.

I would like to do this in the current regex if it's possible and doesn't overly complicate what I currently have.

Right now, I'm obtaining this data through post-processing with separate regexes. I'm using php

preg_match_all('/\d+(?!\s*\))/i', $ret_data['LINE_DATA'], $ret_data['LINE_NUMBERS']);

Thanks!
preg_match_all('/\(\s*\d\s*\)/i', $ret_data['LINE_DATA'], $ret_data['QUANTITIES']);

Body:
You can use a single pattern in the post-processing for the QUANTITIES and the LINE_NUMBERS using an alternation | and removing the empty entries from the result.

$re = '/^(?<KEY>CONF|ESD|TRACKING)[:;\'\s]\s*(?<DATA>.*?)\s*(?:L[:;\'\s]\s*\K(?<LINE_DATA>.*?))?(?<INITIALS>\*[a-zA-Z]+)?\s*$/i';
$str = 'esd:      here is my data      L:       1,2,3(4),5(12)   *sm          ';
preg_match($re, $str, $matches);

preg_match_all('/(?<QUANTITIES>\(\d+\))|(?<LINE_NUMBERS>\d+)/', $matches["LINE_DATA"], $numbers);

print_r(array_filter($numbers["QUANTITIES"]));
print_r(array_filter($numbers["LINE_NUMBERS"]));

Output

Array
(
    [3] => (4)
    [5] => (12)
)
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [4] => 5
)

There could be an option to use the \G anchor to get 2 separate groups for the given example data, but it will make the INITIALS part after it optional:

^(?<KEY>CONF|ESD|TRACKING)[:;'\s]\s*(?<DATA>.*?)\s*L[:;'\s]\s*|\G(?!^)(?:(?<QUANTITIES>\(\d+\))|(?<LINE_NUMBERS>\d+)),?(?:\s*(?<INITIALS>\*[a-zA-Z]+)\s*$)?

^ Start of string

(?<KEY>CONF|ESD|TRACKING)[:;'\s]\s* The KEY group with alternatives, and match a single char listed in the character class and optional whitspace chars

(?<DATA>.*?)\s* Match the DATA group, any char non greedy  followed by optional whitespace chars

L[:;'\s]\s* Match L the any of the list chars and optional whitespace chars

| Or

\G(?!^) Assert the position at the end of the previous match, not at the start

(?: Non capture group

(?<QUANTITIES>\(\d+\)) Group QUANTITIES, match 1+ digits between parenthesis

| Or

(?<LINE_NUMBERS>\d+) Group LINE_NUMBERS, match 1+ digits

) Close non capture group

,? Match an optional comma

(?:\s*(?<INITIALS>\*[a-zA-Z]+)\s*$)? Optional non capture group with group INITIALS

Regex demo | PHP demo


来源: stackexchange

问:
Python wordlist creation
So far I am creating a world based game the only thing I need help with is creating a wordlist without having to type each word or re formate hundreds into the correct formatting. Any tips?

so far I have this:

```<code>fiveLetterWords = ["abuse", "adult", "drama", "drain", "enemy", "entry", "catch", "could", "would", "track", "train", "plain", "plane"]
sixLetterWords = ["people", "things", "really", "abroad", "accept", "belief", "scraps", "trashy", "camera", "create"]
</code>```

I would like to have a few more words than this and if there's a site that has this listed in this format comment it thanks!

答:
If you are on a Unix like OS, you can use the words list:

```<code>words={}
with open('/usr/share/dict/words') as f: # /usr/dict/words on some
    for word in (w.rstrip() for w in f):
        words.setdefault(len(word), []).append(word)
</code>```

If you only want words of a certain length, you can filter them:

```<code>words={}
with open('//usr/share/dict/words') as f:
    for word in (w for w in (w.rstrip() for w in f) if 4<=len(w)<=6):
        words.setdefault(len(word), []).append(word)
</code>```

ContentLicense: CC BY-SA 4.0

Title: Python wordlist creation

Body:
So far I am creating a world based game the only thing I need help with is creating a wordlist without having to type each word or re formate hundreds into the correct formatting. Any tips?

so far I have this:

fiveLetterWords = ["abuse", "adult", "drama", "drain", "enemy", "entry", "catch", "could", "would", "track", "train", "plain", "plane"]
sixLetterWords = ["people", "things", "really", "abroad", "accept", "belief", "scraps", "trashy", "camera", "create"]

I would like to have a few more words than this and if there's a site that has this listed in this format comment it thanks!

Body:
If you are on a Unix like OS, you can use the words list:

words={}
with open('/usr/share/dict/words') as f: # /usr/dict/words on some
    for word in (w.rstrip() for w in f):
        words.setdefault(len(word), []).append(word)

If you only want words of a certain length, you can filter them:

words={}
with open('//usr/share/dict/words') as f:
    for word in (w for w in (w.rstrip() for w in f) if 4<=len(w)<=6):
        words.setdefault(len(word), []).append(word)


问:
How to configure msys2 in codeblocks?
How to configure codeblocks compiler and debugger with msys2 ?

I found an answer related here, but I don't find very usefull as I use windows 7, instead linux ;)

What I want to achive is integrating esp-idf embedded system in codeblocks.

Is this even possible ? Anyone ?

答:
Install CodeBlocks 20.03 without the compiler (installer: codeblocks-20.03-setup.exe, about 37.5 Mb)

Download and install Msys2 by following the instructions on the homepage

Install the mingw-w64 toolchain (open the Msys64 shell and run the command: pacman -S git mingw-w64-x86_64-cmake make mingw-w64-x86_64-toolchain)

Now you need to configure the compiler in CodeBlocks.

Go to Settings -> Compiler...

Click on Toolchain executables tab and browse for mingw64 folder (without bin).

Edit the executable file names as gcc.exe, g++.exe and g++.exe

Click Ok to confirm

Go to Settings -> Debugger... and configure gdb.exe as default debugger (browse for the gdb.exe file into the bin directory)

Now the GCC compiler and the GDB debugger are configured.

You can use pacman from the Msys2 shell, to download and install or uninstall a lot of packages.

I don't know esp-idf but it seems to me that this sdk is not distributed as a msys2 package.

Title: How to configure msys2 in codeblocks?


问:
Finding palindrome in C
A palindrome is a word that reads the same from left to right and from right to left.
I wrote a program that finds palindromes from a console.

```<code>#include <stdio.h>
#include <ctype.h>
#include <string.h>

#define SIZE 100

int main() {
    int i = 0, c;
    int left, right;
    char string[SIZE];

    while (EOF != (c = getchar()) || (c = getchar()) != '\n') {
        if (isspace(c) != 0) {
            if (i > 0) {
                left = 0;
                right = i - 1;
                while (right > left) {
                    if (string[left] != string[right]) {
                        i = 0;
                        break;
                    }
                    ++left;
                    --right;
                }
                if (left >= right) {
                    while (i > 0)
                        printf("%c", string[--i]);
                    printf("%c", c);
                }
                i = 0;
            }
            if (c == '\n')
                break;
        }
        else {
            string[i++] = c;
        }
    }
}
</code>```

For example, we enter the words: dad sad mum. She outputs: dad mum. But if we write dad sad or dad mum sad. The output will be: dad mum.
That is, an extra space is printed when the last word we read is not a palindrome. How can you get around this situation?

答:
Life is easier if you just read the string all at once, then process the string.

```<code>char s[1000];
fgets( s, sizeof(s), stdin );
char * p = strchr( s, '\n' );
if (p) *p = '\0';
</code>```

If you wanted to read one character at a time you should read once, test twice:

```<code>int c;
while ( ((c = getchar()) != '\n') and (c != EOF) )
</code>```

But trying to compute the palindrome-ness at the same time as reading seriously makes your algorithm waaaaay more complicated than it needs to be. Read a string first, then compute.

Now you can use integer indices from each end of the string. If you can get them to meet (or cross) then you’ve got a palindrome. Hint: put that in a function:

```<code>bool is_palindrome( const char * s )
{
  int left  = 0;
  int right = strlen(s) - 1;
  ...
}
</code>```

Title: Finding palindrome in C

Body:
A palindrome is a word that reads the same from left to right and from right to left.
I wrote a program that finds palindromes from a console.

#include <stdio.h>
#include <ctype.h>
#include <string.h>

#define SIZE 100

int main() {
    int i = 0, c;
    int left, right;
    char string[SIZE];

    while (EOF != (c = getchar()) || (c = getchar()) != '\n') {
        if (isspace(c) != 0) {
            if (i > 0) {
                left = 0;
                right = i - 1;
                while (right > left) {
                    if (string[left] != string[right]) {
                        i = 0;
                        break;
                    }
                    ++left;
                    --right;
                }
                if (left >= right) {
                    while (i > 0)
                        printf("%c", string[--i]);
                    printf("%c", c);
                }
                i = 0;
            }
            if (c == '\n')
                break;
        }
        else {
            string[i++] = c;
        }
    }
}

For example, we enter the words: dad sad mum. She outputs: dad mum. But if we write dad sad or dad mum sad. The output will be: dad mum.
That is, an extra space is printed when the last word we read is not a palindrome. How can you get around this situation?

Body:
Life is easier if you just read the string all at once, then process the string.

char s[1000];
fgets( s, sizeof(s), stdin );
char * p = strchr( s, '\n' );
if (p) *p = '\0';

If you wanted to read one character at a time you should read once, test twice:

int c;
while ( ((c = getchar()) != '\n') and (c != EOF) )

But trying to compute the palindrome-ness at the same time as reading seriously makes your algorithm waaaaay more complicated than it needs to be. Read a string first, then compute.

Now you can use integer indices from each end of the string. If you can get them to meet (or cross) then you’ve got a palindrome. Hint: put that in a function:

bool is_palindrome( const char * s )
{
  int left  = 0;
  int right = strlen(s) - 1;
  ...
}


问:
Sort recursively-defined tree by given target value
we have a tree where each node in the tree is an object with a required "val" property that maps to a non-unique integer and an optional "children" property that, if present, maps to an array of child nodes.

This challenge involves writing a function prioritizeNodes(tree, targetVal) which accepts a valid nested tree object conforming to the above definition. The function should sort all "children" arrays containing one or more nodes with node.val === targetVal to the front of the array. For this input, the output for a call to prioritizeNodes(tree, 7)

INPUT

```<code>{
  "val": 1,
  "children": [
    {"val": 2},
    {
      "val": 3,
      "children": [
        {
          "val": 4,
          "children": [
            {"val": 5},
            {"val": 6},
            {"val": 7}
          ]
        }
      ]
    }
  ]
}
</code>```

Expected output

```<code>{
  "val": 1,
  "children": [
    {
      "val": 3, // <-- moved up
      "children": [
        {
          "val": 4,
          "children": [
            {"val": 7}, // <-- moved up
            {"val": 5},
            {"val": 6}
          ]
        }
      ]
    },
    {"val": 2}
  ]
}
</code>```

Each node in a tree with a value or child matching the target was moved to the front of its respective array.

Non-prioritized nodes should be kept in their original relative ordering with respect to one another, and prioritized nodes which were moved to the front of an array should also maintain order with respect to other priority nodes in the array. Your function may mutate the parameter tree in-place in addition to returning it if you wish.

Here's what i've got so far, and i couldn't identify why it still doesn't work, can anyone provide any solution please ?

```<code>class Node {
    val;
    children;

    constructor(data) {
        this.val = data.val || null
        if(data.children?.length > 0){
            this.children = []
            this.addChildren(data.children)
        }else if(this.children?.length <= 0){
            delete this.children
        }
    }
    addChildren(children) {
        if(children?.length > 0){
            for (let i = 0; i < children.length; i++) {
                let newNode = new Node(children[i])
                this.children.push(newNode)
            }
        }
    }
}

function repeater(node, targetVal) {
    let parentFlag = false
    if(node.children?.length > 0){
        for (let i = 0; i < node.children.length; i++) {
            if(repeater(node.children[i], targetVal)){
                node.children.unshift(...node.children.splice(i, 1))
                parentFlag = true
            }
        }
    }
    return node.val === targetVal || parentFlag;
}

const prioritizeNodes = (oldtree, targetVal) => {
    if(!oldtree.children){
        return oldtree;
    }
    let tree = new Node(oldtree)
    for (let i = 0; i < oldtree.children.length; i++) {
        repeater(tree, targetVal)
    }
  console.log(tree)
    return tree;
}
</code>```

答:
shifting priority nodes into the children array will inverse the order of the priority nodes, which is not what is asked for.

I would avoid mutation and create two new children arrays in which the children are divided: one for the priority ones, and one for the other children. Then concatenate those two. Let the recursive function return both the new children array and the flag.

The code:

function prioritizeNodes(tree, targetVal) {
    function recur({val, children}) {
        if (!children) {
            return [{ val }, val === targetVal];
        }
        let categories = [[], []],
            isPrio;
        for (let child of children) {
            [child, isPrio] = recur(child);
            categories[1-isPrio].push(child);
        }
        return [
            { val, children: categories.flat() },
            categories[0].length > 0 || val === targetVal
        ];
    }
    return recur(tree)[0];
}

// Example input
let tree = {"val": 1,"children": [{"val": 2},{"val": 3,"children": [{"val": 4,"children": [{"val": 5},{"val": 6},{"val": 7}]}]}]}

let result = prioritizeNodes(tree, 7);
console.log(result);```

Body:
we have a tree where each node in the tree is an object with a required "val" property that maps to a non-unique integer and an optional "children" property that, if present, maps to an array of child nodes.

This challenge involves writing a function prioritizeNodes(tree, targetVal) which accepts a valid nested tree object conforming to the above definition. The function should sort all "children" arrays containing one or more nodes with node.val === targetVal to the front of the array. For this input, the output for a call to prioritizeNodes(tree, 7)

INPUT

{
  "val": 1,
  "children": [
    {"val": 2},
    {
      "val": 3,
      "children": [
        {
          "val": 4,
          "children": [
            {"val": 5},
            {"val": 6},
            {"val": 7}
          ]
        }
      ]
    }
  ]
}

Expected output

{
  "val": 1,
  "children": [
    {
      "val": 3, // <-- moved up
      "children": [
        {
          "val": 4,
          "children": [
            {"val": 7}, // <-- moved up
            {"val": 5},
            {"val": 6}
          ]
        }
      ]
    },
    {"val": 2}
  ]
}

Each node in a tree with a value or child matching the target was moved to the front of its respective array.

Non-prioritized nodes should be kept in their original relative ordering with respect to one another, and prioritized nodes which were moved to the front of an array should also maintain order with respect to other priority nodes in the array. Your function may mutate the parameter tree in-place in addition to returning it if you wish.

Here's what i've got so far, and i couldn't identify why it still doesn't work, can anyone provide any solution please ?

class Node {
    val;
    children;

    constructor(data) {
        this.val = data.val || null
        if(data.children?.length > 0){
            this.children = []
            this.addChildren(data.children)
        }else if(this.children?.length <= 0){
            delete this.children
        }
    }
    addChildren(children) {
        if(children?.length > 0){
            for (let i = 0; i < children.length; i++) {
                let newNode = new Node(children[i])
                this.children.push(newNode)
            }
        }
    }
}

function repeater(node, targetVal) {
    let parentFlag = false
    if(node.children?.length > 0){
        for (let i = 0; i < node.children.length; i++) {
            if(repeater(node.children[i], targetVal)){
                node.children.unshift(...node.children.splice(i, 1))
                parentFlag = true
            }
        }
    }
    return node.val === targetVal || parentFlag;
}

const prioritizeNodes = (oldtree, targetVal) => {
    if(!oldtree.children){
        return oldtree;
    }
    let tree = new Node(oldtree)
    for (let i = 0; i < oldtree.children.length; i++) {
        repeater(tree, targetVal)
    }
  console.log(tree)
    return tree;
}


问:
GetDrives and Files Sometimes Failing
I am recursively entering my computer drives to list all files available. But sometimes the program runs then stops and says it can't access a directory. </p>

<p>What should I do now, I am using win7. </p>

答: Give a read permission to the folder where your driver lies.</p>

ContentLicense: CC BY-SA 3.0

Title: GetDrives and Files Sometimes Failing

Body:
I am recursively entering my computer drives to list all files available. But sometimes the program runs then stops and says it can't access a directory.

What should I do now, I am using win7.


问:
Connection reset when using jsch to connect to an sftp server hosted in azure
we are currently working with a cloud product that uses JSCH internally to connect to external sftp sources. Im investigating an connection reset exception that we are getting when trying to connect to azure sftp.

Using wireshark i determined that the problem occurs after we send the Client: Key Exchange Init. Establishing the same connection with filezilla we dont have this issue.

comparing the packages from jsch and filezilla i didn't see an obivious issue, but im not an expert on the ssh protocol. im gonna post both requests below if somebody could give me any pointers it would be greatly appreciated.

Request with JSCH (not working)

Request with Filezilla (working)

Response with Filezilla (working)

See below for the log output:

```<code>INFO: Connecting to ***** port 22
INFO: Connection established
INFO: Remote version string: SSH-2.0-AzureSSH_1.0.0
INFO: Local version string: SSH-2.0-JSCH-0.1.54
INFO: CheckCiphers: aes256-ctr,aes192-ctr,aes128-ctr,aes256-cbc,aes192-cbc,aes128-cbc,3des-ctr,arcfour,arcfour128,arcfour256
INFO: CheckKexes: diffie-hellman-group14-sha1,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521
INFO: CheckSignatures: ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521
INFO: SSH_MSG_KEXINIT sent
INFO: Disconnecting from **** port 22
com.jcraft.jsch.JSchException: Session.connect: java.net.SocketException: Connection reset
</code>```

EDIT: following jameses suggestion i got the same result, connection closed but the client request only had the supported algos as payload.
So i tried to replicate the FileZilla request by setting the jsch config regardless if jsch actually supports the algo, i just wanted to see if there is any respone.

But for some reason the connection still gets terminated

Modified jsch request

答:
From SSH RFC:

```<code>   When the connection has been established, both sides MUST send an
   identification string.  This identification string MUST be

      SSH-protoversion-softwareversion SP comments CR LF

   Both the 'protoversion' and 'softwareversion' strings MUST consist of
   printable US-ASCII characters, with the exception of whitespace
   characters and the minus sign (-).  The 'softwareversion' string is
   primarily used to trigger compatibility extensions and to indicate
   the capabilities of an implementation.  The 'comments' string SHOULD
   contain additional information that might be useful in solving user
   problems.  As such, an example of a valid identification string is

      SSH-2.0-billsSSH_3.6.3q3<CR><LF>
</code>```

It seems that this library (and ssh-keyscan) violate the spec due to the "-" in the softwareversion segment: JSCH-0.1.54

As Fabian points out, the "fix" will be available before SFTP GA.

Body:
we are currently working with a cloud product that uses JSCH internally to connect to external sftp sources. Im investigating an connection reset exception that we are getting when trying to connect to azure sftp.

Using wireshark i determined that the problem occurs after we send the Client: Key Exchange Init. Establishing the same connection with filezilla we dont have this issue.

comparing the packages from jsch and filezilla i didn't see an obivious issue, but im not an expert on the ssh protocol. im gonna post both requests below if somebody could give me any pointers it would be greatly appreciated.

Request with JSCH (not working)

Request with Filezilla (working)

Response with Filezilla (working)

See below for the log output:

INFO: Connecting to ***** port 22
INFO: Connection established
INFO: Remote version string: SSH-2.0-AzureSSH_1.0.0
INFO: Local version string: SSH-2.0-JSCH-0.1.54
INFO: CheckCiphers: aes256-ctr,aes192-ctr,aes128-ctr,aes256-cbc,aes192-cbc,aes128-cbc,3des-ctr,arcfour,arcfour128,arcfour256
INFO: CheckKexes: diffie-hellman-group14-sha1,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521
INFO: CheckSignatures: ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521
INFO: SSH_MSG_KEXINIT sent
INFO: Disconnecting from **** port 22
com.jcraft.jsch.JSchException: Session.connect: java.net.SocketException: Connection reset

EDIT: following jameses suggestion i got the same result, connection closed but the client request only had the supported algos as payload.
So i tried to replicate the FileZilla request by setting the jsch config regardless if jsch actually supports the algo, i just wanted to see if there is any respone.

But for some reason the connection still gets terminated

Modified jsch request

Body:
From SSH RFC:

   When the connection has been established, both sides MUST send an
   identification string.  This identification string MUST be

      SSH-protoversion-softwareversion SP comments CR LF

   Both the 'protoversion' and 'softwareversion' strings MUST consist of
   printable US-ASCII characters, with the exception of whitespace
   characters and the minus sign (-).  The 'softwareversion' string is
   primarily used to trigger compatibility extensions and to indicate
   the capabilities of an implementation.  The 'comments' string SHOULD
   contain additional information that might be useful in solving user
   problems.  As such, an example of a valid identification string is

      SSH-2.0-billsSSH_3.6.3q3<CR><LF>

It seems that this library (and ssh-keyscan) violate the spec due to the "-" in the softwareversion segment: JSCH-0.1.54

As Fabian points out, the "fix" will be available before SFTP GA.


问:
How to UPDATE table using calculated column from subquery in Sybase
I have a table that I want to update that contains a column called 'expiration_days'. What I am doing is trying to update the records in the 'expiration_days' column by using an 'alias column' (not sure what to call it) that is apart of a subquery where I calculated the number of days until a user's password has expired. The column from the subquery that I want to take the values from and update them in the actual table is called 'countdown'. I named the subquery results 'query' (derived table). So far I have this:

```<code>UPDATE LOGIN_INFO
SET expiration_days = query.countdown
FROM (
select li.name as name, countdown = 365 - datediff(day, sl.pwdate, getdate())
from master..syslogins sl, LOGIN_INFO li
where li.name = sl.name) query
WHERE LOGIN_INFO.name = query.name
</code>```

The issue I am having is I get this error: You cannot use a derived table in the FROM clause of an UPDATE or DELETE statement. ( I also get: Incorrect syntax near ')' on the subquery where clause)

Is there a way I can take the results from the calculated column in a select statement and update the column in the LOGIN_INFO table in one query or some other easy clean way?

答:
Perhaps something along the lines of:

```<code>update login_info
set    expiration_days = (select 365 - datediff(day,s1.pwdate,getdate())
                          from   master..syslogins s1
                          where  s1.name = li.name)
from   login_info li
where  exists(select 1
              from   master..syslogins s2
              where  s2.name = li.name)
</code>```

NOTES:

the exists() clause is added to insure we don't erroneously update a row in login_info that doesn't have a match in syslogins, otherwise OP will need to modify the logic accordingly (ie, what to set expiration_days to if a matching rows does not exist in syslogins?)

if syslogins.pwdate is NULLable (I don't have access to a running ASE instance at the moment) then OP will need additional logic to handle the scenario where s1.pwdate is NULL; default countdown to some hardcoded value? or perhaps modify the exists() to include the additional clause and s2.pwdate is not NULL?

Body:
I have a table that I want to update that contains a column called 'expiration_days'. What I am doing is trying to update the records in the 'expiration_days' column by using an 'alias column' (not sure what to call it) that is apart of a subquery where I calculated the number of days until a user's password has expired. The column from the subquery that I want to take the values from and update them in the actual table is called 'countdown'. I named the subquery results 'query' (derived table). So far I have this:

UPDATE LOGIN_INFO
SET expiration_days = query.countdown
FROM (
select li.name as name, countdown = 365 - datediff(day, sl.pwdate, getdate())
from master..syslogins sl, LOGIN_INFO li
where li.name = sl.name) query
WHERE LOGIN_INFO.name = query.name

The issue I am having is I get this error: You cannot use a derived table in the FROM clause of an UPDATE or DELETE statement. ( I also get: Incorrect syntax near ')' on the subquery where clause)

Is there a way I can take the results from the calculated column in a select statement and update the column in the LOGIN_INFO table in one query or some other easy clean way?

Body:
Perhaps something along the lines of:

update login_info
set    expiration_days = (select 365 - datediff(day,s1.pwdate,getdate())
                          from   master..syslogins s1
                          where  s1.name = li.name)
from   login_info li
where  exists(select 1
              from   master..syslogins s2
              where  s2.name = li.name)

NOTES:

the exists() clause is added to insure we don't erroneously update a row in login_info that doesn't have a match in syslogins, otherwise OP will need to modify the logic accordingly (ie, what to set expiration_days to if a matching rows does not exist in syslogins?)

if syslogins.pwdate is NULLable (I don't have access to a running ASE instance at the moment) then OP will need additional logic to handle the scenario where s1.pwdate is NULL; default countdown to some hardcoded value? or perhaps modify the exists() to include the additional clause and s2.pwdate is not NULL?


问:
Join condition do not show Nulls for a field
Let's say I have these two tables. The students table stores data about the student showing up to the respected class on a specific date. On the contrary, the classes table shows when the respected class started and when was the class last held.

How can I achieve this in postgreSQL 11.

```<code>select * from students

student_name          student_showed           class_name
  Jeter                 2022-02-05                Math
  Jeter                 2022-02-06                Math
  Jeter                 2022-02-07                Math
  Jeter                 2022-02-08                Math
  Jeter                 2022-02-09                Math
  Jeter                 2022-02-05                English
  Jeter                 2022-02-06                English
  Jeter                 2022-02-07                English
  Jeter                 2022-02-08                English
  Jeter                 2022-02-09                English
  Soriano               2022-02-05                Math
  Soriano               2022-02-06                Math
  Soriano               2022-02-07                Math
  Soriano               2022-02-08                Math
  Soriano               2022-02-09                Math
  Soriano               2022-02-05                English
  Soriano               2022-02-06                English
  Soriano               2022-02-07                English
  Soriano               2022-02-08                English
  Soriano               2022-02-09                English
</code>```

Now for the classes table!

```<code>select * from classes

 class_name             class_started             class_held_date
   Math                   2022-02-05                2022-02-06
  English                 2022-02-05                2022-02-06
   Math                   2022-02-05                2022-02-07
  English                 2022-02-05                2022-02-07
   Math                   2022-02-05                2022-02-09
  English                 2022-02-05                2022-02-09
</code>```

When I do a left-join on the two tables:

```<code>select s.*,c.class_started,c.class_held_date from students as s
left join classes as c on s.class_name = c.class_name and s.student_showed = c.class_held_date

student_name      student_showed      class_name     class_started     class_held_date
  Jeter             2022-02-05          Math
  Jeter             2022-02-06          Math           2022-02-05        2022-02-06
  Jeter             2022-02-07          Math           2022-02-05        2022-02-07
  Jeter             2022-02-08          Math
  Jeter             2022-02-09          Math           2022-02-05        2022-02-09
  Jeter             2022-02-05          English
  Jeter             2022-02-06          English        2022-02-05        2022-02-06
  Jeter             2022-02-07          English        2022-02-05        2022-02-07
  Jeter             2022-02-08          English
  Jeter             2022-02-09          English        2022-02-05        2022-02-09
  Soriano           2022-02-05          Math
  Soriano           2022-02-06          Math           2022-02-05        2022-02-06
  Soriano           2022-02-07          Math           2022-02-05        2022-02-07
  Soriano           2022-02-08          Math
  Soriano           2022-02-09          Math           2022-02-05        2022-02-09
  Soriano           2022-02-05          English
  Soriano           2022-02-06          English        2022-02-05        2022-02-06
  Soriano           2022-02-07          English        2022-02-05        2022-02-07
  Soriano           2022-02-08          English
  Soriano           2022-02-09          English        2022-02-05        2022-02-09
</code>```

Since class_started in the classes tables is a static field, I want it to always show the value rather than show NULLS. I need to show a left join since the student should get credit for showing up to the classes regardless if the classes were held or not.

Can someone please provide insights here.

Result Requested:

```<code>student_name      student_showed      class_name     class_started     class_held_date
  Jeter             2022-02-05          Math           2022-02-05
  Jeter             2022-02-06          Math           2022-02-05        2022-02-06
  Jeter             2022-02-07          Math           2022-02-05        2022-02-07
  Jeter             2022-02-08          Math           2022-02-05
  Jeter             2022-02-09          Math           2022-02-05        2022-02-09
  Jeter             2022-02-05          English        2022-02-05
  Jeter             2022-02-06          English        2022-02-05        2022-02-06
  Jeter             2022-02-07          English        2022-02-05        2022-02-07
  Jeter             2022-02-08          English        2022-02-05
  Jeter             2022-02-09          English        2022-02-05        2022-02-09
  Soriano           2022-02-05          Math           2022-02-05
  Soriano           2022-02-06          Math           2022-02-05        2022-02-06
  Soriano           2022-02-07          Math           2022-02-05        2022-02-07
  Soriano           2022-02-08          Math           2022-02-05
  Soriano           2022-02-09          Math           2022-02-05        2022-02-09
  Soriano           2022-02-05          English        2022-02-05
  Soriano           2022-02-06          English        2022-02-05        2022-02-06
  Soriano           2022-02-07          English        2022-02-05        2022-02-07
  Soriano           2022-02-08          English        2022-02-05
  Soriano           2022-02-09          English        2022-02-05        2022-02-09
</code>```

答:
You should be able to handle this using windowing.

```<code>select
student_name,
...
min (c.class_started) over (partition by student_name,class_name)
from
students as s
left join classes as c on s.class_name = c.class_name and s.student_showed = c.class_held_date
</code>```

SQL Fiddle

Body:
Let's say I have these two tables. The students table stores data about the student showing up to the respected class on a specific date. On the contrary, the classes table shows when the respected class started and when was the class last held.

How can I achieve this in postgreSQL 11.

select * from students

student_name          student_showed           class_name
  Jeter                 2022-02-05                Math
  Jeter                 2022-02-06                Math
  Jeter                 2022-02-07                Math
  Jeter                 2022-02-08                Math
  Jeter                 2022-02-09                Math
  Jeter                 2022-02-05                English
  Jeter                 2022-02-06                English
  Jeter                 2022-02-07                English
  Jeter                 2022-02-08                English
  Jeter                 2022-02-09                English
  Soriano               2022-02-05                Math
  Soriano               2022-02-06                Math
  Soriano               2022-02-07                Math
  Soriano               2022-02-08                Math
  Soriano               2022-02-09                Math
  Soriano               2022-02-05                English
  Soriano               2022-02-06                English
  Soriano               2022-02-07                English
  Soriano               2022-02-08                English
  Soriano               2022-02-09                English

Now for the classes table!

select * from classes

 class_name             class_started             class_held_date
   Math                   2022-02-05                2022-02-06
  English                 2022-02-05                2022-02-06
   Math                   2022-02-05                2022-02-07
  English                 2022-02-05                2022-02-07
   Math                   2022-02-05                2022-02-09
  English                 2022-02-05                2022-02-09

When I do a left-join on the two tables:

select s.*,c.class_started,c.class_held_date from students as s
left join classes as c on s.class_name = c.class_name and s.student_showed = c.class_held_date

student_name      student_showed      class_name     class_started     class_held_date
  Jeter             2022-02-05          Math
  Jeter             2022-02-06          Math           2022-02-05        2022-02-06
  Jeter             2022-02-07          Math           2022-02-05        2022-02-07
  Jeter             2022-02-08          Math
  Jeter             2022-02-09          Math           2022-02-05        2022-02-09
  Jeter             2022-02-05          English
  Jeter             2022-02-06          English        2022-02-05        2022-02-06
  Jeter             2022-02-07          English        2022-02-05        2022-02-07
  Jeter             2022-02-08          English
  Jeter             2022-02-09          English        2022-02-05        2022-02-09
  Soriano           2022-02-05          Math
  Soriano           2022-02-06          Math           2022-02-05        2022-02-06
  Soriano           2022-02-07          Math           2022-02-05        2022-02-07
  Soriano           2022-02-08          Math
  Soriano           2022-02-09          Math           2022-02-05        2022-02-09
  Soriano           2022-02-05          English
  Soriano           2022-02-06          English        2022-02-05        2022-02-06
  Soriano           2022-02-07          English        2022-02-05        2022-02-07
  Soriano           2022-02-08          English
  Soriano           2022-02-09          English        2022-02-05        2022-02-09

Since class_started in the classes tables is a static field, I want it to always show the value rather than show NULLS. I need to show a left join since the student should get credit for showing up to the classes regardless if the classes were held or not.

Can someone please provide insights here.

Result Requested:

student_name      student_showed      class_name     class_started     class_held_date
  Jeter             2022-02-05          Math           2022-02-05
  Jeter             2022-02-06          Math           2022-02-05        2022-02-06
  Jeter             2022-02-07          Math           2022-02-05        2022-02-07
  Jeter             2022-02-08          Math           2022-02-05
  Jeter             2022-02-09          Math           2022-02-05        2022-02-09
  Jeter             2022-02-05          English        2022-02-05
  Jeter             2022-02-06          English        2022-02-05        2022-02-06
  Jeter             2022-02-07          English        2022-02-05        2022-02-07
  Jeter             2022-02-08          English        2022-02-05
  Jeter             2022-02-09          English        2022-02-05        2022-02-09
  Soriano           2022-02-05          Math           2022-02-05
  Soriano           2022-02-06          Math           2022-02-05        2022-02-06
  Soriano           2022-02-07          Math           2022-02-05        2022-02-07
  Soriano           2022-02-08          Math           2022-02-05
  Soriano           2022-02-09          Math           2022-02-05        2022-02-09
  Soriano           2022-02-05          English        2022-02-05
  Soriano           2022-02-06          English        2022-02-05        2022-02-06
  Soriano           2022-02-07          English        2022-02-05        2022-02-07
  Soriano           2022-02-08          English        2022-02-05
  Soriano           2022-02-09          English        2022-02-05        2022-02-09

Body:
You should be able to handle this using windowing.

select
student_name,
...
min (c.class_started) over (partition by student_name,class_name)
from
students as s
left join classes as c on s.class_name = c.class_name and s.student_showed = c.class_held_date

SQL Fiddle


问:
power bi measure with 2 conditions 2 calculate
I am trying to create a measure which will calculate the Total Project Revenue
while I have 2 different projects. For each project there is a different calculation:
for Hourly project the calculation should be: Income * BillHours
for Retainer project the calculation should be: Income*TotalWorkinghours

I wrote the below DAX:

```<code>    enter code here : Total project revenue = IF(max(DimProjects[ProjectType])="Hours",
max(FactWorkingHours[Income])[BillHours],max(FactWorkingHours[Income])*
[Total Working Hours])
</code>```

the rows are calculated correctly but the total in the table is wrong
what should I fix in DAX so the total of all raw will correct as well.
The total Revenue should be 126,403.33

Thank you in advance
you can find here the table with the results

答:
It's hard to say exactly what your measure is doing because, as written here, that is not a valid measure. I pasted it into the DAX Formatter, which I would recommend for formatting and pasting here into code blocks, and the measure was invalid. It would also be helpful to post the other measures this measure references, eg. [Bill Hours] and [Income Hours].

That being said, I think I can kind of tell what's going on. Your total is probably wrong because the filter context at the total level is being based of the condition where:

MAX ( DimProjects[ProjectType] ) = "Retainer" (or some other value not in your shared snippet)

That is because when you consider the MAX of a string, the higher alphabetical order is considered. Therefore, "Retainer" > "Hours". So at the total level, your table is outputting—more than likely, I can't be certain without more information—the false condition of your measure:

MAX ( FactWorkingHours[Income] ) * [Total Working Hours])

There is a better way to handle your intended outcome. IF statements, in the way you are attempting to use it, are rarely used in a calculated measure. You may be better off trying a calculated column without using the MAX functions. Again, I can't give an exact code recommendation without more context. Hope that sends you in the right direction!

Body:
I am trying to create a measure which will calculate the Total Project Revenue
while I have 2 different projects. For each project there is a different calculation:
for Hourly project the calculation should be: Income * BillHours
for Retainer project the calculation should be: Income*TotalWorkinghours

I wrote the below DAX:

    enter code here : Total project revenue = IF(max(DimProjects[ProjectType])="Hours",
max(FactWorkingHours[Income])[BillHours],max(FactWorkingHours[Income])*
[Total Working Hours])

the rows are calculated correctly but the total in the table is wrong
what should I fix in DAX so the total of all raw will correct as well.
The total Revenue should be 126,403.33

Thank you in advance
you can find here the table with the results


问:
How do I get this apple script to pop up a dialog?
The following apple script times out. How do I get it to work?

This runs from inside a bash script and it's supposed to pop up a dialog. It works fine on one mac. But it times out on my computer. However, it start to work after I run the script once inside Apple's Script Editor. Also, if I run the Script Editor version before the script timeout, the dialog pops up! Is this a permissions issue? What is going on and how do I fix it?

Bash Script:

```<code>osascript <<EOT
    tell app "System Events"
        text returned of (display dialog "Enter value:" default answer "default" buttons {"OK"} default button 1 with title "Type A Value")
    end tell
EOT
</code>```

Error:

```<code>46:159: execution error: System Events got an error: AppleEvent timed out. (-1712)
</code>```

答:
The display dialog command is not a System Events command.  It is a Standard Additions command, therefore there is no need for a tell block

Also, inserting an activate command before the display dialog command will ensure the dialog window will appear on top of any currently opened programs or windows.

Try this...

```<code>osascript <<EOT
    activate
    text returned of (display dialog "Enter value:" default answer "default" buttons {"OK"} default button 1 with title "Type A Value")
EOT
</code>```

Body:
The following apple script times out. How do I get it to work?

This runs from inside a bash script and it's supposed to pop up a dialog. It works fine on one mac. But it times out on my computer. However, it start to work after I run the script once inside Apple's Script Editor. Also, if I run the Script Editor version before the script timeout, the dialog pops up! Is this a permissions issue? What is going on and how do I fix it?

Bash Script:

osascript <<EOT
    tell app "System Events"
        text returned of (display dialog "Enter value:" default answer "default" buttons {"OK"} default button 1 with title "Type A Value")
    end tell
EOT

Error:

46:159: execution error: System Events got an error: AppleEvent timed out. (-1712)

Body:
The display dialog command is not a System Events command.  It is a Standard Additions command, therefore there is no need for a tell block

Also, inserting an activate command before the display dialog command will ensure the dialog window will appear on top of any currently opened programs or windows.

Try this...

osascript <<EOT
    activate
    text returned of (display dialog "Enter value:" default answer "default" buttons {"OK"} default button 1 with title "Type A Value")
EOT


问:
RestSharp - 'Init-only property or indexer...' error when using OnBeforeDeserialization
I'm currently trying to build a little API, where I'm utilizing RestSharp. I have a method which should return a list of objects. However, I keep getting the following error when setting 'OnBeforeDeserialization' on my RestRequest:

'Init-only property or indexer 'RestResponseBase.ContentType' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or and 'init' accessor.

Here's my code:

```<code>    public async Task<IEnumerable<MyObject>> GetMyObject()
    {
        var request = new RestRequest("/test", Method.Get);
        request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
        var response = await _client.GetAsync<List<MyObject>>(request);
        return response;
    }
</code>```

To my understanding, I am setting the init-property in an object initializer here: { resp.ContentType = "application/json"; }; What am I doing wrong?

答:
RestResponse.OnBeforeDeserialization is type of Action<RestResponse>, which essentially calls your callback with the a parameter of type RestResponse; it not initializing it. Since ContentType is an init-only setter, you can only set it when instantiating the object (you can try it for yourself by calling new RestResponse { ContentType = "application/json" };.

Moreover, I'm not sure why you are trying to explicitly set the content type for the response; this is something that the server you are talking to does. RestSharp supports both XML and JSON out of the box, for both requests and response deserialization. You can read more here.

Body:
I'm currently trying to build a little API, where I'm utilizing RestSharp. I have a method which should return a list of objects. However, I keep getting the following error when setting 'OnBeforeDeserialization' on my RestRequest:

'Init-only property or indexer 'RestResponseBase.ContentType' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or and 'init' accessor.

Here's my code:

    public async Task<IEnumerable<MyObject>> GetMyObject()
    {
        var request = new RestRequest("/test", Method.Get);
        request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
        var response = await _client.GetAsync<List<MyObject>>(request);
        return response;
    }

To my understanding, I am setting the init-property in an object initializer here: { resp.ContentType = "application/json"; }; What am I doing wrong?


问:
Select next int value in a column excluding an array of values
I need to find a way to get the next free 'Id' of a table, but the result should consider an array.

I'm trying something like this, but without success.

```<code>SELECT
    COALESCE(MAX(idTable), 0) + 1 AS maxId
FROM Table
WHERE someColumn = 123
HAVING COALESCE(MAX(idTable), 0) + 1 NOT IN (777, 778, 779)
</code>```

This code will return to me the value 777, but I need the result to be 780, cause its the next 'Id' not in the array (777, 778, 779)

Note that none of the values 777, 778, 779, 780 exists in this column

答:
You can try statically adding the values you want to exclude using UNION ALL.

```<code>SELECT
    COALESCE(MAX(idTable), 0) + 1 as maxId
FROM (
  SELECT idTable FROM [Table]
  UNION ALL
  SELECT idTable FROM (VALUES (777, 778, 779)) X (idTable)
) X
WHERE someColumn = 123;
</code>```

If this code could ever be run concurrently you would need to consider a table locking strategy.

Body:
I need to find a way to get the next free 'Id' of a table, but the result should consider an array.

I'm trying something like this, but without success.

SELECT
    COALESCE(MAX(idTable), 0) + 1 AS maxId
FROM Table
WHERE someColumn = 123
HAVING COALESCE(MAX(idTable), 0) + 1 NOT IN (777, 778, 779)

This code will return to me the value 777, but I need the result to be 780, cause its the next 'Id' not in the array (777, 778, 779)

Note that none of the values 777, 778, 779, 780 exists in this column

Body:
You can try statically adding the values you want to exclude using UNION ALL.

SELECT
    COALESCE(MAX(idTable), 0) + 1 as maxId
FROM (
  SELECT idTable FROM [Table]
  UNION ALL
  SELECT idTable FROM (VALUES (777, 778, 779)) X (idTable)
) X
WHERE someColumn = 123;

If this code could ever be run concurrently you would need to consider a table locking strategy.


问:
Type mismatch: inferred type is Alignment.Vertical but FiniteAnimationSpec<IntSize> was expected
We had the following code, which was working just fine in Compose version 1.0.5.

@ExperimentalAnimationApi
@ExperimentalMaterialApi
@Composable
private fun AnimateContent(dismissState: DismissState, content: @Composable () -> Unit) {
    AnimatedVisibility(
        visible = !dismissState.isDismissed(DismissDirection.StartToEnd)
                && !dismissState.isDismissed(DismissDirection.EndToStart),
        enter = fadeIn() + expandVertically(Alignment.Top),  // Compile error
        exit = fadeOut() + shrinkVertically(Alignment.Top)   // on these lines
    ) {
        content()
    }
}
```

However, after upgrading to 1.1.0-rc03, we are getting the following build time error:

Type mismatch: inferred type is Alignment.Vertical but
FiniteAnimationSpec was expected

I've researched online, but unfortunately there is close to no information on what this error is or how to fix it.

答:
Looks like they changed the order of arguments of expandVertically and shrinkVertically, the first argument is now animationSpec and direction is second, just use named argument:

expandVertically(expandFrom = Alignment.Top)
shrinkVertically(shrinkTowards = Alignment.Top)
```

Body:
We had the following code, which was working just fine in Compose version 1.0.5.

@ExperimentalAnimationApi
@ExperimentalMaterialApi
@Composable
private fun AnimateContent(dismissState: DismissState, content: @Composable () -> Unit) {
    AnimatedVisibility(
        visible = !dismissState.isDismissed(DismissDirection.StartToEnd)
                && !dismissState.isDismissed(DismissDirection.EndToStart),
        enter = fadeIn() + expandVertically(Alignment.Top),  // Compile error
        exit = fadeOut() + shrinkVertically(Alignment.Top)   // on these lines
    ) {
        content()
    }
}

However, after upgrading to 1.1.0-rc03, we are getting the following build time error:

Type mismatch: inferred type is Alignment.Vertical but
FiniteAnimationSpec was expected

I've researched online, but unfortunately there is close to no information on what this error is or how to fix it.


问:
jquery insertBefore duplication issue
Using insertBerfore to move an item above another where it appears in many nested DIVs... issue is - its duplicating the item that is being move so I have multiple versions of it... What am I doing wrong here?

I've tried using an each loop and that has the same problem...

I just need the DATE to sit above the TITLE HERE

( function($) {

   function journalIndexFeedItemMetaSwapper() {
    $(".journalIndexPostGridFeed .nectar-post-grid .nectar-post-grid-item .item-main span.meta-date").insertBefore(".journalIndexPostGridFeed .nectar-post-grid .nectar-post-grid-item .item-main h3.post-heading");
  }

$(window).load(function() { setTimeout(function(){ journalIndexFeedItemMetaSwapper(); },1000); });

})(jQuery);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="journalIndexPostGridFeed">
<div class="nectar-post-grid">
<div class="nectar-post-grid-item">
<div class="item-main">
<h3 class="post-heading">TITLE HERE</h3>
<span class="meta-date">DATE</span>
</div>
</div>
</div>
</div>

<div class="journalIndexPostGridFeed">
<div class="nectar-post-grid">
<div class="nectar-post-grid-item">
<div class="item-main">
<h3 class="post-heading">TITLE HERE</h3>
<span class="meta-date">DATE</span>
</div>
</div>
</div>
</div>

<div class="journalIndexPostGridFeed">
<div class="nectar-post-grid">
<div class="nectar-post-grid-item">
<div class="item-main">
<h3 class="post-heading">TITLE HERE</h3>
<span class="meta-date">DATE</span>
</div>
</div>
</div>
</div>

<div class="journalIndexPostGridFeed">
<div class="nectar-post-grid">
<div class="nectar-post-grid-item">
<div class="item-main">
<h3 class="post-heading">TITLE HERE</h3>
<span class="meta-date">DATE</span>
</div>
</div>
</div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" type="text/javascript"></script></code>```

答:
From the documentation:

If there is more than one target element, however, cloned copies of the inserted element will be created for each target after the first, and that new set (the original element plus clones) is returned.

Since there are multiple .journalIndexPostGridFeed .nectar-post-grid .nectar-post-grid-item .item-main h3.post-heading elements, the source elements are duplicated for each of them.

I suspect what you really want is to insert each source element before the target in the same DIV, not insert all the sources before all the targets.

(function($) {

  function journalIndexFeedItemMetaSwapper() {
    $(".journalIndexPostGridFeed .nectar-post-grid .nectar-post-grid-item .item-main span.meta-date").each(function() {
      $(this).insertBefore($(this).siblings("h3.post-heading"));
    });
  }

  $(window).load(function() {
    setTimeout(function() {
      journalIndexFeedItemMetaSwapper();
    }, 1000);
  });

})(jQuery);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="journalIndexPostGridFeed">
  <div class="nectar-post-grid">
    <div class="nectar-post-grid-item">
      <div class="item-main">
        <h3 class="post-heading">TITLE HERE</h3>
        <span class="meta-date">DATE</span>
      </div>
    </div>
  </div>
</div>

<div class="journalIndexPostGridFeed">
  <div class="nectar-post-grid">
    <div class="nectar-post-grid-item">
      <div class="item-main">
        <h3 class="post-heading">TITLE HERE</h3>
        <span class="meta-date">DATE</span>
      </div>
    </div>
  </div>
</div>

<div class="journalIndexPostGridFeed">
  <div class="nectar-post-grid">
    <div class="nectar-post-grid-item">
      <div class="item-main">
        <h3 class="post-heading">TITLE HERE</h3>
        <span class="meta-date">DATE</span>
      </div>
    </div>
  </div>
</div>

<div class="journalIndexPostGridFeed">
  <div class="nectar-post-grid">
    <div class="nectar-post-grid-item">
      <div class="item-main">
        <h3 class="post-heading">TITLE HERE</h3>
        <span class="meta-date">DATE</span>
      </div>
    </div>
  </div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" type="text/javascript"></script></code>```

Title: jquery insertBefore duplication issue

Body:
Using insertBerfore to move an item above another where it appears in many nested DIVs... issue is - its duplicating the item that is being move so I have multiple versions of it... What am I doing wrong here?

I've tried using an each loop and that has the same problem...

I just need the DATE to sit above the TITLE HERE

( function($) {

   function journalIndexFeedItemMetaSwapper() {
    $(".journalIndexPostGridFeed .nectar-post-grid .nectar-post-grid-item .item-main span.meta-date").insertBefore(".journalIndexPostGridFeed .nectar-post-grid .nectar-post-grid-item .item-main h3.post-heading");
  }

$(window).load(function() { setTimeout(function(){ journalIndexFeedItemMetaSwapper(); },1000); });

})(jQuery);

TITLE HERE

DATE

TITLE HERE

DATE

TITLE HERE

DATE

TITLE HERE

DATE

Body:
From the documentation:

If there is more than one target element, however, cloned copies of the inserted element will be created for each target after the first, and that new set (the original element plus clones) is returned.

Since there are multiple .journalIndexPostGridFeed .nectar-post-grid .nectar-post-grid-item .item-main h3.post-heading elements, the source elements are duplicated for each of them.

I suspect what you really want is to insert each source element before the target in the same DIV, not insert all the sources before all the targets.

(function($) {

  function journalIndexFeedItemMetaSwapper() {
    $(".journalIndexPostGridFeed .nectar-post-grid .nectar-post-grid-item .item-main span.meta-date").each(function() {
      $(this).insertBefore($(this).siblings("h3.post-heading"));
    });
  }

  $(window).load(function() {
    setTimeout(function() {
      journalIndexFeedItemMetaSwapper();
    }, 1000);
  });

})(jQuery);

<div class="journalIndexPostGridFeed">
  <div class="nectar-post-grid">
    <div class="nectar-post-grid-item">
      <div class="item-main">
        <h3 class="post-heading">TITLE HERE</h3>
        <span class="meta-date">DATE</span>
      </div>
    </div>
  </div>
</div>

<div class="journalIndexPostGridFeed">
  <div class="nectar-post-grid">
    <div class="nectar-post-grid-item">
      <div class="item-main">
        <h3 class="post-heading">TITLE HERE</h3>
        <span class="meta-date">DATE</span>
      </div>
    </div>
  </div>
</div>

<div class="journalIndexPostGridFeed">
  <div class="nectar-post-grid">
    <div class="nectar-post-grid-item">
      <div class="item-main">
        <h3 class="post-heading">TITLE HERE</h3>
        <span class="meta-date">DATE</span>
      </div>
    </div>
  </div>
</div>

<div class="journalIndexPostGridFeed">
  <div class="nectar-post-grid">
    <div class="nectar-post-grid-item">
      <div class="item-main">
        <h3 class="post-heading">TITLE HERE</h3>
        <span class="meta-date">DATE</span>
      </div>
    </div>
  </div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" type="text/javascript"></script>


问:
how to check if a php file is obfuscated?
is there any way we can check if a php file has been obfuscated, using php? I was thinking regex maybe (for instance ioncube's encoded file contains a very long alphabet string, etc.</p>

答:
Often, obsfuscators initialize very large arrays to translate variables into less meaningful names (eg. see obsfucator article

One technique may be to search for these super-large arrays, close to the top of the class/file etc. You may be able to hook xdebug up to examine/look for these. The whole thing of course depends on the obsfuscation technique used. Check the source code, there may be patterns they've used that you can search on.


问:
How to convert dates of a column from one format to another using pandas in python?
I am trying to convert date from "16-Dec-21" format to "2021-12-01" format using Pandas in Python in a CSV file. Here's the table:

Date
ID

16-Dec-21
5665

11-Jan-22
5613

04-Feb-22
5680

Here's my code:

```<code>ds_com['Date'] = pd.to_datetime(ds_com['Date']).dt.strftime('%Y-%m-%d')
</code>```

I've also tried

```<code>ds_com['Date'] = ds_com['Date'].dt.strftime('%Y-%m-%d')
</code>```

But it also didn't work.

The new table should look like this:

Date
ID

2021-12-16
5665

2022-01-11
5613

2022-02-04
5680

The table has hundreds of rows.

The current output shows as this when I open the ds_com.csv file in Excel:

Date
ID

12/16/21
5665

1/11/22
5613

2/4/22
5680

The output shows correctly for

```<code>print(ds_com['Date'][1])
</code>```

Thank you.

答:
You could try this. It would cause excel to not auto format</p>
```<code>ds_com['Date'] = pd.to_datetime(ds_com['Date']).dt.strftime('="%Y-%m-%d"')
</code>```

Body:
I am trying to convert date from "16-Dec-21" format to "2021-12-01" format using Pandas in Python in a CSV file. Here's the table:

Date
ID

16-Dec-21
5665

11-Jan-22
5613

04-Feb-22
5680

Here's my code:

ds_com['Date'] = pd.to_datetime(ds_com['Date']).dt.strftime('%Y-%m-%d')

I've also tried

ds_com['Date'] = ds_com['Date'].dt.strftime('%Y-%m-%d')

But it also didn't work.

The new table should look like this:

Date
ID

2021-12-16
5665

2022-01-11
5613

2022-02-04
5680

The table has hundreds of rows.

The current output shows as this when I open the ds_com.csv file in Excel:

Date
ID

12/16/21
5665

1/11/22
5613

2/4/22
5680

The output shows correctly for

print(ds_com['Date'][1])

Thank you.

Body:
You could try this. It would cause excel to not auto format

ds_com['Date'] = pd.to_datetime(ds_com['Date']).dt.strftime('="%Y-%m-%d"')


问:
How to keep user logged in using Firebase in Swift?
I'm kinda new to Swift programming and I can't find any tutorial on how to keep users logged in after closing the app.

I already did log in and sign up functionality in my app, but what are my steps to keep users logged after closing the app?

答: You can also use Userdefault to persist login state, such that upon successful login, you would persist a value lets call it isLoggedIn which is of type Bool and then all you need to do is to check for isLoggedIn upon each launch of your app, if true, then user is loggedin, you show your landing page otherwise you show your login screen.</p>


问:
C, 2D Array, How to find specific number in all 8 directions
You are allowed to enter only 0 and 1 as values in the arrays. Then in place of all elements having a value of 0, enter the number of elements with a value of 1 around that element in all eight directions. And on the end print the 2d array and the values with 1 change to *.

Here is an example how it's supposed to look like:

Here is my code

```<code>#include <stdio.h>
#include <stdlib.h>

int main()
{
int n,m;
scanf("%d%d", &n, &m);
int a[n][m];
for(int i=0; i<n; i++){
    for(int j=0; j<m; j++){
        scanf("%d", &a[i][j]);
        if(a[i][j]==1){
            a[i][j]=9;
        }
    }
}
for(int i=0; i<n; i++){
    for(int j=0; j<m; j++){
        int counter=0;
        if(a[i][j]==9){
            printf("*\t");
        }else if(a[i][j]==0){
        if(a[i+1][j+1]==9 && i!=n && j!=m) counter++;
        if(a[i-1][j-1]==9 && i!=0 && j!=0) counter++;
        if(a[i+1][j-1]==9 && i!=n && j!=0) counter++;
        if(a[i-1][j+1]==9 && i!=0 && j!=m) counter++;
        if(a[i][j+1]==9 && j!=m) counter++;
        if(a[i][j-1]==9 && j!=0) counter++;
        if(a[i+1][j]==9 && i!=n) counter++;
        if(a[i-1][j]==9 && i!=0) counter++;
        a[i][j]=counter;
        counter=0;
        printf("%d\t", a[i][j]);
        }
    }
    printf("\n");
 }

return 0;
}
</code>```

答:
You have UB (undefined behavior).

With (e.g.):

```<code>if (a[i + 1][j + 1] == 9 && i != n && j != m)
</code>```

Then, a is always fetched, even if i or j is out of range.

To fix this, reorder the terms:

```<code>if (i != n && j != m && a[i + 1][j + 1] == 9)
</code>```

Now, if either i or j is out of range, then the if will be "short circuited": (i.e. _short circuit evaluation) and the a value will not be fetched.

But, your program output is incorrect. You're coding everything out longhand. It makes it hard to debug (i.e. which lines have a bug).

What wasn't explicitly described was that you are summing the non-zero values in a 3x3 kernal around a given zero point.

The hardcoding doesn't scale too well. Suppose the kernal had to be 100x100. Would we code up 10,000 lines of code?

It's much easier to debug if we refactor to use for loops. And, to use more descriptive names instead of i/j/m/n:

```<code>n       hgt
m       wid
i       y*
j       x*
</code>```

Here is the code:

```<code>#include <stdio.h>
#include <stdlib.h>

int
main(int argc,char **argv)
{
    int hgt, wid;
    int counter;
    FILE *xf;

    --argc;
    ++argv;

    if (argc > 0)
        xf = fopen(*argv,"r");
    else
        xf = stdin;
    if (xf == NULL) {
        perror(*argv);
        exit(1);
    }

    fscanf(xf,"%d%d", &hgt, &wid);
    int a[hgt][wid];

    for (int ycur = 0; ycur < hgt; ycur++) {
        for (int xcur = 0; xcur < wid; xcur++) {
            int val;
            fscanf(xf,"%d", &val);

            if (val == 1)
                val = 9;

            a[ycur][xcur] = val;
        }
    }

    for (int yctr = 0; yctr < hgt; yctr++) {
        for (int xctr = 0; xctr < wid; xctr++) {
            if (a[yctr][xctr] == 9) {
                printf("*\t");
                continue;
            }

            counter = 0;
            for (int yoff = -1; yoff <= 1; yoff++) {
                int ycur = yctr + yoff;

                if (ycur < 0)
                    continue;
                if (ycur >= hgt)
                    continue;

                for (int xoff = -1; xoff <= 1; xoff++) {
                    int xcur = xctr + xoff;

                    if (xcur < 0)
                        continue;
                    if (xcur >= wid)
                        continue;

                    counter += (a[ycur][xcur] == 9);
                }
            }

            printf("%d\t",counter);
        }

        printf("\n");
    }

    return 0;
}
</code>```

Here  is the program output for your sample input:

```<code>*   1   1   2   *
2   2   2   *   3
*   1   2   *   2
</code>```

Body:
You are allowed to enter only 0 and 1 as values in the arrays. Then in place of all elements having a value of 0, enter the number of elements with a value of 1 around that element in all eight directions. And on the end print the 2d array and the values with 1 change to *.

Here is an example how it's supposed to look like:

Here is my code

#include <stdio.h>
#include <stdlib.h>

int main()
{
int n,m;
scanf("%d%d", &n, &m);
int a[n][m];
for(int i=0; i<n; i++){
    for(int j=0; j<m; j++){
        scanf("%d", &a[i][j]);
        if(a[i][j]==1){
            a[i][j]=9;
        }
    }
}
for(int i=0; i<n; i++){
    for(int j=0; j<m; j++){
        int counter=0;
        if(a[i][j]==9){
            printf("*\t");
        }else if(a[i][j]==0){
        if(a[i+1][j+1]==9 && i!=n && j!=m) counter++;
        if(a[i-1][j-1]==9 && i!=0 && j!=0) counter++;
        if(a[i+1][j-1]==9 && i!=n && j!=0) counter++;
        if(a[i-1][j+1]==9 && i!=0 && j!=m) counter++;
        if(a[i][j+1]==9 && j!=m) counter++;
        if(a[i][j-1]==9 && j!=0) counter++;
        if(a[i+1][j]==9 && i!=n) counter++;
        if(a[i-1][j]==9 && i!=0) counter++;
        a[i][j]=counter;
        counter=0;
        printf("%d\t", a[i][j]);
        }
    }
    printf("\n");
 }

return 0;
}

Body:
You have UB (undefined behavior).

With (e.g.):

if (a[i + 1][j + 1] == 9 && i != n && j != m)

Then, a is always fetched, even if i or j is out of range.

To fix this, reorder the terms:

if (i != n && j != m && a[i + 1][j + 1] == 9)

Now, if either i or j is out of range, then the if will be "short circuited": (i.e. _short circuit evaluation) and the a value will not be fetched.

But, your program output is incorrect. You're coding everything out longhand. It makes it hard to debug (i.e. which lines have a bug).

What wasn't explicitly described was that you are summing the non-zero values in a 3x3 kernal around a given zero point.

The hardcoding doesn't scale too well. Suppose the kernal had to be 100x100. Would we code up 10,000 lines of code?

It's much easier to debug if we refactor to use for loops. And, to use more descriptive names instead of i/j/m/n:

n       hgt
m       wid
i       y*
j       x*

Here is the code:

#include <stdio.h>
#include <stdlib.h>

int
main(int argc,char **argv)
{
    int hgt, wid;
    int counter;
    FILE *xf;

    --argc;
    ++argv;

    if (argc > 0)
        xf = fopen(*argv,"r");
    else
        xf = stdin;
    if (xf == NULL) {
        perror(*argv);
        exit(1);
    }

    fscanf(xf,"%d%d", &hgt, &wid);
    int a[hgt][wid];

    for (int ycur = 0; ycur < hgt; ycur++) {
        for (int xcur = 0; xcur < wid; xcur++) {
            int val;
            fscanf(xf,"%d", &val);

            if (val == 1)
                val = 9;

            a[ycur][xcur] = val;
        }
    }

    for (int yctr = 0; yctr < hgt; yctr++) {
        for (int xctr = 0; xctr < wid; xctr++) {
            if (a[yctr][xctr] == 9) {
                printf("*\t");
                continue;
            }

            counter = 0;
            for (int yoff = -1; yoff <= 1; yoff++) {
                int ycur = yctr + yoff;

                if (ycur < 0)
                    continue;
                if (ycur >= hgt)
                    continue;

                for (int xoff = -1; xoff <= 1; xoff++) {
                    int xcur = xctr + xoff;

                    if (xcur < 0)
                        continue;
                    if (xcur >= wid)
                        continue;

                    counter += (a[ycur][xcur] == 9);
                }
            }

            printf("%d\t",counter);
        }

        printf("\n");
    }

    return 0;
}

Here  is the program output for your sample input:

*   1   1   2   *
2   2   2   *   3
*   1   2   *   2


问:
Pymodbus Basic Example
I have a simple modbus device (Ebyte MA02-XACX0440) that I'm trying to learn how to work with.  Using a third party GUI called serial port monitor (www.serial-port-monitor.org) I was able to more or less "stumble upon" the proper hexadecimal inputs needed to turn a discrete output on and then off.  I don't understand these terms of unit, address, coils, registers, etc. and how it all relates when it comes to the hexadecimal aspect.  To break down what I think I know so far (below is the hexadecimal string that will turn the first discrete output 'ON'):

0x20 0x05 0x00 0x00 0xFF 0x00 0x8A 0x8B

I know 0x20 is the device address in hex.  The documentation of the Ebyte device stipulates that the default hardware address is '31' and that the first software address is '1'.  If I understand that correctly, that means my first physical modbus device on the line has an address of '32', and if I were to put additional modbus devices on the line (either RS485 or TCP(?)) that the next device would be '33' and so on.

I know that the next byte 0x05 is 'write coil'.

I don't know what the next two bytes of '0x00' and '0x00' refer to.

The next two bytes are essentially on/off with '0xFF00' being 'ON' and 0x0000 being 'OFF'.

The final two bytes are simply the CRC checksum.

So up to this point I can get my DO (Discrete Output) to turn on, open up, and light up an LED as a simple proof of concept.  Now when I take that approach over to using the pymodbus library (my ultimate goal), things don't seem to line up.

I am able to connect to my device using the pymodbus REPL using

```<code>pymodbus.console serial --baudrate 9600 --bytesize 8 --parity N --stopbits 1 --port /dev/cu.usbserial-AH01F4EN
</code>```

I can confirm that the device is connected:

```<code>    ----------------------------------------------------------------------------
__________          _____             .___  __________              .__
\______   \___.__. /     \   ____   __| _/  \______   \ ____ ______ |  |
 |     ___<   |  |/  \ /  \ /  _ \ / __ |    |       _// __ \\____ \|  |
 |    |    \___  /    Y    (  <_> ) /_/ |    |    |   \  ___/|  |_> >  |__
 |____|    / ____\____|__  /\____/\____ | /\ |____|_  /\___  >   __/|____/
           \/            \/            \/ \/        \/     \/|__|
                                        v1.3.0 - [pymodbus, version 2.5.3]
----------------------------------------------------------------------------

> client.connect
true
</code>```

However when I attempt to run the same commands that I did earlier with serial monitor, I'm having difficulty mapping the hexadecimal values to the integers expected by the 'client.write_coil' command in pymodbus:

```<code>    > client.write_coil address=32 value=255 unit=1
{
    "original_function_code": "5 (0x5)",
    "error": "[Input/Output] No Response received from the remote unit/Unable to decode response"
}
</code>```

What is meant by address?  Is this a coil/register address or a device address?  For 'value' I put '255' as that would be all bits flipped to a '1' thinking that would be considered 'ON', and that a value of '0' would be off.  I also tried '65280', which is what 0xFF00 would be in decimal.  What is meant by a unit?  Is that the previous value I determined to be '32' to target the specific device on the line?  Or is it possible that the address would be '31' (which is the hardware address) and then the unit address is '1', making the overall 'address' 32?

EDIT:  This is shown in the 'help' of the client.write_coil command, but still doesn't help me figure out how to put the right pieces in the right places.  I don't know what a 'coil offset' is and how that relates to the discrete outputs.  I don't see anything mapped to the hexadecimal string that would be considered a 'coil offset'.  This is being provided for context to those that may know how to properly form the request.

I also sometimes get this error, and it's not consistent.  If it was a permissions issue one would think you'd get it every single time?  I don't think it makes sense to be either changing the permissions of the file indicated or to run the pymodbus server with root permissions.

```<code>    Unhandled exception in event loop:
  File "/usr/local/Cellar/python@3.9/3.9.7/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/events.py", line 80, in _run
    self._context.run(self._callback, *self._args)
  File "/usr/local/lib/python3.9/site-packages/prompt_toolkit/input/vt100.py", line 170, in callback_wrapper
    callback()
  File "/usr/local/lib/python3.9/site-packages/prompt_toolkit/application/application.py", line 708, in read_from_input
    self.key_processor.process_keys()
  File "/usr/local/lib/python3.9/site-packages/prompt_toolkit/key_binding/key_processor.py", line 271, in process_keys
    self._process_coroutine.send(key_press)
  File "/usr/local/lib/python3.9/site-packages/prompt_toolkit/key_binding/key_processor.py", line 186, in _process
    self._call_handler(matches[-1], key_sequence=buffer[:])
  File "/usr/local/lib/python3.9/site-packages/prompt_toolkit/key_binding/key_processor.py", line 321, in _call_handler
    handler.call(event)
  File "/usr/local/lib/python3.9/site-packages/prompt_toolkit/key_binding/key_bindings.py", line 124, in call
    result = self.handler(event)
  File "/usr/local/lib/python3.9/site-packages/prompt_toolkit/shortcuts/prompt.py", line 798, in _accept_input
    self.default_buffer.validate_and_handle()
  File "/usr/local/lib/python3.9/site-packages/prompt_toolkit/buffer.py", line 1877, in validate_and_handle
    self.append_to_history()
  File "/usr/local/lib/python3.9/site-packages/prompt_toolkit/buffer.py", line 1385, in append_to_history
    self.history.append_string(self.text)
  File "/usr/local/lib/python3.9/site-packages/prompt_toolkit/history.py", line 74, in append_string
    self.store_string(string)
  File "/usr/local/lib/python3.9/site-packages/prompt_toolkit/history.py", line 295, in store_string
    with open(self.filename, "ab") as f:

Exception [Errno 13] Permission denied: '../.pymodhis'
{ress ENTER to continue...
</code>```

答:
The Modbus specs describe the protocol and are worth a look. I use this online Modbus parser when I want to quickly parse a command; it's output for the string of bytes you give (20 05 00 00 FF 00 8A 8B) is:

Part of Data Package
Description
Value

20
Slave address
0x20 (32)

05
Function code
0x05 (5) - Write Single Coil

00 00
Output address
Physical: 0x0000 (0) Logical: 0x0001 (1)

FF 00
Output value
On

8A 8B
CRC
0x8A8B (35467)

The slave address indicates which device on the bus you wish to communicate with. This is set on the device (you cannot just add devices and expect things to work). The method used to set slave ID's differs from device to device (some have a utility to do this, some use switches or settings via their own user interface, and some have this hard coded). Your device (Ebyte MA02-XACX0440) defaults to 32 but this can be changed using the DIP switch on the device (this is covered in the manual).

You are using function code 5 - 'Write Single Coil'. Coils are bits so can be on or off.

The 'output address' indicates which coil on the device you wish to write to. The meaning of this address varies from device to device (generally there will be a table in the documentation that explains this). For your device this is in table 7.1 ("Register list") in the manual.

The value is what to write. For the 'write single coil' function this must be one of two values:

value
meaning

0x0000
Off

0xFF00
On

All other values are invalid. However many libraries (incluing pymodbus) will handle this detail for you allowing you to pass True/False.

Putting this all together you will need something like:

client.write_coil(0, True, unit=32)
```

Note: You have asked a lot of questions so this may not fully answer them but hopefully points you in the right direction (way too much info to put into the comments!).

Title: Pymodbus Basic Example

Body:
I have a simple modbus device (Ebyte MA02-XACX0440) that I'm trying to learn how to work with.  Using a third party GUI called serial port monitor (www.serial-port-monitor.org) I was able to more or less "stumble upon" the proper hexadecimal inputs needed to turn a discrete output on and then off.  I don't understand these terms of unit, address, coils, registers, etc. and how it all relates when it comes to the hexadecimal aspect.  To break down what I think I know so far (below is the hexadecimal string that will turn the first discrete output 'ON'):

0x20 0x05 0x00 0x00 0xFF 0x00 0x8A 0x8B

I know 0x20 is the device address in hex.  The documentation of the Ebyte device stipulates that the default hardware address is '31' and that the first software address is '1'.  If I understand that correctly, that means my first physical modbus device on the line has an address of '32', and if I were to put additional modbus devices on the line (either RS485 or TCP(?)) that the next device would be '33' and so on.

I know that the next byte 0x05 is 'write coil'.

I don't know what the next two bytes of '0x00' and '0x00' refer to.

The next two bytes are essentially on/off with '0xFF00' being 'ON' and 0x0000 being 'OFF'.

The final two bytes are simply the CRC checksum.

So up to this point I can get my DO (Discrete Output) to turn on, open up, and light up an LED as a simple proof of concept.  Now when I take that approach over to using the pymodbus library (my ultimate goal), things don't seem to line up.

I am able to connect to my device using the pymodbus REPL using

pymodbus.console serial --baudrate 9600 --bytesize 8 --parity N --stopbits 1 --port /dev/cu.usbserial-AH01F4EN

I can confirm that the device is connected:

    ----------------------------------------------------------------------------
__________          _____             .___  __________              .__
\______   \___.__. /     \   ____   __| _/  \______   \ ____ ______ |  |
 |     ___<   |  |/  \ /  \ /  _ \ / __ |    |       _// __ \\____ \|  |
 |    |    \___  /    Y    (  <_> ) /_/ |    |    |   \  ___/|  |_> >  |__
 |____|    / ____\____|__  /\____/\____ | /\ |____|_  /\___  >   __/|____/
           \/            \/            \/ \/        \/     \/|__|
                                        v1.3.0 - [pymodbus, version 2.5.3]
----------------------------------------------------------------------------

> client.connect
true

However when I attempt to run the same commands that I did earlier with serial monitor, I'm having difficulty mapping the hexadecimal values to the integers expected by the 'client.write_coil' command in pymodbus:

    > client.write_coil address=32 value=255 unit=1
{
    "original_function_code": "5 (0x5)",
    "error": "[Input/Output] No Response received from the remote unit/Unable to decode response"
}

What is meant by address?  Is this a coil/register address or a device address?  For 'value' I put '255' as that would be all bits flipped to a '1' thinking that would be considered 'ON', and that a value of '0' would be off.  I also tried '65280', which is what 0xFF00 would be in decimal.  What is meant by a unit?  Is that the previous value I determined to be '32' to target the specific device on the line?  Or is it possible that the address would be '31' (which is the hardware address) and then the unit address is '1', making the overall 'address' 32?

EDIT:  This is shown in the 'help' of the client.write_coil command, but still doesn't help me figure out how to put the right pieces in the right places.  I don't know what a 'coil offset' is and how that relates to the discrete outputs.  I don't see anything mapped to the hexadecimal string that would be considered a 'coil offset'.  This is being provided for context to those that may know how to properly form the request.

I also sometimes get this error, and it's not consistent.  If it was a permissions issue one would think you'd get it every single time?  I don't think it makes sense to be either changing the permissions of the file indicated or to run the pymodbus server with root permissions.

    Unhandled exception in event loop:
  File "/usr/local/Cellar/python@3.9/3.9.7/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/events.py", line 80, in _run
    self._context.run(self._callback, *self._args)
  File "/usr/local/lib/python3.9/site-packages/prompt_toolkit/input/vt100.py", line 170, in callback_wrapper
    callback()
  File "/usr/local/lib/python3.9/site-packages/prompt_toolkit/application/application.py", line 708, in read_from_input
    self.key_processor.process_keys()
  File "/usr/local/lib/python3.9/site-packages/prompt_toolkit/key_binding/key_processor.py", line 271, in process_keys
    self._process_coroutine.send(key_press)
  File "/usr/local/lib/python3.9/site-packages/prompt_toolkit/key_binding/key_processor.py", line 186, in _process
    self._call_handler(matches[-1], key_sequence=buffer[:])
  File "/usr/local/lib/python3.9/site-packages/prompt_toolkit/key_binding/key_processor.py", line 321, in _call_handler
    handler.call(event)
  File "/usr/local/lib/python3.9/site-packages/prompt_toolkit/key_binding/key_bindings.py", line 124, in call
    result = self.handler(event)
  File "/usr/local/lib/python3.9/site-packages/prompt_toolkit/shortcuts/prompt.py", line 798, in _accept_input
    self.default_buffer.validate_and_handle()
  File "/usr/local/lib/python3.9/site-packages/prompt_toolkit/buffer.py", line 1877, in validate_and_handle
    self.append_to_history()
  File "/usr/local/lib/python3.9/site-packages/prompt_toolkit/buffer.py", line 1385, in append_to_history
    self.history.append_string(self.text)
  File "/usr/local/lib/python3.9/site-packages/prompt_toolkit/history.py", line 74, in append_string
    self.store_string(string)
  File "/usr/local/lib/python3.9/site-packages/prompt_toolkit/history.py", line 295, in store_string
    with open(self.filename, "ab") as f:

Exception [Errno 13] Permission denied: '../.pymodhis'
{ress ENTER to continue...

Body:
The Modbus specs describe the protocol and are worth a look. I use this online Modbus parser when I want to quickly parse a command; it's output for the string of bytes you give (20 05 00 00 FF 00 8A 8B) is:

Part of Data Package
Description
Value

20
Slave address
0x20 (32)

05
Function code
0x05 (5) - Write Single Coil

00 00
Output address
Physical: 0x0000 (0) Logical: 0x0001 (1)

FF 00
Output value
On

8A 8B
CRC
0x8A8B (35467)

The slave address indicates which device on the bus you wish to communicate with. This is set on the device (you cannot just add devices and expect things to work). The method used to set slave ID's differs from device to device (some have a utility to do this, some use switches or settings via their own user interface, and some have this hard coded). Your device (Ebyte MA02-XACX0440) defaults to 32 but this can be changed using the DIP switch on the device (this is covered in the manual).

You are using function code 5 - 'Write Single Coil'. Coils are bits so can be on or off.

The 'output address' indicates which coil on the device you wish to write to. The meaning of this address varies from device to device (generally there will be a table in the documentation that explains this). For your device this is in table 7.1 ("Register list") in the manual.

The value is what to write. For the 'write single coil' function this must be one of two values:

value
meaning

0x0000
Off

0xFF00
On

All other values are invalid. However many libraries (incluing pymodbus) will handle this detail for you allowing you to pass True/False.

Putting this all together you will need something like:

client.write_coil(0, True, unit=32)

Note: You have asked a lot of questions so this may not fully answer them but hopefully points you in the right direction (way too much info to put into the comments!).


答:
Your code is finding all instances of X and inserting them before all instances of Y. There are probably more elegant methods, but an easy one is to use a loop and reference the relative objects for each using closest() and find()

(function($) {
  function journalIndexFeedItemMetaSwapper() {
    let el = ".journalIndexPostGridFeed .nectar-post-grid .nectar-post-grid-item .item-main span.meta-date"
    $(el).each(function() {
      $(this).insertBefore($(this).closest('.item-main').find("h3.post-heading"))
    });
  }

  $(window).load(function() {
    setTimeout(function() {
      journalIndexFeedItemMetaSwapper();
    }, 1000);
  });
})(jQuery);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="journalIndexPostGridFeed">
  <div class="nectar-post-grid">
    <div class="nectar-post-grid-item">
      <div class="item-main">
        <h3 class="post-heading">TITLE HERE</h3>
        <span class="meta-date">DATE</span>
      </div>
    </div>
  </div>
</div>

<div class="journalIndexPostGridFeed">
  <div class="nectar-post-grid">
    <div class="nectar-post-grid-item">
      <div class="item-main">
        <h3 class="post-heading">TITLE HERE</h3>
        <span class="meta-date">DATE</span>
      </div>
    </div>
  </div>
</div>

<div class="journalIndexPostGridFeed">
  <div class="nectar-post-grid">
    <div class="nectar-post-grid-item">
      <div class="item-main">
        <h3 class="post-heading">TITLE HERE</h3>
        <span class="meta-date">DATE</span>
      </div>
    </div>
  </div>
</div>

<div class="journalIndexPostGridFeed">
  <div class="nectar-post-grid">
    <div class="nectar-post-grid-item">
      <div class="item-main">
        <h3 class="post-heading">TITLE HERE</h3>
        <span class="meta-date">DATE</span>
      </div>
    </div>
  </div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" type="text/javascript"></script></code>```

Title: jquery insertBefore duplication issue

Body:
Your code is finding all instances of X and inserting them before all instances of Y. There are probably more elegant methods, but an easy one is to use a loop and reference the relative objects for each using closest() and find()

(function($) {
  function journalIndexFeedItemMetaSwapper() {
    let el = ".journalIndexPostGridFeed .nectar-post-grid .nectar-post-grid-item .item-main span.meta-date"
    $(el).each(function() {
      $(this).insertBefore($(this).closest('.item-main').find("h3.post-heading"))
    });
  }

  $(window).load(function() {
    setTimeout(function() {
      journalIndexFeedItemMetaSwapper();
    }, 1000);
  });
})(jQuery);

<div class="journalIndexPostGridFeed">
  <div class="nectar-post-grid">
    <div class="nectar-post-grid-item">
      <div class="item-main">
        <h3 class="post-heading">TITLE HERE</h3>
        <span class="meta-date">DATE</span>
      </div>
    </div>
  </div>
</div>

<div class="journalIndexPostGridFeed">
  <div class="nectar-post-grid">
    <div class="nectar-post-grid-item">
      <div class="item-main">
        <h3 class="post-heading">TITLE HERE</h3>
        <span class="meta-date">DATE</span>
      </div>
    </div>
  </div>
</div>

<div class="journalIndexPostGridFeed">
  <div class="nectar-post-grid">
    <div class="nectar-post-grid-item">
      <div class="item-main">
        <h3 class="post-heading">TITLE HERE</h3>
        <span class="meta-date">DATE</span>
      </div>
    </div>
  </div>
</div>

<div class="journalIndexPostGridFeed">
  <div class="nectar-post-grid">
    <div class="nectar-post-grid-item">
      <div class="item-main">
        <h3 class="post-heading">TITLE HERE</h3>
        <span class="meta-date">DATE</span>
      </div>
    </div>
  </div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" type="text/javascript"></script>


问:
jQuery/JavaScript "this" pointer confusion
The behavior of "this" when function bar is called is baffling me. See the code below. Is there any way to arrange for "this" to be a plain old js object instance when bar is called from a click handler, instead of being the html element?

```<code>// a class with a method

function foo() {

    this.bar();  // when called here, "this" is the foo instance

    var barf = this.bar;
    barf();   // when called here, "this" is the global object

    // when called from a click, "this" is the html element
    $("#thing").after($("<div>click me</div>").click(barf));
}

foo.prototype.bar = function() {
    alert(this);
}
</code>```

答:
You may use Function.apply on the function to set what this should refer to:

```<code>$("#thing").after($("<div>click me</div>").click(function() {
    barf.apply(document); // now this refers to the document
});
</code>```

OwnerDisplayName: I. J. Kennedy

ContentLicense: CC BY-SA 2.5

Body:
The behavior of "this" when function bar is called is baffling me. See the code below. Is there any way to arrange for "this" to be a plain old js object instance when bar is called from a click handler, instead of being the html element?

// a class with a method

function foo() {

    this.bar();  // when called here, "this" is the foo instance

    var barf = this.bar;
    barf();   // when called here, "this" is the global object

    // when called from a click, "this" is the html element
    $("#thing").after($("
click me
").click(barf));
}

foo.prototype.bar = function() {
    alert(this);
}

Body:
You may use Function.apply on the function to set what this should refer to:

$("#thing").after($("<div>click me</div>").click(function() {
    barf.apply(document); // now this refers to the document
});

OwnerDisplayName: Moff

LastEditorDisplayName: Moff


问:
How to sort an array of pointers with a pointer to NULL?
I tried to implement a bubble sort of array of pointers, from greatest to least value that they point to, basically I have to put a pointer to NULL in the middle of the elements (second cell), and when I try to sort them, I want the NULL pointer to be put to the last position of the cell (2) and the other ones to be in order except for this one that is put to the last position.
But this gives me a segmentation fault:</p>
```<code>typedef struct example{
     int data;
}exp;

exp *arr[3];

static void sort_arr(exp *[]);

int main(){

 arr[0] = malloc(sizeof(*arr[0]));
 arr[0]->data = 1;

 arr[1] = NULL;

 arr[2] = malloc(sizeof(*arr[2]));
 arr[2]->data = 2;

 sort_arr(arr);

 return 0;
}

static void sort_arr(exp *pass_arr[]){
    for (int i = 0; i < 3; i++)
    {
        for (int j = i + 1; j < 3; ++j)
        {
            if (pass_arr[i]->data < pass_arr[j]->data)
            {
                exp *temp = pass_arr[i];
                pass_arr[i] = pass_arr[j];
                pass_arr[j] = temp;
            }
        }
    }
    return;
}
</code>```

答:
It is enough to change the if statement for example the following way

```<code>if ( pass_arr[j] != NULL &&
     ( pass_arr[i] == NULL || pass_arr[i]->data < pass_arr[j]->data ) )
</code>```

This is better than this condition

```<code>if (pass_arr[i] == NULL ||
    (pass_arr[j] != NULL && pass_arr[i]->data < pass_arr[j]->data))
</code>```

because in the last case there can be redundant swaps of two null pointers.

Body:
I tried to implement a bubble sort of array of pointers, from greatest to least value that they point to, basically I have to put a pointer to NULL in the middle of the elements (second cell), and when I try to sort them, I want the NULL pointer to be put to the last position of the cell (2) and the other ones to be in order except for this one that is put to the last position.
But this gives me a segmentation fault:

typedef struct example{
     int data;
}exp;

exp *arr[3];

static void sort_arr(exp *[]);

int main(){

 arr[0] = malloc(sizeof(*arr[0]));
 arr[0]->data = 1;

 arr[1] = NULL;

 arr[2] = malloc(sizeof(*arr[2]));
 arr[2]->data = 2;

 sort_arr(arr);

 return 0;
}

static void sort_arr(exp *pass_arr[]){
    for (int i = 0; i < 3; i++)
    {
        for (int j = i + 1; j < 3; ++j)
        {
            if (pass_arr[i]->data < pass_arr[j]->data)
            {
                exp *temp = pass_arr[i];
                pass_arr[i] = pass_arr[j];
                pass_arr[j] = temp;
            }
        }
    }
    return;
}

Body:
It is enough to change the if statement for example the following way

if ( pass_arr[j] != NULL &&
     ( pass_arr[i] == NULL || pass_arr[i]->data < pass_arr[j]->data ) )

This is better than this condition

if (pass_arr[i] == NULL ||
    (pass_arr[j] != NULL && pass_arr[i]->data < pass_arr[j]->data))

because in the last case there can be redundant swaps of two null pointers.