问:
Antlr grammar confusion: Not Reporting Errors when clear error is given
I'm trying to design a simple query language as following

```<code>grammar FilterExpression;

// Lexer rules

AND : 'AND' ;
OR  : 'OR' ;
NOT : 'NOT';

GT : '>' ;
GE : '>=' ;
LT : '<' ;
LE : '<=' ;
EQ : '=' ;

DECIMAL    : '-'?[0-9]+('.'[0-9]+)? ;
KEY       : ~[ \t\r\n\\"~=<>:(),]+ ;
QUOTED_WORD: ["] ('\\"' | ~["])* ["] ;
NEWLINE    : '\r'? '\n';
WS         : [ \t\r\n]+ -> skip ;

StringFilter   : KEY ':' QUOTED_WORD;
NumericalFilter  : KEY (GT | GE | LT | LE | EQ) DECIMAL;

condition      : StringFilter                                # stringCondition
               | NumericalFilter                             # numericalCondition
               | StringFilter op=(AND|OR) StringFilter       # combinedStringCondition
               | NumericalFilter op=(AND|OR) NumericalFilter # combinedNumericalCondition
               | condition AND condition                     # combinedCondition
               | '(' condition ')'                           # parens
               ;

</code>```

I added a few tests and would like to verify if they work as expected. To my surprise, some cases which should be clearly wrong passed

For instance when I type

```<code>(brand:"apple" AND t>3) 1>3
</code>```

where the 1>3 is deliberately put as an error. However it seems Antlr is still happily generating a tree which looks like:

Is it because my grammar has some problems I didn't realize?

I also tried in IntelliJ plugin (because I thought grun might not behaving as expected) but it give

Test code I'm using. Note I also tried to use BailErrorStrategy but these doesn't seem to help

```<code>public class ParserTest {
  private class BailLexer extends FilterExpressionLexer {
    public BailLexer(CharStream input) {
      super(input);
    }
    public void recover(LexerNoViableAltException e) {
      throw new RuntimeException(e);
    }
  }

  private FilterExpressionParser createParser(String filterString) {
    //FilterExpressionLexer lexer = new FilterExpressionLexer(CharStreams.fromString(filterString));
    FilterExpressionLexer lexer = new BailLexer(CharStreams.fromString(filterString));
    CommonTokenStream tokens = new CommonTokenStream(lexer);
    FilterExpressionParser parser = new FilterExpressionParser(tokens);

    parser.setErrorHandler(new BailErrorStrategy());
    parser.addErrorListener(new ANTLRErrorListener() {
      @Override
      public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) {
        System.out.print("here1");
      }

      @Override
      public void reportAmbiguity(Parser recognizer, DFA dfa, int startIndex, int stopIndex, boolean exact, BitSet ambigAlts, ATNConfigSet configs) {
        System.out.print("here2");

      }

      @Override
      public void reportAttemptingFullContext(Parser recognizer, DFA dfa, int startIndex, int stopIndex, BitSet conflictingAlts, ATNConfigSet configs) {
        System.out.print("here3");

      }

      @Override
      public void reportContextSensitivity(Parser recognizer, DFA dfa, int startIndex, int stopIndex, int prediction, ATNConfigSet configs) {

        System.out.print("here4");
      }
    });

    return parser;
  }

  @Test
  public void test() {
    FilterExpressionParser parser = createParser("(brand:\"apple\" AND t>3) 1>3");
    parser.condition();
  }

}
</code>```

答:
Looks like I found the answer finally.

The reason is in the grammar I didn't provide an EOF. And obviously in ANTLR it's perfectly fine to parse the prefix os syntax. that's why the rest of the test string

(brand:"apple" AND t>3) 1>3 i.e. 1>3 is allowed.

See discussion here: https://github.com/antlr/antlr4/issues/351

Then I changed the grammar a little to add an EOF at the end of the syntax condition EOF everything works

Body:
I'm trying to design a simple query language as following

grammar FilterExpression;

// Lexer rules

AND : 'AND' ;
OR  : 'OR' ;
NOT : 'NOT';

GT : '>' ;
GE : '>=' ;
LT : '<' ;
LE : '<=' ;
EQ : '=' ;

