问:
custom maven plugin fail: java.lang.ArrayIndexOutOfBoundsException: 3379 at org.objectweb.asm.ClassReader.<init>(Unknown Source)
I have written a custom maven plugin by java-annotations, and when run "mvn clean install" by jdk8 and maven 3.5.0, then get follow error:

```<code>[ERROR] Failed to execute goal org.apache.maven.plugins:maven-plugin-plugin:3.5:descriptor (default-descriptor) on project pg-maven-plugin: Execution default-descriptor of goal org.apache.maven.plugins:maven-plugin-plugin:3.5:descriptor failed: 3379 -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.maven.plugins:maven-plugin-plugin:3.5:descriptor (default-descriptor) on project pg-maven-plugin: Execution default-descriptor of goal org.apache.maven.plugins:maven-plugin-plugin:3.5:descriptor failed: 3379
        at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:213)
        at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:154)
        at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:146)
        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:51)
        at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128)
        at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:309)
        at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:194)
        at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:107)
        at org.apache.maven.cli.MavenCli.execute(MavenCli.java:993)
        at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:345)
        at org.apache.maven.cli.MavenCli.main(MavenCli.java:191)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
        at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
        at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
        at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
Caused by: org.apache.maven.plugin.PluginExecutionException: Execution default-descriptor of goal org.apache.maven.plugins:maven-plugin-plugin:3.5:descriptor failed: 3379
        at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:145)
        at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:208)
        ... 20 more
Caused by: java.lang.ArrayIndexOutOfBoundsException: 3379
        at org.objectweb.asm.ClassReader.<init>(Unknown Source)
        at org.objectweb.asm.ClassReader.<init>(Unknown Source)
        at org.objectweb.asm.ClassReader.<init>(Unknown Source)
        at org.apache.maven.tools.plugin.extractor.annotations.scanner.DefaultMojoAnnotationsScanner.analyzeClassStream(DefaultMojoAnnotationsScanner.java:214)
        at org.apache.maven.tools.plugin.extractor.annotations.scanner.DefaultMojoAnnotationsScanner.scanArchive(DefaultMojoAnnotationsScanner.java:145)
        at org.apache.maven.tools.plugin.extractor.annotations.scanner.DefaultMojoAnnotationsScanner.scan(DefaultMojoAnnotationsScanner.java:112)
        at org.apache.maven.tools.plugin.extractor.annotations.scanner.DefaultMojoAnnotationsScanner.scan(DefaultMojoAnnotationsScanner.java:79)
        at org.apache.maven.tools.plugin.extractor.annotations.JavaAnnotationsMojoDescriptorExtractor.scanAnnotations(JavaAnnotationsMojoDescriptorExtractor.java:124)
        at org.apache.maven.tools.plugin.extractor.annotations.JavaAnnotationsMojoDescriptorExtractor.execute(JavaAnnotationsMojoDescriptorExtractor.java:103)
        at org.apache.maven.tools.plugin.scanner.DefaultMojoScanner.populatePluginDescriptor(DefaultMojoScanner.java:96)
        at org.apache.maven.plugin.plugin.AbstractGeneratorMojo.execute(AbstractGeneratorMojo.java:283)
        at org.apache.maven.plugin.plugin.DescriptorGeneratorMojo.execute(DescriptorGeneratorMojo.java:90)
        at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:134)
        ... 21 more
[ERROR]
</code>```

Follow codes is pom:

    http://maven.apache.org/maven-v4_0_0.xsd">
        4.0.0

            net.engining.pg
            pg-parent
            3.0.0-SNAPSHOT
            ..

```<code>    <name>PowerGear - 代码生成Maven插件</name>
    <artifactId>pg-maven-plugin</artifactId>
    <packaging>maven-plugin</packaging>

    <properties>
        <maven-core.version>3.5.0</maven-core.version>
        <plexus-build-api.version>0.0.7</plexus-build-api.version>
        <maven-plugin-annotations.version>3.5</maven-plugin-annotations.version>
        <maven-plugin-plugin.version>3.5</maven-plugin-plugin.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>net.engining.pg</groupId>
            <artifactId>pg-support</artifactId>
        </dependency>
        <dependency>
            <groupId>net.engining.pg</groupId>
            <artifactId>pg-gwt</artifactId>
        </dependency>

        <dependency>
            <groupId>org.apache.maven</groupId>
            <artifactId>maven-core</artifactId>
            <version>${maven-core.version}</version>
        </dependency>
        <dependency>
            <groupId>dom4j</groupId>
            <artifactId>dom4j</artifactId>
        </dependency>
        <dependency>
            <groupId>jaxen</groupId>
            <artifactId>jaxen</artifactId>
        </dependency>
        <dependency>
            <groupId>org.sonatype.plexus</groupId>
            <artifactId>plexus-build-api</artifactId>
            <version>${plexus-build-api.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.maven</groupId>
            <artifactId>maven-plugin-api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-plugin-plugin</artifactId>
            <version>3.5</version>
        </dependency>
        <dependency>
            <groupId>org.apache.maven.plugin-tools</groupId>
            <artifactId>maven-plugin-annotations</artifactId>
            <version>${maven-plugin-annotations.version}</version>
        </dependency>
        <dependency>
            <!-- 用里面的Java代码生成模型 -->
            <groupId>org.apache.ibatis</groupId>
            <artifactId>ibator</artifactId>
        </dependency>

    </dependencies>
    <description>用于生成基于PowerGear的基础数据库包装框架。用于代码生成的代码模型API基于ibator的内部工具类，其License基于Apache License V2，见 http://http://ibatis.apache.org/docs/tools/ibator/license.html </description>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-plugin-plugin</artifactId>
                <version>${maven-plugin-plugin.version}</version>
                <executions>
                    <execution>
                        <id>default-descriptor</id>
                        <phase>process-classes</phase>
                    </execution>
                </executions>
            </plugin>
        </plugins>
        <pluginManagement>
            <plugins>
                <!--This plugin's configuration is used to store Eclipse m2e settings
                    only. It has no influence on the Maven build itself. -->
                <plugin>
                    <groupId>org.eclipse.m2e</groupId>
                    <artifactId>lifecycle-mapping</artifactId>
                    <version>1.0.0</version>
                    <configuration>
                        <lifecycleMappingMetadata>
                            <pluginExecutions>
                                <pluginExecution>
                                    <pluginExecutionFilter>
                                        <groupId>
                                            org.apache.maven.plugins
                                        </groupId>
                                        <artifactId>
                                            maven-plugin-plugin
                                        </artifactId>
                                        <versionRange>
                                            [3.3,)
                                        </versionRange>
                                        <goals>
                                            <goal>descriptor</goal>
                                        </goals>
                                    </pluginExecutionFilter>
                                    <action>
                                        <ignore></ignore>
                                    </action>
                                </pluginExecution>
                            </pluginExecutions>
                        </lifecycleMappingMetadata>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
    <profiles>
        <profile>
            <id>obfuscated</id>
            <build>
                <plugins>
                    <plugin>
                        <groupId>com.github.wvengen</groupId>
                        <artifactId>proguard-maven-plugin</artifactId>
                        <version>2.0.8</version>
                        <executions>
                            <execution>
                                <phase>package</phase>
                                <goals>
                                    <goal>proguard</goal>
                                </goals>
                            </execution>
                        </executions>
                        <configuration>
                            <proguardVersion>5.2.1</proguardVersion>
                            <obfuscate>true</obfuscate>
                            <addMavenDescriptor>true</addMavenDescriptor>
                            <options>
                                <option>-dontshrink</option>
                                <option>-dontoptimize</option>
                                <option>-keepattributes *Annotation*</option>
                                <option>-keepattributes Signature</option>
                                <option>-repackageclasses ''</option>
                                <option>-allowaccessmodification</option>
                                <option>-keepclasseswithmembers class * extends
                                    org.apache.maven.plugin.AbstractMojo { * ;}</option>
                                <option>-keepclasseswithmembers class
                                    net.engining.pg.maven.plugin.ui.Generation { * ;}</option>
                            </options>
                            <libs>
                                <lib>${java.home}/lib/rt.jar</lib>
                            </libs>
                        </configuration>
                        <dependencies>
                            <dependency>
                                <groupId>net.sf.proguard</groupId>
                                <artifactId>proguard-base</artifactId>
                                <version>5.2.1</version>
                                <scope>runtime</scope>
                            </dependency>
                        </dependencies>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>
</project>
</code>```

答:
I had the same issue. It disappeared when I removed one of the depencencies, in my case it was

```<code>    <dependency>
      <groupId>org.eclipse.jgit</groupId>
      <artifactId>org.eclipse.jgit</artifactId>
      <version>4.8.0.201706111038-r</version>
    </dependency>
</code>```

It seems that maven-plugin is ill-behaving in combination with certain other dependencies.

Body:
I have written a custom maven plugin by java-annotations, and when run "mvn clean install" by jdk8 and maven 3.5.0, then get follow error:

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-plugin-plugin:3.5:descriptor (default-descriptor) on project pg-maven-plugin: Execution default-descriptor of goal org.apache.maven.plugins:maven-plugin-plugin:3.5:descriptor failed: 3379 -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.maven.plugins:maven-plugin-plugin:3.5:descriptor (default-descriptor) on project pg-maven-plugin: Execution default-descriptor of goal org.apache.maven.plugins:maven-plugin-plugin:3.5:descriptor failed: 3379
        at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:213)
        at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:154)
        at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:146)
        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:51)
        at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128)
        at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:309)
        at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:194)
        at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:107)
        at org.apache.maven.cli.MavenCli.execute(MavenCli.java:993)
        at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:345)
        at org.apache.maven.cli.MavenCli.main(MavenCli.java:191)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
        at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
        at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
        at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
Caused by: org.apache.maven.plugin.PluginExecutionException: Execution default-descriptor of goal org.apache.maven.plugins:maven-plugin-plugin:3.5:descriptor failed: 3379
        at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:145)
        at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:208)
        ... 20 more
