问:
UnhandledPromiseRejectionWarning discord js music bot
I am making a discord js music bot but when I change the song in it this error comes and after getting this error few times I get 403 error code and I have to restart the bot again</p>
```<code>(node:248) UnhandledPromiseRejectionWarning: DiscordAPIError: Missing Permissions
    at RequestHandler.execute (/home/runner/jammashama-1/node_modules/discord.js/src/rest/RequestHandler.js:154:13)
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
    at async RequestHandler.push (/home/runner/jammashama-1/node_modules/discord.js/src/rest/RequestHandler.js:39:14)
    at async GuildMember.edit (/home/runner/jammashama-1/node_modules/discord.js/src/structures/GuildMember.js:312:5)
(node:248) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:248) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Error: write EPIPE
ID: ubgFZnja_HE
Name: TheFatRat - Fly Away (Lyrics) feat. Anjulie
    at WriteWrap.onWriteComplete [as oncomplete] (internal/stream_base_commons.js:94:16) {
  errno: 'EPIPE',
  code: 'EPIPE',
  syscall: 'write'
}
(node:248) UnhandledPromiseRejectionWarning: DiscordAPIError: Missing Permissions
    at RequestHandler.execute (/home/runner/jammashama-1/node_modules/discord.js/src/rest/RequestHandler.js:154:13)
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
    at async RequestHandler.push (/home/runner/jammashama-1/node_modules/discord.js/src/rest/RequestHandler.js:39:14)
    at async GuildMember.edit (/home/runner/jammashama-1/node_modules/discord.js/src/structures/GuildMember.js:312:5)
(node:248) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
</code>```

答:
DiscordAPIError: Missing Permissions

The problem is that your bot does not have the required permissions.

Body:
I am making a discord js music bot but when I change the song in it this error comes and after getting this error few times I get 403 error code and I have to restart the bot again

(node:248) UnhandledPromiseRejectionWarning: DiscordAPIError: Missing Permissions
    at RequestHandler.execute (/home/runner/jammashama-1/node_modules/discord.js/src/rest/RequestHandler.js:154:13)
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
    at async RequestHandler.push (/home/runner/jammashama-1/node_modules/discord.js/src/rest/RequestHandler.js:39:14)
    at async GuildMember.edit (/home/runner/jammashama-1/node_modules/discord.js/src/structures/GuildMember.js:312:5)
(node:248) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:248) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Error: write EPIPE
ID: ubgFZnja_HE
Name: TheFatRat - Fly Away (Lyrics) feat. Anjulie
    at WriteWrap.onWriteComplete [as oncomplete] (internal/stream_base_commons.js:94:16) {
  errno: 'EPIPE',
  code: 'EPIPE',
  syscall: 'write'
}
(node:248) UnhandledPromiseRejectionWarning: DiscordAPIError: Missing Permissions
    at RequestHandler.execute (/home/runner/jammashama-1/node_modules/discord.js/src/rest/RequestHandler.js:154:13)
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
    at async RequestHandler.push (/home/runner/jammashama-1/node_modules/discord.js/src/rest/RequestHandler.js:39:14)
    at async GuildMember.edit (/home/runner/jammashama-1/node_modules/discord.js/src/structures/GuildMember.js:312:5)
(node:248) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)


来源: stackexchange

问:
Error when installing ESSURVEY package in R
I am trying to install the package "essurvey". But it is just throwing out error messages.

I am running Ubuntu 20.04 LTS and R version 4.1.2 (2021-11-01).

```<code>    > install.packages("essurvey")
Installing package into ‘/home/knut/R/x86_64-pc-linux-gnu-library/4.1’
(as ‘lib’ is unspecified)
also installing the dependencies ‘curl’, ‘xml2’, ‘httr’, ‘rvest’

trying URL 'https://cloud.r-project.org/src/contrib/curl_4.3.2.tar.gz'
Content type 'application/x-gzip' length 793345 bytes (774 KB)
==================================================
downloaded 774 KB

trying URL 'https://cloud.r-project.org/src/contrib/xml2_1.3.3.tar.gz'
Content type 'application/x-gzip' length 283965 bytes (277 KB)
==================================================
downloaded 277 KB

trying URL 'https://cloud.r-project.org/src/contrib/httr_1.4.2.tar.gz'
Content type 'application/x-gzip' length 159950 bytes (156 KB)
==================================================
downloaded 156 KB

trying URL 'https://cloud.r-project.org/src/contrib/rvest_1.0.2.tar.gz'
Content type 'application/x-gzip' length 94357 bytes (92 KB)
==================================================
downloaded 92 KB

trying URL 'https://cloud.r-project.org/src/contrib/essurvey_1.0.8.tar.gz'
Content type 'application/x-gzip' length 73081 bytes (71 KB)
==================================================
downloaded 71 KB

* installing *source* package ‘curl’ ...
** package ‘curl’ successfully unpacked and MD5 sums checked
** using staged installation
Package libcurl was not found in the pkg-config search path.
Perhaps you should add the directory containing `libcurl.pc'
to the PKG_CONFIG_PATH environment variable
No package 'libcurl' found
Package libcurl was not found in the pkg-config search path.
Perhaps you should add the directory containing `libcurl.pc'
to the PKG_CONFIG_PATH environment variable
No package 'libcurl' found
Using PKG_CFLAGS=
Using PKG_LIBS=-lcurl
------------------------- ANTICONF ERROR ---------------------------
Configuration failed because libcurl was not found. Try installing:
 * deb: libcurl4-openssl-dev (Debian, Ubuntu, etc)
 * rpm: libcurl-devel (Fedora, CentOS, RHEL)
 * csw: libcurl_dev (Solaris)
If libcurl is already installed, check that 'pkg-config' is in your
PATH and PKG_CONFIG_PATH contains a libcurl.pc file. If pkg-config
is unavailable you can set INCLUDE_DIR and LIB_DIR manually via:
R CMD INSTALL --configure-vars='INCLUDE_DIR=... LIB_DIR=...'
--------------------------------------------------------------------
ERROR: configuration failed for package ‘curl’
* removing ‘/home/knut/R/x86_64-pc-linux-gnu-library/4.1/curl’
Warning in install.packages :
  installation of package ‘curl’ had non-zero exit status
* installing *source* package ‘xml2’ ...
** package ‘xml2’ successfully unpacked and MD5 sums checked
** using staged installation
Package libxml-2.0 was not found in the pkg-config search path.
Perhaps you should add the directory containing `libxml-2.0.pc'
to the PKG_CONFIG_PATH environment variable
No package 'libxml-2.0' found
Package libxml-2.0 was not found in the pkg-config search path.
Perhaps you should add the directory containing `libxml-2.0.pc'
to the PKG_CONFIG_PATH environment variable
No package 'libxml-2.0' found
Using PKG_CFLAGS=
Using PKG_LIBS=-lxml2
------------------------- ANTICONF ERROR ---------------------------
Configuration failed because libxml-2.0 was not found. Try installing:
 * deb: libxml2-dev (Debian, Ubuntu, etc)
 * rpm: libxml2-devel (Fedora, CentOS, RHEL)
 * csw: libxml2_dev (Solaris)
If libxml-2.0 is already installed, check that 'pkg-config' is in your
PATH and PKG_CONFIG_PATH contains a libxml-2.0.pc file. If pkg-config
is unavailable you can set INCLUDE_DIR and LIB_DIR manually via:
R CMD INSTALL --configure-vars='INCLUDE_DIR=... LIB_DIR=...'
--------------------------------------------------------------------
ERROR: configuration failed for package ‘xml2’
* removing ‘/home/knut/R/x86_64-pc-linux-gnu-library/4.1/xml2’
Warning in install.packages :
  installation of package ‘xml2’ had non-zero exit status
ERROR: dependency ‘curl’ is not available for package ‘httr’
* removing ‘/home/knut/R/x86_64-pc-linux-gnu-library/4.1/httr’
Warning in install.packages :
  installation of package ‘httr’ had non-zero exit status
ERROR: dependencies ‘httr’, ‘xml2’ are not available for package ‘rvest’
* removing ‘/home/knut/R/x86_64-pc-linux-gnu-library/4.1/rvest’
Warning in install.packages :
  installation of package ‘rvest’ had non-zero exit status
ERROR: dependencies ‘xml2’, ‘httr’, ‘rvest’ are not available for package ‘essurvey’
* removing ‘/home/knut/R/x86_64-pc-linux-gnu-library/4.1/essurvey’
Warning in install.packages :
  installation of package ‘essurvey’ had non-zero exit status

The downloaded source packages are in
    ‘/tmp/RtmpWcvxK9/downloaded_packages’
</code>```

I have tried installing both the curl package and libcurl4-openssl-dev,libxml2-dev. The curl package gives me the same non-zero exit status, and libcurl4-openssl-dev,libxml2-dev shows:

```<code>> install.packages("libcurl4-openssl-dev")
Installing package into ‘/home/knut/R/x86_64-pc-linux-gnu-library/4.1’
(as ‘lib’ is unspecified)
Warning in install.packages :
  package ‘libcurl4-openssl-dev’ is not available for this version of R

A version of this package for your version of R might be available elsewhere,
see the ideas at
https://cran.r-project.org/doc/manuals/r-patched/R-admin.html#Installing-packages
</code>```

I hope I am missing something big here, I am new to programming in general.

答:
Grzegorz Sapijaszko answered my question with this answer:

From terminal install the package as: $ sudo apt install libcurl4-openssl-dev. THis part of error: Configuration failed because libcurl was not found. Try installing:  * deb: libcurl4-openssl-dev (Debian, Ubuntu, etc) tells you what packatge is missing.

The same for libxml2-dev: like sapi@t5810:~$ sudo apt install libxml2-dev

Thank you!

ContentLicense: CC BY-SA 4.0

Body:
I am trying to install the package "essurvey". But it is just throwing out error messages.

I am running Ubuntu 20.04 LTS and R version 4.1.2 (2021-11-01).

    > install.packages("essurvey")
Installing package into ‘/home/knut/R/x86_64-pc-linux-gnu-library/4.1’
(as ‘lib’ is unspecified)
also installing the dependencies ‘curl’, ‘xml2’, ‘httr’, ‘rvest’

trying URL 'https://cloud.r-project.org/src/contrib/curl_4.3.2.tar.gz'
Content type 'application/x-gzip' length 793345 bytes (774 KB)
==================================================
downloaded 774 KB

trying URL 'https://cloud.r-project.org/src/contrib/xml2_1.3.3.tar.gz'
Content type 'application/x-gzip' length 283965 bytes (277 KB)
==================================================
downloaded 277 KB

trying URL 'https://cloud.r-project.org/src/contrib/httr_1.4.2.tar.gz'
Content type 'application/x-gzip' length 159950 bytes (156 KB)
==================================================
downloaded 156 KB

trying URL 'https://cloud.r-project.org/src/contrib/rvest_1.0.2.tar.gz'
Content type 'application/x-gzip' length 94357 bytes (92 KB)
==================================================
downloaded 92 KB

