问:
ERROR: failed to validate image tag(s): could not parse reference: docker.io/library/projectName:0.0.1-SNAPSHOT
I was getting ERROR: failed to validate image tag(s): could not parse reference: docker.io/library/projectName:0.0.1-SNAPSHOT while building the docker image.

I am using "spotify" maven dependency in the SpringBoot project.

```<code><plugin>
    <groupId>com.spotify</groupId>
    <artifactId>dockerfile-maven-plugin</artifactId>
    <version>1.4.9</version>
    <configuration>
        <repository>${project.artifactId}</repository>
    </configuration>
</plugin>
</code>```

After running a few Google queries, it seems I am the only one getting this issue.

The confluence URL in below stack trace just says it's "uncatched runtime exceptions".

Stack trace:

```<code>[INFO]  > Running creator
[INFO]     [creator]     ERROR: failed to validate image tag(s): could not parse reference: docker.io/library/projectName:0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  33.479 s
[INFO] Finished at: 2020-06-02T05:33:13+05:30
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.springframework.boot:spring-boot-maven-plugin:2.3.0.RELEASE:build-image (default-cli) on project projectName: Execution default-cli of goal org.springframework.boot:spring-boot-maven-plugin:2.3.0.RELEASE:build-image failed: Builder lifecycle 'creator' failed with status code 3 -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.springframework.boot:spring-boot-maven-plugin:2.3.0.RELEASE:build-image (default-cli) on project projectName: Execution default-cli of goal org.springframework.boot:spring-boot-maven-plugin:2.3.0.RELEASE:build-image failed: Builder lifecycle 'creator' failed with status code 3
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:215)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
    at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
    at org.apache.maven.cli.MavenCli.execute (MavenCli.java:957)
    at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:289)
    at org.apache.maven.cli.MavenCli.main (MavenCli.java:193)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:566)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:282)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:225)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:406)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:347)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:566)
    at org.apache.maven.wrapper.BootstrapMainStarter.start (BootstrapMainStarter.java:39)
    at org.apache.maven.wrapper.WrapperExecutor.execute (WrapperExecutor.java:122)
    at org.apache.maven.wrapper.MavenWrapperMain.main (MavenWrapperMain.java:61)
Caused by: org.apache.maven.plugin.PluginExecutionException: Execution default-cli of goal org.springframework.boot:spring-boot-maven-plugin:2.3.0.RELEASE:build-image failed: Builder lifecycle 'creator' failed with status code 3
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo (DefaultBuildPluginManager.java:148)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:210)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
    at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
    at org.apache.maven.cli.MavenCli.execute (MavenCli.java:957)
    at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:289)
    at org.apache.maven.cli.MavenCli.main (MavenCli.java:193)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:566)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:282)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:225)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:406)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:347)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:566)
    at org.apache.maven.wrapper.BootstrapMainStarter.start (BootstrapMainStarter.java:39)
    at org.apache.maven.wrapper.WrapperExecutor.execute (WrapperExecutor.java:122)
    at org.apache.maven.wrapper.MavenWrapperMain.main (MavenWrapperMain.java:61)
Caused by: org.springframework.boot.buildpack.platform.build.BuilderException: Builder lifecycle 'creator' failed with status code 3
    at org.springframework.boot.buildpack.platform.build.Lifecycle.run (Lifecycle.java:157)
    at org.springframework.boot.buildpack.platform.build.Lifecycle.execute (Lifecycle.java:118)
    at org.springframework.boot.buildpack.platform.build.Builder.executeLifecycle (Builder.java:112)
    at org.springframework.boot.buildpack.platform.build.Builder.build (Builder.java:73)
    at org.springframework.boot.maven.BuildImageMojo.buildImage (BuildImageMojo.java:136)
    at org.springframework.boot.maven.BuildImageMojo.execute (BuildImageMojo.java:128)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo (DefaultBuildPluginManager.java:137)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:210)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
    at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
    at org.apache.maven.cli.MavenCli.execute (MavenCli.java:957)
    at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:289)
    at org.apache.maven.cli.MavenCli.main (MavenCli.java:193)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:566)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:282)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:225)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:406)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:347)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:566)
    at org.apache.maven.wrapper.BootstrapMainStarter.start (BootstrapMainStarter.java:39)
    at org.apache.maven.wrapper.WrapperExecutor.execute (WrapperExecutor.java:122)
    at org.apache.maven.wrapper.MavenWrapperMain.main (MavenWrapperMain.java:61)
[ERROR]
[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/PluginExecutionException
</code>```

答:
Issue explanation:

The issue is with the name of the project. When docker says "could not parse reference" then it means the name of the docker file. Also, it "failed to validate image tag(s)" because initially, it was not able to parse the image.

Solution:

For some reason or probably it's by design, docker can not parse the image name if there are characters in Capital letter.

I just had to change the artifactId in my maven.xml file
<artifactId>projectName</artifactId> to <artifactId>projectname</artifactId>

Body:
I was getting ERROR: failed to validate image tag(s): could not parse reference: docker.io/library/projectName:0.0.1-SNAPSHOT while building the docker image.

I am using "spotify" maven dependency in the SpringBoot project.

<plugin>
    <groupId>com.spotify</groupId>
    <artifactId>dockerfile-maven-plugin</artifactId>
    <version>1.4.9</version>
    <configuration>
        <repository>${project.artifactId}</repository>
    </configuration>
</plugin>

After running a few Google queries, it seems I am the only one getting this issue.

The confluence URL in below stack trace just says it's "uncatched runtime exceptions".

Stack trace:

[INFO]  > Running creator
[INFO]     [creator]     ERROR: failed to validate image tag(s): could not parse reference: docker.io/library/projectName:0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  33.479 s
[INFO] Finished at: 2020-06-02T05:33:13+05:30
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.springframework.boot:spring-boot-maven-plugin:2.3.0.RELEASE:build-image (default-cli) on project projectName: Execution default-cli of goal org.springframework.boot:spring-boot-maven-plugin:2.3.0.RELEASE:build-image failed: Builder lifecycle 'creator' failed with status code 3 -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.springframework.boot:spring-boot-maven-plugin:2.3.0.RELEASE:build-image (default-cli) on project projectName: Execution default-cli of goal org.springframework.boot:spring-boot-maven-plugin:2.3.0.RELEASE:build-image failed: Builder lifecycle 'creator' failed with status code 3
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:215)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
    at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
    at org.apache.maven.cli.MavenCli.execute (MavenCli.java:957)
    at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:289)
    at org.apache.maven.cli.MavenCli.main (MavenCli.java:193)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:566)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:282)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:225)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:406)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:347)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:566)
    at org.apache.maven.wrapper.BootstrapMainStarter.start (BootstrapMainStarter.java:39)
    at org.apache.maven.wrapper.WrapperExecutor.execute (WrapperExecutor.java:122)
    at org.apache.maven.wrapper.MavenWrapperMain.main (MavenWrapperMain.java:61)
Caused by: org.apache.maven.plugin.PluginExecutionException: Execution default-cli of goal org.springframework.boot:spring-boot-maven-plugin:2.3.0.RELEASE:build-image failed: Builder lifecycle 'creator' failed with status code 3
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo (DefaultBuildPluginManager.java:148)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:210)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
    at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
    at org.apache.maven.cli.MavenCli.execute (MavenCli.java:957)
    at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:289)
    at org.apache.maven.cli.MavenCli.main (MavenCli.java:193)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:566)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:282)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:225)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:406)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:347)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:566)
    at org.apache.maven.wrapper.BootstrapMainStarter.start (BootstrapMainStarter.java:39)
    at org.apache.maven.wrapper.WrapperExecutor.execute (WrapperExecutor.java:122)
    at org.apache.maven.wrapper.MavenWrapperMain.main (MavenWrapperMain.java:61)
Caused by: org.springframework.boot.buildpack.platform.build.BuilderException: Builder lifecycle 'creator' failed with status code 3
    at org.springframework.boot.buildpack.platform.build.Lifecycle.run (Lifecycle.java:157)
    at org.springframework.boot.buildpack.platform.build.Lifecycle.execute (Lifecycle.java:118)
    at org.springframework.boot.buildpack.platform.build.Builder.executeLifecycle (Builder.java:112)
    at org.springframework.boot.buildpack.platform.build.Builder.build (Builder.java:73)
    at org.springframework.boot.maven.BuildImageMojo.buildImage (BuildImageMojo.java:136)
    at org.springframework.boot.maven.BuildImageMojo.execute (BuildImageMojo.java:128)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo (DefaultBuildPluginManager.java:137)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:210)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
    at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
    at org.apache.maven.cli.MavenCli.execute (MavenCli.java:957)
    at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:289)
    at org.apache.maven.cli.MavenCli.main (MavenCli.java:193)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:566)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:282)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:225)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:406)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:347)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:566)
    at org.apache.maven.wrapper.BootstrapMainStarter.start (BootstrapMainStarter.java:39)
    at org.apache.maven.wrapper.WrapperExecutor.execute (WrapperExecutor.java:122)
    at org.apache.maven.wrapper.MavenWrapperMain.main (MavenWrapperMain.java:61)
