问:
Hive query output to file
I run hive query by java code.
Example:

"SELECT * FROM table WHERE id > 100"

How to export result to hdfs file.

答:
Two ways can store HQL query results:

Save into HDFS Location

INSERT OVERWRITE DIRECTORY "HDFS Path" ROW FORMAT DELIMITED FIELDS TERMINATED BY '|'
SELECT * FROM XXXX LIMIT 10;
```

<ol start="2">
<li>Save to Local File</li>
</ol>

<pre class="lang-sh prettyprint-override"><code>$hive  -e "select * from table_Name" > ~/sample_output.txt
$hive -e "select * from table where city = 'London' and id >=100" > /home/user/outputdirectory/city details.csv
</code>```

Title: Hive query output to file

Body:
Two ways can store HQL query results:

Save into HDFS Location

INSERT OVERWRITE DIRECTORY "HDFS Path" ROW FORMAT DELIMITED FIELDS TERMINATED BY '|'
SELECT * FROM XXXX LIMIT 10;

Save to Local File

$hive  -e "select * from table_Name" > ~/sample_output.txt
$hive -e "select * from table where city = 'London' and id >=100" > /home/user/outputdirectory/city details.csv


来源: stackexchange

问:
Get latest date in a column
I have a bunch of videos with a channelId field and a "createdAt" field with values like:

```<code>2019-08-13 11:59:46.000000
2019-03-05 18:00:00.000000
2018-12-21 12:14:46.000000
</code>```

Each channelId has at least 1 video, often more. I want the latest video date for each channelId.

My SQLite code:

```<code>SELECT
julianday(max(v.createdAt, "utc")) AS days
FROM videos v
GROUP BY v.channelId
</code>```

returns NULL for the "days".

But

```<code>SELECT
julianday(min(v.createdAt, "utc")) AS days
FROM videos v
GROUP BY v.channelId
</code>```

works?

How do I get the latest video upload time? Why does max() return NULL while min() works?

答:
Change to this:

```<code>julianday(max(v.publishedAt), "utc")
</code>```

Your code does not use the aggregation max() function but the max() function that compares values in a list and returns the maximum.

Also:

```<code>julianday(min(v.publishedAt), "utc")
</code>```

although you say it works. It works because any datetime value compared as a string is less than the string "utc".

ContentLicense: CC BY-SA 4.0

Title: Get latest date in a column

Body:
I have a bunch of videos with a channelId field and a "createdAt" field with values like:

2019-08-13 11:59:46.000000
2019-03-05 18:00:00.000000
2018-12-21 12:14:46.000000

Each channelId has at least 1 video, often more. I want the latest video date for each channelId.

My SQLite code:

SELECT
julianday(max(v.createdAt, "utc")) AS days
FROM videos v
GROUP BY v.channelId

returns NULL for the "days".

But

SELECT
julianday(min(v.createdAt, "utc")) AS days
FROM videos v
GROUP BY v.channelId

works?

How do I get the latest video upload time? Why does max() return NULL while min() works?

Body:
Change to this:

julianday(max(v.publishedAt), "utc")

Your code does not use the aggregation max() function but the max() function that compares values in a list and returns the maximum.

Also:

julianday(min(v.publishedAt), "utc")

although you say it works. It works because any datetime value compared as a string is less than the string "utc".


问:
PostgreSQL SSL Configuration
I have tried a lot but did't get exact knowledge to copy which files to client side

Getting error " Valid authentication certificate required"

Below is postgres DB server directory

```<code>total 80
skipping unwanted directory
-rw-------. 1 postgres postgres  1285 Feb 13 20:16 rootCA.crt
-rw-------. 1 postgres postgres  1168 Feb 13 20:16 server.crt
-rw-------. 1 postgres postgres  1679 Feb 13 20:17 server.key
</code>```

Below is postgresql.conf file content related to SSL configuration.

```<code>[postgres@munmvs2951 raj]$ cat postgresql.conf | grep ssl
ssl = on                                # (change requires restart)
ssl_ciphers = 'HIGH:MEDIUM:+3DES:!aNULL' # allowed SSL ciphers
#ssl_prefer_server_ciphers = on         # (change requires restart)
#ssl_ecdh_curve = 'prime256v1'          # (change requires restart)
#ssl_renegotiation_limit = 512MB        # amount of data between renegotiations
ssl_cert_file = 'server.crt'            # (change requires restart)
ssl_key_file = 'server.key'             # (change requires restart)
ssl_ca_file = 'rootCA.crt'                      # (change requires restart)
#ssl_crl_file = ''                      # (change requires restart)
</code>```

Below is the pg_hba file.

```<code># TYPE  DATABASE        USER            ADDRESS                 METHOD

# "local" is for Unix domain socket connections only
local   all             all                                     trust
# IPv4 local connections:
host    all             all             127.0.0.1/32            trust
# IPv6 local connections:
host    all             all             ::1/128                 trust
# Allow replication connections from localhost, by a user with the
# replication privilege.
#local   replication     postgres                                trust
#host    replication     postgres        127.0.0.1/32            trust
#host    replication     postgres        ::1/128                 trust
#secure client
hostssl  postgres       postgres        clientip/32               md5 clientcert=1
</code>```

Below is the client side PostgreSQL user home directory from where psql will connect to server.

```<code>[postgres@clinet ~]$ ll
total 32
-rw------- 1 postgres postgres 1168 Feb 15 10:27 client.crt
-rw------- 1 postgres postgres  989 Feb 15 10:27 client.csr
-rw------- 1 postgres postgres 1285 Feb 15 11:47 rootCA.crt
-rw------- 1 postgres postgres 1675 Feb 15 11:47 rootCA.key
-rw------- 1 postgres postgres   17 Feb 15 11:47 rootCA.srl
-rw------- 1 postgres postgres 1168 Feb 15 11:47 server.crt
-rw------- 1 postgres postgres  989 Feb 15 11:47 server.csr
-rw------- 1 postgres postgres 1679 Feb 15 11:47 server.key
</code>```

```<code>[postgres@client ~]$ pwd
/home/postgres
</code>```

when i going to connect, getting below error.

```<code>[postgres@client ~]$ /opt/PostgresPlus/9.4AS/bin/psql -U postgres -p5443 -hserverip
psql.bin: FATAL:  connection requires a valid client certificate
FATAL:  no pg_hba.conf entry for host "10.80.x.x", user "postgres", database "postgres", SSL off
</code>```

However, I can access without  clientcert=1 in pg_hba file.

Ref:

```<code>[postgres@client ~]$ /opt/PostgresPlus/9.4AS/bin/psql -U postgres -p5443 -hserverip
psql.bin (9.4.1.3)
SSL connection (protocol: TLSv1.2, cipher: ECDHE-RSA-AES256-GCM-SHA384, bits: 256, compression: off)
Type "help" for help.

postgres=#
</code>```

In above successful connection, i think ssl checking only at server side not client side.

but i want to know which files should i copy to PostgreSQL home directory @client side. to check certificate as per clientcert=1

Thanks for your help.

答:
See https://www.postgresql.org/docs/current/libpq-ssl.html

Below is the client side PostgreSQL user home directory from where psql will connect to server

They do not belong in the home directory, they belong in a subdirectory of the home directory named .postgresql.  Or in Windows, in a directory named "%APPDATA% \ postgresql".  And file rootCA.crt has to be named root.crt, unless you have gone out of your way to change the name/location on the client side configuration, which it doesn't seem you have done (you have changed it on the server side, but that doesn't change it on the client side).  And client.crt should be named postgresql.crt and you are missing the key file for it. And the fact that you have a file named rootCA.key in the client's directory is frightening, no one but the CA should have access to that.

Title: PostgreSQL SSL Configuration

Body:
I have tried a lot but did't get exact knowledge to copy which files to client side

Getting error " Valid authentication certificate required"

Below is postgres DB server directory

total 80
skipping unwanted directory
-rw-------. 1 postgres postgres  1285 Feb 13 20:16 rootCA.crt
-rw-------. 1 postgres postgres  1168 Feb 13 20:16 server.crt
-rw-------. 1 postgres postgres  1679 Feb 13 20:17 server.key

Below is postgresql.conf file content related to SSL configuration.

[postgres@munmvs2951 raj]$ cat postgresql.conf | grep ssl
ssl = on                                # (change requires restart)
ssl_ciphers = 'HIGH:MEDIUM:+3DES:!aNULL' # allowed SSL ciphers
#ssl_prefer_server_ciphers = on         # (change requires restart)
#ssl_ecdh_curve = 'prime256v1'          # (change requires restart)
#ssl_renegotiation_limit = 512MB        # amount of data between renegotiations
ssl_cert_file = 'server.crt'            # (change requires restart)
ssl_key_file = 'server.key'             # (change requires restart)
ssl_ca_file = 'rootCA.crt'                      # (change requires restart)
#ssl_crl_file = ''                      # (change requires restart)

Below is the pg_hba file.

# TYPE  DATABASE        USER            ADDRESS                 METHOD

# "local" is for Unix domain socket connections only
local   all             all                                     trust
# IPv4 local connections:
host    all             all             127.0.0.1/32            trust
# IPv6 local connections:
host    all             all             ::1/128                 trust
# Allow replication connections from localhost, by a user with the
# replication privilege.
#local   replication     postgres                                trust
#host    replication     postgres        127.0.0.1/32            trust
#host    replication     postgres        ::1/128                 trust
#secure client
hostssl  postgres       postgres        clientip/32               md5 clientcert=1

Below is the client side PostgreSQL user home directory from where psql will connect to server.

[postgres@clinet ~]$ ll
total 32
-rw------- 1 postgres postgres 1168 Feb 15 10:27 client.crt
-rw------- 1 postgres postgres  989 Feb 15 10:27 client.csr
-rw------- 1 postgres postgres 1285 Feb 15 11:47 rootCA.crt
-rw------- 1 postgres postgres 1675 Feb 15 11:47 rootCA.key
-rw------- 1 postgres postgres   17 Feb 15 11:47 rootCA.srl
-rw------- 1 postgres postgres 1168 Feb 15 11:47 server.crt
-rw------- 1 postgres postgres  989 Feb 15 11:47 server.csr
-rw------- 1 postgres postgres 1679 Feb 15 11:47 server.key

[postgres@client ~]$ pwd
/home/postgres

when i going to connect, getting below error.

[postgres@client ~]$ /opt/PostgresPlus/9.4AS/bin/psql -U postgres -p5443 -hserverip
psql.bin: FATAL:  connection requires a valid client certificate
FATAL:  no pg_hba.conf entry for host "10.80.x.x", user "postgres", database "postgres", SSL off

However, I can access without  clientcert=1 in pg_hba file.

Ref:

[postgres@client ~]$ /opt/PostgresPlus/9.4AS/bin/psql -U postgres -p5443 -hserverip
psql.bin (9.4.1.3)
SSL connection (protocol: TLSv1.2, cipher: ECDHE-RSA-AES256-GCM-SHA384, bits: 256, compression: off)
Type "help" for help.

postgres=#

In above successful connection, i think ssl checking only at server side not client side.