trying URL 'https://cloud.r-project.org/src/contrib/essurvey_1.0.8.tar.gz'
Content type 'application/x-gzip' length 73081 bytes (71 KB)
==================================================
downloaded 71 KB

* installing *source* package ‘curl’ ...
** package ‘curl’ successfully unpacked and MD5 sums checked
** using staged installation
Package libcurl was not found in the pkg-config search path.
Perhaps you should add the directory containing `libcurl.pc'
to the PKG_CONFIG_PATH environment variable
No package 'libcurl' found
Package libcurl was not found in the pkg-config search path.
Perhaps you should add the directory containing `libcurl.pc'
to the PKG_CONFIG_PATH environment variable
No package 'libcurl' found
Using PKG_CFLAGS=
Using PKG_LIBS=-lcurl
------------------------- ANTICONF ERROR ---------------------------
Configuration failed because libcurl was not found. Try installing:
 * deb: libcurl4-openssl-dev (Debian, Ubuntu, etc)
 * rpm: libcurl-devel (Fedora, CentOS, RHEL)
 * csw: libcurl_dev (Solaris)
If libcurl is already installed, check that 'pkg-config' is in your
PATH and PKG_CONFIG_PATH contains a libcurl.pc file. If pkg-config
is unavailable you can set INCLUDE_DIR and LIB_DIR manually via:
R CMD INSTALL --configure-vars='INCLUDE_DIR=... LIB_DIR=...'
--------------------------------------------------------------------
ERROR: configuration failed for package ‘curl’
* removing ‘/home/knut/R/x86_64-pc-linux-gnu-library/4.1/curl’
Warning in install.packages :
  installation of package ‘curl’ had non-zero exit status
* installing *source* package ‘xml2’ ...
** package ‘xml2’ successfully unpacked and MD5 sums checked
** using staged installation
Package libxml-2.0 was not found in the pkg-config search path.
Perhaps you should add the directory containing `libxml-2.0.pc'
to the PKG_CONFIG_PATH environment variable
No package 'libxml-2.0' found
Package libxml-2.0 was not found in the pkg-config search path.
Perhaps you should add the directory containing `libxml-2.0.pc'
to the PKG_CONFIG_PATH environment variable
No package 'libxml-2.0' found
Using PKG_CFLAGS=
Using PKG_LIBS=-lxml2
------------------------- ANTICONF ERROR ---------------------------
Configuration failed because libxml-2.0 was not found. Try installing:
 * deb: libxml2-dev (Debian, Ubuntu, etc)
 * rpm: libxml2-devel (Fedora, CentOS, RHEL)
 * csw: libxml2_dev (Solaris)
If libxml-2.0 is already installed, check that 'pkg-config' is in your
PATH and PKG_CONFIG_PATH contains a libxml-2.0.pc file. If pkg-config
is unavailable you can set INCLUDE_DIR and LIB_DIR manually via:
R CMD INSTALL --configure-vars='INCLUDE_DIR=... LIB_DIR=...'
--------------------------------------------------------------------
ERROR: configuration failed for package ‘xml2’
* removing ‘/home/knut/R/x86_64-pc-linux-gnu-library/4.1/xml2’
Warning in install.packages :
  installation of package ‘xml2’ had non-zero exit status
ERROR: dependency ‘curl’ is not available for package ‘httr’
* removing ‘/home/knut/R/x86_64-pc-linux-gnu-library/4.1/httr’
Warning in install.packages :
  installation of package ‘httr’ had non-zero exit status
ERROR: dependencies ‘httr’, ‘xml2’ are not available for package ‘rvest’
* removing ‘/home/knut/R/x86_64-pc-linux-gnu-library/4.1/rvest’
Warning in install.packages :
  installation of package ‘rvest’ had non-zero exit status
ERROR: dependencies ‘xml2’, ‘httr’, ‘rvest’ are not available for package ‘essurvey’
* removing ‘/home/knut/R/x86_64-pc-linux-gnu-library/4.1/essurvey’
Warning in install.packages :
  installation of package ‘essurvey’ had non-zero exit status

The downloaded source packages are in
    ‘/tmp/RtmpWcvxK9/downloaded_packages’

I have tried installing both the curl package and libcurl4-openssl-dev,libxml2-dev. The curl package gives me the same non-zero exit status, and libcurl4-openssl-dev,libxml2-dev shows:

> install.packages("libcurl4-openssl-dev")
Installing package into ‘/home/knut/R/x86_64-pc-linux-gnu-library/4.1’
(as ‘lib’ is unspecified)
Warning in install.packages :
  package ‘libcurl4-openssl-dev’ is not available for this version of R

A version of this package for your version of R might be available elsewhere,
see the ideas at
https://cran.r-project.org/doc/manuals/r-patched/R-admin.html#Installing-packages

I hope I am missing something big here, I am new to programming in general.


问:
Firebase query function returning undefined when page is refreshed
I Got a service in Angular that gets User Data from firestore. The relevant service code is as follows:

```<code>userType:string = ''

async getProfileType(): Promise<string> {
    const userUID = await this.getUserUID();

    const getUserType = () => {
      this.af
        .collection('users')
        .doc(userUID)
        .valueChanges()
        .subscribe((doc: any) => {
          console.log(doc.userType);
          this.userType = doc.userType;
        });

      return this.userType;
    };
    return getUserType();
  }

</code>```

When I try to invoke it in the component by injecting it and calling the function in the ngOnInit method I get the following error:
ERROR TypeError: Cannot read properties of undefined (reading 'userType')

And when I invoke the function from the service manually it returns the data fine, but I'm not sure why it can't do the same thing when invoked on the ngOnInit method.

I've tried making ngOnInit async and use await on the getProfileType function but that didn't seem to make a difference.

The Component TypeScript is as follows:

```<code>import { Component, OnInit } from '@angular/core';
import { AngularFirestore } from '@angular/fire/compat/firestore';
import { UserInfoService } from '../services/user-info/user-info.service';

@Component({
  selector: 'app-edit-profiles',
  templateUrl: './edit-profiles.component.html',
  styleUrls: ['./edit-profiles.component.scss'],
})
export class EditProfilesComponent implements OnInit {
  constructor(public userInfo: UserInfoService, private af: AngularFirestore) {}

  async ngOnInit() {
    this.userInfo.getProfileType();
  }
</code>```

The Component HTML is as follows:

```<code><div *ngIf="userInfo.userType === 'user'">
  You're a User
</div>
<div *ngIf="userInfo.userType === 'project'">
  You're a Project
</div>
<button mat-flat-button (click)="userInfo.getProfileType()">Get Profile Type</button>

</code>```

Any help or direction is appreciated, cheers!

答:
Your getProfileType method claims to be returning a Promise<string>, but it's actually just returning a string that hasn't been initialize yet as you're never awaiting the database result.

```<code>async getProfileType(): Promise<string> {
</code>```

I'd recommend returning an Observable<string>, since the profile type may change:

```<code>getProfileType(): Observable<string> {
  const userUID = await this.getUserUID();

  return this.af
    .collection('users')
    .doc(userUID)
    .valueChanges()
    .pipe(map((doc: any) => {
      return doc.userType;
    }));
}
</code>```

Alternatively, you can stick to the Promise approach, but then return just one document with take(1) or first():

```<code>getProfileType(): Observable<string> {
  const userUID = await this.getUserUID();

  return this.af
    .collection('users')
    .doc(userUID)
    .valueChanges()
    .pipe(take(1))
    .pipe((doc: any) => {
      return doc.userType;
    });
}
</code>```

Body:
I Got a service in Angular that gets User Data from firestore. The relevant service code is as follows:

userType:string = ''

async getProfileType(): Promise<string> {
    const userUID = await this.getUserUID();

    const getUserType = () => {
      this.af
        .collection('users')
        .doc(userUID)
        .valueChanges()
        .subscribe((doc: any) => {
          console.log(doc.userType);
          this.userType = doc.userType;
        });

      return this.userType;
    };
    return getUserType();
  }

When I try to invoke it in the component by injecting it and calling the function in the ngOnInit method I get the following error:
ERROR TypeError: Cannot read properties of undefined (reading 'userType')

And when I invoke the function from the service manually it returns the data fine, but I'm not sure why it can't do the same thing when invoked on the ngOnInit method.

I've tried making ngOnInit async and use await on the getProfileType function but that didn't seem to make a difference.

The Component TypeScript is as follows:

import { Component, OnInit } from '@angular/core';
import { AngularFirestore } from '@angular/fire/compat/firestore';
import { UserInfoService } from '../services/user-info/user-info.service';

@Component({
  selector: 'app-edit-profiles',
  templateUrl: './edit-profiles.component.html',
  styleUrls: ['./edit-profiles.component.scss'],
})
export class EditProfilesComponent implements OnInit {
  constructor(public userInfo: UserInfoService, private af: AngularFirestore) {}

  async ngOnInit() {
    this.userInfo.getProfileType();
  }

The Component HTML is as follows:

  You're a User