Caused by: java.lang.ArrayIndexOutOfBoundsException: 3379
        at org.objectweb.asm.ClassReader.<init>(Unknown Source)
        at org.objectweb.asm.ClassReader.<init>(Unknown Source)
        at org.objectweb.asm.ClassReader.<init>(Unknown Source)
        at org.apache.maven.tools.plugin.extractor.annotations.scanner.DefaultMojoAnnotationsScanner.analyzeClassStream(DefaultMojoAnnotationsScanner.java:214)
        at org.apache.maven.tools.plugin.extractor.annotations.scanner.DefaultMojoAnnotationsScanner.scanArchive(DefaultMojoAnnotationsScanner.java:145)
        at org.apache.maven.tools.plugin.extractor.annotations.scanner.DefaultMojoAnnotationsScanner.scan(DefaultMojoAnnotationsScanner.java:112)
        at org.apache.maven.tools.plugin.extractor.annotations.scanner.DefaultMojoAnnotationsScanner.scan(DefaultMojoAnnotationsScanner.java:79)
        at org.apache.maven.tools.plugin.extractor.annotations.JavaAnnotationsMojoDescriptorExtractor.scanAnnotations(JavaAnnotationsMojoDescriptorExtractor.java:124)
        at org.apache.maven.tools.plugin.extractor.annotations.JavaAnnotationsMojoDescriptorExtractor.execute(JavaAnnotationsMojoDescriptorExtractor.java:103)
        at org.apache.maven.tools.plugin.scanner.DefaultMojoScanner.populatePluginDescriptor(DefaultMojoScanner.java:96)
        at org.apache.maven.plugin.plugin.AbstractGeneratorMojo.execute(AbstractGeneratorMojo.java:283)
        at org.apache.maven.plugin.plugin.DescriptorGeneratorMojo.execute(DescriptorGeneratorMojo.java:90)
        at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:134)
        ... 21 more
[ERROR]