[ERROR]
[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/PluginExecutionException


来源: stackexchange

问:
I want to copy only the last one of the text in the input box using js or jquery
The logic for copying the value of the input box when clicking the input box is as follows.

<input type="text" value="{{p.filename}}" id="file_{{p.id}}" size=100 onclick="copy_for_file_name({{p.id}})">

function copy_for_file_name(id){
    var copyText = document.getElementById("file_"+id);
    copyText.select();
    copyText.setSelectionRange(0, 99999); /*For mobile devices*/
    document.execCommand("copy");
    // alert("copy is completed")
}
```

<p>At this time, if the value of the input box is </p>

```challenge/templates/challenge/challenge_list.html
```

Can the code be modified so that only challenge_list.html is copied
when the onclick event is executed?

答:
If you want to copy only the filename (without the directory name), try using the following code:

var fileName = ((filePath.lastIndexOf("/")+1)<filePath.length)?(filePath.substr(filePath.lastIndexOf("/")+1)):filePath
```

<p>It uses the last index of a forward slash to construct a substring (starting at the character after the last slash, to the end of the string). If there aren't any slashes, it returns the original string.</p>

<h3>How to use:</h3>

<p>Just set <code>filePath</code> to the path you want to modify, and it sets <code>fileName</code> to the resulting filename. It's one line, and it can be placed anywhere in your code.</p>

<h3>Function version:</h3>

<pre class="lang-js prettyprint-override"><code>var getFilename = function (path) {return (((path.lastIndexOf("/")+1)<path.length)?(path.substr(path.lastIndexOf("/")+1)):path)}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
The logic for copying the value of the input box when clicking the input box is as follows.

<input type="text" value="{{p.filename}}" id="file_{{p.id}}" size=100 onclick="copy_for_file_name({{p.id}})">

function copy_for_file_name(id){
    var copyText = document.getElementById("file_"+id);
    copyText.select();
    copyText.setSelectionRange(0, 99999); /*For mobile devices*/
    document.execCommand("copy");
    // alert("copy is completed")
}

At this time, if the value of the input box is

challenge/templates/challenge/challenge_list.html

Can the code be modified so that only challenge_list.html is copied
when the onclick event is executed?

Body:
If you want to copy only the filename (without the directory name), try using the following code:

var fileName = ((filePath.lastIndexOf("/")+1)<filePath.length)?(filePath.substr(filePath.lastIndexOf("/")+1)):filePath

It uses the last index of a forward slash to construct a substring (starting at the character after the last slash, to the end of the string). If there aren't any slashes, it returns the original string.

How to use:

Just set filePath to the path you want to modify, and it sets fileName to the resulting filename. It's one line, and it can be placed anywhere in your code.

Function version:

var getFilename = function (path) {return (((path.lastIndexOf("/")+1)<path.length)?(path.substr(path.lastIndexOf("/")+1)):path)}


问:
Errors while trying to upgrade MySQL server from 5.7 to 8.0 on Ubuntu 18.04
I don't know if I am not doing something correctly or if some flaw is occurring that I can't see. Below are the steps I am taking to try to set up the server but I must be missing something.

1)Add APT repository:

$ wget https://repo.mysql.com//mysql-apt-config_0.8.14-1_all.deb

$ sudo dpkg -i mysql-apt-config_0.8.14-1_all.deb

2)Configuring mysql-apt-config screen

Select MySQL server & cluster (Currently selected: mysql 8.0)

Select mysql-8.0 as the server version to be received

Finally, select ok

3)Updating and installing MySQL server

$ sudo apt-get update

$ sudo apt-get install mysql-server

When I do this the following shows:

The errors I am getting

I enter the command "mysql -u root -p" and enter my password. The terminal displays the error 2002 (HY000): can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2). I search for the sock using the command "sudo find / -type s" and the socket doesn't show up in the list. Through files and terminal, I navigate to the directory '/var/run/mysqld' and would expect to find some files, but nothing shows up there. So far I have tried to completely uninstall mysql from my machine and reinstall but get the same result. Otherwise, Ubuntu has been upgraded and updated and I have MySQL Workbench 8.0.20.

答:
I managed to get everything working correctly. I was able to make the installation but ended up possibly losing my database so I will have to just recreate it.

This source was very helpful:

https://unix.stackexchange.com/questions/389747/error-processing-package-mysql-community-server-during-apt-get-upgrade


问:
question on wether a specific function exists in godot 3.2
i was wondering if there's a function in godot that allows we to see where in the screen or specifically in what cardinal direction based on the screen the cursor is in. i was wondering if such a function exists as i'm currently creating a 2d isometric game similar to ROTMG/realm of the mad god and i would like to know how i could make the sprite of the player change based on what cardinal direction/part of the screen the cursor is located. In short i'm inquiring if there's a function in godot that locates the cursor and tells me where it is located through cardinal directions i.e. northeast part of the screen</p>

答:
If your sprite is a Node2D, you can use get_local_mouse_position() in the script attached to your sprite to check where the mouse position is relative to it.

From there, you can find the angle using angle_to_point(mouse_position) with the sprite's position and mouse position.


问:
Need explanation for C++ code
```<code>namespace Stack {
  struct Rep; // definition of stack layout is elsewhere
  typedef Rep& stack;
  stack create(); // make a new stack
  void destroy(stack s); // delete s
  void push(stack s, char c); // push c onto s
  char pop(stack s); // pop s
}
</code>```

This is in the "A Tour of C++" Unit, before even the basic material like functions, loops, and fundamental datatypes...I don't know if/how I'm supposed to understand this code or not.

Anyway, can someone please explain it? It's supposed to be part of an explanation on how to "define a stack manager with an interface"

For starters, I specifically don't know what "typedef Rep& stack" means.

答: typedef Rep& stack means that in namespace Stack if you use stack it would mean its type is Rep&. It is like assigning a type to a word.

ContentLicense: CC BY-SA 3.0

Title: Need explanation for C++ code

Body:
namespace Stack {
  struct Rep; // definition of stack layout is elsewhere
  typedef Rep& stack;
  stack create(); // make a new stack
  void destroy(stack s); // delete s
  void push(stack s, char c); // push c onto s
  char pop(stack s); // pop s
}

This is in the "A Tour of C++" Unit, before even the basic material like functions, loops, and fundamental datatypes...I don't know if/how I'm supposed to understand this code or not.

Anyway, can someone please explain it? It's supposed to be part of an explanation on how to "define a stack manager with an interface"

For starters, I specifically don't know what "typedef Rep& stack" means.


问:
Copying based on cell color does not work using VBA in excel
I am trying to copy rows based on the cell color to a different sheet in excel.
My code is below. But it's not copying. What am I doing wrong?

`

```<code>Sub Button1_Click()

a = Worksheets("Sheet1").Cells(Rows.Count, 1).End(xlUp).Row

For i = 2 To a

    If Worksheets("Sheet1").Cells(i, 2).Interior.Color = RGB(255, 0, 0) Then

        Worksheets("Sheet1").Rows(i).Copy

        Worksheets("Sheet2").Activate

        b = Worksheets("Sheet2").Cells(Rows.Count, 1).End(xlUp).Row

        Worksheets("Sheet2").Cells(b + 1, 1).Select

        ActiveSheet.Paste

        Worksheets("Sheet1").Activate

    End If

Next

Application.CutCopyMode = False

ThisWorkbook.Worksheets("Sheet1").Cells(1, 1).Select

End Sub
</code>```

`

答:
From your previous question, I'm guessing you are working with conditional formatting.

In that case, you have to use Range.DisplayFormat.Interior.Color.

```<code>If Worksheets("Sheet1").Cells(i, 2).DisplayFormat.Interior.Color = RGB(255, 0, 0) Then
</code>```

Note that you should also avoid Select and Activate.

Body:
I am trying to copy rows based on the cell color to a different sheet in excel.
My code is below. But it's not copying. What am I doing wrong?

`

Sub Button1_Click()

a = Worksheets("Sheet1").Cells(Rows.Count, 1).End(xlUp).Row

For i = 2 To a

    If Worksheets("Sheet1").Cells(i, 2).Interior.Color = RGB(255, 0, 0) Then

        Worksheets("Sheet1").Rows(i).Copy

        Worksheets("Sheet2").Activate

        b = Worksheets("Sheet2").Cells(Rows.Count, 1).End(xlUp).Row

        Worksheets("Sheet2").Cells(b + 1, 1).Select

        ActiveSheet.Paste

        Worksheets("Sheet1").Activate

    End If

Next

Application.CutCopyMode = False

ThisWorkbook.Worksheets("Sheet1").Cells(1, 1).Select

End Sub

`

Body:
From your previous question, I'm guessing you are working with conditional formatting.

In that case, you have to use Range.DisplayFormat.Interior.Color.

If Worksheets("Sheet1").Cells(i, 2).DisplayFormat.Interior.Color = RGB(255, 0, 0) Then

Note that you should also avoid Select and Activate.


问:
How to merge two arrays of objects by key
I have two json files. One with the name of the States, its abbreviation and an ID ("Estados.json"). The other one i have multiple objects with ID, city names and a corresponding State code ("Cidades.json"). What i'm trying to do is to merge both arrays based, getting, for each state, all its corresponding cities under a new key.

The expected output is something like this:

```<code>[{
"ID": "1",
"Sigla": "AC",
"Nome": "Acre"
"Cidades":
    {
    "ID": 79,
    "Nome": "Acrelândia",
    "Estado": "1"},
    {
     "ID": "80",
     "Nome": "Assis Brasil",
     "Estado": "1"},

      ...,

      {all the objects that have the same "Estado" key value 1}

      }]
</code>```

Link to the both json files: https://github.com/felipefdl/cidades-estados-brasil-json

答:
Here we are the using map method and Object.assign method to merge the array of objects by using id.</p>

```<code>function mergeArrayObjects(arr1,arr2){
   return arr1.map((item,i)=>{
       if(item.id === arr2[i].id){
           //merging two objects
           return Object.assign({},item,arr2[i])
       }
   })
}
</code>```

Body:
I have two json files. One with the name of the States, its abbreviation and an ID ("Estados.json"). The other one i have multiple objects with ID, city names and a corresponding State code ("Cidades.json"). What i'm trying to do is to merge both arrays based, getting, for each state, all its corresponding cities under a new key.

The expected output is something like this:

[{
"ID": "1",
"Sigla": "AC",
"Nome": "Acre"
"Cidades":
    {
    "ID": 79,
    "Nome": "Acrelândia",
    "Estado": "1"},
    {
     "ID": "80",
     "Nome": "Assis Brasil",
     "Estado": "1"},

      ...,

      {all the objects that have the same "Estado" key value 1}

      }]

Link to the both json files: https://github.com/felipefdl/cidades-estados-brasil-json

Body:
Here we are the using map method and Object.assign method to merge the array of objects by using id.

