问:
Maven plugins are not downloading or resolving when I create a new project
I am very new to maven was about to start learning spring with maven but when I created my first project with maven in eclipse this error occurred and I think maven plugins are not getting downloaded. I have tried several solutions from stackoverflow but nothing worked.

Console Window is like :-

```<code>[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  0.097 s
[INFO] Finished at: 2020-06-01T21:17:39-07:00
[INFO] ------------------------------------------------------------------------
[ERROR] No goals have been specified for this build. You must specify a valid lifecycle phase or a goal in the format <plugin-prefix>:<goal> or <plugin-group-id>:<plugin-artifact-id>[:<plugin-version>]:<goal>. Available lifecycle phases are: validate, initialize, generate-sources, process-sources, generate-resources, process-resources, compile, process-classes, generate-test-sources, process-test-sources, generate-test-resources, process-test-resources, test-compile, process-test-classes, test, prepare-package, package, pre-integration-test, integration-test, post-integration-test, verify, install, deploy, pre-clean, clean, post-clean, pre-site, site, post-site, site-deploy. -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/NoGoalSpecifiedException
</code>```

Error window is like this:-

Please see this screenshot for exact information of errors.

Screenshot attached

POM.xml file

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.anuragr07</groupId>
  <artifactId>springpractice</artifactId>
  <version>0.0.1-SNAPSHOT</version>
</project>
</code>```

Solutions tried so far:-

Installing maven using help > install a new software option

Tried mvn install using cmd

Tried uncommenting proxy tag in setting.xml file

Tried 'https' instead of 'http' in proxy tag in settings.xml file

Tried reinstalling eclipse

and maybe more..

After mvn package

```<code>E:\Workspace\springpractice>mvn package
[INFO] Scanning for projects...
[INFO]
[INFO] --------------------< com.anuragr07:springpractice >--------------------
[INFO] Building springpractice 0.0.1-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
Downloading from central: https://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-resources-plugin/2.6/maven-resources-plugin-2.6.pom

**Downloaded all the plugins**

[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  20.831 s
[INFO] Finished at: 2020-06-01T23:52:35-07:00
[INFO] ------------------------------------------------------------------------

</code>```

I am really frustrated and searching for solutions from past 24 hours. Please help me resolve this.

Thanks!

答:
There was an issue with the settings.xml file and the solution is:-

Close the eclipse first - try to work in CMD and configure maven there. Remove setting.xml in your user directory if the file exists there.

Download Maven from official site.

Add the path to %MVN_HOME%\bin to the Path env. variable in windows.

open CMD and cd to the folder where you have a pom.xml.

Type: mvn package. 6. Post the output.

Thanks to @MarkBramnik

Body:
I am very new to maven was about to start learning spring with maven but when I created my first project with maven in eclipse this error occurred and I think maven plugins are not getting downloaded. I have tried several solutions from stackoverflow but nothing worked.

Console Window is like :-

[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  0.097 s
[INFO] Finished at: 2020-06-01T21:17:39-07:00
[INFO] ------------------------------------------------------------------------
[ERROR] No goals have been specified for this build. You must specify a valid lifecycle phase or a goal in the format <plugin-prefix>:<goal> or <plugin-group-id>:<plugin-artifact-id>[:<plugin-version>]:<goal>. Available lifecycle phases are: validate, initialize, generate-sources, process-sources, generate-resources, process-resources, compile, process-classes, generate-test-sources, process-test-sources, generate-test-resources, process-test-resources, test-compile, process-test-classes, test, prepare-package, package, pre-integration-test, integration-test, post-integration-test, verify, install, deploy, pre-clean, clean, post-clean, pre-site, site, post-site, site-deploy. -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/NoGoalSpecifiedException

Error window is like this:-

Please see this screenshot for exact information of errors.

Screenshot attached

POM.xml file

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.anuragr07</groupId>
  <artifactId>springpractice</artifactId>
  <version>0.0.1-SNAPSHOT</version>
</project>

Solutions tried so far:-

Installing maven using help > install a new software option

Tried mvn install using cmd

Tried uncommenting proxy tag in setting.xml file

Tried 'https' instead of 'http' in proxy tag in settings.xml file

Tried reinstalling eclipse

and maybe more..

After mvn package

E:\Workspace\springpractice>mvn package
[INFO] Scanning for projects...
[INFO]
[INFO] --------------------< com.anuragr07:springpractice >--------------------
[INFO] Building springpractice 0.0.1-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
Downloading from central: https://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-resources-plugin/2.6/maven-resources-plugin-2.6.pom

**Downloaded all the plugins**

[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  20.831 s
[INFO] Finished at: 2020-06-01T23:52:35-07:00
[INFO] ------------------------------------------------------------------------

I am really frustrated and searching for solutions from past 24 hours. Please help me resolve this.

Thanks!


来源: stackexchange

问:
Installing pySpark gives this error : ERROR: Command errored out with exit status 1
I am using Anaconda's Spyder Python 3.7 on Windows 10

I have Java

```<code>C:\Users\GX>java -version
java version "1.8.0_251"
Java(TM) SE Runtime Environment (build 1.8.0_251-b08)
Java HotSpot(TM) 64-Bit Server VM (build 25.251-b08, mixed mode)
</code>```

When I try to install pySpark on Anaconda

I get this error

```<code>pip install pyspark
Collecting pyspark
  Using cached pyspark-2.4.5.tar.gz (217.8 MB)
Note: you may need to restart the kernel to use updated packages.
    ERROR: Command errored out with exit status 1:
     command: 'C:\Users\GX\anaconda3\pythonw.exe' -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\GX\\AppData\\Local\\Temp\\pip-install-qtv58ism\\pyspark\\setup.py'"'"'; __file__='"'"'C:\\Users\\GX\\AppData\\Local\\Temp\\pip-install-qtv58ism\\pyspark\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base 'C:\Users\GX\AppData\Local\Temp\pip-install-qtv58ism\pyspark\pip-egg-info'
         cwd: C:\Users\GX\AppData\Local\Temp\pip-install-qtv58ism\pyspark\
    Complete output (31 lines):
    Could not import pypandoc - required to package PySpark
    Traceback (most recent call last):
      File "C:\Users\GX\anaconda3\lib\site-packages\setuptools\installer.py", line 128, in fetch_build_egg
        subprocess.check_call(cmd)
      File "C:\Users\GX\anaconda3\lib\subprocess.py", line 363, in check_call
        raise CalledProcessError(retcode, cmd)
    subprocess.CalledProcessError: Command '['C:\\Users\\GX\\anaconda3\\pythonw.exe', '-m', 'pip', '--disable-pip-version-check', 'wheel', '--no-deps', '-w', 'C:\\Users\\GX\\AppData\\Local\\Temp\\tmppc02y1qc', '--quiet', 'pypandoc']' returned non-zero exit status 2.

    During handling of the above exception, another exception occurred:

    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "C:\Users\GX\AppData\Local\Temp\pip-install-qtv58ism\pyspark\setup.py", line 224, in <module>
        'Programming Language :: Python :: Implementation :: PyPy']
      File "C:\Users\GX\anaconda3\lib\site-packages\setuptools\__init__.py", line 143, in setup
        _install_setup_requires(attrs)
      File "C:\Users\GX\anaconda3\lib\site-packages\setuptools\__init__.py", line 138, in _install_setup_requires
        dist.fetch_build_eggs(dist.setup_requires)
      File "C:\Users\GX\anaconda3\lib\site-packages\setuptools\dist.py", line 721, in fetch_build_eggs
        replace_conflicting=True,
      File "C:\Users\GX\anaconda3\lib\site-packages\pkg_resources\__init__.py", line 783, in resolve
        replace_conflicting=replace_conflicting
      File "C:\Users\GX\anaconda3\lib\site-packages\pkg_resources\__init__.py", line 1066, in best_match
        return self.obtain(req, installer)
      File "C:\Users\GX\anaconda3\lib\site-packages\pkg_resources\__init__.py", line 1078, in obtain
        return installer(requirement)
      File "C:\Users\GX\anaconda3\lib\site-packages\setuptools\dist.py", line 777, in fetch_build_egg
        return fetch_build_egg(self, req)
      File "C:\Users\GX\anaconda3\lib\site-packages\setuptools\installer.py", line 130, in fetch_build_egg
        raise DistutilsError(str(e))
    distutils.errors.DistutilsError: Command '['C:\\Users\\GX\\anaconda3\\pythonw.exe', '-m', 'pip', '--disable-pip-version-check', 'wheel', '--no-deps', '-w', 'C:\\Users\\GX\\AppData\\Local\\Temp\\tmppc02y1qc', '--quiet', 'pypandoc']' returned non-zero exit status 2.
    ----------------------------------------
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.

