问:
mvn compilation error LifecycleExecutionException
I've installed maven by adding it to my path. When I run the command mvn -v it returns:

```<code>Apache Maven 3.5.2 (138edd61fd100ec658bfa2d307c43b76940a5d7d; 2017-10-18T10:58:13+03:00)
Maven home: /Users/yarkoni/apache-maven-3.5.2 Java version: 9, vendor: Oracle Corporation
Java home: /Library/Java/JavaVirtualMachines/jdk-9.jdk/Contents/Home
Default locale: en_US, platform encoding: UTF-8 OS name: "mac os x",
version: "10.12.6", arch: "x86_64", family: "mac"
</code>```

To my understand in order to install I downloaded and added it to my PATH.
I then try to runt he example appEngine app locally:

```<code>mvn -Plocal clean appengine:devserver
</code>```

I get the following error:

```<code>    [INFO] Compiling 11 source files to /Users/yarkoni/Projects/getting-started-java/bookshelf-standard/2-structured-data/target/bookshelf-standard-2-1.0-SNAPSHOT/WEB-INF/classes An exception has occurred in the compiler (9-internal).
Please file a bug against the Java compiler via the Java bug reporting page (http://bugreport.java.com) after checking the Bug Database (http://bugs.java.com) for duplicates. Include your program and the following diagnostic in your report. Thank you.
java.io.UncheckedIOException: java.nio.file.NotDirectoryException: /Library/Java/JavaVirtualMachines/jdk-9.jdk/Contents/Home/lib/modules
    at com.sun.tools.javac.file.Locations$BootClassPathLocationHandler.lazy(Locations.java:712)
    at com.sun.tools.javac.file.Locations$BootClassPathLocationHandler.isDefault(Locations.java:546)
    at com.sun.tools.javac.file.Locations.isDefaultBootClassPath(Locations.java:126)
    at com.sun.tools.javac.file.BaseFileManager.isDefaultBootClassPath(BaseFileManager.java:204)
    at com.sun.tools.javac.main.Arguments.validate(Arguments.java:479)
    at com.sun.tools.javac.api.JavacTaskImpl.prepareCompiler(JavacTaskImpl.java:168)
    at com.sun.tools.javac.api.JavacTaskImpl.access$000(JavacTaskImpl.java:69)
    at com.sun.tools.javac.api.JavacTaskImpl$1.call(JavacTaskImpl.java:96)
    at com.sun.tools.javac.api.JavacTaskImpl$1.call(JavacTaskImpl.java:93)
    at com.sun.tools.javac.api.JavacTaskImpl.handleExceptions(JavacTaskImpl.java:128)
    at com.sun.tools.javac.api.JavacTaskImpl.doCall(JavacTaskImpl.java:93)
    at com.sun.tools.javac.api.JavacTaskImpl.call(JavacTaskImpl.java:87)
    at com.google.errorprone.BaseErrorProneJavaCompiler$1.call(BaseErrorProneJavaCompiler.java:99)
    at com.google.errorprone.BaseErrorProneCompiler.run(BaseErrorProneCompiler.java:137)
    at com.google.errorprone.BaseErrorProneCompiler.run(BaseErrorProneCompiler.java:108)
    at com.google.errorprone.ErrorProneCompiler.run(ErrorProneCompiler.java:119)
    at org.codehaus.plexus.compiler.javac.errorprone.JavacCompilerWithErrorProne$CompilerInvoker.compile(JavacCompilerWithErrorProne.java:222)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    at org.codehaus.plexus.compiler.javac.errorprone.JavacCompilerWithErrorProne.performCompile(JavacCompilerWithErrorProne.java:91)
    at org.apache.maven.plugin.compiler.AbstractCompilerMojo.execute(AbstractCompilerMojo.java:943)
    at org.apache.maven.plugin.compiler.CompilerMojo.execute(CompilerMojo.java:137)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:134)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:208)
    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.MojoExecutor.executeForkedExecutions(MojoExecutor.java:353)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:198)
    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:955)
    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:290)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:194)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    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: java.nio.file.NotDirectoryException: /Library/Java/JavaVirtualMachines/jdk-9.jdk/Contents/Home/lib/modules
    at java.base/sun.nio.fs.UnixFileSystemProvider.newDirectoryStream(UnixFileSystemProvider.java:407)
    at java.base/java.nio.file.Files.newDirectoryStream(Files.java:465)
    at java.base/java.nio.file.Files.list(Files.java:3524)
    at com.sun.tools.javac.file.Locations$BootClassPathLocationHandler.systemClasses(Locations.java:665)
    at com.sun.tools.javac.file.Locations$BootClassPathLocationHandler.computePath(Locations.java:621)
    at com.sun.tools.javac.file.Locations$BootClassPathLocationHandler.lazy(Locations.java:709)     ... 49 more
</code>```

答:
```<code> java.nio.file.NotDirectoryException: /Library/Java/JavaVirtualMachines/jdk-9.jdk/Contents/Home/lib/modules
</code>```

Seems like /Library/Java/JavaVirtualMachines/jdk-9.jdk/Contents/Home/lib/modules is not a directory in your current file system, but it should be. Maybe a someone or something messed with your Java installation. You should make sure this path point to a directory or re-install your JDK.

Body:
I've installed maven by adding it to my path. When I run the command mvn -v it returns:

Apache Maven 3.5.2 (138edd61fd100ec658bfa2d307c43b76940a5d7d; 2017-10-18T10:58:13+03:00)
Maven home: /Users/yarkoni/apache-maven-3.5.2 Java version: 9, vendor: Oracle Corporation
Java home: /Library/Java/JavaVirtualMachines/jdk-9.jdk/Contents/Home
Default locale: en_US, platform encoding: UTF-8 OS name: "mac os x",
version: "10.12.6", arch: "x86_64", family: "mac"

To my understand in order to install I downloaded and added it to my PATH.
I then try to runt he example appEngine app locally:

mvn -Plocal clean appengine:devserver

I get the following error:

    [INFO] Compiling 11 source files to /Users/yarkoni/Projects/getting-started-java/bookshelf-standard/2-structured-data/target/bookshelf-standard-2-1.0-SNAPSHOT/WEB-INF/classes An exception has occurred in the compiler (9-internal).
Please file a bug against the Java compiler via the Java bug reporting page (http://bugreport.java.com) after checking the Bug Database (http://bugs.java.com) for duplicates. Include your program and the following diagnostic in your report. Thank you.
java.io.UncheckedIOException: java.nio.file.NotDirectoryException: /Library/Java/JavaVirtualMachines/jdk-9.jdk/Contents/Home/lib/modules
    at com.sun.tools.javac.file.Locations$BootClassPathLocationHandler.lazy(Locations.java:712)
    at com.sun.tools.javac.file.Locations$BootClassPathLocationHandler.isDefault(Locations.java:546)
    at com.sun.tools.javac.file.Locations.isDefaultBootClassPath(Locations.java:126)
    at com.sun.tools.javac.file.BaseFileManager.isDefaultBootClassPath(BaseFileManager.java:204)
    at com.sun.tools.javac.main.Arguments.validate(Arguments.java:479)
    at com.sun.tools.javac.api.JavacTaskImpl.prepareCompiler(JavacTaskImpl.java:168)
    at com.sun.tools.javac.api.JavacTaskImpl.access$000(JavacTaskImpl.java:69)
    at com.sun.tools.javac.api.JavacTaskImpl$1.call(JavacTaskImpl.java:96)
    at com.sun.tools.javac.api.JavacTaskImpl$1.call(JavacTaskImpl.java:93)
    at com.sun.tools.javac.api.JavacTaskImpl.handleExceptions(JavacTaskImpl.java:128)
    at com.sun.tools.javac.api.JavacTaskImpl.doCall(JavacTaskImpl.java:93)
    at com.sun.tools.javac.api.JavacTaskImpl.call(JavacTaskImpl.java:87)
    at com.google.errorprone.BaseErrorProneJavaCompiler$1.call(BaseErrorProneJavaCompiler.java:99)
    at com.google.errorprone.BaseErrorProneCompiler.run(BaseErrorProneCompiler.java:137)
    at com.google.errorprone.BaseErrorProneCompiler.run(BaseErrorProneCompiler.java:108)
    at com.google.errorprone.ErrorProneCompiler.run(ErrorProneCompiler.java:119)
    at org.codehaus.plexus.compiler.javac.errorprone.JavacCompilerWithErrorProne$CompilerInvoker.compile(JavacCompilerWithErrorProne.java:222)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    at org.codehaus.plexus.compiler.javac.errorprone.JavacCompilerWithErrorProne.performCompile(JavacCompilerWithErrorProne.java:91)
    at org.apache.maven.plugin.compiler.AbstractCompilerMojo.execute(AbstractCompilerMojo.java:943)
    at org.apache.maven.plugin.compiler.CompilerMojo.execute(CompilerMojo.java:137)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:134)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:208)
    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.MojoExecutor.executeForkedExecutions(MojoExecutor.java:353)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:198)
    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:955)
    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:290)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:194)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    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: java.nio.file.NotDirectoryException: /Library/Java/JavaVirtualMachines/jdk-9.jdk/Contents/Home/lib/modules
    at java.base/sun.nio.fs.UnixFileSystemProvider.newDirectoryStream(UnixFileSystemProvider.java:407)
    at java.base/java.nio.file.Files.newDirectoryStream(Files.java:465)
    at java.base/java.nio.file.Files.list(Files.java:3524)
    at com.sun.tools.javac.file.Locations$BootClassPathLocationHandler.systemClasses(Locations.java:665)
    at com.sun.tools.javac.file.Locations$BootClassPathLocationHandler.computePath(Locations.java:621)
    at com.sun.tools.javac.file.Locations$BootClassPathLocationHandler.lazy(Locations.java:709)     ... 49 more

Body:
 java.nio.file.NotDirectoryException: /Library/Java/JavaVirtualMachines/jdk-9.jdk/Contents/Home/lib/modules

Seems like /Library/Java/JavaVirtualMachines/jdk-9.jdk/Contents/Home/lib/modules is not a directory in your current file system, but it should be. Maybe a someone or something messed with your Java installation. You should make sure this path point to a directory or re-install your JDK.


来源: stackexchange

问:
Copy database tables from one database to another DB EF code first
I have a database with two tables :

```<code>Employee       Salary
========      ================
Id Name        Id EmpId  Salary
</code>```

and of course there is a class for each table to implement code first migration.

Is there any way to copy the database tables from the source database to another database and change the names of the tables using EF code-first?

PS: The target for this method is to create default database with default structure and when new client register create his own tables in existing database with new name