  You're a Project

<button mat-flat-button (click)="userInfo.getProfileType()">Get Profile Type</button>

Any help or direction is appreciated, cheers!

Body:
Your getProfileType method claims to be returning a Promise<string>, but it's actually just returning a string that hasn't been initialize yet as you're never awaiting the database result.

async getProfileType(): Promise<string> {

I'd recommend returning an Observable<string>, since the profile type may change:

getProfileType(): Observable<string> {
  const userUID = await this.getUserUID();

  return this.af
    .collection('users')
    .doc(userUID)
    .valueChanges()
    .pipe(map((doc: any) => {
      return doc.userType;
    }));
}

Alternatively, you can stick to the Promise approach, but then return just one document with take(1) or first():

getProfileType(): Observable<string> {
  const userUID = await this.getUserUID();

  return this.af
    .collection('users')
    .doc(userUID)
    .valueChanges()
    .pipe(take(1))
    .pipe((doc: any) => {
      return doc.userType;
    });
}


问:
how to create a view/table from a single column
enter image description here

so i have the following table and want to create a query that will output the days it was most requested.
for example on 01/02/2000 there was 3 requests in total, on 02/02/2000 there was 2 request in total, on 03/03/2000 there was 6 request in total and on 04/02/2000 there was 4 request in total. so basically i want to output this in table is that possible or will it be easier to just create another table with all this info and make dates a foreign key?

答:
To get the date with highest number of request you can use rownum like below:

```<code>select * from
(select Date,Count(Date) as Total from Table Group by Date
order by Count(Date) desc)
where rownum=1;
</code>```

or you can use row_number() window function as below:

```<code>with cte as
(
   select Date,Count(Date) as Total ,row_number()over( order by Count(Date) desc)rn from employees
   group by Date
)
select Date, Total from cte where rn=1
</code>```

Body:
To get the date with highest number of request you can use rownum like below:

select * from
(select Date,Count(Date) as Total from Table Group by Date
order by Count(Date) desc)
where rownum=1;

or you can use row_number() window function as below:

with cte as
(
   select Date,Count(Date) as Total ,row_number()over( order by Count(Date) desc)rn from employees
   group by Date
)
select Date, Total from cte where rn=1


问:
How to run powershell script in maven
I currently dealing with a problem using maven. I try to update a file when building the software using maven. For some reason, I have to use a powershell script and run it when building using mvn. Here is my code:

```<code><exec executable="powershell.exe"
                      spawn="true">
                    <arg value="/c"/>
                    <arg value="myReplace.ps1"/>
                    <arg value="../../the/path/to/the/directory/" />
                    <arg value ="filename"/>
                    <arg value="value1" />
                    <arg value="value2" />
                    <arg value="value3" />
             </exec>
</code>```

It does not work as expected, can someone help me?

答:
This avoids a bug with PowerShell hanging on StdIn.</p>
```<code>        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <configuration>
                <useMavenLogger>true</useMavenLogger>
            </configuration>
            <executions>
                <execution>
                    <id>run-my-script</id>
                    <phase>generate-sources</phase>
                    <goals>
                        <goal>exec</goal>
                    </goals>
                    <configuration>
                        <executable>powershell.exe</executable>
                        <arguments>
                            <argument>-InputFormat</argument>
                            <argument>None</argument>
                            <argument>-File</argument>
                            <argument>${basedir}/my_script.ps1</argument>
                        </arguments>
                    </configuration>
                </execution>
            <executions>
        <plugin>
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to run powershell script in maven

Body:
I currently dealing with a problem using maven. I try to update a file when building the software using maven. For some reason, I have to use a powershell script and run it when building using mvn. Here is my code:

<exec executable="powershell.exe"
                      spawn="true">
                    <arg value="/c"/>
                    <arg value="myReplace.ps1"/>
                    <arg value="../../the/path/to/the/directory/" />
                    <arg value ="filename"/>
                    <arg value="value1" />
                    <arg value="value2" />
                    <arg value="value3" />
             </exec>

It does not work as expected, can someone help me?

Body:
This avoids a bug with PowerShell hanging on StdIn.

        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <configuration>
                <useMavenLogger>true</useMavenLogger>
            </configuration>
            <executions>
                <execution>
                    <id>run-my-script</id>
                    <phase>generate-sources</phase>
                    <goals>
                        <goal>exec</goal>
                    </goals>
                    <configuration>
                        <executable>powershell.exe</executable>
                        <arguments>
                            <argument>-InputFormat</argument>
                            <argument>None</argument>
                            <argument>-File</argument>
                            <argument>${basedir}/my_script.ps1</argument>
                        </arguments>
                    </configuration>
                </execution>
            <executions>
        <plugin>


问:
Vue project cannot resolve '@'
My vue-cli version is 4.5.15, but it cannot resolve @ as ./src and all paths using '@' are not found. Why did this happen and how could I solve it?

答:
Your statement tries to import a file which does not exist: import Layout from '@/layout' would work with layout.vue or layout/index.js, neither of which is present.

To fix this, you can either import the single components with their full path (as mentioned in @wittgenstein's comment): import Footer from '@/layout/Footer'

Or you can create layout/index.js which exposes all components inside the directory:

import Footer from './Footer.vue'
import Header from './Header.vue'
// ...

export default {
  Footer, Header, // ...
}
```

Then you can import components like that: import { Footer, Header } from '@/layout'

Title: Vue project cannot resolve '@'

Body:
Your statement tries to import a file which does not exist: import Layout from '@/layout' would work with layout.vue or layout/index.js, neither of which is present.

To fix this, you can either import the single components with their full path (as mentioned in @wittgenstein's comment): import Footer from '@/layout/Footer'

Or you can create layout/index.js which exposes all components inside the directory:

import Footer from './Footer.vue'
import Header from './Header.vue'
// ...

export default {
  Footer, Header, // ...
}

Then you can import components like that: import { Footer, Header } from '@/layout'


问:
How can I set firebase adminsdk file in .env file?
When I convert my adminSdk text to JSON.stringify and paste it .env file. it gives me that kind of error.</p>

答:
You probably want to do something like this.

```<code>// Admin SDK
const admin = require('firebase-admin')

// use environment variables to initialize the app!
admin.initializeApp({
  credential: admin.credential.cert({
    projectId: process.env.FIREBASE_PROJECT_ID,
    clientEmail: process.env.FIREBASE_CLIENT_EMAIL,
    // replace `\` and `n` character pairs w/ single `\n` character
    privateKey: process.env.FIREBASE_PRIVATE_KEY?.replace(/\\n/g, '\n'),
  }),
})
</code>```

In your environment file

```<code>FIREBASE_PROJECT_ID="[PROJECT_ID]"
FIREBASE_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\n[KEY_IS_HERE]\n-----END PRIVATE KEY-----\n"
FIREBASE_CLIENT_EMAIL="[CLIENT_EMAIL]"
</code>```

Body:
You probably want to do something like this.

// Admin SDK
const admin = require('firebase-admin')

// use environment variables to initialize the app!
admin.initializeApp({
  credential: admin.credential.cert({
    projectId: process.env.FIREBASE_PROJECT_ID,
    clientEmail: process.env.FIREBASE_CLIENT_EMAIL,
    // replace `\` and `n` character pairs w/ single `\n` character
    privateKey: process.env.FIREBASE_PRIVATE_KEY?.replace(/\\n/g, '\n'),
  }),
})

In your environment file

FIREBASE_PROJECT_ID="[PROJECT_ID]"
FIREBASE_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\n[KEY_IS_HERE]\n-----END PRIVATE KEY-----\n"
FIREBASE_CLIENT_EMAIL="[CLIENT_EMAIL]"


问:
Detecting an "invalid date" Date instance in JavaScript
I'd like to tell the difference between valid and invalid date objects in JS, but couldn't figure out how:

```<code>var d = new Date("foo");
console.log(d.toString()); // shows 'Invalid Date'
console.log(typeof d); // shows 'object'
console.log(d instanceof Date); // shows 'true'
</code>```

Any ideas for writing an isValidDate function?

Ash recommended Date.parse for parsing date strings, which gives an authoritative way to check if the date string is valid.

What I would prefer, if possible, is have my API accept a Date instance and to be able to check/assert whether it's valid or not. Borgar's solution does that, but I need to test it across browsers. I also wonder whether there's a more elegant way.

Ash made me consider not having my API accept Date instances at all, this would be easiest to validate.

Borgar suggested testing for a Date instance, and then testing for the Date's time value. If the date is invalid, the time value is NaN. I checked with ECMA-262 and this behavior is in the standard, which is exactly what I'm looking for.

答:
Inspired by Borgar's approach I made sure that the code not only validates the date, but actually makes sure the date is a real date, meaning that dates like 31/09/2011 and 29/02/2011 are not allowed.

function(dateStr) {
  s = dateStr.split('/');
  d = new Date(+s[2], s[1] - 1, +s[0]);
  if (Object.prototype.toString.call(d) === "[object Date]") {
    if (!isNaN(d.getTime()) && d.getDate() == s[0] &&
      d.getMonth() == (s[1] - 1)) {
      return true;
    }
  }
  return "Invalid date!";
}
```

Body:
I'd like to tell the difference between valid and invalid date objects in JS, but couldn't figure out how:

var d = new Date("foo");
console.log(d.toString()); // shows 'Invalid Date'
console.log(typeof d); // shows 'object'
console.log(d instanceof Date); // shows 'true'

Any ideas for writing an isValidDate function?

Ash recommended Date.parse for parsing date strings, which gives an authoritative way to check if the date string is valid.

What I would prefer, if possible, is have my API accept a Date instance and to be able to check/assert whether it's valid or not. Borgar's solution does that, but I need to test it across browsers. I also wonder whether there's a more elegant way.

Ash made me consider not having my API accept Date instances at all, this would be easiest to validate.

Borgar suggested testing for a Date instance, and then testing for the Date's time value. If the date is invalid, the time value is NaN. I checked with ECMA-262 and this behavior is in the standard, which is exactly what I'm looking for.


问:
How to run an api request until a condition is met in c#
I'm new to C# and my purpose is to parse a value from an API call and keep on doing the call until that value is between 5 and 10 for that parameter.

I have successfully parsed that value from valuez and got the proper result in finalresult, now my problem is to make the call repeatedly until I reach the intended value bracket, I tried debugging the code below but when it reaches var timer the entire block is highlighted at once and not every line is accessed separately. I know the condition of stopping between 5 and 10 is not in the code below but it was supposed to run endlessly before i modify that part.

sample response

```<code>{{
"value1" : "input1",
"value2" : null,
"value3" : {"valuex" : 4,
"valuey" : 5,
"valuez" : 6}
"value4" : 17
}}
</code>```

,

Code

```<code>var options = new RestClientOptions(Endpoint)
double finalresult = -1;

var startTimeSpan = System.TimeSpan.Zero;
var periodTimeSpan = System.TimeSpan.FromMinutes(1);

var timer = new System.Threading.Timer(async(e) =>
{
var client = new RestClient(options);
vsr request = new RestRequest();
var response = await client.GetAsync(request);
var requestContent = response.Content;
var parsed = JsonConvert.DeserializeObject<StatusResponse>(responseContent);
finalresult = statusResponse.value3.valuez

}, null, startTimeSpan, periodTimeSpan);
</code>```

答:
I think this is what you need:

```<code>public async Task<double> GetValuez()
{
  var options = new RestClientOptions(Endpoint)
  double finalresult = -1;

  var startTimeSpan = System.TimeSpan.Zero;
  var periodTimeSpan = System.TimeSpan.FromMinutes(1);
  var client = new RestClient(options);

  while (true)
  {
    var request = new RestRequest();
    var response = await client.GetAsync(request);
    var requestContent = response.Content;
    var parsed = JsonConvert.DeserializeObject<StatusResponse>(responseContent);
    finalresult = statusResponse.value3.valuez

    if (finalresult >= 5 && finalresult <= 10) return finalresult;

    await Task.Delay(periodTimeSpan);
  }
}
</code>```

It's a simple loop that will keep requesting until the condition is met.

Body:
I'm new to C# and my purpose is to parse a value from an API call and keep on doing the call until that value is between 5 and 10 for that parameter.

I have successfully parsed that value from valuez and got the proper result in finalresult, now my problem is to make the call repeatedly until I reach the intended value bracket, I tried debugging the code below but when it reaches var timer the entire block is highlighted at once and not every line is accessed separately. I know the condition of stopping between 5 and 10 is not in the code below but it was supposed to run endlessly before i modify that part.

sample response

{{
"value1" : "input1",
"value2" : null,
"value3" : {"valuex" : 4,
"valuey" : 5,
"valuez" : 6}
"value4" : 17
}}

,

Code

var options = new RestClientOptions(Endpoint)
double finalresult = -1;

var startTimeSpan = System.TimeSpan.Zero;
var periodTimeSpan = System.TimeSpan.FromMinutes(1);

var timer = new System.Threading.Timer(async(e) =>
{
var client = new RestClient(options);
vsr request = new RestRequest();
var response = await client.GetAsync(request);
var requestContent = response.Content;
var parsed = JsonConvert.DeserializeObject<StatusResponse>(responseContent);
finalresult = statusResponse.value3.valuez

}, null, startTimeSpan, periodTimeSpan);

Body:
I think this is what you need:

public async Task<double> GetValuez()
{
  var options = new RestClientOptions(Endpoint)
  double finalresult = -1;

  var startTimeSpan = System.TimeSpan.Zero;
  var periodTimeSpan = System.TimeSpan.FromMinutes(1);
  var client = new RestClient(options);

  while (true)
  {
    var request = new RestRequest();
    var response = await client.GetAsync(request);
    var requestContent = response.Content;
    var parsed = JsonConvert.DeserializeObject<StatusResponse>(responseContent);
    finalresult = statusResponse.value3.valuez

    if (finalresult >= 5 && finalresult <= 10) return finalresult;

    await Task.Delay(periodTimeSpan);
  }
}

It's a simple loop that will keep requesting until the condition is met.


问:
how can pass different parameters using [routerLink] or router.navigate to a component?
I configured app-routing.module.ts as following:

const routes: Routes = [
  {
    path: "branches/:branch",
    component: BranchesComponent
  },

  // ...
];```
</div>
</div>
</p>
<p>and also in app.component.html have:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><li>
       engineering
    </li>
    <li>
       baseSciense
    </li>
    <li>
       humanities
    </li>
  </ul>

  <router-outlet></router-outlet></code>```

and in the barnches.component.ts I coded as bellow:

branch: string ='';

  constructor(private route: ActivatedRoute) { }

  ngOnInit(): void {

    this.route.params.subscribe(({branch: branch1}) => this.branch = branch1);

    // I also tried this code:
    // this.route.params.subscribe(branch => this.branch = branch['branch']);

    // unfortunately, bellow codes have error on p.branch and params.branch! why?
    // this.route.params.subscribe(p => this.branch = p.branch)
    // this.branch = this.route.snapshot.params.branch;

    console.log(`branch is : ${this.branch}`);
  }```
</div>
</div>
</p>
<p>till here everything comes correct, and URL is changed once the respective link is clicked, such as :</p>
```http://localhost:4200/branches/engineering

http://localhost:4200/branches/baseSciense

http://localhost:4200/branches/humanities
```

but the property branch in Branches component is not changed and has same value (engineering) for different parameters in log of the console. it is illogical for me!

how can solve this problem as pass different parameters to and capture them into branches component? Best regards

答:
You need to move your console.log within the subscription. Most of the code related to this feature will need to take place within the subscription. The Component doesn't re-render on url change because it is loading the same component and angular doesn't re-render components if it is the same component.

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
  template: 'Branch: {{branch}}',
})
export class BranchesComponent implements OnInit {
  branch = '';

  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
    // Set the value every time the URL param changes.
    this.route.params.subscribe(({ branch }) => {
      this.branch = branch;
      console.log('branch:', this.branch);
    });
  }
}
```

Body:
I configured app-routing.module.ts as following:

const routes: Routes = [
  {
    path: "branches/:branch",
    component: BranchesComponent
  },

  // ...
];

and also in app.component.html have:

       engineering

       baseSciense

       humanities

  <router-outlet></router-outlet>

and in the barnches.component.ts I coded as bellow:

branch: string ='';

  constructor(private route: ActivatedRoute) { }

  ngOnInit(): void {

    this.route.params.subscribe(({branch: branch1}) => this.branch = branch1);

    // I also tried this code:
    // this.route.params.subscribe(branch => this.branch = branch['branch']);

    // unfortunately, bellow codes have error on p.branch and params.branch! why?
    // this.route.params.subscribe(p => this.branch = p.branch)
    // this.branch = this.route.snapshot.params.branch;

    console.log(`branch is : ${this.branch}`);
  }

till here everything comes correct, and URL is changed once the respective link is clicked, such as :

http://localhost:4200/branches/engineering

http://localhost:4200/branches/baseSciense

http://localhost:4200/branches/humanities

but the property branch in Branches component is not changed and has same value (engineering) for different parameters in log of the console. it is illogical for me!

how can solve this problem as pass different parameters to and capture them into branches component? Best regards


问:
Why does running `flask run` on Windows result in "flask is not recognized as an internal or external command, operable program or batch file"
I needed to setup Flask for windows, so I ran the following commands:

```<code>set FLASK_APP=application.py
set FLASK_DEBUG=1
set DATABASE_URL='postgres.......' =>(the credential given by the Heroku account)
flask run
</code>```

But when I hit enter on the flask run, I get an error that says -

flask is not recognized as an internal or external command, operable program or batch file

Why is this not working? I've been trying to work on it but I'm still having the same error message.

What could be the issue?

答:
Make sure you've saved the application.py and the app variable exists.

then run python -m flask run ,

Body:
I needed to setup Flask for windows, so I ran the following commands:

set FLASK_APP=application.py
set FLASK_DEBUG=1
set DATABASE_URL='postgres.......' =>(the credential given by the Heroku account)
flask run

But when I hit enter on the flask run, I get an error that says -

flask is not recognized as an internal or external command, operable program or batch file

Why is this not working? I've been trying to work on it but I'm still having the same error message.

What could be the issue?


问:
Implementation of a lock using test and set
Below is the code is given in OSTEP book regarding the implementation of a lock using test and set instruction. My question is that in such implementation, couldn't a thread that is not holding the lock call the unlock function and take away the lock?</p>

```<code>typedef struct __lock_t {
 int flag;
 } lock_t;

 void init(lock_t *lock) {
 // 0 indicates that lock is available, 1 that it is held
 lock->flag = 0;
 }

 void lock(lock_t *lock) {
 while (TestAndSet(&lock->flag, 1) == 1)
 ; // spin-wait (do nothing)
 }

 void unlock(lock_t *lock) {
 lock->flag = 0;
 }