function mergeArrayObjects(arr1,arr2){
   return arr1.map((item,i)=>{
       if(item.id === arr2[i].id){
           //merging two objects
           return Object.assign({},item,arr2[i])
       }
   })
}


问:
2d histogram: Get result of full nbins x nbins
I am using matplotlib's hist2d function to make a 2d histogram of data that I have, however I am having trouble interpreting the result.

Here is the plot I have:

This was created using the line:

```<code>hist = plt.hist2d(X, Y, (160,160), norm=mpl.colors.LogNorm(vmin=1, vmax=20))
</code>```

This returns a 2d array of (160, 160), as well as the bin edges etc.

In the plot there are bins which have a high frequency of values (yellow bins). I would like to be able to get the results of this histogram and filter out the bins that have low values, preserving the high bins. But I would expect there to be 160*160 values, but I can only find 160 X and 160 Y values.

What I would like to do is essentially filter out the more dense data from the less dense data. If this means representing the data as a single value (a bin), then that is ok.

Am I misinterpreting the function or am I not accessing the data results correctly? I have tried with spicy also but the results seem to be in the same or similar format.

答:
You need Seaborn package.

You mentioned

I would like to be able to get the results of this histogram and filter out the bins that have low values, preserving the high bins.

You should definitely be using one of those:

seaborn.joinplot(...,kind='hex') : it shows the counts of observations that fall within hexagonal bins. This plot works best with relatively large dataset.

seaborn.joinplot(...,kind='kde') : use the kernel density estimation to visualize a bivariate distribution. I recommed it better.

Example 'kde'

Use number of levels n_levels and shade_lowest=False to ignore low values.

```<code>import seaborn as sns
import numpy as np
import matplotlib.pylab as plt
x, y = np.random.randn(2, 300)
plt.figure(figsize=(6,5))
sns.kdeplot(x, y, zorder=0, n_levels=6, shade=True, cbar=True,
     shade_lowest=False, cmap='viridis')
</code>```

Body:
I am using matplotlib's hist2d function to make a 2d histogram of data that I have, however I am having trouble interpreting the result.

Here is the plot I have:

This was created using the line:

hist = plt.hist2d(X, Y, (160,160), norm=mpl.colors.LogNorm(vmin=1, vmax=20))

This returns a 2d array of (160, 160), as well as the bin edges etc.

In the plot there are bins which have a high frequency of values (yellow bins). I would like to be able to get the results of this histogram and filter out the bins that have low values, preserving the high bins. But I would expect there to be 160*160 values, but I can only find 160 X and 160 Y values.

What I would like to do is essentially filter out the more dense data from the less dense data. If this means representing the data as a single value (a bin), then that is ok.

Am I misinterpreting the function or am I not accessing the data results correctly? I have tried with spicy also but the results seem to be in the same or similar format.

Body:
You need Seaborn package.

You mentioned

I would like to be able to get the results of this histogram and filter out the bins that have low values, preserving the high bins.

You should definitely be using one of those:

seaborn.joinplot(...,kind='hex') : it shows the counts of observations that fall within hexagonal bins. This plot works best with relatively large dataset.

seaborn.joinplot(...,kind='kde') : use the kernel density estimation to visualize a bivariate distribution. I recommed it better.

Example 'kde'

Use number of levels n_levels and shade_lowest=False to ignore low values.

import seaborn as sns
import numpy as np
import matplotlib.pylab as plt
x, y = np.random.randn(2, 300)
plt.figure(figsize=(6,5))
sns.kdeplot(x, y, zorder=0, n_levels=6, shade=True, cbar=True,
     shade_lowest=False, cmap='viridis')


问:
React: Importing a function and passing states to it not working
Hi new to react,i can't call the function Adder from an other file, I'm receiving an error Invalid hook call. Hooks can only be called inside of the body of a function component...i need to pass states to it and call it how can i do it?

```<code>import React, { useState, useContext } from 'react'
    import {SnacksContext, Snacks} from './Snacks'
    import {Adder} from './adderMethod'
const AddSnack=()=>{
const [snack,setSnacks]=useContext(SnacksContext)

const [{product,price,picture},setValues]=Handler({
    product:"",
    price:"",
    picture:""
})
    return(
        <div>
            <h1>add item:</h1>
            <input name="product" value={product} onChange={setValues} placeholder="name"></input>
            <input name="price"  type="number" value={price}  onChange={setValues} placeholder="price"></input>
            <input name="picture" value={picture}  onChange={setValues} placeholder="image(add images/)"></input>
            <button onClick={()=>Adder(product,price,picture)}>add item</button> /*<--this part is wrong*/

        </div>
    )
}
export default AddSnack
</code>```

Im trying to call the function below from another file

```<code>import React, { useState, useContext } from 'react'
    import {SnacksContext, Snacks} from './Snacks'
    export const Adder=(x,y,z)=>{
        const [snacks,setSnacks]=useContext(SnacksContext)
        setSnacks([...snacks,{product:x,price:y,picture:z}])
    }
</code>```

答:
at Adder, you call the hook useContext. since you call Adder at button on click, you are calling useContext hook outside of component's body. I suggest you tweak your Adder to return the state handler and snacks as the following:

```<code>import React, { useState, useContext } from 'react'
import {SnacksContext, Snacks} from './Snacks'
export const Adder = () => {
  const [snacks,setSnacks] = useContext(SnacksContext)
  const updateSnacks = (x , y, z) => setSnacks([...snacks,{product:x,price:y,picture:z}])
  return [snacks, updateSnacks]
}
</code>```

now at AddSnack component you call your hook at its body  retrieving snacks and updateSnacks:

```<code>import React, { useState, useContext } from 'react'
import { Adder } from './adderMethod'

const AddSnack = () => {
const [snacks, updateSnacks]= Adder()
</code>```

at button now you can call your updateSnacks safety:

```<code><button onClick={() => updateSnacks(product,price,picture)}>add item</button>
</code>```

Body:
Hi new to react,i can't call the function Adder from an other file, I'm receiving an error Invalid hook call. Hooks can only be called inside of the body of a function component...i need to pass states to it and call it how can i do it?

import React, { useState, useContext } from 'react'
    import {SnacksContext, Snacks} from './Snacks'
    import {Adder} from './adderMethod'
const AddSnack=()=>{
const [snack,setSnacks]=useContext(SnacksContext)

const [{product,price,picture},setValues]=Handler({
    product:"",
    price:"",
    picture:""
})
    return(

add item:

            <input name="product" value={product} onChange={setValues} placeholder="name"></input>
            <input name="price"  type="number" value={price}  onChange={setValues} placeholder="price"></input>
            <input name="picture" value={picture}  onChange={setValues} placeholder="image(add images/)"></input>
            <button onClick={()=>Adder(product,price,picture)}>add item</button> /*<--this part is wrong*/

    )
}
export default AddSnack

Im trying to call the function below from another file

import React, { useState, useContext } from 'react'
    import {SnacksContext, Snacks} from './Snacks'
    export const Adder=(x,y,z)=>{
        const [snacks,setSnacks]=useContext(SnacksContext)
        setSnacks([...snacks,{product:x,price:y,picture:z}])
    }

Body:
at Adder, you call the hook useContext. since you call Adder at button on click, you are calling useContext hook outside of component's body. I suggest you tweak your Adder to return the state handler and snacks as the following:

import React, { useState, useContext } from 'react'
import {SnacksContext, Snacks} from './Snacks'
export const Adder = () => {
  const [snacks,setSnacks] = useContext(SnacksContext)
  const updateSnacks = (x , y, z) => setSnacks([...snacks,{product:x,price:y,picture:z}])
  return [snacks, updateSnacks]
}

now at AddSnack component you call your hook at its body  retrieving snacks and updateSnacks:

import React, { useState, useContext } from 'react'
import { Adder } from './adderMethod'

const AddSnack = () => {
const [snacks, updateSnacks]= Adder()

at button now you can call your updateSnacks safety:

<button onClick={() => updateSnacks(product,price,picture)}>add item</button>


问:
Define a new column based on preferences in one set of columns, and available resources in another
I have a dataframe with many columns, of which 7 are relevant here.

```<code>df1=pd.DataFrame({'Shipment ID':[1,2,3,4,5,6],'Pref 1':['UPS','DHL','DHL','ARA','USPS','FED'],'Pref 2':['DHL','','FED','FED','UPS','USPS'],'Pref 3':['FED','','','DHL','ARA',''],'BudgetUPS':[NaN,'No','Yes',NaN,'No','Yes'],'BudgetUSPS':['Yes','Yes','Yes',NaN,'Yes','No'],'BudgetFED':['No','Yes',NaN,'Yes','Yes','No'],'BudgetARA':['Yes',NaN,NaN,NaN,NaN,'Yes'],'BudgetDHL':['No','Yes','Yes',NaN,'Yes','Yes']})
</code>```

The data here represents the top 3 customer preferences for a shipping agent for each of the shipments being generated by an e-commerce site. The Budget columns specify whether the budget for the corresponding shipping agent is available, not available, or unknown (due to query failure).

What I need to generate is a column that picks up the top two (or one, or none) of the preferences for each shipment ID and create entries (column name: Prefnbudget) like "FED UPS", "USPS", "DHL ARA", "None" for each shipment. The purpose of this step is to a) detect if a shipment can be processed with customer preference, and the budget constraint (to prevent deadlocks), b) query the customer with a confirmation.

I would like to make the answer as pythonic as possible. It is certainly easy to do this in a loop over a list ['DHL','UPS','USPS','ARA','FED'], etc. but I want something that is more vectorized, and pithily compact.

答:
I copied your dataframe. Below is one way to implement your task:</p>