DECIMAL    : '-'?[0-9]+('.'[0-9]+)? ;
KEY       : ~[ \t\r\n\\"~=<>:(),]+ ;
QUOTED_WORD: ["] ('\\"' | ~["])* ["] ;
NEWLINE    : '\r'? '\n';
WS         : [ \t\r\n]+ -> skip ;

StringFilter   : KEY ':' QUOTED_WORD;
NumericalFilter  : KEY (GT | GE | LT | LE | EQ) DECIMAL;

condition      : StringFilter                                # stringCondition
               | NumericalFilter                             # numericalCondition
               | StringFilter op=(AND|OR) StringFilter       # combinedStringCondition
               | NumericalFilter op=(AND|OR) NumericalFilter # combinedNumericalCondition
               | condition AND condition                     # combinedCondition
               | '(' condition ')'                           # parens
               ;

I added a few tests and would like to verify if they work as expected. To my surprise, some cases which should be clearly wrong passed

For instance when I type

(brand:"apple" AND t>3) 1>3

where the 1>3 is deliberately put as an error. However it seems Antlr is still happily generating a tree which looks like:

Is it because my grammar has some problems I didn't realize?

I also tried in IntelliJ plugin (because I thought grun might not behaving as expected) but it give

Test code I'm using. Note I also tried to use BailErrorStrategy but these doesn't seem to help

public class ParserTest {
  private class BailLexer extends FilterExpressionLexer {
    public BailLexer(CharStream input) {
      super(input);
    }
    public void recover(LexerNoViableAltException e) {
      throw new RuntimeException(e);
    }
  }

  private FilterExpressionParser createParser(String filterString) {
    //FilterExpressionLexer lexer = new FilterExpressionLexer(CharStreams.fromString(filterString));
    FilterExpressionLexer lexer = new BailLexer(CharStreams.fromString(filterString));
    CommonTokenStream tokens = new CommonTokenStream(lexer);
    FilterExpressionParser parser = new FilterExpressionParser(tokens);

    parser.setErrorHandler(new BailErrorStrategy());
    parser.addErrorListener(new ANTLRErrorListener() {
      @Override
      public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) {
        System.out.print("here1");
      }

      @Override
      public void reportAmbiguity(Parser recognizer, DFA dfa, int startIndex, int stopIndex, boolean exact, BitSet ambigAlts, ATNConfigSet configs) {
        System.out.print("here2");

      }

      @Override
      public void reportAttemptingFullContext(Parser recognizer, DFA dfa, int startIndex, int stopIndex, BitSet conflictingAlts, ATNConfigSet configs) {
        System.out.print("here3");

      }

      @Override
      public void reportContextSensitivity(Parser recognizer, DFA dfa, int startIndex, int stopIndex, int prediction, ATNConfigSet configs) {

        System.out.print("here4");
      }
    });

    return parser;
  }

  @Test
  public void test() {
    FilterExpressionParser parser = createParser("(brand:\"apple\" AND t>3) 1>3");
    parser.condition();
  }

}


来源: stackexchange

问:
Access section key value from another section in config.ini
I have a config.ini file

```<code>[env]
name = local

[dir]
proj_home = /apps/${env:name}/project
</code>```

Python code:

```<code>config = configparser.ConfigParser()
config.read('config.ini')
projHome = config.get('dir', 'proj_home')
</code>```

But projHome value is coming '/apps/${env:name}/project', it should be '/apps/local/project'

Am I doing something wrong in syntax?

答:
That ${section:option} syntax is only available when you're using extended interpolation:

```<code>>>> cf = configparser.ConfigParser(interpolation=configparser.ExtendedInterpolation())
>>> cf.add_section('env')
>>> cf.set('env', 'name', 'local')
>>> cf.add_section('dir')
>>> cf.set('dir', 'proj_home', '/apps/${env:name}/project')
>>> cf.get('dir', 'proj_home')
'/apps/local/project'
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a config.ini file

[env]
name = local

[dir]
proj_home = /apps/${env:name}/project

Python code:

config = configparser.ConfigParser()
config.read('config.ini')
projHome = config.get('dir', 'proj_home')

But projHome value is coming '/apps/${env:name}/project', it should be '/apps/local/project'

Am I doing something wrong in syntax?

Body:
That ${section:option} syntax is only available when you're using extended interpolation:

>>> cf = configparser.ConfigParser(interpolation=configparser.ExtendedInterpolation())
>>> cf.add_section('env')
>>> cf.set('env', 'name', 'local')
>>> cf.add_section('dir')
>>> cf.set('dir', 'proj_home', '/apps/${env:name}/project')
>>> cf.get('dir', 'proj_home')
'/apps/local/project'


问:
Problem with generating a PKCS#12 key from an RSA key
I have a set of RSA keys which are used for testing. I am working on an enhancement for PKCS#12. The existing RSA keys all have a password on them, let's say "mypass". I want to generate three types of PKCS#12 keys:

No password on the PKCS#12 envelope (which if you read this is really the null string) and no password on the RSA key inside

Password on the PKCS#12 envelope and no password on the RSA key inside

Password on both the PKCS#12 envelop and the on the RSA key inside

I'm having trouble with the first option category

Here, I copy the PEM formatted source key into my workspace and create a decrypted version prefixed by the letter d. $tkey is the PEM formatted input key.

```<code>echo RSA keys PEM formatted
key=${name}.priv.rsa.pem
dkey=d${name}.priv.rsa.pem
pubkey=${name}.pub.rsa.pem
cp $tkey ./${key}
openssl rsa -in $key -passin pass:mypass -out $dkey -outform pem -passout pass:
</code>```

I think that the decrypted key doesn't have a password on it, because openssl does not prompt me for a password when I use it to sign some data.

I do the following to generate my PKCS#12 keys (where $tcert is the path to input key's certificate).

```<code>tcert=`dirname $tkey`/${name}.crt
key=${name}.priv.p12
echo PKCS#12 envelope without password and unencrypted RSA key
openssl pkcs12 -export -inkey $dkey -in $tcert -out d$key -name d$name  -passout pass:
echo PKCS#12 envelope with password and unencrypted RSA key
openssl pkcs12 -export -inkey $dkey -in $tcert -out x$key -name  $name  -passout pass:mypass
echo PKCS#12 envelope with password and password protected RSA key
openssl pkcs12 -export -inkey $tkey -in $tcert -out  $key -name  $name  -passout pass:mypass -passin pass:mypass
</code>```

I then inspect each key doing the following (adding mypass as needed). When I go to display the d key, it asks me for a password for the RSA key. If I input "mypass", it dumps the key.

```<code>openssl pkcs12 -info -in $dkey -passin pass:
</code>```

Since the above is scripted, I had the script echo the lines so that I could be sure that it was using the correct files and such.

I'm obviously doing something wrong, but I don't see it.

答:
I was wrong about needing to input my old password. Any four characters of input worked. Which lead me to look at the code where I found a hard coded 4 character requirement on the default PEM callback.

```<code>crypto/pem/pem_lib.c
#define MIN_LENGTH      4

int PEM_def_callback(char *buf, int num, int rwflag, void *userdata)
{
    int i, min_len;
    const char *prompt;

    /* We assume that the user passes a default password as userdata */
    if (userdata) {
        i = strlen(userdata);
        i = (i > num) ? num : i;
        memcpy(buf, userdata, i);
        return i;
    }

    prompt = EVP_get_pw_prompt();
    if (prompt == NULL)
        prompt = "Enter PEM pass phrase:";

    /*
     * rwflag == 0 means decryption
     * rwflag == 1 means encryption
     *
     * We assume that for encryption, we want a minimum length, while for
     * decryption, we cannot know any minimum length, so we assume zero.
     */
    min_len = rwflag ? MIN_LENGTH : 0;

    i = EVP_read_pw_string_min(buf, min_len, num, prompt, rwflag);
    if (i != 0) {
        PEMerr(PEM_F_PEM_DEF_CALLBACK, PEM_R_PROBLEMS_GETTING_PASSWORD);
        memset(buf, 0, (unsigned int)num);
        return -1;
    }
    return strlen(buf);
}
</code>```

Had I paid attention to the error messages, I would have seen "You must type in 4 to 1024 characters".

```<code>Enter PEM pass phrase:
Error outputting keys and certificates
139783395758528:error:28078065:UI routines:UI_set_result_ex:result too small:../crypto/ui/ui_lib.c:903:You must type in 4 to 1024 characters
139783395758528:error:2807106B:UI routines:UI_process:processing error:../crypto/ui/ui_lib.c:543:while reading strings
139783395758528:error:0906406D:PEM routines:PEM_def_callback:problems getting password:../crypto/pem/pem_lib.c:59:
139783395758528:error:0907E06F:PEM routines:do_pk8pkey:read key:../crypto/pem/pem_pk8.c:83:
</code>```

So, the key is not password protected, but the callback function that was called requires four characters of input.

Body:
I have a set of RSA keys which are used for testing. I am working on an enhancement for PKCS#12. The existing RSA keys all have a password on them, let's say "mypass". I want to generate three types of PKCS#12 keys:

No password on the PKCS#12 envelope (which if you read this is really the null string) and no password on the RSA key inside

Password on the PKCS#12 envelope and no password on the RSA key inside

Password on both the PKCS#12 envelop and the on the RSA key inside

I'm having trouble with the first option category

Here, I copy the PEM formatted source key into my workspace and create a decrypted version prefixed by the letter d. $tkey is the PEM formatted input key.

echo RSA keys PEM formatted
key=${name}.priv.rsa.pem
dkey=d${name}.priv.rsa.pem
pubkey=${name}.pub.rsa.pem
cp $tkey ./${key}
openssl rsa -in $key -passin pass:mypass -out $dkey -outform pem -passout pass:

I think that the decrypted key doesn't have a password on it, because openssl does not prompt me for a password when I use it to sign some data.

I do the following to generate my PKCS#12 keys (where $tcert is the path to input key's certificate).

tcert=`dirname $tkey`/${name}.crt
key=${name}.priv.p12
echo PKCS#12 envelope without password and unencrypted RSA key
openssl pkcs12 -export -inkey $dkey -in $tcert -out d$key -name d$name  -passout pass:
echo PKCS#12 envelope with password and unencrypted RSA key
openssl pkcs12 -export -inkey $dkey -in $tcert -out x$key -name  $name  -passout pass:mypass
echo PKCS#12 envelope with password and password protected RSA key
openssl pkcs12 -export -inkey $tkey -in $tcert -out  $key -name  $name  -passout pass:mypass -passin pass:mypass

I then inspect each key doing the following (adding mypass as needed). When I go to display the d key, it asks me for a password for the RSA key. If I input "mypass", it dumps the key.

openssl pkcs12 -info -in $dkey -passin pass:

Since the above is scripted, I had the script echo the lines so that I could be sure that it was using the correct files and such.

I'm obviously doing something wrong, but I don't see it.

Body:
I was wrong about needing to input my old password. Any four characters of input worked. Which lead me to look at the code where I found a hard coded 4 character requirement on the default PEM callback.

crypto/pem/pem_lib.c
#define MIN_LENGTH      4

int PEM_def_callback(char *buf, int num, int rwflag, void *userdata)
{
    int i, min_len;
    const char *prompt;

    /* We assume that the user passes a default password as userdata */
    if (userdata) {
        i = strlen(userdata);
        i = (i > num) ? num : i;
        memcpy(buf, userdata, i);
        return i;
    }

    prompt = EVP_get_pw_prompt();
    if (prompt == NULL)
        prompt = "Enter PEM pass phrase:";

    /*
     * rwflag == 0 means decryption
     * rwflag == 1 means encryption
     *
     * We assume that for encryption, we want a minimum length, while for
     * decryption, we cannot know any minimum length, so we assume zero.
     */
    min_len = rwflag ? MIN_LENGTH : 0;

    i = EVP_read_pw_string_min(buf, min_len, num, prompt, rwflag);
    if (i != 0) {
        PEMerr(PEM_F_PEM_DEF_CALLBACK, PEM_R_PROBLEMS_GETTING_PASSWORD);
        memset(buf, 0, (unsigned int)num);
        return -1;
    }
    return strlen(buf);
}

Had I paid attention to the error messages, I would have seen "You must type in 4 to 1024 characters".

Enter PEM pass phrase:
Error outputting keys and certificates
139783395758528:error:28078065:UI routines:UI_set_result_ex:result too small:../crypto/ui/ui_lib.c:903:You must type in 4 to 1024 characters
139783395758528:error:2807106B:UI routines:UI_process:processing error:../crypto/ui/ui_lib.c:543:while reading strings
139783395758528:error:0906406D:PEM routines:PEM_def_callback:problems getting password:../crypto/pem/pem_lib.c:59:
139783395758528:error:0907E06F:PEM routines:do_pk8pkey:read key:../crypto/pem/pem_pk8.c:83:

So, the key is not password protected, but the callback function that was called requires four characters of input.


问:
Angular material expand one row at a time and close all other opened row
Hi I have a Mat table with expand collapse option.

I have used exactly the below link for my reference.

https://stackblitz.com/edit/angular-material2-expandable-rows-filter-pagination-sorting

Now the problem is I need to collapse all the previous opened row before opening the new row.

Can someone please help me in this.

答:
Hello see this https://stackblitz.com/edit/angular-material2-expandable-rows-filter-pagination-sort-7jpsik?file=app%2Ftable-example.ts

this add a event emitter in cdk-detail-row-directive.ts in this way:

@Output() toggleChange = new EventEmitter(); // added

and when the toggle function is call yo add this:

```<code>this.toggleChange.emit(this); // added
</code>```

See table.example.ts for more changes

Body:
Hello see this https://stackblitz.com/edit/angular-material2-expandable-rows-filter-pagination-sort-7jpsik?file=app%2Ftable-example.ts

this add a event emitter in cdk-detail-row-directive.ts in this way:

@Output() toggleChange = new EventEmitter(); // added

and when the toggle function is call yo add this:

this.toggleChange.emit(this); // added

See table.example.ts for more changes


问:
I can't start MySQL server in NodeJs after reset MySQL password using Windows's cmd
I reset my MySQL password using cmd commands from this guide.

```<code>cd "C:\Program Files\MySQL\MySQL Server 8.0\bin"
mysqld
--defaults-file="C:\\ProgramData\\MySQL\\MySQL Server 8.0\\my.ini"
--init-file=C:\\Users\\<username>\\resetMYSQL.txt
</code>```

resetMYSQL contains a command to change password

```<code>ALTER USER 'root'@'localhost' IDENTIFIED BY '<myNewPassword>';
</code>```

Now, it turned out I have to keep running the mysqld command above to start my server or else I'll get this error. If I run the command again I can flawlessly run my server until I terminate it.

This is the error.  It's ECONNREFUSED.

I think my password is already reset, because apart from the command line, I also run ALTER USER in Workbench after I got access to it while the cmd is running.

Btw, before this I can just start my server using Node and Sequelize and didn't have to start server elsewhere or set anything beforehand

I'm not sure what is the problem here, so I don't know which keyword I should look up on Google. I googled the error code, but those cases seems unrelated to mine.
I'd be glad if you can explain me what's going on.

答:
The nodejs error message you showed us, a ECONNREFUSED message with a traceback, shows the your mysql database server program was not running when your nodejs program tried to connect to it. Nodejs reaches out to MySQL via TCP/IP. TCP/IP responds "I don't know any MySQL." Specifically, it responds "ECONNREFUSED on port 3306," meaning "nothing on this machine accepts connections on MySQL's port."

nodejs does not start the mysql software for you. It connects to it and uses it.. MySQL has to be running already for that work.

Ordinarily, software like mysql runs in the form of a operating system service; a background process that runs all the time on the machine to await requests).

And, ordinarily, you don't provide init files to MySQL to do things like change passwords, except just once, if you must, to rescue something broken.  In your case it looks like you forgot your MySQL password, so you needed to use an init file to rescue yourself.  Once the password is reset, stop using that init file.

Explaining how to make MySQL run as a service on your machine is beyond the scope of a Stack Overflow answer. But the installers for MySQL, on almost every operating system, set it up to run as a service automatically. It's generally useless otherwise.

Body:
I reset my MySQL password using cmd commands from this guide.

cd "C:\Program Files\MySQL\MySQL Server 8.0\bin"
mysqld
--defaults-file="C:\\ProgramData\\MySQL\\MySQL Server 8.0\\my.ini"
--init-file=C:\\Users\\<username>\\resetMYSQL.txt

resetMYSQL contains a command to change password

ALTER USER 'root'@'localhost' IDENTIFIED BY '<myNewPassword>';

Now, it turned out I have to keep running the mysqld command above to start my server or else I'll get this error. If I run the command again I can flawlessly run my server until I terminate it.

This is the error.  It's ECONNREFUSED.

I think my password is already reset, because apart from the command line, I also run ALTER USER in Workbench after I got access to it while the cmd is running.

Btw, before this I can just start my server using Node and Sequelize and didn't have to start server elsewhere or set anything beforehand

I'm not sure what is the problem here, so I don't know which keyword I should look up on Google. I googled the error code, but those cases seems unrelated to mine.
I'd be glad if you can explain me what's going on.


问:
Drop rows in pandas based on the same key
How can I drop rows where column A is the key, and any rows for that key contain both "foo" and "moo" in column C

df_before:

```<code>"cat"   |"waverly way"|"foo"|10.0
"cat"   |"smokey st"  |"moo"|9.7
"rabbit"|"rapid ave"  |"foo"|6.6
"rabbit"|"far blvd"   |"too"|3.2
</code>```

df_after:

```<code>"rabbit"|"rapid ave"  |"foo"|6.6
"rabbit"|"far blvd"   |"too"|3.2
</code>```

答:
Here's another way of doing it:</p>

```<code>x = df.groupby(by=['A'])['C'].agg(' '.join).str.contains((r'(?=.*foo)(?=.*moo)')).reset_index()
index = list(x[x['C']==True]['A'])
print(df[~df['A'].isin(index)])

        A            B    C    D
2  rabbit  rapid ave    foo  6.6
3  rabbit  far blvd     too  3.2
</code>```

Body:
How can I drop rows where column A is the key, and any rows for that key contain both "foo" and "moo" in column C

df_before:

"cat"   |"waverly way"|"foo"|10.0
"cat"   |"smokey st"  |"moo"|9.7
"rabbit"|"rapid ave"  |"foo"|6.6
"rabbit"|"far blvd"   |"too"|3.2

df_after:

"rabbit"|"rapid ave"  |"foo"|6.6
"rabbit"|"far blvd"   |"too"|3.2

Body:
Here's another way of doing it:

x = df.groupby(by=['A'])['C'].agg(' '.join).str.contains((r'(?=.*foo)(?=.*moo)')).reset_index()
index = list(x[x['C']==True]['A'])
print(df[~df['A'].isin(index)])

        A            B    C    D
2  rabbit  rapid ave    foo  6.6
3  rabbit  far blvd     too  3.2


答:
Just change array $values to $values['answer'] in usort function</p>

```<code>$values=json_decode($values, true);
$order = array('Rome', 'Berlin', 'Tokyo','Beijing',
                'New York','Athens','Moscow','Los Angeles',
                'Paris','Madrid','Chicago','Melbourne','Amman');
usort($values['answer'], function ($a, $b) use ($order) {
    $pos_a = array_search($a['City'], $order);
    $pos_b = array_search($b['City'], $order);
    return $pos_a - $pos_b;
});
</code>```

Title: PHP sort array with custom order

Body:
I know that this question is not new but I didn't find a solution. I have an API request which returns JSON:

$values = '{"retcode" : "0 Done",
            "trans_id" : "326678",
            "answer" : [ { "City" : "New York", "Digits" : "5", "Datetime" : "1590773203", "DatetimeMsc" : "1590773203568", "Value" : "0.66480", "Average" : "0.66485", "Last" : "0.00000", "Volume" : "0", "VolumeReal" : "0"
                    } , { "City" : "Berlin","Digits" : "5", "Datetime" : "1590773203", "DatetimeMsc" : "1590773203568", "Value" : "0.89917", "Average" : "0.89920", "Last" : "0.00000", "Volume" : "0", "VolumeReal" : "0"
                    } , { "City" : "Paris", "Digits" : "3", "Datetime" : "1590773203", "DatetimeMsc" : "1590773203569", "Value" : "119.680", "Average" : "119.684", "Last" : "0.000", "Volume" : "0", "VolumeReal" : "0"
                    } , { "City" : "Athens", "Digits" : "5", "Datetime" : "1590773203", "DatetimeMsc" : "1590773203569", "Value" : "1.11211", "Average" : "1.11213", "Last" : "0.00000", "Volume" : "0", "VolumeReal" : "0"
                    } , { "City" : "Beijing", "Digits" : "5", "Datetime" : "1590773203", "DatetimeMsc" : "1590773203568", "Value" : "1.23677", "Average" : "1.23686", "Last" : "0.00000", "Volume" : "0", "VolumeReal" : "0"
                    } , { "City" : "Moscow", "Digits" : "5", "Datetime" : "1590773203", "DatetimeMsc" : "1590773203167", "Value" : "1.37647", "Average" : "1.37654", "Last" : "0.00000", "Volume" : "0", "VolumeReal" : "0"
                    } , { "City" : "Tokyo", "Digits" : "3", "Datetime" : "1590773203", "DatetimeMsc" : "1590773203370", "Value" : "107.616", "Average" : "107.619", "Last" : "0.000", "Volume" : "0", "VolumeReal" : "0"
                    } , { "City" : "Melbourne", "Digits" : "2", "Datetime" : "1590773203", "DatetimeMsc" : "1590773203569", "Value" : "11622.15", "Average" : "11622.95", "Last" : "0.00", "Volume" : "0", "VolumeReal" : "0"
                    } , { "City" : "Amman", "Digits" : "2", "Datetime" : "1590773203", "DatetimeMsc" : "1590773203370", "Value" : "3017.30", "Average" : "3017.70", "Last" : "0.00", "Volume" : "0", "VolumeReal" : "0"
                    } , { "City" : "Chicago", "Digits" : "2", "Datetime" : "1590773203", "DatetimeMsc" : "1590773203569", "Value" : "25261.20", "Average" : "25262.70", "Last" : "0.00", "Volume" : "0", "VolumeReal" : "0"
                    } , { "City" : "Los Angeles", "Digits" : "2", "Datetime" : "1590773203", "DatetimeMsc" : "1590773203772", "Value" : "9408.10", "Average" : "9409.00", "Last" : "0.00", "Volume" : "0", "VolumeReal" : "0"
                    } , { "City" : "Madrid", "Digits" : "3", "Datetime" : "1590773203", "DatetimeMsc" : "1590773203772", "Value" : "33.623", "Average" : "33.663", "Last" : "0.000", "Volume" : "0", "VolumeReal" : "0"
                    } , { "City" : "Rome", "Digits" : "2", "Datetime" : "1590773203", "DatetimeMsc" : "1590773203370", "Value" : "1731.83", "Average" : "1732.06", "Last" : "0.00", "Volume" : "0", "VolumeReal" : "0"
                    } ] }';

I convert the JSON to an Array and create also an array with custom order depends on the City

$values=json_decode($values, true);
$order = array('Rome', 'Berlin', 'Tokyo','Beijing',
                'New York','Athens','Moscow','Los Angeles',
                'Paris','Madrid','Chicago','Melbourne','Amman');
usort($values, function ($a, $b) use ($order) {
    $pos_a = array_search($a['City'], $order);
    $pos_b = array_search($b['City'], $order);
    return $pos_a - $pos_b;
});
var_dump($values);

This code returns the same array as it is after json_decode. Any suggestions? Thanks in advance.

Body:
Just change array $values to $values['answer'] in usort function

$values=json_decode($values, true);
$order = array('Rome', 'Berlin', 'Tokyo','Beijing',
                'New York','Athens','Moscow','Los Angeles',
                'Paris','Madrid','Chicago','Melbourne','Amman');
usort($values['answer'], function ($a, $b) use ($order) {
    $pos_a = array_search($a['City'], $order);
    $pos_b = array_search($b['City'], $order);
    return $pos_a - $pos_b;
});


问:
HL2 sleep settings
I am building a tool for HL2.

I am using the command below to set the sleep settings in HL2 through my tool.

"https://127.0.0.1:10443/api/power/cfg/SCHEME_CURRENT/SUB_SLEEP/STANDBYIDLE?ValueAC=1800&ValueDC=1800";

After running the above command, in the device portal, I can see that both on battery and plugged in values are set to 30 min, as expected.
Though my device goes to sleep after few min, maybe 3 or 5 minutes.

If I set the settings manually through the device portal, then everything works as expected, the device goes to sleep after 30 min.
Is there sth in the command that I am using wrong?
In HL1 it seems like it is working, but not in HL2.

Any advice?

答:
When changing the sleep settings, the Device Portal makes these POST requests:

```<code>.../api/power/cfg/SCHEME_CURRENT/SUB_SLEEP/STANDBYIDLE?ValueAC=180&ValueDC=600
.../api/power/cfg/SCHEME_CURRENT/SUB_VIDEO/VIDEOIDLE?ValueAC=180&ValueDC=600
.../api/power/activecfg?scheme=SCHEME_CURRENT
</code>```

You should make the same requests in your tool. Just replace the values (180 and 600) with your own.

Title: HL2 sleep settings

Body:
When changing the sleep settings, the Device Portal makes these POST requests:

.../api/power/cfg/SCHEME_CURRENT/SUB_SLEEP/STANDBYIDLE?ValueAC=180&ValueDC=600
.../api/power/cfg/SCHEME_CURRENT/SUB_VIDEO/VIDEOIDLE?ValueAC=180&ValueDC=600
.../api/power/activecfg?scheme=SCHEME_CURRENT

You should make the same requests in your tool. Just replace the values (180 and 600) with your own.


问:
How to spread a nested object in Javascript?
I've been trying to copy a nested object properties into another object by using the spread operator. But, I got an error.

So I tried to spread the nested object separately:

```<code>try {
  console.log(
    ...{
      autre_panne: { nbr_op_sav: 12, percentage_op_sav: 0 },
      fonctionnement_bluetooth: { nbr_op_sav: 13, percentage_op_sav: 0 },
      memoire_interne: { nbr_op_sav: 15, percentage_op_sav: 0 },
      non_precise: { nbr_op_sav: 15, percentage_op_sav: 0 },
      panne_audio: { nbr_op_sav: 68, percentage_op_sav: 0 },
      piece_aspect_mecanique: { nbr_op_sav: 78, percentage_op_sav: 0 },
      probleme_charge: { nbr_op_sav: 2, percentage_op_sav: 0 },
    }
  );
} catch (error) {
  console.log("Error spreading");
  console.log(error);
}
</code>```

I get this error:

Error spreading TypeError: Found non-callable @@iterator

      at Object. (C:\Users\Avempace\Desktop\Projects\playground\play.js:227:11)

      at Module._compile (internal/modules/cjs/loader.js:955:30)

      at Object.Module._extensions..js (internal/modules/cjs/loader.js:991:10)

      at Module.load (internal/modules/cjs/loader.js:811:32)

      at Function.Module._load (internal/modules/cjs/loader.js:723:14)

      at Function.Module.runMain (internal/modules/cjs/loader.js:1043:10)

PS:
Similar questions mentioned in SO, do not answer my question:

1. How to use object spread with nested properties?

2. How to spread nested properties in Object?

答:
You can try:

```<code>const myData = {<the data>}
console.log(...Object.entries(myData).flat());
</code>```

Object.entries converts each key-value pair into arrays within an array.
flat() spreads each array into the main array. ...Object destructure the final array.

Body:
I've been trying to copy a nested object properties into another object by using the spread operator. But, I got an error.

So I tried to spread the nested object separately:

try {
  console.log(
    ...{
      autre_panne: { nbr_op_sav: 12, percentage_op_sav: 0 },
      fonctionnement_bluetooth: { nbr_op_sav: 13, percentage_op_sav: 0 },
      memoire_interne: { nbr_op_sav: 15, percentage_op_sav: 0 },
      non_precise: { nbr_op_sav: 15, percentage_op_sav: 0 },
      panne_audio: { nbr_op_sav: 68, percentage_op_sav: 0 },
      piece_aspect_mecanique: { nbr_op_sav: 78, percentage_op_sav: 0 },
      probleme_charge: { nbr_op_sav: 2, percentage_op_sav: 0 },
    }
  );
} catch (error) {
  console.log("Error spreading");
  console.log(error);
}

I get this error:

Error spreading TypeError: Found non-callable @@iterator

      at Object. (C:\Users\Avempace\Desktop\Projects\playground\play.js:227:11)

      at Module._compile (internal/modules/cjs/loader.js:955:30)

      at Object.Module._extensions..js (internal/modules/cjs/loader.js:991:10)

      at Module.load (internal/modules/cjs/loader.js:811:32)

      at Function.Module._load (internal/modules/cjs/loader.js:723:14)

      at Function.Module.runMain (internal/modules/cjs/loader.js:1043:10)

PS:
Similar questions mentioned in SO, do not answer my question:

1. How to use object spread with nested properties?

2. How to spread nested properties in Object?

Body:
You can try:

const myData = {<the data>}
console.log(...Object.entries(myData).flat());

Object.entries converts each key-value pair into arrays within an array.
flat() spreads each array into the main array. ...Object destructure the final array.


问:
What is the difference between const and readonly in C#?
What is the difference between const and readonly in C#?

When would you use one over the other?

答:
One thing to add to what people have said above. If you have an assembly containing a readonly value (e.g. readonly MaxFooCount = 4; ), you can change the value that calling assemblies see by shipping a new version of that assembly with a different value (e.g.  readonly MaxFooCount = 5;)

But with a const, it would be folded into the caller's code when the caller was compiled.

If you've reached this level of C# proficiency, you are ready for Bill Wagner's book, Effective C#: 50 Specific Ways to Improve Your C#
Which answers this question in detail, (and 49 other things).

OwnerDisplayName: Tim

LastEditorDisplayName: Patrik

OwnerDisplayName: Anthony

ContentLicense: CC BY-SA 2.5


问:
Can I include flash content inside a silverlight app?
I have a silverlight application, which requires charts with printing. As silverlight does not support printing, I was thinking of including some flash charts inside my application. I know it sounds weird.... But is it possible?</p>

答: No, it is not possible to run flash content inside of Silverlight or vice-versa. However, it is possible to run both types of content on the same html page. You can even (I think) have them layered on top of each other using windowless controls. You can have them communicate via javascript. You could probably do something similar to solve the problem you are facing.

OwnerDisplayName: Big Boss

OwnerDisplayName: KeithMahoney


问:
How do I access my array from my table data source?
I am starting my first Cocoa Project. And I have a serious (for me) but maybe easy problem (for you) to solve and I need some direction where to start.

The short description: I have built a class "PortConnection.h" who writes all ports found by an external class (AMSerial.h) into an array when the function -listPorts is called. Here is the code for the PortConnection.h

```<code>#import <Cocoa/Cocoa.h>
#import "AMSerialPortList.h"
#import "AMSerialPortAdditions.h"
#import "AMSerialPort.h"

@interface PortConnection : NSObject {
@private
    AMSerialPort *port;
    NSMutableArray *portArray;
}

- (void)listDevices;

@property (nonatomic, retain) NSMutableArray *portArray;
@property (nonatomic, retain) AMSerialPort *port;

@end
</code>```

and following the PortConnection.m

```<code>#import "PortConnection.h"
#import "AMSerialPortList.h"
#import "AMSerialPortAdditions.h"
#import "AMSerialPort.h"

@implementation PortConnection
@synthesize portArray;
@synthesize port;

- (void)listDevices
{
    // get an port enumerator
    NSEnumerator *enumerator = [AMSerialPortList portEnumerator];
    AMSerialPort *aPort;

    while ((aPort = [enumerator nextObject]))
    {
        // Add Devices to Array
        [portArray addObject:[aPort bsdPath]];

    }
}
</code>```

So far it is perfectly working.
Now my questions

I have implemented an tableView in the GUI for display the results of the method called above. This file is called "PortTableViewController.h" and is the datasource for my TableView.

Here is the .h file

```<code>#import <Foundation/Foundation.h>
#import "PortConnection.h"

@interface PortTableViewController : NSObject <NSTableViewDataSource> {
@private
    IBOutlet NSTableView *portTableView;
}

@property (assign) IBOutlet NSTableView *portTableView;

@end
</code>```

and here is the .m file:

```<code>#import "PortTableViewController.h"
#import "PortConnection.h"

@implementation PortTableViewController
@synthesize portTableView;

#pragma mark -
#pragma mark TableView Delegates

- (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView{
    PortConnection *portConnection = [[PortConnection alloc] init];
    [portConnection listDevices];
    return [portConnection.portArray count];
}

- (id)tableView:(NSTableView *)tableView objectValueForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row{
        ??????? I DO NOT HAVE A CLUE HOW TO ACCESS THE ARRAY IN PORTCONNECTION.M CORRECTLY
}

@end
</code>```

QUESTIONS:

1) When having a look on the TableViewDataSourceDelegates how do I access the filled portArray in the PortConnection.m class correctly. It doesn't seem to work the way I do it.

2) Do I have to create an Object from Portconnection.h every time I want to retrieve Data from it in a tableviewdelegate method?

I am really thankful for every kind of help! I want to learn something.. and I really appreciate your support! Thanks.. for question in order to help me, don't hesitate. I really appreciate it....

Thanks
Sebastian

答:
If you don't want to create a field in every delegate you could create a static variable in PortConnection which holds the array. Initially the array is nil and on the first call to get the ports you create the list if needed.

In the implementation file:

```<code>static NSMutableArray *portArray;

+ (NSArray) listPorts {
    if(portArray != nil)
        return (NSArray *)portArray;

    NSEnumerator *enumerator = [AMSerialPortList portEnumerator];
    AMSerialPort *aPort;

    portArray = [[NSMutableArray alloc] init];

    while ((aPort = [enumerator nextObject])) {
        // Add Devices to Array
        [portArray addObject:[aPort bsdPath]];
    }
}
</code>```

This of course depends on how often the portArray will change, if it's often I would probably just generate it every time.

You could also do a getPortArray which calls generatePortArray if portArray is nil

ContentLicense: CC BY-SA 3.0

Body:
I am starting my first Cocoa Project. And I have a serious (for me) but maybe easy problem (for you) to solve and I need some direction where to start.

The short description: I have built a class "PortConnection.h" who writes all ports found by an external class (AMSerial.h) into an array when the function -listPorts is called. Here is the code for the PortConnection.h

#import <Cocoa/Cocoa.h>
#import "AMSerialPortList.h"
#import "AMSerialPortAdditions.h"
#import "AMSerialPort.h"

@interface PortConnection : NSObject {
@private
    AMSerialPort *port;
    NSMutableArray *portArray;
}

- (void)listDevices;

@property (nonatomic, retain) NSMutableArray *portArray;
@property (nonatomic, retain) AMSerialPort *port;

@end

and following the PortConnection.m

#import "PortConnection.h"
#import "AMSerialPortList.h"
#import "AMSerialPortAdditions.h"
#import "AMSerialPort.h"

@implementation PortConnection
@synthesize portArray;
@synthesize port;

- (void)listDevices
{
    // get an port enumerator
    NSEnumerator *enumerator = [AMSerialPortList portEnumerator];
    AMSerialPort *aPort;

    while ((aPort = [enumerator nextObject]))
    {
        // Add Devices to Array
        [portArray addObject:[aPort bsdPath]];

    }
}

So far it is perfectly working.
Now my questions

I have implemented an tableView in the GUI for display the results of the method called above. This file is called "PortTableViewController.h" and is the datasource for my TableView.

Here is the .h file

#import <Foundation/Foundation.h>
#import "PortConnection.h"

@interface PortTableViewController : NSObject <NSTableViewDataSource> {
@private
    IBOutlet NSTableView *portTableView;
}

@property (assign) IBOutlet NSTableView *portTableView;

@end

and here is the .m file:

#import "PortTableViewController.h"
#import "PortConnection.h"

@implementation PortTableViewController
@synthesize portTableView;

#pragma mark -
#pragma mark TableView Delegates

- (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView{
    PortConnection *portConnection = [[PortConnection alloc] init];
    [portConnection listDevices];
    return [portConnection.portArray count];
}

- (id)tableView:(NSTableView *)tableView objectValueForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row{
        ??????? I DO NOT HAVE A CLUE HOW TO ACCESS THE ARRAY IN PORTCONNECTION.M CORRECTLY
}

@end

QUESTIONS:

1) When having a look on the TableViewDataSourceDelegates how do I access the filled portArray in the PortConnection.m class correctly. It doesn't seem to work the way I do it.

2) Do I have to create an Object from Portconnection.h every time I want to retrieve Data from it in a tableviewdelegate method?

I am really thankful for every kind of help! I want to learn something.. and I really appreciate your support! Thanks.. for question in order to help me, don't hesitate. I really appreciate it....

Thanks
Sebastian

Body:
If you don't want to create a field in every delegate you could create a static variable in PortConnection which holds the array. Initially the array is nil and on the first call to get the ports you create the list if needed.

In the implementation file:

static NSMutableArray *portArray;

+ (NSArray) listPorts {
    if(portArray != nil)
        return (NSArray *)portArray;

    NSEnumerator *enumerator = [AMSerialPortList portEnumerator];
    AMSerialPort *aPort;

    portArray = [[NSMutableArray alloc] init];

    while ((aPort = [enumerator nextObject])) {
        // Add Devices to Array
        [portArray addObject:[aPort bsdPath]];
    }
}

This of course depends on how often the portArray will change, if it's often I would probably just generate it every time.

You could also do a getPortArray which calls generatePortArray if portArray is nil


问:
Start a docker container based on condition
Problem-

I have a docker-compose.yml with 6 services. When i execute docker-compose up, all 6 containers gets started but i need 2 containers to start its work initially and rest 4 containers based on conditions.

Description-

6 services in compose(2 services for all users & 4 services for 2 users):-

-2 service for all users

I'm mounting login required pages in first container

I maintained database for login accounts in 2nd container

-2 services for each users

Based on the user, i redirect from login page to different applications

at this point, i mounted his/her application in one container and database in another.

Is there a way, when i run docker-compose up -it should start only 2 services common to all users and based on the user login i need to start other 2 services where his/her application mounted ???

答:
I often have some services that are no-ops based on the environment.

If you add this you will pass through the external user to the container:

```<code>    environment:
      - USER=${USER}
    entrypoint: ./my_entrypoint_conditional_wrapper.sh
</code>```

In the entrypoint script, check the USER variable, and if the service should NOT start, simply exit 0, otherwise run the original entrypoint.

If the image you are using is one you didn't build, you can always use volumes to pass-through just the script:

```<code>    volumes:
      - ./my_entrypoint_conditional_wrapper.sh: /tmp/./my_entrypoint_conditional_wrapper.sh
    entrypoint: /tmp/my_entrypoint_conditional_wrapper.sh
</code>```

Body:
I often have some services that are no-ops based on the environment.

If you add this you will pass through the external user to the container:

    environment:
      - USER=${USER}
    entrypoint: ./my_entrypoint_conditional_wrapper.sh

In the entrypoint script, check the USER variable, and if the service should NOT start, simply exit 0, otherwise run the original entrypoint.

If the image you are using is one you didn't build, you can always use volumes to pass-through just the script:

    volumes:
      - ./my_entrypoint_conditional_wrapper.sh: /tmp/./my_entrypoint_conditional_wrapper.sh
    entrypoint: /tmp/my_entrypoint_conditional_wrapper.sh


问:
Mapping different column and table names for Laravel Authentication without re-writing all of the auth classes
We store our authentication information in a different table and column names than Laravel uses by default. It's still stored in MySQL. When doing research, in the documentation it says that we have to write completely different authentication handlers.

Is there really not any way to just remap the table and column names in a central place?

If not is there a better way to handle this? Should we just create a new table using the authentication information?

答:
The Model associated with the login process can be modified in:

```<code>config/auth.php
</code>```

under the 'providers' section:

```<code>'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => \App\Models\MyOwnUsersTable::class,
    ],
],
</code>```

However, the login process is a bit more tricky.  the LoginController uses the AuthenticatesUsers trait, where you may override the required methods.  For example the login method

```<code>class LoginController extends Controller
{
    use AuthenticatesUsers;

    public function login(Request $request)
    {
        //Do whatever you have to do
        return $this->sendLoginResponse($request);
    }

}
</code>```

So, basically, I encourage you to study the

```<code>Illuminate\Foundation\Auth\AuthenticatesUsers
</code>```

and reuse as much as possible from that class, and only override the methods you need to.

Body:
The Model associated with the login process can be modified in:

config/auth.php

under the 'providers' section:

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => \App\Models\MyOwnUsersTable::class,
    ],
],

However, the login process is a bit more tricky.  the LoginController uses the AuthenticatesUsers trait, where you may override the required methods.  For example the login method

class LoginController extends Controller
{
    use AuthenticatesUsers;

    public function login(Request $request)
    {
        //Do whatever you have to do
        return $this->sendLoginResponse($request);
    }

}

So, basically, I encourage you to study the

Illuminate\Foundation\Auth\AuthenticatesUsers

and reuse as much as possible from that class, and only override the methods you need to.


问:
Using a jinja variable in JS script
I'm new to Flask and looking for a way to parse one or n values of a jinja variable.

The app route hands an object over to the html template.

```<code>`selection2 = db.execute("SELECT user.id, bikes.id, bikes.name, bikeshopname, price, city, img, enddate FROM user LEFT JOIN bikes ON user.id = bikes.userid LEFT JOIN renthistory ON bikes.id = renthistory.bikeid WHERE user.city = :city AND price NOT NULL", city=select_city)
    return render_template("/bikes.html", selection2=selection2)`