runfile('C:/Users/GX/OneDrive/__PhD/POC/Pred04d.py', wdir='C:/Users/GX/OneDrive/__PhD/POC')
</code>```

I tried using pip3 but that did not work.

Any idea how to fix that?

答:
I found the solution

I used

```<code>conda install pyspark
</code>```

that works

ContentLicense: CC BY-SA 4.0

Body:
I am using Anaconda's Spyder Python 3.7 on Windows 10

I have Java

C:\Users\GX>java -version
java version "1.8.0_251"
Java(TM) SE Runtime Environment (build 1.8.0_251-b08)
Java HotSpot(TM) 64-Bit Server VM (build 25.251-b08, mixed mode)

When I try to install pySpark on Anaconda

I get this error

pip install pyspark
Collecting pyspark
  Using cached pyspark-2.4.5.tar.gz (217.8 MB)
Note: you may need to restart the kernel to use updated packages.
    ERROR: Command errored out with exit status 1:
     command: 'C:\Users\GX\anaconda3\pythonw.exe' -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\GX\\AppData\\Local\\Temp\\pip-install-qtv58ism\\pyspark\\setup.py'"'"'; __file__='"'"'C:\\Users\\GX\\AppData\\Local\\Temp\\pip-install-qtv58ism\\pyspark\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base 'C:\Users\GX\AppData\Local\Temp\pip-install-qtv58ism\pyspark\pip-egg-info'
         cwd: C:\Users\GX\AppData\Local\Temp\pip-install-qtv58ism\pyspark\
    Complete output (31 lines):
    Could not import pypandoc - required to package PySpark
    Traceback (most recent call last):
      File "C:\Users\GX\anaconda3\lib\site-packages\setuptools\installer.py", line 128, in fetch_build_egg
        subprocess.check_call(cmd)
      File "C:\Users\GX\anaconda3\lib\subprocess.py", line 363, in check_call
        raise CalledProcessError(retcode, cmd)
    subprocess.CalledProcessError: Command '['C:\\Users\\GX\\anaconda3\\pythonw.exe', '-m', 'pip', '--disable-pip-version-check', 'wheel', '--no-deps', '-w', 'C:\\Users\\GX\\AppData\\Local\\Temp\\tmppc02y1qc', '--quiet', 'pypandoc']' returned non-zero exit status 2.

    During handling of the above exception, another exception occurred:

    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "C:\Users\GX\AppData\Local\Temp\pip-install-qtv58ism\pyspark\setup.py", line 224, in <module>
        'Programming Language :: Python :: Implementation :: PyPy']
      File "C:\Users\GX\anaconda3\lib\site-packages\setuptools\__init__.py", line 143, in setup
        _install_setup_requires(attrs)
      File "C:\Users\GX\anaconda3\lib\site-packages\setuptools\__init__.py", line 138, in _install_setup_requires
        dist.fetch_build_eggs(dist.setup_requires)
      File "C:\Users\GX\anaconda3\lib\site-packages\setuptools\dist.py", line 721, in fetch_build_eggs
        replace_conflicting=True,
      File "C:\Users\GX\anaconda3\lib\site-packages\pkg_resources\__init__.py", line 783, in resolve
        replace_conflicting=replace_conflicting
      File "C:\Users\GX\anaconda3\lib\site-packages\pkg_resources\__init__.py", line 1066, in best_match
        return self.obtain(req, installer)
      File "C:\Users\GX\anaconda3\lib\site-packages\pkg_resources\__init__.py", line 1078, in obtain
        return installer(requirement)
      File "C:\Users\GX\anaconda3\lib\site-packages\setuptools\dist.py", line 777, in fetch_build_egg
        return fetch_build_egg(self, req)
      File "C:\Users\GX\anaconda3\lib\site-packages\setuptools\installer.py", line 130, in fetch_build_egg
        raise DistutilsError(str(e))
    distutils.errors.DistutilsError: Command '['C:\\Users\\GX\\anaconda3\\pythonw.exe', '-m', 'pip', '--disable-pip-version-check', 'wheel', '--no-deps', '-w', 'C:\\Users\\GX\\AppData\\Local\\Temp\\tmppc02y1qc', '--quiet', 'pypandoc']' returned non-zero exit status 2.
    ----------------------------------------
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.

runfile('C:/Users/GX/OneDrive/__PhD/POC/Pred04d.py', wdir='C:/Users/GX/OneDrive/__PhD/POC')

I tried using pip3 but that did not work.

Any idea how to fix that?

Body:
I found the solution

I used

conda install pyspark

that works


问:
Create new file from templates with bash script
I have to create conf files and init.d which are very similar. These files permit to deploy new HTTP service on my servers. These files are the same and only some parameters change from one file to another (listen_port, domain, and path on server.)

As any error in these files leads to dysfunction of service I would like to create these files using a bash script.

For example:

```<code>generate_new_http_service.sh 8282 subdomain.domain.example /home/myapp/rootOfHTTPService
</code>```

I am looking for a kind of templating module that I could use with bash. This templating module would use some generic conf and init.d scripts to create new ones.

Could I could use python templating engine?

答:
Template module for bash? Use sed, Luke! Here is an example of one of millions of possible ways of doing this:

```<code>$ cat template.txt
#!/bin/sh

echo Hello, I am a server running from %DIR% and listening for connection at %HOST% on port %PORT% and my configuration file is %DIR%/server.conf

$ cat create.sh
#!/bin/sh

sed -e "s;%PORT%;$1;g" -e "s;%HOST%;$2;g" -e "s;%DIR%;$3;g" template.txt > script.sh

$ bash ./create.sh 1986 example.com /tmp
$ bash ./script.sh
Hello, I am a server running from /tmp and listening for connection at example.com on port 1986 and my configuration file is /tmp/server.conf
$
</code>```

Body:
I have to create conf files and init.d which are very similar. These files permit to deploy new HTTP service on my servers. These files are the same and only some parameters change from one file to another (listen_port, domain, and path on server.)

As any error in these files leads to dysfunction of service I would like to create these files using a bash script.

For example:

generate_new_http_service.sh 8282 subdomain.domain.example /home/myapp/rootOfHTTPService

I am looking for a kind of templating module that I could use with bash. This templating module would use some generic conf and init.d scripts to create new ones.

Could I could use python templating engine?

Body:
Template module for bash? Use sed, Luke! Here is an example of one of millions of possible ways of doing this:

$ cat template.txt
#!/bin/sh

echo Hello, I am a server running from %DIR% and listening for connection at %HOST% on port %PORT% and my configuration file is %DIR%/server.conf

$ cat create.sh
#!/bin/sh

sed -e "s;%PORT%;$1;g" -e "s;%HOST%;$2;g" -e "s;%DIR%;$3;g" template.txt > script.sh

$ bash ./create.sh 1986 example.com /tmp
$ bash ./script.sh
Hello, I am a server running from /tmp and listening for connection at example.com on port 1986 and my configuration file is /tmp/server.conf
$

ContentLicense: CC BY-SA 3.0


问:
T-SQL Lead () function issue while using GROUP BY clause
I am trying to insert data from several tables into the one resulting table.

But, since I am using the Lead() function in SELECT / GROUP BY - for creating one of the fields, I am having an error:

Windowed functions can only appear in the SELECT or ORDER BY clause

How should I modify my code so it would work?

```<code>      USE [WH];
      INSERT INTO [exp].[Profile] (

                   [MedicalConditionFK]
                 , [EHRProgramFK]
                 , [EffectiveDate]
                 , [ExpirationDate]

               )

       SELECT
              c.medicalcondition_id
            , Max(ISNULL(epi.[EHRProgramFK], -1)) AS [EHRProgramFK]
            , p.[effective_date] AS [EffectiveDate]
            , DateAdd(day, -1, lead (p.[effective_date], 1, '2050-12-31') OVER
                      (partition by p.[client_id], c.[medicalcondition_id] Order By
                                                   p.[effective_date])) AS [ExpirationDate]

      FROM
            [exp].[Condition] c
            INNER JOIN [exp].[Medical] p ON
                                         c.[ClientMedicalProfile_id] = p.[ClientMedicalProfile_id]
            LEFT JOIN [exp].[Episode] epi ON
                                         (p.[effective_date] BETWEEN epi.[AdmissionDate]
                                          AND epi.[DischargeDate] and epi.[DBCode] = 'CS-SM')

      WHERE
            (p.[effective_date] IS NOT NULL)

      GROUP BY
              c.medicalcondition_id
            , p.[effective_date]
            , DateAdd(day, -1, lead (p.[effective_date], 1, '2050-12-31') OVER
                  (partition by p.[client_id], c.[medicalcondition_id] Order By p.[effective_date]))
</code>```

答:
To make your query valid, you need to put the columns that are used in the window function in the group by clause (not the window function itself).

Basically it means that you have to add column client_id:

```<code>GROUP BY
    c.medicalcondition_id,
    p.[effective_date],
    p.[client_id]