Follow codes is pom:

    http://maven.apache.org/maven-v4_0_0.xsd">
        4.0.0

            net.engining.pg
            pg-parent
            3.0.0-SNAPSHOT
            ..

    <name>PowerGear - 代码生成Maven插件</name>
    <artifactId>pg-maven-plugin</artifactId>
    <packaging>maven-plugin</packaging>

    <properties>
        <maven-core.version>3.5.0</maven-core.version>
        <plexus-build-api.version>0.0.7</plexus-build-api.version>
        <maven-plugin-annotations.version>3.5</maven-plugin-annotations.version>
        <maven-plugin-plugin.version>3.5</maven-plugin-plugin.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>net.engining.pg</groupId>
            <artifactId>pg-support</artifactId>
        </dependency>
        <dependency>
            <groupId>net.engining.pg</groupId>
            <artifactId>pg-gwt</artifactId>
        </dependency>

        <dependency>
            <groupId>org.apache.maven</groupId>
            <artifactId>maven-core</artifactId>
            <version>${maven-core.version}</version>
        </dependency>
        <dependency>
            <groupId>dom4j</groupId>
            <artifactId>dom4j</artifactId>
        </dependency>
        <dependency>
            <groupId>jaxen</groupId>
            <artifactId>jaxen</artifactId>
        </dependency>
        <dependency>
            <groupId>org.sonatype.plexus</groupId>
            <artifactId>plexus-build-api</artifactId>
            <version>${plexus-build-api.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.maven</groupId>
            <artifactId>maven-plugin-api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-plugin-plugin</artifactId>
            <version>3.5</version>
        </dependency>
        <dependency>
            <groupId>org.apache.maven.plugin-tools</groupId>
            <artifactId>maven-plugin-annotations</artifactId>
            <version>${maven-plugin-annotations.version}</version>
        </dependency>
        <dependency>

            <groupId>org.apache.ibatis</groupId>
            <artifactId>ibator</artifactId>
        </dependency>

    </dependencies>
    <description>用于生成基于PowerGear的基础数据库包装框架。用于代码生成的代码模型API基于ibator的内部工具类，其License基于Apache License V2，见 http://http://ibatis.apache.org/docs/tools/ibator/license.html </description>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-plugin-plugin</artifactId>
                <version>${maven-plugin-plugin.version}</version>
                <executions>
                    <execution>
                        <id>default-descriptor</id>
                        <phase>process-classes</phase>
                    </execution>
                </executions>
            </plugin>
        </plugins>
        <pluginManagement>
            <plugins>

                <plugin>
                    <groupId>org.eclipse.m2e</groupId>
                    <artifactId>lifecycle-mapping</artifactId>
                    <version>1.0.0</version>
                    <configuration>
                        <lifecycleMappingMetadata>
                            <pluginExecutions>
                                <pluginExecution>
                                    <pluginExecutionFilter>
                                        <groupId>
                                            org.apache.maven.plugins
                                        </groupId>
                                        <artifactId>
                                            maven-plugin-plugin
                                        </artifactId>
                                        <versionRange>
                                            [3.3,)
                                        </versionRange>
                                        <goals>
                                            <goal>descriptor</goal>
                                        </goals>
                                    </pluginExecutionFilter>
                                    <action>
                                        <ignore></ignore>
                                    </action>
                                </pluginExecution>
                            </pluginExecutions>
                        </lifecycleMappingMetadata>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
    <profiles>
        <profile>
            <id>obfuscated</id>
            <build>
                <plugins>
                    <plugin>
                        <groupId>com.github.wvengen</groupId>
                        <artifactId>proguard-maven-plugin</artifactId>
                        <version>2.0.8</version>
                        <executions>
                            <execution>
                                <phase>package</phase>
                                <goals>
                                    <goal>proguard</goal>
                                </goals>
                            </execution>
                        </executions>
                        <configuration>
                            <proguardVersion>5.2.1</proguardVersion>
                            <obfuscate>true</obfuscate>
                            <addMavenDescriptor>true</addMavenDescriptor>
                            <options>
                                <option>-dontshrink</option>
                                <option>-dontoptimize</option>
                                <option>-keepattributes *Annotation*</option>
                                <option>-keepattributes Signature</option>
                                <option>-repackageclasses ''</option>
                                <option>-allowaccessmodification</option>
                                <option>-keepclasseswithmembers class * extends
                                    org.apache.maven.plugin.AbstractMojo { * ;}</option>
                                <option>-keepclasseswithmembers class
                                    net.engining.pg.maven.plugin.ui.Generation { * ;}</option>
                            </options>
                            <libs>
                                <lib>${java.home}/lib/rt.jar</lib>
                            </libs>
                        </configuration>
                        <dependencies>
                            <dependency>
                                <groupId>net.sf.proguard</groupId>
                                <artifactId>proguard-base</artifactId>
                                <version>5.2.1</version>
                                <scope>runtime</scope>
                            </dependency>
                        </dependencies>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>
</project>

Body:
I had the same issue. It disappeared when I removed one of the depencencies, in my case it was

    <dependency>
      <groupId>org.eclipse.jgit</groupId>
      <artifactId>org.eclipse.jgit</artifactId>
      <version>4.8.0.201706111038-r</version>
    </dependency>

It seems that maven-plugin is ill-behaving in combination with certain other dependencies.


来源: stackexchange

问:
Alternate blinking with CSS3 animation
I am trying to find a CSS-only way to make specific tags (like p or img) blink in alternating patterns. While I have been able to find a means to make anything blink (see .blinky) in code sample, I have not been able to make two separate classes alternate the blinking.

Part of the solution might be the animation-delay property shown in .blinky2, but after the specified delay in seconds, it blinks in sync with .blinky and not offset by the delay.

I found some related SO links that got me started -- Imitating a blink tag with CSS3 animations and CSS Tricks -- but I have not yet seen any instructions to define offset blinking for .blink2. Is such a thing supported, or does it require further tricks?

.blinky {
  animation: blink-animation 1s steps(5, start) infinite;
  -webkit-animation: blink-animation 1s steps(5, start) infinite;
  font-size: x-large;
  color: blue;
  display: inline;
}

.blinky2 {
  /* Need make this alternate blinking*/
  animation: blink-animation 1s steps(5, start) infinite;
  -webkit-animation: blink-animation 1s steps(5, start) infinite;
  /* This just postpones blinking for 1-sec, then it's in sync with .blinky*/
  animation-delay: 1s;
  -webkit-animation-delay: 1s;
  font-size: x-large;
  color: red;
  display: inline;
}

@keyframes blink-animation {
  to {
    visibility: hidden;
  }
}

@-webkit-keyframes blink-animation {
  to {
    visibility: hidden;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>The <var>blinky</var> and <var>blinky2</var> classes should alternate blinking.</p>

<div>
  <p class="blinky">Blinky</p>
  <p class="blinky2">Blinky 2</p>
  <p class="blinky">Blinky</p>
  <p class="blinky2">Blinky 2</p>
  <p class="blinky">Blinky</p>
</div></code>```

答:
The key to alternating blinking lies in setting up the animation-delay value to half of the "1s" in animation: blink-animation 1s steps(5, start) infinite to "0.5s".

I'm not sure what a generalized formula would look like, but for this purpose "0.5s" seems to work.

I tested this by letting it run for 10 minutes, and still remained blinking in alternation.

So .blinky2 now looks like this:

```<code>.blinky2 {
  /* Need make this alternate blinking*/
  animation: blink-animation 1s steps(5, start) infinite;
  -webkit-animation: blink-animation 1s steps(5, start) infinite;

  animation-delay: 0.5s;
  -webkit-animation-delay: 0.5s;
  font-size: x-large;
  color: red;
  display: inline;
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Alternate blinking with CSS3 animation

Body:
I am trying to find a CSS-only way to make specific tags (like p or img) blink in alternating patterns. While I have been able to find a means to make anything blink (see .blinky) in code sample, I have not been able to make two separate classes alternate the blinking.

Part of the solution might be the animation-delay property shown in .blinky2, but after the specified delay in seconds, it blinks in sync with .blinky and not offset by the delay.

I found some related SO links that got me started -- Imitating a blink tag with CSS3 animations and CSS Tricks -- but I have not yet seen any instructions to define offset blinking for .blink2. Is such a thing supported, or does it require further tricks?

.blinky {
  animation: blink-animation 1s steps(5, start) infinite;
  -webkit-animation: blink-animation 1s steps(5, start) infinite;
  font-size: x-large;
  color: blue;
  display: inline;
}

.blinky2 {
  /* Need make this alternate blinking*/
  animation: blink-animation 1s steps(5, start) infinite;
  -webkit-animation: blink-animation 1s steps(5, start) infinite;
  /* This just postpones blinking for 1-sec, then it's in sync with .blinky*/
  animation-delay: 1s;
  -webkit-animation-delay: 1s;
  font-size: x-large;
  color: red;
  display: inline;
}

@keyframes blink-animation {
  to {
    visibility: hidden;
  }
}

@-webkit-keyframes blink-animation {
  to {
    visibility: hidden;
  }
}

The <var>blinky</var> and <var>blinky2</var> classes should alternate blinking.

Blinky

Blinky 2

Blinky

Blinky 2

Blinky

Body:
The key to alternating blinking lies in setting up the animation-delay value to half of the "1s" in animation: blink-animation 1s steps(5, start) infinite to "0.5s".

I'm not sure what a generalized formula would look like, but for this purpose "0.5s" seems to work.

I tested this by letting it run for 10 minutes, and still remained blinking in alternation.

So .blinky2 now looks like this:

.blinky2 {
  /* Need make this alternate blinking*/
  animation: blink-animation 1s steps(5, start) infinite;
  -webkit-animation: blink-animation 1s steps(5, start) infinite;

  animation-delay: 0.5s;
  -webkit-animation-delay: 0.5s;
  font-size: x-large;
  color: red;
  display: inline;
}


问:
Removing divs gives error
So I created a dice simulator with an option to reset the table. I create new divs with dice number by appendChild and want to remove it with remove().

Even though it appears to be working I keep getting errors.
The code and error is below:

function addMoreDice() {
  for (var i = 0; i < numInput.value; i++) {
    var div = document.createElement('div');
    div.className = "diceStyle";
    div.id = "dice" + String(i);
    div.innerHTML = Math.floor((Math.random() * 6) + 1);

    document.getElementById('diceTable').appendChild(div);
    howManyDice++;
  }
  currentValue = numInput.value;

}

function removeDice() {
  var removeDiv = document.getElementsByClassName("diceStyle");
  for (var i = 0; i < numInput.value; i++) {
    removeDiv[numInput.value - i - 1].remove();
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="diceTable"></div></code>```

Uncaught TypeError: Cannot read property 'remove' of undefined
    at removeDice

Updating with html, although there isnt really anything there:

```<code>    <p>Pick how many dice you want to roll:</p>
<input id="diceNumber" type="number" name="diceNumber" onchange="return addMoreDice()">

<div id="diceTable">

</div>
</code>```

Edited removeDice function, sadly changes nothing, works, but gives errors

```<code>function removeDice(){
var removeDiv = document.getElementsByClassName("diceStyle");
var value = numInput.value;
if(value >0){
    for(var i=value; i > 0; i--){
        removeDiv[i-1].remove();
    }
}
}
</code>```

答:
The issue appears to be in the removeDice() function. Removing an item from the array decreases the number of items in the array (obviously), but the for-loop is assuming that the array still has the same number of items as when the for-loop started. So if the for-loop started with 5 items, and then removes one, there will be only 4 items in the array. Since the for-loop is assuming that there are 5 items, it will try to remove the 5th item in the array, but since the array only has 4 items, there is no 5th item to remove, causing an error. To fix the issue, loop backwards:
for(var i = numInput.value; i > 0; i--)

Title: Removing divs gives error

Body:
So I created a dice simulator with an option to reset the table. I create new divs with dice number by appendChild and want to remove it with remove().

Even though it appears to be working I keep getting errors.
The code and error is below:

function addMoreDice() {
  for (var i = 0; i < numInput.value; i++) {
    var div = document.createElement('div');
    div.className = "diceStyle";
    div.id = "dice" + String(i);
    div.innerHTML = Math.floor((Math.random() * 6) + 1);

    document.getElementById('diceTable').appendChild(div);
    howManyDice++;
  }
  currentValue = numInput.value;

}

function removeDice() {
  var removeDiv = document.getElementsByClassName("diceStyle");
  for (var i = 0; i < numInput.value; i++) {
    removeDiv[numInput.value - i - 1].remove();
  }
}

Uncaught TypeError: Cannot read property 'remove' of undefined
    at removeDice

Updating with html, although there isnt really anything there:

Pick how many dice you want to roll:

<input id="diceNumber" type="number" name="diceNumber" onchange="return addMoreDice()">

Edited removeDice function, sadly changes nothing, works, but gives errors

function removeDice(){
var removeDiv = document.getElementsByClassName("diceStyle");
var value = numInput.value;
if(value >0){
    for(var i=value; i > 0; i--){
        removeDiv[i-1].remove();
    }
}
}


问:
gcc shows 0 for a struct's property but clang shows a different value
Consider this code:

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

struct Z
{
    Z() { cout << "ctor Z" << endl; }
};

struct A
{
    A() = default;
    A(int xx) : x(xx) {}
    int x;
    Z z;
};

int main()
{
    A a;
    cout << "a.x = " << a.x << endl;
}
</code>```

Compiled with newest GCC it prints:

```<code>ctor Z
a.x = 0
</code>```

But compiled with newest Clang it prints:

```<code>ctor Z
a.x = 4198800
</code>```

Why? Can someone explain this?
Does GCC initiates the 'x' prinitive value while it doesn't have to do it? Or, maybe Clang doesn't initiante the 'x' with 0, while it should do it?

The same happens when I remove my constructors from the "A" struct, so it is not a matter of the constructor being marked as 'default' or something like that. To put this simply - one compiler generates code which calls constructors of its members being class objects, and also members being primitives. The other compiler runs constructor of only the class objects members.

Why?

答:
It shouldn't be a surprise that different compilers produce different code. Otherwise there would only be one compiler.

The differences between them are particularly noticeable in the way they treat instances of undefined behaviour, such as reading the indeterminate "value" of an uninitialised object (e.g. A::x here).

It's both extremely complicated and utterly pointless to rationalise about why specific compilers specifically resulted in specific values here, because there are so very many possible explanations, all of which could change the next time you hit "compile". It's easier to discuss when an implementation fills a memory space with e.g. 0xCCCCCCCC in debug mode, so that you can see when you forgot to initialise something. That hasn't happened in either case here, though.

Body:
Consider this code:

#include <iostream>
using namespace std;

struct Z
{
    Z() { cout << "ctor Z" << endl; }
};

struct A
{
    A() = default;
    A(int xx) : x(xx) {}
    int x;
    Z z;
};

int main()
{
    A a;
    cout << "a.x = " << a.x << endl;
}

Compiled with newest GCC it prints:

ctor Z
a.x = 0

But compiled with newest Clang it prints:

ctor Z
a.x = 4198800

Why? Can someone explain this?
Does GCC initiates the 'x' prinitive value while it doesn't have to do it? Or, maybe Clang doesn't initiante the 'x' with 0, while it should do it?

The same happens when I remove my constructors from the "A" struct, so it is not a matter of the constructor being marked as 'default' or something like that. To put this simply - one compiler generates code which calls constructors of its members being class objects, and also members being primitives. The other compiler runs constructor of only the class objects members.

Why?


问:
How to make QtLinguist shipped with Qt 5.9.1 work?
Goal: Generate/update the *.ts files of a Qt widgets app using lupdate.

Setup:

Windows 7 Pro 64 (tried on Windows 10 Home as well)

Qt 5.9.1 Prebult Components for msvc2017 64-bit,

Visual Studio Community 2017.

The problem: I have run lupdate from the QtCreator, as well as manually from the console, but in neither case it is working. The message is:

Starting external tool
  "C:\Qt\Qt5.9.1\5.9.1\msvc2017_64\bin\lupdate.exe"
  C:/Documents/Projects/untitled1/untitled1.pro WARNING: Project ERROR:
  Cannot run compiler 'cl'. Maybe you forgot to setup the environment?

"C:\Qt\Qt5.9.1\5.9.1\msvc2017_64\bin\lupdate.exe" finished

Otherwise the project is compiled, run and debugged without problems with the kit: Desktop Qt 5.9.1 MSVC2017 64bit (default), which is the reason I think the environment is properly set up.

I can't find any information regarding this issue. Any ideas how to make lupdate work?

EDIT: I am adding screenshots of the current setup (which is made by the Qt installer) in attempt to clarify why I believe the environment is properly set up:

kits

cmake configuration

答:
In my case the culprit was the fact that Qt Creator had somehow picked different target ABIs for C and C++:

After fixing this, I managed to get lupdate running with no issues.

ContentLicense: CC BY-SA 4.0


问:
Using GETDATE() and also adding time parameters such as between 9AM and 8:59AM
I am trying to complete a query where I and looking at data from the previous day but I want to add a time frame such as 9 am (previous day) to 8:59 am (current day).

I am using the code below that gets me the previous day data but I want to add the time.

```<code>AND [GasTime] BETWEEN CONVERT(DATETIME, GETDATE() -2, 102)  AND CONVERT(DATETIME, GETDATE() -1, 102)
</code>```

Thanks for your help.

答:
If 2012+</p>

```<code>and GasTime between format(GetDate()-2,'yyyy-MM-dd 09:00') and format(GetDate()-1,'yyyy-MM-dd 08:59:59')
</code>```

Body:
I am trying to complete a query where I and looking at data from the previous day but I want to add a time frame such as 9 am (previous day) to 8:59 am (current day).

I am using the code below that gets me the previous day data but I want to add the time.

AND [GasTime] BETWEEN CONVERT(DATETIME, GETDATE() -2, 102)  AND CONVERT(DATETIME, GETDATE() -1, 102)

Thanks for your help.

Body:
If 2012+

and GasTime between format(GetDate()-2,'yyyy-MM-dd 09:00') and format(GetDate()-1,'yyyy-MM-dd 08:59:59')


问:
Iterating over multiple rows in Python - Science Data Cleaning
I am working with a large private dataset and I need some assistance in figuring out how to iterate a program over multiple rows.

```<code>import csv

with open('report_export.csv') as f:

    reader = csv.DictReader(f)
    report_export = list(reader)

x = report_export[25]["Text_Content"]
x.split(sep='. ')[1]

 ' Azithromycin is an antibiotic agent and a member of a subclass of
   macrolide antibiotics with bactericidal and bacteriostatic activities.
</code>```

report_export.csv is a data file pull from a local database containing information chemicals from publications. I want some textual information from this file. It is located under the column "Text Content". "25" is a random row that worked as proof of principle for the code. The x.split(sep='. ')[1] is used
 for isolating the desired string and differentiating between decimals and periods. This file is rather large, 5000 rows on CSV, and I want to be able to extract statements about the chemicals similar to output above.

I am having difficulty figuring out how to iterate over multiple rows in this case. I need the program to read over the rows, retrieve the 2nd string (1 position) from the list, and be able to save this data to a new csv file.

Any assistance with achieving the ability to iterate over rows would be helpful.

Thank you!

Best,

PEB

答:
Look into pandas pandas.read_csv(filename) method

```<code>import pandas as pd
dataframe = pd.read_csv(filename)
</code>```

And in order to iterate over the rows use the method iterrows()

```<code>for index, row in df.iterrows():
    print(row)
</code>```

Body:
I am working with a large private dataset and I need some assistance in figuring out how to iterate a program over multiple rows.

import csv

with open('report_export.csv') as f:

    reader = csv.DictReader(f)
    report_export = list(reader)

x = report_export[25]["Text_Content"]
x.split(sep='. ')[1]

 ' Azithromycin is an antibiotic agent and a member of a subclass of
   macrolide antibiotics with bactericidal and bacteriostatic activities.

report_export.csv is a data file pull from a local database containing information chemicals from publications. I want some textual information from this file. It is located under the column "Text Content". "25" is a random row that worked as proof of principle for the code. The x.split(sep='. ')[1] is used
 for isolating the desired string and differentiating between decimals and periods. This file is rather large, 5000 rows on CSV, and I want to be able to extract statements about the chemicals similar to output above.

I am having difficulty figuring out how to iterate over multiple rows in this case. I need the program to read over the rows, retrieve the 2nd string (1 position) from the list, and be able to save this data to a new csv file.

Any assistance with achieving the ability to iterate over rows would be helpful.

Thank you!

Best,

PEB

Body:
Look into pandas pandas.read_csv(filename) method

import pandas as pd
dataframe = pd.read_csv(filename)

And in order to iterate over the rows use the method iterrows()

for index, row in df.iterrows():
    print(row)


问:
Python - Save back changes using beautifulsoup
I parsing html file using Beautifulsoup and checking whether the text are in uppercase and in that case I am changing it to lower case. When I save the output to new html file, the changes are not being reflected. Can someone point me what i am doing wrong.</p>

```<code>def recursiveChildren(x):
    if "childGenerator" in dir(x):
      for child in x.childGenerator():
          name = getattr(child, "name", None)
          if name is not None:
             print(child.name)
          recursiveChildren(child)
    else:
      if not x.isspace():
         print (x)
         if(x.isupper()):
          x.string = x.lower()
          x=x.replace(x,x.string)

if __name__ == "__main__":
    with open("\path\) as fp:
      soup = BeautifulSoup(fp)
    for child in soup.childGenerator():
       recursiveChildren(child)
    html = soup.prettify("utf-8")
    with open("\path\") as file:
      file.write(html)
</code>```

答:
I don't think your way would cope with markup like:

```<code> <p>TEXT<span>More Text<i>TEXT</i>TEXT</span>TEXT</p>
</code>```

Also the method you want is replaceWith() not replace(). You have not opened your file for writing.

This is the way I would do it.

```<code>from bs4 import BeautifulSoup

filename = "test.html"
if __name__ == "__main__":
    # Open the file.
    with open(filename, "r") as fp:
        soup = BeautifulSoup(fp, "html.parser") # Or BeautifulSoup(fp, "lxml")
        # Iterate over all the text found in the document.
        for txt in soup.findAll(text=True):
            # If all the case-based characters (letters) of the string are uppercase.
            if txt.isupper():
                # Replace with lowercase.
                txt.replaceWith(txt.lower())
    # Write the file.
    with open(filename, "wb") as file:
        file.write(soup.prettify("utf-8"))
</code>```

Body:
I parsing html file using Beautifulsoup and checking whether the text are in uppercase and in that case I am changing it to lower case. When I save the output to new html file, the changes are not being reflected. Can someone point me what i am doing wrong.

def recursiveChildren(x):
    if "childGenerator" in dir(x):
      for child in x.childGenerator():
          name = getattr(child, "name", None)
          if name is not None:
             print(child.name)
          recursiveChildren(child)
    else:
      if not x.isspace():
         print (x)
         if(x.isupper()):
          x.string = x.lower()
          x=x.replace(x,x.string)

if __name__ == "__main__":
    with open("\path\) as fp:
      soup = BeautifulSoup(fp)
    for child in soup.childGenerator():
       recursiveChildren(child)
    html = soup.prettify("utf-8")
    with open("\path\") as file:
      file.write(html)

Body:
I don't think your way would cope with markup like:

 <p>TEXT<span>More Text<i>TEXT</i>TEXT</span>TEXT</p>

Also the method you want is replaceWith() not replace(). You have not opened your file for writing.

This is the way I would do it.

from bs4 import BeautifulSoup

filename = "test.html"
if __name__ == "__main__":
    # Open the file.
    with open(filename, "r") as fp:
        soup = BeautifulSoup(fp, "html.parser") # Or BeautifulSoup(fp, "lxml")
        # Iterate over all the text found in the document.
        for txt in soup.findAll(text=True):
            # If all the case-based characters (letters) of the string are uppercase.
            if txt.isupper():
                # Replace with lowercase.
                txt.replaceWith(txt.lower())
    # Write the file.
    with open(filename, "wb") as file:
        file.write(soup.prettify("utf-8"))


问:
Excel exporting to Access, via VBA, is causing instability
I have to create over 170 named ranges in Excel which I am trying to load into an Access table.  Below is my code.

```<code>Sub Load_To_ALLL_TSD()

Dim strDatabasePath As String
Dim oApp As Access.Application
Dim PathOfworkbook As String

PathToDB = ThisWorkbook.Path
strDatabasePath = PathToDB & "\RAROC.accdb"

Set oApp = CreateObject("Access.Application")
'Set db = Application.CurrentProject
oApp.Visible = True

oApp.OpenCurrentDatabase strDatabasePath

Set db = CurrentDb()
Set rs = db.OpenRecordset("ALLL_TSD", dbOpenTable)

    With oApp
            With rs
                .AddNew ' create a new record
                ' add values to each field in the record
                .Fields("TSD_Base_Rate_Received") = Range("TSD_Base_Rate_Received").Value
                .Fields("TSD_Base_Rate_Received_Input") = Range("TSD_Base_Rate_Received_Input").Value
                .Fields("TSD_Calculated_RAROC") = Range("TSD_Calculated_RAROC").Value
                .Fields("TSD_Capital_Factor") = Range("TSD_Capital_Factor").Value

                ' etc, etc, lot more fields and named ranges here

                ' add more fields if necessary...
                .Update ' stores the new record
            End With
    End With

Set oApp = Nothing
MsgBox ("Done!  All Data saved to RAROC database!!")

End Sub
</code>```

I'm getting some weird errors!  If I run the code using F8, it works fine.  If I click a button to fire the code, sometimes it works and sometimes it doesn't work.  I has errored out on several different lines.

Once it threw an error here:

```<code>Set rs = db.OpenRecordset("ALLL_TSD", dbOpenTable)
</code>```

Error reads 'object variable or with block not set'

Once it said 'Microsoft Access has stopped working' and it threw an error on this line.

.Fields("TSD_Base_Rate_Received_Input") = Range("TSD_Base_Rate_Received_Input").Value

I've seen some other weird things too.

I have a reference set to both:

```<code>Microsoft DAO 3.6 Object Library
Microsoft Access 14.0 Object Library
</code>```

It almost seems like I'm establishing a connection to Access and then almost immediately I lost the connection, somehow.

Finally, I have no Forms or Reports, and the DB is not split.  I have just one single table in there now, which I am trying to write to. What can I try to resolve this?

答:
Here's a basic example without using Access.

Needs a reference to Microsoft ActiveX Data Objects 2.x Library

```<code>Sub Tester()

    Dim con As New ADODB.Connection, rs As New ADODB.Recordset

    con.Open "Provider=Microsoft.ACE.OLEDB.12.0;" _
             & "Data Source = " & ThisWorkbook.Path & "\RAROC.accdb"

    'get an empty recordset to add new records to
    rs.Open "select * from [ALLL_TSD] where false", con, _
             adOpenDynamic, adLockBatchOptimistic

    With rs
        .AddNew
        .Fields("TSD_Base_Rate_Received") = Range("TSD_Base_Rate_Received").Value
        .Fields("TSD_Base_Rate_Received_Input") = Range("TSD_Base_Rate_Received_Input").Value
        .Fields("TSD_Calculated_RAROC") = Range("TSD_Calculated_RAROC").Value
        .Fields("TSD_Capital_Factor") = Range("TSD_Capital_Factor").Value
        'etc...
        .UpdateBatch '<< EDIT
        .Close
    End With

    con.Close
End Sub
</code>```

Body:
I have to create over 170 named ranges in Excel which I am trying to load into an Access table.  Below is my code.

Sub Load_To_ALLL_TSD()

Dim strDatabasePath As String
Dim oApp As Access.Application
Dim PathOfworkbook As String

PathToDB = ThisWorkbook.Path
strDatabasePath = PathToDB & "\RAROC.accdb"

Set oApp = CreateObject("Access.Application")
'Set db = Application.CurrentProject
oApp.Visible = True

oApp.OpenCurrentDatabase strDatabasePath

Set db = CurrentDb()
Set rs = db.OpenRecordset("ALLL_TSD", dbOpenTable)

    With oApp
            With rs
                .AddNew ' create a new record
                ' add values to each field in the record
                .Fields("TSD_Base_Rate_Received") = Range("TSD_Base_Rate_Received").Value
                .Fields("TSD_Base_Rate_Received_Input") = Range("TSD_Base_Rate_Received_Input").Value
                .Fields("TSD_Calculated_RAROC") = Range("TSD_Calculated_RAROC").Value
                .Fields("TSD_Capital_Factor") = Range("TSD_Capital_Factor").Value

                ' etc, etc, lot more fields and named ranges here

                ' add more fields if necessary...
                .Update ' stores the new record
            End With
    End With

Set oApp = Nothing
MsgBox ("Done!  All Data saved to RAROC database!!")

End Sub

I'm getting some weird errors!  If I run the code using F8, it works fine.  If I click a button to fire the code, sometimes it works and sometimes it doesn't work.  I has errored out on several different lines.

Once it threw an error here:

Set rs = db.OpenRecordset("ALLL_TSD", dbOpenTable)

Error reads 'object variable or with block not set'

Once it said 'Microsoft Access has stopped working' and it threw an error on this line.

.Fields("TSD_Base_Rate_Received_Input") = Range("TSD_Base_Rate_Received_Input").Value

I've seen some other weird things too.

I have a reference set to both:

Microsoft DAO 3.6 Object Library
Microsoft Access 14.0 Object Library

It almost seems like I'm establishing a connection to Access and then almost immediately I lost the connection, somehow.

Finally, I have no Forms or Reports, and the DB is not split.  I have just one single table in there now, which I am trying to write to. What can I try to resolve this?

Body:
Here's a basic example without using Access.

Needs a reference to Microsoft ActiveX Data Objects 2.x Library

Sub Tester()

    Dim con As New ADODB.Connection, rs As New ADODB.Recordset

    con.Open "Provider=Microsoft.ACE.OLEDB.12.0;" _
             & "Data Source = " & ThisWorkbook.Path & "\RAROC.accdb"

    'get an empty recordset to add new records to
    rs.Open "select * from [ALLL_TSD] where false", con, _
             adOpenDynamic, adLockBatchOptimistic

    With rs
        .AddNew
        .Fields("TSD_Base_Rate_Received") = Range("TSD_Base_Rate_Received").Value
        .Fields("TSD_Base_Rate_Received_Input") = Range("TSD_Base_Rate_Received_Input").Value
        .Fields("TSD_Calculated_RAROC") = Range("TSD_Calculated_RAROC").Value
        .Fields("TSD_Capital_Factor") = Range("TSD_Capital_Factor").Value
        'etc...
        .UpdateBatch '<< EDIT
        .Close
    End With

    con.Close
End Sub


答:
x is being default initialized. Looking at http://en.cppreference.com/w/cpp/language/default_initialization

Default initialization is performed in three situations:

1) when a variable with automatic, static, or thread-local storage duration is declared with no initializer;

2) when an object with dynamic storage duration is created by a new-expression with no initializer or when an object is created by a new-expression with the initializer consisting of an empty pair of parentheses (until C++03);

3) when a base class or a non-static data member is not mentioned in a constructor initializer list and that constructor is called.

The effects of default initialization are:

if T is a non-POD (until C++11) class type, the constructors are considered and subjected to overload resolution against the empty argument list. The constructor selected (which is one of the default constructors) is called to provide the initial value for the new object;

if T is an array type, every element of the array is default-initialized;

otherwise, nothing is done: the objects with automatic storage duration (and their subobjects) are initialized to indeterminate values.

Title: gcc shows 0 for a struct's property but clang shows a different value


问:
rJava install troubles
I am trying to get RJava to work.

I have downloaded the 64-bit Java and tried to manually set where to find my java within R Studio.

I keep on getting this error:

```<code>Error: package or namespace load failed for ‘rJava’:
 .onLoad failed in loadNamespace() for 'rJava', details:
  call: dyn.load(file, DLLpath = DLLpath, ...)
  error: unable to load shared object '/Library/Frameworks/R.framework/Versions/3.4/Resources/library/rJava/libs/rJava.so':
  dlopen(/Library/Frameworks/R.framework/Versions/3.4/Resources/library/rJava/libs/rJava.so, 6): Library not loaded: @rpath/libjvm.dylib
  Referenced from: /Library/Frameworks/R.framework/Versions/3.4/Resources/library/rJava/libs/rJava.so
  Reason: image not found
</code>```

Any responses will be apreciated

答:
Take a look at the location here: R, Java, rJava and macOS adventures

You can find there description of how to deal with Java, R, rJava inside macOS. There is some mess, generally, there. You have to pay attention to few things like:

location of JDK,

making sure R points to proper libs,

making sure you are using Oracle's based JDK.

Eventually, you should get it running once setting all the stuff in place.

I don't post full description here as it's quite long. Also, pay attention to JDK settings that allow to run JNI based codes. You need to make sure that JDK has proper settings inside

```<code>`/usr/libexec/java_home`/../Info.plist
</code>```

Lots of things to be done, but eventually, it should work :)

Have fun with R.

Title: rJava install troubles

Body:
I am trying to get RJava to work.

I have downloaded the 64-bit Java and tried to manually set where to find my java within R Studio.

I keep on getting this error:

Error: package or namespace load failed for ‘rJava’:
 .onLoad failed in loadNamespace() for 'rJava', details:
  call: dyn.load(file, DLLpath = DLLpath, ...)
  error: unable to load shared object '/Library/Frameworks/R.framework/Versions/3.4/Resources/library/rJava/libs/rJava.so':
  dlopen(/Library/Frameworks/R.framework/Versions/3.4/Resources/library/rJava/libs/rJava.so, 6): Library not loaded: @rpath/libjvm.dylib
  Referenced from: /Library/Frameworks/R.framework/Versions/3.4/Resources/library/rJava/libs/rJava.so
  Reason: image not found

Any responses will be apreciated

Body:
Take a look at the location here: R, Java, rJava and macOS adventures

You can find there description of how to deal with Java, R, rJava inside macOS. There is some mess, generally, there. You have to pay attention to few things like:

location of JDK,

making sure R points to proper libs,

making sure you are using Oracle's based JDK.

Eventually, you should get it running once setting all the stuff in place.

I don't post full description here as it's quite long. Also, pay attention to JDK settings that allow to run JNI based codes. You need to make sure that JDK has proper settings inside

`/usr/libexec/java_home`/../Info.plist

Lots of things to be done, but eventually, it should work :)

Have fun with R.


问:
How to run two python application in docker
I want to run two python applicaiton in docker with different ports.

My shell script is below, the name is serverRun.sh

```<code>exec python __server_code.py &
exec python server_time_test.py &
</code>```

in dockerfile, I am trying to run these two python application

```<code>RUN ["chmod", "+x", "./serverRun.sh"]
</code>```

It did not work. Any idea?

答: The RUN instruction is only referenced during build. It won't be running when you launch the container. You want to use ENTRYPOINT or CMD

Body:
I want to run two python applicaiton in docker with different ports.

My shell script is below, the name is serverRun.sh

exec python __server_code.py &
exec python server_time_test.py &

in dockerfile, I am trying to run these two python application

RUN ["chmod", "+x", "./serverRun.sh"]

It did not work. Any idea?


问:
PHP Queries in Play Framework 1.3.x
I'd like to know if I can use PHP in order to get data from a MySQL database. A fraction of the code can be seen here:

```<code><?php
$servername = "localhost";
$username = "root";
$password = "pass";
$dbname = "name";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
     die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT aa, bb, cc FROM data";
$result = $conn->query($sql);
...
?>
</code>```

This is placed inside an HTML file in the Play Framework folder "views", and is properly loaded by the controller, but when it loads, it just shows me the code as if it were text, and not code or the action that would be supposed to do, so it is like it does not recognise it. How can I solve it?

答: Best thing to do is write it totally in php.  Forget about using the bloated playframework and trying to figure out all the connections that you would have to make to tie it all together.</p>

Title: PHP Queries in Play Framework 1.3.x

Body:
I'd like to know if I can use PHP in order to get data from a MySQL database. A fraction of the code can be seen here:

<?php
$servername = "localhost";
$username = "root";
$password = "pass";
$dbname = "name";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
     die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT aa, bb, cc FROM data";
$result = $conn->query($sql);
...
?>

This is placed inside an HTML file in the Play Framework folder "views", and is properly loaded by the controller, but when it loads, it just shows me the code as if it were text, and not code or the action that would be supposed to do, so it is like it does not recognise it. How can I solve it?


问:
React js nested axios call
How can i make nested axios call? I need to pass the result of first axios call as parameter to second axios

答:
You can chain just like a normal promise. Fire off the next request in the .then of the first request and then return that promise so you'll have a .then for you second request.

```<code>axios.get(...)
  .then((response) => {
    return axios.get(...); // using response.data
  })
  .then((response) => {
    console.log('Response', response);
  });
</code>```

Title: React js nested axios call

Body:
You can chain just like a normal promise. Fire off the next request in the .then of the first request and then return that promise so you'll have a .then for you second request.

axios.get(...)
  .then((response) => {
    return axios.get(...); // using response.data
  })
  .then((response) => {
    console.log('Response', response);
  });


问:
How can I Sort a List<int> using another List<int>?
I need to Sort a List using another List.
I am trying to use :

```<code>var docsIds = new List<int>() { 1, 7, 4 };
var tileSizes = new List<int>();
tileSizes = tileSizes.OrderBy(x => docsIds.IndexOf());
</code>```

Input : 1,2,3,4,5,6,7

Expected Output: 1,7,4,2,3,5,6

Any help is appreciated.

答:
Assuming that tileSizes only has values chosen from docIds (which seems to be the intent, though the question is a bit unclear), then the missing piece is a parameter to IndexOf(), specifically IndexOf(x).

Then, IndexOf() returns an integer showing where in docIds the value would be, and OrderBy() can use that in sorting.

Oh, right.  And OrderBy() doesn't return a List, but rather an Enumerable, so you'll need a ToList() at the end.  Putting that all together, your last line should be something like...

```<code>tileSizes = tileSizes.OrderBy(x => docsIds.IndexOf(x)).ToList();
</code>```

Body:
I need to Sort a List using another List.
I am trying to use :

var docsIds = new List<int>() { 1, 7, 4 };
var tileSizes = new List<int>();
tileSizes = tileSizes.OrderBy(x => docsIds.IndexOf());

Input : 1,2,3,4,5,6,7

Expected Output: 1,7,4,2,3,5,6

Any help is appreciated.

Body:
Assuming that tileSizes only has values chosen from docIds (which seems to be the intent, though the question is a bit unclear), then the missing piece is a parameter to IndexOf(), specifically IndexOf(x).

Then, IndexOf() returns an integer showing where in docIds the value would be, and OrderBy() can use that in sorting.

Oh, right.  And OrderBy() doesn't return a List, but rather an Enumerable, so you'll need a ToList() at the end.  Putting that all together, your last line should be something like...

tileSizes = tileSizes.OrderBy(x => docsIds.IndexOf(x)).ToList();


问:
Skip non capturing groups in regex
I wrote a regex to capture certain fields in the windows event logs, below is the regex:

```<code>(?:Subject\:)(?<Subject>.+)$[\n](?:Created)
</code>```

Below are the sample windows event logs which match the Regex.

```<code>Log: ABC
Source: DocumentService
Level: Error
Subject:

ABC.BizService.DocumentVendors.DocumentVendorException: No Instances

Created On (UTC): 7/6/2017 8:57:04 PM
Created On (Local Machine): 7/6/2017 4:57:04 PM

System Information
Machine: Server1
Operating System: Microsoft Windows NT 6.2.9200.0
Process ID: 1360
Process Name: abc.Server.Document
System Name: PROD
Domain: Dom1
User: DOM1\66

Message ID: 0
Transaction Context: 0
Exception Id: 00000000-0000-0000-0000-000000000000
Submitted Message:

Error building document '638. No Instances'
</code>```

When i use the output of the Regex i get the below output:

```<code>ABC.BizService.DocumentVendors.DocumentVendorException: No Instances

Created On (UTC): 7/6/2017 8:57:04 PM
</code>```

In the final output i even want to exclude this Created On field and everything after that. If you notice i just want to capture what is being written in the Subject Field. Looks like in my Regex i am even taking care of non capturing group. But they are still appearing.

答:
Since .+ is greedy, the capture group is matching everything up to the second Created line, so the first Created line is being included in the match.

Use a non-greedy quantifier .+? to get the shortest match rather than the longest one.

```<code>(?:Subject\:)(?<Subject>.+?)$[\n](?:Created)
</code>```

Title: Skip non capturing groups in regex

Body:
I wrote a regex to capture certain fields in the windows event logs, below is the regex:

(?:Subject\:)(?<Subject>.+)$[\n](?:Created)

Below are the sample windows event logs which match the Regex.

Log: ABC
Source: DocumentService
Level: Error
Subject:

ABC.BizService.DocumentVendors.DocumentVendorException: No Instances

Created On (UTC): 7/6/2017 8:57:04 PM
Created On (Local Machine): 7/6/2017 4:57:04 PM

System Information
Machine: Server1
Operating System: Microsoft Windows NT 6.2.9200.0
Process ID: 1360
Process Name: abc.Server.Document
System Name: PROD
Domain: Dom1
User: DOM1\66

Message ID: 0
Transaction Context: 0
Exception Id: 00000000-0000-0000-0000-000000000000
Submitted Message:

Error building document '638. No Instances'

When i use the output of the Regex i get the below output:

ABC.BizService.DocumentVendors.DocumentVendorException: No Instances

Created On (UTC): 7/6/2017 8:57:04 PM

In the final output i even want to exclude this Created On field and everything after that. If you notice i just want to capture what is being written in the Subject Field. Looks like in my Regex i am even taking care of non capturing group. But they are still appearing.

Body:
Since .+ is greedy, the capture group is matching everything up to the second Created line, so the first Created line is being included in the match.

Use a non-greedy quantifier .+? to get the shortest match rather than the longest one.

(?:Subject\:)(?<Subject>.+?)$[\n](?:Created)


问:
Get the longest text in HTML document using Jquery or javascript
HTML:

```<code><div id="customdiv">
<p>AAAAAA AAAAA AAAAA AAAAA AAAAA AAAA</p>
<p>AAAAAA</p>
<p>AAAAAA</p>
</div>
</code>```

I need the output like this:

Largest value is:AAAAAA AAAAA AAAAA AAAAA AAAAA AAAA
Length:37

答:
You can get the inner HTML of a tag by using the DOM's innerHTML property.

For your example, you could use

```<code>function findLongestText() {
  var longestInnerHTML = "";
  var pTags = document.getElementsByTagName("p");

  for (var i = 0; i < pTags.length; i++) {
    var innerHTML = pTags[i].innerHTML;

    if (innerHTML.length > longestInnerHTML.length) {
      longestInnerHTML = innerHTML;
    }
  }
  console.log("longest: " + longestInnerHTML);
}
</code>```

to find the longest p tag in your document.

Body:
HTML:

AAAAAA AAAAA AAAAA AAAAA AAAAA AAAA

AAAAAA

AAAAAA

I need the output like this:

Largest value is:AAAAAA AAAAA AAAAA AAAAA AAAAA AAAA
Length:37

Body:
You can get the inner HTML of a tag by using the DOM's innerHTML property.

For your example, you could use

function findLongestText() {
  var longestInnerHTML = "";
  var pTags = document.getElementsByTagName("p");

  for (var i = 0; i < pTags.length; i++) {
    var innerHTML = pTags[i].innerHTML;

    if (innerHTML.length > longestInnerHTML.length) {
      longestInnerHTML = innerHTML;
    }
  }
  console.log("longest: " + longestInnerHTML);
}

to find the longest p tag in your document.


问:
AWS lambda : Passing data from custom authorizer to business lambda
I am using custom authentication (with custom authorizer) for accessing AWS lambda. The authorization process works fine. But I have a problem to transmit data (ex principalId) between the authorizer lambda and the business lambda. All my lambdas are developed in JS.
As explain in AWS doc, in the authorizer lambda, I add few simple fields (principalId in the code below) in context field of the Auth response. But in my business lambda, I am not able to get these fields. The AWS documentation talks about $context variable.

First, could you explain me if the $context variable is another variable or the same variable than the context variable received in parameter of the JS function?

Second, could you explain me how to get in my business lambda the data field (ex: principalId) provided by the authorizer?

Seb

答: In addition to Alexis answer, principalId - is currently the only param which can be passed from custom authorizer to a Lambda (as of today). However, the workaround for passing custom params is to stringify JSON parameters into the principleId. The discussion on this matter is here</p>


问:
How to make textbox resize as the window resize
Any property to set to make textbox to resize according to the window size?</p>

答:
One method would be to bind the height and width of the TextBox to the height and width of the Window, for example:

<TextBox Height={Binding RelativeSource={RelativeSource FindAncestor,
           AncestorType={x:Type Window}}, Path=Height} />

There may be a different property that might want to bind to, or you might want to use an expression so the TextBox isn't exactly the Height/Width of the parent window.  A lot depends on your specific usage scenario, but this should be enough to get you started.

ContentLicense: CC BY-SA 2.5


问:
"Inline temporary variable" (IDE0019) fix causes syntax errors when used with interfaces
I'm getting an object from ViewData.Model in an ActionFilter, and I need to make sure it conforms to a given interface. Here's an example:

```<code>object d = DateTime.Now;
IComparable c = d as IComparable;
if (c != null)
{
    //do stuff
}
</code>```

Visual Studio 2017 gives me an IDE0019 "Inline temporary variable" suggestion on the second line. Selecting it refactors the code to this:

```<code>object d = DateTime.Now;
if (d is IComparable c) // Line 31
{
    //do stuff
}
</code>```

I like this syntax, and I'd like to use it. There are no errors shown in the editor, but when building I get a litany of errors:

```<code>1>C:\Users\me\MyProject\MyFile.cs(31,34,31,35): error CS1026: ) expected
1>C:\Users\me\MyProject\MyFile.cs(31,35,31,36): error CS1002: ; expected
1>C:\Users\me\MyProject\MyFile.cs(31,35,31,36): error CS1513: } expected
</code>```

Line 31 is the if statement. It looks like the compiler is expecting a lot more syntax, but I can't figure out what. The generated code appears identical to this example from the documentation for is:

```<code>public int CompareTo(Object o)
{
    if (o is Employee e)
    {
        return Name.CompareTo(e.Name);
    }
    throw new ArgumentException("o is not an Employee object.");
}
</code>```

How can I fix these errors? I'm on VS2017 (26430.14) and .NET Framework v4.0.30319.

答:
As found on VS 2017 - New C# 7 feature for out parameters causes project not to build:

Updating Microsoft.Net.Compilers package solved the problem on my asp.net mvc project.

From What is the Purpose of Microsoft.Net.Compilers?:

The point of the Microsoft.Net.Compilers package is that the compilers distributed with that package will be used for compiling your project, rather than the compiler that comes with .NET Framework or with Visual Studio.

So if you're upgrading an older project to use C# 7 features, and the project references that package, make sure to update that package as well, otherwise the compiler contained in that package will be used if the project is set to the "default" compiler.

Body:
I'm getting an object from ViewData.Model in an ActionFilter, and I need to make sure it conforms to a given interface. Here's an example:

object d = DateTime.Now;
IComparable c = d as IComparable;
if (c != null)
{
    //do stuff
}

Visual Studio 2017 gives me an IDE0019 "Inline temporary variable" suggestion on the second line. Selecting it refactors the code to this:

object d = DateTime.Now;
if (d is IComparable c) // Line 31
{
    //do stuff
}

I like this syntax, and I'd like to use it. There are no errors shown in the editor, but when building I get a litany of errors:

1>C:\Users\me\MyProject\MyFile.cs(31,34,31,35): error CS1026: ) expected
1>C:\Users\me\MyProject\MyFile.cs(31,35,31,36): error CS1002: ; expected
1>C:\Users\me\MyProject\MyFile.cs(31,35,31,36): error CS1513: } expected

Line 31 is the if statement. It looks like the compiler is expecting a lot more syntax, but I can't figure out what. The generated code appears identical to this example from the documentation for is:

public int CompareTo(Object o)
{
    if (o is Employee e)
    {
        return Name.CompareTo(e.Name);
    }
    throw new ArgumentException("o is not an Employee object.");
}

How can I fix these errors? I'm on VS2017 (26430.14) and .NET Framework v4.0.30319.


问:
What is a UTM code?
What Are UTM Codes and How Do You Use Them?

When you are navigating looking for products, there are some information about
you are looking for, that remains unvisible on the navigator and some pages uses them for identify your preferences.

Why appears some "&utm" references on url?

答:
Those are query string variables used by Google Analytics to tag links with additional metadata.

The "UTM" part refers to the historical "Urchin Tracking Module", as Google bought the Urchin company and evolved it into the Analytics product.

Title: What is a UTM code?


问:
Is it better to do things in fewer view controllers or less?
I'm learning swift3 by working on a project of my own and I was wondering if there was any rules/recommendations on minimizing the number of view Controllers or using more to minimize the activity happening in one view. Or is it really just preference?

For example, I can either segue into a new view or just have things disappear/appear - such as to fill information.

All I've seen so far is different approaches by people which makes me think it's preference.

答:
To answer the technical part of the query: don't factor performance into your thinking. A view controller is a very light thing — it normally uses fairly minimal storage and its job is primarily to react to view events. So processing costs are usually on demand, rather than intrinsic. Anything that is timed should be gated on viewDidAppear and viewDidDisappear, also so as not to cost anything unless that controller's views are visible.

Therefore the question is structure, not performance. I have an opinion about that — particularly since view controller containment was introduced, view controllers should do a single layout with the neatest implementation possible, with combinations and segues being handled by a parent, whether one of the supplied options such as UINavigationController or one of your own design, or if only segues are of interest then implicitly by that mechanism — but StackOverflow isn't really the forum for opinions because other people definitely think differently.


问:
single quote in php from java string
I have a java (android) application that uses php to talk to the MS database. The problem is one part in my app. I have a string that is a sql statement, and that string will not insert into the database with the single quotes

```<code>String sql = "select * from table where col = 'testing' AND Col2 = 'Tester'";
</code>```

I get that in the php script by using: $script = $_REQUEST['Script'];

2 things, I want to insert that script into a a column with the datatype char
and i also want to run that script as well. Thanks!

I am not having the users run there own scripts on my DB. as they check a checkbox it a StringBuilder builds a script upon what they select. So if they check Female or male The String add the Select * from Table where Gender = 'Female' etc.

答:
Try: </p>

```<code>$script = mysql_real_escape_string($_REQUEST['Script']);
</code>```

Title: single quote in php from java string

Body:
I have a java (android) application that uses php to talk to the MS database. The problem is one part in my app. I have a string that is a sql statement, and that string will not insert into the database with the single quotes

String sql = "select * from table where col = 'testing' AND Col2 = 'Tester'";

I get that in the php script by using: $script = $_REQUEST['Script'];

2 things, I want to insert that script into a a column with the datatype char
and i also want to run that script as well. Thanks!

I am not having the users run there own scripts on my DB. as they check a checkbox it a StringBuilder builds a script upon what they select. So if they check Female or male The String add the Select * from Table where Gender = 'Female' etc.

Body:
Try:

$script = mysql_real_escape_string($_REQUEST['Script']);


问:
Cannot find the VBA macro assigned to the button in Excel
I got a workbook from someone else, and there is a button assigned with a macro (since I can right click and choose Assign Macro to actually see the macro name).

However, I cannot find this macro in any Modules inside VBE as well as the code window behind ThisWorkbook and any Sheet (so it's not an event). In addition, I found that after I clicked Assign Macro option from right-click menu, I was switched to another worksheet that has several cells that looks like this,

But it looks to me that those formula are not from WorksheetFunction. Is the button really associated with a VBA macro or if this is just something else?

答:
That's an XLM sheet, the "pre-VBA" way of writing macros:

https://support.office.com/en-us/article/Working-with-Excel-4-0-macros-ba8924d4-e157-4bb2-8d76-2c07ff02e0b8


问:
Can spark execute table operations on remote nodes? (vs. row operations)
Most of spark's Dataset functions are per-row operations. However, I'd like to distribute execution of ML tasks to run on Spark -- most ML tasks are naturally operations that are functions of tables, and not natually functions of rows. (I've looked at MLLib -- its way too limited, and in many cases execution is made orders of magnitude slower in spark by distribute operations over many cores that could otherwise fit on a single core).

Its important that ML algorithms process collections of rows, not single rows, and so I'd like to materialize a table into memory on a node. (I pinky promise it will fit into core). How can I do this?

Functionally, I'd like to do:

```<code>def mlsubtask(table, arg2, arg3):
     data = table.collect()
     ...

sc = SparkContext(...)
sqlctx = SQLContext(sc)
...
df = sqlctx.sql("SELECT ...")
results = sc.parallelize([(df,arg2,arg3),(df,arg2,arg3),(df,arg2,arg3)]).map(mlsubtask).collect()
</code>```

If can perform execution like this:

```<code>sc = SparkContext(...)
sqlctx = SQLContext(sc)
...
df = sqlctx.sql("SELECT ...")
df = df.collect()
results = sc.parallelize([(df,arg2,arg3),(df,arg2,arg3),(df,arg2,arg3)]).map(mlsubtask).collect()
</code>```

... but this brings the data to the client, which in then re-serialized and quite inefficient.

答:
For a single task:</p>

```<code>def mlsubtask(iter_rows):
    data_table = list(iter_rows) # Or other way of bringing into memory.
   ...

df.repartition(1).mapPartitions(mlsubtask)
</code>```

Body:
Most of spark's Dataset functions are per-row operations. However, I'd like to distribute execution of ML tasks to run on Spark -- most ML tasks are naturally operations that are functions of tables, and not natually functions of rows. (I've looked at MLLib -- its way too limited, and in many cases execution is made orders of magnitude slower in spark by distribute operations over many cores that could otherwise fit on a single core).

Its important that ML algorithms process collections of rows, not single rows, and so I'd like to materialize a table into memory on a node. (I pinky promise it will fit into core). How can I do this?

Functionally, I'd like to do:

def mlsubtask(table, arg2, arg3):
     data = table.collect()
     ...

sc = SparkContext(...)
sqlctx = SQLContext(sc)
...
df = sqlctx.sql("SELECT ...")
results = sc.parallelize([(df,arg2,arg3),(df,arg2,arg3),(df,arg2,arg3)]).map(mlsubtask).collect()

If can perform execution like this:

sc = SparkContext(...)
sqlctx = SQLContext(sc)
...
df = sqlctx.sql("SELECT ...")
df = df.collect()
results = sc.parallelize([(df,arg2,arg3),(df,arg2,arg3),(df,arg2,arg3)]).map(mlsubtask).collect()

... but this brings the data to the client, which in then re-serialized and quite inefficient.

Body:
For a single task:

def mlsubtask(iter_rows):
    data_table = list(iter_rows) # Or other way of bringing into memory.
   ...

df.repartition(1).mapPartitions(mlsubtask)


问:
How can I make Web API serialize DateTime in any object into number of milliseconds since 1970?
In my ASP.NET web service I need all my dates to be serialized to JSON as numbers which represent a number of milliseconds passed since 1970 please. I'm using Newtonsoft.Json serializer. What do I need to do to set it up this way?

UPDATE:
the available documentation (http://www.newtonsoft.com/json/help/html/DatesInJSON.htm) only mentions serializing a single object with custom settings, what i am looking for is the default serialization settings that would govern serialization of any object

答:
I'm not sure if this is the easiest way, but you can create a custom converter for DateTimes, then a custom JsonMediaTypeFormatter which uses that converter.</p>

```<code>// This class overrides conversion for DateTime values
public class MyDateConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(DateTime);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        // Your algorithm here
        var customValue = ((DateTime)value).Ticks;
        writer.WriteValue(customValue);
    }
}

// This formatter will create serializers with the above converter injected
public class MyJsonFormatter : JsonMediaTypeFormatter
{
    public override JsonSerializer CreateJsonSerializer()
    {
        var serializer = base.CreateJsonSerializer();
        serializer.Converters.Add(new MyDateConverter());
        return serializer;
    }
}

// Inside your WebApi config code, replace the default formatter with your custom one
var defaultJsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
config.Formatters.Remove(defaultJsonFormatter);
config.Formatters.Insert(0, new MyJsonFormatter());
</code>```

Body:
I'm not sure if this is the easiest way, but you can create a custom converter for DateTimes, then a custom JsonMediaTypeFormatter which uses that converter.

// This class overrides conversion for DateTime values
public class MyDateConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(DateTime);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        // Your algorithm here
        var customValue = ((DateTime)value).Ticks;
        writer.WriteValue(customValue);
    }
}

// This formatter will create serializers with the above converter injected
public class MyJsonFormatter : JsonMediaTypeFormatter
{
    public override JsonSerializer CreateJsonSerializer()
    {
        var serializer = base.CreateJsonSerializer();
        serializer.Converters.Add(new MyDateConverter());
        return serializer;
    }
}

// Inside your WebApi config code, replace the default formatter with your custom one
var defaultJsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
config.Formatters.Remove(defaultJsonFormatter);
config.Formatters.Insert(0, new MyJsonFormatter());


问:
Eclipse editor tab wrap-around
I can switch editors in Eclipse by using Ctrl+PgUp/PdDown.

But when the leftmost editor tab is selected, I cannot switch one more tab to the left and wrap-around to get to the rightmost tab.

How can I make my editor tabs wrap-around?

答:
The Show most recently used tabs setting must be disabled for tabs to wrap-around.

Go to Preferences > General > Appearance and uncheck the Show most recently used tabs box.

Title: Eclipse editor tab wrap-around


答:
I usually like to do things a bit more manually, so there is my solution:

```<code>List<int> randomItems = new List<int>(){1,2,3,4,5,6,7};
List<int> outputOrder = new List<int>(){0,6,3,1,2,4,5};
List<int> resultList = new List<int>();

foreach(int order in outputOrder)
{
    resultList.Add(randomItems[order]);
}
</code>```

Edited in order to replicate the OP values

The resultList will contain: 1,7,4,2,3,5,6

Alternatively you can have the outputOrder like this:

```<code>List<int> outputOrder = new List<int>(){1,7,4,2,3,5,6};
</code>```

and simply change the loop instruction to:

```<code>resultList.Add(randomItems[order--]);
</code>```

And the result will be the same.

Title: How can I Sort a List<int> using another List<int>?

Body:
I usually like to do things a bit more manually, so there is my solution:

List<int> randomItems = new List<int>(){1,2,3,4,5,6,7};
List<int> outputOrder = new List<int>(){0,6,3,1,2,4,5};
List<int> resultList = new List<int>();

foreach(int order in outputOrder)
{
    resultList.Add(randomItems[order]);
}

Edited in order to replicate the OP values

The resultList will contain: 1,7,4,2,3,5,6

Alternatively you can have the outputOrder like this:

List<int> outputOrder = new List<int>(){1,7,4,2,3,5,6};

and simply change the loop instruction to:

resultList.Add(randomItems[order--]);

And the result will be the same.


问:
How to detect 'Enter' key on keyPress when used with React
I am using ReactJs to develop my application. I am trying to submit an input text when Enter is pressed by handling the onKeyPress event. It detects other inputs, but not enter. I have tried different ways - event.key, event.charCode, event.keyCode, event.which... Nothing seems to work.

```<code>React.createElement("input", {tabIndex: "1", onKeyPress: this.handleKeyPress, onChange: this.handleChange,
                           placeholder: "ex: 1,10,15"}),

handleChange: function (event) {
        this.setState({userInputBuckets: event.target.value});
    },
handleKeyPress: function (event) {
        if (event.charCode == 13) {
            event.preventDefault();
            this.props.table.handleSubtotalBy(this.props.columnDef, this.state.userInputBuckets);
        }
    },
</code>```

I also tried with onKewDown handling, it detects the correct key, but it doesn't execute the if block even though it evaluates event.keyCode == 13 as true.

答:
Move e.stopPropagataion from handleSubtotalBy into handleKeyPress:

```<code>handleKeyPress(event) {
  if (event.charCode == 13) {
    event.preventDefault();
    event.stopPropagation();
    this.props.table.handleSubtotalBy(this.props.columnDef, this.state.userInputBuckets);
  }
}

handleSubtotalBy(columnDef, partitions) {
  const subtotalBy = this.state.subtotalBy || [];
  // ...
}
</code>```

Body:
I am using ReactJs to develop my application. I am trying to submit an input text when Enter is pressed by handling the onKeyPress event. It detects other inputs, but not enter. I have tried different ways - event.key, event.charCode, event.keyCode, event.which... Nothing seems to work.

React.createElement("input", {tabIndex: "1", onKeyPress: this.handleKeyPress, onChange: this.handleChange,
                           placeholder: "ex: 1,10,15"}),

handleChange: function (event) {
        this.setState({userInputBuckets: event.target.value});
    },
handleKeyPress: function (event) {
        if (event.charCode == 13) {
            event.preventDefault();
            this.props.table.handleSubtotalBy(this.props.columnDef, this.state.userInputBuckets);
        }
    },

I also tried with onKewDown handling, it detects the correct key, but it doesn't execute the if block even though it evaluates event.keyCode == 13 as true.

Body:
Move e.stopPropagataion from handleSubtotalBy into handleKeyPress:

handleKeyPress(event) {
  if (event.charCode == 13) {
    event.preventDefault();
    event.stopPropagation();
    this.props.table.handleSubtotalBy(this.props.columnDef, this.state.userInputBuckets);
  }
}

handleSubtotalBy(columnDef, partitions) {
  const subtotalBy = this.state.subtotalBy || [];
  // ...
}


问:
Iterating over multiple rows in Python - Science Data Cleaning
I am working with a large private dataset and I need some assistance in figuring out how to iterate a program over multiple rows.

```<code>import csv

with open('report_export.csv') as f:

    reader = csv.DictReader(f)
    report_export = list(reader)

x = report_export[25]["Text_Content"]
x.split(sep='. ')[1]

 ' Azithromycin is an antibiotic agent and a member of a subclass of
   macrolide antibiotics with bactericidal and bacteriostatic activities.
</code>```

report_export.csv is a data file pull from a local database containing information chemicals from publications. I want some textual information from this file. It is located under the column "Text Content". "25" is a random row that worked as proof of principle for the code. The x.split(sep='. ')[1] is used
 for isolating the desired string and differentiating between decimals and periods. This file is rather large, 5000 rows on CSV, and I want to be able to extract statements about the chemicals similar to output above.

I am having difficulty figuring out how to iterate over multiple rows in this case. I need the program to read over the rows, retrieve the 2nd string (1 position) from the list, and be able to save this data to a new csv file.

Any assistance with achieving the ability to iterate over rows would be helpful.

Thank you!

Best,

PEB

答:
The call to list(reader) will read the entire file into a list. To iterate over rows in the csv file without reading everything in at once, replace that line with a loop:

```<code>for row in reader:
    x = row["Text_Content"]
    etc.
</code>```

That said, five thousand rows is not that much, so you could also just iterate over the list report_export that you created:

```<code>for row in report_export:
    x = row["Text_Content"]
    etc.
</code>```

Body:
I am working with a large private dataset and I need some assistance in figuring out how to iterate a program over multiple rows.

import csv

with open('report_export.csv') as f:

    reader = csv.DictReader(f)
    report_export = list(reader)

x = report_export[25]["Text_Content"]
x.split(sep='. ')[1]

 ' Azithromycin is an antibiotic agent and a member of a subclass of
   macrolide antibiotics with bactericidal and bacteriostatic activities.

report_export.csv is a data file pull from a local database containing information chemicals from publications. I want some textual information from this file. It is located under the column "Text Content". "25" is a random row that worked as proof of principle for the code. The x.split(sep='. ')[1] is used
 for isolating the desired string and differentiating between decimals and periods. This file is rather large, 5000 rows on CSV, and I want to be able to extract statements about the chemicals similar to output above.

I am having difficulty figuring out how to iterate over multiple rows in this case. I need the program to read over the rows, retrieve the 2nd string (1 position) from the list, and be able to save this data to a new csv file.

Any assistance with achieving the ability to iterate over rows would be helpful.

Thank you!

Best,

PEB

Body:
The call to list(reader) will read the entire file into a list. To iterate over rows in the csv file without reading everything in at once, replace that line with a loop:

for row in reader:
    x = row["Text_Content"]
    etc.

That said, five thousand rows is not that much, so you could also just iterate over the list report_export that you created:

for row in report_export:
    x = row["Text_Content"]
    etc.


问:
Horizontal Sliding Transition Scrolling
I am brand new to Android development and have gotten through these two resources successfully:

http://news.softpedia.com/news/How-to-Run-Android-Applications-on-Ubuntu-115152.shtml

http://wiki.phonegap.com/w/page/30862722/phonegap-android-eclipse-quickstart

Now I want to make the index.html have a button on it, that, when clicked, does a horizontal right-to-left sliding page transition to a right.html. And when I click a button in right.html, I want to do a left-to-right horizontal sliding page transition right back.

Can anyone demonstrate what I am to do in index.html and right.html to achieve this? Or, do you think it's easier to do this with some framework that goes on top of the Javascript, such as Zepto.js, or jQuery, or Sencha Touch, or jQTouch?

EDIT: I think what I'm hearing is that I need to learn about Webkit Transformations, which provide the sliding effects?

答:
CSS transitions are not meant to transition between two different html files, they are meant to transition between two different css states. You could work around this placing the content in an iframe, or populating a div with an ajax request, but it would be going against the grain.

If you know CSS and a tiny bit of Javascript you can accomplish it with relative ease.

http://jsfiddle.net/ANZpm/

(view in a webkit browser or FF4). I coded this in five minutes, and it's dead simple if you are well versed in CSS.

I would recommend playing around with CSS transitions and then jumping to the framework craze.

Title: Horizontal Sliding Transition Scrolling


问:
Discord Bot [VB.net] Check if message has a mentioned user
```<code>Case "-move" 'The command 'n shizzle like that ;p
If message.serverpermission.Administrator = true then
Dim user = message.Message.MentionedUsers.FirstOrDefault()
Dim role = message.Server.FindRoles(arg, True).FirstOrDefault()
Await user.AddRoles(role) '!error on this line!
</code>```

I want to check if the admin specified an user, if not, he will receive an error like ,,There is no one online with that name" or like ... ,,You need to specify/mention an user"
(Program returns an error if no one is mentioned&crashes;

System.NullReferenceException; 'Object reference not set to an
  instance of an object.')

If you could help me with this problem, thanks! ^^

答:
I've found the fix for the problem here;</p>

```<code>If IsNothing(user) Then
Await message.Channel.SendMessage("You need to mention a user.")
else
if isnothing(role) then
Await message.Channel.SendMessage("That role is invalid.")
else
Await message.Channel.SendMessage("Success message here ;P")
end if
end if
</code>```

Body:
Case "-move" 'The command 'n shizzle like that ;p
If message.serverpermission.Administrator = true then
Dim user = message.Message.MentionedUsers.FirstOrDefault()
Dim role = message.Server.FindRoles(arg, True).FirstOrDefault()
Await user.AddRoles(role) '!error on this line!

I want to check if the admin specified an user, if not, he will receive an error like ,,There is no one online with that name" or like ... ,,You need to specify/mention an user"
(Program returns an error if no one is mentioned&crashes;

System.NullReferenceException; 'Object reference not set to an
  instance of an object.')

If you could help me with this problem, thanks! ^^

Body:
I've found the fix for the problem here;

If IsNothing(user) Then
Await message.Channel.SendMessage("You need to mention a user.")
else
if isnothing(role) then
Await message.Channel.SendMessage("That role is invalid.")
else
Await message.Channel.SendMessage("Success message here ;P")
end if
end if


问:
Trying to set up a paginated query on firebase
I'm trying to set up a paginated query on my firebase database.

I have data in this format

```<code>"posts":
{
    1 : {//more nested data}
    2 : {}
    3 : {}
}
</code>```

And so on.

I'm trying to set up a query on Android such that it fetches 5 nodes at a time.

I tried this
Note : mDBref points to /posts

```<code>mDBRef.orderByKey()
.startAt("1")
.limitToFirst(5)
.ref();
</code>```

And running a single value event listener on that ref.

However I'm getting in my dataSnapshot all the 7 elements I have within /posts

Apologies in advance for the formatting, I'm posting this on mobile.

答:
That last ref() call at the end returns the reference to the entire location.

Do this instead:

```<code>Query query = mDBRef.orderByKey()
    .startAt("1")
    .limitToFirst(5);
</code>```

Two additional points:

The method is called getRef() on Android, not ref().

Where did you get the idea from to add ref() at the end? I've seen this mistake a few times recently and would like to remove the source of it if possible.

Body:
I'm trying to set up a paginated query on my firebase database.

I have data in this format

"posts":
{
    1 : {//more nested data}
    2 : {}
    3 : {}
}

And so on.

I'm trying to set up a query on Android such that it fetches 5 nodes at a time.

I tried this
Note : mDBref points to /posts

mDBRef.orderByKey()
.startAt("1")
.limitToFirst(5)
.ref();

And running a single value event listener on that ref.

However I'm getting in my dataSnapshot all the 7 elements I have within /posts

Apologies in advance for the formatting, I'm posting this on mobile.

Body:
That last ref() call at the end returns the reference to the entire location.

Do this instead:

Query query = mDBRef.orderByKey()
    .startAt("1")
    .limitToFirst(5);

Two additional points:

The method is called getRef() on Android, not ref().

Where did you get the idea from to add ref() at the end? I've seen this mistake a few times recently and would like to remove the source of it if possible.


问:
getElementID dont work on chrome
I have a code like this:

```<code>parent.document.getElementById("test").value ="1";
</code>```

but it doesnt work on chrome. The error is:

"Uncaught TypeError: Cannot call
  method 'getElementById' of undefined"

any help is apreciated thanks in advance! :)

答:
Well, this is strange. Because your code should work. I even tested it now to be sure. So somehow your parent isn't the window object. That's why it has no document property.

The global parent is the parent property of the window object (window.parent) which usually points to the window object itself . So usually parent and window are the same thing and you don't even have to use this object explicitly most of the time.

So my guess is that you've somehow overwritten parent with some other object.

Edit: My second guess is that you haven't overwritten parent yourself but have embedded the window into another window. So your parent becomes this outer window and you probably don't have access to its document.

Title: getElementID dont work on chrome

Body:
I have a code like this:

parent.document.getElementById("test").value ="1";

but it doesnt work on chrome. The error is:

"Uncaught TypeError: Cannot call
  method 'getElementById' of undefined"

any help is apreciated thanks in advance! :)