</code>```

In the template I implemented it like this:

{% for row in selection2 %}

{% endfor %}

In the js function I get the value (a certain date) of that particular paragraph. So it works for the first item.

```<code>function getBikeRentEndDate() {
  let enddate = (document.getElementById("enddate").innerHTML);
  document.getElementById('showdate').innerHTML = enddate;
}
</code>```

But what I want is to look in all the   created once the template is rendered. And then show a message if a condition is true. Something like "if date is => today - show a message.

I know there is a way but after researching and trail and erroring for quite a while, I hope someone can point it out.

答:
To achieve the desired result, you have to first cast the jinja2 variable to js.

To do that in your template:

```<code><script>
    const listselection2 = JSON.parse('{{ selection2 | tojson | safe }}');
    //do your stuff with listselection2.
</script>
</code>```

Title: Using a jinja variable in JS script

Body:
I'm new to Flask and looking for a way to parse one or n values of a jinja variable.

The app route hands an object over to the html template.

`selection2 = db.execute("SELECT user.id, bikes.id, bikes.name, bikeshopname, price, city, img, enddate FROM user LEFT JOIN bikes ON user.id = bikes.userid LEFT JOIN renthistory ON bikes.id = renthistory.bikeid WHERE user.city = :city AND price NOT NULL", city=select_city)
    return render_template("/bikes.html", selection2=selection2)`

In the template I implemented it like this:

{% for row in selection2 %}

{% endfor %}

In the js function I get the value (a certain date) of that particular paragraph. So it works for the first item.

function getBikeRentEndDate() {
  let enddate = (document.getElementById("enddate").innerHTML);
  document.getElementById('showdate').innerHTML = enddate;
}

But what I want is to look in all the   created once the template is rendered. And then show a message if a condition is true. Something like "if date is => today - show a message.

I know there is a way but after researching and trail and erroring for quite a while, I hope someone can point it out.

Body:
To achieve the desired result, you have to first cast the jinja2 variable to js.

To do that in your template:

<script>
    const listselection2 = JSON.parse('{{ selection2 | tojson | safe }}');
    //do your stuff with listselection2.
</script>


问:
How set background-image for different screen variation?
I am having trouble with how to set different background images (or make responsive background images) for different screen sizes. My intention is to set 2 background images. First is for the size of a mobile screen and another of the size of a PC screen. I tried browsing the internet and watching tutorials on Youtube but it drives me no closer to what I want to happen. I am new to programming web applications and any help, tips and suggestions would be very much appreciated. Thank you. </p>

答:
I found a solution for this problem. Just in case someone's having a hard time looking for answer it's here.
Credits and thanks to the owner of this article.</p>


问:
Equivalent of <c:url/> for Velocity
Is there an equivalent of the <c:url/> tag (of jsp core taglib fame) for Apache Velocity? I'd like to create urls when I don't always know the path/context root (a la <c:url value="/mypage"/>).

Thanks

答: Take a look at LinkTool.</p>

Title: Equivalent of <c:url/> for Velocity

Body: Take a look at LinkTool.


问:
Moving multi-column Listbox back to Excel
I've populated a Userform from four columns, following the advice in VBA Excel Populate ListBox with multiple columns.

I now want to allow my users to be able to remove any line, and for the contents in the new Listbox to be moved back to the Excel worksheet, using the same columns.

EDIT: The full list of items can be anything from one single line to dozens of lines. As an example of how my code is working: assuming, from a list of 5 lines, Line number 3 is removed by the user. In this case, all entries up-to the deleted point are restored to the correct range (so lines 1 and 2 are correct). Lines 4 and below are not restored.

Is there a way to get all remaining lines to populate in Excel?

Users can delete whole lines from this code:

```<code>Private Sub Remove_Click()
Dim i as Integer
For i = Me.ListBox1.ListCount - 1 To 0 Step -1
        If Me.ListBox1.Selected(i) = True Then
            Me.ListBox1.RemoveItem i
            Exit For
        End If
    Next