</code>```

While this will avoid the syntax error, I cannot tell if this will produce the resultset that you want. For this, you would probably need to ask a new question, providing proper sample data and desired results.

Body:
I am trying to insert data from several tables into the one resulting table.

But, since I am using the Lead() function in SELECT / GROUP BY - for creating one of the fields, I am having an error:

Windowed functions can only appear in the SELECT or ORDER BY clause

How should I modify my code so it would work?

      USE [WH];
      INSERT INTO [exp].[Profile] (

                   [MedicalConditionFK]
                 , [EHRProgramFK]
                 , [EffectiveDate]
                 , [ExpirationDate]

               )

       SELECT
              c.medicalcondition_id
            , Max(ISNULL(epi.[EHRProgramFK], -1)) AS [EHRProgramFK]
            , p.[effective_date] AS [EffectiveDate]
            , DateAdd(day, -1, lead (p.[effective_date], 1, '2050-12-31') OVER
                      (partition by p.[client_id], c.[medicalcondition_id] Order By
                                                   p.[effective_date])) AS [ExpirationDate]

      FROM
            [exp].[Condition] c
            INNER JOIN [exp].[Medical] p ON
                                         c.[ClientMedicalProfile_id] = p.[ClientMedicalProfile_id]
            LEFT JOIN [exp].[Episode] epi ON
                                         (p.[effective_date] BETWEEN epi.[AdmissionDate]
                                          AND epi.[DischargeDate] and epi.[DBCode] = 'CS-SM')

      WHERE
            (p.[effective_date] IS NOT NULL)

      GROUP BY
              c.medicalcondition_id
            , p.[effective_date]
            , DateAdd(day, -1, lead (p.[effective_date], 1, '2050-12-31') OVER
                  (partition by p.[client_id], c.[medicalcondition_id] Order By p.[effective_date]))

Body:
To make your query valid, you need to put the columns that are used in the window function in the group by clause (not the window function itself).

Basically it means that you have to add column client_id:

GROUP BY
    c.medicalcondition_id,
    p.[effective_date],
    p.[client_id]

While this will avoid the syntax error, I cannot tell if this will produce the resultset that you want. For this, you would probably need to ask a new question, providing proper sample data and desired results.


问:
Writing a function for getting data from a URL
I'm trying to write the following function for getting Facebook data from a URL and then converting to a dataframe.

```<code>read_URL <- function(df_name,start_date,end_date,token){
  URL <-  fromJSON(paste0("https://graph.facebook.com/v5.0/me?fields=posts.limit(30).until"start_date".since"end_date"&access_token=",token,""))
  df_name <- URL$posts$data
}
</code>```

Unfortunately my function does not work, and i'm not sure why.
Obviously the URL works before trying to convert into the function.
This is the error that i'm getting:

```<code>Error: unexpected symbol in:
"read_URL <- function(df_name,start_date,end_date,token){
  URL <-  fromJSON(paste0("https://graph.facebook.com/v5.0/me?fields=posts.limit(30).until"start_date"
>   df_name <- URL$posts$data
Error: object 'URL' not found
> }
</code>```

Any help will be greatly appreciated
    Error: unexpected '}' in "}"

答:
I think you are trying to construct the URL using paste. Try :

```<code>library(jsonlite)

read_URL <- function(df_name,start_date,end_date,token){
   URL <-  fromJSON(paste0('https://graph.facebook.com/v5.0/me?fields=posts.limit(30).until', start_date, ".since", end_date, "&access_token=",token))
   df_name <- URL$posts$data
   return(df_name)
}
</code>```

You can also look into glue package which makes constructing of URL with parameters simple.

```<code>read_URL <- function(df_name,start_date,end_date,token){
    URL <-  fromJSON(glue::glue('https://graph.facebook.com/v5.0/me?fields=posts.limit(30).until{start_date}.since{end_date}&access_token={token}'))
    df_name <- URL$posts$data
    return(df_name)
}
</code>```

Body:
I'm trying to write the following function for getting Facebook data from a URL and then converting to a dataframe.

read_URL <- function(df_name,start_date,end_date,token){
  URL <-  fromJSON(paste0("https://graph.facebook.com/v5.0/me?fields=posts.limit(30).until"start_date".since"end_date"&access_token=",token,""))
  df_name <- URL$posts$data
}

Unfortunately my function does not work, and i'm not sure why.
Obviously the URL works before trying to convert into the function.
This is the error that i'm getting:

Error: unexpected symbol in:
"read_URL <- function(df_name,start_date,end_date,token){
  URL <-  fromJSON(paste0("https://graph.facebook.com/v5.0/me?fields=posts.limit(30).until"start_date"
>   df_name <- URL$posts$data
Error: object 'URL' not found
> }

Any help will be greatly appreciated
    Error: unexpected '}' in "}"

Body:
I think you are trying to construct the URL using paste. Try :

library(jsonlite)

read_URL <- function(df_name,start_date,end_date,token){
   URL <-  fromJSON(paste0('https://graph.facebook.com/v5.0/me?fields=posts.limit(30).until', start_date, ".since", end_date, "&access_token=",token))
   df_name <- URL$posts$data
   return(df_name)
}

You can also look into glue package which makes constructing of URL with parameters simple.

read_URL <- function(df_name,start_date,end_date,token){
    URL <-  fromJSON(glue::glue('https://graph.facebook.com/v5.0/me?fields=posts.limit(30).until{start_date}.since{end_date}&access_token={token}'))
    df_name <- URL$posts$data
    return(df_name)
}


问:
Regex capture all matches in word
For example, I have this string:

```<code>222
</code>```

What pattern I should use to get a count of "22" matches exactly 2 times?

```<code>222 -> (22)2 and 2(22)
</code>```

So, for 2222 I would have 3 matches:

```<code>2222 -> (22)22 and 2(22)2 and 22(22)
</code>```

答:
You can use Positive Lookahead:

```<code>2(?=2)
</code>```

Example: https://regex101.com/r/gGLv4k/1

Title: Regex capture all matches in word

Body:
For example, I have this string:

222

What pattern I should use to get a count of "22" matches exactly 2 times?

222 -> (22)2 and 2(22)

So, for 2222 I would have 3 matches:

2222 -> (22)22 and 2(22)2 and 22(22)

Body:
You can use Positive Lookahead:

2(?=2)

Example: https://regex101.com/r/gGLv4k/1


问:
Hide scroll bar for search filter and show only for mat-option in Angular
I want to hide the scroll bar for mat-select-filter and show only for mat-option in Angular .

In AppComponent.html

```<code><mat-form-field class="input-permissions">
    <mat-select
      placeholder="Permissions"
      multiple
      [formControl]="permissionsControl"
      disableOptionCentering
    >
      <mat-select-filter
        [placeholder]="'Search Permissions'"
        [array]="permissions"
        (filteredReturn)="filteredList = $event"
        [displayMember]="'appPermissions'"
        [showSpinner]="false"
      >
      </mat-select-filter>
      <mat-option
        *ngFor="let permission of permissions"
        [value]="permission.value"
      >
        {{ permission.value}}
      </mat-option>
    </mat-select>
  </mat-form-field>
</code>```

Now it is showing like this,

I want to show the scroll bar like this,

Any help would be appreciated.

答:
I was able to solve this by using virtual scroll inside mat-select for mat-option in Angular.
https://material.angular.io/cdk/scrolling/overview</p>

Body:
I want to hide the scroll bar for mat-select-filter and show only for mat-option in Angular .

In AppComponent.html

<mat-form-field class="input-permissions">
    <mat-select
      placeholder="Permissions"
      multiple
      [formControl]="permissionsControl"
      disableOptionCentering
    >
      <mat-select-filter
        [placeholder]="'Search Permissions'"
        [array]="permissions"
        (filteredReturn)="filteredList = $event"
        [displayMember]="'appPermissions'"
        [showSpinner]="false"
      >
      </mat-select-filter>
      <mat-option
        *ngFor="let permission of permissions"
        [value]="permission.value"
      >
        {{ permission.value}}
      </mat-option>
    </mat-select>
  </mat-form-field>

Now it is showing like this,

I want to show the scroll bar like this,

Any help would be appreciated.


问:
HttpRequest.RouteValues property is not accessible from code but accessible from debugger
I am trying to create middleware which performs some checking for particular requests.

For example, I have such routes:

api/Test/{paramToCheck}/aaa

api/Test/bbb/ccc

and I have these requests:

http://some-host-and-port/api/Test/1234/aaa

http://some-host-and-port/api/Test/bbb/ccc

Now inside my middleware I want to check if request contains {paramToCheck} and get value of this parameter.

When I set breakpoint inside InvokeAsync I can see httpContext.Request.RouteValues property containing all needed data (Keys contains "paramToCheck" and Values contains its value).

But in code I can't access this property, I get error:

Error CS1061: 'HttpRequest' does not contain a definition for
  'RouteValues' and no accessible extension method 'RouteValues'
  accepting a first argument of type 'HttpRequest' could be found (are
  you missing a using directive or an assembly reference?)

var value = httpContext.Request.RouteValues["paramToCheck"];

How can I access this property or how can I perform needed check?

Code:

```<code>public class MyMiddleware
{
    private readonly RequestDelegate _next;

    public MyMiddleware
    (
        RequestDelegate next
    ) => this._next = next;

    public async Task InvokeAsync(HttpContext httpContext)
    {
        var value = httpContext.Request.RouteValues["paramToCheck"]; // error here

        //... some logis with value

        await this._next(httpContext);
    }
}
</code>```

EDIT

Middleware is inside netstandard2.1 class library and it cannot be moved to api project as it is common and should be used by several api projects.

UPDATE

Seems like currently it cannot be achieved as RouteValues propery was added in Microsoft.AspNetCore.Http.Abstractions 3.0.0 which is inside NetCoreApp 3 metapackage. And there is no possibility to install this package in netstandard 2.1 project because the latest version is 2.2.0.

答:
Using a class library, the answer for me was to upgrade to using .netcore 3.1's Microsoft.AspNetCore.App instead of Microsoft.AspNetCore.Http.Abstractions v2.2

As stated here, .net core 3 did away with all the small packages, so I replaced

```<code><PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="2.2.0" />
  </ItemGroup>
</code>```

with

```<code><PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
      <FrameworkReference Include="Microsoft.AspNetCore.App"/>
  </ItemGroup>
</code>```

and then I could access the route like so:

```<code>HttpContext.Request.RouteValues["version"];
</code>```

where {version} was set in the route.

Body:
I am trying to create middleware which performs some checking for particular requests.

For example, I have such routes:

api/Test/{paramToCheck}/aaa

api/Test/bbb/ccc

and I have these requests:

http://some-host-and-port/api/Test/1234/aaa

http://some-host-and-port/api/Test/bbb/ccc

Now inside my middleware I want to check if request contains {paramToCheck} and get value of this parameter.

When I set breakpoint inside InvokeAsync I can see httpContext.Request.RouteValues property containing all needed data (Keys contains "paramToCheck" and Values contains its value).

But in code I can't access this property, I get error:

Error CS1061: 'HttpRequest' does not contain a definition for
  'RouteValues' and no accessible extension method 'RouteValues'
  accepting a first argument of type 'HttpRequest' could be found (are
  you missing a using directive or an assembly reference?)

var value = httpContext.Request.RouteValues["paramToCheck"];

How can I access this property or how can I perform needed check?

Code:

public class MyMiddleware
{
    private readonly RequestDelegate _next;

    public MyMiddleware
    (
        RequestDelegate next
    ) => this._next = next;

    public async Task InvokeAsync(HttpContext httpContext)
    {
        var value = httpContext.Request.RouteValues["paramToCheck"]; // error here

        //... some logis with value

        await this._next(httpContext);
    }
}

EDIT

Middleware is inside netstandard2.1 class library and it cannot be moved to api project as it is common and should be used by several api projects.

UPDATE

Seems like currently it cannot be achieved as RouteValues propery was added in Microsoft.AspNetCore.Http.Abstractions 3.0.0 which is inside NetCoreApp 3 metapackage. And there is no possibility to install this package in netstandard 2.1 project because the latest version is 2.2.0.

Body:
Using a class library, the answer for me was to upgrade to using .netcore 3.1's Microsoft.AspNetCore.App instead of Microsoft.AspNetCore.Http.Abstractions v2.2

As stated here, .net core 3 did away with all the small packages, so I replaced

<PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="2.2.0" />
  </ItemGroup>

with

<PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
      <FrameworkReference Include="Microsoft.AspNetCore.App"/>
  </ItemGroup>

and then I could access the route like so:

HttpContext.Request.RouteValues["version"];

where {version} was set in the route.


问:
Why LSTM uses sigmoid function to mimic the gate mechanism instead of binary value(0/1)?
In LSTM, we usually use sigmoid function to mimic the gates mechanism (soft), but the problem is in a lot of cases, such function gives a value around 0.5, which does not mean anything in terms of gates. Why don't use binary value (0/1) in LSTM, what is the basic idea and intuition using sigmoid function in LSTM and GRU?</p>

答: A binary function in your network would cause problems with backpropagation, since its not a 'nicely differentiable' function (the delta function, which is its derivative, won't play nice in numeric computations)</p>


问:
How do you make websites with Java?
This might be a really trivial question, but I've been writing Java programs at my school and I just found out that I can create websites with Java as well.

How can I do that? Any good books/tutorials for that?

Which is better for Web development, Java or PHP?

Also, when using PHP, MySQL comes into picture and while writing Java programs for desktop, we just use File I/O, so what is better for web dev, File I/O or MySQL?

答:
You are asking a few different questions...

How can I create websites with Java?

The simplest way to start making websites with Java is to use JSP.  JSP stands for Java Server Pages, and it allows you to embed HTML in Java code files for dynamic page creation.  In order to compile and serve JSPs, you will need a Servlet Container, which is basically a web server that runs Java classes.  The most popular basic Servlet Container is called Tomcat, and it's provided free by The Apache Software Foundation.  Follow the tutorial that cletus provided here.

Once you have Tomcat up and running, and have a basic understanding of how to deploy JSPs, you'll probably want to start creating your own JSPs.  I always like IBM developerWorks tutorials.  They have a JSP tutorial here that looks alright (though a bit dated).

You'll find out that there is a lot more to Java web development than JSPs, but these tutorials will get you headed in the right direction.

PHP vs. Java

This is a pretty subjective question.  PHP and Java are just tools, and in the hands of a bad programmer, any tool is useless.  PHP and Java both have their strengths and weaknesses, and the discussion of them is probably outside of the scope of this post.  I'd say that if you already know Java, stick with Java.

File I/O vs. MySQL

MySQL is better suited for web applications, as it is designed to handle many concurrent users.  You should know though that Java can use MySQL just as easily as PHP can, through JDBC, Java's database connectivity framework.

OwnerDisplayName: GVRV

Title: How do you make websites with Java?

OwnerDisplayName: flashcards


问:
How to supply a templated function as a parameter for another function, with a default value, in C++?
How can I have a templated function as a parameter for another function, with a default value?

For example, if I wanted to supply a function with a templated sort function, but have it default to std::sort, what would that look like?

The following does not work:

```<code>#include <algorithm> // std::sort

template <class iterator_type, class sort_comparison>
void temp(void (*sort_func)(iterator_type, iterator_type, sort_comparison) = std::sort)
{
    return;
}

int main()
{
    temp();

    return 0;
}
</code>```

It still seems to require a supplied parameter according to the gcc errors.

答:
An alternative and less constrained solution is to wrap std::sort or another function template invocation into a lambda object:

```<code>template <class Container, class Sort>
void temp(Container& c, Sort sort) {
    sort(c);
}

template <class Container>
void temp(Container& c) {
    temp(c, [](auto& c) { std::sort(c.begin(), c.end()); });
}

int main() {
    std::vector<int> v;
    temp(v);
    temp(v, [](auto& c) { std::stable_sort(c.begin(), c.end()); });

    std::list<int> l;
    temp(l, [](auto& c) { c.sort(); }); // std::sort is incompatible with std::list
}
</code>```

In C++03 lambda expressions aren't available (there are limited substitutes like boost::lambda but it has exactly the same limitation that it needs a pointer to function, cannot call a function template, unlike C++11 lambda), so that you have to code that functional class explicitly (but it gives you more flexibility with overloading):

```<code>struct Sort {
    template<class C>
    void operator()(C& c) {
        std::sort(c.begin(), c.end());
    }

    template<class T, class A>
    void operator()(std::list<T, A>& c) {
        c.sort();
    }
};
// ...
    temp(v, Sort());
    temp(l, Sort());
</code>```

Still though, that is probably the simplest, fastest to compile and execute solution in C++03. It is verbose and non-local, but that is the best/simplest you can do in C++03.

Body:
How can I have a templated function as a parameter for another function, with a default value?

For example, if I wanted to supply a function with a templated sort function, but have it default to std::sort, what would that look like?

The following does not work:

#include <algorithm> // std::sort

template <class iterator_type, class sort_comparison>
void temp(void (*sort_func)(iterator_type, iterator_type, sort_comparison) = std::sort)
{
    return;
}

int main()
{
    temp();

    return 0;
}

It still seems to require a supplied parameter according to the gcc errors.

Body:
An alternative and less constrained solution is to wrap std::sort or another function template invocation into a lambda object:

template <class Container, class Sort>
void temp(Container& c, Sort sort) {
    sort(c);
}

template <class Container>
void temp(Container& c) {
    temp(c, [](auto& c) { std::sort(c.begin(), c.end()); });
}

int main() {
    std::vector<int> v;
    temp(v);
    temp(v, [](auto& c) { std::stable_sort(c.begin(), c.end()); });

    std::list<int> l;
    temp(l, [](auto& c) { c.sort(); }); // std::sort is incompatible with std::list
}

In C++03 lambda expressions aren't available (there are limited substitutes like boost::lambda but it has exactly the same limitation that it needs a pointer to function, cannot call a function template, unlike C++11 lambda), so that you have to code that functional class explicitly (but it gives you more flexibility with overloading):

struct Sort {
    template<class C>
    void operator()(C& c) {
        std::sort(c.begin(), c.end());
    }

    template<class T, class A>
    void operator()(std::list<T, A>& c) {
        c.sort();
    }
};
// ...
    temp(v, Sort());
    temp(l, Sort());

Still though, that is probably the simplest, fastest to compile and execute solution in C++03. It is verbose and non-local, but that is the best/simplest you can do in C++03.


问:
Flex child of child does not expand to 100%
In CSS, if a child of a child is set to width: 100% and the wrapping div has display: flex set, the content does not expand to 100% it only uses the space of the content.

How would one make it expand to the size the grandchild sets itself but still use flex?

flex-grow is probably not the answer since this will always expand to take up the full space and not respect the size the grandchild sets itself.

See following example:

.wrapperFlex, .wrapperBlock{
  border: 1px solid silver;
}

.wrapperFlex {
  display: flex;
}

.levelOne {
}

.levelOneGrow {
  flex-grow: 1;
}

.levelTwo, .levelTwoFullWidth {
  color: white;
  background-color: blue;
}

.levelTwoFullWidth {
  width: 100%;
}

.levelOnePassthrough{
  display: contents;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- Premise -->
<div class="wrapperFlex">
  <div>PRE</div>
  <div class="levelOne">
    <div class="levelTwoFullWidth">
      WRAPPER FLEX
    </div>
  </div>
  <div>AFTER</div>
</div>
<br/>

<!-- Not what is wanted, the grandchild here does not actually expand to 100%
it should be only as wide as the content here -->
<div class="wrapperFlex">
  <div>PRE</div>
  <div class="levelOneGrow">
    <div class="levelTwo">
      WRAPPER FLEX GROW
    </div>
  </div>
  <div>AFTER</div>
</div>

<br/>

<!-- What is wanted but not possible, display: contents is not commonly available -->
<div class="wrapperFlex">
  <div>PRE</div>
  <div class="levelOnePassthrough">
    <div class="levelTwoFullWidth ">
      WRAPPER FLEX PASSTHROUGH
    </div>
  </div>
  <div>AFTER</div>
</div></code>```

答:
Can you set flex-basis to the child?

.wrapperFlex, .wrapperBlock{
  border: 1px solid silver;
}

.wrapperFlex {
  display: flex;
}

.wrapperBlock {
  display: block;
}

.levelOne {
  flex-basis: 100%; /* Set flex-basis to 100% */
}

.levelTwo {
  color: white;
  width: 100%;
  background-color: blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapperFlex">
  <div class="levelOne">
    <div class="levelTwo">
      WRAPPER FLEX
    </div>
  </div>
</div>

<br/>

<div class="wrapperBlock">
  <div class="levelOne">
    <div class="levelTwo">
      WRAPPER BLOCK
    </div>
  </div>
</div></code>```

Body:
In CSS, if a child of a child is set to width: 100% and the wrapping div has display: flex set, the content does not expand to 100% it only uses the space of the content.

How would one make it expand to the size the grandchild sets itself but still use flex?

flex-grow is probably not the answer since this will always expand to take up the full space and not respect the size the grandchild sets itself.

See following example:

.wrapperFlex, .wrapperBlock{
  border: 1px solid silver;
}

.wrapperFlex {
  display: flex;
}

.levelOne {
}

.levelOneGrow {
  flex-grow: 1;
}

.levelTwo, .levelTwoFullWidth {
  color: white;
  background-color: blue;
}

.levelTwoFullWidth {
  width: 100%;
}

.levelOnePassthrough{
  display: contents;
}

PRE

      WRAPPER FLEX

AFTER

PRE

      WRAPPER FLEX GROW

AFTER

PRE

      WRAPPER FLEX PASSTHROUGH

AFTER

Body:
Can you set flex-basis to the child?

.wrapperFlex, .wrapperBlock{
  border: 1px solid silver;
}

.wrapperFlex {
  display: flex;
}

.wrapperBlock {
  display: block;
}

.levelOne {
  flex-basis: 100%; /* Set flex-basis to 100% */
}

.levelTwo {
  color: white;
  width: 100%;
  background-color: blue;
}

<div class="wrapperFlex">
  <div class="levelOne">
    <div class="levelTwo">
      WRAPPER FLEX
    </div>
  </div>
</div>

<br/>

<div class="wrapperBlock">
  <div class="levelOne">
    <div class="levelTwo">
      WRAPPER BLOCK
    </div>
  </div>
</div>


问:
BigQuery question - Attribution modeling with the paths table
this may be a basic question but I just couldn't figure it out. Sample data and query could be found here.

The purpose of query is to figure out which placement to attribute credit to. In the first-touch model, the earliest touch that led to a conversion (FLOODLIGHT) is credited. So here 22 has 1 credit, 11 has 2. I don't quite get the first-tough query especially the unnest part. What's the point of comparing prev_conversion_event.event_time < conversion_event.event_time? Aren't they essentially the same? I mean both of them came from UNNEST(t.*_path.events). And attributed_event.event_time also came from the same place. I'm just confused as hell here. Much appreciate the help!

For convenience I'm pasting the sample data and query below:

Sample data

/* Substitute *_paths for the specific paths table that you want to query. */
SELECT
  (
  SELECT
    attributed_event_metadata.placement_id
  FROM (
    SELECT
      AS STRUCT attributed_event.placement_id,
      ROW_NUMBER() OVER(ORDER BY attributed_event.event_time ASC) AS rank
    FROM
      UNNEST(t.*_paths.events) AS attributed_event
    WHERE
      attributed_event.event_type != "FLOODLIGHT"
      AND attributed_event.event_time < conversion_event.event_time
      AND attributed_event.event_time > (
      SELECT
        IFNULL( (
          SELECT
            MAX(prev_conversion_event.event_time) AS event_time
          FROM
            UNNEST(t.*_paths.events) AS prev_conversion_event
          WHERE
            prev_conversion_event.event_type = "FLOODLIGHT"
            AND prev_conversion_event.event_time < conversion_event.event_time),
          0)) ) AS attributed_event_metadata
  WHERE
    attributed_event_metadata.rank = 1) AS placement_id,
  COUNT(*) AS credit
FROM
  adh.*_paths AS t,
  UNNEST(*_paths.events) AS conversion_event
WHERE
  conversion_event.event_type = "FLOODLIGHT"
GROUP BY
  placement_id
HAVING
  placement_id IS NOT NULL
ORDER BY
  credit DESC

答:
The point of comparing both prev_conversion_event.event_time and conversion_event.event_time is hinted at the names assigned to each value.

What we want is to find all the events between two Floodlights. Then, you need to check that your event attributed_event is not a Floodlight and it is between two Floodlights i.e.

```<code>attributed_event.event_type != "FLOODLIGHT"
attributed_event.event_time < conversion_event.event_time
attributed_event.event_time > MAX(prev_conversion_event.event_time)
</code>```

where MAX(prev_conversion_event.event_time) has to reflect the previous Floodlight to the current one conversion_event.event_time, hence you need

```<code>prev_conversion_event.event_type = "FLOODLIGHT"
conversion_event.event_type = "FLOODLIGHT"
prev_conversion_event.event_time < conversion_event.event_time
</code>```

Of course, all three elements prev_conversion, conversion and attributed are obtained from the same events (with additional filtering) hence you need to take them from the same column

```<code>UNNEST(t.*_paths.events) AS prev_conversion_event WHERE ...
UNNEST(t.*_paths.events) AS conversion_event WHERE ...
UNNEST(t.*_paths.events) AS attributed_event WHERE ...
</code>```

Then, you just need to combine the previous conditions in the proper order and add the rank and the credit as appropriate for each use case (First-touch, Last-touch, Linear).

I hope that this explanation is clear enough. Let me know if something is unclear so I can help you understand it further.

Body:
The point of comparing both prev_conversion_event.event_time and conversion_event.event_time is hinted at the names assigned to each value.

What we want is to find all the events between two Floodlights. Then, you need to check that your event attributed_event is not a Floodlight and it is between two Floodlights i.e.

attributed_event.event_type != "FLOODLIGHT"
attributed_event.event_time < conversion_event.event_time
attributed_event.event_time > MAX(prev_conversion_event.event_time)

where MAX(prev_conversion_event.event_time) has to reflect the previous Floodlight to the current one conversion_event.event_time, hence you need

prev_conversion_event.event_type = "FLOODLIGHT"
conversion_event.event_type = "FLOODLIGHT"
prev_conversion_event.event_time < conversion_event.event_time

Of course, all three elements prev_conversion, conversion and attributed are obtained from the same events (with additional filtering) hence you need to take them from the same column

UNNEST(t.*_paths.events) AS prev_conversion_event WHERE ...
UNNEST(t.*_paths.events) AS conversion_event WHERE ...
UNNEST(t.*_paths.events) AS attributed_event WHERE ...

Then, you just need to combine the previous conditions in the proper order and add the rank and the credit as appropriate for each use case (First-touch, Last-touch, Linear).

I hope that this explanation is clear enough. Let me know if something is unclear so I can help you understand it further.


问:
How to get err, stderr from execSync()?
In node 12, execSync can return stdout, e.g.

```<code>const execSync = require('child_process').execSync;

const stdout = execSync('ls');
console.log(`stdout: ${stdout}`);
</code>```

But how to get err and stderr ?
In the callback of child_process.exec, you have all 3.

I can use async way, but prefer to use execSync() if it's easier.

答:
execSync Returns:  |  The stdout from the command.execSync extents  spawnSync, so you cannot catch array error message, if you want, you can use spawnSync,
https://nodejs.org/api/child_process.html#child_process_child_process_spawnsync_command_args_options</p>

```<code>Returns: <Object>

pid <number> Pid of the child process.
output <Array> Array of results from stdio output.
stdout <Buffer> | <string> The contents of output[1].
stderr <Buffer> | <string> The contents of output[2].
status <number> | <null> The exit code of the subprocess, or null if the subprocess terminated due to a signal.
signal <string> | <null> The signal used to kill the subprocess, or null if the subprocess did not terminate due to a signal.
error <Error> The error object if the child process failed or timed out.

</code>```

Title: How to get err, stderr from execSync()?

Body:
In node 12, execSync can return stdout, e.g.

const execSync = require('child_process').execSync;

const stdout = execSync('ls');
console.log(`stdout: ${stdout}`);

But how to get err and stderr ?
In the callback of child_process.exec, you have all 3.

I can use async way, but prefer to use execSync() if it's easier.

Body:
execSync Returns:  |  The stdout from the command.execSync extents  spawnSync, so you cannot catch array error message, if you want, you can use spawnSync,
https://nodejs.org/api/child_process.html#child_process_child_process_spawnsync_command_args_options

Returns: <Object>

pid <number> Pid of the child process.
output <Array> Array of results from stdio output.
stdout <Buffer> | <string> The contents of output[1].
stderr <Buffer> | <string> The contents of output[2].
status <number> | <null> The exit code of the subprocess, or null if the subprocess terminated due to a signal.
signal <string> | <null> The signal used to kill the subprocess, or null if the subprocess did not terminate due to a signal.
error <Error> The error object if the child process failed or timed out.


问:
I change my BackgroundImage with a randomElement from an Array but its zoomed in and not fitting perfectly
I have an array with my Image-names and a button. When I click on the button, the background-image schould get chaged. All is working but the pictures are a little bit zoomed and are not scaled to screen size.

```<code>import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    var imagesArray = ["1", "2", "3", "4"]

    @IBAction func changeBackgroundImageButton_Tapped(_ sender: UIButton) {

        if let randomImage = imagesArray.randomElement(){

            view.backgroundColor = UIColor(patternImage: UIImage(named: randomImage)!)
        }

    }

}
</code>```

So what should I do that the background-images are not zoomed and scaled perfectly? Thanks!

答:
This is tested code

```<code>class ViewController: UIViewController {

        var imagesArray = ["1", "2", "3"]

        lazy var imageView:UIImageView = {
            let imageView = UIImageView()
            imageView.frame = UIScreen.main.bounds
            imageView.backgroundColor = .red
            imageView.contentMode = .scaleAspectFit
            imageView.image = UIImage(named: imagesArray.randomElement() ?? "1")
            return imageView
        }()

        @IBAction func changeBackground_Tapped(_ sender: UIButton) {
                imageView.image = UIImage(named: imagesArray.randomElement() ?? "1")

            }

       private func setupView() {
            view.addSubview(imageView)
        }

        override func viewDidLayoutSubviews() {
            super.viewDidLayoutSubviews()
            imageView.frame = view.bounds
        }

        override func viewDidLoad() {

            super.viewDidLoad()
             setupView()

        }

    }
</code>```

Body:
I have an array with my Image-names and a button. When I click on the button, the background-image schould get chaged. All is working but the pictures are a little bit zoomed and are not scaled to screen size.

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    var imagesArray = ["1", "2", "3", "4"]

    @IBAction func changeBackgroundImageButton_Tapped(_ sender: UIButton) {

        if let randomImage = imagesArray.randomElement(){

            view.backgroundColor = UIColor(patternImage: UIImage(named: randomImage)!)
        }

    }

}

So what should I do that the background-images are not zoomed and scaled perfectly? Thanks!

Body:
This is tested code

class ViewController: UIViewController {

        var imagesArray = ["1", "2", "3"]

        lazy var imageView:UIImageView = {
            let imageView = UIImageView()
            imageView.frame = UIScreen.main.bounds
            imageView.backgroundColor = .red
            imageView.contentMode = .scaleAspectFit
            imageView.image = UIImage(named: imagesArray.randomElement() ?? "1")
            return imageView
        }()

        @IBAction func changeBackground_Tapped(_ sender: UIButton) {
                imageView.image = UIImage(named: imagesArray.randomElement() ?? "1")

            }

       private func setupView() {
            view.addSubview(imageView)
        }

        override func viewDidLayoutSubviews() {
            super.viewDidLayoutSubviews()
            imageView.frame = view.bounds
        }

        override func viewDidLoad() {

            super.viewDidLoad()
             setupView()

        }

    }


问:
Change Detector Ref not working with Angular Material Dialog Box
I need help to properly implement the ChangeDetectorRef.

What I am trying to do open a Mat Dialog Box on a click, but everytime I add the ChangeDetectorRef contructor the Dialog Box breaks, giving me the error
    NullInjectorError: StaticInjectorError(AppModule)[ViewAdvertComponent -> ChangeDetectorRef]:
      StaticInjectorError(Platform: core)[ViewAdvertComponent -> ChangeDetectorRef]:
        NullInjectorError: No provider for ChangeDetectorRef!

I might just be referencing them wrong, but even the documentation is too complex for my knowledge.

HomePage.ts

```<code>import { Component, OnInit, NgModule, ViewChild, ChangeDetectorRef } from '@angular/core';
import { MaterialModule } from 'src/materialModule';
import { LoginService, iMakes } from '../login-popup/login.service';
import { HomePageService } from './home-page.service';
import { environment } from 'src/environments/environment';
import { HttpClient } from '@angular/common/http';
import { MatSnackBar } from '@angular/material/snack-bar';
import { RegisteredUserService } from '../registered-user/registered-user.service';
import { MatDialog } from '@angular/material/dialog';
import { ViewAdvertComponent } from '../view-advert/view-advert.component';
import { SendAdvertIDService } from './sendAdvertID.service';
import { MatPaginator } from '@angular/material/paginator';
import { Observable } from 'rxjs';
import { MatTableDataSource } from '@angular/material/table';
@NgModule({imports:[MaterialModule]})

@Component({
  selector: 'app-home-page',
  templateUrl: './home-page.component.html',
  styleUrls: ['./home-page.component.css'],
  providers:[ViewAdvertComponent]
})

export class HomePageComponent implements OnInit {

  @ViewChild(MatPaginator,{static:false}) paginator: MatPaginator;

  public apiURL = environment.api;
  public isImageLoading:any;
  public adverts:any=[];
  public imageToLoad:any=[];
  public obs: Observable<any>;
  public dataSource:MatTableDataSource<Card>;
  public selected;
  public advertID:any;

  constructor(private cd: ChangeDetectorRef,private advertIDService:SendAdvertIDService, private popup:MatDialog,private http:HttpClient,private lservice:LoginService, private snack:MatSnackBar,private registeredUserService:RegisteredUserService) {}

  ngOnInit() {
    this.registeredUserService.GetAllAdverts().subscribe(val=>
      {
        this.dataSource = new MatTableDataSource<Card>(val);
        this.dataSource.paginator = this.paginator;
        this.obs = this.dataSource.connect();
        let numOfAds=0;
        for(let a of val)
        {
         this.imageToLoad[numOfAds]={url:this.apiURL+'/api/Images/'+a.advertID+'_1'};

          numOfAds++;
        }
      },error => this.snack.open("Something went wrong. Please try again later")._dismissAfter(5000));
  }

ViewAdvert(e) //method that opens the dialog box
  {
    this.cd.markForCheck();
    this.advertIDService.SetAdvertID(e);
    this.popup.open(ViewAdvertComponent,{
      width: '500px',
    });
  }
</code>```

ViewAdvert.ts (which executes inside the Dialog Box)

```<code>import { Component, ViewChild, ChangeDetectorRef, ChangeDetectionStrategy} from '@angular/core';
import { HomePageComponent } from '../home-page/home-page.component';
import { SendAdvertIDService } from '../home-page/sendAdvertID.service';
import { ViewAdvertService, iAdvertID } from './view-advert.service';
import { environment } from 'src/environments/environment';

@Component({
  selector: 'app-view-advert',
  changeDetection: ChangeDetectionStrategy.OnPush,
  templateUrl: './view-advert.component.html',
  styleUrls: ['./view-advert.component.css']
})
export class ViewAdvertComponent {
  @ViewChild('slideshow',{static:false}) slideshow:any;
  public advertID:String;
  public apiURL = environment.api;
  public imageID:any;
  public imageSource:any=[];
  public imageToSlideShow:any=[];
  public counter:any=0;
  public faultyImages:any=[];
  constructor(private cd: ChangeDetectorRef,public home:HomePageComponent,private advertIDService:SendAdvertIDService, private viewService:ViewAdvertService) {
    this.advertID=home.advertID;

  }
  ngOnInit(e) {
    this.cd.markForCheck();
    this.advertID= this.advertIDService.GetAdvertID();
    let param:iAdvertID={
     id:this.advertID
    }
   this.viewService.AdvertDetails(param).subscribe(val=>
    {
      this.imageID=val[0].advertID;
      this.counter=1;
      for(let i=0;i<=4;i++)
      {
        this.imageSource[i]=this.apiURL+'/api/Images/'+this.imageID+'_'+this.counter;
        this.faultyImages[i]=e;
        if(this.imageSource[i]==this.faultyImages[i])
        {
          console.log(this.faultyImages[i]);
        }
        else{
          this.imageToSlideShow[i]=this.imageSource[i];
        }
        this.counter++;
      }
    });
  }

}
</code>```

答:
You cannot inject a component (ViewAdvertComponent) into another component (HomePageComponent).

But I think you don't need that, but this https://material.angular.io/components/dialog/.

Body:
I need help to properly implement the ChangeDetectorRef.

What I am trying to do open a Mat Dialog Box on a click, but everytime I add the ChangeDetectorRef contructor the Dialog Box breaks, giving me the error
    NullInjectorError: StaticInjectorError(AppModule)[ViewAdvertComponent -> ChangeDetectorRef]:
      StaticInjectorError(Platform: core)[ViewAdvertComponent -> ChangeDetectorRef]:
        NullInjectorError: No provider for ChangeDetectorRef!

I might just be referencing them wrong, but even the documentation is too complex for my knowledge.

HomePage.ts

import { Component, OnInit, NgModule, ViewChild, ChangeDetectorRef } from '@angular/core';
import { MaterialModule } from 'src/materialModule';
import { LoginService, iMakes } from '../login-popup/login.service';
import { HomePageService } from './home-page.service';
import { environment } from 'src/environments/environment';
import { HttpClient } from '@angular/common/http';
import { MatSnackBar } from '@angular/material/snack-bar';
import { RegisteredUserService } from '../registered-user/registered-user.service';
import { MatDialog } from '@angular/material/dialog';
import { ViewAdvertComponent } from '../view-advert/view-advert.component';
import { SendAdvertIDService } from './sendAdvertID.service';
import { MatPaginator } from '@angular/material/paginator';
import { Observable } from 'rxjs';
import { MatTableDataSource } from '@angular/material/table';
@NgModule({imports:[MaterialModule]})

@Component({
  selector: 'app-home-page',
  templateUrl: './home-page.component.html',
  styleUrls: ['./home-page.component.css'],
  providers:[ViewAdvertComponent]
})

export class HomePageComponent implements OnInit {

  @ViewChild(MatPaginator,{static:false}) paginator: MatPaginator;

  public apiURL = environment.api;
  public isImageLoading:any;
  public adverts:any=[];
  public imageToLoad:any=[];
  public obs: Observable<any>;
  public dataSource:MatTableDataSource<Card>;
  public selected;
  public advertID:any;

  constructor(private cd: ChangeDetectorRef,private advertIDService:SendAdvertIDService, private popup:MatDialog,private http:HttpClient,private lservice:LoginService, private snack:MatSnackBar,private registeredUserService:RegisteredUserService) {}

  ngOnInit() {
    this.registeredUserService.GetAllAdverts().subscribe(val=>
      {
        this.dataSource = new MatTableDataSource<Card>(val);
        this.dataSource.paginator = this.paginator;
        this.obs = this.dataSource.connect();
        let numOfAds=0;
        for(let a of val)
        {
         this.imageToLoad[numOfAds]={url:this.apiURL+'/api/Images/'+a.advertID+'_1'};

          numOfAds++;
        }
      },error => this.snack.open("Something went wrong. Please try again later")._dismissAfter(5000));
  }

ViewAdvert(e) //method that opens the dialog box
  {
    this.cd.markForCheck();
    this.advertIDService.SetAdvertID(e);
    this.popup.open(ViewAdvertComponent,{
      width: '500px',
    });
  }

ViewAdvert.ts (which executes inside the Dialog Box)

import { Component, ViewChild, ChangeDetectorRef, ChangeDetectionStrategy} from '@angular/core';
import { HomePageComponent } from '../home-page/home-page.component';
import { SendAdvertIDService } from '../home-page/sendAdvertID.service';
import { ViewAdvertService, iAdvertID } from './view-advert.service';
import { environment } from 'src/environments/environment';

@Component({
  selector: 'app-view-advert',
  changeDetection: ChangeDetectionStrategy.OnPush,
  templateUrl: './view-advert.component.html',
  styleUrls: ['./view-advert.component.css']
})
export class ViewAdvertComponent {
  @ViewChild('slideshow',{static:false}) slideshow:any;
  public advertID:String;
  public apiURL = environment.api;
  public imageID:any;
  public imageSource:any=[];
  public imageToSlideShow:any=[];
  public counter:any=0;
  public faultyImages:any=[];
  constructor(private cd: ChangeDetectorRef,public home:HomePageComponent,private advertIDService:SendAdvertIDService, private viewService:ViewAdvertService) {
    this.advertID=home.advertID;

  }
  ngOnInit(e) {
    this.cd.markForCheck();
    this.advertID= this.advertIDService.GetAdvertID();
    let param:iAdvertID={
     id:this.advertID
    }
   this.viewService.AdvertDetails(param).subscribe(val=>
    {
      this.imageID=val[0].advertID;
      this.counter=1;
      for(let i=0;i<=4;i++)
      {
        this.imageSource[i]=this.apiURL+'/api/Images/'+this.imageID+'_'+this.counter;
        this.faultyImages[i]=e;
        if(this.imageSource[i]==this.faultyImages[i])
        {
          console.log(this.faultyImages[i]);
        }
        else{
          this.imageToSlideShow[i]=this.imageSource[i];
        }
        this.counter++;
      }
    });
  }

}


问:
Genymotion is not working with Ubuntu 20.04 LTS for androdid studio
I have installed virtual box 6.1 in Ubuntu 20.04 LTS for use in android studio.
Then I installed geny motion 3.1.0 but not working properly.
The error message is shown below.

I cannot degrade virtual box version as it is not suitable for Ubuntu 20.04 LTS.
Please suggest a solution

答: This is a known issue with VirtualBox on Linux. You should try to recompile VirtualBox kernel module. See this article.</p>


问:
Ksql, GROUP BY return ServerError:java.lang.NullPointerException
I am using confluent 4.1.1 , I tried several aggregate commands, but always return NPE with GROUP BY:

```<code>ksql> select cust_id, count(*) as sum_sub from TBL_SUBSCRIBER GROUP BY cust_id;
 ServerError:java.lang.NullPointerException
ksql>

ksql> describe extended TBL_SUBSCRIBER;

Type                 : TABLE
Key field            : SUB_ID
Timestamp field      : Not set - using <ROWTIME>
Key format           : STRING
Value format         : DELIMITED
Kafka output topic   : subscriber (partitions: 10, replication: 3)

 Field               | Type
 ROWTIME             | BIGINT           (system)
 ROWKEY              | VARCHAR(STRING)  (system)
 SUB_ID              | VARCHAR(STRING)
 CONTRACT_ID         | VARCHAR(STRING)
 CUST_ID             | VARCHAR(STRING)
 ACCOUNT_ID          | VARCHAR(STRING)
 TELECOM_SERVICE_ID  | VARCHAR(STRING)
</code>```

Please help me!

答:
Sorry to see you've run into an issue with KSQL. Sounds like a bug in the old version you're running. I'm confident the issue you've run into has been fixed in more recent versions of ksqlDB.  I'm confident because there are explicit test cases that cover performing such a group by on a TABLE source: https://github.com/confluentinc/ksql/blob/964c8ad665599123ad3635a2f806cb316e4f206e/ksqldb-functional-tests/src/test/resources/query-validation-tests/group-by.json#L184-L218

Please upgrade and retry.

Body:
I am using confluent 4.1.1 , I tried several aggregate commands, but always return NPE with GROUP BY:

ksql> select cust_id, count(*) as sum_sub from TBL_SUBSCRIBER GROUP BY cust_id;
 ServerError:java.lang.NullPointerException
ksql>

ksql> describe extended TBL_SUBSCRIBER;

Type                 : TABLE
Key field            : SUB_ID
Timestamp field      : Not set - using <ROWTIME>
Key format           : STRING
Value format         : DELIMITED
Kafka output topic   : subscriber (partitions: 10, replication: 3)

 Field               | Type
 ROWTIME             | BIGINT           (system)
 ROWKEY              | VARCHAR(STRING)  (system)
 SUB_ID              | VARCHAR(STRING)
 CONTRACT_ID         | VARCHAR(STRING)
 CUST_ID             | VARCHAR(STRING)
 ACCOUNT_ID          | VARCHAR(STRING)
 TELECOM_SERVICE_ID  | VARCHAR(STRING)

Please help me!


问:
Create BaseFragment and extend this Fragment in ChildFragment
I don't know whether this is repeated question or not, But I didn't found any solution.

The problem is, there is a screen which has similar views in all the screens, that screens are in fragment.

So, I want to create a base fragment and want to extend this base fragment in all child fragments.

I found on google, for demo examples, But I didn't find any solution.

I don't know from where to start.

Please help me.

I found this links but it is not much clear:

Fragments inheritance Android

When do I need a base activity and base fragment?

BaseFragment.java

```<code>public class BaseFragment extends Fragment {

  public BaseFragment() {
    // Required empty public constructor
  }

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    return inflater.inflate(R.layout.fragment_base, container, false);
  }
}
</code>```

ChildFragment.Java

```<code>public class ChildFragment extends BaseFragment{

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_child, container, false);
  }
}
</code>```

Now, there is a TextView in fragment_child layout. that is displayed when I run the app,
but there are two other views in fragment_base, that is not showing...

答:
Follow this simple and clean approach

```<code>public abstract class BaseFragment extends Fragment {
      public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View root = inflater.inflate(getLayoutId(), null);

    return root;
}