答:
The easiest thing to do is to run code first against the database you are trying to copy the tables from (Add-> New Item -> Data -> ADO.NET Entity Data Model -> Code First from database.) Check off the tables you want to import. When you are done doing that delete the Entity DBContext and the connection string in your web.config. This will create all the models from the db you are trying to create. Add them to your model; Done.</p>

```<code>public DbSet<StudentsModel> MyNewTable{ get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder) {
     modelBuilder.Entity<MyNewTable>().ToTable("MyTable");
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a database with two tables :

Employee       Salary
========      ================
Id Name        Id EmpId  Salary

and of course there is a class for each table to implement code first migration.

Is there any way to copy the database tables from the source database to another database and change the names of the tables using EF code-first?

PS: The target for this method is to create default database with default structure and when new client register create his own tables in existing database with new name

Body:
The easiest thing to do is to run code first against the database you are trying to copy the tables from (Add-> New Item -> Data -> ADO.NET Entity Data Model -> Code First from database.) Check off the tables you want to import. When you are done doing that delete the Entity DBContext and the connection string in your web.config. This will create all the models from the db you are trying to create. Add them to your model; Done.

public DbSet<StudentsModel> MyNewTable{ get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder) {
     modelBuilder.Entity<MyNewTable>().ToTable("MyTable");


问:
Android Picasso Image does not load
There are two situations I load images, first, just directly from the internet, and second, load images that are downloaded in the device. And whenever I load, 8~9 out of 10 images are shown, and 1-2 missing.  I see that decode returned false, and google'd as hard as I can, but couldn't come up.

WAIT_FOR_CONCURRENT_GC blocked 22ms

WAIT_FOR_CONCURRENT_GC blocked 20ms

GC_FOR_ALLOC freed 718K, 31% free 9948K/14256K, paused 49ms, total 51ms

D/skia: --- decoder->decode returned falseGC_CONCURRENT freed 1370K, 30% free 10081K/14256K, paused 3ms+2ms, total 33ms

GC_FOR_ALLOC freed 916K, 30% free 10029K/14256K, paused 66ms, total 67ms

Here's code I use to load through Picasso:

```<code>        Picasso.with(activity)
            .load(path)
            .placeholder(R.drawable.thumbnail_placeholder)
            .resize(width,height)
            .into(imageView);
</code>```

Any ideas how to solve this issue? I am calling fit()/resize() every time I get the images to load on the screen. Help much appreciated, thanks in advance!

FYI, I test on both machines, emulator and the real device, Samsung Galaxy Tab 3, and works without any problems on emulator, but problems occur on real device.

UPDATE:

It was causing by image's color space, where images that weren't showing up were the ones that were in YMCK color space.

答:
If anything not works, it is because of the some problem with the servers that are hosting images, their url does not directly take you to the image, but in backend something else is working, it may open in chrome or other browser, but not for sure in picasso it will load, so you may try this code :

```<code>final OkHttpClient client = new OkHttpClient.Builder()
        .protocols(Collections.singletonList(Protocol.HTTP_1_1))
        .build();

final Picasso picasso = new Picasso.Builder(this)
        .downloader(new OkHttp3Downloader(client))
        .build();

Picasso.setSingletonInstance(picasso);
</code>```

where the OkHttp3Downloader instance is supplied by this library.
https://github.com/JakeWharton/picasso2-okhttp3-downloader

Title: Android Picasso Image does not load

Body:
There are two situations I load images, first, just directly from the internet, and second, load images that are downloaded in the device. And whenever I load, 8~9 out of 10 images are shown, and 1-2 missing.  I see that decode returned false, and google'd as hard as I can, but couldn't come up.

WAIT_FOR_CONCURRENT_GC blocked 22ms

WAIT_FOR_CONCURRENT_GC blocked 20ms

GC_FOR_ALLOC freed 718K, 31% free 9948K/14256K, paused 49ms, total 51ms

D/skia: --- decoder->decode returned falseGC_CONCURRENT freed 1370K, 30% free 10081K/14256K, paused 3ms+2ms, total 33ms

GC_FOR_ALLOC freed 916K, 30% free 10029K/14256K, paused 66ms, total 67ms

Here's code I use to load through Picasso:

        Picasso.with(activity)
            .load(path)
            .placeholder(R.drawable.thumbnail_placeholder)
            .resize(width,height)
            .into(imageView);

Any ideas how to solve this issue? I am calling fit()/resize() every time I get the images to load on the screen. Help much appreciated, thanks in advance!

FYI, I test on both machines, emulator and the real device, Samsung Galaxy Tab 3, and works without any problems on emulator, but problems occur on real device.

UPDATE:

It was causing by image's color space, where images that weren't showing up were the ones that were in YMCK color space.

Body:
If anything not works, it is because of the some problem with the servers that are hosting images, their url does not directly take you to the image, but in backend something else is working, it may open in chrome or other browser, but not for sure in picasso it will load, so you may try this code :

final OkHttpClient client = new OkHttpClient.Builder()
        .protocols(Collections.singletonList(Protocol.HTTP_1_1))
        .build();

final Picasso picasso = new Picasso.Builder(this)
        .downloader(new OkHttp3Downloader(client))
        .build();

Picasso.setSingletonInstance(picasso);

where the OkHttp3Downloader instance is supplied by this library.
https://github.com/JakeWharton/picasso2-okhttp3-downloader


问:
Confusion with type inference of literals in Go
I have started learning GoLang and I am currently reading about its type inference system using the short variable declaration syntax.

Here is a simple program that caught my attention and is causing me some diffculty in understanding:

```<code>package main

import (
    "fmt"
    "sort"
)

type statistics struct {
    numbers []float64
    mean    float64
    median  float64
}

// Performs analytics on a slice of floating-point numbers
func GenerateStats(numbers []float64) (stats statistics) {
    stats.numbers = numbers
    stats.mean = sum(numbers) / float64(len(numbers))
    sort.Float64s(numbers)
    stats.median = median(numbers)
    return stats
}

// Helper function to sum up a slice of floats
func sum(numbers []float64) (total float64) {
    for _, num := range numbers {
        total += num
    }
    return total
}

// Helper to find the median of a sorted slice of floats
func median(numbers []float64) (med float64) {
    n := len(numbers)
    if n%2 == 0 {
        med = numbers[n/2]
    } else {
        med = (numbers[n/2] + numbers[(n-1)/2]) / 2 // Infer 01
    }
    return med
}

func main() {
    nums := []float64{1, 2, 3, 3, 4}
    result := generateStats(nums)
    fmt.Println(result.numbers)
    fmt.Println(result.mean)
    fmt.Println(result.median)

    b := "This is Go" + 1.9 // Infer 02
    fmt.Println(b)
}
</code>```

When I execute this program using: $ go run <path>/statistics.go,

I get the following error message:

```<code># command-line-arguments
<path>/statistics.go:47:20: cannot convert "This is Go" to type float64
<path>/statistics.go:47:20: invalid operation: "This is Go" + 1.9 (mismatched types string and float64)
</code>```

Here is reasoning for the different behavious:

Infer 01: The type of numeric literal 2 is inferred on the basis of the expression it is used in. Since the type of numerator is float64, Go performs the division successfully by assuming 2 as of the corresponding type. Hence, the type of the variable on LHS is float64.

I used the same reasoning for Infer 02:
The type of float literal 1.9 is inferred on the basis of the declaration. However, a float literal cannot be added to a string unless it is implicitly converted to a string. So, I am unsure about the type of the variable b. Hence, an error should be raised.

Now, I am confused by the error message.

Why does the compiler try to implicitly convert string literal to float64 type?

In a general sense: How does the compiler infer types when both the operands are literals? What are some good resources that can help me understand Go's type inference system better?

答:
It does not try to convert it to float64 type. It just warns about the string literal not being of float64.

It could say either the string is not a float, or the float is not a string, but the second line covers both of the cases with the message mismatched types string and float64.

Body:
I have started learning GoLang and I am currently reading about its type inference system using the short variable declaration syntax.

Here is a simple program that caught my attention and is causing me some diffculty in understanding:

package main

import (
    "fmt"
    "sort"
)

type statistics struct {
    numbers []float64
    mean    float64
    median  float64
}

// Performs analytics on a slice of floating-point numbers
func GenerateStats(numbers []float64) (stats statistics) {
    stats.numbers = numbers
    stats.mean = sum(numbers) / float64(len(numbers))
    sort.Float64s(numbers)
    stats.median = median(numbers)
    return stats
}

// Helper function to sum up a slice of floats
func sum(numbers []float64) (total float64) {
    for _, num := range numbers {
        total += num
    }
    return total
}

// Helper to find the median of a sorted slice of floats
func median(numbers []float64) (med float64) {
    n := len(numbers)
    if n%2 == 0 {
        med = numbers[n/2]
    } else {
        med = (numbers[n/2] + numbers[(n-1)/2]) / 2 // Infer 01
    }
    return med
}

func main() {
    nums := []float64{1, 2, 3, 3, 4}
    result := generateStats(nums)
    fmt.Println(result.numbers)
    fmt.Println(result.mean)
    fmt.Println(result.median)

    b := "This is Go" + 1.9 // Infer 02
    fmt.Println(b)
}

When I execute this program using: $ go run <path>/statistics.go,

I get the following error message:

# command-line-arguments
<path>/statistics.go:47:20: cannot convert "This is Go" to type float64
<path>/statistics.go:47:20: invalid operation: "This is Go" + 1.9 (mismatched types string and float64)

Here is reasoning for the different behavious:

Infer 01: The type of numeric literal 2 is inferred on the basis of the expression it is used in. Since the type of numerator is float64, Go performs the division successfully by assuming 2 as of the corresponding type. Hence, the type of the variable on LHS is float64.

I used the same reasoning for Infer 02:
The type of float literal 1.9 is inferred on the basis of the declaration. However, a float literal cannot be added to a string unless it is implicitly converted to a string. So, I am unsure about the type of the variable b. Hence, an error should be raised.

Now, I am confused by the error message.

Why does the compiler try to implicitly convert string literal to float64 type?

In a general sense: How does the compiler infer types when both the operands are literals? What are some good resources that can help me understand Go's type inference system better?


问:
How to set a trigger in Parsley for all input fields via Javascript?
Using ParsleyJs, I'd like to set the trigger for each input field to focusout.

I'm able to set it through data attributes in the html, like this:

```<code><input type="text" name="my-input
       data-parsley-trigger="focusout"
       required>
</code>```

To do the same in Javascript I tried this:

```<code>const formInstance = $('#myForm').parsley();
const inputs = $('input').parsley();

for (let input of inputs) {
  input.options.trigger = 'focusout';
}
</code>```

But it's not adding the trigger.

答:
You're right, according to their documentation, it seems like your code should be working.

For now, you can pass the options when you call parsley().

```<code>const options = {
    trigger: 'focusout'
};