</code>```

答: It's assumed that it's a coding error so that case should not be happening.</p>

Body:
Below is the code is given in OSTEP book regarding the implementation of a lock using test and set instruction. My question is that in such implementation, couldn't a thread that is not holding the lock call the unlock function and take away the lock?

typedef struct __lock_t {
 int flag;
 } lock_t;

 void init(lock_t *lock) {
 // 0 indicates that lock is available, 1 that it is held
 lock->flag = 0;
 }

 void lock(lock_t *lock) {
 while (TestAndSet(&lock->flag, 1) == 1)
 ; // spin-wait (do nothing)
 }

 void unlock(lock_t *lock) {
 lock->flag = 0;
 }


问:
How to integrate auth step into feathers service
I'm trying to integrate jwt/local auth into any call to feathers. So by including user/pass in any call it authorizes, rather than requiring a individual previous call to the /authorization endpoint and passing a header to subsequent calls. Ive tried using authenticate, but it doesnt see my auth strategies from within a hook. Here is the current create code, it does return the jwt token but how do i auth from here and integrate user data from the database into context like the auth generally would otherwise?</p>
```<code>module.exports = (options = {}) => {
  return async (context) => {
    let promise = new Promise((resolve, reject) => {
      context.app
        .service("authentication")
        .create({
          username: context.data.username,
          password: context.data.password,
          strategy:"local"
        })
        .then((response) => {
          console.log(response)
          context.arguments[1]['Authorization'] = response.accessToken
          resolve(context);
        });
    });
    let result = await promise;
    if (result) {
      return context;
    }
  };
};
</code>```

答:
The authenticate hook can take any strategy and will look for whatever you pass in params.authentication. In your example the following:

```<code>module.exports = (options = {}) => {
  return async (context) => {
    context.params = {
      ...context.params,
      authentication: {
        strategy: 'local',
        username: context.data.username,
        password: context.data.password
      }
    }

    return context;
  };
};
</code>```

Would allow for authenticate('local') to run. If you want to get the authentication information from an HTTP request you can implement the parse(req, res) method in a custom strategy.

Body:
I'm trying to integrate jwt/local auth into any call to feathers. So by including user/pass in any call it authorizes, rather than requiring a individual previous call to the /authorization endpoint and passing a header to subsequent calls. Ive tried using authenticate, but it doesnt see my auth strategies from within a hook. Here is the current create code, it does return the jwt token but how do i auth from here and integrate user data from the database into context like the auth generally would otherwise?

module.exports = (options = {}) => {
  return async (context) => {
    let promise = new Promise((resolve, reject) => {
      context.app
        .service("authentication")
        .create({
          username: context.data.username,
          password: context.data.password,
          strategy:"local"
        })
        .then((response) => {
          console.log(response)
          context.arguments[1]['Authorization'] = response.accessToken
          resolve(context);
        });
    });
    let result = await promise;
    if (result) {
      return context;
    }
  };
};

Body:
The authenticate hook can take any strategy and will look for whatever you pass in params.authentication. In your example the following:

module.exports = (options = {}) => {
  return async (context) => {
    context.params = {
      ...context.params,
      authentication: {
        strategy: 'local',
        username: context.data.username,
        password: context.data.password
      }
    }

    return context;
  };
};

Would allow for authenticate('local') to run. If you want to get the authentication information from an HTTP request you can implement the parse(req, res) method in a custom strategy.


问:
Can't get variable in another class - Flutter
Tell me, I need to get a hash variable in a cubit file which is in block_info_page. I need this variable to make an API request to block_repository that uses the hash_block variable. Is it possible to implement this? Thanks in advance.

cubit

```<code>class BlockinfoCubit extends Cubit<BlockInfoState> {
  final BlockInfoRepository _blockInfoRepository;

  BlockinfoCubit(this._blockInfoRepository) : super(BlockInfoInitialState());

  void getBlockInfo() async {
    emit(BlockInfoLoadingState());
    try {
      final hash_block = ;
      final blocksInfo = await _blockInfoRepository.getBlockInfo(hash_block);
      emit(BlockInfoLoadedState(blocksInfo));
    } catch (e) {
      emit(BlockInfoErrorState(e.toString()));
    }
  }
}
</code>```

block_info_page

```<code>class BlockInfoPage extends StatelessWidget {
  final String hash;
  const BlockInfoPage({Key? key, required this.hash}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.white,
        title: Image.asset(
          'assets/images/logo.png',
          height: 35,
        ),
        centerTitle: false,
      ),
      body: Center(child: Text(hash)),
    );
  }
}
</code>```

block_repository

```<code>class BlockInfoRepository {
  Future<List<BlockInfoModel>> getBlockInfo(hash_block) async {
    final response = await http
        .get(Uri.parse('https://blockchain.../$hash_block'));

    if (response.hashCode == 200) {
      final blockInfo = json.decode(response.body);

      return blockInfo
          .map<BlockInfoModel>((json) => BlockInfoModel.fromJson(json))
          .toList();
    } else {
      throw Exception('Failed to load block-info');
    }
  }
}
</code>```

block_page

```<code>TextButton(
                              onPressed: () => Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                      builder: (context) => BlockInfoPage(
                                          hash: blocksData[index].hash))),