@LayoutRes
protected abstract int getLayoutId();
}
</code>```

that's it for base fragment

Then for child fragment

```<code>public class ChildFragment extends BaseFragment {

@Override
protected int getLayoutId() {
    return R.layout.child_fragment;
}

}
</code>```

Make seprate methods for do your stuffs

Body:
I don't know whether this is repeated question or not, But I didn't found any solution.

The problem is, there is a screen which has similar views in all the screens, that screens are in fragment.

So, I want to create a base fragment and want to extend this base fragment in all child fragments.

I found on google, for demo examples, But I didn't find any solution.

I don't know from where to start.

Please help me.

I found this links but it is not much clear:

Fragments inheritance Android

When do I need a base activity and base fragment?

BaseFragment.java

public class BaseFragment extends Fragment {

  public BaseFragment() {
    // Required empty public constructor
  }

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    return inflater.inflate(R.layout.fragment_base, container, false);
  }
}

ChildFragment.Java

public class ChildFragment extends BaseFragment{

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_child, container, false);
  }
}

Now, there is a TextView in fragment_child layout. that is displayed when I run the app,
but there are two other views in fragment_base, that is not showing...

Body:
Follow this simple and clean approach

public abstract class BaseFragment extends Fragment {
      public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View root = inflater.inflate(getLayoutId(), null);

    return root;
}

@LayoutRes
protected abstract int getLayoutId();
}

that's it for base fragment

Then for child fragment

public class ChildFragment extends BaseFragment {

@Override
protected int getLayoutId() {
    return R.layout.child_fragment;
}

}

Make seprate methods for do your stuffs


问:
rails How to get image name instead of hash for shrine url
Currently when I store any image using shrine uploader then I received url :-

```<code>/uploads/store/90bcb5a78ed5de16a6c62eea1fb80ed1.png
</code>```

but I want url to be display like:-

```<code>/uploads/store/original_image_name.png
</code>```

is there any solution

for reference:-

initializer/shrine.rb

```<code>require "shrine/storage/file_system"
  Shrine.storages = {
    cache: Shrine::Storage::FileSystem.new("public", prefix: "uploads/cache"),
    store: Shrine::Storage::FileSystem.new("public", prefix: "uploads/store")
  }