const inputs = $('input').parsley(options);
</code>```

And remove the loop.

Body:
Using ParsleyJs, I'd like to set the trigger for each input field to focusout.

I'm able to set it through data attributes in the html, like this:

<input type="text" name="my-input
       data-parsley-trigger="focusout"
       required>

To do the same in Javascript I tried this:

const formInstance = $('#myForm').parsley();
const inputs = $('input').parsley();

for (let input of inputs) {
  input.options.trigger = 'focusout';
}

But it's not adding the trigger.

Body:
You're right, according to their documentation, it seems like your code should be working.

For now, you can pass the options when you call parsley().

const options = {
    trigger: 'focusout'
};

const inputs = $('input').parsley(options);

And remove the loop.


问:
Connect a Biztalk send port to a ftps server
I currently working on BizTalk and I got a problem when I try to configure a send port to a ftps server.

I send a request to an amazon server to get a file and I want to send this file on a ftp server.
I use an adapter nsoftware.ftp v3 for my sending port to the ftp server. But when I try it, I got this error message :

This system contains a plaintext-only license, however the( Ftp:Adresse) send port is configured to run with security enabled. You must disable the security features for the send port to execute.

Do I need a certificate with a private key or just the configuration any is ok with the nsoftware adapter?

So actually I use a first flow to get a file on a amazon server and it works . After, I create a send port who must take this file and send him to an ftps server (it is the server of a client). So I use the property BTS.SPName to activate this send port at the file reception and I use a nsoftware.ftp adapter (free version) for the transport type. The client send to me the certificate of the server and I install it on the server.

答: @Martin is right. The error is due to licensing. The version of the license you have does not support SSL/TLS connections. Please submit a support ticket and we can provide information on using the latest version of the adapters (V3 is also a few major versions old).</p>


问:
Taking the address of a function from within that function
First, the question: Is there any reason you can't take the address of a function from within that function?

```<code>#include <stdio.h>

struct foo {
  void(*xf)(void);
  int r;
} sFoo;

void func(void) {
  sFoo.xf = func; /* <-- like this */
}

int main()
{
  func();
  printf("FuncPtr  is: %p\n", sFoo.xf);
  printf("FuncAddr is: %p\n", &func);
  getchar();
  return 0;
}
</code>```

I can't think of a reason why this shouldn't work portably, but that doesn't mean there isn't one. I've tested it with MinGW and MSVC on Windows, and gcc on Ubuntu, and it works fine. The C standard is pretty much silent, except to say that (C99 5.1.1.2) function references are resolved in the final translation phase.

My main aggravation is that I can't find anything that confirms that this is standard behavior. I've run across comments in the past that said that you couldn't take the address of a function from within that function, which I thought were bogus at the time, but didn't really have the time or inclination to actually check it out, until now.

答:
Is there any reason you can't take the address of a function from within that function?

Nope.

The C standard is pretty much silent, except to say that (C99 5.1.1.2) function references are resolved in the final translation phase.

The standard is not silent; it just does not address that particular case explicitly.  It is not a special case.

My main aggravation is that I can't find anything that confirms that this is standard behavior.

The standard specifies that you can obtain the address of a function, and it describes how.  It makes no exception for code inside the function's definition, so the general rules apply there.  It would in fact be pretty inconsistent if you could not obtain a pointer to a function within that function's implementation, since you can certainly call it from there (i.e. recursively).

I've run across comments in the past that said that you couldn't take the address of a function from within that function, which I thought were bogus at the time, but didn't really have the time or inclination to actually check it out, until now.

I'm inclined to agree that such comments were mistaken to whatever extent they were directed at standard C.  Perhaps, though, they were directed at some non-conforming implementation.  Or perhaps you misremember.  Obviously, I cannot address any such comments with specificity unless you provide a reference, and preferrably an in-context quotation in your question.

Body:
First, the question: Is there any reason you can't take the address of a function from within that function?

#include <stdio.h>

struct foo {
  void(*xf)(void);
  int r;
} sFoo;

void func(void) {
  sFoo.xf = func; /* <-- like this */
}

int main()
{
  func();
  printf("FuncPtr  is: %p\n", sFoo.xf);
  printf("FuncAddr is: %p\n", &func);
  getchar();
  return 0;
}

I can't think of a reason why this shouldn't work portably, but that doesn't mean there isn't one. I've tested it with MinGW and MSVC on Windows, and gcc on Ubuntu, and it works fine. The C standard is pretty much silent, except to say that (C99 5.1.1.2) function references are resolved in the final translation phase.

My main aggravation is that I can't find anything that confirms that this is standard behavior. I've run across comments in the past that said that you couldn't take the address of a function from within that function, which I thought were bogus at the time, but didn't really have the time or inclination to actually check it out, until now.


问:
SAP JCo - Server started on front-end workstation
I need to create a program, which resides on the client PC, gets executed from SAP LOGON, receives some RFC requests, returns data and terminates.

I've been following this tutorial on how to implement a JCo server:

https://blogs.sap.com/2017/08/25/sap-jco-server-example/

I configured the JCo connection properties according to the tutorial. My program gets executed, but SAP fails to send any RFC requests to it and ends on a timeout.

I noticed that my program gets executed with the following arguments:

```<code>/H/gd9.company.com, sapgw02, 87945336, IDX=4
</code>```

I guess this is SAP telling me configuration values for the RFC connection. I mean, I shouldn't have them static (like in the configuration file in the tutorial), but rather use the values from the arguments.

The first one should be the host (jco.server.gwhost), although I don't understand why its prep-ended with /H/. She second one is probably jco.server.gwserv.

But what are the other two parameters? Should I use them to configure the RFC connection in some way?

答:
JCo 3.0 does not support started RFC server programs but only registered ones, where the startup initiative comes from the Java side.

You won't get this start RFC server scenario to work with JCo.

Only a workaround would be imaginable with starting some non-Java program like a command shell script whose purpose is only to start the JCo server program which would then register itself at the gateway with some pre-defined program ID. Afterwards you can use a second destination from ABAP side that is configured to use this registered RFC program ID then.
Not nice but currently the only way if you need to stick to Java.

Edit (Jan 10, 2018):

I think the four parameters that you get are:

GWHOST (SAP gateway host prepended by a SAProuter string)

GWSERV (SAP gateway service as symbolic service name)

CONVID   (CPIC conversation ID being used)

IDX           (CPIC connection index specifying some SAP internal data structure being used)

There is no API in JCo 3.0 where to pass these values, i.e. especially the arguments no. 3 and 4. But this is required to get a started RFC server program scenario working. The difference compared to a registered RFC server program scenario is, that for a started RFC server program the CPIC connection has already been opened by the gateway and this existing CPIC connection needs to be used, i.e. the RFC server has to attach itself to this existing connection.

ContentLicense: CC BY-SA 4.0

Body:
I need to create a program, which resides on the client PC, gets executed from SAP LOGON, receives some RFC requests, returns data and terminates.

I've been following this tutorial on how to implement a JCo server:

https://blogs.sap.com/2017/08/25/sap-jco-server-example/

I configured the JCo connection properties according to the tutorial. My program gets executed, but SAP fails to send any RFC requests to it and ends on a timeout.

I noticed that my program gets executed with the following arguments:

/H/gd9.company.com, sapgw02, 87945336, IDX=4

I guess this is SAP telling me configuration values for the RFC connection. I mean, I shouldn't have them static (like in the configuration file in the tutorial), but rather use the values from the arguments.

The first one should be the host (jco.server.gwhost), although I don't understand why its prep-ended with /H/. She second one is probably jco.server.gwserv.

But what are the other two parameters? Should I use them to configure the RFC connection in some way?


问:
Can I embed a local image on a Google Map?
I am leveraging Google Maps API from Delphi 10 Seattle.

```<code>procedure TfrmMain.FormCreate(Sender: TObject);
var
  aStream: TMemoryStream;
begin
  WebBrowser1.Navigate('about:blank');
  if Assigned(WebBrowser1.Document) then
  begin
    aStream := TMemoryStream.Create;
    try
      aStream.WriteBuffer(Pointer(HTMLStr)^, Length(HTMLStr));
      aStream.Seek(0, soFromBeginning);
      (WebBrowser1.Document as IPersistStreamInit)
        .Load(TStreamAdapter.Create(aStream));
    finally
      freeandnil(aStream);
    end;
    HTMLWindow2 := (WebBrowser1.Document as IHTMLDocument2).parentWindow;
  end;

  fContainer := TExternalContainer.Create(WebBrowser1);
end;
</code>```

This allows me to make JavaScript calls into the Map JS using an instance of IHtmlDocument2 interface.

```<code>procedure TfrmMain.btnStartPointClick(Sender: TObject);
begin
   HTMLWindow2.execScript(Format('EmbedImageAtLatLng(%s,%s, %s)',[edtLat.Text,edtLon.Text, edtImageName.txt]), 'JavaScript');
end;
</code>```

My client would like me to post a specific image at a specific location for use by his workers.  Is this possible.

Note:  this image is a local image and not served.  It is simply passed in.

答:
I went with an info window.</p>

```<code>marker.info = new google.maps.InfoWindow({
 content: "<div class= ''map-overlay'', style = ''width:110x; height:74px''; float: left><img align=''Left'' src= ''C:/Scripts/QRCode.bmp''></div>"
    });