</code>```

答:
that's really easy.

first import the block_info_page that has the variable inside.

then you have 2 ways:

make the hash variable static: static String hash;

for the other way you don't need to do now anything

WAY 1

you can get the variable like this:
BlockInfoPage.hash;

what it does is: pick the variable out of the class without build the whole class again

WAY 2

you can get the variable like this:
BlockInfoPage().hash;

what it does is: build the whole class again and after this it pick the variable out of the class

if that don't work make the variable global - put the hash variable outside of your class

you can access to the global variable like this:

first import the file that has the global variable inside

you can acces to your global variable like you was in the file that has the global variable inside: hash

PS: because your global variable is not more inside of the class it never will set automatically to the begining value

Body:
Tell me, I need to get a hash variable in a cubit file which is in block_info_page. I need this variable to make an API request to block_repository that uses the hash_block variable. Is it possible to implement this? Thanks in advance.

cubit

class BlockinfoCubit extends Cubit<BlockInfoState> {
  final BlockInfoRepository _blockInfoRepository;

  BlockinfoCubit(this._blockInfoRepository) : super(BlockInfoInitialState());

  void getBlockInfo() async {
    emit(BlockInfoLoadingState());
    try {
      final hash_block = ;
      final blocksInfo = await _blockInfoRepository.getBlockInfo(hash_block);
      emit(BlockInfoLoadedState(blocksInfo));
    } catch (e) {
      emit(BlockInfoErrorState(e.toString()));
    }
  }
}

block_info_page

class BlockInfoPage extends StatelessWidget {
  final String hash;
  const BlockInfoPage({Key? key, required this.hash}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.white,
        title: Image.asset(
          'assets/images/logo.png',
          height: 35,
        ),
        centerTitle: false,
      ),
      body: Center(child: Text(hash)),
    );
  }
}

block_repository

class BlockInfoRepository {
  Future<List<BlockInfoModel>> getBlockInfo(hash_block) async {
    final response = await http
        .get(Uri.parse('https://blockchain.../$hash_block'));

    if (response.hashCode == 200) {
      final blockInfo = json.decode(response.body);

      return blockInfo
          .map<BlockInfoModel>((json) => BlockInfoModel.fromJson(json))
          .toList();
    } else {
      throw Exception('Failed to load block-info');
    }
  }
}

block_page

TextButton(
                              onPressed: () => Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                      builder: (context) => BlockInfoPage(
                                          hash: blocksData[index].hash))),


问:
jQuery - remove user input text from textarea
Okay I have a list of devices where i can select which to edit.
I have 3 states for the edit. When no devices are selected, when 1 device is selected or when x devices are selected.

The problem i have is when a user type some text in the textarea (commentField) and cancels the edit to edit another device, the text there was typed in the textarea won't disapere. It stays so when i get the new dialog for the new edit, the commentfield has the text from the old commentField (as if it wasn't cleared)

I have tried the following codes to remove the text (both when then cancel button is pressed and when i start a new dialog), but nothing works:

```<code>$("#commentField").text(" ");
$("#commentField").value = ' ';
</code>```

Is there anyone who knows how to remove user-typed text from a textarea using jQuery??

Thanks in advance.

-Thor

答:
You're looking for .val():

```<code>$("#commentField").val('');
</code>```

Example: http://jsfiddle.net/andrewwhitaker/q6eLV/

Body:
Okay I have a list of devices where i can select which to edit.
I have 3 states for the edit. When no devices are selected, when 1 device is selected or when x devices are selected.

The problem i have is when a user type some text in the textarea (commentField) and cancels the edit to edit another device, the text there was typed in the textarea won't disapere. It stays so when i get the new dialog for the new edit, the commentfield has the text from the old commentField (as if it wasn't cleared)

I have tried the following codes to remove the text (both when then cancel button is pressed and when i start a new dialog), but nothing works:

$("#commentField").text(" ");
$("#commentField").value = ' ';

Is there anyone who knows how to remove user-typed text from a textarea using jQuery??

Thanks in advance.

-Thor

Body:
You're looking for .val():

$("#commentField").val('');

Example: http://jsfiddle.net/andrewwhitaker/q6eLV/


问:
What is difference between normal functions and typeclass functions?

class (Typeable e, Show e) => Exception e where
    toException   :: e -> SomeException
    fromException :: SomeException -> Maybe e

    toException = SomeException
    fromException (SomeException e) = cast e
```
```data MyException1 = Exception1A | Exception1B
    deriving (Show)
instance Exception MyException1

data MyException2 = Exception2A | Exception2B
    deriving (Show)
instance Exception MyException2
```
<p>It is able to define multiple exceptions. So, multiple <code>fromException</code> functions are able to be defined too. I think it is weird because two functions can have same name and same input.</p>
<pre class="lang-hs prettyprint-override"><code>fromException :: SomeException -> Maybe MyException1
fromException :: SomeException -> Maybe MyException2
</code>```

Even if the reason why this behavior is ok is "Two functions have different type include return type (and expressions are  evaluated based these all types)", it is weird, because I can't define normal functions that way.

f :: Integer -> Maybe Integer
f = cast

f :: Integer -> Maybe Char
f n = cast $ show n
```

What is difference between normal functions and type class functions?

答:
The fact that you cannot define normal functions that way is the whole difference.

The whole purpose of type classes is to allow overloading - that is, defining multiple different functions with different types, but same name. And have the compiler pick the right one automatically based on types expected in the context.

Body:
class (Typeable e, Show e) => Exception e where
    toException   :: e -> SomeException
    fromException :: SomeException -> Maybe e

    toException = SomeException
    fromException (SomeException e) = cast e

data MyException1 = Exception1A | Exception1B
    deriving (Show)
instance Exception MyException1

data MyException2 = Exception2A | Exception2B
    deriving (Show)
instance Exception MyException2

It is able to define multiple exceptions. So, multiple fromException functions are able to be defined too. I think it is weird because two functions can have same name and same input.

fromException :: SomeException -> Maybe MyException1
fromException :: SomeException -> Maybe MyException2

Even if the reason why this behavior is ok is "Two functions have different type include return type (and expressions are  evaluated based these all types)", it is weird, because I can't define normal functions that way.

f :: Integer -> Maybe Integer
f = cast

f :: Integer -> Maybe Char
f n = cast $ show n

What is difference between normal functions and type class functions?


问:
Legend wont display in stacked bar graph where the 2 series of values are numerical
I have a stacked bar graph with 2 numerical values and the bars are stacked on top of eachother.  I would like to display a Legend that indicates the description of the 2 colors.  Here it is my code but its not displaying.  Any help from anyone I would be greatful for.

```<code>ggplot(data=my_data, aes(x = Xaxis)) +
    ggtitle("My Title")+
    theme(plot.title = element_text(hjust = 0.5, face="bold"))+
    geom_col(aes(y = v1), fill ="red")+
    geom_col(aes(y = v2), fill="blue")+
    labs(y= "Amount", color ="Legend")+
    theme(legend.title = element_text(color='black',face='bold'),
        legend.text = element_text(color='black',face='bold'))+
    scale_y_continuous(labels = comma)
</code>```

From the above code the legend does not display

答:
Update:
As I already mentioned in the comments you may consider another strategy with long format, but with your format you are in conflict with showing the legend of fill argument and getting the correct colors.

If you put the fill argument outside of aes no legend will be shown but you get the correct colors.

If you put fill argument inside the aes then the legend will be shown but the colors will be not as desired -> this is because you're basically generating a new factor variable and a legend.

https://github.com/tidyverse/ggplot2/issues/1675

With the mtcars dataset:

```<code>ggplot(data=mtcars, aes(x = cyl)) +
  ggtitle("My Title")+
  theme(plot.title = element_text(hjust = 0.5, face="bold"))+
  geom_col(aes(x = cyl, y = disp, fill ="red"))+
  geom_col(aes(x= cyl, y = mpg, fill="blue"))+
  labs(y= "Amount", color ="Legend")+
  theme(legend.title = element_text(color='black',face='bold'),
        legend.text = element_text(color='black',face='bold'))+
  scale_fill_manual(values = c('red','blue'), labels=c('disp', 'mpg'))
</code>```

First answer:
try this:

```<code>ggplot(data=my_data, aes(x = Xaxis)) +
  ggtitle("My Title")+
  theme(plot.title = element_text(hjust = 0.5, face="bold"))+
  geom_col(aes(y = v1, fill ="red"))+
  geom_col(aes(y = v2, fill="blue")))+
  labs(y= "Amount", color ="Legend")+
  theme(legend.title = element_text(color='black',face='bold'),
        legend.text = element_text(color='black',face='bold'))+
  scale_y_continuous(labels = comma)
</code>```

your code with the mtcars data set:

```<code>ggplot(data=mtcars, aes(x = cyl)) +
  ggtitle("My Title")+
  theme(plot.title = element_text(hjust = 0.5, face="bold"))+
  geom_col(aes(y = disp, fill ="red"))+
  geom_col(aes(y = mpg, fill="blue"))+
  labs(y= "Amount", color ="Legend")+
  theme(legend.title = element_text(color='black',face='bold'),
        legend.text = element_text(color='black',face='bold'))
</code>```

gives:

Body:
I have a stacked bar graph with 2 numerical values and the bars are stacked on top of eachother.  I would like to display a Legend that indicates the description of the 2 colors.  Here it is my code but its not displaying.  Any help from anyone I would be greatful for.

ggplot(data=my_data, aes(x = Xaxis)) +
    ggtitle("My Title")+
    theme(plot.title = element_text(hjust = 0.5, face="bold"))+
    geom_col(aes(y = v1), fill ="red")+
    geom_col(aes(y = v2), fill="blue")+
    labs(y= "Amount", color ="Legend")+
    theme(legend.title = element_text(color='black',face='bold'),
        legend.text = element_text(color='black',face='bold'))+
    scale_y_continuous(labels = comma)

From the above code the legend does not display

Body:
Update:
As I already mentioned in the comments you may consider another strategy with long format, but with your format you are in conflict with showing the legend of fill argument and getting the correct colors.

If you put the fill argument outside of aes no legend will be shown but you get the correct colors.

If you put fill argument inside the aes then the legend will be shown but the colors will be not as desired -> this is because you're basically generating a new factor variable and a legend.

https://github.com/tidyverse/ggplot2/issues/1675

With the mtcars dataset:

ggplot(data=mtcars, aes(x = cyl)) +
  ggtitle("My Title")+
  theme(plot.title = element_text(hjust = 0.5, face="bold"))+
  geom_col(aes(x = cyl, y = disp, fill ="red"))+
  geom_col(aes(x= cyl, y = mpg, fill="blue"))+
  labs(y= "Amount", color ="Legend")+
  theme(legend.title = element_text(color='black',face='bold'),
        legend.text = element_text(color='black',face='bold'))+
  scale_fill_manual(values = c('red','blue'), labels=c('disp', 'mpg'))