</code>```

model/image_uploader.rb

```<code>class ImageUploader < Shrine
  plugin :derivatives
  plugin :url_options, store: { host: "www.cloudfair.com" }
  Attacher.derivatives_processor do |original|
    processor = ImageProcessing::MiniMagick.source(original)
    {
      large:  processor.resize_to_limit!(1280, 800),
      medium: processor.resize_to_limit!(600, 600),
      small:  processor.resize_to_limit!(400, 400),
    }
  end
end
</code>```

to upload image:-

```<code>photo = Photo.new
photo.image = params[:image_file]
photo.image_derivative!
photo.save()
</code>```

to access image URL:-

```<code>photo.image(:small).url
</code>```

答:
you can use something like this in your uploader file</p>

```<code>def filename
  if original_filename
    "#{model.original_filename}.#{file.extension}"
  end
end
</code>```

Body:
Currently when I store any image using shrine uploader then I received url :-

/uploads/store/90bcb5a78ed5de16a6c62eea1fb80ed1.png

but I want url to be display like:-

/uploads/store/original_image_name.png

is there any solution

for reference:-

initializer/shrine.rb

require "shrine/storage/file_system"
  Shrine.storages = {
    cache: Shrine::Storage::FileSystem.new("public", prefix: "uploads/cache"),
    store: Shrine::Storage::FileSystem.new("public", prefix: "uploads/store")
  }

model/image_uploader.rb

class ImageUploader < Shrine
  plugin :derivatives
  plugin :url_options, store: { host: "www.cloudfair.com" }
  Attacher.derivatives_processor do |original|
    processor = ImageProcessing::MiniMagick.source(original)
    {
      large:  processor.resize_to_limit!(1280, 800),
      medium: processor.resize_to_limit!(600, 600),
      small:  processor.resize_to_limit!(400, 400),
    }
  end
end

to upload image:-

photo = Photo.new
photo.image = params[:image_file]
photo.image_derivative!
photo.save()

to access image URL:-

photo.image(:small).url

Body:
you can use something like this in your uploader file

def filename
  if original_filename
    "#{model.original_filename}.#{file.extension}"
  end
end


问:
Passing a number to a function in react js
I want to pass a number to the function.I follow same way to pass both string and integer values. I can pass the string value. But I can't pass the integer value in that way.

This is my lesson2.js file

```<code>import React from 'react'