</code>```

Body:
I am leveraging Google Maps API from Delphi 10 Seattle.

procedure TfrmMain.FormCreate(Sender: TObject);
var
  aStream: TMemoryStream;
begin
  WebBrowser1.Navigate('about:blank');
  if Assigned(WebBrowser1.Document) then
  begin
    aStream := TMemoryStream.Create;
    try
      aStream.WriteBuffer(Pointer(HTMLStr)^, Length(HTMLStr));
      aStream.Seek(0, soFromBeginning);
      (WebBrowser1.Document as IPersistStreamInit)
        .Load(TStreamAdapter.Create(aStream));
    finally
      freeandnil(aStream);
    end;
    HTMLWindow2 := (WebBrowser1.Document as IHTMLDocument2).parentWindow;
  end;

  fContainer := TExternalContainer.Create(WebBrowser1);
end;

This allows me to make JavaScript calls into the Map JS using an instance of IHtmlDocument2 interface.

procedure TfrmMain.btnStartPointClick(Sender: TObject);
begin
   HTMLWindow2.execScript(Format('EmbedImageAtLatLng(%s,%s, %s)',[edtLat.Text,edtLon.Text, edtImageName.txt]), 'JavaScript');
end;

My client would like me to post a specific image at a specific location for use by his workers.  Is this possible.

Note:  this image is a local image and not served.  It is simply passed in.

Body:
I went with an info window.

marker.info = new google.maps.InfoWindow({
 content: "<div class= ''map-overlay'', style = ''width:110x; height:74px''; float: left><img align=''Left'' src= ''C:/Scripts/QRCode.bmp''></div>"
    });


问:
Jquery ui tab hidden div appearing on main tab
I'm not sure exactly how to describe/ask this so I'll give it my best shot.  I am using add tab functionality in jquery's tabs.  On the first tab I have a jqgrid which I use to select items to open in a new tab.  When an item is selected the new tab is created successfully, but a div is added below the jqgrid which looks something like the following (white space added).  What might I be doing wrong to cause this phantom div to show up?  I found this using firebug, but since I haven't switched tabs yet nothing should be showing up right?  Also, it appears that 2 divs are created for each addtab I do.  Is 2 normal?

EDIT: 2 is not normal, the example code does not create two on the jquery ui website.

```<code><div id="ui-tabs-2" class="ui-tabs-panel ui-widget-content ui-corner-bottom ui-tabs-hide"></div>
</code>```

Thanks.

Code used for addtab.

```<code>function addTab() {
    var selected_row = $grid.jqGrid('getGridParam',('selrow'));
    $tabs.tabs('add', selected_row, selected_row);
}
</code>```

And the tab template.

```<code>tabTemplate: "<li><a href='#{href}'>#{label}</a><span class='ui-icon ui-icon-close'>Remove Tab</span></li>",
</code>```

Edit: Basically adding a tab is creating two divs.  IDs that are odd are actually wanted, and even ids are not.  (id a div with id="ui-tabs-3" is correct, but another tab is added as well which is of id="ui-tabs-2".  The 2 is not wanted.)  Nowhere am I telling it to add two tabs, and the even numbered stuff is dumby and has nothing, but I believe it is causing the crazy white space to appear and grow every time I add a new tab.  Any ideas?  I'm not doing anything complicated and can't pull code apart any further I don't think without taking away the add functionality itself.

Thanks.

Edit: And the tab init stuff as well?  Am I missing something obvious?  Seems like 6 lines of code involved and one would think I would see what I screwed up?

```<code>var $tabs = jQuery("#tabs").tabs({
                    //tabTemplate: "<li><a href='http://localhost:8000/tickets/byId/#{href}/'>#{label}</a> <span class='ui-icon ui-icon-close'>Remove Tab</span></li>",
                tabTemplate: "<li><a href='#{href}'>#{label}</a><span class='ui-icon ui-icon-close'>Remove Tab</span></li>",
                ajaxOptions: {
                    error: function(xhr, status, index, anchor) {
                        jQuery(anchor.hash).html("If you're reading this then something didn't go right....oops.");
                    }
                }
            }).bind("tabsselect",function(event,ui){
                if (ui.index == 0) {
                    $grid.trigger('reloadGrid');
                }
            });
</code>```

答:
I believe this bug answers my question.

http://bugs.jqueryui.com/ticket/5069

ContentLicense: CC BY-SA 2.5

Body:
I'm not sure exactly how to describe/ask this so I'll give it my best shot.  I am using add tab functionality in jquery's tabs.  On the first tab I have a jqgrid which I use to select items to open in a new tab.  When an item is selected the new tab is created successfully, but a div is added below the jqgrid which looks something like the following (white space added).  What might I be doing wrong to cause this phantom div to show up?  I found this using firebug, but since I haven't switched tabs yet nothing should be showing up right?  Also, it appears that 2 divs are created for each addtab I do.  Is 2 normal?

EDIT: 2 is not normal, the example code does not create two on the jquery ui website.

Thanks.

Code used for addtab.

function addTab() {
    var selected_row = $grid.jqGrid('getGridParam',('selrow'));
    $tabs.tabs('add', selected_row, selected_row);
}

And the tab template.

tabTemplate: "
#{label}Remove Tab
",

Edit: Basically adding a tab is creating two divs.  IDs that are odd are actually wanted, and even ids are not.  (id a div with id="ui-tabs-3" is correct, but another tab is added as well which is of id="ui-tabs-2".  The 2 is not wanted.)  Nowhere am I telling it to add two tabs, and the even numbered stuff is dumby and has nothing, but I believe it is causing the crazy white space to appear and grow every time I add a new tab.  Any ideas?  I'm not doing anything complicated and can't pull code apart any further I don't think without taking away the add functionality itself.

Thanks.

Edit: And the tab init stuff as well?  Am I missing something obvious?  Seems like 6 lines of code involved and one would think I would see what I screwed up?

var $tabs = jQuery("#tabs").tabs({
                    //tabTemplate: "
#{label} Remove Tab
",
                tabTemplate: "
#{label}Remove Tab
",
                ajaxOptions: {
                    error: function(xhr, status, index, anchor) {
                        jQuery(anchor.hash).html("If you're reading this then something didn't go right....oops.");
                    }
                }
            }).bind("tabsselect",function(event,ui){
                if (ui.index == 0) {
                    $grid.trigger('reloadGrid');
                }
            });


问:
Change opacity on mouseover in R Shiny
I've an absolute Panel in my R shiny app whose and I'm trying to change its opacity depending on mouseover action. If the cursor is on the panel then the opacity will be 1 orelse 0.5

I tried the code below but it makes the panel transparent irrespective of mouseover action

```<code>                                       fluidPage(
                                         tags$head(tags$style(
                                           HTML('
         #input_date_control {opacity : 0.65;}
         #sel_date {opacity: 1;}')
                                         )),
                                absolutePanel(id = "input_date_control", class = "panel panel-default", fixed = TRUE,
                                              draggable = TRUE, top = 60, left = "auto", right = 20, bottom = "auto",
                                              width = 230, height = 213,

  box(title = 'Selector', width = 11.5, status = 'primary', solidHeader = TRUE,

                                                  tags$head(
                                                    tags$style(
                                                      ".selectize-dropdown, .selectize-input, .selectize-input {
                                                      line-height: 10px;
                                                      }"
  )),

  selectizeInput("disease", label = "Select disease('s)",
                 choices = unique(salmonella_all$Disease), multiple = T,
                 options = list(maxItems = 12, placeholder = 'Select a disease'),
                 selected = "Chlamydia"),

  dateRangeInput("daterange", "Select date range:",
                 start = "2014-01-07",
                 end   = "2017-10-15",
                 min = "2014-01-07",
                 max = "2017-10-15"
                 ))))

</code>```

The output of the code

I want to panel to be transparent when theres no mouse over and opaque only when the cursor is over the panel

答:
Use</p>

```<code> #sel_date:hover{
opacity: 1;
}
</code>```

Title: Change opacity on mouseover in R Shiny

Body:
I've an absolute Panel in my R shiny app whose and I'm trying to change its opacity depending on mouseover action. If the cursor is on the panel then the opacity will be 1 orelse 0.5

I tried the code below but it makes the panel transparent irrespective of mouseover action

                                       fluidPage(
                                         tags$head(tags$style(
                                           HTML('
         #input_date_control {opacity : 0.65;}
         #sel_date {opacity: 1;}')
                                         )),
                                absolutePanel(id = "input_date_control", class = "panel panel-default", fixed = TRUE,
                                              draggable = TRUE, top = 60, left = "auto", right = 20, bottom = "auto",
                                              width = 230, height = 213,

  box(title = 'Selector', width = 11.5, status = 'primary', solidHeader = TRUE,

                                                  tags$head(
                                                    tags$style(
                                                      ".selectize-dropdown, .selectize-input, .selectize-input {
                                                      line-height: 10px;
                                                      }"
  )),

  selectizeInput("disease", label = "Select disease('s)",
                 choices = unique(salmonella_all$Disease), multiple = T,
                 options = list(maxItems = 12, placeholder = 'Select a disease'),
                 selected = "Chlamydia"),

  dateRangeInput("daterange", "Select date range:",
                 start = "2014-01-07",
                 end   = "2017-10-15",
                 min = "2014-01-07",
                 max = "2017-10-15"
                 ))))

The output of the code

I want to panel to be transparent when theres no mouse over and opaque only when the cursor is over the panel

Body:
Use

 #sel_date:hover{
opacity: 1;
}


问:
how to display different data type values with same variable in javascript
Issue:

When I am using same variable to hold different data types in java script,
and trying to display all values, it is not showing up all values except the last value which it holds. is there any alternate way to show up all data type values with same variable?

Script:

```<code><script>
var x;
document.getElementById("demo").innerHTML = x;
x = 5;
document.getElementById("demo").innerHTML = x;
x = "John";
document.getElementById("demo").innerHTML = x;
</script>
</code>```

Expected result:

undefined
5
John

Actual result:

John

答:
I wanted to comment on Scath answer but i can´t comment.

Like the others said you are replacing de content, you should use concatenation.

But I would use br tag instead of '\n' to get the expected result.

```<code><script>
    var x;
    document.getElementById("demo").innerHTML = x+ '<br/>';
    x = 5;
    document.getElementById("demo").innerHTML += x+ '<br/>';
    x = "John";
    document.getElementById("demo").innerHTML += x+ '<br/>';
</script>
</code>```

Body:
Issue:

When I am using same variable to hold different data types in java script,
and trying to display all values, it is not showing up all values except the last value which it holds. is there any alternate way to show up all data type values with same variable?

Script:

Expected result:

undefined
5
John

Actual result:

John

Body:
I wanted to comment on Scath answer but i can´t comment.

Like the others said you are replacing de content, you should use concatenation.

But I would use br tag instead of '\n' to get the expected result.

<script>
    var x;
    document.getElementById("demo").innerHTML = x+ '<br/>';
    x = 5;
    document.getElementById("demo").innerHTML += x+ '<br/>';
    x = "John";
    document.getElementById("demo").innerHTML += x+ '<br/>';
</script>


问:
Reading in Unicode Emoji correctly into R
I have a set of comments from Facebook (pulled via a system like Sprinkr) that contain both text and emojis, and I'm trying to run a variety of analysis on them in R, but running into difficulty into ingesting the emoji characters correctly.

For example: I have a .csv (encoded in UTF-8) that will have a message line containing something like this:

"IS THIS CORRECT!?!?! Please say it isn't true!!! Our family only eats the original Reeses Peanut Butter Cups"

I then ingest it into R in the following way:

```<code>library(tidyverse)
library(janitor)
raw.fb.comments <- read_csv("data.csv",
                            locale = locale(encoding="UTF-8"))
fb.comments <- raw.fb.comments %>%
  clean_names() %>%
  filter(senderscreenname != "Reese's") %>%
  select(c(message,messagetype,sentiment)) %>%
  mutate(type = "Facebook")