First answer:
try this:

ggplot(data=my_data, aes(x = Xaxis)) +
  ggtitle("My Title")+
  theme(plot.title = element_text(hjust = 0.5, face="bold"))+
  geom_col(aes(y = v1, fill ="red"))+
  geom_col(aes(y = v2, fill="blue")))+
  labs(y= "Amount", color ="Legend")+
  theme(legend.title = element_text(color='black',face='bold'),
        legend.text = element_text(color='black',face='bold'))+
  scale_y_continuous(labels = comma)

your code with the mtcars data set:

ggplot(data=mtcars, aes(x = cyl)) +
  ggtitle("My Title")+
  theme(plot.title = element_text(hjust = 0.5, face="bold"))+
  geom_col(aes(y = disp, fill ="red"))+
  geom_col(aes(y = mpg, fill="blue"))+
  labs(y= "Amount", color ="Legend")+
  theme(legend.title = element_text(color='black',face='bold'),
        legend.text = element_text(color='black',face='bold'))

gives:


问:
Background rectangle fit to label text in Kivy
I am trying to get a background around a label that fits the number of lines in the texted in it.  For example, a label with text 'Line1\nLine1\nLine3' would have a larger Y dimension that just 'line1'

What currently happens is all of the labels are the same size and clip-off text that doesn't fit within them, the labels are also inside a recycleview layout because I would like to be able to scroll and update large amount of the labels often.

I have tried a few things but have had no luck, and am struggling to get a variable to be understood where I have added # HERE in the .kv file

```<code>from kivy.app import App
from kivy.properties import NumericProperty, Clock, ObjectProperty, StringProperty
from kivy.uix.widget import Widget
from kivy.uix.recycleview import RecycleView
from kivy.uix.button import Button
from kivy.uix.label import Label

class TopPostsTest(RecycleView):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        message_height = NumericProperty(20)
        items = ["hello\ntest\ntest", "test, gghgjhgjhgjhgjhghjghjgjhgjhgjhgjhgjhgjhgjhgjhg", "cheese"]
        self.data = [{'text':str(p)} for p in items]

class LabelColor(Label):
    pass

class TruthApp(App):
#    def build(self):
#        return super().build()
    pass

if __name__ == "__main__":
    TruthApp().run()
</code>```
```<code><MainControl@PageLayout>:
    border: "25dp"
    swipe_threshold: 0.4
    TopPostsTest:
    Settings:

<LabelColor>:
    color: 0,0,0,1
    text_size: self.size
    halign: 'left'
    valign: 'top'
    font_name: "Assets/Fonts/Nunito-Bold.ttf"
    font_size: "12dp"
    multiline: True

    canvas.before:
        Color:
            rgba: (0.8, 0.8, 0.8, 1)
        RoundedRectangle:
            pos: self.pos
            size: self.size
            radius: [5, 5, 5, 5]
    canvas:
        Color:
            rgba:0,0.9,0.9,1
        Line:
            width:0.8
            rounded_rectangle:(self.x,self.y,self.width,root.height, 5) # HERE

<TopPostsTest>:
    viewclass: 'LabelColor'
    scroll_y: 1
    RecycleBoxLayout:
        id: message_view
        default_size: None, dp(40) # NewHERE
        default_size_hint: 1, None
        size_hint_y: None
        padding: ["10dp", "16dp"]
        spacing: "8dp"
        height: self.minimum_height
        orientation: 'vertical'
</code>```

Thank you for any help :)

Edit:
I have found that I have been changing the wrong value and that the variable that needs changing has been marker with # NewHERE, however I am still unable to get it to work or get a variable from the py file into the kv

答:
In order to get a Label that expands vertically as it's text-content grows you can set its height to its texture height.

Also, to fit the text within available space (width) you can change text_size.

Thus you can modify the kvlang for LabelColor as,

<LabelColor>:
    color: 0,0,0,1
    text_size: self.width, None
    size_hint_y: None
    height: self.texture_size[1]
```

Body:
I am trying to get a background around a label that fits the number of lines in the texted in it.  For example, a label with text 'Line1\nLine1\nLine3' would have a larger Y dimension that just 'line1'

What currently happens is all of the labels are the same size and clip-off text that doesn't fit within them, the labels are also inside a recycleview layout because I would like to be able to scroll and update large amount of the labels often.

I have tried a few things but have had no luck, and am struggling to get a variable to be understood where I have added # HERE in the .kv file

from kivy.app import App
from kivy.properties import NumericProperty, Clock, ObjectProperty, StringProperty
from kivy.uix.widget import Widget
from kivy.uix.recycleview import RecycleView
from kivy.uix.button import Button
from kivy.uix.label import Label

class TopPostsTest(RecycleView):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        message_height = NumericProperty(20)
        items = ["hello\ntest\ntest", "test, gghgjhgjhgjhgjhghjghjgjhgjhgjhgjhgjhgjhgjhgjhg", "cheese"]
        self.data = [{'text':str(p)} for p in items]

class LabelColor(Label):
    pass

class TruthApp(App):
#    def build(self):
#        return super().build()
    pass

if __name__ == "__main__":
    TruthApp().run()

<MainControl@PageLayout>:
    border: "25dp"
    swipe_threshold: 0.4
    TopPostsTest:
    Settings:

<LabelColor>:
    color: 0,0,0,1
    text_size: self.size
    halign: 'left'
    valign: 'top'
    font_name: "Assets/Fonts/Nunito-Bold.ttf"
    font_size: "12dp"
    multiline: True

    canvas.before:
        Color:
            rgba: (0.8, 0.8, 0.8, 1)
        RoundedRectangle:
            pos: self.pos
            size: self.size
            radius: [5, 5, 5, 5]
    canvas:
        Color:
            rgba:0,0.9,0.9,1
        Line:
            width:0.8
            rounded_rectangle:(self.x,self.y,self.width,root.height, 5) # HERE

<TopPostsTest>:
    viewclass: 'LabelColor'
    scroll_y: 1
    RecycleBoxLayout:
        id: message_view
        default_size: None, dp(40) # NewHERE
        default_size_hint: 1, None
        size_hint_y: None
        padding: ["10dp", "16dp"]
        spacing: "8dp"
        height: self.minimum_height
        orientation: 'vertical'

Thank you for any help :)

Edit:
I have found that I have been changing the wrong value and that the variable that needs changing has been marker with # NewHERE, however I am still unable to get it to work or get a variable from the py file into the kv


问:
Inject javascript from content script with a chrome extension v3
I'm migration my extension from V2 to V3. Now all is working fine except for one thing. In my V2 version I did

```<code>const actualCode = '(' + function () { 'console.log("demo");' } + `)();`;
const script = document.createElement('script');
script.textContent = actualCode;
(document.head || document.documentElement).appendChild(script);
script.remove();
</code>```

Note that the console.log("demo") is a simplification of what I need to inject :)

I need to inject some javascript for my chrome-extension-magic to take place.

Now, in V3 this doesn't work anymore. I get the following error in my devtools-console

```<code>content.js:23114

   Refused to execute inline script because it violates the following
   ContentSecurity Policy directive: "script-src 'self'". Either the
   'unsafe-inline' keyword, a hash ('sha256-tN52+5...6d2I/Szq8='), or a nonce
   ('nonce-...') is required to enable inline execution.
</code>```

In the migration guide I noticed this section

```<code>"content_security_policy": {
   "extension_pages": "...",
   "sandbox": "..."
}
</code>```

but there is not much description there, so this is magic to me. So I hope someone know can help me with this?

答:
Refer to Access variables and functions defined in page context using a content script

Since content scripts are executed in an "isolated world" environment,
we can't do some special dom operations in content_script js.

This example will show you how to inject inject.js to web page before document start:

```<code>// document_start.js
var s = document.createElement('script');
s.src = chrome.runtime.getURL('inject.js');
s.onload = function() {
    this.remove();
};
(document.head || document.documentElement).appendChild(s);
</code>```

manifest.json example for ManifestV3

```<code>"content_scripts": [
      {
            "matches": ["<all_urls>"],
            "js": ["document_start.js"],
            "run_at": "document_start" //default document end
      }
]
"web_accessible_resources": [{
  "resources": ["inject.js"],
  "matches": ["<all_urls>"]
}]
</code>```

Updated: 2023-03-08

Support es6 module import

If you want es6 module import, just add s.type="module"

```<code>function injectScript(src) {
    const s = document.createElement('script');
    s.src = chrome.runtime.getURL(src);
    s.type = "module"
    s.onload = function() {
        this.remove();
    };
    (document.head || document.documentElement).appendChild(s);
}

injectScript('inject/main.js')
</code>```

Then you could use es6 import  like this:

```<code>// inject/main.js
import { initColor } from './init.js'; //import inject/init.js

initColor()
</code>```

Body:
I'm migration my extension from V2 to V3. Now all is working fine except for one thing. In my V2 version I did

const actualCode = '(' + function () { 'console.log("demo");' } + `)();`;
const script = document.createElement('script');
script.textContent = actualCode;
(document.head || document.documentElement).appendChild(script);
script.remove();

Note that the console.log("demo") is a simplification of what I need to inject :)

I need to inject some javascript for my chrome-extension-magic to take place.

Now, in V3 this doesn't work anymore. I get the following error in my devtools-console

content.js:23114

   Refused to execute inline script because it violates the following
   ContentSecurity Policy directive: "script-src 'self'". Either the
   'unsafe-inline' keyword, a hash ('sha256-tN52+5...6d2I/Szq8='), or a nonce
   ('nonce-...') is required to enable inline execution.

In the migration guide I noticed this section

"content_security_policy": {
   "extension_pages": "...",
   "sandbox": "..."
}

but there is not much description there, so this is magic to me. So I hope someone know can help me with this?

Body:
Refer to Access variables and functions defined in page context using a content script

Since content scripts are executed in an "isolated world" environment,
we can't do some special dom operations in content_script js.

This example will show you how to inject inject.js to web page before document start:

// document_start.js
var s = document.createElement('script');
s.src = chrome.runtime.getURL('inject.js');
s.onload = function() {
    this.remove();
};
(document.head || document.documentElement).appendChild(s);

manifest.json example for ManifestV3

"content_scripts": [
      {
            "matches": ["<all_urls>"],
            "js": ["document_start.js"],
            "run_at": "document_start" //default document end
      }
]
"web_accessible_resources": [{
  "resources": ["inject.js"],
  "matches": ["<all_urls>"]
}]

Updated: 2023-03-08

Support es6 module import

If you want es6 module import, just add s.type="module"

function injectScript(src) {
    const s = document.createElement('script');
    s.src = chrome.runtime.getURL(src);
    s.type = "module"
    s.onload = function() {
        this.remove();
    };
    (document.head || document.documentElement).appendChild(s);
}

injectScript('inject/main.js')

Then you could use es6 import  like this:

// inject/main.js
import { initColor } from './init.js'; //import inject/init.js

initColor()


问:
Number of Channels in category
I'm creating a Join to Create System and want to name the channel with numbers. So if there are alredy two channels in this category, the third one would be named "Channel 3".</p>
```<code>@client.event
async def on_voice_state_update(member, before, after):