class lesson2 extends React.Component{

    constructor(props){
        super(props);
        this.state = {counter:1}
    }

    add(){
        this.setState(function(state,props){
            return{
                counter: state.counter + props.increment
            };
        })
    }

    render(){
        return(
        <div>
            Counter : {this.state.counter}</div>
        );
    }
}

export default lesson2
</code>```

This is my App.js

```<code>import React from 'react';
import './App.css';
import Variable from './Components/variable_dec'
import Lesson2 from './Components/lesson2'

function App() {
  return (
    <div className="App">

        <p>
          <Variable name='D' />
          <Lesson2 increment={10}/>
        </p>

    </div>
  );
}

export default App;
</code>```

This is my output. But in my correct output should be Counter : 11. The problem is that the increment value doesn't add to the counter. So hope your help to solve my problem.

答:
i can't see where you called the add function. If you want to initialize your counter with increment, you should set your state with props.increment in constructor instead of setting it to 1.</p>

```<code>this.state = {counter:props.increment}
</code>```

Body:
I want to pass a number to the function.I follow same way to pass both string and integer values. I can pass the string value. But I can't pass the integer value in that way.

This is my lesson2.js file

import React from 'react'

class lesson2 extends React.Component{

    constructor(props){
        super(props);
        this.state = {counter:1}
    }

    add(){
        this.setState(function(state,props){
            return{
                counter: state.counter + props.increment
            };
        })
    }

    render(){
        return(

            Counter : {this.state.counter}

        );
    }
}

export default lesson2

This is my App.js

import React from 'react';
import './App.css';
import Variable from './Components/variable_dec'
import Lesson2 from './Components/lesson2'

function App() {
  return (

          <Variable name='D' />
          <Lesson2 increment={10}/>

  );
}

export default App;

This is my output. But in my correct output should be Counter : 11. The problem is that the increment value doesn't add to the counter. So hope your help to solve my problem.

Body:
i can't see where you called the add function. If you want to initialize your counter with increment, you should set your state with props.increment in constructor instead of setting it to 1.

this.state = {counter:props.increment}


问:
Ant Design with sass in React with create-react-app
I'm trying to use Ant design with sass on my React project using antd-scss-theme-plugin but all I can find on the web is a configuration using Webpack. My project has been made with create-react-app and I shouldn't worry about webpack configuration. In fact, I don't have any webpack config file that I manage myself.

I have installed antd and node-sass-chokidar with npm and followed the configurations. All work. I can import ant components and use them, and I can use sass too. With a watch-css script, my css is automatically compiled and I can see the modifications in real time.

Now I'd like to override the less components of ant design with my sass files but as I said, the only help I can find online and the only package that I know of is for a webpack project.

Does anybody used antd-scss-theme-plugin with create-react-app or know how to deal with the configuration ?

Here is some of my configurations file :

.babelrc :

```<code>{
  "presets": ["env"],
  "plugins": ["transform-class-properties", "transform-object-rest-spread"]
}
</code>```

config-overrides.js :

```<code>const { injectBabelPlugin } = require('react-app-rewired')