fb.comments$message[5]
[1] "IS THIS CORRECT!?!?! Please say it isn't true!!! Our family only eats the original Reeses Peanut Butter Cups\xf0\u009f\u0092\u009a\xf0\u009f\u0092\u009a\xf0\u009f\u0092\u009a\n\n"
</code>```

Now, from what I understand from other sources, I need to transform this UTF-8 into ASCII, which I can then use to link it up with other emoji resources (like the wonderful emojidictionary). To make the join work, I need to get this into R-encoding, something like this:

```<code><e2><9d><a4><ef><b8><8f>
</code>```

However, adding the normal step (using iconv) doesn't get me there:

```<code>fb.comments <- raw.fb.comments %>%
  clean_names() %>%
  filter(senderscreenname != "Reese's") %>%
  select(c(message,messagetype,sentiment)) %>%
  mutate(type = "Facebook") %>%
  mutate(message = iconv(message, from="UTF-8", to="ascii",sub="byte"))
fb.comments$message[5]
[1] "IS THIS CORRECT!?!?! Please say it isn't true!!! Our family only eats the original Reeses Peanut Butter Cups<f0><9f><92><9a><f0><9f><92><9a><f0><9f><92><9a>\n\n"
</code>```

Can anyone out there illuminate to me what I'm missing, or do I need to find a different emoji mapping resource? Thanks!

答:
The goal is not really clear, but I suspect that giving up on representing emoji correcty and just representing it as bytes is not the best way. If for example you wish to convert emoji to their description you can do something like this:</p>

```<code>x <- "IS THIS CORRECT!?!?! Please say it isn't true!!! Our family only eats the original Reeses Peanut Butter Cups"

## read emoji info and get rid of documentation lines
readLines("https://unicode.org/Public/emoji/5.0/emoji-test.txt",
          encoding="UTF-8") %>%
    stri_subset_regex(pattern = "^[^#]") %>%
    stri_subset_regex(pattern = ".+") -> emoji

## get the emoji characters and clean them up
emoji %>%
    stri_extract_all_regex(pattern = "# *.{1,2} *") %>%
    stri_replace_all_fixed(pattern = c("*", "#"),
                           replacement = "",
                           vectorize_all=FALSE) %>%
    stri_trim_both() -> emoji.chars

## get the emoji character descriptions
emoji %>%
    stri_extract_all_regex(pattern = "#.*$") %>%
    stri_replace_all_regex(pattern = "# *.{1,2} *",
                           replacement = "") %>%
    stri_trim_both() -> emoji.descriptions

## replace emoji characters with their descriptions.
stri_replace_all_regex(x,
                       pattern = emoji.chars,
                       replacement = emoji.descriptions,
                       vectorize_all=FALSE)

## [1] "IS THIS CORRECT!?!?! Please say it isn't true!!! Our family only eats the original Reeses Peanut Butter Cupsgreen heartgreen heartgreen heart"
</code>```

Body:
I have a set of comments from Facebook (pulled via a system like Sprinkr) that contain both text and emojis, and I'm trying to run a variety of analysis on them in R, but running into difficulty into ingesting the emoji characters correctly.

For example: I have a .csv (encoded in UTF-8) that will have a message line containing something like this:

"IS THIS CORRECT!?!?! Please say it isn't true!!! Our family only eats the original Reeses Peanut Butter Cups"

I then ingest it into R in the following way:

library(tidyverse)
library(janitor)
raw.fb.comments <- read_csv("data.csv",
                            locale = locale(encoding="UTF-8"))
fb.comments <- raw.fb.comments %>%
  clean_names() %>%
  filter(senderscreenname != "Reese's") %>%
  select(c(message,messagetype,sentiment)) %>%
  mutate(type = "Facebook")
fb.comments$message[5]
[1] "IS THIS CORRECT!?!?! Please say it isn't true!!! Our family only eats the original Reeses Peanut Butter Cups\xf0\u009f\u0092\u009a\xf0\u009f\u0092\u009a\xf0\u009f\u0092\u009a\n\n"

Now, from what I understand from other sources, I need to transform this UTF-8 into ASCII, which I can then use to link it up with other emoji resources (like the wonderful emojidictionary). To make the join work, I need to get this into R-encoding, something like this:

<e2><9d><a4><ef><b8><8f>

However, adding the normal step (using iconv) doesn't get me there:

fb.comments <- raw.fb.comments %>%
  clean_names() %>%
  filter(senderscreenname != "Reese's") %>%
  select(c(message,messagetype,sentiment)) %>%
  mutate(type = "Facebook") %>%
  mutate(message = iconv(message, from="UTF-8", to="ascii",sub="byte"))
fb.comments$message[5]
[1] "IS THIS CORRECT!?!?! Please say it isn't true!!! Our family only eats the original Reeses Peanut Butter Cups<f0><9f><92><9a><f0><9f><92><9a><f0><9f><92><9a>\n\n"

Can anyone out there illuminate to me what I'm missing, or do I need to find a different emoji mapping resource? Thanks!

Body:
The goal is not really clear, but I suspect that giving up on representing emoji correcty and just representing it as bytes is not the best way. If for example you wish to convert emoji to their description you can do something like this:

x <- "IS THIS CORRECT!?!?! Please say it isn't true!!! Our family only eats the original Reeses Peanut Butter Cups"

## read emoji info and get rid of documentation lines
readLines("https://unicode.org/Public/emoji/5.0/emoji-test.txt",
          encoding="UTF-8") %>%
    stri_subset_regex(pattern = "^[^#]") %>%
    stri_subset_regex(pattern = ".+") -> emoji

## get the emoji characters and clean them up
emoji %>%
    stri_extract_all_regex(pattern = "# *.{1,2} *") %>%
    stri_replace_all_fixed(pattern = c("*", "#"),
                           replacement = "",
                           vectorize_all=FALSE) %>%
    stri_trim_both() -> emoji.chars

## get the emoji character descriptions
emoji %>%
    stri_extract_all_regex(pattern = "#.*$") %>%
    stri_replace_all_regex(pattern = "# *.{1,2} *",
                           replacement = "") %>%
    stri_trim_both() -> emoji.descriptions

## replace emoji characters with their descriptions.
stri_replace_all_regex(x,
                       pattern = emoji.chars,
                       replacement = emoji.descriptions,
                       vectorize_all=FALSE)

## [1] "IS THIS CORRECT!?!?! Please say it isn't true!!! Our family only eats the original Reeses Peanut Butter Cupsgreen heartgreen heartgreen heart"


问:
Setting a negative margin which is a percentage of its height. Pure CSS
I have a series of images, which have different captions.
each of these captions needs to appear to float halfway over the bottom of the image.
Here is a mockup of how this looks and also how I have structured it in divs.
because there needs to be space between the bottom of the caption and whatever div is beneath, the caption cannot be absolutely positioned.

I am aware this could be done in javascript but this would be a hack so I'd prefer to find a CSS only solution.

...and here is the code so far: JS FIDDLE

.outer {
  position: relative;
  width: 320px;
  margin-bottom:24px // this needs to be the space between the bottom of the caption and the next image or whatever div is beneath.
}

.image {
  background-color: blue;
  width: 320px;
  height: 380px;
  position: relative;
  border-radius: 5px;
}

.caption {
  position: relative;
  margin-top: -24px;
  /* THIS NEEDS TO BE 50% of the Captions variable height */
}

.card {
  margin-right: 25%;
  margin-left: 5%;
  position: relative;
  background-color: #FFFFFF;
  padding: 24px;
  line-height: 24px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="outer">
  <div class="image">
  </div>
  <div class="caption">
    <div class="card">
      Lorem ipsum dolar sit amet consectetur idipiscine ipsumd lorem ipsum dolar sit amet. a
    </div>
  </div>
</div></code>```

答:
Try Changing Margin-top to -25%.</p>

```<code>.caption {
display:block;
position:relative;
margin-top:-25%;
}
</code>```

Body:
I have a series of images, which have different captions.
each of these captions needs to appear to float halfway over the bottom of the image.
Here is a mockup of how this looks and also how I have structured it in divs.
because there needs to be space between the bottom of the caption and whatever div is beneath, the caption cannot be absolutely positioned.

I am aware this could be done in javascript but this would be a hack so I'd prefer to find a CSS only solution.

...and here is the code so far: JS FIDDLE

.outer {
  position: relative;
  width: 320px;
  margin-bottom:24px // this needs to be the space between the bottom of the caption and the next image or whatever div is beneath.
}

.image {
  background-color: blue;
  width: 320px;
  height: 380px;
  position: relative;
  border-radius: 5px;
}

.caption {
  position: relative;
  margin-top: -24px;
  /* THIS NEEDS TO BE 50% of the Captions variable height */
}

.card {
  margin-right: 25%;
  margin-left: 5%;
  position: relative;
  background-color: #FFFFFF;
  padding: 24px;
  line-height: 24px;
}

      Lorem ipsum dolar sit amet consectetur idipiscine ipsumd lorem ipsum dolar sit amet. a

Body:
Try Changing Margin-top to -25%.

.caption {
display:block;
position:relative;
margin-top:-25%;
}


问:
Component not reloaded with react hot loader
https://github.com/James2516/hot-reload

I'm trying to add hot loader to an existing webpack project.

It detected file changes but did not reload the component.

To reproduce:

yarn && yarn start

change src/App.js content

答:
The examples are taken from https://gaearon.github.io/react-hot-loader/getstarted/#step-2-of-3-using-hmr-to-replace-the-root-component, though it seems as though you already followed this guide.

The first problem is that [HMR] Waiting for update signal from WDS... is printed to the console twice, and any attempted recompiles also occur twice. This is caused by your entry in ./config/webpack/Dev.js being:

```<code>entry: [
  'webpack-dev-server/client?http://localhost:4545/',
  'webpack/hot/only-dev-server',
  'react-hot-loader/patch',
  './client.js',
]
</code>```

The first few steps of the guide have the entry point as:

```<code>[
  'webpack-dev-server/client?http://0.0.0.0:3000', // WebpackDevServer host and port
  'webpack/hot/only-dev-server', // 'only' prevents reload on syntax errors
  './scripts/index' // Your app's entry point
]
</code>```

Step 3a under  Step 3 (of 3): Adding React Hot Loader to preserve component state instructs you to modify the entry of webpack.config.js to look like:

```<code>[
  'react-hot-loader/patch', // RHL patch
  './scripts/index' // Your app's entry point
]
</code>```

react-hot-loader handles what these two entries were previously doing, so they can be replaced with 'react-hot-loader/patch'.

So your new entry point should be:

```<code>[
  'react-hot-loader/patch',
  './client.js'
]
</code>```

Next, Step 3b in the same section has a code snippet that looks like:

```<code>if (module.hot) {
  module.hot.accept('./containers/rootContainer.js', () => {
    const NextRootContainer = require('./containers/rootContainer').default;
    render(NextRootContainer);
  });
}
</code>```

Changing your module.hot block to:

```<code>if (module.hot) {
  module.hot.accept('./App', () => {
    const newApp = require('./App').default;
    render(newApp);
  }
}
</code>```