End Sub
</code>```

The code I'm using to try to re-populate the Excel sheet is here. No error messages are shown. It's as though the code thinks it's finished.

```<code>Private Sub CommandButton1_Click()
Dim ws      As Worksheet
Dim rng     As Range
Dim MyArray
Dim x As Long
Set ws = Sheets("EnteredData")

Set rng = ws.Range("M3:P" & ws.Range("M" & ws.Rows.Count).End(xlUp).Row)

    rng.Clear

    MyArray = Me.ListBox1.List
    x = Me.ListBox1.ListCount - 1
    ws.Range("M3:P" & x).Value = MyArray

End Sub
</code>```

I'd really appreciate any help in resolving this issue. Thanks

答:
It looks like the problem lies with this line...

```<code>ws.Range("M3:P" & x).Value = MyArray
</code>```

You'll need to account for the first three lines, so it should be...

```<code>ws.Range("M3:P" & 3 + x).Value = MyArray
</code>```

Body:
I've populated a Userform from four columns, following the advice in VBA Excel Populate ListBox with multiple columns.

I now want to allow my users to be able to remove any line, and for the contents in the new Listbox to be moved back to the Excel worksheet, using the same columns.

EDIT: The full list of items can be anything from one single line to dozens of lines. As an example of how my code is working: assuming, from a list of 5 lines, Line number 3 is removed by the user. In this case, all entries up-to the deleted point are restored to the correct range (so lines 1 and 2 are correct). Lines 4 and below are not restored.

Is there a way to get all remaining lines to populate in Excel?

Users can delete whole lines from this code:

Private Sub Remove_Click()
Dim i as Integer
For i = Me.ListBox1.ListCount - 1 To 0 Step -1
        If Me.ListBox1.Selected(i) = True Then
            Me.ListBox1.RemoveItem i
            Exit For
        End If
    Next
End Sub

The code I'm using to try to re-populate the Excel sheet is here. No error messages are shown. It's as though the code thinks it's finished.

Private Sub CommandButton1_Click()
Dim ws      As Worksheet
Dim rng     As Range
Dim MyArray
Dim x As Long
Set ws = Sheets("EnteredData")

Set rng = ws.Range("M3:P" & ws.Range("M" & ws.Rows.Count).End(xlUp).Row)

    rng.Clear

    MyArray = Me.ListBox1.List
    x = Me.ListBox1.ListCount - 1
    ws.Range("M3:P" & x).Value = MyArray

End Sub

I'd really appreciate any help in resolving this issue. Thanks

Body:
It looks like the problem lies with this line...

ws.Range("M3:P" & x).Value = MyArray

You'll need to account for the first three lines, so it should be...

ws.Range("M3:P" & 3 + x).Value = MyArray


问:
Compare my variable with a csv file and get the matching value in javascript
I have a javascript variable. I need to compare it to an external csv file and collect a matching value.

For example : my variable is blue. I have a file.csv formatted in this way :

"blue","top","110","in stock", "red","down","111","in stock" ...

The value I need to collect is always two positions after the variable. So if my variable is Blue, I need to get 110 as a new variable . If my variable is red I need to get 111 as a new variable so on.

How can I do this ?
thank you :)

答:
This function should do the trick :</p>

```<code>//test variables
testarray =["blue","top","110","in stock", "red","down","111","in stock"]