```<code># this dictionary maps column name to its index (column count) in the dataframe
dictIndexToCol = {col_name: i for i, col_name in enumerate(df1.columns)}

def getPref(row, dictIdxToCol=dictIndexToCol):
    """ This function takes the preferences and checks whether Budget value is Yes """
    pref1 = row[1]
    pref2 = row[2]
    pref3 = row[3]

    pref_budget = " "
    if len(pref1) > 0:
        if row[dictIdxToCol[f"Budget{pref1}"]] == "Yes":
            pref_budget += pref1 + " "

    if len(pref2) > 0:
        if row[dictIdxToCol[f"Budget{pref2}"]] == "Yes":
            pref_budget += pref2 + " "

    if len(pref3) > 0:
        if row[dictIdxToCol[f"Budget{pref3}"]] == "Yes":
            pref_budget += pref3

    return pref_budget

df1["Prefnbudget"] = df1.apply(lambda row: getPref(row), axis=1)
</code>```

Body:
I have a dataframe with many columns, of which 7 are relevant here.

df1=pd.DataFrame({'Shipment ID':[1,2,3,4,5,6],'Pref 1':['UPS','DHL','DHL','ARA','USPS','FED'],'Pref 2':['DHL','','FED','FED','UPS','USPS'],'Pref 3':['FED','','','DHL','ARA',''],'BudgetUPS':[NaN,'No','Yes',NaN,'No','Yes'],'BudgetUSPS':['Yes','Yes','Yes',NaN,'Yes','No'],'BudgetFED':['No','Yes',NaN,'Yes','Yes','No'],'BudgetARA':['Yes',NaN,NaN,NaN,NaN,'Yes'],'BudgetDHL':['No','Yes','Yes',NaN,'Yes','Yes']})

The data here represents the top 3 customer preferences for a shipping agent for each of the shipments being generated by an e-commerce site. The Budget columns specify whether the budget for the corresponding shipping agent is available, not available, or unknown (due to query failure).

What I need to generate is a column that picks up the top two (or one, or none) of the preferences for each shipment ID and create entries (column name: Prefnbudget) like "FED UPS", "USPS", "DHL ARA", "None" for each shipment. The purpose of this step is to a) detect if a shipment can be processed with customer preference, and the budget constraint (to prevent deadlocks), b) query the customer with a confirmation.

I would like to make the answer as pythonic as possible. It is certainly easy to do this in a loop over a list ['DHL','UPS','USPS','ARA','FED'], etc. but I want something that is more vectorized, and pithily compact.

Body:
I copied your dataframe. Below is one way to implement your task:

# this dictionary maps column name to its index (column count) in the dataframe
dictIndexToCol = {col_name: i for i, col_name in enumerate(df1.columns)}

def getPref(row, dictIdxToCol=dictIndexToCol):
    """ This function takes the preferences and checks whether Budget value is Yes """
    pref1 = row[1]
    pref2 = row[2]
    pref3 = row[3]

    pref_budget = " "
    if len(pref1) > 0:
        if row[dictIdxToCol[f"Budget{pref1}"]] == "Yes":
            pref_budget += pref1 + " "

    if len(pref2) > 0:
        if row[dictIdxToCol[f"Budget{pref2}"]] == "Yes":
            pref_budget += pref2 + " "

    if len(pref3) > 0:
        if row[dictIdxToCol[f"Budget{pref3}"]] == "Yes":
            pref_budget += pref3

    return pref_budget

df1["Prefnbudget"] = df1.apply(lambda row: getPref(row), axis=1)


问:
HTTPClient POST tries to parse a non-JSON response
I'm trying to make a request in Angular and I know that the HTTP response will not be in JSON but in text. However, Angular seems to be expecting a JSON response since the error is the following:

SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse
  () at XMLHttpRequest.c

As well as

Http failure during parsing for http://localhost:9...

This is the post method:

```<code>return this.http.post(this.loginUrl, this.createLoginFormData(username, password), this.httpOptions)
  .pipe(
    tap( // Log the result or error
      data => console.log(data);
      error => console.log(error)
    )
  );
</code>```

and the headers.

```<code>private httpOptions = {

  headers: new HttpHeaders({
    'Accept': 'text/html, application/xhtml+xml, */*',
    'Content-Type': 'application/x-www-form-urlencoded',
    responseType: 'text'
  },

) };
</code>```

I thought that responseType: 'text' would be enough to make Angular expect a non JSON response.

答:
I had the same problem after an angular update due http client was updated to parse the  response as JSON, failing when the response doesn't contains a valid json (i.e a text or a raw html).

To avoid automatic json parsing,  add the header "responseType" as a parameter in the get or post call:

```<code>this.http.get(template,{responseType:'text'})
  .subscribe(result => {

    // result contains the "treated as text content"

    });
</code>```

In general:
If expect a Json result (like in a rest api):

```<code> HttpClient.get(url) // returns Observable Json formatted
</code>```

If text or raw html is expected:

```<code>HttpClient.get(url, {responseType:'text'}) // returns a string Observable
</code>```