module.exports = function override(config) {
  injectBabelPlugin(
    ['import', { libraryName: 'antd', libraryDirectory: 'es', style: true }],
    config,
  )
  return config
}
</code>```

package.json :

```<code>    {
  "name": "xxx",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "antd": "^3.8.0",
    "antd-scss-theme-plugin": "^1.0.7",
    "connected-react-router": "^4.3.0",
    "history": "^4.7.2",
    "material-icons-react": "^1.0.2",
    "node-sass-chokidar": "^1.3.3",
    "npm-run-all": "^4.1.3",
    "prop-types": "^15.6.2",
    "react": "^16.4.2",
    "react-app-rewired": "^1.5.2",
    "react-dom": "^16.4.2",
    "react-redux": "^5.0.7",
    "react-router": "^4.3.1",
    "react-router-dom": "^4.3.1",
    "react-router-prop-types": "^1.0.4",
    "react-scripts": "1.1.4",
    "recompose": "^0.27.1",
    "redux": "^4.0.0",
    "redux-thunk": "^2.3.0"
  },
  "devDependencies": {
    "babel-cli": "^6.26.0",
    "babel-plugin-import": "^1.8.0",
    "babel-plugin-transform-class-properties": "^6.24.1",
    "babel-plugin-transform-object-rest-spread": "^6.26.0",
    "babel-preset-env": "^1.7.0",
    "eslint": "^4.19.1",
    "eslint-config-airbnb": "^17.0.0",
    "eslint-config-prettier": "^2.9.0",
    "eslint-plugin-import": "^2.13.0",
    "eslint-plugin-jsx-a11y": "^6.1.1",
    "eslint-plugin-react": "^7.10.0",
    "eslint-plugin-react-redux": "^2.3.0",
    "prettier": "^1.14.0"
  },
  "scripts": {
    "build-css": "node-sass-chokidar src/ -o src/",
    "watch-css": "npm run build-css && node-sass-chokidar src/ -o src/ --watch --recursive",
    "start-js": "react-app-rewired start",
    "start": "npm-run-all -p watch-css start-js",
    "build-js": "react-app-rewired build",
    "build": "npm-run-all build-css build-js",
    "test": "react-app-rewired test --env=jsdom",
    "eject": "react-scripts eject",
    "format": "prettier --write \"src/**/*.js\"",
    "lint": "eslint ."
  }
}
</code>```

Thanks for all your future answers ;) !

答:
I have my old project running with SASS, CRA, and Antd using below config setup. But If you go to official Antd website, they have now an updated tutorial for configuring Antd with Create React App. But in any case, what they have explained is its usage with less and not sass, so to use sass in your project you have to combine both CRA sass setup and Antd theme customization to make things work.

Here's a sample from my project where I used the less plugin to update/customize Antd theme. You should create a custom-override.js file in the root directory of your project and add these lines of code

```<code>const { override, fixBabelImports, addLessLoader } = require('customize-cra');
// you can also use craco instead of customize-cra,
// which is now the most updated way in their current docs.

module.exports = override(
  fixBabelImports('import', {
    libraryName: 'antd',
    libraryDirectory: 'es',
    style: true,
  }),

  addLessLoader({
    javascriptEnabled: true,
    modifyVars: {
      '@primary-color': '#6237a0',
      '@link-color': '#6237a0',
      '@success-color': '#0ea70e',
      '@steps-nav-arrow-color': '#d1cdd6',
    },
  }),
);
</code>```

Then you just need to work with scss the normal way as you would do in sass based CRA project.

To use Sass, first install node-sass:

```<code>npm install node-sass --save
# or
yarn add node-sass
</code>```

Then just update your code and rename App.css to App.scss and import the same in the main(app.js) file. You can even extend the code by doing sass imports/defining variables etc ( all things that you can do with sass).

Here's a snapshot of my app.scss where all my styles are defined in the styles folder.

```<code>/*
Variable definition
*/
@import 'styles/variable';

/*
common style import
*/
@import 'styles/common';

/**
*
# # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # #       Components styles import    # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # #
*
* below I do imports for all my routes and components.
*/