channel = after.channel

v_channels = [939457151146012672, 942088196576145418]
v_categories = [939457129625059329, 942087974244483112]

if channel.id in v_channels:
    guild = after.channel.guild
    category = discord.utils.get(guild.categories, id=v_categories[1])
    count = len( #number of channels in category
    channelname = f"Channel [ {count + 1} ]"
</code>```

答:
Use the channels attribute.

@client.event
async def on_voice_state_update(member, before, after):

  channel = after.channel

  v_channels = [
    939457151146012672,
    942088196576145418
  ]
  v_categories = [
    939457129625059329,
    942087974244483112
  ]

  if channel.id in v_channels:
    guild = after.channel.guild
    category = discord.utils.get(
      guild.categories,
      id=v_categories[1]
    )
    count = len(category.channels)
    channelname = f"Channel [ {count + 1} ]"
```

Title: Number of Channels in category

Body:
I'm creating a Join to Create System and want to name the channel with numbers. So if there are alredy two channels in this category, the third one would be named "Channel 3".

@client.event
async def on_voice_state_update(member, before, after):

channel = after.channel

v_channels = [939457151146012672, 942088196576145418]
v_categories = [939457129625059329, 942087974244483112]

if channel.id in v_channels:
    guild = after.channel.guild
    category = discord.utils.get(guild.categories, id=v_categories[1])
    count = len( #number of channels in category
    channelname = f"Channel [ {count + 1} ]"


问:
Spot instances on Amazon ECS
I am currently using on demand instances for my ECS cluster in AWS. I am running ~50 small containers on each instance. Each of them with same reserved CPU and memory.

In order to save costs, I want to switch to using spot instances instead.

Will ECS handle buying of spot instances and keeping my amount of desired server according to my auto scale settings?

What happens when an instance is terminated? Will all the tasks running on the instance be terminated or will they move to another spot instance?

Are spot instances even available for T2/T3?

答: A new Capacity Provider can be created with the desired Spot settings and associated with the existing Cluster</p>

Title: Spot instances on Amazon ECS


问:
Replacing string "true" and "false" from union type to booleans
I've got one union type that is constructed from object keys, which may contain string, number, and boolean keys.

Example:

```<code>type Example = "true" | "semi" | "false";
</code>```

What I want to achieve is to get a new type, which replaces strings true or false with actual boolean values.

```<code>type Example = true | "semi" | false;
</code>```

Converting directly to boolean won't work since there might be cases where I don't have either true or false

This is what I've tried

```<code>type ReplaceTrue<T> = Extract<T, "true"> extends never ? T : Exclude<T, "true"> | true;
type ReplaceFalse<T> = Extract<T, "false"> extends never ? T : Exclude<T, "false"> | false;

type PickMyType<T> = ReplaceBoolean<T, "true", true> | ReplaceBoolean<T, "false", false>
</code>```

I've also tried combining ReplaceTrue and ReplaceFalse to a single type, but I think that this would lead to a more unreadable code.

However, I feel like these solutions are not elegant and I'm wondering if there is any other method of replacing them.

答:
This is achievable by a straightforward distributive conditional type:

```<code>type ReplBool<T> = T extends "true" ? true : T extends "false" ? false : T;

type Example = "true" | "semi" | "false";
type ReplacedExample = ReplBool<Example>;
// type ReplacedExample = boolean | "semi"
// note that boolean is an alias for true | false
</code>```

You can do more complicated things involving mapped lookups or nested utility types, but the above definition is probably the tersest definition for something with just two cases.

Playground link to code

Body:
I've got one union type that is constructed from object keys, which may contain string, number, and boolean keys.

Example:

type Example = "true" | "semi" | "false";

What I want to achieve is to get a new type, which replaces strings true or false with actual boolean values.

type Example = true | "semi" | false;

Converting directly to boolean won't work since there might be cases where I don't have either true or false

This is what I've tried

type ReplaceTrue<T> = Extract<T, "true"> extends never ? T : Exclude<T, "true"> | true;
type ReplaceFalse<T> = Extract<T, "false"> extends never ? T : Exclude<T, "false"> | false;

type PickMyType<T> = ReplaceBoolean<T, "true", true> | ReplaceBoolean<T, "false", false>

I've also tried combining ReplaceTrue and ReplaceFalse to a single type, but I think that this would lead to a more unreadable code.

However, I feel like these solutions are not elegant and I'm wondering if there is any other method of replacing them.

Body:
This is achievable by a straightforward distributive conditional type:

type ReplBool<T> = T extends "true" ? true : T extends "false" ? false : T;

type Example = "true" | "semi" | "false";
type ReplacedExample = ReplBool<Example>;
// type ReplacedExample = boolean | "semi"
// note that boolean is an alias for true | false

You can do more complicated things involving mapped lookups or nested utility types, but the above definition is probably the tersest definition for something with just two cases.

Playground link to code


问:
Convert specific fields before mapping in controller
I need to convert two specific fields before mapping to Dto class.
Data i get from form:

```<code>userName: test
password: 123
active: N
enabled: N
external: N
id: -1
</code>```

Dto class:

```<code>@Getter @Setter
public class UserDto {
    protected Integer id;
    protected String userName;
    protected String password;
    protected boolean active = false;
    protected boolean enabled = true;
    protected String external;
}
</code>```

Fields active and enabled are a boolean type, but from form i get "Y" or "N" string values. Cause of it, i got an error Failed to convert property value of type 'java.lang.String' to required type 'boolean' for property 'active'; nested exception is java.lang.IllegalArgumentException: Invalid boolean value [N]

I've read about the Сonverter<T,V> and PropertyEditors, but I'm not sure if they work for me and how can i apply it only for 2 specific fields.

Controller:

```<code>    @RequestMapping(value = "/user/save",method = RequestMethod.POST)
    public ResponseEntity<String> saveUser(@ModelAttribute UserDto userDto, BindingResult bindingResultM, HttpServletRequest req) {

        List<FieldError> errors = bindingResultM.getFieldErrors();
        for (FieldError error : errors) {
            log.error("bindingResultM: " + error.getObjectName() + " - " + error.getDefaultMessage());
        }
        try {
            userService.saveUserDto(userDto);
            return new ResponseEntity<>("OK", HttpStatus.OK);
        } catch (Exception e){
            throw new ResponseException(e.getMessage(), HttpStatus.METHOD_FAILURE);
        }
    }
</code>```

答:
Because you are saying you need to get data from the form to populate the UserDTO object, which is a process of translate String type to other type.

So, you need to use "org.springframework.core.convert.converter.Converter", "java.beans.PropertyEditor", or "org.springframework.format.Formatter". All of three can do the job of translating String type to other type or other type to String type.

But PropertyEditor is too complicated, so usually we always use Converter or Formatter, and these two can be set in the same method "default void addFormatters(FormatterRegistry registry) {}" of the "WebMvcConfigurer" interface.

But that's for the whole application, you only want the translation happen for "active" and "enabled" fields of UserDTO.

Then you need to use the "org.springframework.web.bind.annotation.InitBinder", which can be defined inside the Controller for specific method parameter. The "userDTO" of the "@InitBinder" means the data binder is only used for the "userDTO" method parameter inside this Controller. (This name is case-sensitive, so if you "userDto" in the method, you need to change it to userDto in the @InitBinder annotation.)
Inside this method, you can specify the Formatter only for "active" and "enabled" fields, by using this method:

```<code>public void addCustomFormatter(Formatter<?> formatter, String... fields){}
</code>```

Of course you can specify the Converter for these two fields, but there is no direct method for it in the "WebDataBinder" class. So, it is eaiser to use the Formatter.

```<code>@InitBinder("userDTO")
public void forUserDto(WebDataBinder binder) {
    binder.addCustomFormatter(new BooleanFormatter(), "active", "enabled");
}
</code>```

Here is the BooleanFormatter class:

```<code>public class BooleanFormatter implements Formatter<Boolean>{

    @Override
    public String print(Boolean object, Locale locale) {
        if (object) {
            return "Y";
        }
        return "N";
    }

    @Override
    public Boolean parse(String text, Locale locale) throws ParseException {
        if (text.equals("Y")) {
            return true;
        }
        return false;
    }
}
</code>```

Body:
I need to convert two specific fields before mapping to Dto class.
Data i get from form:

userName: test
password: 123
active: N
enabled: N
external: N
id: -1

Dto class:

@Getter @Setter
public class UserDto {
    protected Integer id;
    protected String userName;
    protected String password;
    protected boolean active = false;
    protected boolean enabled = true;
    protected String external;
}

Fields active and enabled are a boolean type, but from form i get "Y" or "N" string values. Cause of it, i got an error Failed to convert property value of type 'java.lang.String' to required type 'boolean' for property 'active'; nested exception is java.lang.IllegalArgumentException: Invalid boolean value [N]

I've read about the Сonverter<T,V> and PropertyEditors, but I'm not sure if they work for me and how can i apply it only for 2 specific fields.

Controller:

    @RequestMapping(value = "/user/save",method = RequestMethod.POST)
    public ResponseEntity<String> saveUser(@ModelAttribute UserDto userDto, BindingResult bindingResultM, HttpServletRequest req) {

        List<FieldError> errors = bindingResultM.getFieldErrors();
        for (FieldError error : errors) {
            log.error("bindingResultM: " + error.getObjectName() + " - " + error.getDefaultMessage());
        }
        try {
            userService.saveUserDto(userDto);
            return new ResponseEntity<>("OK", HttpStatus.OK);
        } catch (Exception e){
            throw new ResponseException(e.getMessage(), HttpStatus.METHOD_FAILURE);
        }
    }

Body:
Because you are saying you need to get data from the form to populate the UserDTO object, which is a process of translate String type to other type.

So, you need to use "org.springframework.core.convert.converter.Converter", "java.beans.PropertyEditor", or "org.springframework.format.Formatter". All of three can do the job of translating String type to other type or other type to String type.

But PropertyEditor is too complicated, so usually we always use Converter or Formatter, and these two can be set in the same method "default void addFormatters(FormatterRegistry registry) {}" of the "WebMvcConfigurer" interface.

But that's for the whole application, you only want the translation happen for "active" and "enabled" fields of UserDTO.

Then you need to use the "org.springframework.web.bind.annotation.InitBinder", which can be defined inside the Controller for specific method parameter. The "userDTO" of the "@InitBinder" means the data binder is only used for the "userDTO" method parameter inside this Controller. (This name is case-sensitive, so if you "userDto" in the method, you need to change it to userDto in the @InitBinder annotation.)
Inside this method, you can specify the Formatter only for "active" and "enabled" fields, by using this method:

public void addCustomFormatter(Formatter<?> formatter, String... fields){}

Of course you can specify the Converter for these two fields, but there is no direct method for it in the "WebDataBinder" class. So, it is eaiser to use the Formatter.

@InitBinder("userDTO")
public void forUserDto(WebDataBinder binder) {
    binder.addCustomFormatter(new BooleanFormatter(), "active", "enabled");
}

Here is the BooleanFormatter class:

public class BooleanFormatter implements Formatter<Boolean>{

    @Override
    public String print(Boolean object, Locale locale) {
        if (object) {
            return "Y";
        }
        return "N";
    }

    @Override
    public Boolean parse(String text, Locale locale) throws ParseException {
        if (text.equals("Y")) {
            return true;
        }
        return false;
    }
}


问:
I'm trying to write a program that reverses an array and it keeps saying I can not convert int * to int. How do I fix that?
```<code>int* reverse_Array(int size, int* arr)
{
    int* areverse[10];

    int s = 0;

    for (int c = 10; c > 0; c--)

        arr[c] = areverse[s]; // the issue happens here with the =

    return areverse[s];
}
</code>```

The issue happens with the = between arr[c] and areverse[s]

I tried a couple fixes but each one doesn't really fix it.

I am writing code that should reverse a array
"(using a function by returning a pointer/array)"

答:
@MattaGodus when we are starting error occurs.I have mentioned out the problems and the and way to fix them.

Problems in the code:

int* areverse[10];

should be :

```<code>int * areverse = new int[size];//what ever the size it
</code>```

Problem with this line int* areverse[10] is when the function returns stack area is cleared.

Using the new keyword we are creating variable inside of heap now even our function returns this area remains.

arr[c] = areverse[s];

we should be assigning areverse from arr

return areverse[s];

It should be:

```<code>return areverse;
</code>```

Code with bug fixed:

```<code>#include <iostream>
using namespace std;

int *reverse_Array(int , int*);

////////Reverses an array of integer//////////
int* reverse_Array(int size, int* arr){

    int * areverse = new int[size];//use new keyword to allocated new memory inside method
    for (int c = size -1 ; c >= 0; c--)
        areverse[size-1 -c] = arr[c]; // the issue happens here with the =

    return areverse;
}

////////Main////////
int main(){
    int arr[] = {1, 2, 3, 4};
    int size = sizeof(arr) / sizeof(int);
    int * rarr = reverse_Array(size, arr);
    for (int i = 0;i<size; i++)
        cout<<rarr[i]<<" ";
    cout<<endl;
    return 0;
}
</code>```

output:

```<code>$ g++ main.cpp && ./a.out
4 3 2 1
</code>```

Body:
int* reverse_Array(int size, int* arr)
{
    int* areverse[10];

    int s = 0;

    for (int c = 10; c > 0; c--)

        arr[c] = areverse[s]; // the issue happens here with the =

    return areverse[s];
}

The issue happens with the = between arr[c] and areverse[s]

I tried a couple fixes but each one doesn't really fix it.

I am writing code that should reverse a array
"(using a function by returning a pointer/array)"

Body:
@MattaGodus when we are starting error occurs.I have mentioned out the problems and the and way to fix them.

Problems in the code:

int* areverse[10];

should be :

int * areverse = new int[size];//what ever the size it

Problem with this line int* areverse[10] is when the function returns stack area is cleared.

Using the new keyword we are creating variable inside of heap now even our function returns this area remains.

arr[c] = areverse[s];

we should be assigning areverse from arr

return areverse[s];

It should be:

return areverse;

Code with bug fixed:

#include <iostream>
using namespace std;

int *reverse_Array(int , int*);

////////Reverses an array of integer//////////
int* reverse_Array(int size, int* arr){

    int * areverse = new int[size];//use new keyword to allocated new memory inside method
    for (int c = size -1 ; c >= 0; c--)
        areverse[size-1 -c] = arr[c]; // the issue happens here with the =

    return areverse;
}

////////Main////////
int main(){
    int arr[] = {1, 2, 3, 4};
    int size = sizeof(arr) / sizeof(int);
    int * rarr = reverse_Array(size, arr);
    for (int i = 0;i<size; i++)
        cout<<rarr[i]<<" ";
    cout<<endl;
    return 0;
}

output:

$ g++ main.cpp && ./a.out
4 3 2 1


问:
How to pass arguments from command line to Gradle
I'm trying to pass an argument from command line to a Java class.  I followed this post: http://gradle.1045684.n5.nabble.com/Gradle-application-plugin-question-td5539555.html but the code does not work for me (perhaps it is not meant for JavaExec?).  Here is what I tried:

task listTests(type:JavaExec){
    main = "util.TestGroupScanner"
    classpath = sourceSets.util.runtimeClasspath
    // this works...
    args 'demo'
    /*
    // this does not work!
    if (project.hasProperty("group")){
        args group
    }
    */
}
```
<p>The output from the above hard coded args value is:</p>
```C:\ws\svn\sqe\sandbox\selenium2forbg\testgradle>g listTests
:compileUtilJava UP-TO-DATE
:processUtilResources UP-TO-DATE
:utilClasses UP-TO-DATE
:listTests
Received argument: demo

BUILD SUCCESSFUL

Total time: 13.422 secs
```
<p>However, once I change the code to use the hasProperty section and pass "demo" as an argument on the command line, I get a NullPointerException:</p>
```C:\ws\svn\sqe\sandbox\selenium2forbg\testgradle>g listTests -Pgroup=demo -s

FAILURE: Build failed with an exception.

* Where:
Build file 'C:\ws\svn\sqe\sandbox\selenium2forbg\testgradle\build.gradle' line:25

* What went wrong:
A problem occurred evaluating root project 'testgradle'.
> java.lang.NullPointerException (no error message)

* Try:
Run with --info or --debug option to get more log output.

* Exception is:
org.gradle.api.GradleScriptException: A problem occurred evaluating root project
 'testgradle'.
    at org.gradle.groovy.scripts.internal.DefaultScriptRunnerFactory$ScriptRunnerImpl.run(DefaultScriptRunnerFactory.java:54)
    at org.gradle.configuration.DefaultScriptPluginFactory$ScriptPluginImpl.apply(DefaultScriptPluginFactory.java:127)
    at org.gradle.configuration.BuildScriptProcessor.evaluate(BuildScriptProcessor.java:38)
```
<p>There is a simple test project available at http://gradle.1045684.n5.nabble.com/file/n5709919/testgradle.zip that illustrates the problem.</p>
<p>This is using Gradle 1.0-rc-3.  The NullPointer is from this line of code:</p>
<pre class="lang-groovy prettyprint-override"><code>  args group
</code>```

I added the following assignment before the task definition, but it didn't change the outcome:

  group = hasProperty('group') ? group : 'nosuchgroup'
```

Any pointers on how to pass command line arguments to Gradle appreciated.

答:
Here is a solution for Kotlin DSL (build.gradle.kts).

I first try to get the variable as a property and if it was null try to get it from OS environment variables (can be useful in CIs like GitHub Actions).

tasks.create("MyCustomTask") {
    val songName = properties["songName"]
        ?: System.getenv("SONG_NAME")
        ?: error("""Property "songName" or environment variable "SONG_NAME" not found""")

    // OR getting the property with 'by'. Did not work for me!
    // For this approach, name of the variable should be the same as the property name
    // val songName: String? by properties

    println("The song name: $songName")
}
```
<p>We can then pass a value for the property from command line:</p>
<pre class="lang-sh prettyprint-override"><code>./gradlew MyCustomTask -PsongName="Black Forest"
</code>```

Or create a file named local.properties at the root of the project and set the property:

```<code>songName=Black Forest
</code>```

We can also add an env variable named SONG_NAME with our desired value and then run the task:

./gradlew MyCustomTask
```

Body:
I'm trying to pass an argument from command line to a Java class.  I followed this post: http://gradle.1045684.n5.nabble.com/Gradle-application-plugin-question-td5539555.html but the code does not work for me (perhaps it is not meant for JavaExec?).  Here is what I tried:

task listTests(type:JavaExec){
    main = "util.TestGroupScanner"
    classpath = sourceSets.util.runtimeClasspath
    // this works...
    args 'demo'
    /*
    // this does not work!
    if (project.hasProperty("group")){
        args group
    }
    */
}

The output from the above hard coded args value is:

C:\ws\svn\sqe\sandbox\selenium2forbg\testgradle>g listTests
:compileUtilJava UP-TO-DATE
:processUtilResources UP-TO-DATE
:utilClasses UP-TO-DATE
:listTests
Received argument: demo

BUILD SUCCESSFUL

Total time: 13.422 secs

However, once I change the code to use the hasProperty section and pass "demo" as an argument on the command line, I get a NullPointerException:

C:\ws\svn\sqe\sandbox\selenium2forbg\testgradle>g listTests -Pgroup=demo -s

FAILURE: Build failed with an exception.

* Where:
Build file 'C:\ws\svn\sqe\sandbox\selenium2forbg\testgradle\build.gradle' line:25

* What went wrong:
A problem occurred evaluating root project 'testgradle'.
> java.lang.NullPointerException (no error message)

* Try:
Run with --info or --debug option to get more log output.

* Exception is:
org.gradle.api.GradleScriptException: A problem occurred evaluating root project
 'testgradle'.
    at org.gradle.groovy.scripts.internal.DefaultScriptRunnerFactory$ScriptRunnerImpl.run(DefaultScriptRunnerFactory.java:54)
    at org.gradle.configuration.DefaultScriptPluginFactory$ScriptPluginImpl.apply(DefaultScriptPluginFactory.java:127)
    at org.gradle.configuration.BuildScriptProcessor.evaluate(BuildScriptProcessor.java:38)

There is a simple test project available at http://gradle.1045684.n5.nabble.com/file/n5709919/testgradle.zip that illustrates the problem.

This is using Gradle 1.0-rc-3.  The NullPointer is from this line of code:

  args group

I added the following assignment before the task definition, but it didn't change the outcome:

  group = hasProperty('group') ? group : 'nosuchgroup'

Any pointers on how to pass command line arguments to Gradle appreciated.

Body:
Here is a solution for Kotlin DSL (build.gradle.kts).

I first try to get the variable as a property and if it was null try to get it from OS environment variables (can be useful in CIs like GitHub Actions).

tasks.create("MyCustomTask") {
    val songName = properties["songName"]
        ?: System.getenv("SONG_NAME")
        ?: error("""Property "songName" or environment variable "SONG_NAME" not found""")

    // OR getting the property with 'by'. Did not work for me!
    // For this approach, name of the variable should be the same as the property name
    // val songName: String? by properties

    println("The song name: $songName")
}

We can then pass a value for the property from command line:

./gradlew MyCustomTask -PsongName="Black Forest"

Or create a file named local.properties at the root of the project and set the property:

songName=Black Forest

We can also add an env variable named SONG_NAME with our desired value and then run the task:

./gradlew MyCustomTask