//function
function testfunction(array, variable){
    var varindex = array.indexOf(variable)
    return array[varindex+2]
}
//calling the function
testfunction(testarray, "blue")
</code>```

Body:
This function should do the trick :

//test variables
testarray =["blue","top","110","in stock", "red","down","111","in stock"]

//function
function testfunction(array, variable){
    var varindex = array.indexOf(variable)
    return array[varindex+2]
}
//calling the function
testfunction(testarray, "blue")


问:
Convert a react class component to react hooks component
I want to convert this react class component into a react hooks component.
I converted most of the code and now I need help to convert the part of code that is between the render and the return functions.

Here is the class component:

```<code>class LoginGoogle extends React.Component {
    state = {
        loading: true,
        error: null,
        data: {},
    };

    componentDidMount() {
        fetch(`/api/auth/google/callback${this.props.location.search}`, { headers: new Headers({ accept: 'application/json' }) })
            .then((response) => {
                if (response.ok) {
                    return response.json();
                }
                throw new Error('Something went wrong!');
            })
            .then((data) => {
                this.setState({ loading: false, data });
            })
            .catch((error) => {
                this.setState({ loading: false, error });
                console.error(error);
            });
    }

    render() {
        const { loading, error, data } = this.state;
        if (loading) {
            return <Layout>Loading....</Layout>;
        }

        if (error) {
            return (
                <Layout>
                    <div>
                        <p>Error:</p>
                        <code className="Code-block">{error.toString()}</code>
                    </div>
                </Layout>
            );
        }

        return (
            <Layout>
                <div>
                    <details>
                        <summary>Welcome {data.user.name}</summary>
                        <p>Here is your info: </p>
                        <code className="Code-block">{JSON.stringify(data, null, 2)}</code>
                    </details>
                </div>
            </Layout>
        );
    }
}
</code>```

And this is the new react hooks component that I created. As I mentioned before it's still not finished yet.

```<code>function LoginGoogle (props) {

    const [start, setStart] = useState(
        {
        loading: true,
        error: null,
        data: {},
           }
    )

    useEffect(() => {
        fetch(`/api/auth/google/callback${props.location.search}`, { headers: new Headers({ accept: 'application/json' }) })
            .then((response) => {
                if (response.ok) {
                    return response.json();
                }
                throw new Error('Something went wrong!');
            })
            .then((data) => {
                setStart({ loading: false, data });
            })
            .catch((error) => {
                setStart({ loading: false, error });
                console.error(error);
            });
    })

        const { loading, error, data } = this.state;
        if (loading) {
            return <Layout>Loading....</Layout>;
        }

        if (error) {
            return (
                <Layout>
                    <div>
                        <p>Error:</p>
                        <code className="Code-block">{error.toString()}</code>
                    </div>
                </Layout>
            );
        }

        return (
            <Layout>
                <div>
                    <details>
                        <summary>Welcome {data.user.name}</summary>
                        <p>Here is your info: </p>
                        <code className="Code-block">{JSON.stringify(data, null, 2)}</code>
                    </details>
                </div>
            </Layout>
        );
    }