Correctly reloads the component, so it doesn't make sense that following Step 3c breaks HMR.

c. Webpack 2 has built-in support for ES2015 modules, and you won’t need to re-require your app root in module.hot.accept. The example above becomes:

```<code>if (module.hot) {
  module.hot.accept('./containers/rootContainer', () => {
   render(RootContainer) });
}
</code>```

Note: To make this work, you’ll need to opt out of Babel transpiling ES2015 modules by changing the Babel ES2015 preset to be

"presets": [["es2015", { "modules": false }]]

Which you did correctly in .babelrc. The only problem is that in ./config/webpack/Base.js you have:

```<code>loader: 'babel-loader',
query: {
  presets: ['es2015', 'react', 'stage-2']
}
</code>```

This causes babel-loader to use these presets instead of the ones defined in .babelrc. Removing query in this rule and changing presets in .babelrc to:

```<code>"presets": [["es2015", { "modules": false }], "react", "stage-2"
</code>```

Correctly enables HMR with your module.hot block as:

```<code>if (module.hot) {
  module.hot.accept('./App', () => { render(App); });
}
</code>```

Body:
The examples are taken from https://gaearon.github.io/react-hot-loader/getstarted/#step-2-of-3-using-hmr-to-replace-the-root-component, though it seems as though you already followed this guide.

The first problem is that [HMR] Waiting for update signal from WDS... is printed to the console twice, and any attempted recompiles also occur twice. This is caused by your entry in ./config/webpack/Dev.js being:

entry: [
  'webpack-dev-server/client?http://localhost:4545/',
  'webpack/hot/only-dev-server',
  'react-hot-loader/patch',
  './client.js',
]

The first few steps of the guide have the entry point as:

[
  'webpack-dev-server/client?http://0.0.0.0:3000', // WebpackDevServer host and port
  'webpack/hot/only-dev-server', // 'only' prevents reload on syntax errors
  './scripts/index' // Your app's entry point
]

Step 3a under  Step 3 (of 3): Adding React Hot Loader to preserve component state instructs you to modify the entry of webpack.config.js to look like:

[
  'react-hot-loader/patch', // RHL patch
  './scripts/index' // Your app's entry point
]

react-hot-loader handles what these two entries were previously doing, so they can be replaced with 'react-hot-loader/patch'.

So your new entry point should be:

[
  'react-hot-loader/patch',
  './client.js'
]

Next, Step 3b in the same section has a code snippet that looks like:

if (module.hot) {
  module.hot.accept('./containers/rootContainer.js', () => {
    const NextRootContainer = require('./containers/rootContainer').default;
    render(NextRootContainer);
  });
}

Changing your module.hot block to:

if (module.hot) {
  module.hot.accept('./App', () => {
    const newApp = require('./App').default;
    render(newApp);
  }
}

Correctly reloads the component, so it doesn't make sense that following Step 3c breaks HMR.

c. Webpack 2 has built-in support for ES2015 modules, and you won’t need to re-require your app root in module.hot.accept. The example above becomes:

if (module.hot) {
  module.hot.accept('./containers/rootContainer', () => {
   render(RootContainer) });
}

Note: To make this work, you’ll need to opt out of Babel transpiling ES2015 modules by changing the Babel ES2015 preset to be

"presets": [["es2015", { "modules": false }]]

Which you did correctly in .babelrc. The only problem is that in ./config/webpack/Base.js you have:

loader: 'babel-loader',
query: {
  presets: ['es2015', 'react', 'stage-2']
}

This causes babel-loader to use these presets instead of the ones defined in .babelrc. Removing query in this rule and changing presets in .babelrc to:

"presets": [["es2015", { "modules": false }], "react", "stage-2"

Correctly enables HMR with your module.hot block as:

if (module.hot) {
  module.hot.accept('./App', () => { render(App); });
}


问:
WPF Sorting an ObservableCollection de-selects a ComboBox
I have a ComboBox where a user can select what JobType they are working on.  The ComboBox has a list of AllJobTypes.  The problem stems from when a user adds a new JobType, I add the JobType to the AllJobTypes ObservableCollection, then sort it.  When the sorting happens the ComboBox get's de-selected and not really sure why.  The JobConfig.SelectedJobType.Name never changes in this process.  Is there a way to sort an observable collection where it doesn't break the ComboBox?

```<code>public class JobTypeList : ObservableCollection<JobType> {

  public void SortJobTypes() {
    var sortableList = new List<JobType>(this);
    sortableList.Sort((x, y) => x.Name.CompareTo(y.Name));
    //this works but it creates a bug in the select for JobTypes
    for (int i = 0; i < sortableList.Count; i++) {
        this.Move(this.IndexOf(sortableList[i]), i);
    }
  }
</code>```

And in the XAML

```<code><ComboBox Grid.Column="0" SelectionChanged="JobTypeComboBox_SelectionChanged"
                              Name="JobTypeComboBox"
                              ItemsSource="{Binding Path=AllJobTypes}"
                              DisplayMemberPath="Name"
                              SelectedValuePath="Name"
                              SelectedValue="{Binding
Path=JobConfig.SelectedJobType.Name}" />
</code>```

答:
Here's a version using ItemsSource/SelectedItem.  Note that you can add a new item to the list and sort it without losing the currently selected item in the view.

The window

```<code><Window
    x:Class="SortingAList.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:SortingAList"
    mc:Ignorable="d"
    Title="MainWindow"
    Height="350"
    Width="525">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition />
            <RowDefinition />
        </Grid.RowDefinitions>
        <TextBox
            Text="{Binding NewJobType, Delay=1000}"
            HorizontalAlignment="Center"
            VerticalAlignment="Center"
            Width="200" />
        <ComboBox
            Grid.Row="1"
            ItemsSource="{Binding JobTypes}"
            SelectedItem="{Binding SelectedJobType}"
            DisplayMemberPath="Name"
            HorizontalAlignment="Center"
            VerticalAlignment="Center"
            Width="200" />
    </Grid>
</Window>
</code>```

The code

```<code>public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new ViewModel();
    }
}

public class Notifier : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    protected void Notify([CallerMemberName]string property = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property));
    }
}

public class ViewModel : Notifier
{
    private JobType _selectedJobType;
    private string _newJobType;

    public JobTypeList JobTypes { get; private set; }
    public JobType SelectedJobType { get => _selectedJobType; set { _selectedJobType = value; Notify(); } }
    public string NewJobType { get => _newJobType; set { _newJobType = value; Notify(); AddNewJobType(value); } }
    public ViewModel()
    {
        JobTypes = new JobTypeList();
        JobTypes.Add(new JobType { Name = "Butcher" });
        JobTypes.Add(new JobType { Name = "Baker" });
        JobTypes.Add(new JobType { Name = "LED maker" });
    }

    private void AddNewJobType(string name)
    {
        if(JobTypes.Any(x => x.Name == name)) return;
        JobTypes.Add(new JobType { Name = name });
        JobTypes.SortJobTypes();
    }
}
public class JobType : Notifier
{
    private string _name;

    public string Name { get => _name; set { _name = value; Notify(); } }
}
</code>```

Using your JobTypesList

```<code>public class JobTypeList : ObservableCollection<JobType>
{

    public void SortJobTypes()
    {
        var sortableList = new List<JobType>(this);
        sortableList.Sort((x, y) => x.Name.CompareTo(y.Name));
        //this works but it creates a bug in the select for JobTypes
        for(int i = 0; i < sortableList.Count; i++)
        {
            this.Move(this.IndexOf(sortableList[i]), i);
        }
    }
}
</code>```

Body:
I have a ComboBox where a user can select what JobType they are working on.  The ComboBox has a list of AllJobTypes.  The problem stems from when a user adds a new JobType, I add the JobType to the AllJobTypes ObservableCollection, then sort it.  When the sorting happens the ComboBox get's de-selected and not really sure why.  The JobConfig.SelectedJobType.Name never changes in this process.  Is there a way to sort an observable collection where it doesn't break the ComboBox?

public class JobTypeList : ObservableCollection<JobType> {

  public void SortJobTypes() {
    var sortableList = new List<JobType>(this);
    sortableList.Sort((x, y) => x.Name.CompareTo(y.Name));
    //this works but it creates a bug in the select for JobTypes
    for (int i = 0; i < sortableList.Count; i++) {
        this.Move(this.IndexOf(sortableList[i]), i);
    }
  }

And in the XAML

<ComboBox Grid.Column="0" SelectionChanged="JobTypeComboBox_SelectionChanged"
                              Name="JobTypeComboBox"
                              ItemsSource="{Binding Path=AllJobTypes}"
                              DisplayMemberPath="Name"
                              SelectedValuePath="Name"
                              SelectedValue="{Binding
Path=JobConfig.SelectedJobType.Name}" />

Body:
Here's a version using ItemsSource/SelectedItem.  Note that you can add a new item to the list and sort it without losing the currently selected item in the view.

The window

<Window
    x:Class="SortingAList.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:SortingAList"
    mc:Ignorable="d"
    Title="MainWindow"
    Height="350"
    Width="525">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition />
            <RowDefinition />
        </Grid.RowDefinitions>
        <TextBox
            Text="{Binding NewJobType, Delay=1000}"
            HorizontalAlignment="Center"
            VerticalAlignment="Center"
            Width="200" />
        <ComboBox
            Grid.Row="1"
            ItemsSource="{Binding JobTypes}"
            SelectedItem="{Binding SelectedJobType}"
            DisplayMemberPath="Name"
            HorizontalAlignment="Center"
            VerticalAlignment="Center"
            Width="200" />
    </Grid>
</Window>

The code

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new ViewModel();
    }
}

public class Notifier : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    protected void Notify([CallerMemberName]string property = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property));
    }
}

public class ViewModel : Notifier
{
    private JobType _selectedJobType;
    private string _newJobType;

    public JobTypeList JobTypes { get; private set; }
    public JobType SelectedJobType { get => _selectedJobType; set { _selectedJobType = value; Notify(); } }
    public string NewJobType { get => _newJobType; set { _newJobType = value; Notify(); AddNewJobType(value); } }
    public ViewModel()
    {
        JobTypes = new JobTypeList();
        JobTypes.Add(new JobType { Name = "Butcher" });
        JobTypes.Add(new JobType { Name = "Baker" });
        JobTypes.Add(new JobType { Name = "LED maker" });
    }

    private void AddNewJobType(string name)
    {
        if(JobTypes.Any(x => x.Name == name)) return;
        JobTypes.Add(new JobType { Name = name });
        JobTypes.SortJobTypes();
    }
}
public class JobType : Notifier
{
    private string _name;

    public string Name { get => _name; set { _name = value; Notify(); } }
}

Using your JobTypesList

public class JobTypeList : ObservableCollection<JobType>
{