@import 'styles/dashboard';
@import 'styles/details';
</code>```

Body:
I'm trying to use Ant design with sass on my React project using antd-scss-theme-plugin but all I can find on the web is a configuration using Webpack. My project has been made with create-react-app and I shouldn't worry about webpack configuration. In fact, I don't have any webpack config file that I manage myself.

I have installed antd and node-sass-chokidar with npm and followed the configurations. All work. I can import ant components and use them, and I can use sass too. With a watch-css script, my css is automatically compiled and I can see the modifications in real time.

Now I'd like to override the less components of ant design with my sass files but as I said, the only help I can find online and the only package that I know of is for a webpack project.

Does anybody used antd-scss-theme-plugin with create-react-app or know how to deal with the configuration ?

Here is some of my configurations file :

.babelrc :

{
  "presets": ["env"],
  "plugins": ["transform-class-properties", "transform-object-rest-spread"]
}

config-overrides.js :

const { injectBabelPlugin } = require('react-app-rewired')

module.exports = function override(config) {
  injectBabelPlugin(
    ['import', { libraryName: 'antd', libraryDirectory: 'es', style: true }],
    config,
  )
  return config
}

package.json :

    {
  "name": "xxx",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "antd": "^3.8.0",
    "antd-scss-theme-plugin": "^1.0.7",
    "connected-react-router": "^4.3.0",
    "history": "^4.7.2",
    "material-icons-react": "^1.0.2",
    "node-sass-chokidar": "^1.3.3",
    "npm-run-all": "^4.1.3",
    "prop-types": "^15.6.2",
    "react": "^16.4.2",
    "react-app-rewired": "^1.5.2",
    "react-dom": "^16.4.2",
    "react-redux": "^5.0.7",
    "react-router": "^4.3.1",
    "react-router-dom": "^4.3.1",
    "react-router-prop-types": "^1.0.4",
    "react-scripts": "1.1.4",
    "recompose": "^0.27.1",
    "redux": "^4.0.0",
    "redux-thunk": "^2.3.0"
  },
  "devDependencies": {
    "babel-cli": "^6.26.0",
    "babel-plugin-import": "^1.8.0",
    "babel-plugin-transform-class-properties": "^6.24.1",
    "babel-plugin-transform-object-rest-spread": "^6.26.0",
    "babel-preset-env": "^1.7.0",
    "eslint": "^4.19.1",
    "eslint-config-airbnb": "^17.0.0",
    "eslint-config-prettier": "^2.9.0",
    "eslint-plugin-import": "^2.13.0",
    "eslint-plugin-jsx-a11y": "^6.1.1",
    "eslint-plugin-react": "^7.10.0",
    "eslint-plugin-react-redux": "^2.3.0",
    "prettier": "^1.14.0"
  },
  "scripts": {
    "build-css": "node-sass-chokidar src/ -o src/",
    "watch-css": "npm run build-css && node-sass-chokidar src/ -o src/ --watch --recursive",
    "start-js": "react-app-rewired start",
    "start": "npm-run-all -p watch-css start-js",
    "build-js": "react-app-rewired build",
    "build": "npm-run-all build-css build-js",
    "test": "react-app-rewired test --env=jsdom",
    "eject": "react-scripts eject",
    "format": "prettier --write \"src/**/*.js\"",
    "lint": "eslint ."
  }
}

Thanks for all your future answers ;) !

Body:
I have my old project running with SASS, CRA, and Antd using below config setup. But If you go to official Antd website, they have now an updated tutorial for configuring Antd with Create React App. But in any case, what they have explained is its usage with less and not sass, so to use sass in your project you have to combine both CRA sass setup and Antd theme customization to make things work.

Here's a sample from my project where I used the less plugin to update/customize Antd theme. You should create a custom-override.js file in the root directory of your project and add these lines of code

const { override, fixBabelImports, addLessLoader } = require('customize-cra');
// you can also use craco instead of customize-cra,
// which is now the most updated way in their current docs.

module.exports = override(
  fixBabelImports('import', {
    libraryName: 'antd',
    libraryDirectory: 'es',
    style: true,
  }),

  addLessLoader({
    javascriptEnabled: true,
    modifyVars: {
      '@primary-color': '#6237a0',
      '@link-color': '#6237a0',
      '@success-color': '#0ea70e',
      '@steps-nav-arrow-color': '#d1cdd6',
    },
  }),
);

Then you just need to work with scss the normal way as you would do in sass based CRA project.

To use Sass, first install node-sass:

npm install node-sass --save
# or
yarn add node-sass

Then just update your code and rename App.css to App.scss and import the same in the main(app.js) file. You can even extend the code by doing sass imports/defining variables etc ( all things that you can do with sass).

Here's a snapshot of my app.scss where all my styles are defined in the styles folder.

/*
Variable definition
*/
@import 'styles/variable';

/*
common style import
*/
@import 'styles/common';

/**
*
# # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # #       Components styles import    # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # #
*
* below I do imports for all my routes and components.
*/

@import 'styles/dashboard';
@import 'styles/details';


答: set .levelOne {width:100%} ,if im not misunderstanding you.</p>

Title: Flex child of child does not expand to 100%

Body:
In CSS, if a child of a child is set to width: 100% and the wrapping div has display: flex set, the content does not expand to 100% it only uses the space of the content.

How would one make it expand to the size the grandchild sets itself but still use flex?

flex-grow is probably not the answer since this will always expand to take up the full space and not respect the size the grandchild sets itself.

See following example:

.wrapperFlex, .wrapperBlock{
  border: 1px solid silver;
}

.wrapperFlex {
  display: flex;
}

.levelOne {
}

.levelOneGrow {
  flex-grow: 1;
}

.levelTwo, .levelTwoFullWidth {
  color: white;
  background-color: blue;
}

.levelTwoFullWidth {
  width: 100%;
}

.levelOnePassthrough{
  display: contents;
}

PRE

      WRAPPER FLEX

AFTER

PRE

      WRAPPER FLEX GROW

AFTER

PRE

      WRAPPER FLEX PASSTHROUGH

AFTER


问:
What AWS instance type to pick for nodes in K8s
We are moving our app to Kubernetes, to run on AWS/EC2. The nodes will run various type of apps: Nginx, Postgres, Hadoop, Django,celery.

What do you think is a good/valuable type of instance for this ? Or should we pick different instances for different pods/apps ?

答:
What kind of instances you should pick up depends on many different factors. Amazon EC2 provides a wide selection of instance types optimized to fit different use cases. Instance types comprise varying combinations of CPU, memory, storage, and networking capacity and give you the flexibility to choose the appropriate mix of resources for your applications. Each instance type includes one or more instance sizes, allowing you to scale your resources to the requirements of your target workload.

In context of CPU and memory utilization of course bigger is better than smaller but of course prices will be higher.

To see visible results and graphs to compare performance of specific EC2 instance  Metricly can help you make that decision. In this article are topics, which discusses the considerations that you need to take into account with EC2 instance type selection, as well as how to measure those aspects and the impact those choices have on cost.

Here you can find differences between some of instances and their specification: ec2-nstance-types.


问:
Jest has detected the following 2 open handles potentially keeping Jest from exiting:
I am new to testing. I am using JEST to test my nodejs API's. When i am writing all the tests in one file its running properly without any error but when i am separating it its giving me port is already under use As for each file its running different node instance.

Both the files i am writing this to test

```<code>const supertest = require('supertest');
const app = require('../index');
describe('API Testing for APIs', () => {
  it('Healthcheck endpoint', async () => {
    const response = await supertest(app).get('/healthcheck');
    expect(response.status).toBe(200);
    expect(response.body.status).toBe('ok');
  });
});
</code>```

How i can separate my test in different files to organise my tests in better way or is there anyway to organise test files.

PS - please suggest what are the best practises to write NodeJS api tests.

答:
When you use Express with Jest and Supertest, you need to separate in two different files your Express application definition and the application listen. Supertest doesn't run on any port. It simulates an HTTP request response to your Express application. It'll be something like this:

File: app.js

```<code>const express = require('express');
const app = express();

app.get('/healthcheck', (req, res) => {
    res.json({msg: 'Hello!'});
};

module.exports = app;
</code>```

File: index.js

```<code>const app = require('./app');
app.listen(3000);
</code>```

File: index.test.js

```<code>const request = require('supertest');
const app = require('./app');

test('Health check', async () => {
    const response = await request(app)
        .get('/healthcheck')
        .send()
        .expect(200);

   expect(response.body.msg).toBe('Hello!');
};
</code>```

Body:
I am new to testing. I am using JEST to test my nodejs API's. When i am writing all the tests in one file its running properly without any error but when i am separating it its giving me port is already under use As for each file its running different node instance.

Both the files i am writing this to test

const supertest = require('supertest');
const app = require('../index');
describe('API Testing for APIs', () => {
  it('Healthcheck endpoint', async () => {
    const response = await supertest(app).get('/healthcheck');
    expect(response.status).toBe(200);
    expect(response.body.status).toBe('ok');
  });
});

How i can separate my test in different files to organise my tests in better way or is there anyway to organise test files.

PS - please suggest what are the best practises to write NodeJS api tests.

Body:
When you use Express with Jest and Supertest, you need to separate in two different files your Express application definition and the application listen. Supertest doesn't run on any port. It simulates an HTTP request response to your Express application. It'll be something like this:

File: app.js

const express = require('express');
const app = express();

app.get('/healthcheck', (req, res) => {
    res.json({msg: 'Hello!'});
};

module.exports = app;

File: index.js

const app = require('./app');
app.listen(3000);

File: index.test.js

const request = require('supertest');
const app = require('./app');

test('Health check', async () => {
    const response = await request(app)
        .get('/healthcheck')
        .send()
        .expect(200);

   expect(response.body.msg).toBe('Hello!');
};


问:
mvc 3 nested objects binding
I am very new to MVC 3 so this could be an easy one. I have a viewmodel with a nested object like this:

```<code> public class EventViewModel
 {
    public Event Event { get; set; }
 }

 public class Event
 {
    [Required]
    public int Id { get; set; }

    public string Title { get; set; }
 }
</code>```

In my 'create' view I do something like this:

```<code>@model EventViewModel
@Html.EditorFor(model => model.Event.Title)
</code>```

Here's the code form my event controller:

```<code>public class EventController : Controller
{

  [HttpPost]
  public ActionResult Create(EventViewModel @event)
  {
    ...
  }
}
</code>```

This editor is inside of form tag. When i postback to my controller the title of the event is null instead of what i entered in the form. Do I need some kind of custom binder? Am I doing something unconventional when I use nested objects in my viewmodel?

答:
Changing the name of my nested class to TheEvent fixed the problem somehow...this is what my viewmodel looks like now..</p>

```<code>public class EventViewModel
{
    public Event TheEvent { get; set; }
}
</code>```

Title: mvc 3 nested objects binding

Body:
I am very new to MVC 3 so this could be an easy one. I have a viewmodel with a nested object like this:

 public class EventViewModel
 {
    public Event Event { get; set; }
 }

 public class Event
 {
    [Required]
    public int Id { get; set; }

    public string Title { get; set; }
 }

In my 'create' view I do something like this:

@model EventViewModel
@Html.EditorFor(model => model.Event.Title)

Here's the code form my event controller:

public class EventController : Controller
{

  [HttpPost]
  public ActionResult Create(EventViewModel @event)
  {
    ...
  }
}

This editor is inside of form tag. When i postback to my controller the title of the event is null instead of what i entered in the form. Do I need some kind of custom binder? Am I doing something unconventional when I use nested objects in my viewmodel?

Body:
Changing the name of my nested class to TheEvent fixed the problem somehow...this is what my viewmodel looks like now..

public class EventViewModel
{
    public Event TheEvent { get; set; }
}