</code>```

These are the steps that I took to convert the code :
10 Steps to Convert React Class Component to React Functional Component with Hooks!

答:
First and foremost, the logic from componentDidMount should be within the useEffect hook, which you got it right. However, you will need to add an empty array as the dependency array, which will ensure that the HTTP request will be called once on mount:

```<code>useEffect(() => {
    fetch(`/api/auth/google/callback${props.location.search}`, { headers: new Headers({ accept: 'application/json' }) })
        .then((response) => {
            if (response.ok) {
                return response.json();
            }
            throw new Error('Something went wrong!');
        })
        .then((data) => {
            setStart({ loading: false, data });
        })
        .catch((error) => {
            setStart({ loading: false, error });
            console.error(error);
        });
}, []);
</code>```

With that, you should conditionally render the JSX elements based on the your component's state, as defined by the start state:

```<code>const { data, error, loading } = start;

return (
  <>
    {error && (
       <Layout>
         <div>
           <p>Error:</p>
           <code className="Code-block">{error.toString()}</code>
           </div>
       </Layout>
    )}
    {data && (
      <Layout>
        <div>
           <details>
             <summary>Welcome {data.user.name}</summary>
             <p>Here is your info: </p>
             <code className="Code-block">{JSON.stringify(data, null, 2)}</code>     </details>
         </div>
      </Layout>
    )}
    {
      loading && <Layout>Loading....</Layout>
    }
  <>
);
</code>```

Body:
I want to convert this react class component into a react hooks component.
I converted most of the code and now I need help to convert the part of code that is between the render and the return functions.

Here is the class component:

class LoginGoogle extends React.Component {
    state = {
        loading: true,
        error: null,
        data: {},
    };

    componentDidMount() {
        fetch(`/api/auth/google/callback${this.props.location.search}`, { headers: new Headers({ accept: 'application/json' }) })
            .then((response) => {
                if (response.ok) {
                    return response.json();
                }
                throw new Error('Something went wrong!');
            })
            .then((data) => {
                this.setState({ loading: false, data });
            })
            .catch((error) => {
                this.setState({ loading: false, error });
                console.error(error);
            });
    }

    render() {
        const { loading, error, data } = this.state;
        if (loading) {
            return <Layout>Loading....</Layout>;
        }

        if (error) {
            return (
                <Layout>

Error:

                        {error.toString()}

                </Layout>
            );
        }

        return (
            <Layout>

                        Welcome {data.user.name}

Here is your info:

                        {JSON.stringify(data, null, 2)}

            </Layout>
        );
    }
}

And this is the new react hooks component that I created. As I mentioned before it's still not finished yet.

function LoginGoogle (props) {

    const [start, setStart] = useState(
        {
        loading: true,
        error: null,
        data: {},
           }
    )

    useEffect(() => {
        fetch(`/api/auth/google/callback${props.location.search}`, { headers: new Headers({ accept: 'application/json' }) })
            .then((response) => {
                if (response.ok) {
                    return response.json();
                }
                throw new Error('Something went wrong!');
            })
            .then((data) => {
                setStart({ loading: false, data });
            })
            .catch((error) => {
                setStart({ loading: false, error });
                console.error(error);
            });
    })

        const { loading, error, data } = this.state;
        if (loading) {
            return <Layout>Loading....</Layout>;
        }

        if (error) {
            return (
                <Layout>

Error:

                        {error.toString()}

                </Layout>
            );
        }

        return (
            <Layout>

                        Welcome {data.user.name}

Here is your info:

                        {JSON.stringify(data, null, 2)}

            </Layout>
        );
    }

These are the steps that I took to convert the code :
10 Steps to Convert React Class Component to React Functional Component with Hooks!

Body:
First and foremost, the logic from componentDidMount should be within the useEffect hook, which you got it right. However, you will need to add an empty array as the dependency array, which will ensure that the HTTP request will be called once on mount:

useEffect(() => {
    fetch(`/api/auth/google/callback${props.location.search}`, { headers: new Headers({ accept: 'application/json' }) })
        .then((response) => {
            if (response.ok) {
                return response.json();
            }
            throw new Error('Something went wrong!');
        })
        .then((data) => {
            setStart({ loading: false, data });
        })
        .catch((error) => {
            setStart({ loading: false, error });
            console.error(error);
        });
}, []);

With that, you should conditionally render the JSX elements based on the your component's state, as defined by the start state:

const { data, error, loading } = start;

return (
  <>
    {error && (
       <Layout>
         <div>
           <p>Error:</p>
           <code className="Code-block">{error.toString()}</code>
           </div>
       </Layout>
    )}
    {data && (
      <Layout>
        <div>
           <details>
             <summary>Welcome {data.user.name}</summary>
             <p>Here is your info: </p>
             <code className="Code-block">{JSON.stringify(data, null, 2)}</code>     </details>
         </div>
      </Layout>
    )}
    {
      loading && <Layout>Loading....</Layout>
    }
  <>
);


问:
Media queries - not responding on devices
```<code>@media screen (max-width: 750px) or (screen and (max-width: 750px) (-webkit-min-device-pixel-ratio: 2),(min-resolution: 192dpi)) {
        div.body, div.body div.links, div.body div.links div, div.footer, div.footer div {
            display: block !important;
            overflow: hidden !important;
}
</code>```

another version

```<code>@media screen and (max-width: 750px) {
        div.body, div.body div.links, div.body div.links div, div.footer, div.footer div, table, td, tr{
            display: block !important;
            overflow: hidden !important;
        }
</code>```

Hi all,

Above is my media queries for my code. This code is for a news letter and for some reason the media queries will have no effect went sent to a mobile device. Is there something that I am missing in the media queries? The phone I am using to test is an iPhone XR.

Thank you so much in advance!

Dom

答:
Please remove !important and add a }.Also use @media all like this

```<code>@media all and (max-width: 750px) {
    div.body, div.body div.links, div.body div.links div, div.footer, div.footer div, table, td, tr{
        display: block;
        overflow: hidden;
    }
}
</code>```

did it work?

Body:
@media screen (max-width: 750px) or (screen and (max-width: 750px) (-webkit-min-device-pixel-ratio: 2),(min-resolution: 192dpi)) {
        div.body, div.body div.links, div.body div.links div, div.footer, div.footer div {
            display: block !important;
            overflow: hidden !important;
}

another version

@media screen and (max-width: 750px) {
        div.body, div.body div.links, div.body div.links div, div.footer, div.footer div, table, td, tr{
            display: block !important;
            overflow: hidden !important;
        }

Hi all,

Above is my media queries for my code. This code is for a news letter and for some reason the media queries will have no effect went sent to a mobile device. Is there something that I am missing in the media queries? The phone I am using to test is an iPhone XR.

Thank you so much in advance!

Dom

Body:
Please remove !important and add a }.Also use @media all like this

@media all and (max-width: 750px) {
    div.body, div.body div.links, div.body div.links div, div.footer, div.footer div, table, td, tr{
        display: block;
        overflow: hidden;
    }
}

did it work?


问:
Cannot resolve / reject a Promise
I wrote a service method which allow an user to get a authenticate in my restify API. The get method invoke this:

```<code>public async auth(email: string, password: string): Promise<Customer> {
    let connection = await DatabaseProvider.getConnection();
    const customer = await connection.getRepository(Customer).findOne({ email });

    try {
        let isMatch = await bcrypt.compare(password, customer!.password);

        if (!isMatch) throw 'Password did not match';
        Promise.resolve(customer);
    } catch (err) {
        Promise.reject('Authentication failed');
    }
}
</code>```

the problem's that I get:

A function whose declared type is neither 'void' nor 'any' must return a value.

seems that Promise.resolve(customer) does not return anything, I also tried to prefix with return but same problem

答:
```<code>public async auth(email: string, password: string): Promise<Customer> {
    let connection = await DatabaseProvider.getConnection();

    const customer = await connection.getRepository(Customer).findOne({ email });

    let isMatch = await bcrypt.compare(password, customer!.password);

    if (!isMatch) throw 'Password did not match';

    if(customer)
      return customer;

    throw 'Customer is undefined';
}
</code>```

This should work i guess...

Title: Cannot resolve / reject a Promise

Body:
I wrote a service method which allow an user to get a authenticate in my restify API. The get method invoke this:

public async auth(email: string, password: string): Promise<Customer> {
    let connection = await DatabaseProvider.getConnection();
    const customer = await connection.getRepository(Customer).findOne({ email });

    try {
        let isMatch = await bcrypt.compare(password, customer!.password);

        if (!isMatch) throw 'Password did not match';
        Promise.resolve(customer);
    } catch (err) {
        Promise.reject('Authentication failed');
    }
}

the problem's that I get:

A function whose declared type is neither 'void' nor 'any' must return a value.

seems that Promise.resolve(customer) does not return anything, I also tried to prefix with return but same problem

Body:
public async auth(email: string, password: string): Promise<Customer> {
    let connection = await DatabaseProvider.getConnection();

    const customer = await connection.getRepository(Customer).findOne({ email });

    let isMatch = await bcrypt.compare(password, customer!.password);

    if (!isMatch) throw 'Password did not match';

    if(customer)
      return customer;

    throw 'Customer is undefined';
}

This should work i guess...


问:
Removing numbers from a given string
I am trying to get rid of any numbers in a string.

However, when I run my program the number is removed, but other parts of the string are removed as well.

```<code>string = 'My name is Anish, & I am 22 years old! The wall is blue, and the floor is orange. The weather is great, but it is raining?'

def num_remover(words):
    t = words.split()
    d = [e for e in t if e.isalpha()]
    a = " ".join(d)
    return a

print(bluh_remover(string))
</code>```

output:

My name is I am 22 years The wall is and the floor is The weather is but it is

答:
It is missing because you have split the string, therefore, the word Anish will come as 'Anish,' which is not string because of special character.
string = 'My name is Anish, & I am 22 years old! The wall is blue, and the floor is orange. The weather is great, but it is raining?'

```<code>def num_remover(words):
    new = ''
    temp = ''
    for i in words:
       if i.isdigit():
           new = new + temp
           temp = ''
       else:
           temp = temp + i
    return new + temp
print(num_remover(string))
</code>```

Output:

```<code>My name is Anish, & I am  years old! The wall is blue, and the floor is orange. The weather is great, but it is raining?
</code>```

Title: Removing numbers from a given string

Body:
I am trying to get rid of any numbers in a string.

However, when I run my program the number is removed, but other parts of the string are removed as well.

string = 'My name is Anish, & I am 22 years old! The wall is blue, and the floor is orange. The weather is great, but it is raining?'

def num_remover(words):
    t = words.split()
    d = [e for e in t if e.isalpha()]
    a = " ".join(d)
    return a

print(bluh_remover(string))

output:

My name is I am 22 years The wall is and the floor is The weather is but it is

Body:
It is missing because you have split the string, therefore, the word Anish will come as 'Anish,' which is not string because of special character.
string = 'My name is Anish, & I am 22 years old! The wall is blue, and the floor is orange. The weather is great, but it is raining?'

def num_remover(words):
    new = ''
    temp = ''
    for i in words:
       if i.isdigit():
           new = new + temp
           temp = ''
       else:
           temp = temp + i
    return new + temp
print(num_remover(string))

Output:

My name is Anish, & I am  years old! The wall is blue, and the floor is orange. The weather is great, but it is raining?


问:
Use BitmapDecoder in an other thread then where is created. (The calling thread cannot access this object because a different thread owns it.)
So, i have a function that will load an image from disk async in an other thread ( big images will be loaded and I don't want the UI THread to be locked while loading).

Loading is done like this

```<code>  public override void LoadFile()
        {
            using (var imageStream = new FileStream(_filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                Decoder = new TiffBitmapDecoder(imageStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);
                InitializeFile();
            }
        }
</code>```

Then I want to use the Decoder on the main thread

```<code>   public List<ThumbnailModel> LoadPages()
        {
            var result = new List<ThumbnailModel>();

            foreach (var frame in Decoder.Frames) <--// this line throws exception
            {
                result.Add(new ThumbnailModel
                {
                    Name = _metadataLoader.GetPageName((BitmapMetadata)frame.Metadata),
                    Bitmap = new WriteableBitmap(frame)
                });
            }

            return result;
        }
</code>```

Now here is the problem, whenever I reach the line where I try to access the Decoder.Frames it throws exception (The calling thread cannot access this object because a different thread owns it.)

Is there a way I can use my Decoder in the main thread if not, the only possible solution is to load all the image information in the other thread?

Full code version :
    // this is the task, that calls the imageFactory LoadFile method - NewThread

```<code>  private async Task OpenFileAsync(string strFilePath)
            {
                var newFile = _imageFileFactory.LoadFile(strFilePath);

            if (newFile != null)
            {
                _imagefile = newFile;
            }
        }
  //image factory load file - NewThread
  public IImageFile LoadFile(string filePath)
        {
            if (string.IsNullOrWhiteSpace(filePath))
            {
                return null;
            }

            var fileExtension = Path.GetExtension(filePath); // .tiff or .jpeg

            var file = new ImageFileTiff(filePath, _metatadaFactory, _metadataVersioner);

            file.LoadFile();

            return file;
        }
// ImageFileTiff LoadFile will create a decoder - NewThread
 public override void LoadFile()
        {
            using (var imageStream = new FileStream(_filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                Decoder = new JpegBitmapDecoder(imageStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);

                InitializeFile();
            }
        }
</code>```

After we have an IImageFile we call on MainThread(UIThread)

```<code>var pages = _imagefile.LoadPages();
</code>```

Where LoadPages is the place where the app breaks. also called on UIThread
    public List LoadPages()
        {
            var result = new List();

```<code>        foreach (var frame in Decoder.Frames)
        {
            result.Add(new ThumbnailModel
            {
                Name = _metadataLoader.GetPageName((BitmapMetadata)frame.Metadata),
                Bitmap = new WriteableBitmap(frame)
            });
        }

        return result;
    }
</code>```

答:
I thought you could simply return the decoder from the thread to be able to access it but your decoder is a TiffBitmapDecoder which inherits from DispatcherObject (https://learn.microsoft.com/en-gb/dotnet/api/system.windows.threading.dispatcherobject?view=netcore-3.1).

So you won't be able to access it from a different thread than the one where it was created msdn:"Only the thread that the Dispatcher was created on may access the DispatcherObject directly"

What you could do instead is use the decoder in it's thread and return the final result:

I couldn't build on your sample since there was to much missing for me to test it but I built a similar project to give an exemple:

```<code>public partial class MainWindow : Window
{
    public MainWindow()
    {

    }

    public TiffBitmapDecoder LoadFile()
    {
        OpenFileDialog openFileDialog = new OpenFileDialog();
        openFileDialog.InitialDirectory = "c:\\";
        openFileDialog.Filter = "tiff files (*.tif)|*.tif|All files (*.*)|*.*";
        openFileDialog.FilterIndex = 2;
        openFileDialog.RestoreDirectory = true;

        if (openFileDialog.ShowDialog() == true && !string.IsNullOrEmpty(openFileDialog.FileName))
        {
            //I didn't bother to check the file extension since it's just an exemple
            using (var imageStream = openFileDialog.OpenFile())
            {
                return new TiffBitmapDecoder(imageStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);
            }
        }
        else
        {
            //User cancelled
            return null;
        }
    }

    public List<ThumbnailModel> LoadPages(TiffBitmapDecoder decoder)
    {
        //TiffBitmapDecoder" inherits from DispatcherObject/>
        //https://learn.microsoft.com/en-gb/dotnet/api/system.windows.threading.dispatcherobject?view=netcore-3.1
        var result = new List<ThumbnailModel>();
        if (decoder != null)
        {
            try
            {
                foreach (var frame in decoder.Frames)
                {
                    result.Add(new ThumbnailModel
                    {
                        //set the variables
                    });
                }
            }
            catch(InvalidOperationException e)
            {
                MessageBox.Show(e.Message, "Error");
            }
        }
        else
        {
            //Nothing to do
        }
        return result;
    }

    private async Task AsyncLoading()
    {
        this.thumbnailModels = await Task.Run<List<ThumbnailModel>>(() =>
        {
            var decoder = this.LoadFile();
            return this.LoadPages(decoder);
        });
    }

    private List<ThumbnailModel> thumbnailModels = null;

    private async void AsyncLoadingButton_Click(object sender, RoutedEventArgs e)
    {
        await this.AsyncLoading();
    }
}

public class ThumbnailModel
{
}
</code>```

Content of MainWindow.xaml just in case:

```<code><Grid>
    <StackPanel Orientation="Vertical">
        <Button x:Name="NoReturnButton" Margin="10" HorizontalAlignment="Center" Content="Call AsyncLoadingNoReturn" Click="AsyncLoadingButton_Click" />
    </StackPanel>
</Grid>
</code>```

Body:
So, i have a function that will load an image from disk async in an other thread ( big images will be loaded and I don't want the UI THread to be locked while loading).

Loading is done like this

  public override void LoadFile()
        {
            using (var imageStream = new FileStream(_filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                Decoder = new TiffBitmapDecoder(imageStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);
                InitializeFile();
            }
        }

Then I want to use the Decoder on the main thread

   public List<ThumbnailModel> LoadPages()
        {
            var result = new List<ThumbnailModel>();

            foreach (var frame in Decoder.Frames) <--// this line throws exception
            {
                result.Add(new ThumbnailModel
                {
                    Name = _metadataLoader.GetPageName((BitmapMetadata)frame.Metadata),
                    Bitmap = new WriteableBitmap(frame)
                });
            }

            return result;
        }

Now here is the problem, whenever I reach the line where I try to access the Decoder.Frames it throws exception (The calling thread cannot access this object because a different thread owns it.)

Is there a way I can use my Decoder in the main thread if not, the only possible solution is to load all the image information in the other thread?

Full code version :
    // this is the task, that calls the imageFactory LoadFile method - NewThread

  private async Task OpenFileAsync(string strFilePath)
            {
                var newFile = _imageFileFactory.LoadFile(strFilePath);

            if (newFile != null)
            {
                _imagefile = newFile;
            }
        }
  //image factory load file - NewThread
  public IImageFile LoadFile(string filePath)
        {
            if (string.IsNullOrWhiteSpace(filePath))
            {
                return null;
            }

            var fileExtension = Path.GetExtension(filePath); // .tiff or .jpeg

            var file = new ImageFileTiff(filePath, _metatadaFactory, _metadataVersioner);

            file.LoadFile();

            return file;
        }
// ImageFileTiff LoadFile will create a decoder - NewThread
 public override void LoadFile()
        {
            using (var imageStream = new FileStream(_filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                Decoder = new JpegBitmapDecoder(imageStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);

                InitializeFile();
            }
        }

After we have an IImageFile we call on MainThread(UIThread)

var pages = _imagefile.LoadPages();

Where LoadPages is the place where the app breaks. also called on UIThread
    public List LoadPages()
        {
            var result = new List();

        foreach (var frame in Decoder.Frames)
        {
            result.Add(new ThumbnailModel
            {
                Name = _metadataLoader.GetPageName((BitmapMetadata)frame.Metadata),
                Bitmap = new WriteableBitmap(frame)
            });
        }

        return result;
    }

Body:
I thought you could simply return the decoder from the thread to be able to access it but your decoder is a TiffBitmapDecoder which inherits from DispatcherObject (https://learn.microsoft.com/en-gb/dotnet/api/system.windows.threading.dispatcherobject?view=netcore-3.1).

So you won't be able to access it from a different thread than the one where it was created msdn:"Only the thread that the Dispatcher was created on may access the DispatcherObject directly"

What you could do instead is use the decoder in it's thread and return the final result:

I couldn't build on your sample since there was to much missing for me to test it but I built a similar project to give an exemple:

public partial class MainWindow : Window
{
    public MainWindow()
    {

    }

    public TiffBitmapDecoder LoadFile()
    {
        OpenFileDialog openFileDialog = new OpenFileDialog();
        openFileDialog.InitialDirectory = "c:\\";
        openFileDialog.Filter = "tiff files (*.tif)|*.tif|All files (*.*)|*.*";
        openFileDialog.FilterIndex = 2;
        openFileDialog.RestoreDirectory = true;

        if (openFileDialog.ShowDialog() == true && !string.IsNullOrEmpty(openFileDialog.FileName))
        {
            //I didn't bother to check the file extension since it's just an exemple
            using (var imageStream = openFileDialog.OpenFile())
            {
                return new TiffBitmapDecoder(imageStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);
            }
        }
        else
        {
            //User cancelled
            return null;
        }
    }

    public List<ThumbnailModel> LoadPages(TiffBitmapDecoder decoder)
    {
        //TiffBitmapDecoder" inherits from DispatcherObject/>
        //https://learn.microsoft.com/en-gb/dotnet/api/system.windows.threading.dispatcherobject?view=netcore-3.1
        var result = new List<ThumbnailModel>();
        if (decoder != null)
        {
            try
            {
                foreach (var frame in decoder.Frames)
                {
                    result.Add(new ThumbnailModel
                    {
                        //set the variables
                    });
                }
            }
            catch(InvalidOperationException e)
            {
                MessageBox.Show(e.Message, "Error");
            }
        }
        else
        {
            //Nothing to do
        }
        return result;
    }

    private async Task AsyncLoading()
    {
        this.thumbnailModels = await Task.Run<List<ThumbnailModel>>(() =>
        {
            var decoder = this.LoadFile();
            return this.LoadPages(decoder);
        });
    }

    private List<ThumbnailModel> thumbnailModels = null;

    private async void AsyncLoadingButton_Click(object sender, RoutedEventArgs e)
    {
        await this.AsyncLoading();
    }
}

public class ThumbnailModel
{
}

Content of MainWindow.xaml just in case:

<Grid>
    <StackPanel Orientation="Vertical">
        <Button x:Name="NoReturnButton" Margin="10" HorizontalAlignment="Center" Content="Call AsyncLoadingNoReturn" Click="AsyncLoadingButton_Click" />
    </StackPanel>
</Grid>


问:
From semantic perspective, what's the moment an undefined behavior of `&mut` noalias occurred in Rust?
As Rust reference documention said

Breaking the pointer aliasing rules. &mut T and &T follow LLVM’s scoped noalias model, except if the &T contains an UnsafeCell.

It's really ambiguous.

I want to know that what's the exactly moment an undefined behavior of &mut noalias occurred in Rust.

Is it any of below, or something else?

When defining two &mut that point to the same address?

When two &mut that point to the same address exposed to rust?

When perfrom any operation on a &mut that point to the same address of any other &mut?

For example, this code is observously UB:

unsafe {
    let mut x = 123usize;
    let a = (&mut x as *mut usize).as_mut().unwrap(); // created, but not accessed
    let b = (&mut x as *mut usize).as_mut().unwrap(); // created, accessed
    *b = 666;
    drop(a);
}
```

<p>But what if I modify the code like this:</p>

<pre class="lang-rust prettyprint-override"><code>struct S<'a> {
    ref_x: &'a mut usize
}

fn main() {
    let mut x = 123;
    let s = S { ref_x: &mut x }; // like the `T` in `ManuallyDrop<T>`
    let taken = unsafe { std::ptr::read(&s as *const S) }; // like `ManuallyDrop<T>::take`
    // at thist ime, we have two `&mut x`
    *(taken.ref_x) = 666;
    drop(s);
    // UB or not?
}
</code>```

Is the second version also UB?

The second version is totally the same implemention to std::mem::ManuallyDrop. If the second version is UB, is it a security bug of std::mem::ManuallyDrop<T>?

答:
What the aliasing restriction is not

It is actually common to have multiple existing &mut T aliasing the same item.

The simplest example is:

```<code>fn main() {
   let mut i = 32;
   let j = &mut i;
   let k = &mut *j;

   *k = 3;

   println!("{}", i);
}
</code>```

Note, though, that due to borrowing rules you cannot access the other aliases simultaneously.

If you look at the implementation of ManuallyDrop::take:

```<code>pub unsafe fn take(slot: &mut ManuallyDrop<T>) -> T {
    ptr::read(&slot.value)
}
</code>```

You will note that there are no simultaneously accessible &mut T: calling the function re-borrows ManuallyDrop making slot the only accessible mutable reference.

Why is aliasing in Rust so ill-defined

It's really ambiguous. I want to know that what's the exactly moment an undefined behavior of &mut noalias occurred in Rust.

Tough luck, because as specified in the Nomicon:

Unfortunately, Rust hasn't actually defined its aliasing model.

The reason is that the language team wants to make sure that the definition they reach is both safe (demonstrably so), practical, and yet does not close the door to possible refinements. It's a tall order.

The Rust Unsafe Code Guidelines Working Group is still working on establishing the exact boundaries, and in particular Ralf Jung is working on an operational model for aliasing called Stacked Borrows.

Note: the Stacked Borrows model is implemented in MIRI, and therefore you can validate your code against the Stacked Borrows model simply by executing your code in MIRI. Of course Stacked Borrows is still experimental, so this doesn't guarantee anything.

What caution recommends

I personally subscribe to caution. Seeing as the exact model is unspecified, the rules are ever changing and therefore I recommend taking the stricter interpretation possible.

Thus, I interpret the no-aliasing rule of &mut T as:

At any point in the code, there shall not be two accessible references in scope which alias the same memory if one of them is &mut T.

That is, I consider that forming a &mut T to an instance T for which another &T or &mut T is in scope without invalidating the aliases (via borrowing) is ill-formed.

It may very well be overly cautious, but at least if the aliasing model ends up being more conservative than planned, my code will still be valid.

Body:
As Rust reference documention said

Breaking the pointer aliasing rules. &mut T and &T follow LLVM’s scoped noalias model, except if the &T contains an UnsafeCell.

It's really ambiguous.

I want to know that what's the exactly moment an undefined behavior of &mut noalias occurred in Rust.

Is it any of below, or something else?

When defining two &mut that point to the same address?

When two &mut that point to the same address exposed to rust?

When perfrom any operation on a &mut that point to the same address of any other &mut?

For example, this code is observously UB:

unsafe {
    let mut x = 123usize;
    let a = (&mut x as *mut usize).as_mut().unwrap(); // created, but not accessed
    let b = (&mut x as *mut usize).as_mut().unwrap(); // created, accessed
    *b = 666;
    drop(a);
}

But what if I modify the code like this:

struct S<'a> {
    ref_x: &'a mut usize
}

fn main() {
    let mut x = 123;
    let s = S { ref_x: &mut x }; // like the `T` in `ManuallyDrop<T>`
    let taken = unsafe { std::ptr::read(&s as *const S) }; // like `ManuallyDrop<T>::take`
    // at thist ime, we have two `&mut x`
    *(taken.ref_x) = 666;
    drop(s);
    // UB or not?
}

Is the second version also UB?

The second version is totally the same implemention to std::mem::ManuallyDrop. If the second version is UB, is it a security bug of std::mem::ManuallyDrop<T>?

Body:
What the aliasing restriction is not

It is actually common to have multiple existing &mut T aliasing the same item.

The simplest example is:

fn main() {
   let mut i = 32;
   let j = &mut i;
   let k = &mut *j;

   *k = 3;

   println!("{}", i);
}

Note, though, that due to borrowing rules you cannot access the other aliases simultaneously.

If you look at the implementation of ManuallyDrop::take:

pub unsafe fn take(slot: &mut ManuallyDrop<T>) -> T {
    ptr::read(&slot.value)
}

You will note that there are no simultaneously accessible &mut T: calling the function re-borrows ManuallyDrop making slot the only accessible mutable reference.

Why is aliasing in Rust so ill-defined

It's really ambiguous. I want to know that what's the exactly moment an undefined behavior of &mut noalias occurred in Rust.

Tough luck, because as specified in the Nomicon:

Unfortunately, Rust hasn't actually defined its aliasing model.

The reason is that the language team wants to make sure that the definition they reach is both safe (demonstrably so), practical, and yet does not close the door to possible refinements. It's a tall order.

The Rust Unsafe Code Guidelines Working Group is still working on establishing the exact boundaries, and in particular Ralf Jung is working on an operational model for aliasing called Stacked Borrows.

Note: the Stacked Borrows model is implemented in MIRI, and therefore you can validate your code against the Stacked Borrows model simply by executing your code in MIRI. Of course Stacked Borrows is still experimental, so this doesn't guarantee anything.

What caution recommends

I personally subscribe to caution. Seeing as the exact model is unspecified, the rules are ever changing and therefore I recommend taking the stricter interpretation possible.

Thus, I interpret the no-aliasing rule of &mut T as:

At any point in the code, there shall not be two accessible references in scope which alias the same memory if one of them is &mut T.

That is, I consider that forming a &mut T to an instance T for which another &T or &mut T is in scope without invalidating the aliases (via borrowing) is ill-formed.

It may very well be overly cautious, but at least if the aliasing model ends up being more conservative than planned, my code will still be valid.


问:
Configure Sorbet to treat all files without comment as if they had a typed: ignore comment
My question is related to this one 1 but I'm ok with adding type comments to the files that have type annotations. We just don't want to have auto generated comments on hundreds of files although nothing else happened in the files. Is there a way to configure Sorbet to work like this?</p>

答:
You might go a long way by using the following Sorbet flags:

$ srb tc --help
Typechecker for Ruby
Usage:
  sorbet [OPTION...] <path 1> <path 2> ...
...
      --ignore string           Ignores input files that contain the given
                                string in their paths (relative to the input
                                path passed to Sorbet). Strings beginning with /
                                match against the prefix of these relative
                                paths; others are substring matchs. Matches must
                                be against whole folder and file names, so
                                `foo` matches `/foo/bar.rb` and `/bar/foo/baz.rb`
                                but not `/foo.rb` or `/foo2/bar.rb`.
...
      --typed-override filepath.yaml
                                Yaml config that overrides strictness levels
                                on files (default: "")
...
```

If all the files you want to ignore are in a folder together or can be matched by some path matches, then a few --ignore lines in your sorbet/config file should do what you want.

Otherwise, you could use the typed overrides from a YAML file to make Sorbet interpret the files you want as typed: ignore. You should, again, be able to add this flag to your sorbet/config file.

Body:
You might go a long way by using the following Sorbet flags:

$ srb tc --help
Typechecker for Ruby
Usage:
  sorbet [OPTION...] <path 1> <path 2> ...
...
      --ignore string           Ignores input files that contain the given
                                string in their paths (relative to the input
                                path passed to Sorbet). Strings beginning with /
                                match against the prefix of these relative
                                paths; others are substring matchs. Matches must
                                be against whole folder and file names, so
                                `foo` matches `/foo/bar.rb` and `/bar/foo/baz.rb`
                                but not `/foo.rb` or `/foo2/bar.rb`.
...
      --typed-override filepath.yaml
                                Yaml config that overrides strictness levels
                                on files (default: "")
...

If all the files you want to ignore are in a folder together or can be matched by some path matches, then a few --ignore lines in your sorbet/config file should do what you want.

Otherwise, you could use the typed overrides from a YAML file to make Sorbet interpret the files you want as typed: ignore. You should, again, be able to add this flag to your sorbet/config file.