    public void SortJobTypes()
    {
        var sortableList = new List<JobType>(this);
        sortableList.Sort((x, y) => x.Name.CompareTo(y.Name));
        //this works but it creates a bug in the select for JobTypes
        for(int i = 0; i < sortableList.Count; i++)
        {
            this.Move(this.IndexOf(sortableList[i]), i);
        }
    }
}


问:
Elixir process limit?
I would like to create an Elixir code similar to this:

```<code>def infinite_loop(created_workers \\ []) do
  case next_from_queue do
    {:ok, queue_msg} ->
      new_worker = Task.async(fn -> crawling(queue_msg) end)
      infinite_loop([new_worker | created_workers])
    {:error, :empty} ->
      created_workers.map(&Task.await/1)
  end
end
</code>```

Assuming that:

The crawling function will create another 3 Task

Every crawling worker could spend 3 seconds running

The queue could have millions of messages

How can I know what is the limit of parallel process on Elixir? How can I manage it to don't break?

答:
I'd recommend using Task.async_stream for this. Task.async_stream allows you to process a stream in parallel while limiting the number of tasks that are run in parallel. While the default limit on the number of processes is 262144 in Erlang 20, if you're crawling a site, you probably want a much lower limit.

You can create a stream from a function that keeps returning new items using Stream.iterate:

```<code>stream =
  Stream.iterate(next_from_queue(), fn _ -> next_from_queue() end)
  |> Stream.take_while(fn {:ok, _} -> true; {:error, :empty} -> false end)
</code>```

Since you want to stop at {:error, :empty}, we use Stream.take_while to stop the stream.

Then use Task.async_stream like this:

```<code>stream
|> Task.async_stream(fn {:ok, queue_msg} ->
  crawling(queue_msg)
end, max_concurrency: 16)
</code>```

This will run the stream with a maximum of 16 tasks in parallel. The end result will be a list of all return values of crawling(queue_msg).

Title: Elixir process limit?

Body:
I would like to create an Elixir code similar to this:

def infinite_loop(created_workers \\ []) do
  case next_from_queue do
    {:ok, queue_msg} ->
      new_worker = Task.async(fn -> crawling(queue_msg) end)
      infinite_loop([new_worker | created_workers])
    {:error, :empty} ->
      created_workers.map(&Task.await/1)
  end
end

Assuming that:

The crawling function will create another 3 Task

Every crawling worker could spend 3 seconds running

The queue could have millions of messages

How can I know what is the limit of parallel process on Elixir? How can I manage it to don't break?

Body:
I'd recommend using Task.async_stream for this. Task.async_stream allows you to process a stream in parallel while limiting the number of tasks that are run in parallel. While the default limit on the number of processes is 262144 in Erlang 20, if you're crawling a site, you probably want a much lower limit.

You can create a stream from a function that keeps returning new items using Stream.iterate:

stream =
  Stream.iterate(next_from_queue(), fn _ -> next_from_queue() end)
  |> Stream.take_while(fn {:ok, _} -> true; {:error, :empty} -> false end)

Since you want to stop at {:error, :empty}, we use Stream.take_while to stop the stream.

Then use Task.async_stream like this:

stream
|> Task.async_stream(fn {:ok, queue_msg} ->
  crawling(queue_msg)
end, max_concurrency: 16)

This will run the stream with a maximum of 16 tasks in parallel. The end result will be a list of all return values of crawling(queue_msg).


问:
How to clone Mongoose schema?
I am working on Mongoose plugin that have to access existing model and create similar schema as previous model and fix some attributes and add some custom properties. How to do such cloning of scheme? I tried but its not working:

```<code>var mongoose = require('mongoose');

var mainSchema = new mognoose.schema({'prop' : String});
var anotherSchema = new mongoose.schema(mainSchema);
</code>```

Of course, its not working at all and I can't find any solution in API doc and source code (as far I can read that code).

答:
For anyone googling, try:

```<code>schema.clone();
</code>```

This creates a full copy of the schema, so you can add more properties, multiple discriminators, etc.

http://mongoosejs.com/docs/api.html#schema_Schema-clone

Title: How to clone Mongoose schema?

Body:
I am working on Mongoose plugin that have to access existing model and create similar schema as previous model and fix some attributes and add some custom properties. How to do such cloning of scheme? I tried but its not working:

var mongoose = require('mongoose');

var mainSchema = new mognoose.schema({'prop' : String});
var anotherSchema = new mongoose.schema(mainSchema);

Of course, its not working at all and I can't find any solution in API doc and source code (as far I can read that code).

Body:
For anyone googling, try:

schema.clone();

This creates a full copy of the schema, so you can add more properties, multiple discriminators, etc.

http://mongoosejs.com/docs/api.html#schema_Schema-clone


问:
C string arrays

Possible Duplicates:

  string literal in c

  Assigning strings to arrays of characters

I got the following code:

```<code>char result[3][4];

result[0] = "horse";
result[1] = "pig";
result[2] = "chicken";
</code>```

It won't compile saying Incompatible types in assignment. What am I doing wrong?

答:
You can assign a string literal (eg: "horse") to a char array only when you declare it, not after.

```<code>char array[4] = "str"; // is OK
char array2[4];
array2 = "str"; // is NOT OK.
</code>```

You could do like this:

```<code>char result[3][4] = { "horse", "pig", "chicken" };
</code>```

but warning: "horse" and "chicken" are longer than char[4].

If you want to assign a string literal to an already declared char array you'll have to use strcpy (or other similar functions).

The other solution, suggested by many is to declare result as an array of char pointers: char *result[3];, but if you do like this you won't be allowed to modify the content of the strings pointed by result[i].

Title: C string arrays

Body:
Possible Duplicates:

  string literal in c

  Assigning strings to arrays of characters

I got the following code:

char result[3][4];

result[0] = "horse";
result[1] = "pig";
result[2] = "chicken";

It won't compile saying Incompatible types in assignment. What am I doing wrong?

Body:
You can assign a string literal (eg: "horse") to a char array only when you declare it, not after.

char array[4] = "str"; // is OK
char array2[4];
array2 = "str"; // is NOT OK.

You could do like this:

char result[3][4] = { "horse", "pig", "chicken" };

but warning: "horse" and "chicken" are longer than char[4].

If you want to assign a string literal to an already declared char array you'll have to use strcpy (or other similar functions).

The other solution, suggested by many is to declare result as an array of char pointers: char *result[3];, but if you do like this you won't be allowed to modify the content of the strings pointed by result[i].


问:
Fit QLabel height without WordWrap
I need to do a manual word wrap because the native wordWrap from Qt splits in wrong places. I've already done the wrap to my text, but the content wasn't showing all the content. The QLabel was cutting the top and the bottom like the image:

Can I fit the Qlabel to the height of the text inside it without wordWrap?

答:
QLabel should resize automatically to the needed height if you place it in the layout, it does not matter if wordWrap is enabled or not, see the doc :
http://doc.qt.io/qt-5/layout.html

Title: Fit QLabel height without WordWrap


问:
How to find an element B that exists below another element A
Say in a webpage:

```<code>Element A     #A is here
...           #Some code
Element B     #B is here
</code>```

A and B don't have parent child relationship, but they have the same locator.

No elements exist between A and B that have the same locator.

How do I locate B (There are other elements below B that also have the same locator), given that I have located A.

答:
Can you share the part of the HTML where Element A and Element B are present, without it no one can provide a efficient way to locate elements.

having said, when you have multiple elements having the same locator and if you know the order when they are retrieved by the driver, you can use the find_elements method

```<code>elements = find_elements_by_css(<your_locator_strategy_>)
</code>```

assuming you have used css, this will return a list and lets say Element B is the second item, you can do

```<code>elements[1].click()
</code>```

assuming you want to click on the element

Body:
Say in a webpage:

Element A     #A is here
...           #Some code
Element B     #B is here

A and B don't have parent child relationship, but they have the same locator.

No elements exist between A and B that have the same locator.

How do I locate B (There are other elements below B that also have the same locator), given that I have located A.

Body:
Can you share the part of the HTML where Element A and Element B are present, without it no one can provide a efficient way to locate elements.

having said, when you have multiple elements having the same locator and if you know the order when they are retrieved by the driver, you can use the find_elements method

elements = find_elements_by_css(<your_locator_strategy_>)

assuming you have used css, this will return a list and lets say Element B is the second item, you can do

elements[1].click()

assuming you want to click on the element


问:
Difference between 'is' and '==' in C#
Im trying to understand exactly when is should be used or not used in C#. I have seen answers written for python but nothing on C#. Also it looks like 'is' is doing more than just comparing value, its also checking to see if an object can be cast as another object. Would this lead to a scenario where one could be true and the other false?</p>

答:
They check completely different things. is compares types. == compares values.

```<code>var isString = "Abc" is String; // => true
var equalToString = "Abc" == String; // Error: `string' is a `type' but a `variable' was expected
</code>```

There is one domain where these can both apply, and have different meanings, and that's in type checking:

```<code>class Car {}
class SportsCar: Car {}

var car = new Car();
var sportsCar = new SportsCar();

/* 1 */ Console.WriteLine(car is Car); // => true, car is exactly of type Car
/* 2 */ Console.WriteLine(sportsCar is Car); // => true, since SportsCar *is a subclass* of Car
/* 3 */ Console.WriteLine(car is SportsCar); // => false, since Car is not a subclass of SportsCar
/* 4 */ Console.WriteLine(sportsCar is SportsCar); // => true, sportsCar is exactly of type SportsCar

/* 5 */ Console.WriteLine(car.GetType() == typeof(Car)); // => true, car is exactly of type Car
/* 6 */ Console.WriteLine(sportsCar.GetType() == typeof(Car)); // => false, since SportsCar *is not exactly* Car
/* 7 */ Console.WriteLine(car.GetType() == typeof(SportsCar)); // => false, since Car is not a subclass of SportsCar
/* 8 */ Console.WriteLine(sportsCar.GetType() == typeof(SportsCar)); // => true, sportsCar is exactly of type SportsCar
</code>```

Lines 1/5, 3/7, and 4/8 both result the same (respectively) but notice that line 2 and 6 differ

Title: Difference between 'is' and '==' in C#

Body:
They check completely different things. is compares types. == compares values.

var isString = "Abc" is String; // => true
var equalToString = "Abc" == String; // Error: `string' is a `type' but a `variable' was expected

There is one domain where these can both apply, and have different meanings, and that's in type checking:

class Car {}
class SportsCar: Car {}

var car = new Car();
var sportsCar = new SportsCar();