If the return type is unexpected (You'll get the headers as well so you can parse your data properly):

```<code>HttpClient.get(url, {observe:response}) //returns Observable<HttpResponse <T>>
</code>```

Body:
I'm trying to make a request in Angular and I know that the HTTP response will not be in JSON but in text. However, Angular seems to be expecting a JSON response since the error is the following:

SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse
  () at XMLHttpRequest.c

As well as

Http failure during parsing for http://localhost:9...

This is the post method:

return this.http.post(this.loginUrl, this.createLoginFormData(username, password), this.httpOptions)
  .pipe(
    tap( // Log the result or error
      data => console.log(data);
      error => console.log(error)
    )
  );

and the headers.

private httpOptions = {

  headers: new HttpHeaders({
    'Accept': 'text/html, application/xhtml+xml, */*',
    'Content-Type': 'application/x-www-form-urlencoded',
    responseType: 'text'
  },

) };

I thought that responseType: 'text' would be enough to make Angular expect a non JSON response.

Body:
I had the same problem after an angular update due http client was updated to parse the  response as JSON, failing when the response doesn't contains a valid json (i.e a text or a raw html).

To avoid automatic json parsing,  add the header "responseType" as a parameter in the get or post call:

this.http.get(template,{responseType:'text'})
  .subscribe(result => {

    // result contains the "treated as text content"

    });

In general:
If expect a Json result (like in a rest api):

 HttpClient.get(url) // returns Observable Json formatted

If text or raw html is expected:

HttpClient.get(url, {responseType:'text'}) // returns a string Observable

If the return type is unexpected (You'll get the headers as well so you can parse your data properly):

HttpClient.get(url, {observe:response}) //returns Observable<HttpResponse <T>>


问:
Microservices + CQRS implementation
I am working on implementing a microservice architecture using the CQRS pattern. I have a working implementation using API Gateway, Lambda and DynamoDB with one exception - the event sourcing.

Event Sourcing has the applications publishing a notification to an event stream that other services in the platform can consume. This notification represents an event that took place as part of the originating HTTP request. For instance, if the user makes a HTTP POST with a complete "check patient into hospital" model then the Lambda will break that apart and publish multiple events in sequential order.

Patient Checked in (includes Patient Id, hospital id + visit id)

Room Assigned (includes room number, + visit id)

Patient tested (includes tested + visit id)

Patient checked-out (visit id)

The intent for this pattern is to provide an audit trail of all events that took place while the patient was in the hospital. This example (not what I'm actually building) would be stored in an event source that can be replayed at any time. If the VisitId was deleted across all services we could just replay the events one at a time, in order, and reproduce an exact copy of the original record. You consider all records immutable to achieve this. Each POST would push into the event source and then land in the database that would pull the data out during a HTTP GET request. It would also have subscribers that would take pieces of this data and do other things - such as a "Visit Survey" service that would listen to the Patient Checked Out event and prep a post-op survey.

I've looked at several AWS services to provide this. I know about Kinesis Data Streams but I don't like the pricing structure nor do I want to deal with shards (no autoscaling). Since my entire platform is built on consumption based pricing (Dynamo, Lambda etc) I want to keep my event source the same way. This makes it easier for me to estimate a per-user cost as I just do math based on estimated requests per month, per user.

I've been using SNS for the stream itself, delivering the notifications, and it's been great. Super fast and not had any major issues while developing it. The issue though is that this is not suitable for a replay store - only delivery of the event messages. For a replay store I thought Kinesis Firehose made a lot of sense... Send it to S3 + SNS at the same time. Turns out SNS isn't a delivery destination available. I can Put to S3 myself and then publish to SNS but that seems like duplicate work in the code base when I can setup an S3 trigger to fire a Lambda and just have another small Lambda that reacts to the Event landing in S3 and do the insert into the DynamoDB. I've seen that this can be much slower though than just publishing through SNS. I'm also not sure about retry policies on the Put event. This simplifies retries though as I can just re-use the code in the triggered Lambda to replay all events in a bucket path.

I could just PutObject and then Publish to SNS within the same HTTP POST Lambda. If the SNS Publish fails though then I now have an object in S3 that was never published. I'd have to write a different Lambda to handle the fixing and publishing. Not the end of the world - either-way I have two Lambdas to deploy. I'm just not sure which way makes more sense in this pattern with AWS services.

Has anyone done something similar and have any recommendations? Am I working my way into a technical hole that will be difficult to manage later? I'm open to other paths as well if I can keep it to a consumption based pricing model. Thanks!

答:
Event Sourcing has the applications publishing a notification to an event stream that other services in the platform can consume.

You'll want to be a little bit careful here -- there are at least two different definitions of "event sourcing" running around.

If you care about event sourcing, in the sense usually coupled with CQRS (Greg Young, et al), then your events are your book of record.  The important complication this introduces is that your service needs to be able to lock the "event stream" when making changes to it (without that lock, you run into "lost edit" scenarios and have to clean up the mess).

So the "pointer to your current changes" needs to live in something that has transactions.  DynamoDB should be fine for this (based on my memory of the event sourcing break out room at re:Invent 2017).  In theory, you could have the lock in dynamo, which contains a pointer to an immutable document stored in S3.  I haven't been able to persuade myself that the trade offs justify the complexity, but as best I can tell there's nothing in that architecture that violates physics and causality.

If your operations team isn't happy with Dynamo, another reasonable option is RDS; choose your preferred relational data engine, deploy an event storage schema to it, and off you go.

As for the pub sub part, I believe you to be on the right track with SNS.  It's the right choice for "fanning out" messages from a publisher to multiple consumers.  Yes, it doesn't support replay, but that's fine -- replay can happen by pulling events from the book of record.  See the later parts of Greg Young's Polyglot Data talk.  Yes, sometimes you will get messages on both the push channel and the pull channel, but that's fine; you already signed up for idempotent message handling when you decided a distributed architecture was a good idea.

Edit

Why the need to store a pointer in DynamoDB?

Because S3 doesn't offer you any locking; which means that on the unhappy path, where two copies of your logic are trying to write different versions of your data, you end up victim to the lost edit problem.

You could manage the situation with optimistic locking - something analogous to HTTP's conditional PUT; but S3 (last time I checked) doesn't support conditional modification.

You could use S3 as an object store for immutable documents, but now you need some mechanism to determine which document in S3 is the "current" one.  If you try to implement that in S3, you run into the same lost edit problem all over again.

So you need a different tool to handle that part of the problem; some tool that is suitable for "state succession".  So DynamoDB fits there.

If you are using DynamoDB for locking, can you also use it for event storage?  I don't have enough laps to feel confident that I know the answer there.  For small problems, I'm mostly confident that the answer is yes.  For large problems...?

Possibly useful discussions:

Rich Hickey; The Language of the System

Kenneth Truyers; Git as a NoSql Database

Title: Microservices + CQRS implementation


问:
How do I find indexes that have statistics_norecompute = ON
I'm looking for a SQL Server 2005 query that will list all the indexes and with their respective STATISTICS_NORECOMPUTE value.  I didn't see any obvious value in sysindexes that corresponds to that value.</p>

答:
The column is no_recompute in sys.stats which says

Every index will have a corresponding statistics row with the same name and ID (sys.indexes.object_id = sys.stats.object_id AND sys.indexes.index_id = sys.stats.stats_id), but not every statistics row has a corresponding index.

So a JOIN between sys.indexes and sys.stats will match the index for you

Reason:

statistics can be for columns or indexes

an index has exactly one statistic.

STATISTICS_NORECOMPUTE applies to the statistic for that index, not the index itself


问:
Mysql [5.6] Innodb select query order by id asc limit 100 is much slower than desc
My table schema looks like this:

```<code>create table myTable (
   id int(11) not null auto_increment,
   name varchar(255) not null,
   PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=894609724 DEFAULT CHARSET=utf8;
</code>```

Total number of the rows are not more than 500. Rows with id < 894609000 are deleted. And does not exist in table

When I do: SELECT * FROM myTable ORDER BY id DESC LIMIT 100; it response time is 50 ms.

But when I do: SELECT * FROM myTable ORDER BY id ASC LIMIT 100; its response time is 10 sec. which is 200 times slower than the reverse order query.

Could anyone please tell me why this kind of behaviour?

EDIT: I did EXPLAIN {query} too, it gives the same result for both the queries.

答:
Please do these 3 statements and provide the results:</p>

```<code>SHOW TABLE STATUS LIKE 'myTable';
OPTIMIZE TABLE myTable;
SHOW TABLE STATUS LIKE 'myTable';
</code>```

Body:
My table schema looks like this:

create table myTable (
   id int(11) not null auto_increment,
   name varchar(255) not null,
   PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=894609724 DEFAULT CHARSET=utf8;

Total number of the rows are not more than 500. Rows with id < 894609000 are deleted. And does not exist in table

When I do: SELECT * FROM myTable ORDER BY id DESC LIMIT 100; it response time is 50 ms.

But when I do: SELECT * FROM myTable ORDER BY id ASC LIMIT 100; its response time is 10 sec. which is 200 times slower than the reverse order query.

Could anyone please tell me why this kind of behaviour?

EDIT: I did EXPLAIN {query} too, it gives the same result for both the queries.

Body:
Please do these 3 statements and provide the results:

SHOW TABLE STATUS LIKE 'myTable';
OPTIMIZE TABLE myTable;
SHOW TABLE STATUS LIKE 'myTable';


问:
Using files for for shared memory IPC
In my application, there is one process which writes data to a file, and then, in response to receiving a request, will send (some) of that data via the network to the requesting process.  The basis of this question is to see if we can speed up communication when both processes happen to be on the same host.  (In my case, the processes are Java, but I think this discussion can apply more broadly.)

There are a few projects out there which use the MappedByteBuffers returned by Java's FileChannel.map() as a way to have shared memory IPC between JVMs on the same host (see Chronicle Queue, Aeron IPC, etc.).

One approach to speeding up same-host communication would be to have my application use one of those technologies to provide the request-response pathway for same-host communication, either in conjunction with the existing mechanism for writing to the data file, or by providing a unified means of both communication and writing to the file.

Another approach would be to allow the requesting process to have direct access to the data file.

I tend to favor the second approach - assuming it would be correct - as it would be easier to implement, and seems more efficient than copying/transmitting a copy of the data for each request (assuming we didn't replace the existing mechanism for writing to the file).

Essentially, I'd like to understanding what exactly occurs when two processes have access to the same file, and use it to communicate, specifically Java (1.8) and Linux (3.10).

From my understanding, it seems like if two processes have the same file open at the same time, the "communication" between them will essentially be via "shared memory".

Note that this question is not concerned with the performance implication of using a MappedByteBuffer or not - it seem highly likely that a using mapped buffers, and the reduction in copying and system calls, will reduce overhead compared to reading and writing the file, but that might require significant changes to the application.

Here is my understanding:

When Linux loads a file from disk, it copies the contents of that file to pages in memory.  That region of memory is called the page cache.  As far as I can tell, it does this regardless of which Java method (FileInputStream.read(), RandomAccessFile.read(), FileChannel.read(), FileChannel.map()) or native method is used to read the file (obseved with "free" and monitoring the "cache" value).

If another process attempts to load the same file (while it is still resident in the cache) the kernel detects this and doesn't need to reload the file.  If the page cache gets full, pages will get evicted  - dirty ones being written back out to the disk.  (Pages also get written back out if there is an explicit flush to disk, and periodically, with a kernel thread).

Having a (large) file already in the cache is a significant performance boost, much more so than the differences based on which Java methods we use to open/read that file.

If a file is loaded using the mmap system call (C) or via FileChannel.map() (Java), essentially the file's pages (in the cache) are loaded directly into the process' address space.  Using other methods to open a file, the file is loaded into pages not in the process' address space, and then the various methods to read/write that file copy some bytes from/to those pages into a buffer in the process' address space.  There is an obvious performance benefit avoiding that copy, but my question isn't concerned with performance.

So in summary, if I understand correctly - while mapping offer a performance advantage, it doesn't seem like it offers any "shared memory" functionality that we don't already get just from the nature of the Linux and the page cache.

So, please let me know where my understanding is off.

Thanks.

答:
Essentially, I'm trying to understand what happens when two processes have the same file open at the same time, and if one could use this to safely and performantly offer communication between to processes.

If you are using regular files using read and write operations (i.e. not memory mapping them) then the two processes do not share any memory.

User-space memory in the Java Buffer objects associated with the file is NOT shared across address spaces.

When a write syscall is made, data is copied from pages in one processes address space to pages in kernel space.  (These could be pages in the page cache.  That is OS specific.)

When a read syscall is made, data is copied from pages in kernel space to pages in the reading processes address space.

It has to be done that way.  If the operating system shared pages associated with the reader and writer processes buffers behind their backs, then that would be an security / information leakage hole:

The reader would be able to see data in the writer's address space that had not yet been written via write(...), and maybe never would be.

The writer would be able to see data that the reader (hypothetically) wrote into its read buffer.

It would not be possible to address the problem by clever use of memory protection because the granularity of memory protection is a page versus the granularity of read(...) and write(...) which is as little as a single byte.

Sure: you can safely use reading and writing files to transfer data between two processes.  But you would need to define a protocol that allows the reader to know how much data the writer has written.  And the reader knowing when the writer has written something could entail polling; e.g. to see if the file has been modified.

If you look at this in terms of just the data copying in the communication "channel"

With memory mapped files you copy (serialize) the data from application heap objects to the mapped buffer, and a second time (deserialize) from the mapped buffer to application heap objects.

With ordinary files there are two additional copies: 1) from the writing processes (non-mapped) buffer to kernel space pages (e.g. in the page cache), 2) from the kernel space pages to the reading processes (non-mapped) buffer.

The article below explains what is going on with conventional read / write and memory mapping.  (It is in the context of copying a file and "zero-copy", but you can ignore that.)

Reference:

Zero Copy I: User-Mode Perspective

Title: Using files for for shared memory IPC


问:
Crash github.com/siralam/LoopingViewPager Android studio
I’m following a tutorial on a basic app. The code has been deprecated, so I worked around it on a single image. But now I’m getting crashes all the time an the activity. I know it’s here because before I started this part the app it worked fine.</p>

```<code>public class MyBestDealsAdapter extends LoopingPagerAdapter<BestDealModel> {

    @BindView(R.id.img_best_deal)
    ImageView img_best_deal;
    @BindView(R.id.txt_best_deals)
    TextView txt_best_deals;

    Unbinder unbinder;

    public MyBestDealsAdapter(Context context, List<BestDealModel> itemList, boolean isInfinite) {
        super(context, itemList, isInfinite);
       // this.context = context;
        //this.BestDealModel= itemList;   **this is what I tried**
    }

    @Override
    protected View inflateView(int viewType, ViewGroup container, int listPosition) {
        return LayoutInflater. **this context for some reason is getting flagged y tried creating Context context and the flagg goes away but still crash** from(context).inflate(R.layout.layout_best_deals_items,container,false);
    }

    @Override
    protected void bindView(View convertView, int listPosition, int viewType) {
        unbinder = ButterKnife.bind(this,convertView);
        //set data
        Glide.with(convertView).load **same here for itemList i tried BestDealModel itemlist flag gone still** crash(itemList.get(listPosition).getImage()).into(img_best_deal);
</code>```

答:
```<code>public class MyBestDealsAdapter extends LoopingPagerAdapter<BestDealModel> {
private final List<BestDealModel> itemList;
private final boolean isInfinite;
private Context context;

@BindView(R.id.img_best_deal)
ImageView img_best_deal;
@BindView(R.id.txt_best_deal)
TextView txt_best_deal;

Unbinder unbinder;

   public MyBestDealsAdapter(Context context,List<BestDealModel> itemList, boolean isInfinite) {
    super(context, itemList, isInfinite);
       this.context = context;
       this.itemList = itemList;
       this.isInfinite = isInfinite;
   }

@Override
protected void bindView(View convertView, int listPosition, int viewType) {
    unbinder = ButterKnife.bind(this,convertView);

    //set data
    Glide.with(convertView).load(itemList.get(listPosition).getimage()).into(img_best_deal);
    txt_best_deal.setText(itemList.get(listPosition).getName());
}

@Override
protected View inflateView(int viewType, ViewGroup container, int listPosition) {
    return LayoutInflater.from(context).inflate(R.layout.layout_best_deal_item, container, false);
}
</code>```

}

this is the solution That worked out

Body:
I’m following a tutorial on a basic app. The code has been deprecated, so I worked around it on a single image. But now I’m getting crashes all the time an the activity. I know it’s here because before I started this part the app it worked fine.

public class MyBestDealsAdapter extends LoopingPagerAdapter<BestDealModel> {

    @BindView(R.id.img_best_deal)
    ImageView img_best_deal;
    @BindView(R.id.txt_best_deals)
    TextView txt_best_deals;

    Unbinder unbinder;

    public MyBestDealsAdapter(Context context, List<BestDealModel> itemList, boolean isInfinite) {
        super(context, itemList, isInfinite);
       // this.context = context;
        //this.BestDealModel= itemList;   **this is what I tried**
    }

    @Override
    protected View inflateView(int viewType, ViewGroup container, int listPosition) {
        return LayoutInflater. **this context for some reason is getting flagged y tried creating Context context and the flagg goes away but still crash** from(context).inflate(R.layout.layout_best_deals_items,container,false);
    }

    @Override
    protected void bindView(View convertView, int listPosition, int viewType) {
        unbinder = ButterKnife.bind(this,convertView);
        //set data
        Glide.with(convertView).load **same here for itemList i tried BestDealModel itemlist flag gone still** crash(itemList.get(listPosition).getImage()).into(img_best_deal);

Body:
public class MyBestDealsAdapter extends LoopingPagerAdapter<BestDealModel> {
private final List<BestDealModel> itemList;
private final boolean isInfinite;
private Context context;

@BindView(R.id.img_best_deal)
ImageView img_best_deal;
@BindView(R.id.txt_best_deal)
TextView txt_best_deal;

Unbinder unbinder;

   public MyBestDealsAdapter(Context context,List<BestDealModel> itemList, boolean isInfinite) {
    super(context, itemList, isInfinite);
       this.context = context;
       this.itemList = itemList;
       this.isInfinite = isInfinite;
   }

@Override
protected void bindView(View convertView, int listPosition, int viewType) {
    unbinder = ButterKnife.bind(this,convertView);

    //set data
    Glide.with(convertView).load(itemList.get(listPosition).getimage()).into(img_best_deal);
    txt_best_deal.setText(itemList.get(listPosition).getName());
}

@Override
protected View inflateView(int viewType, ViewGroup container, int listPosition) {
    return LayoutInflater.from(context).inflate(R.layout.layout_best_deal_item, container, false);
}

}

this is the solution That worked out


答:
const j1 = `https://raw.githubusercontent.com/felipefdl/cidades-estados-brasil-json/master/Estados.json`;
const j2 = `https://raw.githubusercontent.com/felipefdl/cidades-estados-brasil-json/master/Cidades.json`;

(async () => {
  const Estados = await ((await fetch(j1)).json());
  const Cidades = await ((await fetch(j2)).json());

  Estados.forEach(e => {
    e.Cidades = Cidades.filter(c => e.ID === c.Estado);
  });

  console.log(Estados[0]);

  // Estados now contains Cidades
})();```

Title: How to merge two arrays of objects by key


问:
Swipe gestures with QML Stackview
So QML StackView provides a way to navigate back by usin the pop() function. I am looking for a way to go the previous page by simply swiping to the right with UI elements following the fingers of the user (kind of like a SwipeView). How can I achieve this? I have looked around and all I found was this https://github.com/alejoasotelo/SwipePageStackWindow which is an old project that does a similar thing with the old PageStack.

答:
One possible way to do this is to create a custom element called swiper that has a swipeview with 3 pages. 1 and 3 are blank but 2 has content. When page 1 is active, it allows all events to pass through unless a left swipe is detected. Page 2 has a loader So you can change the contents.

If you create two of these on top of each other you can move the one in front of the other whenever you need to switch views. Two loaders means the content will never consume too much memory.

So you'll have a variable isBottomActive

And one method
function pushNewView(view) <- this will move whichever swiper is not active to the front, put the view into it's loader and change currentIndex to 2.

Now if you need to go backwards you just swipe to the right. The swipers view index changes (you can tie a method here to make the old swipeview move back to the bottom with a different view as well)

Title: Swipe gestures with QML Stackview


答:
You're in a namespace called 'Stack', so as to keep all any of the symbols you declare from being global and potentially clashing with other symbols.

struct Rep is a forward declaration that says that there is a type of struct named Rep defined properly somewhere else, and that's the one you'll be referring to even if you don't know exactly what layout it has here.

typedef Rep& stack makes 'stack' a literal synonym of 'Rep &', as Messa has already answered. So everywhere you write 'stack' it's the same as writing 'Rep &'. Rep & means a reference to a struct of type 'Rep'. The size of the reference will be known even without knowing the full definition of Rep so the forward declaration isn't a problem.

The four remaining lines declare functions that, presumably, will perform the operations the names suggest and as mentioned in the comments.

Title: Need explanation for C++ code

Body:
namespace Stack {
  struct Rep; // definition of stack layout is elsewhere
  typedef Rep& stack;
  stack create(); // make a new stack
  void destroy(stack s); // delete s
  void push(stack s, char c); // push c onto s
  char pop(stack s); // pop s
}

This is in the "A Tour of C++" Unit, before even the basic material like functions, loops, and fundamental datatypes...I don't know if/how I'm supposed to understand this code or not.

Anyway, can someone please explain it? It's supposed to be part of an explanation on how to "define a stack manager with an interface"

For starters, I specifically don't know what "typedef Rep& stack" means.


问:
Microsoft Graph API: Getting error "Authorization_IdentityNotFound"
With my outlook.com account I logged in to portal.azure.com and I created a new application. Microsoft has provided a sample app (daemon_console) for quick experiments (in QuickStart guide) and I followed steps provided for the sample app, the app automatically takes the application id and client secret you generated and updates the configuration JSON file (appsettings.json) with this info. I downloaded the code after these steps but when I run the sample app it throws the error "Authorization_IdentityNotFound".

Looks like it is able to fetch the token but following code is throwing the error:

```<code>            var httpClient = new HttpClient();
            var apiCaller = new ProtectedApiCallHelper(httpClient);
            await apiCaller.CallWebApiAndProcessResultASync($"{config.ApiUrl}v1.0/users", result.AccessToken, Display);
</code>```

Microsofts page has step to get Admin consent in two ways:

If you are a global administrator, go to API Permissions page select Grant admin consent for Enter_the_Tenant_Name_Here

Standard user
If you're a standard user of your tenant, then you need to ask a global administrator to grant admin consent for your application. To do this, give the following URL to your administrator:
https://login.microsoftonline.com/common/adminconsent?client_id=my apps client id

I have tried both these options. With the first option, I am able to grant the required permissions. But the issue still exists.

With the second option when I go to the suggested URL it fails with error:
"AADSTS500113: No reply address is registered for the application."

I think this should have been a straightforward process but somehow the app is not able to execute and fails with errors:

```<code> "code": "Authorization_IdentityNotFound",
"message": "The identity of the calling application could not be established.",
</code>```

Please let me know if anyone has tried these steps and has managed to resolve this issue.

Note that I can run "https://graph.microsoft.com/v1.0/users" from graph explorer with my outlook.com account and it works perfectly fine.

答:
I tested it, and at first I was running into the same issue,
its because of the common in the appsettings.json

```<code>replace the   "Tenant": "common"
with   "Tenant": "your Tenant ID",
</code>```

You can get the tenant ID from the overview page of your app registration Directory (tenant) ID. After you do that, make sure you right click the project and click rebuild. because if I just do a normal run it had it cached and did not update it from common.

Body:
With my outlook.com account I logged in to portal.azure.com and I created a new application. Microsoft has provided a sample app (daemon_console) for quick experiments (in QuickStart guide) and I followed steps provided for the sample app, the app automatically takes the application id and client secret you generated and updates the configuration JSON file (appsettings.json) with this info. I downloaded the code after these steps but when I run the sample app it throws the error "Authorization_IdentityNotFound".

Looks like it is able to fetch the token but following code is throwing the error:

            var httpClient = new HttpClient();
            var apiCaller = new ProtectedApiCallHelper(httpClient);
            await apiCaller.CallWebApiAndProcessResultASync($"{config.ApiUrl}v1.0/users", result.AccessToken, Display);

Microsofts page has step to get Admin consent in two ways:

If you are a global administrator, go to API Permissions page select Grant admin consent for Enter_the_Tenant_Name_Here

Standard user
If you're a standard user of your tenant, then you need to ask a global administrator to grant admin consent for your application. To do this, give the following URL to your administrator:
https://login.microsoftonline.com/common/adminconsent?client_id=my apps client id

I have tried both these options. With the first option, I am able to grant the required permissions. But the issue still exists.

With the second option when I go to the suggested URL it fails with error:
"AADSTS500113: No reply address is registered for the application."

I think this should have been a straightforward process but somehow the app is not able to execute and fails with errors:

 "code": "Authorization_IdentityNotFound",
"message": "The identity of the calling application could not be established.",

Please let me know if anyone has tried these steps and has managed to resolve this issue.

Note that I can run "https://graph.microsoft.com/v1.0/users" from graph explorer with my outlook.com account and it works perfectly fine.

Body:
I tested it, and at first I was running into the same issue,
its because of the common in the appsettings.json

replace the   "Tenant": "common"
with   "Tenant": "your Tenant ID",

You can get the tenant ID from the overview page of your app registration Directory (tenant) ID. After you do that, make sure you right click the project and click rebuild. because if I just do a normal run it had it cached and did not update it from common.


问:
Sum cols where row value is equal to header - Pandas
I am trying to sum columns in a pandas df where the column is equal to a specific value. Using the df below, where ['X'] == 'GrV', I want to sum cols ('GrV A', 'GrV B'). But I'm returning nan values.

```<code>import pandas as pd

df = pd.DataFrame({
    'X' : ['GrV', 'GrX', 'GrY', 'GrZ', 'GrV', 'GrX', 'GrY', 'GrZ'],
    'GrV A' : [4, 2, 6, 5, 1, 2, 5, 6],
    'GrX A' : [3, 4, 5, 1, 2, 5, 6, 2],
    'GrY A' : [5, 2, 2, 6, 5, 1, 5, 4],
    'GrZ A' : [1, 2, 5, 5, 2, 1, 5, 4],
    'GrV B' : [4, 2, 6, 5, 1, 2, 5, 6],
    'GrX B' : [3, 4, 5, 1, 2, 5, 6, 2],
    'GrY B' : [5, 2, 2, 6, 5, 1, 5, 4],
    'GrZ B' : [1, 2, 5, 5, 2, 1, 5, 4],
        })

df['Total'] = df.loc[(df['X'] == 'GrV'), ('GrV A', 'GrV B')].sum()
df['Total'] = df.loc[(df['X'] == 'GrX'), ('GrX A', 'GrX B')].sum()
df['Total'] = df.loc[(df['X'] == 'GrY'), ('GrY A', 'GrY B')].sum()
df['Total'] = df.loc[(df['X'] == 'GrZ'), ('GrZ A', 'GrZ B')].sum()
</code>```

Intended Output:

```<code>     X  GrV A  GrX A  GrY A  GrZ A  GrV B  GrX B  GrY B  GrZ B  Total
0  GrV      4      3      5      1      4      3      5      1      8
1  GrX      2      4      2      2      2      4      2      2      8
2  GrY      6      5      2      5      6      5      2      5      4
3  GrZ      5      1      6      5      5      1      6      5     10
4  GrV      1      2      5      2      1      2      5      2      2
5  GrX      2      5      1      1      2      5      1      1     10
6  GrY      5      6      5      5      5      6      5      5     10
7  GrZ      6      2      4      4      6      2      4      4      8
</code>```

答:
Let us try melt with groupby

```<code>s=df.reset_index().melt(['index','X']).loc[lambda x : x['X']==x['variable'].str.split(' ').str[0]].groupby('index').value.sum()
df['new']=s
df
     X  GrV A  GrX A  GrY A  GrZ A  GrV B  GrX B  GrY B  GrZ B  new
0  GrV      4      3      5      1      4      3      5      1    8
1  GrX      2      4      2      2      2      4      2      2    8
2  GrY      6      5      2      5      6      5      2      5    4
3  GrZ      5      1      6      5      5      1      6      5   10
4  GrV      1      2      5      2      1      2      5      2    2
5  GrX      2      5      1      1      2      5      1      1   10
6  GrY      5      6      5      5      5      6      5      5   10
7  GrZ      6      2      4      4      6      2      4      4    8
</code>```

Body:
I am trying to sum columns in a pandas df where the column is equal to a specific value. Using the df below, where ['X'] == 'GrV', I want to sum cols ('GrV A', 'GrV B'). But I'm returning nan values.

import pandas as pd

df = pd.DataFrame({
    'X' : ['GrV', 'GrX', 'GrY', 'GrZ', 'GrV', 'GrX', 'GrY', 'GrZ'],
    'GrV A' : [4, 2, 6, 5, 1, 2, 5, 6],
    'GrX A' : [3, 4, 5, 1, 2, 5, 6, 2],
    'GrY A' : [5, 2, 2, 6, 5, 1, 5, 4],
    'GrZ A' : [1, 2, 5, 5, 2, 1, 5, 4],
    'GrV B' : [4, 2, 6, 5, 1, 2, 5, 6],
    'GrX B' : [3, 4, 5, 1, 2, 5, 6, 2],
    'GrY B' : [5, 2, 2, 6, 5, 1, 5, 4],
    'GrZ B' : [1, 2, 5, 5, 2, 1, 5, 4],
        })

df['Total'] = df.loc[(df['X'] == 'GrV'), ('GrV A', 'GrV B')].sum()
df['Total'] = df.loc[(df['X'] == 'GrX'), ('GrX A', 'GrX B')].sum()
df['Total'] = df.loc[(df['X'] == 'GrY'), ('GrY A', 'GrY B')].sum()
df['Total'] = df.loc[(df['X'] == 'GrZ'), ('GrZ A', 'GrZ B')].sum()

Intended Output:

     X  GrV A  GrX A  GrY A  GrZ A  GrV B  GrX B  GrY B  GrZ B  Total
0  GrV      4      3      5      1      4      3      5      1      8
1  GrX      2      4      2      2      2      4      2      2      8
2  GrY      6      5      2      5      6      5      2      5      4
3  GrZ      5      1      6      5      5      1      6      5     10
4  GrV      1      2      5      2      1      2      5      2      2
5  GrX      2      5      1      1      2      5      1      1     10
6  GrY      5      6      5      5      5      6      5      5     10
7  GrZ      6      2      4      4      6      2      4      4      8

Body:
Let us try melt with groupby

s=df.reset_index().melt(['index','X']).loc[lambda x : x['X']==x['variable'].str.split(' ').str[0]].groupby('index').value.sum()
df['new']=s
df
     X  GrV A  GrX A  GrY A  GrZ A  GrV B  GrX B  GrY B  GrZ B  new
0  GrV      4      3      5      1      4      3      5      1    8
1  GrX      2      4      2      2      2      4      2      2    8
2  GrY      6      5      2      5      6      5      2      5    4
3  GrZ      5      1      6      5      5      1      6      5   10
4  GrV      1      2      5      2      1      2      5      2    2
5  GrX      2      5      1      1      2      5      1      1   10
6  GrY      5      6      5      5      5      6      5      5   10
7  GrZ      6      2      4      4      6      2      4      4    8


问:
How do I read from the terminal in Python?
I just want to use os.system("dir") and also be able to save the text outputted to a variable.  I tried using sys.stdout.read() but running sys.stdout.readable() returns False.  Do you know how I can read from the terminal?

答:
using os library:</p>

```<code>info = os.popen('dir').read()
</code>```

Body:
using os library:

info = os.popen('dir').read()


问:
Sum of an array in which the array is a property of a property in the outer object
```<code>{
    'Edsger W. Dijkstra': [ // o
      { author: 'Edsger W. Dijkstra', likes: 5 },
      { author: 'Edsger W. Dijkstra', likes: 10 }
    ],
    'Benizio Mauritez': [
      { author: 'Benizio Mauritez', likes: 12 },
      { author: 'Benizio Mauritez', likes: 8 }
    ]
  }
</code>```

I have this object which in this case, represents users from a blog in which, I am trying to merge a single author with their total likes already merged, e.g:

```<code>{
    [
        author: Edsger W. Dijkstra,
        likes: 15
    ],
    [
        author: Benizio Mauritez,
        likes: 20
    ],
}
</code>```

How can I do this? I've already trying reducing their props (Got stucked at re-assigning or creating a new prop out of that), tried lodash's sumBy function so if someone can enlight me on how to do this, I would be very much appreciating it!, many thanks
!

答:
I have come with an answer this is how it looks like

```<code>[
  {
    "author": "Edsger W. Dijkstra",
    "likes": 15
  },
  {
    "author": "Benizio Mauritez",
    "likes": 20
  }
]

</code>```

I have provided the explanation in the code segment hopefully it helps.
Basically I have used Object.keys which allows you to use Array higher-order function like * map, reduce, filter...etc*, and then used reduce to add the likes for each user and then finally return the object with the desired data.

Hopefully, this helps

Links to know more about

Object.keys: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

Array.prototype.reduce: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

Array.prototype.map: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

let obj = {
    'Edsger W. Dijkstra': [
      { author: 'Edsger W. Dijkstra', likes: 5 },
      { author: 'Edsger W. Dijkstra', likes: 10 }
    ],
    'Benizio Mauritez': [
      { author: 'Benizio Mauritez', likes: 12 },
      { author: 'Benizio Mauritez', likes: 8 }
    ]
  }

 /*
 1) Using Object.keys helps to traverse all the keys in an Object
 2) Then as the value for the available keys is also array we can use reduce to add the likes
 Note: If you don't know about reduce read the article on MDN https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

 3) As map returns an new array the ans variable will hold an array with returned objects
 */
let ans = Object.keys(obj).map((item)=>{
                        let count=  obj[item].reduce((acc,current)=> acc + current.likes,0);
                        return {'author':item,'likes':count}
                        });

console.log(ans)```

Body:
{
    'Edsger W. Dijkstra': [ // o
      { author: 'Edsger W. Dijkstra', likes: 5 },
      { author: 'Edsger W. Dijkstra', likes: 10 }
    ],
    'Benizio Mauritez': [
      { author: 'Benizio Mauritez', likes: 12 },
      { author: 'Benizio Mauritez', likes: 8 }
    ]
  }

I have this object which in this case, represents users from a blog in which, I am trying to merge a single author with their total likes already merged, e.g:

{
    [
        author: Edsger W. Dijkstra,
        likes: 15
    ],
    [
        author: Benizio Mauritez,
        likes: 20
    ],
}

How can I do this? I've already trying reducing their props (Got stucked at re-assigning or creating a new prop out of that), tried lodash's sumBy function so if someone can enlight me on how to do this, I would be very much appreciating it!, many thanks
!

Body:
I have come with an answer this is how it looks like

[
  {
    "author": "Edsger W. Dijkstra",
    "likes": 15
  },
  {
    "author": "Benizio Mauritez",
    "likes": 20
  }
]

I have provided the explanation in the code segment hopefully it helps.
Basically I have used Object.keys which allows you to use Array higher-order function like * map, reduce, filter...etc*, and then used reduce to add the likes for each user and then finally return the object with the desired data.

Hopefully, this helps

Links to know more about

Object.keys: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

Array.prototype.reduce: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

Array.prototype.map: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

let obj = {
    'Edsger W. Dijkstra': [
      { author: 'Edsger W. Dijkstra', likes: 5 },
      { author: 'Edsger W. Dijkstra', likes: 10 }
    ],
    'Benizio Mauritez': [
      { author: 'Benizio Mauritez', likes: 12 },
      { author: 'Benizio Mauritez', likes: 8 }
    ]
  }

 /*
 1) Using Object.keys helps to traverse all the keys in an Object
 2) Then as the value for the available keys is also array we can use reduce to add the likes
 Note: If you don't know about reduce read the article on MDN https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

 3) As map returns an new array the ans variable will hold an array with returned objects
 */
let ans = Object.keys(obj).map((item)=>{
                        let count=  obj[item].reduce((acc,current)=> acc + current.likes,0);
                        return {'author':item,'likes':count}
                        });

console.log(ans)


问:
how to do lookup and filter data on the same table in Oracle SQL
In SQL, where we need to filter the unnecessary data from a table:

case 1: if 2 IDs are same and DOD is not null then Record is needed

case 2: if single id is there and dod is not null then Record is needed

case 3: if 2 ids are same and if DOD is null for any one of them ,then record is not needed

Your help is much appreciated.

Thanks

答:
You can use analytic functions for this:

```<code>select t.*
from (
    select
        t.*,
        sum(case when dod is null then 1 else 0 end) over(partition by id) no_nulls
    from mytable t
) t
where no_nulls = 0
</code>```

Note that this also excludes records that have no duplicate id but whose dod is null (you did not describe how to handle those).

You could also use not exists (which can conviniently be turned to a delete statement if needed):

```<code>select t.*
from mytable t
where not exists(select 1 from mytable t1 where t1.id = t.id and t1.dod is null)
where no_nulls = 0
</code>```

Body:
You can use analytic functions for this:

select t.*
from (
    select
        t.*,
        sum(case when dod is null then 1 else 0 end) over(partition by id) no_nulls
    from mytable t
) t
where no_nulls = 0

Note that this also excludes records that have no duplicate id but whose dod is null (you did not describe how to handle those).

You could also use not exists (which can conviniently be turned to a delete statement if needed):

select t.*
from mytable t
where not exists(select 1 from mytable t1 where t1.id = t.id and t1.dod is null)
where no_nulls = 0


问:
How to alternate output between two lists?
I am trying to output which card a player gets as the card is being handed out. My idea was to output each card by alternating from the two lists. I have included an example below.

```<code>Ex.
List1 = [Banana,Cherry,Orange,Apple,Tomato]
List2 = [Blue,Red,Orange,Yellow,Grey,Purple]

Output:

    Banana
    Blue
    Cherry
    Red
    Orange
    Yellow...
</code>```

This is what I have so far.

```<code>for card in player_A:
    print("Player A is dealt= ",card,"")
for card in Player_B:
    print("Player B is dealt=",card,"")
</code>```

How can I go about doing that?

答:
You can just do</p>

```<code>for i in range(len(List1)):
    print("Player A is dealt= ", List1[i], "")
    print("Player B is dealt= ", List2[i], "")
</code>```

Body:
I am trying to output which card a player gets as the card is being handed out. My idea was to output each card by alternating from the two lists. I have included an example below.

Ex.
List1 = [Banana,Cherry,Orange,Apple,Tomato]
List2 = [Blue,Red,Orange,Yellow,Grey,Purple]

Output:

    Banana
    Blue
    Cherry
    Red
    Orange
    Yellow...

This is what I have so far.

for card in player_A:
    print("Player A is dealt= ",card,"")
for card in Player_B:
    print("Player B is dealt=",card,"")

How can I go about doing that?

Body:
You can just do

for i in range(len(List1)):
    print("Player A is dealt= ", List1[i], "")
    print("Player B is dealt= ", List2[i], "")


问:
XML Tag grouping in RTF template to calculate totals via nested table not giving formatted output. Extra row in the nested table
My XML Tag generated is as follows-

```<code><P_MONTH>01</P_MONTH>

-<G_1>

<DIVISION>CA Division</DIVISION>

<DISTRICT>CA District</DISTRICT>

<DEPARTMENT>Global Operations</DEPARTMENT>

<DEP_EMPL_COUNT>9</DEP_EMPL_COUNT>

</G_1>

-<G_1>

<DIVISION>CA Division</DIVISION>

<DISTRICT>CA District</DISTRICT>

<DEPARTMENT>Laboratory Services</DEPARTMENT>

<DEP_EMPL_COUNT>11</DEP_EMPL_COUNT>

</G_1>

-<G_1>

<DIVISION>CA Division</DIVISION>

<DISTRICT>CA District</DISTRICT>

<DEPARTMENT>Corporate</DEPARTMENT>

<DEP_EMPL_COUNT>3</DEP_EMPL_COUNT>

</G_1>

-<G_1>

<DIVISION>CA Division</DIVISION>

<DISTRICT>S District</DISTRICT>

<DEPARTMENT>Corporate Administration</DEPARTMENT>
<INTERNAL_ADDRESS_LINE>100-01-000-000-210-99802-000-000000-000000</INTERNAL_ADDRESS_LINE>

<DEP_EMPL_COUNT>6</DEP_EMPL_COUNT>
<SERVICE_LINE>000</SERVICE_LINE>

</G_1>

-<G_1>

<DIVISION>CA Division</DIVISION>

<DISTRICT>S District</DISTRICT>

<DEPARTMENT>Corporate Technology</DEPARTMENT>

<DEP_EMPL_COUNT>1</DEP_EMPL_COUNT>

</G_1>
</code>```

When I am using these tag like below in the RTF template-

```<code>DIVISION                            DISTRICT                    DEPARTMENT                 COUNT
<?for-each:G_1?> <DIVISION>         <DISTRICT>                   <DEPARTMENT>             <COUNT> <?end for-each?>
</code>```

This is giving an output like -

```<code>DIVISION              DISTRICT                          DEPARTMENT                      COUNT
CA Division           CA District                     Global Operations                  9
CA Division           CA District                     Laboratory Services                11
CA Division           CA District                     Corporate                          3
CA Division           S District                      Corporate Administration           6
CA Division           S District                      Corporate Technology               1
</code>```

But I want the grouping to be done in the output and the total calculated as per the grouping of the district and division.
I have used a nested table for that. somewhat like -

But the RTF template is giving me an extra row in the output even though the RTF template formatting is correct-

 what can i use to remove the extra row and perfect the formatting

答: Try this. Click in the whitespace below the table (below Division Total), and pressing on Ctrl + [. This will reduce the font size to smallest. That should reduce the visible space.</p>

Body:
My XML Tag generated is as follows-

<P_MONTH>01</P_MONTH>

-<G_1>

<DIVISION>CA Division</DIVISION>

<DISTRICT>CA District</DISTRICT>

<DEPARTMENT>Global Operations</DEPARTMENT>

<DEP_EMPL_COUNT>9</DEP_EMPL_COUNT>

</G_1>

-<G_1>

<DIVISION>CA Division</DIVISION>

<DISTRICT>CA District</DISTRICT>

<DEPARTMENT>Laboratory Services</DEPARTMENT>

<DEP_EMPL_COUNT>11</DEP_EMPL_COUNT>

</G_1>

-<G_1>

<DIVISION>CA Division</DIVISION>

<DISTRICT>CA District</DISTRICT>

<DEPARTMENT>Corporate</DEPARTMENT>

<DEP_EMPL_COUNT>3</DEP_EMPL_COUNT>

</G_1>

-<G_1>

<DIVISION>CA Division</DIVISION>

<DISTRICT>S District</DISTRICT>

<DEPARTMENT>Corporate Administration</DEPARTMENT>
<INTERNAL_ADDRESS_LINE>100-01-000-000-210-99802-000-000000-000000</INTERNAL_ADDRESS_LINE>

<DEP_EMPL_COUNT>6</DEP_EMPL_COUNT>
<SERVICE_LINE>000</SERVICE_LINE>

</G_1>

-<G_1>

<DIVISION>CA Division</DIVISION>

<DISTRICT>S District</DISTRICT>

<DEPARTMENT>Corporate Technology</DEPARTMENT>

<DEP_EMPL_COUNT>1</DEP_EMPL_COUNT>

</G_1>

When I am using these tag like below in the RTF template-

DIVISION                            DISTRICT                    DEPARTMENT                 COUNT
<?for-each:G_1?> <DIVISION>         <DISTRICT>                   <DEPARTMENT>             <COUNT> <?end for-each?>

This is giving an output like -

DIVISION              DISTRICT                          DEPARTMENT                      COUNT
CA Division           CA District                     Global Operations                  9
CA Division           CA District                     Laboratory Services                11
CA Division           CA District                     Corporate                          3
CA Division           S District                      Corporate Administration           6
CA Division           S District                      Corporate Technology               1

But I want the grouping to be done in the output and the total calculated as per the grouping of the district and division.
I have used a nested table for that. somewhat like -

But the RTF template is giving me an extra row in the output even though the RTF template formatting is correct-

 what can i use to remove the extra row and perfect the formatting