but i want to know which files should i copy to PostgreSQL home directory @client side. to check certificate as per clientcert=1

Thanks for your help.


问:
Regex get subfolder name from URL after domain extension
i'm new to regex, so I want to write a regExp to identify a special subfolder path directly after the tld top level domain extension.

http://sub.domain.tld/foo/bar

How to do it?

答:
If you're searching for a parent folder which itself is in the root directory, try like /\.tld\/([^/]+)\//

const str = "http://sub.domain.tld/foo/bar";

console.log(str.match(/\.tld\/([^/]+)\//)[1])```

\.tld\/ preceded by .tld/

([^/]+) capture everything that is not a / ...

\/ ...till the first /

Body:
If you're searching for a parent folder which itself is in the root directory, try like /\.tld\/([^/]+)\//

const str = "http://sub.domain.tld/foo/bar";

console.log(str.match(/\.tld\/([^/]+)\//)[1])

\.tld\/ preceded by .tld/

([^/]+) capture everything that is not a / ...

\/ ...till the first /


问:
Unable to pass prop back to parent component
I'm doing a simple test where I have a name state in the parent component which I update when a button in the child is clicked. But this does not work, and I'm confused on if I'm doing something wrong.

Parent:

```<code>import React from "react";
import "./styles.css";
import Hello from "./Hello";

export default function App() {
  const [name, setName] = React.useState();

  const handle = item => {
    setName(item);
  };

  console.log(name);

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <Hello test={handle} />
      {name}
    </div>
  );
}

</code>```

Child:

```<code>import React from "react";

export default function App() {
  return (
    <div>
      <button onclick={() => this.props.test("TEST")}>Activate Lasers</button>
    </div>
  );
}
</code>```

What am I doing wrong?

答:
```<code>import React from "react";

export default function App(props) {
 return (
    <div>
      <button onClick={() => props.test("TEST")}>Activate Lasers </button>
    </div>
  );
}
</code>```

It should be onClick Secondly you are using this which is pointing to stateless component that is undefined and have no property props within it.

Body:
I'm doing a simple test where I have a name state in the parent component which I update when a button in the child is clicked. But this does not work, and I'm confused on if I'm doing something wrong.

Parent:

import React from "react";
import "./styles.css";
import Hello from "./Hello";

export default function App() {
  const [name, setName] = React.useState();

  const handle = item => {
    setName(item);
  };

  console.log(name);

  return (

Hello CodeSandbox

Start editing to see some magic happen!

      <Hello test={handle} />
      {name}

  );
}

Child:

import React from "react";

export default function App() {
  return (

      <button onclick={() => this.props.test("TEST")}>Activate Lasers</button>

  );
}

What am I doing wrong?

Body:
import React from "react";

export default function App(props) {
 return (
    <div>
      <button onClick={() => props.test("TEST")}>Activate Lasers </button>
    </div>
  );
}

It should be onClick Secondly you are using this which is pointing to stateless component that is undefined and have no property props within it.


问:
Is it possible to implement multi-stage SORT using QUERY?
https://docs.google.com/spreadsheets/d/1XoxAY8MEgrGrpG1yJ2VthHDOGr6u2pBZC1YotpDfslE/edit?usp=sharing

Tab Deck Trends cell A3 contains the QUERY command where you can see the current sorting order.

What I am wanting to achieve is the following:

Any row where Col E equals 4, I would like the secondary sorting to be based on Col F

All other rows I would like the secondary sorting to be based on Col D (as it currently is set).

Is it even possible to have multiple sorting rules in one QUERY?

答:
try:

```<code>=QUERY({QUERY({
 'Combined Opp Meta'!A2:G11; 'Combined Opp Meta'!A14:G23; 'Combined Opp Meta'!A26:G35},
 "where Col5 = 4
  order by Col5 desc,Col6 desc", 0);
 QUERY({
 'Combined Opp Meta'!A2:G11; 'Combined Opp Meta'!A14:G23; 'Combined Opp Meta'!A26:G35},
 "where Col5 <> 4
  order by Col5 desc,Col4 desc", 0)},
 "limit 12", 0)
</code>```

array literal fix:

```<code>=QUERY({IFERROR(QUERY({
 'Combined Opp Meta'!A2:G11; 'Combined Opp Meta'!A14:G23; 'Combined Opp Meta'!A26:G35},
 "where Col5 = 4
  order by Col5 desc,Col6 desc", 0), {"","","","","","",""});
 IFERROR(QUERY({
 'Combined Opp Meta'!A2:G11; 'Combined Opp Meta'!A14:G23; 'Combined Opp Meta'!A26:G35},
 "where Col5 <> 4
  order by Col5 desc,Col4 desc", 0), {"","","","","","",""})},
 "where Col1 is not null limit 12", 0)
</code>```

Body:
try:

=QUERY({QUERY({
 'Combined Opp Meta'!A2:G11; 'Combined Opp Meta'!A14:G23; 'Combined Opp Meta'!A26:G35},
 "where Col5 = 4
  order by Col5 desc,Col6 desc", 0);
 QUERY({
 'Combined Opp Meta'!A2:G11; 'Combined Opp Meta'!A14:G23; 'Combined Opp Meta'!A26:G35},
 "where Col5 <> 4
  order by Col5 desc,Col4 desc", 0)},
 "limit 12", 0)

array literal fix:

=QUERY({IFERROR(QUERY({
 'Combined Opp Meta'!A2:G11; 'Combined Opp Meta'!A14:G23; 'Combined Opp Meta'!A26:G35},
 "where Col5 = 4
  order by Col5 desc,Col6 desc", 0), {"","","","","","",""});
 IFERROR(QUERY({
 'Combined Opp Meta'!A2:G11; 'Combined Opp Meta'!A14:G23; 'Combined Opp Meta'!A26:G35},
 "where Col5 <> 4
  order by Col5 desc,Col4 desc", 0), {"","","","","","",""})},
 "where Col1 is not null limit 12", 0)


问:
Crooked 2D array when printing it on stdout (populating a blank 2D array)
I'm trying to populate a blank 2d array (matrix) with a character D put onto a random position.

This is the code which works properly:

```<code>#define RIGHE 10
#define COLONNE 10

void drawMap(char[][COLONNE]);

int main()
{
    char mappa[RIGHE][COLONNE] = {" "}; // blank, as an empty chess board

    drawMap(mappa);

    return 0;

}

/* Disegna la mappa da gioco */
void drawMap(char mappa[][COLONNE])
{
    int rigaDestinazione, colonnaDestinazione;

    srand(time(NULL)); // Randomizza numeri

    rigaDestinazione = rand() % RIGHE;
    colonnaDestinazione = rand() % COLONNE;

    mappa[rigaDestinazione][colonnaDestinazione] = 'D';

    for (int i = 0; i < RIGHE; i++) {
        for (int j = 0; j < RIGHE; j++) {
            printf("[ %c ]", mappa[i][j]);
        }
        printf("\n");
    }

}
</code>```

Unfortunately when I print it, it seems to be asymmetric as you can see, the output is:

```<code>[   ][  ][  ][  ][  ][  ][  ][  ][  ][  ]
[  ][  ][  ][  ][  ][  ][  ][  ][  ][  ]
[  ][  ][  ][  ][  ][  ][  ][  ][  ][  ]
[  ][  ][  ][  ][  ][  ][  ][  ][  ][  ]
[  ][  ][  ][  ][  ][  ][  ][  ][  ][  ]
[  ][  ][  ][  ][  ][  ][  ][  ][  ][  ]
[  ][  ][  ][  ][  ][  ][  ][  ][  ][  ]
[  ][  ][  ][  ][ D ][  ][  ][  ][  ][  ]
[  ][  ][  ][  ][  ][  ][  ][  ][  ][  ]
[  ][  ][  ][  ][  ][  ][  ][  ][  ][  ]
</code>```

How can I fix?

答:
This:

```<code>char mappa[RIGHE][COLONNE] = {" "}; // blank, as an empty chess board
</code>```

Is initializing only the first element of the array, you can use memset to initialize them all:

```<code>memset(mappa, ' ', sizeof(mappa)); //<-- #include <string.h>
</code>```

Live sample

You should also note that to initialize a char you use ' ' not " ", this is for strings.

Just to be thorough, srand(time(NULL)); only needs to be executed once, you can place it in main() before the call of the function.

Body:
I'm trying to populate a blank 2d array (matrix) with a character D put onto a random position.

This is the code which works properly:

#define RIGHE 10
#define COLONNE 10

void drawMap(char[][COLONNE]);

int main()
{
    char mappa[RIGHE][COLONNE] = {" "}; // blank, as an empty chess board

    drawMap(mappa);

    return 0;

}

/* Disegna la mappa da gioco */
void drawMap(char mappa[][COLONNE])
{
    int rigaDestinazione, colonnaDestinazione;

    srand(time(NULL)); // Randomizza numeri

    rigaDestinazione = rand() % RIGHE;
    colonnaDestinazione = rand() % COLONNE;

    mappa[rigaDestinazione][colonnaDestinazione] = 'D';

    for (int i = 0; i < RIGHE; i++) {
        for (int j = 0; j < RIGHE; j++) {
            printf("[ %c ]", mappa[i][j]);
        }
        printf("\n");
    }

}

Unfortunately when I print it, it seems to be asymmetric as you can see, the output is:

[   ][  ][  ][  ][  ][  ][  ][  ][  ][  ]
[  ][  ][  ][  ][  ][  ][  ][  ][  ][  ]
[  ][  ][  ][  ][  ][  ][  ][  ][  ][  ]
[  ][  ][  ][  ][  ][  ][  ][  ][  ][  ]
[  ][  ][  ][  ][  ][  ][  ][  ][  ][  ]
[  ][  ][  ][  ][  ][  ][  ][  ][  ][  ]
[  ][  ][  ][  ][  ][  ][  ][  ][  ][  ]
[  ][  ][  ][  ][ D ][  ][  ][  ][  ][  ]
[  ][  ][  ][  ][  ][  ][  ][  ][  ][  ]
[  ][  ][  ][  ][  ][  ][  ][  ][  ][  ]

How can I fix?

Body:
This:

char mappa[RIGHE][COLONNE] = {" "}; // blank, as an empty chess board

Is initializing only the first element of the array, you can use memset to initialize them all:

memset(mappa, ' ', sizeof(mappa)); //<-- #include <string.h>

Live sample

You should also note that to initialize a char you use ' ' not " ", this is for strings.

Just to be thorough, srand(time(NULL)); only needs to be executed once, you can place it in main() before the call of the function.


问:
How to add objects to a list with a thread and use the list at the same time without getting ConcurrentModificationException?
The title tells it all, I have a Timer t1 which periodically adds objects to a List.
Then I have an other Timer t2 iterating on the list at constant intervals to display its content.

I totaly understand why i'm getting these exceptions but I can't come up with the right answer to avoid it. Iv'e tried running my operations in synchronized(list){} and such things but nothing makes it. My algorithm apears to be working just fine despite these exceptions but i would like to make it clean nontheless.

Any idea?

Edit:
I'm using java.util.Timer;

答: https://www.baeldung.com/java-mutex Maybe take a look at mutex-structures, these might come in handy</p>


问:
How to create a docker image from dotnet core 2.2 and powershell core?
I'm trying to "dockerize" a dotnet standard library, for now I'm using a simple docker file, to build and pack it using just dotnet cli commands.

```<code># Build stage
FROM microsoft/dotnet:2.2-sdk as build
ARG Version
WORKDIR /src
COPY . .

RUN dotnet restore
RUN dotnet build -p:Version=$Version -c Release --no-restore

RUN dotnet pack -p:Version=$Version -c Release --include-symbols --no-restore --no-build -o /src/.artifacts
</code>```

I want to be able to run a powershell script ci.ps1 from my docker file, but there is no powershell core installed in the dotnet:2.2-sdk.

Is there any examples out there on how to run powershell core scripts from inside a dotnet image ? How can I create my own image from powershell core and dotnet sdk ?

Thanks

答:
This is the exact use case I recently needed to implement, and you can indeed get Powershell Core up and running from a .NET Core SDK image - in my case the below was done against image mcr.microsoft.com/dotnet/core/sdk:2.2-stretch.

The full solution looks something like as follows:

```<code>FROM mcr.microsoft.com/dotnet/core/sdk:2.2-stretch AS build
...

FROM build AS final
WORKDIR /app
COPY --from=publish /app/publish .
RUN dotnet tool install --global PowerShell \
&& ln -s /root/.dotnet/tools/pwsh /usr/bin/pwsh
</code>```

Where:

dotnet tool install --global PowerShell installs PowerShell into the container. However this alone is not quite good enough because as observed in @amirtharaj-rs answer, the command pwsh will not work unless invoked from the PowerShell installation directory.
For example, you may encounter something like:

```<code>root@a1d30119664d:/app# pwsh
bash: pwsh: command not found
</code>```

ln -s /root/.dotnet/tools/pwsh /usr/bin/pwsh creates a link called pwsh which points to where PowerShell is installed. This is the key line which enables pwsh to be invoked from anywhere:

```<code>root@a1d30119664d:/app# pwsh
PowerShell 6.2.4
Copyright (c) Microsoft Corporation. All rights reserved.

https://aka.ms/pscore6-docs
Type 'help' to get help.
</code>```

If the above does not work, then you may need to ensure that the execute bit is set on /usr/bin/pwsh. You can check this by running ls -l /usr/bin/pwsh.

If you do need to set the execute bit, add chmod 755 /root/.dotnet/tools/pwsh to the Dockerfile RUN command. So the complete RUN command would look something like:

```<code>FROM mcr.microsoft.com/dotnet/core/sdk:2.2-stretch AS build
...

FROM build AS final
WORKDIR /app
COPY --from=publish /app/publish .
RUN dotnet tool install --global PowerShell \
&& ln -s /root/.dotnet/tools/pwsh /usr/bin/pwsh
&& chmod 755 /root/.dotnet/tools/pwsh
</code>```

If interested, I learnt the above via the discussion history on this Github issue: https://github.com/Microsoft/azure-pipelines-agent/issues/1862.

Body:
I'm trying to "dockerize" a dotnet standard library, for now I'm using a simple docker file, to build and pack it using just dotnet cli commands.

# Build stage
FROM microsoft/dotnet:2.2-sdk as build
ARG Version
WORKDIR /src
COPY . .

RUN dotnet restore
RUN dotnet build -p:Version=$Version -c Release --no-restore

RUN dotnet pack -p:Version=$Version -c Release --include-symbols --no-restore --no-build -o /src/.artifacts

I want to be able to run a powershell script ci.ps1 from my docker file, but there is no powershell core installed in the dotnet:2.2-sdk.

Is there any examples out there on how to run powershell core scripts from inside a dotnet image ? How can I create my own image from powershell core and dotnet sdk ?

Thanks

Body:
This is the exact use case I recently needed to implement, and you can indeed get Powershell Core up and running from a .NET Core SDK image - in my case the below was done against image mcr.microsoft.com/dotnet/core/sdk:2.2-stretch.

The full solution looks something like as follows:

FROM mcr.microsoft.com/dotnet/core/sdk:2.2-stretch AS build
...

FROM build AS final
WORKDIR /app
COPY --from=publish /app/publish .
RUN dotnet tool install --global PowerShell \
&& ln -s /root/.dotnet/tools/pwsh /usr/bin/pwsh

Where:

dotnet tool install --global PowerShell installs PowerShell into the container. However this alone is not quite good enough because as observed in @amirtharaj-rs answer, the command pwsh will not work unless invoked from the PowerShell installation directory.
For example, you may encounter something like:

root@a1d30119664d:/app# pwsh
bash: pwsh: command not found

ln -s /root/.dotnet/tools/pwsh /usr/bin/pwsh creates a link called pwsh which points to where PowerShell is installed. This is the key line which enables pwsh to be invoked from anywhere:

root@a1d30119664d:/app# pwsh
PowerShell 6.2.4
Copyright (c) Microsoft Corporation. All rights reserved.

https://aka.ms/pscore6-docs
Type 'help' to get help.

If the above does not work, then you may need to ensure that the execute bit is set on /usr/bin/pwsh. You can check this by running ls -l /usr/bin/pwsh.

If you do need to set the execute bit, add chmod 755 /root/.dotnet/tools/pwsh to the Dockerfile RUN command. So the complete RUN command would look something like:

FROM mcr.microsoft.com/dotnet/core/sdk:2.2-stretch AS build
...

FROM build AS final
WORKDIR /app
COPY --from=publish /app/publish .
RUN dotnet tool install --global PowerShell \
&& ln -s /root/.dotnet/tools/pwsh /usr/bin/pwsh
&& chmod 755 /root/.dotnet/tools/pwsh

If interested, I learnt the above via the discussion history on this Github issue: https://github.com/Microsoft/azure-pipelines-agent/issues/1862.


问:
How do symbolic references resolve to direct references in Class loading phase in Java?
In class file's constant pool a class reference is show as CONSTANT_Class_info structure. How does it get resolved to direct memory address?
The memory space which CONSTANT_Class_info structure points to and memory address occupied are not the same...</p>

答: The CONSTANT_Class_info structure contains an index pointing to a string/utf8 value in the same constant pool. This string/utf8 contains the name of the class to be resolved. If the class in question has a already been loaded then the JVM uses some kind of data structure/lookup function to map the name to a class, while if the class has not already been loaded, then the name is used to find the class in question on the classpath, and load it. </p>


问:
Show a modal after images are uploaded with JS and Firebase
How to show a modal after images being uploaded to firebase storage.

```<code>   imgRef1.put(file1).then(function(snapshot) {
            console.log('Uploaded a blob or file!');
                snapshot.ref.getDownloadURL().then(function(downloadURL) {
                    console.log("File available at", downloadURL);
                    imgAns1 = downloadURL;
                });
   }).catch(error => {
        console.log("Error Occured");
   });;
</code>```

I am uploading a file with the above code, and getting the image URL. And then I am assigning it to a imageview src in a modal.

```<code> document.getElementById("imgSelectAns1").src = imgAns1;
</code>```

But when modal opens up image won't load because it takes some time to upload this. How can I open the modal after the image is being successfully uploaded ?

答:
Both uploading data and getting a download URL are asynchronous operations. While the call to the server is going on, the rest of your code continues to run. Then when the server has returned data, your callback gets called.

This is easiest to understand if you place some logging statements:

```<code>console.log("Starting upload...");
imgRef1.put(file1).then(function(snapshot) {
    console.log('Uploaded a blob or file. Getting download URL...');
    snapshot.ref.getDownloadURL().then(function(downloadURL) {
        console.log("File available at", downloadURL);
        imgAns1 = downloadURL;
    });
    console.log("Started getting download URL");
}).catch(error => {
    console.error("Error occurred: "+error);
});
console.log("Started upload");
</code>```

If you run this code, the output will be:

Starting upload...

Started upload

Uploaded a blob or file. Getting download URL...

Started getting download URL

File available at...

So the code doesn't execute in the same order as it exists in your file. Instead the callbacks get called later, after the calls to the server are complete. Because of this any code that needs the data from the server needs to be inside the callback function, or be called from there.

Most likely you're calling document.getElementById("imgSelectAns1").src = imgAns1 from somewhere in your code, when imgAns1 = downloadURL hasn't been called yet.

The fix is to move that code into the callback:

```<code>imgRef1.put(file1).then(function(snapshot) {
    snapshot.ref.getDownloadURL().then(function(downloadURL) {
        document.getElementById("imgSelectAns1").src = downloadURL;
    });
}).catch(error => {
    console.error("Error occurred: "+error);
});
</code>```

Body:
How to show a modal after images being uploaded to firebase storage.

   imgRef1.put(file1).then(function(snapshot) {
            console.log('Uploaded a blob or file!');
                snapshot.ref.getDownloadURL().then(function(downloadURL) {
                    console.log("File available at", downloadURL);
                    imgAns1 = downloadURL;
                });
   }).catch(error => {
        console.log("Error Occured");
   });;

I am uploading a file with the above code, and getting the image URL. And then I am assigning it to a imageview src in a modal.

 document.getElementById("imgSelectAns1").src = imgAns1;

But when modal opens up image won't load because it takes some time to upload this. How can I open the modal after the image is being successfully uploaded ?

Body:
Both uploading data and getting a download URL are asynchronous operations. While the call to the server is going on, the rest of your code continues to run. Then when the server has returned data, your callback gets called.

This is easiest to understand if you place some logging statements:

console.log("Starting upload...");
imgRef1.put(file1).then(function(snapshot) {
    console.log('Uploaded a blob or file. Getting download URL...');
    snapshot.ref.getDownloadURL().then(function(downloadURL) {
        console.log("File available at", downloadURL);
        imgAns1 = downloadURL;
    });
    console.log("Started getting download URL");
}).catch(error => {
    console.error("Error occurred: "+error);
});
console.log("Started upload");

If you run this code, the output will be:

Starting upload...

Started upload

Uploaded a blob or file. Getting download URL...

Started getting download URL

File available at...

So the code doesn't execute in the same order as it exists in your file. Instead the callbacks get called later, after the calls to the server are complete. Because of this any code that needs the data from the server needs to be inside the callback function, or be called from there.

Most likely you're calling document.getElementById("imgSelectAns1").src = imgAns1 from somewhere in your code, when imgAns1 = downloadURL hasn't been called yet.

The fix is to move that code into the callback:

imgRef1.put(file1).then(function(snapshot) {
    snapshot.ref.getDownloadURL().then(function(downloadURL) {
        document.getElementById("imgSelectAns1").src = downloadURL;
    });
}).catch(error => {
    console.error("Error occurred: "+error);
});


问:
Filter out the text files
The code separates files from directories.

I am trying to filter out the text files(.txt) and print out the files that remain.

I don't want the text files to be printed at all. I want the code to be implemented after the if statement if (listOfFiles[i].isFile()) { so after it checks to see if a given value is an actual file and then to determine if it is a text file, and if either test fails, add it to the listOfFiles array list.

Need help

```<code>import java.io.BufferedInputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class Exc_3 {

    public static void main(String[] args) {
        File folder = new File("C:\\Users\\skyla\\Desktop");
        File[] listOfFiles = folder.listFiles();
        List<String> files = new ArrayList<>();
        List<String> directories = new ArrayList<>();

        for (int i = 0; i < listOfFiles.length; i++) {

            if (listOfFiles[i].isFile()) {
                    files.add(listOfFiles[i].getName());
            } else if (listOfFiles[i].isDirectory()) {
                directories.add(listOfFiles[i].getName());
            }
        }
        System.out.println("List of files :\n---------------");
        for (String fName : files)
            System.out.println(fName);

        System.out.println("\nList of directories :\n---------------------");
        for (String dName : directories)
            System.out.println(dName);
    }
}
</code>```

答:
Why don't you use the piece of code below. You can also use it into a function that checks whether your files is a .txt file by producing a boolean true if mimeType="text/plain"

```<code>Path path = FileSystems.getDefault().getPath("myFolder", "myFile");
String mimeType = Files.probeContentType(path);
</code>```

Good luck

Title: Filter out the text files

Body:
The code separates files from directories.

I am trying to filter out the text files(.txt) and print out the files that remain.

I don't want the text files to be printed at all. I want the code to be implemented after the if statement if (listOfFiles[i].isFile()) { so after it checks to see if a given value is an actual file and then to determine if it is a text file, and if either test fails, add it to the listOfFiles array list.

Need help

import java.io.BufferedInputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class Exc_3 {

    public static void main(String[] args) {
        File folder = new File("C:\\Users\\skyla\\Desktop");
        File[] listOfFiles = folder.listFiles();
        List<String> files = new ArrayList<>();
        List<String> directories = new ArrayList<>();

        for (int i = 0; i < listOfFiles.length; i++) {

            if (listOfFiles[i].isFile()) {
                    files.add(listOfFiles[i].getName());
            } else if (listOfFiles[i].isDirectory()) {
                directories.add(listOfFiles[i].getName());
            }
        }
        System.out.println("List of files :\n---------------");
        for (String fName : files)
            System.out.println(fName);

        System.out.println("\nList of directories :\n---------------------");
        for (String dName : directories)
            System.out.println(dName);
    }
}

Body:
Why don't you use the piece of code below. You can also use it into a function that checks whether your files is a .txt file by producing a boolean true if mimeType="text/plain"

Path path = FileSystems.getDefault().getPath("myFolder", "myFile");
String mimeType = Files.probeContentType(path);

Good luck


问:
use multiple go routines for different operations on mysql
I have a piece of Go code with 3 different functions, insertIntoMysql, updateRowMysql and deleteRowmysql. I check for operation type and run one of these functions as needed.

I want to convert my normal functions into go routines to be able to handle more operations.

But here is the issue:

If I convert into goroutines, I will lose the sequence of operations.

For example, the insert operations are much more frequent than the delete operations and insert operations are being queued in the insert channel while the delete channel is empty it is possible for my code to try to delete a row before it gets inserted (e.g. a row is inserted and the deleted 1 sec later).

Any ideas on how to make sure the sequence of my operations on mysql is the same as the received operations.

here is the code:

```<code>
    go insertIntoMysql(insertChan, fields, db, config.DestinationTable)
    go updatefieldMysql(updateChan, fields, db, config.DestinationTable)
    go deleteFromMysql(deleteChan, fields, db, config.DestinationTable)

    for !opsDone {
        select {
        case op, open := <-mysqlChan:
            if !open {
                opsDone = true
                break
            }

            switch op.Operation {
            case "i":
                //fmt.Println("got insert operation")
                insertChan <- op
                break
            case "u":
                fmt.Println("got update operation")
                updateChan <- op
                break
            case "d":
                fmt.Println("got delete operation")
                deleteChan <- op
                break
            case "c":
                fmt.Println("got command operation")
                //no logic yet
                break
            }

            break
        }
    }
    close(done)
    close(insertChan)
    close(deleteChan)
    close(updateChan)

}
</code>```

答:
Looking at your code and your question/requirement: Stay in order as the original go channel delivered the data.
Staying in sync and still firing off multiple go routines to process the data, could be done like this:

```<code>func processStatements(mysqlChan chan *instructions) {
    var wg sync.WaitGroup
    prevOp := "" // Previous operation
    for {
        op, open := <-mysqlChan
        if !open {
            break
        }
        if prevOp!=op.Operation {
            // Next operation type, unknown side effects on previous operations,
            // wait for previous to finish before continuing
            wg.Wait()
        }

        switch op.Operation {
        case "i":
            wg.Add(1)
            go processInsert(op,wg)
            break
        case "u":
            wg.Add(1)
            go processUpdate(op,wg)
            break
        case "d":
            wg.Add(1)
            go processDelete(op,wg)
            break
        case "c":
            break
        }
        prevOp = op.Operation
    }
    // Previous go routines might still be running, wait till done
    wg.Wait()
    // Close any channels
}

func processInsert(c chan *sqlCall,wg *sync.WaitGroup) {
    defer wg.Done()
    // Do actual insert etc
}
</code>```

The main differences with your program are:

Processing is in order, safe against your base scenario

Process of next operation type will wait until previous operation type is finished

Multiple of the same operations run in parallel (as for in your code a single operation per type would run in parallel). Depending on the data distribution either of them can be faster or slower (i,i,i,d,u = 3 waits in this code, while it would also be 3 waits in your code, however in your code the 3 i would run sequential, here they run parallel) (Look into insert or update for mysql, since now your inserts could suddenly be updates depending on your data).

Body:
I have a piece of Go code with 3 different functions, insertIntoMysql, updateRowMysql and deleteRowmysql. I check for operation type and run one of these functions as needed.

I want to convert my normal functions into go routines to be able to handle more operations.

But here is the issue:

If I convert into goroutines, I will lose the sequence of operations.

For example, the insert operations are much more frequent than the delete operations and insert operations are being queued in the insert channel while the delete channel is empty it is possible for my code to try to delete a row before it gets inserted (e.g. a row is inserted and the deleted 1 sec later).

Any ideas on how to make sure the sequence of my operations on mysql is the same as the received operations.

here is the code:

    go insertIntoMysql(insertChan, fields, db, config.DestinationTable)
    go updatefieldMysql(updateChan, fields, db, config.DestinationTable)
    go deleteFromMysql(deleteChan, fields, db, config.DestinationTable)

    for !opsDone {
        select {
        case op, open := <-mysqlChan:
            if !open {
                opsDone = true
                break
            }

            switch op.Operation {
            case "i":
                //fmt.Println("got insert operation")
                insertChan <- op
                break
            case "u":
                fmt.Println("got update operation")
                updateChan <- op
                break
            case "d":
                fmt.Println("got delete operation")
                deleteChan <- op
                break
            case "c":
                fmt.Println("got command operation")
                //no logic yet
                break
            }

            break
        }
    }
    close(done)
    close(insertChan)
    close(deleteChan)
    close(updateChan)

}

Body:
Looking at your code and your question/requirement: Stay in order as the original go channel delivered the data.
Staying in sync and still firing off multiple go routines to process the data, could be done like this:

func processStatements(mysqlChan chan *instructions) {
    var wg sync.WaitGroup
    prevOp := "" // Previous operation
    for {
        op, open := <-mysqlChan
        if !open {
            break
        }
        if prevOp!=op.Operation {
            // Next operation type, unknown side effects on previous operations,
            // wait for previous to finish before continuing
            wg.Wait()
        }

        switch op.Operation {
        case "i":
            wg.Add(1)
            go processInsert(op,wg)
            break
        case "u":
            wg.Add(1)
            go processUpdate(op,wg)
            break
        case "d":
            wg.Add(1)
            go processDelete(op,wg)
            break
        case "c":
            break
        }
        prevOp = op.Operation
    }
    // Previous go routines might still be running, wait till done
    wg.Wait()
    // Close any channels
}

func processInsert(c chan *sqlCall,wg *sync.WaitGroup) {
    defer wg.Done()
    // Do actual insert etc
}

The main differences with your program are:

Processing is in order, safe against your base scenario

Process of next operation type will wait until previous operation type is finished

Multiple of the same operations run in parallel (as for in your code a single operation per type would run in parallel). Depending on the data distribution either of them can be faster or slower (i,i,i,d,u = 3 waits in this code, while it would also be 3 waits in your code, however in your code the 3 i would run sequential, here they run parallel) (Look into insert or update for mysql, since now your inserts could suddenly be updates depending on your data).


问:
How to suppress "Confirm 'set'? (y/n)" promtp for the `tmux conf 'set -g mouse on'`?
I would lke to make these two aliases work without prompting:

alias txmon="tmux conf 'set -g mouse on'  &&  tmux conf 'set -g mouse-utf8 on'"
```

<pre class="lang-sh prettyprint-override"><code>alias txmoff="tmux conf 'set -g mouse off'  &&  tmux conf 'set -g mouse-utf8 off'"
</code>```

but when run in a tmux session, the yield this prompt in brown font at the bottom left hand-side corner:

```<code>Confirm 'set'? (y/n)
</code>```

I couldn't find anything on the matter either in man tmux nor on the World Wlid Web ;)

答:
conf matches the command confirm-before and that is what it does - it asks for confirmation.

If you don't want it to ask, don't use that command:

```<code>alias txmon="tmux set -g mouse on \; set -g mouse-utf8 on"
</code>```

Note that mouse-utf8 was removed from tmux some years ago so you should check you still need it.

Also if you want to toggle the option you can leave out the on or off: tmux set -g mouse.

Body:
I would lke to make these two aliases work without prompting:

alias txmon="tmux conf 'set -g mouse on'  &&  tmux conf 'set -g mouse-utf8 on'"

alias txmoff="tmux conf 'set -g mouse off'  &&  tmux conf 'set -g mouse-utf8 off'"

but when run in a tmux session, the yield this prompt in brown font at the bottom left hand-side corner:

Confirm 'set'? (y/n)

I couldn't find anything on the matter either in man tmux nor on the World Wlid Web ;)

Body:
conf matches the command confirm-before and that is what it does - it asks for confirmation.

If you don't want it to ask, don't use that command:

alias txmon="tmux set -g mouse on \; set -g mouse-utf8 on"

Note that mouse-utf8 was removed from tmux some years ago so you should check you still need it.

Also if you want to toggle the option you can leave out the on or off: tmux set -g mouse.


问:
Invalid binary when uploading to App Store
I was using the following features before, I am not using it at the moment, so I removed it from info.plist, but I am having a problem when I upload the application. I don't want to add those features to info.plist because I don't use them anymore. What should I do?

ITMS-90683: Missing Purpose String in Info.plist - Your app's code references one or more APIs that access sensitive user data. The app's Info.plist file should contain a NSPhotoLibraryUsageDescription key with a user-facing purpose string explaining clearly and completely why your app needs the data. Starting Spring 2019, all apps submitted to the App Store that access user data are required to include a purpose string. If you're using external libraries or SDKs, they may reference APIs that require a purpose string. While your app might not use these APIs, a purpose string is still required. You can contact the developer of the library or SDK and request they release a version of their code that doesn't contain the APIs. Learn more (https://developer.apple.com/documentation/uikit/core_app/protecting_the_user_s_privacy).

ITMS-90683: Missing Purpose String in Info.plist - Your app's code references one or more APIs that access sensitive user data. The app's Info.plist file should contain a NSCameraUsageDescription key with a user-facing purpose string explaining clearly and completely why your app needs the data. Starting Spring 2019, all apps submitted to the App Store that access user data are required to include a purpose string. If you're using external libraries or SDKs, they may reference APIs that require a purpose string. While your app might not use these APIs, a purpose string is still required. You can contact the developer of the library or SDK and request they release a version of their code that doesn't contain the APIs.

答:
If you're seeing that warning, the App Store (by automatically looking through your compiled application) believes that you're using those features. Usually this means that code exists in your application that references these APIs. In this case, it's code that works with the camera and photo library. Even if you don't use those features any more, if the code in your compiled binary references those APIs, Apple will insist on those purposes being present in your info.plist (since they can't tell the difference between those features being present and used, or present and unused).

Your choices are:

If you don't think those features will be coming back, remove the code that uses these APIs entirely from your app. You may also want to just temporarily not include the files by removing them from your app's build target.

If this is too complex, and you're certain that these features aren't actually in use in your app any more, then fill out those parts of your info.plist with whatever messages you had previously, safe in the knowledge that no user will ever actually see them.

In summary, if you reference those APIs, even if you don't use them, you must have appropriate purpose strings in your app's info.plist.


问:
How to properly cache data in spring boot application with Thymleaf
I am writing some Java code for my Spring boot application to receive a list of 40,000 elements and, through Thymeleaf post it in a dropdown field. However, I noticed that when I load the data and go to the dropdown, everything is slow.

I was told  to cache the values and store them. Though I am not too familiar with this process I  tried using the @Cacheable annotation for my SpringBootApplication, but it still didn't work. I am trying to see what I did wrong or if there is a better way to approach this issue I am having.

Service Layer:

```<code>@SuppressWarnings("unchecked")
@Cacheable("String")
public List<String> getServerListing(){
    StoredProcedureQuery storedProcedure = entityManager.createStoredProcedureQuery("GetAllServers");
    return storedProcedure.getResultList();

}
</code>```

First, I have a stored procedure bring down all the data from the server, (~40,000 records).

Controller:

```<code>List<String> servers = joinQueryService.getServerListing();

modelAndView.addObject("servers", servers);
</code>```

Then, I set it to a List of strings and send it to front-end.

Thymeleaf:

```<code><div class="row">
    <div class="col col-lg-9 search-bar">
        <div class="form-group">
            <label>Server:</label> <select class="js-example-basic-single3"
                th:field="*{servers}" id="selectData3">
                <option value=""></option>
                <option th:each="servers : ${servers}" th:value="${servers}" th:text="${servers}" />
            </select>

        </div>
    </div>
</div>
</code>```

SpringBoot:

```<code>@SpringBootApplication
@Cacheable
public class TaddmDevApplication {

    public static void main(String[] args) {

        Policy.setPolicy(new TaddmPolicy());

        SpringApplication.run(TaddmDevApplication.class, args);
    }

}
</code>```

答:
I think the problem here is: A browser will take several seconds to load and/or display such a large drop-down, regardless of how streamlined the rest of your application is.

As a test, I created a text file containing nothing except a 40,000-item drop-down (test.htm):

```<code><!DOCTYPE html>
<html>
<body>
<h2>Create a drop-down List</h2>

<label for="widgets">Choose a widget:</label>

<select id="widgets">
  <option value="widget1">Widget 1</option>
  <option value="widget2">Widget 2</option>
  <option value="widget3">Widget 3</option>
  <option value="widget4">Widget 4</option>
  <option value="widget5">Widget 5</option>
  <option value="widget6">Widget 6</option>
  <option value="widget7">Widget 7</option>
  ... snipped for brevity!
  <option value="widget39998">Widget 39998</option>
  <option value="widget39999">Widget 39999</option>
  <option value="widget40000">Widget 40000</option>
</select>

</body>
</html>
</code>```

I then opened that file in Chrome and recorded the processing time:

It took about 5 seconds. There was no database fetch; no network traffic; no server-side processing.

I think the bottom line is: A drop-down of this size will be unwieldy for users, as well as being slow to handle in the browser.

This means your question becomes a different one: How to send a more modest amount of data to the browser, and allow the user to navigate through the results of each load, one page at a time. I completely agree with your goal of "milliseconds", rather than seconds, by the way. That is exactly right. Maybe you already have one, but try to have a specific goal in mind ("under 300 ms" or some such).

Of course, there may well be optimizations in your code - but they are probably moot at this point.

Probably not the answer you wanted, but I hope this helped!

Body:
I am writing some Java code for my Spring boot application to receive a list of 40,000 elements and, through Thymeleaf post it in a dropdown field. However, I noticed that when I load the data and go to the dropdown, everything is slow.

I was told  to cache the values and store them. Though I am not too familiar with this process I  tried using the @Cacheable annotation for my SpringBootApplication, but it still didn't work. I am trying to see what I did wrong or if there is a better way to approach this issue I am having.

Service Layer:

@SuppressWarnings("unchecked")
@Cacheable("String")
public List<String> getServerListing(){
    StoredProcedureQuery storedProcedure = entityManager.createStoredProcedureQuery("GetAllServers");
    return storedProcedure.getResultList();

}

First, I have a stored procedure bring down all the data from the server, (~40,000 records).

Controller:

List<String> servers = joinQueryService.getServerListing();

modelAndView.addObject("servers", servers);

Then, I set it to a List of strings and send it to front-end.

Thymeleaf:

            Server: <select class="js-example-basic-single3"
                th:field="*{servers}" id="selectData3">
                <option value=""></option>
                <option th:each="servers : ${servers}" th:value="${servers}" th:text="${servers}" />
            </select>

SpringBoot:

@SpringBootApplication
@Cacheable
public class TaddmDevApplication {

    public static void main(String[] args) {

        Policy.setPolicy(new TaddmPolicy());

        SpringApplication.run(TaddmDevApplication.class, args);
    }

}

Body:
I think the problem here is: A browser will take several seconds to load and/or display such a large drop-down, regardless of how streamlined the rest of your application is.

As a test, I created a text file containing nothing except a 40,000-item drop-down (test.htm):

<!DOCTYPE html>
<html>
<body>
<h2>Create a drop-down List</h2>

<label for="widgets">Choose a widget:</label>

<select id="widgets">
  <option value="widget1">Widget 1</option>
  <option value="widget2">Widget 2</option>
  <option value="widget3">Widget 3</option>
  <option value="widget4">Widget 4</option>
  <option value="widget5">Widget 5</option>
  <option value="widget6">Widget 6</option>
  <option value="widget7">Widget 7</option>
  ... snipped for brevity!
  <option value="widget39998">Widget 39998</option>
  <option value="widget39999">Widget 39999</option>
  <option value="widget40000">Widget 40000</option>
</select>

</body>
</html>

I then opened that file in Chrome and recorded the processing time:

It took about 5 seconds. There was no database fetch; no network traffic; no server-side processing.

I think the bottom line is: A drop-down of this size will be unwieldy for users, as well as being slow to handle in the browser.

This means your question becomes a different one: How to send a more modest amount of data to the browser, and allow the user to navigate through the results of each load, one page at a time. I completely agree with your goal of "milliseconds", rather than seconds, by the way. That is exactly right. Maybe you already have one, but try to have a specific goal in mind ("under 300 ms" or some such).

Of course, there may well be optimizations in your code - but they are probably moot at this point.

Probably not the answer you wanted, but I hope this helped!


问:
"<Comment: >" needs to have a value for field "id" before this many-to-many relationship can be used?
I'm new to use (many-to-many) relationship,
I need to allow the users can leave the comment on the user post. this site looks like Quora or StackOverflow the user should signup to get the questions field to put his question and other users whose in site can leave there comments.
 so, how can I continue by adding (add) in (many-to-many) or the real question is: how can I add a comment by (many-to-many) in this code
if anyone help me to complete this issue, please.

views.py

```<code>from django.shortcuts import render, redirect, get_list_or_404
from .forms import UserAskingForm, CommentForm
from .models import UserAsking, Comment
from django.contrib.auth.decorators import login_required

@login_required
def user_asking(request):
    form = UserAskingForm
    if request.method == 'POST':
        form = UserAskingForm(request.POST, instance=request.user.userprofile)
        if form.is_valid():
            asking = form.save(commit=False)
            asking.title = form.cleaned_data['title']
            asking.question = form.cleaned_data['question']
            asking.field = form.cleaned_data['field']
            asking = UserAsking.objects.create(userprofile=request.user.userprofile,
                                               title=asking.title,
                                               question=asking.question,
                                               field=asking.field)
            asking.save()
            return redirect('community:user_questions')
    else:
        form = UserAskingForm()
        return render(request, 'community/asking_question.html', {'form': form})

    return render(request, 'community/asking_question.html', {'form': form})

@login_required
def user_questions(request):
    all_objects = UserAsking.objects.all().order_by('-title')
    all_objects = get_list_or_404(all_objects)
    return render(request, 'community/user_questions.html', {'all_objects': all_objects})

def question_view(request, user_id):
    my_question = UserAsking.objects.get(pk=user_id) # question number e.g '1' for user 'medoabdin'
    comment_form = CommentForm

    if request.method == 'GET':
        comment_form = comment_form(request.GET)
        if comment_form.is_valid():
            comments = comment_form.save(commit=False)
            comments.comment = comment_form.cleaned_data['comment']
            # comments is the value of data
            comments.userasking.add()
            #users = User.objects.filter(username=request.user) # medoabdin
            #comments = Comment.objects.create(userasking=my_question, comment=comments)
            #comments.userasking.set(users)
            #comments.userasking.add(*users)

    return render(request, 'community/question_view.html', {'my_question': my_question, 'comment_form': comment_form})
</code>```

models.py

```<code>from django.db import models
from account.models import UserProfile
from django.db.models.signals import post_save

CHOICE = [('Technology', 'Technology'), ('Computer Science', 'Computer Science'),
          ('Lawyer', 'Lawyer'), ('Trading', 'Trading'),
          ('Engineering', 'Engineering'), ('Life Dialy', 'Life Dialy')
]

class UserAsking(models.Model):
    userprofile = models.ForeignKey(UserProfile, on_delete=models.CASCADE)
    title = models.CharField(max_length=100, blank=False, help_text='Be specific and imagine you’re asking a question to another person')
    question = models.TextField(max_length=500, blank=False, help_text='Include all the information someone would need to answer your question')
    field = models.CharField(max_length=20, choices=CHOICE, default='Technology', help_text='Add the field to describe what your question is about')

    def __str__(self):
        return self.title

class Comment(models.Model):
    userasking = models.ManyToManyField(UserAsking)
    comment = models.TextField(max_length=500, blank=True)

    def __str__(self):
        return self.comment
</code>```

forms.py

```<code>from django import forms
from .models import UserAsking, Comment

class UserAskingForm(forms.ModelForm):
    title = forms.CharField(required=True,
                            widget=forms.TextInput(attrs={'placeholder': 'Type Your Title...',
                                                          'class': 'form-control',
                                                          'data-placement': 'top',
                                                          'title': 'type your title',
                                                          'data-tooltip': 'tooltip'
                                                          }),
                            help_text='Be specific and imagine you’re asking a question to another person')
    question = forms.CharField(required=True,
                               widget=forms.Textarea(attrs={'placeholder': 'Type Your Details Of Your Question...',
                                                            'class': 'form-control',
                                                            'data-placement': 'top',
                                                            'title': 'type your question simply',
                                                            'data-tooltip': 'tooltip'
                                                            }),
                               help_text='Include all the information someone would need to answer your question')

    class Meta:
        model = UserAsking
        fields = '__all__'
        exclude = ['userprofile']

class CommentForm(forms.ModelForm):
    comment = forms.CharField(max_length=500, required=False, widget=forms.Textarea(attrs={'placeholder': 'Type your comment simply',
                                                                                'class': 'form-control'}))

    class Meta:
        model = Comment
        fields = ['comment']
</code>```

答:
You first save the object to the database, before you can use it in a relation:

```<code>def question_view(request, user_id):
    my_question = UserAsking.objects.get(pk=user_id)
    comment_form = CommentForm
    if request.method == 'GET':
        comment_form = comment_form(request.GET)
        if comment_form.is_valid():
            <b>comments = comment_form.save()</b>
            comments.userasking.add(<b>my_question</b>)
    # …</code>```

That bein said, I find it rather odd that a Question has a many-to-many relation to a UserAsking. That thus means that the same comment can be related to multiple UserAsking objects?

Body:
I'm new to use (many-to-many) relationship,
I need to allow the users can leave the comment on the user post. this site looks like Quora or StackOverflow the user should signup to get the questions field to put his question and other users whose in site can leave there comments.
 so, how can I continue by adding (add) in (many-to-many) or the real question is: how can I add a comment by (many-to-many) in this code
if anyone help me to complete this issue, please.

views.py

from django.shortcuts import render, redirect, get_list_or_404
from .forms import UserAskingForm, CommentForm
from .models import UserAsking, Comment
from django.contrib.auth.decorators import login_required

@login_required
def user_asking(request):
    form = UserAskingForm
    if request.method == 'POST':
        form = UserAskingForm(request.POST, instance=request.user.userprofile)
        if form.is_valid():
            asking = form.save(commit=False)
            asking.title = form.cleaned_data['title']
            asking.question = form.cleaned_data['question']
            asking.field = form.cleaned_data['field']
            asking = UserAsking.objects.create(userprofile=request.user.userprofile,
                                               title=asking.title,
                                               question=asking.question,
                                               field=asking.field)
            asking.save()
            return redirect('community:user_questions')
    else:
        form = UserAskingForm()
        return render(request, 'community/asking_question.html', {'form': form})

    return render(request, 'community/asking_question.html', {'form': form})

@login_required
def user_questions(request):
    all_objects = UserAsking.objects.all().order_by('-title')
    all_objects = get_list_or_404(all_objects)
    return render(request, 'community/user_questions.html', {'all_objects': all_objects})

def question_view(request, user_id):
    my_question = UserAsking.objects.get(pk=user_id) # question number e.g '1' for user 'medoabdin'
    comment_form = CommentForm

    if request.method == 'GET':
        comment_form = comment_form(request.GET)
        if comment_form.is_valid():
            comments = comment_form.save(commit=False)
            comments.comment = comment_form.cleaned_data['comment']
            # comments is the value of data
            comments.userasking.add()
            #users = User.objects.filter(username=request.user) # medoabdin
            #comments = Comment.objects.create(userasking=my_question, comment=comments)
            #comments.userasking.set(users)
            #comments.userasking.add(*users)

    return render(request, 'community/question_view.html', {'my_question': my_question, 'comment_form': comment_form})

models.py

from django.db import models
from account.models import UserProfile
from django.db.models.signals import post_save

CHOICE = [('Technology', 'Technology'), ('Computer Science', 'Computer Science'),
          ('Lawyer', 'Lawyer'), ('Trading', 'Trading'),
          ('Engineering', 'Engineering'), ('Life Dialy', 'Life Dialy')
]

class UserAsking(models.Model):
    userprofile = models.ForeignKey(UserProfile, on_delete=models.CASCADE)
    title = models.CharField(max_length=100, blank=False, help_text='Be specific and imagine you’re asking a question to another person')
    question = models.TextField(max_length=500, blank=False, help_text='Include all the information someone would need to answer your question')
    field = models.CharField(max_length=20, choices=CHOICE, default='Technology', help_text='Add the field to describe what your question is about')

    def __str__(self):
        return self.title

class Comment(models.Model):
    userasking = models.ManyToManyField(UserAsking)
    comment = models.TextField(max_length=500, blank=True)

    def __str__(self):
        return self.comment

forms.py

from django import forms
from .models import UserAsking, Comment

class UserAskingForm(forms.ModelForm):
    title = forms.CharField(required=True,
                            widget=forms.TextInput(attrs={'placeholder': 'Type Your Title...',
                                                          'class': 'form-control',
                                                          'data-placement': 'top',
                                                          'title': 'type your title',
                                                          'data-tooltip': 'tooltip'
                                                          }),
                            help_text='Be specific and imagine you’re asking a question to another person')
    question = forms.CharField(required=True,
                               widget=forms.Textarea(attrs={'placeholder': 'Type Your Details Of Your Question...',
                                                            'class': 'form-control',
                                                            'data-placement': 'top',
                                                            'title': 'type your question simply',
                                                            'data-tooltip': 'tooltip'
                                                            }),
                               help_text='Include all the information someone would need to answer your question')

    class Meta:
        model = UserAsking
        fields = '__all__'
        exclude = ['userprofile']

class CommentForm(forms.ModelForm):
    comment = forms.CharField(max_length=500, required=False, widget=forms.Textarea(attrs={'placeholder': 'Type your comment simply',
                                                                                'class': 'form-control'}))

    class Meta:
        model = Comment
        fields = ['comment']

Body:
You first save the object to the database, before you can use it in a relation:

def question_view(request, user_id):
    my_question = UserAsking.objects.get(pk=user_id)
    comment_form = CommentForm
    if request.method == 'GET':
        comment_form = comment_form(request.GET)
        if comment_form.is_valid():
            comments = comment_form.save()
            comments.userasking.add(my_question)
    # …

That bein said, I find it rather odd that a Question has a many-to-many relation to a UserAsking. That thus means that the same comment can be related to multiple UserAsking objects?


问:
Flutter stuck at Installing build\app\outputs\apk\app.apk
When I run:

```<code>$ flutter run
</code>```

I'm getting a prompt on my mobile device asking if I want to install the app on my device. I give yes, then nothing happens!

It's stuck here:

```<code>Launching lib/main.dart on POCO F1 in debug mode...
Initializing gradle...                                           1.5s
Resolving dependencies...                                        9.2s
Gradle task 'assembleDebug'...                                  22.9s
Built build\app\outputs\apk\debug\app-debug.apk.
Installing build\app\outputs\apk\app.apk...                     14.9s
</code>```

Then nothing.

答:
Background: While the app was being installed by Android Studio, I manually deleted the app from the device. Thereafter I discovered that the app would not install.

This problem was resolved by going to Settings > Apps  and noting that the app was disabled rather than uninstalled even though I did confirm the uninstall request. In any case, I tapped the app and performed an uninstall from the Settings > Apps screen.

Body:
When I run:

$ flutter run

I'm getting a prompt on my mobile device asking if I want to install the app on my device. I give yes, then nothing happens!

It's stuck here:

Launching lib/main.dart on POCO F1 in debug mode...
Initializing gradle...                                           1.5s
Resolving dependencies...                                        9.2s
Gradle task 'assembleDebug'...                                  22.9s
Built build\app\outputs\apk\debug\app-debug.apk.
Installing build\app\outputs\apk\app.apk...                     14.9s

Then nothing.


问:
Scikit Learn RFECV ValueError: continuous is not supported
I am trying to use scikit learn RFECV for feature selection in a given dataset using the code below:

```<code>import pandas as pd
from sklearn.ensemble import RandomForestRegressor
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.feature_selection import RFECV

# Data Processing
df = pd.read_csv('Combined_Data_final_2019H2_10min.csv')
X, y = (df.drop(['TimeStamp','Power_kW'], axis=1)), df['Power_kW']
SEED = 10
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=SEED)

# The "accuracy" scoring is proportional to the number of correct classifications
clf_rf_4 = RandomForestRegressor()
rfecv = RFECV(estimator=clf_rf_4, step=1, cv=4,scoring='accuracy')   #4-fold cross-validation (cv=4)

rfecv = rfecv.fit(X_train, y_train)

print('Optimal number of features :', rfecv.n_features_)
print('Best features :', X.columns[rfecv.support_])

# Plot number of features VS. cross-validation scores
plt.figure()
plt.xlabel("Number of features selected")
plt.ylabel("Cross validation score of number of selected features")
plt.plot(range(1, len(rfecv.grid_scores_) + 1), rfecv.grid_scores_)
plt.show()
</code>```

I have tried a number of different solutions but I continuously get the following error code:

```<code>ValueError: continuous is not supported
</code>```

Any ideas?

Any help would be very much appreciated!

答:
I believe your error is due to these 2 lines:

```<code>clf_rf_4 = RandomForestRegressor()
rfecv = RFECV(estimator=clf_rf_4, step=1, cv=4,scoring='accuracy')
</code>```

accuracy is not defined for continuous outputs. Try to change it to something like:

```<code>rfecv = RFECV(estimator=clf_rf_4, step=1, cv=4,scoring='r2')
</code>```

For a full list of regression scoring metrics see here, note the Regression line.

Body:
I am trying to use scikit learn RFECV for feature selection in a given dataset using the code below:

import pandas as pd
from sklearn.ensemble import RandomForestRegressor
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.feature_selection import RFECV

# Data Processing
df = pd.read_csv('Combined_Data_final_2019H2_10min.csv')
X, y = (df.drop(['TimeStamp','Power_kW'], axis=1)), df['Power_kW']
SEED = 10
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=SEED)

# The "accuracy" scoring is proportional to the number of correct classifications
clf_rf_4 = RandomForestRegressor()
rfecv = RFECV(estimator=clf_rf_4, step=1, cv=4,scoring='accuracy')   #4-fold cross-validation (cv=4)

rfecv = rfecv.fit(X_train, y_train)

print('Optimal number of features :', rfecv.n_features_)
print('Best features :', X.columns[rfecv.support_])

# Plot number of features VS. cross-validation scores
plt.figure()
plt.xlabel("Number of features selected")
plt.ylabel("Cross validation score of number of selected features")
plt.plot(range(1, len(rfecv.grid_scores_) + 1), rfecv.grid_scores_)
plt.show()

I have tried a number of different solutions but I continuously get the following error code:

ValueError: continuous is not supported

Any ideas?

Any help would be very much appreciated!

Body:
I believe your error is due to these 2 lines:

clf_rf_4 = RandomForestRegressor()
rfecv = RFECV(estimator=clf_rf_4, step=1, cv=4,scoring='accuracy')

accuracy is not defined for continuous outputs. Try to change it to something like:

rfecv = RFECV(estimator=clf_rf_4, step=1, cv=4,scoring='r2')

For a full list of regression scoring metrics see here, note the Regression line.


问:
error: package com.google.android.gms.drive does not exist
Hi everyone I have this problem that I can't solve even tho I checked on StackOverflow and I tried all the solutions but nothing is working.

So bellow I will put the dependencies and sync them and everything seems ok but when I press compile I get this error:
     package com.google.android.gms.drive does not exist

but I included the dependency and I can't understand why I get this error.

Can anyone help me, please? Thank you.

```<code>dependencies {

implementation fileTree(dir: 'libs', include: ['*.jar'])

implementation 'androidx.constraintlayout:constraintlayout:1.1.3'

implementation 'androidx.appcompat:appcompat:1.1.0'

implementation 'com.android.support:appcompat-v7:29.1.0'
implementation 'com.android.support:recyclerview-v7:29.1.0'
implementation 'com.android.support:design:29.1.0'

implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation 'com.squareup.picasso:picasso:2.5.2'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'

implementation "com.google.android.gms:play-services-base:17.1.0"
implementation 'com.google.android.gms:play-services-ads:18.3.0'
implementation 'com.google.android.gms:play-services-auth:17.0.0'
implementation 'com.google.android.gms:play-services-maps:17.0.0'

implementation 'com.google.android.gms:play-services-location:17.0.0'

// Add the Firebase SDK for Google Analytics
// Add the SDKs for any other Firebase products you want to use in your app
// For example, to use Firebase Authentication and Cloud Firestore
implementation 'com.google.firebase:firebase-auth:19.2.0'
implementation 'com.google.firebase:firebase-firestore:21.4.0'
implementation 'com.google.firebase:firebase-analytics:17.2.2'
implementation 'com.google.firebase:firebase-database:19.2.1'
testImplementation 'junit:junit:4.12'

androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

implementation 'com.github.bumptech.glide:glide:4.11.0'
// FirebaseUI for Firebase Realtime Database
implementation 'com.firebaseui:firebase-ui-database:6.2.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.11.0'
</code>```

}enter code here

答:
The first thing I would recommend you is to check if on top of the build.gradle you added the plugin

apply plugin: 'com.android.application'

then do a clean build, from Build -> Clean build

If should not work downgrade the dependencies just to be sure is not any particular bug from the current version of the play services. Let us know!

Body:
Hi everyone I have this problem that I can't solve even tho I checked on StackOverflow and I tried all the solutions but nothing is working.

So bellow I will put the dependencies and sync them and everything seems ok but when I press compile I get this error:
     package com.google.android.gms.drive does not exist

but I included the dependency and I can't understand why I get this error.

Can anyone help me, please? Thank you.

dependencies {

implementation fileTree(dir: 'libs', include: ['*.jar'])

implementation 'androidx.constraintlayout:constraintlayout:1.1.3'

implementation 'androidx.appcompat:appcompat:1.1.0'

implementation 'com.android.support:appcompat-v7:29.1.0'
implementation 'com.android.support:recyclerview-v7:29.1.0'
implementation 'com.android.support:design:29.1.0'

implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation 'com.squareup.picasso:picasso:2.5.2'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'

implementation "com.google.android.gms:play-services-base:17.1.0"
implementation 'com.google.android.gms:play-services-ads:18.3.0'
implementation 'com.google.android.gms:play-services-auth:17.0.0'
implementation 'com.google.android.gms:play-services-maps:17.0.0'

implementation 'com.google.android.gms:play-services-location:17.0.0'

// Add the Firebase SDK for Google Analytics
// Add the SDKs for any other Firebase products you want to use in your app
// For example, to use Firebase Authentication and Cloud Firestore
implementation 'com.google.firebase:firebase-auth:19.2.0'
implementation 'com.google.firebase:firebase-firestore:21.4.0'
implementation 'com.google.firebase:firebase-analytics:17.2.2'
implementation 'com.google.firebase:firebase-database:19.2.1'
testImplementation 'junit:junit:4.12'

androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

implementation 'com.github.bumptech.glide:glide:4.11.0'
// FirebaseUI for Firebase Realtime Database
implementation 'com.firebaseui:firebase-ui-database:6.2.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.11.0'

}enter code here


问:
"self" in objective C

Possible Duplicate:

  Should I Use self Keyword (Properties) In The Implementation?

Say I have a class "Person", with an instance variable "age". Coming from Python, when writing methods for the Person class, I am used to accessing age using "self.age", however in Objective C I have noticed that both and "self.age" and "age" are accepted when referring to the instance variable (whereas in Python only the former would work).

When it is not explicitly specified which instance's variable you mean, does it default to 'self'? And is it considered bad style not to explicitly specify self? If not, are there conventions on when to use self.age and when to use age?

答: Using self uses the accessor and mutator methods, while leaving it out modifies the instance variable directly. In order to use self.age, you must have age declared as a property with the @property syntax. I typically try to use self wherever I can.

ContentLicense: CC BY-SA 3.0

Title: "self" in objective C


问:
Angular 4 Mobile number validation
I want to validate a mobile number using Angular 4 and it should not accept any characters other than numbers up to just 10 digits.

Below is my code ,

```<code><input type="text" formControlName="mobileNo" minlength=10 maxlength=10>
</code>```

答:
try this code......
 typescript code ..

```<code>  form: FormGroup;
  pattern1 =  "^[0-9_-]{10,12}";
  constructor(public fb: FormBuilder) {
    this.form = this.fb.group({
      phone: ['', [Validators.required, Validators.pattern(this.pattern1)]]
    })
  }
</code>```

html code..

```<code><form [formGroup]="form">
  <input type="text" formControlName="phone">
  <ng-container *ngIf="form.controls.phone.errors">
   <ng-container *ngIf="form.controls.phone.errors.pattern">
    phone no is not statndard patter
    </ng-container>
      <ng-container *ngIf="form.controls.phone.errors.required">
    phone no is required
    </ng-container>
  </ng-container>

</form>
</code>```

Title: Angular 4 Mobile number validation

Body:
I want to validate a mobile number using Angular 4 and it should not accept any characters other than numbers up to just 10 digits.

Below is my code ,

<input type="text" formControlName="mobileNo" minlength=10 maxlength=10>

Body:
try this code......
 typescript code ..

  form: FormGroup;
  pattern1 =  "^[0-9_-]{10,12}";
  constructor(public fb: FormBuilder) {
    this.form = this.fb.group({
      phone: ['', [Validators.required, Validators.pattern(this.pattern1)]]
    })
  }

html code..

<form [formGroup]="form">
  <input type="text" formControlName="phone">
  <ng-container *ngIf="form.controls.phone.errors">
   <ng-container *ngIf="form.controls.phone.errors.pattern">
    phone no is not statndard patter
    </ng-container>
      <ng-container *ngIf="form.controls.phone.errors.required">
    phone no is required
    </ng-container>
  </ng-container>

</form>


答:
This code

```<code>char mappa[RIGHE][COLONNE] = {" "}; // blank, as an empty chess board
</code>```

initializes the first element of the array, i.e. mappa[0], with the string " ". This makes the top-left element contain ' ' (the space char), and the remaining row is filled with NUL chars, '\0'. All the other rows are zero-initialized.

Compare with the following example:

```<code>char mappa[RIGHE][COLONNE] = {"Hello","world!"};
</code>```

In this case your output could be (up to placement of the D):

[ H ][ e ][ l ][ l ][ o ][  ][  ][  ][  ][  ]
[ w ][ o ][ r ][ l ][ d ][ ! ][  ][  ][  ][  ]
[  ][  ][  ][  ][  ][  ][  ][  ][  ][  ]
[  ][  ][  ][  ][  ][  ][  ][ D ][  ][  ]
[  ][  ][  ][  ][  ][  ][  ][  ][  ][  ]
[  ][  ][  ][  ][  ][  ][  ][  ][  ][  ]
[  ][  ][  ][  ][  ][  ][  ][  ][  ][  ]
[  ][  ][  ][  ][  ][  ][  ][  ][  ][  ]
[  ][  ][  ][  ][  ][  ][  ][  ][  ][  ]
[  ][  ][  ][  ][  ][  ][  ][  ][  ][  ]
```

<p>What you actually want is to fill the whole array with spaces, like this:</p>

```    char mappa[RIGHE][COLONNE];
    memset(mappa, ' ', sizeof mappa);
```

where memset is a function from the <string.h> header.

Title: Crooked 2D array when printing it on stdout (populating a blank 2D array)

Body:
I'm trying to populate a blank 2d array (matrix) with a character D put onto a random position.

This is the code which works properly:

#define RIGHE 10
#define COLONNE 10

void drawMap(char[][COLONNE]);

int main()
{
    char mappa[RIGHE][COLONNE] = {" "}; // blank, as an empty chess board

    drawMap(mappa);

    return 0;

}

/* Disegna la mappa da gioco */
void drawMap(char mappa[][COLONNE])
{
    int rigaDestinazione, colonnaDestinazione;

    srand(time(NULL)); // Randomizza numeri

    rigaDestinazione = rand() % RIGHE;
    colonnaDestinazione = rand() % COLONNE;

    mappa[rigaDestinazione][colonnaDestinazione] = 'D';

    for (int i = 0; i < RIGHE; i++) {
        for (int j = 0; j < RIGHE; j++) {
            printf("[ %c ]", mappa[i][j]);
        }
        printf("\n");
    }

}

Unfortunately when I print it, it seems to be asymmetric as you can see, the output is:

[   ][  ][  ][  ][  ][  ][  ][  ][  ][  ]
[  ][  ][  ][  ][  ][  ][  ][  ][  ][  ]
[  ][  ][  ][  ][  ][  ][  ][  ][  ][  ]
[  ][  ][  ][  ][  ][  ][  ][  ][  ][  ]
[  ][  ][  ][  ][  ][  ][  ][  ][  ][  ]
[  ][  ][  ][  ][  ][  ][  ][  ][  ][  ]
[  ][  ][  ][  ][  ][  ][  ][  ][  ][  ]
[  ][  ][  ][  ][ D ][  ][  ][  ][  ][  ]
[  ][  ][  ][  ][  ][  ][  ][  ][  ][  ]
[  ][  ][  ][  ][  ][  ][  ][  ][  ][  ]

How can I fix?

Body:
This code

char mappa[RIGHE][COLONNE] = {" "}; // blank, as an empty chess board

initializes the first element of the array, i.e. mappa[0], with the string " ". This makes the top-left element contain ' ' (the space char), and the remaining row is filled with NUL chars, '\0'. All the other rows are zero-initialized.

Compare with the following example:

char mappa[RIGHE][COLONNE] = {"Hello","world!"};

In this case your output could be (up to placement of the D):

[ H ][ e ][ l ][ l ][ o ][  ][  ][  ][  ][  ]
[ w ][ o ][ r ][ l ][ d ][ ! ][  ][  ][  ][  ]
[  ][  ][  ][  ][  ][  ][  ][  ][  ][  ]
[  ][  ][  ][  ][  ][  ][  ][ D ][  ][  ]
[  ][  ][  ][  ][  ][  ][  ][  ][  ][  ]
[  ][  ][  ][  ][  ][  ][  ][  ][  ][  ]
[  ][  ][  ][  ][  ][  ][  ][  ][  ][  ]
[  ][  ][  ][  ][  ][  ][  ][  ][  ][  ]
[  ][  ][  ][  ][  ][  ][  ][  ][  ][  ]
[  ][  ][  ][  ][  ][  ][  ][  ][  ][  ]

What you actually want is to fill the whole array with spaces, like this:

    char mappa[RIGHE][COLONNE];
    memset(mappa, ' ', sizeof mappa);

where memset is a function from the <string.h> header.


问:
Why do some variables declared using let inside a function become available in another function, while others result in a reference error?
I can't understand why variables act so strange when declared inside a function.

In the first function I declare with let the variables b and c with the value 10:

```<code>b = c = 10;
</code>```

In the second function I show:

```<code>b + ", " + c
</code>```

And this shows:

```<code>10, 10
</code>```

Also in first function I declare a with value 10:

```<code>let a = b = c = 10;
</code>```

But in the second function it shows an error:

Can't find variable: a

Now in the first function I declare d with value 20:

```<code>var d = 20;
</code>```

But in the second function it shows the same error as before, but with the variable d:

Can't find variable: d

Example:

function first() {
  let a = b = c = 10;
  var d = 20;
  second();
}

function second() {
  console.log(b + ", " + c); //shows "10, 10"

  try{ console.log(a); }  // Rreference error
  catch(e){ console.error(e.message) }

  try{ console.log(d); } // Reference error
  catch(e){ console.error(e.message) }
}
first()```

答:
The strange issue is caused by scoping rules in JavaScript

```<code>function first() {
   let a = b = c = 10; // a is in local scope, b and c are in global scope
   var d = 20; // d is in local scope
   second(); // will have access to b and c from the global scope
}
</code>```

Assuming that you want to declare 3 local variables initialised to the same value (100). Your first() will look like below. In this case, second() will not have access to any of the variables because they are local to first()

```<code>function first() {
   let a = 100; // a is in local scope init to 100
   let b = a; // b is in local scope init to a
   let c = b // c is in local scope init to b

   var d = 20; // d is in local scope
   second(); // will not have access a, b, c, or d
}
</code>```

However, if you want global variables then your first() will look like below. In this case, second will have access to all the variables because they are in global scope

```<code>function first() {
   a = 100; // a is in global scope
   b = a; // b is in global scope
   c = b // c is in global scope

   d = 20; // d is in global scope
   second(); // will have access to a, b, c, and d from the global scope
}
</code>```

Local variables (aka. accessible in the code block where they are declared).
 A Code block is any {} with line(s) of code between.

function() {var, let, const in here is accessible to entire function},

for() {var in here is accessible to outer scope, let, const accessible only in here},

etc.

Global variables (aka accessible in the global scope).

These variables are attached to the global object. The global object is environment dependent. It is the window object in browsers.

Special note: You can declare variables in JavaScript without using the var, let, const keywords. A variable declared this way is attached to the global object, therefore accessible in the global scope.

a = 100 // is valid and is in global scope

Some articles for further reading:
https://www.sitepoint.com/demystifying-javascript-variable-scope-hoisting/
https://scotch.io/tutorials/understanding-scope-in-javascript
https://www.digitalocean.com/community/tutorials/understanding-variables-scope-hoisting-in-javascript

Body:
I can't understand why variables act so strange when declared inside a function.

In the first function I declare with let the variables b and c with the value 10:

b = c = 10;

In the second function I show:

b + ", " + c

And this shows:

10, 10

Also in first function I declare a with value 10:

let a = b = c = 10;

But in the second function it shows an error:

Can't find variable: a

Now in the first function I declare d with value 20:

var d = 20;

But in the second function it shows the same error as before, but with the variable d:

Can't find variable: d

Example:

function first() {
  let a = b = c = 10;
  var d = 20;
  second();
}

function second() {
  console.log(b + ", " + c); //shows "10, 10"

  try{ console.log(a); }  // Rreference error
  catch(e){ console.error(e.message) }

  try{ console.log(d); } // Reference error
  catch(e){ console.error(e.message) }
}
first()

Body:
The strange issue is caused by scoping rules in JavaScript

function first() {
   let a = b = c = 10; // a is in local scope, b and c are in global scope
   var d = 20; // d is in local scope
   second(); // will have access to b and c from the global scope
}

Assuming that you want to declare 3 local variables initialised to the same value (100). Your first() will look like below. In this case, second() will not have access to any of the variables because they are local to first()

function first() {
   let a = 100; // a is in local scope init to 100
   let b = a; // b is in local scope init to a
   let c = b // c is in local scope init to b

   var d = 20; // d is in local scope
   second(); // will not have access a, b, c, or d
}

However, if you want global variables then your first() will look like below. In this case, second will have access to all the variables because they are in global scope

function first() {
   a = 100; // a is in global scope
   b = a; // b is in global scope
   c = b // c is in global scope

   d = 20; // d is in global scope
   second(); // will have access to a, b, c, and d from the global scope
}

Local variables (aka. accessible in the code block where they are declared).
 A Code block is any {} with line(s) of code between.

function() {var, let, const in here is accessible to entire function},

for() {var in here is accessible to outer scope, let, const accessible only in here},

etc.

Global variables (aka accessible in the global scope).

These variables are attached to the global object. The global object is environment dependent. It is the window object in browsers.

Special note: You can declare variables in JavaScript without using the var, let, const keywords. A variable declared this way is attached to the global object, therefore accessible in the global scope.

a = 100 // is valid and is in global scope

Some articles for further reading:
https://www.sitepoint.com/demystifying-javascript-variable-scope-hoisting/
https://scotch.io/tutorials/understanding-scope-in-javascript
https://www.digitalocean.com/community/tutorials/understanding-variables-scope-hoisting-in-javascript


问:
"main" function in Lua?
In python, one would usually define a main function, in order to allow the script to be used as module (if needed):

```<code>def main():
    print("Hello world")
    return 0

if __name__ == "__main__":
    sys.exit(main())
</code>```

In Lua, the idiom if __name__ == "__main__" isn't possible as such (that means, I don't think it is).

That's what I'm usually doing in order to have a similar behaviour in Lua:

```<code>os.exit((function(args)
    print("Hello world")
    return 0
end)(arg))
</code>```

... But this approach seems rather "heavy on parentheses" :-)

Is there a more common approach (besides defining a global main function, which seems redundant)?

答:
When Lua requires a module, it passes it the name it's been required with as varargs (...).

So, if your script doesn't intend to take any arguments (from the command line or otherwise), you can use something like

```<code>if ... then
  return this_mod --module case
else
  main() --main case
end
</code>```

Note, however, that this isn't foolproof in the (entirely) possible case that you take arguments. However, at this point, you can combine this with Lukasz's answer to get:

```<code>if not package.loaded[...] then
  --main case
else --module case
end
</code>```

Still not perfect (for instance, if the script is called with a first argument of string or the name of some other already-loaded module), but likely good enough. In other situations, I defer to MattJ's answer.

ContentLicense: CC BY-SA 2.5

Title: "main" function in Lua?

Body:
In python, one would usually define a main function, in order to allow the script to be used as module (if needed):

def main():
    print("Hello world")
    return 0

if __name__ == "__main__":
    sys.exit(main())

In Lua, the idiom if __name__ == "__main__" isn't possible as such (that means, I don't think it is).

That's what I'm usually doing in order to have a similar behaviour in Lua:

os.exit((function(args)
    print("Hello world")
    return 0
end)(arg))

... But this approach seems rather "heavy on parentheses" :-)

Is there a more common approach (besides defining a global main function, which seems redundant)?

Body:
When Lua requires a module, it passes it the name it's been required with as varargs (...).

So, if your script doesn't intend to take any arguments (from the command line or otherwise), you can use something like

if ... then
  return this_mod --module case
else
  main() --main case
end

Note, however, that this isn't foolproof in the (entirely) possible case that you take arguments. However, at this point, you can combine this with Lukasz's answer to get:

if not package.loaded[...] then
  --main case
else --module case
end

Still not perfect (for instance, if the script is called with a first argument of string or the name of some other already-loaded module), but likely good enough. In other situations, I defer to MattJ's answer.


问:
Unable to pass prop back to parent component
I'm doing a simple test where I have a name state in the parent component which I update when a button in the child is clicked. But this does not work, and I'm confused on if I'm doing something wrong.

Parent:

```<code>import React from "react";
import "./styles.css";
import Hello from "./Hello";

export default function App() {
  const [name, setName] = React.useState();

  const handle = item => {
    setName(item);
  };

  console.log(name);

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <Hello test={handle} />
      {name}
    </div>
  );
}

</code>```

Child:

```<code>import React from "react";

export default function App() {
  return (
    <div>
      <button onclick={() => this.props.test("TEST")}>Activate Lasers</button>
    </div>
  );
}
</code>```

What am I doing wrong?

答:
First:
React events are written in camelCase syntax:

onClick instead of onclick.

second
the keyword this in react usually used in-class component, and using it in a functional component to bind it with where you are using it, so now you need to pass the props to the child so that you can access the function.
this should work

```<code>import React from "react";

export default function Hello(props) {
  return (
    <div>
      <button onClick={() => props.test("TEST")}>Activate Lasers</button>
    </div>
  );
}
</code>```

and third try to use the same naming for thing :) to be more readable
I hope I helped you

Body:
I'm doing a simple test where I have a name state in the parent component which I update when a button in the child is clicked. But this does not work, and I'm confused on if I'm doing something wrong.

Parent:

import React from "react";
import "./styles.css";
import Hello from "./Hello";

export default function App() {
  const [name, setName] = React.useState();

  const handle = item => {
    setName(item);
  };

  console.log(name);

  return (

Hello CodeSandbox

Start editing to see some magic happen!

      <Hello test={handle} />
      {name}

  );
}

Child:

import React from "react";

export default function App() {
  return (

      <button onclick={() => this.props.test("TEST")}>Activate Lasers</button>

  );
}

What am I doing wrong?

Body:
First:
React events are written in camelCase syntax:

onClick instead of onclick.

second
the keyword this in react usually used in-class component, and using it in a functional component to bind it with where you are using it, so now you need to pass the props to the child so that you can access the function.
this should work

import React from "react";

export default function Hello(props) {
  return (
    <div>
      <button onClick={() => props.test("TEST")}>Activate Lasers</button>
    </div>
  );
}

and third try to use the same naming for thing :) to be more readable
I hope I helped you