/* 1 */ Console.WriteLine(car is Car); // => true, car is exactly of type Car
/* 2 */ Console.WriteLine(sportsCar is Car); // => true, since SportsCar *is a subclass* of Car
/* 3 */ Console.WriteLine(car is SportsCar); // => false, since Car is not a subclass of SportsCar
/* 4 */ Console.WriteLine(sportsCar is SportsCar); // => true, sportsCar is exactly of type SportsCar

/* 5 */ Console.WriteLine(car.GetType() == typeof(Car)); // => true, car is exactly of type Car
/* 6 */ Console.WriteLine(sportsCar.GetType() == typeof(Car)); // => false, since SportsCar *is not exactly* Car
/* 7 */ Console.WriteLine(car.GetType() == typeof(SportsCar)); // => false, since Car is not a subclass of SportsCar
/* 8 */ Console.WriteLine(sportsCar.GetType() == typeof(SportsCar)); // => true, sportsCar is exactly of type SportsCar

Lines 1/5, 3/7, and 4/8 both result the same (respectively) but notice that line 2 and 6 differ


问:
Same request parameter several times results in a comma seperated string?
When passing the same request parameter in a URL several times:

```<code>mypage?lang=en&lang=co&lang=he
</code>```

When looking on the server side, it seems that it's translated to a comma seperated string:

```<code>string Lang = Request.Params["lang"];
// Lang = "en,co,he"
</code>```

Is this normal behaviour? Is there any server side setting or a proper coding way to eliminate this behaviour and get only the first value and dismiss all other parameters? By dismissing, I mean "clean" all other URL parameters from the query string (I find this cannot be done so easily).

答:
This is a normal behaviour, because param keys must be unique.
When you put multiple params with the same key, instead of throwing an exception, returns an array. You should use only :</p>

```<code> var langParams =  Request.Params["lang"].Split(',');
 if(langParams.Length > 0
 {
     var firstlangParam = langParams[0];
     //do your staff....
 }
</code>```

Body:
When passing the same request parameter in a URL several times:

mypage?lang=en&lang=co&lang=he

When looking on the server side, it seems that it's translated to a comma seperated string:

string Lang = Request.Params["lang"];
// Lang = "en,co,he"

Is this normal behaviour? Is there any server side setting or a proper coding way to eliminate this behaviour and get only the first value and dismiss all other parameters? By dismissing, I mean "clean" all other URL parameters from the query string (I find this cannot be done so easily).

Body:
This is a normal behaviour, because param keys must be unique.
When you put multiple params with the same key, instead of throwing an exception, returns an array. You should use only :

 var langParams =  Request.Params["lang"].Split(',');
 if(langParams.Length > 0
 {
     var firstlangParam = langParams[0];
     //do your staff....
 }


问:
Logstash mysql database data not loading to elasticsearch index
I have been working on this all evening and it is driving me crazy. It is supposed to be very simple but it is not working. This works with Oracle but not with MySQL and I created similar db.config that is fed to logstash using -f option.

```<code>input {

 jdbc {
       jdbc_driver_library => "/opt/elk/logstash-5.6.0/lib/mysql-connector-java-5.1.45-bin.jar"
       jdbc_driver_class => "Java::com.mysql.jdbc.Driver"
       jdbc_connection_string => "jdbc:mysql://serverName:3306/dbName?verifyServerCertificate=false&useSSL=true"
       jdbc_user => "userName"
       jdbc_password => "PasswordValue"

    statement => "select user_id, visitor_returning, config_os, visitor_days_since_last from visiting_table where user_id is not null"

    #optional extras I use
      type => "visit"
      tags => ["awesome", "import"]
 }
</code>```

}

output{
stdout {codec => json_lines}

```<code>if [type] == "visit"{
        elasticsearch{
            hosts => "127.0.0.1"
            index => "visitDb"
            document_type => "visit_results"
        }
    }
stdout{}
</code>```

}

Once I run the logstash, it is not loading the data into Elastic search index. I cannot even see the index named visitDb when I do the below.

curl 'localhost:9200/_cat/indices?v'

```<code>health status index          uuid                   pri rep docs.count docs.deleted store.size pri.store.size
</code>```

yellow open   .kibana        Fg6P7XuHSTaonbKEbLcz5A   1   1         21            3     56.5kb         56.5kb
yellow open   orderstotdb    obxZ38prTFCG0W-BFTIhgw   5   1         60            0    245.4kb        245.4kb
y

I am unable to figure out what is going on with MySQL. I can see the console log retrieving the data in json format and writing to console, but the index does not reflect in ElasticSearch nor shows up in Kibana to create index pattern.

Can someone please help ??

答: Answering my own question in case any one else is having the same issue. Elastic Search rejects index names with upper case, since I had name visitDb with D capital, it was rejecting index name creation, go figure :) Hours lost in debugging different options.</p>

Body:
I have been working on this all evening and it is driving me crazy. It is supposed to be very simple but it is not working. This works with Oracle but not with MySQL and I created similar db.config that is fed to logstash using -f option.

input {

 jdbc {
       jdbc_driver_library => "/opt/elk/logstash-5.6.0/lib/mysql-connector-java-5.1.45-bin.jar"
       jdbc_driver_class => "Java::com.mysql.jdbc.Driver"
       jdbc_connection_string => "jdbc:mysql://serverName:3306/dbName?verifyServerCertificate=false&useSSL=true"
       jdbc_user => "userName"
       jdbc_password => "PasswordValue"

    statement => "select user_id, visitor_returning, config_os, visitor_days_since_last from visiting_table where user_id is not null"

    #optional extras I use
      type => "visit"
      tags => ["awesome", "import"]
 }

}

output{
stdout {codec => json_lines}

if [type] == "visit"{
        elasticsearch{
            hosts => "127.0.0.1"
            index => "visitDb"
            document_type => "visit_results"
        }
    }
stdout{}

}

Once I run the logstash, it is not loading the data into Elastic search index. I cannot even see the index named visitDb when I do the below.

curl 'localhost:9200/_cat/indices?v'

health status index          uuid                   pri rep docs.count docs.deleted store.size pri.store.size

yellow open   .kibana        Fg6P7XuHSTaonbKEbLcz5A   1   1         21            3     56.5kb         56.5kb
yellow open   orderstotdb    obxZ38prTFCG0W-BFTIhgw   5   1         60            0    245.4kb        245.4kb
y

I am unable to figure out what is going on with MySQL. I can see the console log retrieving the data in json format and writing to console, but the index does not reflect in ElasticSearch nor shows up in Kibana to create index pattern.

Can someone please help ??


问:
How can I get a list of all variables used in a template?
I have a situation when there are many templates that are using different variables. How can get a list of all the variable names within one template, so I could pass in exactly what the template needs when rendering?

I know I can use regular expression, but it's not as easy to implement as it may seem. The syntax around the variable name can really differ and I don't have the time or resources to lookup every possible situation.

答:
A regex would still work, given the following minimal test cases:

```<code>{{ name }}
{{ name.child }}
{{ name[child] }}
{{ name["child"] }}
{{ name_last["child"] }}
{{ name1["child"] }}
{{ function() }}
{% if variable %}
</code>```

So, if you wanted to parse this as a pcre (even though the question is tagged javascript my understanding is that you want to pre-parse the page), you:

Look for an opening {{ and a closing }}, optionally padded by whitespace: {{\s?\s?}}

Look for the 'head' of a context phrase: ([\w]+)

Create a second non-capture group with the stuff that delineates property selectors: ((?:\..+)|(?:\[.+))?

And you're left with: {{\s?([\w]+)((?:\..+)|(?:\[.+)?)\s?}} whose first capture group ($1) which will match, in the test sample, name, name_last and name1.

Live example.

Body:
A regex would still work, given the following minimal test cases:

{{ name }}
{{ name.child }}
{{ name[child] }}
{{ name["child"] }}
{{ name_last["child"] }}
{{ name1["child"] }}
{{ function() }}
{% if variable %}

So, if you wanted to parse this as a pcre (even though the question is tagged javascript my understanding is that you want to pre-parse the page), you:

Look for an opening {{ and a closing }}, optionally padded by whitespace: {{\s?\s?}}

Look for the 'head' of a context phrase: ([\w]+)

Create a second non-capture group with the stuff that delineates property selectors: ((?:\..+)|(?:\[.+))?

And you're left with: {{\s?([\w]+)((?:\..+)|(?:\[.+)?)\s?}} whose first capture group ($1) which will match, in the test sample, name, name_last and name1.

Live example.


问:
Using DeepL API to translate text
Is there any possibility to find out if the DeepL translator offers an API for the translation? Unfortunately I haven't found any information on this.

Would like to implement this to an Excel script for auto translation. I've already tried it with Google (like https://translate.google.com/#en/es/Hello%20World) but DeepL seems more accurate.

答:
The REST API is finally (commercially) available, see the API reference documentation.

A sample request would be

```<code>https://api.deepl.com/v1/translate?text=Hello%20World!&target_lang=EN&auth_key=XXX
</code>```

where XXX is the authentication key you need to register with DeepL.

Title: Using DeepL API to translate text

Body:
The REST API is finally (commercially) available, see the API reference documentation.

A sample request would be

https://api.deepl.com/v1/translate?text=Hello%20World!&target_lang=EN&auth_key=XXX

where XXX is the authentication key you need to register with DeepL.


问:
How to generate all possible pairs with permutations from list in Python?
How do I generate all possible pairs permutations from a list in Python?

Example:

```<code>input = [3, 8, 2]
output = ['3-8', '3-2', '8-3', '8-2', '2-3', '2-8']
</code>```

答:
You can try itertools:

Data is:

```<code>input = [3, 8, 2]
import itertools
</code>```

One line solution:

```<code>print(['{}-{}'.format(i[0],i[1]) for i in itertools.permutations(input,r=2)])
</code>```

Detailed solution:

Above list comprehension is same as:

```<code>final_list=[]
for i in itertools.permutations(input,r=2):
    final_list.append(('{}-{}'.format(i[0],i[1])))
print(final_list)
</code>```

If you want the result of subtraction then:

```<code>final_list=[]
for i in itertools.permutations(input,r=2):
    final_list.append((i[0]-i[1]))
print(final_list)
</code>```

Body:
How do I generate all possible pairs permutations from a list in Python?

Example:

input = [3, 8, 2]
output = ['3-8', '3-2', '8-3', '8-2', '2-3', '2-8']

Body:
You can try itertools:

Data is:

input = [3, 8, 2]
import itertools

One line solution:

print(['{}-{}'.format(i[0],i[1]) for i in itertools.permutations(input,r=2)])

Detailed solution:

Above list comprehension is same as:

final_list=[]
for i in itertools.permutations(input,r=2):
    final_list.append(('{}-{}'.format(i[0],i[1])))
print(final_list)

If you want the result of subtraction then:

final_list=[]
for i in itertools.permutations(input,r=2):
    final_list.append((i[0]-i[1]))
print(final_list)