问:
Groovy command using inheritance cannot compile in Spring Boot remote shell
I have an abstract groovy class with some utility methods that I want to extend from other groovy command classes (for use in Spring Boot's remote shell). However, when I attempt to run the groovy command class, I get a CommandException.

My groovy abstract class looks like the following.

```<code>package commands
import com.xyz.MyService
import org.crsh.command.InvocationContext
import org.springframework.beans.factory.BeanFactory

abstract class abstractcmd {
    private static final String SPRING_FACTORY = "spring.beanfactory"

    protected MyService getMyService(InvocationContext context) {
        return getBeanFactory(context).getBean(MyService.class);
    }

    private BeanFactory getBeanFactory(InvocationContext context) {
        return context.attributes[SPRING_FACTORY];
    }
}
</code>```

My groovy command class looks like the following.

```<code>package commands
import org.crsh.cli.Command
import org.crsh.cli.Usage
import org.crsh.command.InvocationContext

@Usage("do something commands")
class foo extends abstractcmd {
    @Command
    @Usage("bar")
    def String bar(InvocationContext context) {
        try {
            getMyService(context).bar()
            return "did bar"
        } catch (Exception e) {
            return String.format("could not do bar: %s", e.toString())
        }
    }
}
</code>```

When I SSH into the shell and execute foo bar I get the following exception.

```
org.crsh.shell.impl.command.spi.CommandException: Could not create command foo instance
    at org.crsh.lang.impl.groovy.GroovyCompiler$1.getCommand(GroovyCompiler.java:192) ~[crash.shell-1.3.2.jar:?]
    at org.crsh.lang.LanguageCommandResolver.resolveCommand(LanguageCommandResolver.java:101) ~[crash.shell-1.3.2.jar:?]
    at org.crsh.shell.impl.command.CRaSH.getCommand(CRaSH.java:100) ~[crash.shell-1.3.2.jar:?]
    at org.crsh.shell.impl.command.CRaSHSession.getCommand(CRaSHSession.java:96) ~[crash.shell-1.3.2.jar:?]
    at org.crsh.lang.impl.script.PipeLineFactory.create(PipeLineFactory.java:89) ~[crash.shell-1.3.2.jar:?]
    at org.crsh.lang.impl.script.ScriptRepl.eval(ScriptRepl.java:88) ~[crash.shell-1.3.2.jar:?]
    at org.crsh.shell.impl.command.CRaSHSession.createProcess(CRaSHSession.java:163) ~[crash.shell-1.3.2.jar:?]
    at org.crsh.shell.impl.async.AsyncProcess.execute(AsyncProcess.java:172) ~[crash.shell-1.3.2.jar:?]
    at org.crsh.console.Console.iterate(Console.java:219) ~[crash.shell-1.3.2.jar:?]
    at org.crsh.console.Console.on(Console.java:158) ~[crash.shell-1.3.2.jar:?]
    at org.crsh.console.Console.on(Console.java:135) ~[crash.shell-1.3.2.jar:?]
    at org.crsh.console.jline.JLineProcessor.run(JLineProcessor.java:204) ~[crash.shell-1.3.2.jar:?]
    at org.crsh.ssh.term.CRaSHCommand.run(CRaSHCommand.java:99) ~[crash.connectors.ssh-1.3.2.jar:?]
    at java.lang.Thread.run(Thread.java:745) [?:1.8.0_111]
```

If I remove the package commands line from both the abstractcmd and foo classes, then the IDE (IntelliJ) and shell both complain about abstractcmd not being found.

```
2017-03-19 19:34:06 ERROR org.crsh.shell.impl.command.CRaSHProcess.execute:84 - Error while evaluating request 'foo' Could not compile command script foo
org.crsh.shell.impl.command.spi.CommandException: Could not compile command script foo
    at org.crsh.lang.impl.groovy.GroovyClassFactory.parse(GroovyClassFactory.java:65) ~[crash.shell-1.3.2.jar:?]
    at org.crsh.lang.impl.groovy.GroovyCompiler$1.getCommand(GroovyCompiler.java:172) ~[crash.shell-1.3.2.jar:?]
    at org.crsh.lang.LanguageCommandResolver.resolveCommand(LanguageCommandResolver.java:101) ~[crash.shell-1.3.2.jar:?]
    at org.crsh.shell.impl.command.CRaSH.getCommand(CRaSH.java:100) ~[crash.shell-1.3.2.jar:?]
    at org.crsh.shell.impl.command.CRaSHSession.getCommand(CRaSHSession.java:96) ~[crash.shell-1.3.2.jar:?]
    at org.crsh.lang.impl.script.PipeLineFactory.create(PipeLineFactory.java:89) ~[crash.shell-1.3.2.jar:?]
    at org.crsh.lang.impl.script.ScriptRepl.eval(ScriptRepl.java:88) ~[crash.shell-1.3.2.jar:?]
    at org.crsh.shell.impl.command.CRaSHSession.createProcess(CRaSHSession.java:163) ~[crash.shell-1.3.2.jar:?]
    at org.crsh.shell.impl.async.AsyncProcess.execute(AsyncProcess.java:172) ~[crash.shell-1.3.2.jar:?]
    at org.crsh.console.Console.iterate(Console.java:219) ~[crash.shell-1.3.2.jar:?]
    at org.crsh.console.Console.on(Console.java:158) ~[crash.shell-1.3.2.jar:?]
    at org.crsh.console.Console.on(Console.java:135) ~[crash.shell-1.3.2.jar:?]
    at org.crsh.console.jline.JLineProcessor.run(JLineProcessor.java:204) ~[crash.shell-1.3.2.jar:?]
    at org.crsh.ssh.term.CRaSHCommand.run(CRaSHCommand.java:99) ~[crash.connectors.ssh-1.3.2.jar:?]
    at java.lang.Thread.run(Thread.java:745) [?:1.8.0_111]
Caused by: org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
foo: 9: unable to resolve class abstractcmd
 @ line 9, column 1.
   @Usage("bar")
   ^

1 error

    at org.codehaus.groovy.control.ErrorCollector.failIfErrors(ErrorCollector.java:310) ~[groovy-2.4.7.jar:2.4.7]
    at org.codehaus.groovy.control.CompilationUnit.applyToSourceUnits(CompilationUnit.java:946) ~[groovy-2.4.7.jar:2.4.7]
    at org.codehaus.groovy.control.CompilationUnit.doPhaseOperation(CompilationUnit.java:593) ~[groovy-2.4.7.jar:2.4.7]
    at org.codehaus.groovy.control.CompilationUnit.compile(CompilationUnit.java:542) ~[groovy-2.4.7.jar:2.4.7]
    at groovy.lang.GroovyClassLoader.doParseClass(GroovyClassLoader.java:298) ~[groovy-2.4.7.jar:2.4.7]
    at groovy.lang.GroovyClassLoader.parseClass(GroovyClassLoader.java:268) ~[groovy-2.4.7.jar:2.4.7]
    at org.crsh.lang.impl.groovy.GroovyClassFactory.parse(GroovyClassFactory.java:59) ~[crash.shell-1.3.2.jar:?]
    ... 14 more
```

The only way that I am able to get a custom command to work properly if is I don't extend abstractcmd (thereby implement the "util" methods in the command class) and remove the package line.

I am using Spring Boot v1.5.1.RELEASE.

Any ideas on what I'm doing wrong?

答:
Looks like CRaSH has issues with groovy classes extending other groovy classes, because if you don't extend one, it works just fine.

I'm sorry but I did not have time to fully investigate how and why (corrections/updates are more than welcome), and didn't find anything in the docs but the good news is that you can extend an abstract java class to achieve the same thing. I stumbled upon such a sample for the cron command that extends a GroovyCommand abstract class with the following javadoc:

```<code>/**
 * The base command for Groovy class based commands.
 */
public abstract class GroovyCommand extends BaseCommand implements GroovyObject
</code>```

So, to cut a long story short, you could use the following workaround:

Abstract SpringAwareCommand java class

```<code>package crash.commands;

import org.crsh.command.BaseCommand;
import org.springframework.beans.factory.BeanFactory;

public abstract class SpringAwareCommand extends BaseCommand {

    private static final String SPRING_BEAN_FACTORY = "spring.beanfactory";

    protected <T> T getBean(Class<T> beanClass) {
        return ((BeanFactory) this.context.getAttributes().get(SPRING_BEAN_FACTORY)).getBean(beanClass);
    }

}
</code>```

Updated foo groovy class

```<code>package crash.commands

import com.xyz.MyService
import org.crsh.cli.Command
import org.crsh.cli.Usage

@Usage("do something commands")
class foo extends SpringAwareCommand {
    @Command
    @Usage("bar")
    def String bar() {
        try {
            getBean(MyService.class).bar()
            return "did bar"
        } catch (Exception e) {
            return String.format("could not do bar: %s", e.toString())
        }
    }
}
</code>```

Body:
I have an abstract groovy class with some utility methods that I want to extend from other groovy command classes (for use in Spring Boot's remote shell). However, when I attempt to run the groovy command class, I get a CommandException.

My groovy abstract class looks like the following.

package commands
import com.xyz.MyService
import org.crsh.command.InvocationContext
import org.springframework.beans.factory.BeanFactory

abstract class abstractcmd {
    private static final String SPRING_FACTORY = "spring.beanfactory"

    protected MyService getMyService(InvocationContext context) {
        return getBeanFactory(context).getBean(MyService.class);
    }

    private BeanFactory getBeanFactory(InvocationContext context) {
        return context.attributes[SPRING_FACTORY];
    }
}

My groovy command class looks like the following.

package commands
import org.crsh.cli.Command
import org.crsh.cli.Usage
import org.crsh.command.InvocationContext

@Usage("do something commands")
class foo extends abstractcmd {
    @Command
    @Usage("bar")
    def String bar(InvocationContext context) {
        try {
            getMyService(context).bar()
            return "did bar"
        } catch (Exception e) {
            return String.format("could not do bar: %s", e.toString())
        }
    }
}

When I SSH into the shell and execute foo bar I get the following exception.

org.crsh.shell.impl.command.spi.CommandException: Could not create command foo instance
    at org.crsh.lang.impl.groovy.GroovyCompiler$1.getCommand(GroovyCompiler.java:192) ~[crash.shell-1.3.2.jar:?]
    at org.crsh.lang.LanguageCommandResolver.resolveCommand(LanguageCommandResolver.java:101) ~[crash.shell-1.3.2.jar:?]
    at org.crsh.shell.impl.command.CRaSH.getCommand(CRaSH.java:100) ~[crash.shell-1.3.2.jar:?]
    at org.crsh.shell.impl.command.CRaSHSession.getCommand(CRaSHSession.java:96) ~[crash.shell-1.3.2.jar:?]
    at org.crsh.lang.impl.script.PipeLineFactory.create(PipeLineFactory.java:89) ~[crash.shell-1.3.2.jar:?]
    at org.crsh.lang.impl.script.ScriptRepl.eval(ScriptRepl.java:88) ~[crash.shell-1.3.2.jar:?]
    at org.crsh.shell.impl.command.CRaSHSession.createProcess(CRaSHSession.java:163) ~[crash.shell-1.3.2.jar:?]
    at org.crsh.shell.impl.async.AsyncProcess.execute(AsyncProcess.java:172) ~[crash.shell-1.3.2.jar:?]
    at org.crsh.console.Console.iterate(Console.java:219) ~[crash.shell-1.3.2.jar:?]
    at org.crsh.console.Console.on(Console.java:158) ~[crash.shell-1.3.2.jar:?]
    at org.crsh.console.Console.on(Console.java:135) ~[crash.shell-1.3.2.jar:?]
    at org.crsh.console.jline.JLineProcessor.run(JLineProcessor.java:204) ~[crash.shell-1.3.2.jar:?]
    at org.crsh.ssh.term.CRaSHCommand.run(CRaSHCommand.java:99) ~[crash.connectors.ssh-1.3.2.jar:?]
    at java.lang.Thread.run(Thread.java:745) [?:1.8.0_111]

If I remove the package commands line from both the abstractcmd and foo classes, then the IDE (IntelliJ) and shell both complain about abstractcmd not being found.

2017-03-19 19:34:06 ERROR org.crsh.shell.impl.command.CRaSHProcess.execute:84 - Error while evaluating request 'foo' Could not compile command script foo
org.crsh.shell.impl.command.spi.CommandException: Could not compile command script foo
    at org.crsh.lang.impl.groovy.GroovyClassFactory.parse(GroovyClassFactory.java:65) ~[crash.shell-1.3.2.jar:?]
    at org.crsh.lang.impl.groovy.GroovyCompiler$1.getCommand(GroovyCompiler.java:172) ~[crash.shell-1.3.2.jar:?]
    at org.crsh.lang.LanguageCommandResolver.resolveCommand(LanguageCommandResolver.java:101) ~[crash.shell-1.3.2.jar:?]
    at org.crsh.shell.impl.command.CRaSH.getCommand(CRaSH.java:100) ~[crash.shell-1.3.2.jar:?]
    at org.crsh.shell.impl.command.CRaSHSession.getCommand(CRaSHSession.java:96) ~[crash.shell-1.3.2.jar:?]
    at org.crsh.lang.impl.script.PipeLineFactory.create(PipeLineFactory.java:89) ~[crash.shell-1.3.2.jar:?]
    at org.crsh.lang.impl.script.ScriptRepl.eval(ScriptRepl.java:88) ~[crash.shell-1.3.2.jar:?]
    at org.crsh.shell.impl.command.CRaSHSession.createProcess(CRaSHSession.java:163) ~[crash.shell-1.3.2.jar:?]
    at org.crsh.shell.impl.async.AsyncProcess.execute(AsyncProcess.java:172) ~[crash.shell-1.3.2.jar:?]
    at org.crsh.console.Console.iterate(Console.java:219) ~[crash.shell-1.3.2.jar:?]
    at org.crsh.console.Console.on(Console.java:158) ~[crash.shell-1.3.2.jar:?]
    at org.crsh.console.Console.on(Console.java:135) ~[crash.shell-1.3.2.jar:?]
    at org.crsh.console.jline.JLineProcessor.run(JLineProcessor.java:204) ~[crash.shell-1.3.2.jar:?]
    at org.crsh.ssh.term.CRaSHCommand.run(CRaSHCommand.java:99) ~[crash.connectors.ssh-1.3.2.jar:?]
    at java.lang.Thread.run(Thread.java:745) [?:1.8.0_111]
Caused by: org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
foo: 9: unable to resolve class abstractcmd
 @ line 9, column 1.
   @Usage("bar")
   ^

1 error

    at org.codehaus.groovy.control.ErrorCollector.failIfErrors(ErrorCollector.java:310) ~[groovy-2.4.7.jar:2.4.7]
    at org.codehaus.groovy.control.CompilationUnit.applyToSourceUnits(CompilationUnit.java:946) ~[groovy-2.4.7.jar:2.4.7]
    at org.codehaus.groovy.control.CompilationUnit.doPhaseOperation(CompilationUnit.java:593) ~[groovy-2.4.7.jar:2.4.7]
    at org.codehaus.groovy.control.CompilationUnit.compile(CompilationUnit.java:542) ~[groovy-2.4.7.jar:2.4.7]
    at groovy.lang.GroovyClassLoader.doParseClass(GroovyClassLoader.java:298) ~[groovy-2.4.7.jar:2.4.7]
    at groovy.lang.GroovyClassLoader.parseClass(GroovyClassLoader.java:268) ~[groovy-2.4.7.jar:2.4.7]
    at org.crsh.lang.impl.groovy.GroovyClassFactory.parse(GroovyClassFactory.java:59) ~[crash.shell-1.3.2.jar:?]
    ... 14 more

The only way that I am able to get a custom command to work properly if is I don't extend abstractcmd (thereby implement the "util" methods in the command class) and remove the package line.

I am using Spring Boot v1.5.1.RELEASE.

Any ideas on what I'm doing wrong?

Body:
Looks like CRaSH has issues with groovy classes extending other groovy classes, because if you don't extend one, it works just fine.

I'm sorry but I did not have time to fully investigate how and why (corrections/updates are more than welcome), and didn't find anything in the docs but the good news is that you can extend an abstract java class to achieve the same thing. I stumbled upon such a sample for the cron command that extends a GroovyCommand abstract class with the following javadoc:

/**
 * The base command for Groovy class based commands.
 */
public abstract class GroovyCommand extends BaseCommand implements GroovyObject

So, to cut a long story short, you could use the following workaround:

Abstract SpringAwareCommand java class

package crash.commands;

import org.crsh.command.BaseCommand;
import org.springframework.beans.factory.BeanFactory;

public abstract class SpringAwareCommand extends BaseCommand {

    private static final String SPRING_BEAN_FACTORY = "spring.beanfactory";

    protected <T> T getBean(Class<T> beanClass) {
        return ((BeanFactory) this.context.getAttributes().get(SPRING_BEAN_FACTORY)).getBean(beanClass);
    }

}

Updated foo groovy class

package crash.commands

import com.xyz.MyService
import org.crsh.cli.Command
import org.crsh.cli.Usage

@Usage("do something commands")
class foo extends SpringAwareCommand {
    @Command
    @Usage("bar")
    def String bar() {
        try {
            getBean(MyService.class).bar()
            return "did bar"
        } catch (Exception e) {
            return String.format("could not do bar: %s", e.toString())
        }
    }
}


来源: stackexchange

问:
Creating a pivot table based on categorical variables
I am currently doing some analysis in R and can't seem to find a working solution to the following problem:

My raw data is a table containing 3 columns: "user id", "year" and "block".
The block column can either have a value 'north', 'east', 'south', 'west' or 'other'.

What i want to creat now is some sort of pivot table (not sure if this is the right term to use here). This table should consist of a single row for each combination of user_id and year followed by 5 new columns containing a dummy variable referencing whether or not the customer was sitting in the respective block that year or not. Similar to the example below:

I have been trying to get things working through the use of the reshape package in R but it seems to struggle handling the categorical variable "block".
Any tips/help is greatly appreciated!

Thanks in advance

答:
With data.table you can try this:

```<code>require(data.table)
dt <- as.data.table(df)
types <- c("east", "north", "south", "west")
dt[, lapply(types, function(x) sum(block==x)), keyby =.(Userid, year)]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
With data.table you can try this:

require(data.table)
dt <- as.data.table(df)
types <- c("east", "north", "south", "west")
dt[, lapply(types, function(x) sum(block==x)), keyby =.(Userid, year)]


问:
Hide port number in URL odoo?
I need to hind port number from url. i am running odoo instance using --db-filter='^%d@', mydomain.com:8069 is works fine but mydomain.com is getting page not found. I have installed nginx and edited /etc/nginx/nginx.conf as below.

/etc/nginx/nginx.conf

```<code>#user  nobody;
worker_processes  1;

events {
    worker_connections  1024;

}

http {
    include       mime.types;
    # anything written in /opt/nginx/conf/mime.types is interpreted as if written inside the http { } block

    default_type  application/octet-stream;
    #

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
#                  '$status $body_bytes_sent "$http_referer" '
#                  '"$http_user_agent" "$http_x_forwarded_for"';

#access_log  logs/access.log  main;

sendfile        on;

keepalive_timeout  65;

server {
    # You would want to make a separate file with its own server block for each virtual domain
    # on your server and then include them.

    listen       8069;
    listen       192.168.1.111:8080;
    listen       192.168.1.111;
    #tells Nginx the hostname and the TCP port where it should listen for HTTP connections.
    # listen 80; is equivalent to listen *:80;

#server_name  localhost;
     server_name  mydomain.com;
     server_name  www.mydomain.com;
    # lets you doname-based virtual hosting

    #charset koi8-r;

    #access_log  logs/host.access.log  main;

    location / {
        #The location setting lets you configure how nginx responds to requests for resources within the server.
        root   html;
        index  index.html index.htm;
    }

    #error_page  404              /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   html;
    }

}
}
</code>```

How can i do that? suggest any solutions..

答:
Try the following server configuration. You can put it in a separate file and include it in the main nginx.conf if you like.

```<code>upstream odoo {
   server 127.0.0.1:8080;  # Or wherever your Odoo service is listening
}

server {
    server_name mydomain.com;
    listen       0.0.0.0:80;

    root /var/www/html/odoo/;
    index index.php index.html index.htm;

    location / {
        try_files $uri $uri/ @odoo;
    }

    location @odoo {
        proxy_set_header X-Real-IP  $remote_addr;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_set_header Host $host;
        proxy_pass http://odoo;
    }
}
</code>```

In short, this defines an upstream server odoo for your odoo service. When a request is received (say mydomain.com/path/to/resource), nginx will try to process it by delivering the corresponding resource it is supposed to serve from the root dir. If that fails, it will retry, appending a slash to it. If that fails as well, it will send the path to the upstream server (odoo) for processing.

Title: Hide port number in URL odoo?

Body:
I need to hind port number from url. i am running odoo instance using --db-filter='^%d@', mydomain.com:8069 is works fine but mydomain.com is getting page not found. I have installed nginx and edited /etc/nginx/nginx.conf as below.

/etc/nginx/nginx.conf

#user  nobody;
worker_processes  1;

events {
    worker_connections  1024;

}

http {
    include       mime.types;
    # anything written in /opt/nginx/conf/mime.types is interpreted as if written inside the http { } block

    default_type  application/octet-stream;
    #

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
#                  '$status $body_bytes_sent "$http_referer" '
#                  '"$http_user_agent" "$http_x_forwarded_for"';

#access_log  logs/access.log  main;

sendfile        on;

keepalive_timeout  65;

server {
    # You would want to make a separate file with its own server block for each virtual domain
    # on your server and then include them.

    listen       8069;
    listen       192.168.1.111:8080;
    listen       192.168.1.111;
    #tells Nginx the hostname and the TCP port where it should listen for HTTP connections.
    # listen 80; is equivalent to listen *:80;

#server_name  localhost;
     server_name  mydomain.com;
     server_name  www.mydomain.com;
    # lets you doname-based virtual hosting

    #charset koi8-r;

    #access_log  logs/host.access.log  main;

    location / {
        #The location setting lets you configure how nginx responds to requests for resources within the server.
        root   html;
        index  index.html index.htm;
    }

    #error_page  404              /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   html;
    }

}
}

How can i do that? suggest any solutions..

Body:
Try the following server configuration. You can put it in a separate file and include it in the main nginx.conf if you like.

upstream odoo {
   server 127.0.0.1:8080;  # Or wherever your Odoo service is listening
}

server {
    server_name mydomain.com;
    listen       0.0.0.0:80;

    root /var/www/html/odoo/;
    index index.php index.html index.htm;

    location / {
        try_files $uri $uri/ @odoo;
    }

    location @odoo {
        proxy_set_header X-Real-IP  $remote_addr;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_set_header Host $host;
        proxy_pass http://odoo;
    }
}

In short, this defines an upstream server odoo for your odoo service. When a request is received (say mydomain.com/path/to/resource), nginx will try to process it by delivering the corresponding resource it is supposed to serve from the root dir. If that fails, it will retry, appending a slash to it. If that fails as well, it will send the path to the upstream server (odoo) for processing.


问:
Compile a small subset of the linux kernel (i.e. just a few files)
I'm trying to extract specific pieces of code from the linux kernel. I specifically want to compile only a few files, and obviously need to ensure any references and dependencies to other files are included for the compile to work.</p>

答:
```make fs/read_write.o
make fs/btrfs/```

For anything else, like .ko files, you need to have System.map available first, which means having built the core kernel image first (vmlinux).

ContentLicense: CC BY-SA 2.5

Body:
make fs/read_write.o
make fs/btrfs/

For anything else, like .ko files, you need to have System.map available first, which means having built the core kernel image first (vmlinux).


问:
Table-valued function displaying only 1 result
I've got this table valued function and I want it to display all records with the same "PeopleID". How can I do it? It's currently displaying only 1 of the possible results.</p>

```<code>ALTER FUNCTION dbo.ufnGetContactInformation(@FuncID int)
RETURNS @retContactInformation TABLE
(
    -- Columns returned by the function
    FuncID int PRIMARY KEY NOT NULL,
    Full_Name nvarchar(75) NULL,
    Phone nvarchar(100) NULL,
    Email nvarchar(50) NULL,
    City nvarchar(20) NULL
)
AS
BEGIN
    DECLARE
        @fullname nvarchar(75),
        @phonenumber nvarchar(100),
        @email nvarchar(50),
        @city nvarchar(20);

    -- > Get common contact information
    SELECT
            @fullname = p.Full_Name,
            @phonenumber = c.Phone,
            @email = c.Email,
            @city = c.CityID
            FROM d_People p, d_Contacts c
            WHERE p.PeopleID=@FuncID;
    -- < Get common contact information
    IF @FuncID IS NOT NULL
    BEGIN
        INSERT @retContactInformation
        SELECT @FuncID, @fullname, @phonenumber, @email, @city;
    END;
    RETURN;
END;
GO
</code>```

答:
You need a proper join for your two tables, otherwise your query makes no sense. What you have now will give you one person full_name, but every contact phone, email, and city.

Bad habits to kick : using old-style JOINs - Aaron Bertrand

When you select into the scalar variables, you will only get one result in each variable. Inserting the variables after setting them to only hold one row will only ever yield at most one row.

You can simplify your function as an in-line table-valued function like so:

```<code>alter function dbo.ufngetcontactinformation(@funcid int)
returns table as return (
  select
     funcid = p.peopleid
   , fullname = p.full_name
   , phonenumber = c.phone
   , email = c.email
   , city = c.cityid
  from d_people p, d_contacts c
  where p.peopleid = @funcid;
);
go
</code>```

Reference

When is a SQL function not a function? "If it’s not inline, it’s rubbish." - Rob Farley

Inline Scalar Functions - Itzik Ben-Gan

Scalar functions, inlining, and performance: An entertaining title for a boring post - Adam Machanic

TSQL User-Defined Functions: Ten Questions You Were Too Shy To Ask - Robert Sheldon

If you have to have a multi-statement table valued function despite the perfomance hit:

```<code>alter function dbo.ufngetcontactinformation(@funcid int)
returns @retcontactinformation table
(
    -- columns returned by the function
    funcid int primary key not null,
    full_name nvarchar(75) null,
    phone nvarchar(100) null,
    email nvarchar(50) null,
    city nvarchar(20) null
)
as
begin
  insert @retcontactinformation
select
    @funcid
  , p.full_name
  , c.phone
  , c.email
  , c.cityid
from d_people p, d_contacts c
where p.peopleid = @funcid;
return;
end;
go
</code>```

Body:
I've got this table valued function and I want it to display all records with the same "PeopleID". How can I do it? It's currently displaying only 1 of the possible results.

ALTER FUNCTION dbo.ufnGetContactInformation(@FuncID int)
RETURNS @retContactInformation TABLE
(
    -- Columns returned by the function
    FuncID int PRIMARY KEY NOT NULL,
    Full_Name nvarchar(75) NULL,
    Phone nvarchar(100) NULL,
    Email nvarchar(50) NULL,
    City nvarchar(20) NULL
)
AS
BEGIN
    DECLARE
        @fullname nvarchar(75),
        @phonenumber nvarchar(100),
        @email nvarchar(50),
        @city nvarchar(20);

    -- > Get common contact information
    SELECT
            @fullname = p.Full_Name,
            @phonenumber = c.Phone,
            @email = c.Email,
            @city = c.CityID
            FROM d_People p, d_Contacts c
            WHERE p.PeopleID=@FuncID;
    -- < Get common contact information
    IF @FuncID IS NOT NULL
    BEGIN
        INSERT @retContactInformation
        SELECT @FuncID, @fullname, @phonenumber, @email, @city;
    END;
    RETURN;
END;
GO

Body:
You need a proper join for your two tables, otherwise your query makes no sense. What you have now will give you one person full_name, but every contact phone, email, and city.

Bad habits to kick : using old-style JOINs - Aaron Bertrand

When you select into the scalar variables, you will only get one result in each variable. Inserting the variables after setting them to only hold one row will only ever yield at most one row.

You can simplify your function as an in-line table-valued function like so:

alter function dbo.ufngetcontactinformation(@funcid int)
returns table as return (
  select
     funcid = p.peopleid
   , fullname = p.full_name
   , phonenumber = c.phone
   , email = c.email
   , city = c.cityid
  from d_people p, d_contacts c
  where p.peopleid = @funcid;
);
go

Reference

When is a SQL function not a function? "If it’s not inline, it’s rubbish." - Rob Farley

Inline Scalar Functions - Itzik Ben-Gan

Scalar functions, inlining, and performance: An entertaining title for a boring post - Adam Machanic

TSQL User-Defined Functions: Ten Questions You Were Too Shy To Ask - Robert Sheldon

If you have to have a multi-statement table valued function despite the perfomance hit:

alter function dbo.ufngetcontactinformation(@funcid int)
returns @retcontactinformation table
(
    -- columns returned by the function
    funcid int primary key not null,
    full_name nvarchar(75) null,
    phone nvarchar(100) null,
    email nvarchar(50) null,
    city nvarchar(20) null
)
as
begin
  insert @retcontactinformation
select
    @funcid
  , p.full_name
  , c.phone
  , c.email
  , c.cityid
from d_people p, d_contacts c
where p.peopleid = @funcid;
return;
end;
go


问:
Proc Optmodel MILP solver, how to find infeasible constraints
I am trying to build an optimization model using proc optmodel. I am using MILP solver and im getting into infeasible solution again and again.

Problem happens when pre solver can't get the conflicting constraint, I dont get any info in log regarding where to go and do edits and its a long and tedious process of figuring out among 1000's of constraints.

Please advice if there is a way to identify the infeasible constraints after a solve run.

I have tried using IIS option which doesnt work for MILP solver, PRESTOL option to get even the slightest infeasible constraints but nothing worked.

答:
If the MILP solver is able to identify a specific constraint that is causing infeasibility, it will show up in the log. i.e.:

Note: Constraint con[1] causes the problem to be infeasible.

If it can't, it will tell you that the problem itself is infeasible. To find out the exact constraint causing the problem, you can remove constraints and loop the solver until it becomes feasible. See this answer for more information. Example code below:

```<code>proc optmodel presolver=none;
   /* declare variables */
   var x{1..3} >=0;

   /* upper bound on variable x[3] */
   x[3].ub = 3;

   /* objective function */
   min obj = x[1] + x[2] + x[3];

   /* constraints */
   con c1: x[1] + x[2] >= 10;
   con c2: x[1] + x[3] <= 4;
   con c3: 4 <= x[2] + x[3] <= 5;

   num iteration init 1;
   set IIS{1 .. iteration} init {};
   do while (1);
     solve with lp / iis = on;
     IIS[iteration] = {ci in 1 .. _NCON_: _CON_[ci].status ~= ''};
     if card(IIS[iteration]) = 0 then leave;
     for {ci in IIS[iteration]: _CON_[ci].status = 'I_L'}
        _CON_[ci].lb = -constant('big');
     for {ci in IIS[iteration]: _CON_[ci].status = 'I_U'}
        _CON_[ci].ub = constant('big');
     iteration = iteration + 1;
   end;
   iteration = iteration - 1;
   for {ii in 1 .. iteration}
     put IIS[ii]=;
quit;
</code>```

Source: LeoLopes, SAS Community Forum

Body:
If the MILP solver is able to identify a specific constraint that is causing infeasibility, it will show up in the log. i.e.:

Note: Constraint con[1] causes the problem to be infeasible.

If it can't, it will tell you that the problem itself is infeasible. To find out the exact constraint causing the problem, you can remove constraints and loop the solver until it becomes feasible. See this answer for more information. Example code below:

proc optmodel presolver=none;
   /* declare variables */
   var x{1..3} >=0;

   /* upper bound on variable x[3] */
   x[3].ub = 3;

   /* objective function */
   min obj = x[1] + x[2] + x[3];

   /* constraints */
   con c1: x[1] + x[2] >= 10;
   con c2: x[1] + x[3] <= 4;
   con c3: 4 <= x[2] + x[3] <= 5;

   num iteration init 1;
   set IIS{1 .. iteration} init {};
   do while (1);
     solve with lp / iis = on;
     IIS[iteration] = {ci in 1 .. _NCON_: _CON_[ci].status ~= ''};
     if card(IIS[iteration]) = 0 then leave;
     for {ci in IIS[iteration]: _CON_[ci].status = 'I_L'}
        _CON_[ci].lb = -constant('big');
     for {ci in IIS[iteration]: _CON_[ci].status = 'I_U'}
        _CON_[ci].ub = constant('big');
     iteration = iteration + 1;
   end;
   iteration = iteration - 1;
   for {ii in 1 .. iteration}
     put IIS[ii]=;
quit;

Source: LeoLopes, SAS Community Forum


问:
jquery json and objects
I am trying to work with an API to get JSON pulled from online, it keeps interpreting text as objects, if you compare the output this gives and the source of the link, it fails to grab some key information.

$(document).ready(function() {
  $.getJSON("http://www.dnd5eapi.co/api/races/1", function(result) {
    $.each(result, function(i, field) {
      $("#output").append(field + "
 ");
    });
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<div id="output"></div></code>```

答:
It does not miss key information, you are simply iterating through the properties of the result JSON object. You are not iterating through the properties of the properties of the object, and so on, recursively. You can see some [object Object] in the output, these occur if a property value is another object instead of a string. These contain the information you are "missing".

As Rory McCrossan said, this is because you are gettin a JSON result and you get it already parsed in an object rather than a string. This way you can easily access its properties, but if you rather need the original string, use $.get or $.ajax instead of $.getJSON and specify the dataType as text.

For recursive JSON iteration, see this.

Example for simple text-based parsing:

```<code>$(document).ready(function(){
    $.get(
    {
        url: "http://www.dnd5eapi.co/api/races/1",
        dataType: "text",
        success: function(result){
            $("#output").append(result);
    }});
});
</code>```

Title: jquery json and objects

Body:
It does not miss key information, you are simply iterating through the properties of the result JSON object. You are not iterating through the properties of the properties of the object, and so on, recursively. You can see some [object Object] in the output, these occur if a property value is another object instead of a string. These contain the information you are "missing".

As Rory McCrossan said, this is because you are gettin a JSON result and you get it already parsed in an object rather than a string. This way you can easily access its properties, but if you rather need the original string, use $.get or $.ajax instead of $.getJSON and specify the dataType as text.

For recursive JSON iteration, see this.

Example for simple text-based parsing:

$(document).ready(function(){
    $.get(
    {
        url: "http://www.dnd5eapi.co/api/races/1",
        dataType: "text",
        success: function(result){
            $("#output").append(result);
    }});
});


问:
Spring : Sharing Application Context between different servlets
I have a web application and SOAP Web service in same project. I have defined two servlet xml

mvc-servlet.xml

```<code><import resource="ws-applicationContext.xml"/>
</code>```

soap-servlet.xml

```<code><import resource="soap-applicationContext.xml"/>
</code>```

Bot these applicationContext import a common file

Contents of soap-applicationContext.xml

```<code><import resource="my-common-applicationContext.xml"/>

<context:annotation-config/>
<context:component-scan base-package="com.xyz.myproject1"/>
</code>```

Contents of ws-applicationContext.xml

```<code><import resource="my-common-applicationContext.xml"/>

<context:annotation-config/>
<context:component-scan base-package="com.xyz.myproject2"/>
</code>```

my-common-applicationContext.xml  has common packages which are needed by both like integration,data etc.

At start of application , since my-common-applicationContext.xml is included in both the application context, it gets loaded twice. This leads to DataConfigurations being loaded twice.

What is the best way to solve this problem also ensuring both the context have access to relevant beans ?

答:
Figured out the right way to do it .
All common files go in common but are loaded with ContextLoaderListener. This ensures all classes are available.</p>

```<code><listener>
    <listener-class>
        org.springframework.web.context.ContextLoaderListener
    </listener-class>
</listener>

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        classpath:my-common-applicationContext.xml
    </param-value>
</context-param>
</code>```

Body:
I have a web application and SOAP Web service in same project. I have defined two servlet xml

mvc-servlet.xml

<import resource="ws-applicationContext.xml"/>

soap-servlet.xml

<import resource="soap-applicationContext.xml"/>

Bot these applicationContext import a common file

Contents of soap-applicationContext.xml

<import resource="my-common-applicationContext.xml"/>

<context:annotation-config/>
<context:component-scan base-package="com.xyz.myproject1"/>

Contents of ws-applicationContext.xml

<import resource="my-common-applicationContext.xml"/>

<context:annotation-config/>
<context:component-scan base-package="com.xyz.myproject2"/>

my-common-applicationContext.xml  has common packages which are needed by both like integration,data etc.

At start of application , since my-common-applicationContext.xml is included in both the application context, it gets loaded twice. This leads to DataConfigurations being loaded twice.

What is the best way to solve this problem also ensuring both the context have access to relevant beans ?

Body:
Figured out the right way to do it .
All common files go in common but are loaded with ContextLoaderListener. This ensures all classes are available.

<listener>
    <listener-class>
        org.springframework.web.context.ContextLoaderListener
    </listener-class>
</listener>

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        classpath:my-common-applicationContext.xml
    </param-value>
</context-param>


问:
Return Collection after update()?
Using Raw, how to return collection of updated row?

For example:

```<code>$updated = DB::table('users')->where('id', 1)->update(['votes' => 123]);
</code>```

I was expecting dd($updated) to return updated row of collection but it returned 1.

```<code>{{$updated->votes}} should return 123
</code>```

答:
In controller you write below code for update :

```<code> $updated = DB::table('users')->where('id', 1)->update(['votes' => 123])->get();
</code>```

Title: Return Collection after update()?

Body:
Using Raw, how to return collection of updated row?

For example:

$updated = DB::table('users')->where('id', 1)->update(['votes' => 123]);

I was expecting dd($updated) to return updated row of collection but it returned 1.

{{$updated->votes}} should return 123

Body:
In controller you write below code for update :

 $updated = DB::table('users')->where('id', 1)->update(['votes' => 123])->get();


问:
jquery mouseenter on child div with bigger dimensions than parent div
I have a parent div with height=100px which is smaller than child div which has height=200px.

When I attach jquery mouseenter on parent div then the event triggers even if I hover the pointer over child ( hover over the portion of child which extends the height of parent ).

Can anyone explain this?

$(document).ready(function() {
  $(".parent").mouseover(function(e) {
   console.log(e.target);
  });
  $(".child").mouseover(function(e) {
   console.log(e.target);
  });
  $(".grandchild").mouseover(function(e) {
   console.log(e.target);
  });
 });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.parent {
   background-color: green;
   height: 50px;
  }
  .child {
   background-color: red;
   height: 100px;
  }
  .grandchild {
   background-color: blue;
   height: 200px;
  }</code>```

    Test

```

--UPDATE--
At first it unclear to me what was exactly the problem. Now I think I understand (I updated the code).

Say we have a parent div with width=100px and height=100px.

Then we have a child div with width=200px and height=200px (bigger area than parent).

When I hover the mouse over the child (but not over the parent yet) the browser calculates that the pointer is over the parent too, although it does not.

So if I have a handler both on child and on parent, they will fire both by the time I enter the child div only.

Thank you.

答:
use this in your css. It removes all mouse events on the child element. (Also isnt hover-able...)

```<code>.child{pointer-events: none}
</code>```

"pointer-events: none":

The element is never the target of mouse events; however, mouse events may target its descendant elements if those descendants have pointer-events set to some other value. In these circumstances, mouse events will trigger event listeners on this parent element as appropriate on their way to/from the descendant during the event capture/bubble phases.

source: https://developer.mozilla.org/en/docs/Web/CSS/pointer-events

Body:
I have a parent div with height=100px which is smaller than child div which has height=200px.

When I attach jquery mouseenter on parent div then the event triggers even if I hover the pointer over child ( hover over the portion of child which extends the height of parent ).

Can anyone explain this?

$(document).ready(function() {
  $(".parent").mouseover(function(e) {
   console.log(e.target);
  });
  $(".child").mouseover(function(e) {
   console.log(e.target);
  });
  $(".grandchild").mouseover(function(e) {
   console.log(e.target);
  });
 });

.parent {
   background-color: green;
   height: 50px;
  }
  .child {
   background-color: red;
   height: 100px;
  }
  .grandchild {
   background-color: blue;
   height: 200px;
  }

    Test

--UPDATE--
At first it unclear to me what was exactly the problem. Now I think I understand (I updated the code).

Say we have a parent div with width=100px and height=100px.

Then we have a child div with width=200px and height=200px (bigger area than parent).

When I hover the mouse over the child (but not over the parent yet) the browser calculates that the pointer is over the parent too, although it does not.

So if I have a handler both on child and on parent, they will fire both by the time I enter the child div only.

Thank you.

Body:
use this in your css. It removes all mouse events on the child element. (Also isnt hover-able...)

.child{pointer-events: none}

"pointer-events: none":

The element is never the target of mouse events; however, mouse events may target its descendant elements if those descendants have pointer-events set to some other value. In these circumstances, mouse events will trigger event listeners on this parent element as appropriate on their way to/from the descendant during the event capture/bubble phases.

source: https://developer.mozilla.org/en/docs/Web/CSS/pointer-events


问:
Property or indexer 'Font.Bold' can not be assigned to - it is read only
I would like it to form a tool change it at one of the characters in thickness (Bold), or underscore (Underline) during program run.
I tried to set the next program code, but failed. I received the following error: "Property or indexer 'Font.Bold' can not be assigned to - it is read only"

Why can not I set this property?

```<code>((TextBox)tabControl1.Controls[S].Controls[K]).Font.Bold = true;
</code>```

答:
You cannot change existing font instance. You should create new font instance from one you have and assign it to textbox. E.g. if you only want to change font style, you can use Font(Font prototype, FontStyle newStyle) constructor:

```<code>var textBox = (TextBox)tabControl1.Controls[S].Controls[K];
textBox.Font = new Font(textBox.Font, FontStyle.Bold);
</code>```

Body:
I would like it to form a tool change it at one of the characters in thickness (Bold), or underscore (Underline) during program run.
I tried to set the next program code, but failed. I received the following error: "Property or indexer 'Font.Bold' can not be assigned to - it is read only"

Why can not I set this property?

((TextBox)tabControl1.Controls[S].Controls[K]).Font.Bold = true;

Body:
You cannot change existing font instance. You should create new font instance from one you have and assign it to textbox. E.g. if you only want to change font style, you can use Font(Font prototype, FontStyle newStyle) constructor:

var textBox = (TextBox)tabControl1.Controls[S].Controls[K];
textBox.Font = new Font(textBox.Font, FontStyle.Bold);


问:
How to download a file from a url with Javascript?
How to download a file from a url with Javascript?

I'm trying to get from a textfield a user enters a url as follows:

```<code>new Ext.form.TextField({
                disabled: false,
                        fieldLabel: "file",
                        value:'',
            id:"url"};
</code>```

and I need the value of this variable is the file contained in the above url I am trying as follows:

```<code>var file1 = new OpenLayers.WPS.ComplexPut({
                      identifier: "file1",
                      value: window.location.href = document.getElementById("url")
</code>```

答:
You can use jQuery to load anything from an URL quite easily with:</p>

```<code><script>
   $("#loadhere").load("http://www.google.com");
</script>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
How to download a file from a url with Javascript?

I'm trying to get from a textfield a user enters a url as follows:

new Ext.form.TextField({
                disabled: false,
                        fieldLabel: "file",
                        value:'',
            id:"url"};

and I need the value of this variable is the file contained in the above url I am trying as follows:

var file1 = new OpenLayers.WPS.ComplexPut({
                      identifier: "file1",
                      value: window.location.href = document.getElementById("url")

Body:
You can use jQuery to load anything from an URL quite easily with:

<script>
   $("#loadhere").load("http://www.google.com");
</script>


问:
How do I get culture-neutral type information when reading event viewer content with WMI in C#
I am reading logs from EventViewer using below lines of code.

```<code>var searcher = new ManagementObjectSearcher(@"\\WS2012-DE01\root\cimv2",
               "SELECT * FROM Win32_NTLogEvent WHERE  Type ='Error'");
</code>```

above code works fine in en-US culture, but will fail in other culture because other culture will be representing Error as some other word.

eg: Error word in de-DE culture(german) represents as Fehler. I will be using the same code in different environement. I do not want to maintain a resource file since issue is with only one word or not need a Translator API because of security measures to solve this. Could anyone please provide me a solution.

答:
Don't query filtering by the name of the event type, but filtering by the internal type id:

```<code>var searcher = new ManagementObjectSearcher(@"\\WS2012-DE01\root\cimv2",
               "SELECT * FROM Win32_NTLogEvent WHERE EventType=1");
</code>```

You can see the list of possible values for EventType in the documentation of the WMI Win32_NTLogEvent class.

Note that the property Type is a string and contains the type in the local language, while EventType is an integer with a fixed meaning like

1 = Error

2 = Warning

3 = Information

4 = Security Audit Success

5 = Security Audit Failure

Body:
I am reading logs from EventViewer using below lines of code.

var searcher = new ManagementObjectSearcher(@"\\WS2012-DE01\root\cimv2",
               "SELECT * FROM Win32_NTLogEvent WHERE  Type ='Error'");

above code works fine in en-US culture, but will fail in other culture because other culture will be representing Error as some other word.

eg: Error word in de-DE culture(german) represents as Fehler. I will be using the same code in different environement. I do not want to maintain a resource file since issue is with only one word or not need a Translator API because of security measures to solve this. Could anyone please provide me a solution.

Body:
Don't query filtering by the name of the event type, but filtering by the internal type id:

var searcher = new ManagementObjectSearcher(@"\\WS2012-DE01\root\cimv2",
               "SELECT * FROM Win32_NTLogEvent WHERE EventType=1");

You can see the list of possible values for EventType in the documentation of the WMI Win32_NTLogEvent class.

Note that the property Type is a string and contains the type in the local language, while EventType is an integer with a fixed meaning like

1 = Error

2 = Warning

3 = Information

4 = Security Audit Success

5 = Security Audit Failure


问:
Using Mobile Atlas Creator to create offline map
I am trying to create offline map for my Android application. I use Mobile Atlas Creator. I followed all instructions in the read me file and here. But when I run mobile atlas creator.exe on my Windows, I don't see map in the pane. I choose the map source to OpenStreetMap Mapnik. I prepare the map compatible for Osmdroid ZIP. What could be the problem?
Thanks

答:
MOBAC Version 2.0.0 beta 3 (2350) works again. You can get it here: https://sourceforge.net/projects/mobac/

For me a simple way to download OSM-based tiles. Few tile sources but a lot of export formats.


问:
Stop timesyncd from polling hard coded Debian timeservers
The systemd-timesyncd daemon repeatedly tries to contact the following hard coded (compiled) time servers if neither an NTP server is specified manually nor one received via DHCP:

```<code>0.debian.pool.ntp.org
1.debian.pool.ntp.org
2.debian.pool.ntp.org
3.debian.pool.ntp.org
</code>```

Since I'm operating behind a corporate proxy, it will never be successful to reach these servers. Is there a way to prevent this senseless polling (without recompilation)?

答:
If you aren't allowed to contact any NTP servers to sync with, then disable the the service that does that:

```<code> systemctl stop systemd-timesyncd
 systemctl disable systemd-timesyncd
</code>```

The first command will stop the service immediately. The second will prevent it from being restarted on the next boot.

Body:
The systemd-timesyncd daemon repeatedly tries to contact the following hard coded (compiled) time servers if neither an NTP server is specified manually nor one received via DHCP:

0.debian.pool.ntp.org
1.debian.pool.ntp.org
2.debian.pool.ntp.org
3.debian.pool.ntp.org

Since I'm operating behind a corporate proxy, it will never be successful to reach these servers. Is there a way to prevent this senseless polling (without recompilation)?

Body:
If you aren't allowed to contact any NTP servers to sync with, then disable the the service that does that:

 systemctl stop systemd-timesyncd
 systemctl disable systemd-timesyncd

The first command will stop the service immediately. The second will prevent it from being restarted on the next boot.


问:
Select data from only one table using match with another
I want to display all fields in T1 based on a criterial match in T2, but I don't want to display anything from T2.

So when I query

```<code>SELECT * FROM Personal
WHERE Personal.P_ID=Exam.P_ID
AND Exam.Level='B2'
AND Exam.Certification='Full'
</code>```

I get an error (#1054 - Unknown column 'exam.Level' in 'where clause'), because I don't include the T2 (Exam) in Line 1.

But when I query

```<code>SELECT * FROM Personal, Exam
WHERE Personal.P_ID=Exam.P_ID
AND Exam.Level='B2'
AND Exam.Certification='Full'
</code>```

I get all the Exam table data returned as well.

How do I just return all the T1 (Personal) data?

I checked for previous questions and found this: Select data (join?) from only one table using an id from another table , but the answers still return the unwanted T2 data.

For example,

```<code>SELECT * FROM Personal
JOIN Exam on Personal.P_ID = Exam.P_ID
AND Exam.Level='B2'
AND Exam.Certification='Full'
</code>```

答:
First of all, don't use comma separated tables in your where clause; that's what join is for (more on this here)

To solve your problem you should change what's in your select

```<code>SELECT  Personal.*
FROM    Personal
JOIN    Exam
ON      Personal.P_ID=Exam.P_ID
WHERE   Exam.Level='B2'
AND Exam.Certification='Full'
</code>```

This will show all Personal columns, but you can of course select only some columns with

```<code>SELECT  Personal.column1, Personal.column2
</code>```

Body:
I want to display all fields in T1 based on a criterial match in T2, but I don't want to display anything from T2.

So when I query

SELECT * FROM Personal
WHERE Personal.P_ID=Exam.P_ID
AND Exam.Level='B2'
AND Exam.Certification='Full'

I get an error (#1054 - Unknown column 'exam.Level' in 'where clause'), because I don't include the T2 (Exam) in Line 1.

But when I query

SELECT * FROM Personal, Exam
WHERE Personal.P_ID=Exam.P_ID
AND Exam.Level='B2'
AND Exam.Certification='Full'

I get all the Exam table data returned as well.

How do I just return all the T1 (Personal) data?

I checked for previous questions and found this: Select data (join?) from only one table using an id from another table , but the answers still return the unwanted T2 data.

For example,

SELECT * FROM Personal
JOIN Exam on Personal.P_ID = Exam.P_ID
AND Exam.Level='B2'
AND Exam.Certification='Full'

Body:
First of all, don't use comma separated tables in your where clause; that's what join is for (more on this here)

To solve your problem you should change what's in your select

SELECT  Personal.*
FROM    Personal
JOIN    Exam
ON      Personal.P_ID=Exam.P_ID
WHERE   Exam.Level='B2'
AND Exam.Certification='Full'

This will show all Personal columns, but you can of course select only some columns with

SELECT  Personal.column1, Personal.column2


问:
Cannot retrieve Apache environment variables in PHP

Background

I have an Apache/2.2.15 (Win32) with PHP/5.3.2 set up, handling authentication.

```<code><Directory /usr/www/myhost/private>
  # core authentication and mod_auth_basic configuration
  # for mod_authn_dbd
  AuthType Basic
  AuthName "My Server"
  AuthBasicProvider dbd

  # core authorization configuration
  Require valid-user

  # mod_authn_dbd SQL query to authenticate a user
  AuthDBDUserPWQuery "SELECT Password,UserName,Realm,Access FROM authn WHERE user = %s"
</Directory>
</code>```

The authentication works fine! No problems.

But regarding to the documentation, any extra field returned back from the AuthDBDUserPWQuery will be put into an AUTHENTICATION_fieldname variable in the Environment.

With phpinfo(), I can see these variables with he correct values under "Apache Environment".

AUTHENTICATE_USERNAME

AUTHENTICATE_REALM

AUTHENTICATE_ACCESS

Problem

I can't fetch those environment variables from my php.

```<code>1 <?php
2   $Access = apache_getenv('AUTHENTICATE_ACCESS',true);
3   var_dump($Access);
4 ?>
</code>```

Line 3 prints bool(false) indicating that the variable wasn't found!

However if I  change to another Apache Environment variable such as 'HTTP_HOST' it works.

..and yes, I have tried getenv() also, same result.

There is also a note that the Apache server needs to be compiled with APR 1.3.0 to work. I used the Apache msi build from httpd.apache.org and it seems to be compiled with APR above version 2. Since I can see them with phpinfo() they must be accessible from PHP.

答:
I have used this mod_rewrite rule in an .htaccess file to make the HTTP Authorization header environment variable available in $_SERVER['HTTP_AUTHORIZATION']. I'm sure this could be adapted for your purposes. Not sure if it's the best solution, but it's a solution:

```<code>RewriteRule .* - [env=HTTP_AUTHORIZATION:%{HTTP:Authorization},last]
</code>```

Body:
Background

I have an Apache/2.2.15 (Win32) with PHP/5.3.2 set up, handling authentication.

<Directory /usr/www/myhost/private>
  # core authentication and mod_auth_basic configuration
  # for mod_authn_dbd
  AuthType Basic
  AuthName "My Server"
  AuthBasicProvider dbd

  # core authorization configuration
  Require valid-user

  # mod_authn_dbd SQL query to authenticate a user
  AuthDBDUserPWQuery "SELECT Password,UserName,Realm,Access FROM authn WHERE user = %s"
</Directory>

The authentication works fine! No problems.

But regarding to the documentation, any extra field returned back from the AuthDBDUserPWQuery will be put into an AUTHENTICATION_fieldname variable in the Environment.

With phpinfo(), I can see these variables with he correct values under "Apache Environment".

AUTHENTICATE_USERNAME

AUTHENTICATE_REALM

AUTHENTICATE_ACCESS

Problem

I can't fetch those environment variables from my php.

1 <?php
2   $Access = apache_getenv('AUTHENTICATE_ACCESS',true);
3   var_dump($Access);
4 ?>

Line 3 prints bool(false) indicating that the variable wasn't found!

However if I  change to another Apache Environment variable such as 'HTTP_HOST' it works.

..and yes, I have tried getenv() also, same result.

There is also a note that the Apache server needs to be compiled with APR 1.3.0 to work. I used the Apache msi build from httpd.apache.org and it seems to be compiled with APR above version 2. Since I can see them with phpinfo() they must be accessible from PHP.

Body:
I have used this mod_rewrite rule in an .htaccess file to make the HTTP Authorization header environment variable available in $_SERVER['HTTP_AUTHORIZATION']. I'm sure this could be adapted for your purposes. Not sure if it's the best solution, but it's a solution:

RewriteRule .* - [env=HTTP_AUTHORIZATION:%{HTTP:Authorization},last]


问:
After installing Visual Studio 2017, I'm unable to debug smart device project in Visual Studio 2008
I recently installed Visual Studio 2017, just shortly after it was released (March 2017).

When I go to debug my smart device project in VS 2008 I get a error message dialog that just says "The operation could not be completed". , .

Here is a list of what I've observed:

The project output successfully deploys

no error message is displayed in the output window in Visual Studio

when I go to Debug=>Attach to Process and open the Transport drop down, it doesn't contain Smart Device like it usually does.

ProcMon shows that devenv is maintaining a open connection to the device on port 5355

What I've tried:

I tried debugging on multiple emulator types and devices that I know have worked in the past.

I tried creating an new solution with the default smart device project.

I tried deleting all the files in %localappdata%/Microsoft/CoreCon/1.0

答:
From Developer Community: The cause is an error in the registration of the type library for this component.

To fix this issue, you can either:

Open a command prompt with administrator privileges and execute the following command:

```<code>reg add HKEY_CLASSES_ROOT\TypeLib{6A1A7D39-8449-4287-8EF0-CE256582C940}\8.0\0\win32 /t REG_SZ /d "C:\Program Files (x86)\Common Files\Microsoft Shared\VS7Debug\coloader80.tlb"
</code>```

Alternatively you can execute:

```<code>regsvr32 "C:\Program Files (x86)\Common Files\Microsoft Shared\VS7Debug\coloader80.dll"
</code>```

The correct registration will be included in future versions of Visual Studio.

Body:
From Developer Community: The cause is an error in the registration of the type library for this component.

To fix this issue, you can either:

Open a command prompt with administrator privileges and execute the following command:

reg add HKEY_CLASSES_ROOT\TypeLib{6A1A7D39-8449-4287-8EF0-CE256582C940}\8.0\0\win32 /t REG_SZ /d "C:\Program Files (x86)\Common Files\Microsoft Shared\VS7Debug\coloader80.tlb"

Alternatively you can execute:

regsvr32 "C:\Program Files (x86)\Common Files\Microsoft Shared\VS7Debug\coloader80.dll"

The correct registration will be included in future versions of Visual Studio.


问:
How to convert a string containing escape characters to a string
I have a string that is returned to me which contains escape characters.

Here is a sample string

"test\40gmail.com"

As you can see it contains escape characters. I need it to be converted to its real value which is

"test@gmail.com"

How can I do this?

答:
I just wrote this piece of code and it seems to work beautifully...  It requires that the escape sequence is in HEX, and is valid for value's 0x00 to 0xFF.

```<code>// Example
str = remEscChars(@"Test\x0D") // str = "Test\r"
</code>```

Here is the code.

```<code>private string remEscChars(string str)
{
   int pos = 0;
   string subStr = null;
   string escStr = null;

   try
   {
      while ((pos = str.IndexOf(@"\x")) >= 0)
      {
         subStr = str.Substring(pos + 2, 2);
         escStr = Convert.ToString(Convert.ToChar(Convert.ToInt32(subStr, 16)));
         str = str.Replace(@"\x" + subStr, escStr);
      }
   }
   catch (Exception ex)
   {
      throw ex;
   }

   return str;
}
</code>```

Body:
I just wrote this piece of code and it seems to work beautifully...  It requires that the escape sequence is in HEX, and is valid for value's 0x00 to 0xFF.

// Example
str = remEscChars(@"Test\x0D") // str = "Test\r"

Here is the code.

private string remEscChars(string str)
{
   int pos = 0;
   string subStr = null;
   string escStr = null;

   try
   {
      while ((pos = str.IndexOf(@"\x")) >= 0)
      {
         subStr = str.Substring(pos + 2, 2);
         escStr = Convert.ToString(Convert.ToChar(Convert.ToInt32(subStr, 16)));
         str = str.Replace(@"\x" + subStr, escStr);
      }
   }
   catch (Exception ex)
   {
      throw ex;
   }

   return str;
}


问:
Extract only a single directory from tar (in python)
I am working on a project in python in which I need to extract only a subfolder of tar archive not all the files.
I tried to use

```<code>tar = tarfile.open(tarfile)
tar.extract("dirname", targetdir)
</code>```

But this does not work, it does not extract the given subdirectory also no exception is thrown. I am a beginner in python.
Also if the above function doesn't work for directories whats the difference between this command and tar.extractfile() ?

答:
The other answer will retain the subfolder path, meaning that subfolder/a/b will be extracted to ./subfolder/a/b. To extract a subfolder to the root, so subfolder/a/b would be extracted to ./a/b, you can rewrite the paths with something like this:

```<code>def members(tf):
    l = len("subfolder/")
    for member in tf.getmembers():
        if member.path.startswith("subfolder/"):
            member.path = member.path[l:]
            yield member

with tarfile.open("sample.tar") as tar:
    tar.extractall(members=members(tar))
</code>```

Body:
I am working on a project in python in which I need to extract only a subfolder of tar archive not all the files.
I tried to use

tar = tarfile.open(tarfile)
tar.extract("dirname", targetdir)

But this does not work, it does not extract the given subdirectory also no exception is thrown. I am a beginner in python.
Also if the above function doesn't work for directories whats the difference between this command and tar.extractfile() ?

Body:
The other answer will retain the subfolder path, meaning that subfolder/a/b will be extracted to ./subfolder/a/b. To extract a subfolder to the root, so subfolder/a/b would be extracted to ./a/b, you can rewrite the paths with something like this:

def members(tf):
    l = len("subfolder/")
    for member in tf.getmembers():
        if member.path.startswith("subfolder/"):
            member.path = member.path[l:]
            yield member

with tarfile.open("sample.tar") as tar:
    tar.extractall(members=members(tar))


问:
React Native: vertical centering when using ScrollView
I'm using React Native and I'm having trouble retaining vertical centering of elements as soon as I introduce a ScrollView.  To demonstrate, I created 3 apps with React Native Playground.  All examples have 2 pages, and they can be toggled by tapping the blue button.

Example 1:

This first example shows blocks centered vertically on page 2.  This happens because the container has these styles applied to it:

```<code>flex: 1,
flexDirection: 'column',
justifyContent: 'center',
</code>```

https://rnplay.org/apps/lb5wSQ

However, there's a problem as soon as you switch to page 2, because the entire content of the page doesn't fit, so we need a ScrollView.

Example 2

In this example, I wrap everything inside of a ScrollView.  This allows page 2 to scroll, but now I lost the vertical centering of Page 1.

https://rnplay.org/apps/DCgOgA

Example 3

In order to try and get back the vertical centering of Page 1, I apply flex: 1 to the contentContainerStyle of ScrollView.  This fixes the vertical centering on page 1, but I'm no longer able to scroll all the way down to the bottom on page 2.

https://rnplay.org/apps/LSgbog

How can I fix this so that I get vertical centering of elements on page 1 yet still get ScrollView to scroll all the way to the bottom on page 2?

答: There's a new solution (unfortunately iOS only at the moment) - we can use centerContent prop on Scrollview.

Body:
I'm using React Native and I'm having trouble retaining vertical centering of elements as soon as I introduce a ScrollView.  To demonstrate, I created 3 apps with React Native Playground.  All examples have 2 pages, and they can be toggled by tapping the blue button.

Example 1:

This first example shows blocks centered vertically on page 2.  This happens because the container has these styles applied to it:

flex: 1,
flexDirection: 'column',
justifyContent: 'center',

https://rnplay.org/apps/lb5wSQ

However, there's a problem as soon as you switch to page 2, because the entire content of the page doesn't fit, so we need a ScrollView.

Example 2

In this example, I wrap everything inside of a ScrollView.  This allows page 2 to scroll, but now I lost the vertical centering of Page 1.

https://rnplay.org/apps/DCgOgA

Example 3

In order to try and get back the vertical centering of Page 1, I apply flex: 1 to the contentContainerStyle of ScrollView.  This fixes the vertical centering on page 1, but I'm no longer able to scroll all the way down to the bottom on page 2.

https://rnplay.org/apps/LSgbog

How can I fix this so that I get vertical centering of elements on page 1 yet still get ScrollView to scroll all the way to the bottom on page 2?


问:
Universal certificate works for production but not development
I generated a universal push certificate ("Apple Push Notification service SSL (Sandbox & Production)"), which works correctly on production (enterprise distribution).

However, when I use it with a development app (when I install it from Xcode) it doesn't work, and I get the error "The credentials supplied to the package were not recognized" (a PushSharp error).

My old development-only certificate does work.

Any ideas?

答:
When you take build from Xcode, it will treat the app as development build and will use only the development certificates for app and APNS.

If you want to test the production APNS certficate you need to take an Adhoc build.


问:
Empty MSI property after adding value
Is there any special handling required when setting a property through a CustomAction provided by a merge module? I have two custom actions providing three properties to be used later within the merge module. They are set by usual C# code:

```<code>session["APPSRVPORT"] = port.ToString();
</code>```

MSI log reports that the property has been set to a value:

```<code>MSI (s) (C0!DC) [11:58:04:615]: PROPERTY CHANGE: Adding APPSRVPORT property. Its value is '11376'.
</code>```

When it comes to install the components, the following statement is used to install a registry value which uses the MSI property filled above:

```<code><RegistryValue Name="AppSrvPort" Value="[APPSRVPORT]" Type="string" />
</code>```

However, the log shows that the value is empty at this point:

```<code>MSI (s) (C0:AC) [11:58:06:208]: Executing op: RegAddValue(Name=AppSrvPort,,)
</code>```

Can anybody tell me how to fix this? I've already checked, that the execute sequence is valid (i.e. setting the property comes before action "WriteRegistryValues")

Thanks in advance!

答:
When you reference a property in a .wxs script of a merge module, it will be modularized (i.e. having the merge module GUID appended). So the <RegistryValue> element will actually be interpreted like this:

```<code><RegistryValue Name="AppSrvPort" Value="[APPSRVPORT.YOUR_MERGE_MODULE_ID]" Type="string" />
</code>```

YOUR_MERGE_MODULE_ID will be the GUID of the merge module having - replaced by _, e. g. 1E35CFEB_7FA9_49F2_8E0D_5D941720EE81.

To fix the issue, you could either append the merge module ID when writing the property or suppress modularization.

Since you are using the property only within the merge module, I'd suggest the former to avoid accidentally overwriting any existing property of the main MSI that has the same name. Think of the merge module ID as the "namespace":

```<code>session["APPSRVPORT.YOUR_MERGE_MODULE_ID"] = port.ToString();
</code>```

Suppressing modularization can be useful if a property is intended to be shared between the main MSI and the merge module:

```<code><Property Id="APPSRVPORT" SuppressModularization="yes"/>
</code>```

Note: Suppressing modularization will issue warnings CNDL1006 and CNDL1086 which can be ignored, if you know what you are doing. ;-)

Title: Empty MSI property after adding value

Body:
Is there any special handling required when setting a property through a CustomAction provided by a merge module? I have two custom actions providing three properties to be used later within the merge module. They are set by usual C# code:

session["APPSRVPORT"] = port.ToString();

MSI log reports that the property has been set to a value:

MSI (s) (C0!DC) [11:58:04:615]: PROPERTY CHANGE: Adding APPSRVPORT property. Its value is '11376'.

When it comes to install the components, the following statement is used to install a registry value which uses the MSI property filled above:

<RegistryValue Name="AppSrvPort" Value="[APPSRVPORT]" Type="string" />

However, the log shows that the value is empty at this point:

MSI (s) (C0:AC) [11:58:06:208]: Executing op: RegAddValue(Name=AppSrvPort,,)

Can anybody tell me how to fix this? I've already checked, that the execute sequence is valid (i.e. setting the property comes before action "WriteRegistryValues")

Thanks in advance!

Body:
When you reference a property in a .wxs script of a merge module, it will be modularized (i.e. having the merge module GUID appended). So the <RegistryValue> element will actually be interpreted like this:

<RegistryValue Name="AppSrvPort" Value="[APPSRVPORT.YOUR_MERGE_MODULE_ID]" Type="string" />

YOUR_MERGE_MODULE_ID will be the GUID of the merge module having - replaced by _, e. g. 1E35CFEB_7FA9_49F2_8E0D_5D941720EE81.

To fix the issue, you could either append the merge module ID when writing the property or suppress modularization.

Since you are using the property only within the merge module, I'd suggest the former to avoid accidentally overwriting any existing property of the main MSI that has the same name. Think of the merge module ID as the "namespace":

session["APPSRVPORT.YOUR_MERGE_MODULE_ID"] = port.ToString();

Suppressing modularization can be useful if a property is intended to be shared between the main MSI and the merge module:

<Property Id="APPSRVPORT" SuppressModularization="yes"/>

Note: Suppressing modularization will issue warnings CNDL1006 and CNDL1086 which can be ignored, if you know what you are doing. ;-)


问:
Most efficient way to check if object value exists in PHP 7
I have the following object in PHP 7:

```<code>(int) 0 => object() {
   'master' => null
},
(int) 1 => object() {
   'master' => true
},
(int) 2 => object() {
   'master' => null
},
</code>```

What is the most efficient way to check whether master is true in any key of that object?

I could loop through the object and then set a variable, e.g.

```<code>$master = 0;
foreach ($obj as $key => $value) {
    if ($value->master) {
       $master++;
    }
}
if ($master !== 0) {

}
</code>```

But this seems inefficient.

The object itself has other data in each node, this is a simplified example.

What I'm trying to write, in as few lines as possible is, does any part of this object have master == true? Or, looking at it the other way round, are all my master nodes set to null on this object? A return of true or false would probably suffice as the output, although a count would also be ok.

答:
Assuming that you don't want to loop through the array, and the key of the "master" array is always "master", then this one-liner should do it:

```<code>$masterCount = count(array_filter(array_column($masterArray,'master')));
</code>```

array_column  is used to fetch all of the values of the "master" column, array_filter  without a closure will automatically filter out empty values (false, null, 0) and count of the new array will get you the amount of true values.

Body:
I have the following object in PHP 7:

(int) 0 => object() {
   'master' => null
},
(int) 1 => object() {
   'master' => true
},
(int) 2 => object() {
   'master' => null
},

What is the most efficient way to check whether master is true in any key of that object?

I could loop through the object and then set a variable, e.g.

$master = 0;
foreach ($obj as $key => $value) {
    if ($value->master) {
       $master++;
    }
}
if ($master !== 0) {

}

But this seems inefficient.

The object itself has other data in each node, this is a simplified example.

What I'm trying to write, in as few lines as possible is, does any part of this object have master == true? Or, looking at it the other way round, are all my master nodes set to null on this object? A return of true or false would probably suffice as the output, although a count would also be ok.

Body:
Assuming that you don't want to loop through the array, and the key of the "master" array is always "master", then this one-liner should do it:

$masterCount = count(array_filter(array_column($masterArray,'master')));

array_column  is used to fetch all of the values of the "master" column, array_filter  without a closure will automatically filter out empty values (false, null, 0) and count of the new array will get you the amount of true values.


问:
In Python, is there a reference to the raiser of an Exception?
I'm writing a method check of a class called Rule which can throw a RuleEnforced exception of which the error message includes a string representation of the Rule which raised it. Here is how it is implemented now:

```<code>class RuleEnforced(Exception):
    def __init__(self, rule, reason):
        message = "The rule {rule} failed for the following reason: {reason}".format(rule=rule, reason=reason)
        super(RuleEnforced, self).__init__(message)

class Rule(object):
    def check(self):
        raise RuleEnforced(rule=self, reason="Why not?")
</code>```

The rule=self argument is always the same, however, and I'm looking for a way to make the code more succinct by using, in the Exception, something like "self.caller.__class__" (in pseudo-code). Is there any way to achieve this?

答:
There is no easier method of getting to the instance that raised the exception.

Raised exceptions include a traceback, the stack of calls that lead to the exception site. You could extract self from that stack (the locals and globals of the stack are preserved), but that is not nearly as readable and easy and clear as just passing in rule=self. See the inspect module overview of internal objects to see what traceback and frame objects support.

If you want to access the caller when constructing the exception (so before raising the exception), you'd have to inspect the current call stack and extract self from the caller. Again, this is not intuitive or readable, and depends on implementation details of the Python interpreter. Passing in the rule explicitly is much clearer and more readable. If you do want to go this route, see the sys._getframe() method and the inspect module support for stack inspection.

In other words, from the Zen of Python: Explicit is better than implicit.

Body:
I'm writing a method check of a class called Rule which can throw a RuleEnforced exception of which the error message includes a string representation of the Rule which raised it. Here is how it is implemented now:

class RuleEnforced(Exception):
    def __init__(self, rule, reason):
        message = "The rule {rule} failed for the following reason: {reason}".format(rule=rule, reason=reason)
        super(RuleEnforced, self).__init__(message)

class Rule(object):
    def check(self):
        raise RuleEnforced(rule=self, reason="Why not?")

The rule=self argument is always the same, however, and I'm looking for a way to make the code more succinct by using, in the Exception, something like "self.caller.__class__" (in pseudo-code). Is there any way to achieve this?


问:
Get all primary keys in a MySQL table using Java
How could I get the names of all primary keys in a MySQL table using Java? Let's say I have a table:

```
Name │ Phone Number │ verified
─────┼──────────────┼─────────
John │ 871-123-1842 │    0
Mark │ 912-917-8172 │    1
Matt │ 182-134-9917 │    1
Jake │ 971-991-8264 │    1
```

I would like to get the values John, Mark, Matt, and Jake from the table.

I know there could be an alternative of just having a list of all of all of the primary keys, and adding to it whenever a new one is added, just I'm looking for something simpler, that will take up less space. I'm looking for something like:

```<code>PreparedStatement query = mySqlConnection.prepareStatement("SELECT * FROM `table`");
ResultSet results = query.executeQuery();
List<Object> results = results.getPrimaryKeyValues(); //I don't know what to put here
</code>```

So, how could I achieve getting an Array, or something that I can turn into an Array, of all of the primary keys inside of a MySQL table using Java?

答:
```<code> DatabaseMetaData databaseMetaData = conn.getMetaData();

 ResultSet resultSet = databaseMetaData.getPrimaryKeys(null, null ,  tablename);

while (resultSet.next()) {
                String primarykeys= resultSet.getString(4);
                System.out.println(primarykeys);
            }
</code>```

Body:
How could I get the names of all primary keys in a MySQL table using Java? Let's say I have a table:

Name │ Phone Number │ verified
─────┼──────────────┼─────────
John │ 871-123-1842 │    0
Mark │ 912-917-8172 │    1
Matt │ 182-134-9917 │    1
Jake │ 971-991-8264 │    1

I would like to get the values John, Mark, Matt, and Jake from the table.

I know there could be an alternative of just having a list of all of all of the primary keys, and adding to it whenever a new one is added, just I'm looking for something simpler, that will take up less space. I'm looking for something like:

PreparedStatement query = mySqlConnection.prepareStatement("SELECT * FROM `table`");
ResultSet results = query.executeQuery();
List<Object> results = results.getPrimaryKeyValues(); //I don't know what to put here

So, how could I achieve getting an Array, or something that I can turn into an Array, of all of the primary keys inside of a MySQL table using Java?


问:
Efficiently rendering many images on a unified canvas
I'm lost and in need of direction.

We're trying to render a bunch of small images (X) onto a single, unified canvas using imagemagick.

The different X's can be one of five different sizes: 20x20, 40x40, 60x60, 80x80 or 100x100 each. The large image's width is always set to 600, but the height can be regulated as needed.

We can be using as few as 10 or as many as 10,000 X's at any given moment.

Currently, the bare-bones proof of concept we're working with goes something like:

```<code>images.each do |image|

      image = Magick::Image.read("#{RAILS_ROOT}/public/images/#{image}").first

      w = image.columns
      h = image.rows

      pixels = image.export_pixels(0, 0, w, h, "RGB")

      img.import_pixels(x, y, w, h, "RGB", pixels)

      x += w

end
</code>```

...it's simple and stupid, but it does output a series of images merged into one. Almost there  ;-)

Does anyone know of an effective algorithm with which we can iterate many X's and place them side-by-side, spanning multiple lines and still optimizing the space? The goal here is to create a single image without white space, constructed by all small images.

As stated, I would love any feedback you guys might have on this. Pointers? Ideas? Examples?

Thanks.

答:
It seems like right now the images are noise. You want to solve a tiles problem. The tiles have some fixed size and you want to put them on a surface of a fixed width and minimum height. This can be done globally with DFS, BFS, A*, etc. You can also look at some local method like simulated annealing or hill climbing, depending if you need to global optimum or just a good, reasonable solution. You can find implementations of these methods in the online source repository for AIMA.

Once you have solved the tile problem you can overlay the images, with as piece of code similar to the one you're showing.

Body:
I'm lost and in need of direction.

We're trying to render a bunch of small images (X) onto a single, unified canvas using imagemagick.

The different X's can be one of five different sizes: 20x20, 40x40, 60x60, 80x80 or 100x100 each. The large image's width is always set to 600, but the height can be regulated as needed.

We can be using as few as 10 or as many as 10,000 X's at any given moment.

Currently, the bare-bones proof of concept we're working with goes something like:

images.each do |image|

      image = Magick::Image.read("#{RAILS_ROOT}/public/images/#{image}").first

      w = image.columns
      h = image.rows

      pixels = image.export_pixels(0, 0, w, h, "RGB")

      img.import_pixels(x, y, w, h, "RGB", pixels)

      x += w

end

...it's simple and stupid, but it does output a series of images merged into one. Almost there  ;-)

Does anyone know of an effective algorithm with which we can iterate many X's and place them side-by-side, spanning multiple lines and still optimizing the space? The goal here is to create a single image without white space, constructed by all small images.

As stated, I would love any feedback you guys might have on this. Pointers? Ideas? Examples?

Thanks.


问:
WebStorm 2017.1: TypeScript: import can be shortened inspection issue
Inspection is raising this issue... according to this WebStorm blog post, I tried to update it but it's raising the same issue for these imports:

server.ts

```<code>....
// models
import { IModel } from './models/model'; //import IModel
import { IUserModel } from './models/user'; //import IUserModel
</code>```

models/model.ts

```<code>import { Model } from "mongoose";
import { IUserModel } from "./user";
export interface IModel {
  user: Model<IUserModel>;
}
</code>```

models/user.ts

```<code>import { Document } from "mongoose";
import { IUser } from "../interfaces/user";
export interface IUserModel extends IUser, Document {
  //custom methods for user model would be defined here
}
</code>```

details for update are given in this post

```<code>dir/toExport.ts
    export class Foo {}
dir/index.ts
    export {Foo} from './toExport'
client.ts
    import {Foo} from './dir/toExport' //inspection warining

**after fix**
client.ts
    import {Foo} from './dir'
</code>```

but it does not work as it should do ...

UPDATE

WebStorm Code Style preferences for TypeScript

答:
Unfortunately there are a lot of people which don't want to import directories with index.ts by default (it was the default behaviour several EAPs but we had to disable it).

You can enable this behaviour in

"File | Settings | Editor | Code Style | TypeScript | Imports" -> "Use
  directory import"

Body:
Inspection is raising this issue... according to this WebStorm blog post, I tried to update it but it's raising the same issue for these imports:

server.ts

....
// models
import { IModel } from './models/model'; //import IModel
import { IUserModel } from './models/user'; //import IUserModel

models/model.ts

import { Model } from "mongoose";
import { IUserModel } from "./user";
export interface IModel {
  user: Model<IUserModel>;
}

models/user.ts

import { Document } from "mongoose";
import { IUser } from "../interfaces/user";
export interface IUserModel extends IUser, Document {
  //custom methods for user model would be defined here
}

details for update are given in this post

dir/toExport.ts
    export class Foo {}
dir/index.ts
    export {Foo} from './toExport'
client.ts
    import {Foo} from './dir/toExport' //inspection warining

**after fix**
client.ts
    import {Foo} from './dir'

but it does not work as it should do ...

UPDATE

WebStorm Code Style preferences for TypeScript


问:
How to access JIRA Software files in a docker image?
I deployed Jira in a Docker container.
docker run --detach --publish 8080:8080 cptactionhank/atlassian-jira-software:latest

I am accessing the files using:
docker exec -t -i containerid /bin/bash

But I am not able to see the files which are needed to edit.
Supposedly for creating a maintenance splash page.
Ref : https://confluence.atlassian.com/confkb/how-to-create-a-maintenance-splash-page-290751207.html

答:
According to the documents that you sent and location of the installation directory that you mentioned, you need to edit /opt/atlassian/jira/conf/server.xml file to edit the context section. Then edit /opt/atlassian/jira/conf/web.xml file to adding new error page.

Please note that you have to access those files via bin/bash from docker:

```<code>sudo docker exec -i -t  --user root containerid /bin/bash
</code>```

Also this has a good information as well.

Body:
According to the documents that you sent and location of the installation directory that you mentioned, you need to edit /opt/atlassian/jira/conf/server.xml file to edit the context section. Then edit /opt/atlassian/jira/conf/web.xml file to adding new error page.

Please note that you have to access those files via bin/bash from docker:

sudo docker exec -i -t  --user root containerid /bin/bash

Also this has a good information as well.


问:
IE Bootstrap fonts (icons) not loaded
Internet Explorer 11 has problems showing the icons of bootstrap.
With Opera, Firefox and Chrome it works perfectly, and it also works with Edge but the icons are not shown with IE in Edge mode or (10,9,8).
Before I changed the website to https it worked all fine. I have this problem after changing it to ssl.

Does anyone know what I can do in order to solve this problem (at Server - Microsoft Azure or at load balancer)?

With IE (icons are not shown):

With Firefox:

答:
Spring-Boot is generating cache-invalidating headers in HTTP responses:

```<code>Cache-Control :"no-cache, no-store, max-age=0, must-revalidate"
</code>```

and

```<code>pragma: "no-cache"
</code>```

The solution is to hide those  headers to the browser.

I used nginx as a proxy, adding the folowing commands the https proxied location:

```<code>  proxy_hide_header Cache-Control;
  proxy_hide_header Pragma;
</code>```

See here for details with nginx.

Using apache httpd, the syntax is here

Title: IE Bootstrap fonts (icons) not loaded

Body:
Spring-Boot is generating cache-invalidating headers in HTTP responses:

Cache-Control :"no-cache, no-store, max-age=0, must-revalidate"

and

pragma: "no-cache"

The solution is to hide those  headers to the browser.

I used nginx as a proxy, adding the folowing commands the https proxied location:

  proxy_hide_header Cache-Control;
  proxy_hide_header Pragma;

See here for details with nginx.

Using apache httpd, the syntax is here


问:
How to let user upload multiple images without pre-defining the number of HTML upload input box?
I'm looking for a way to have user upload as many images as they want (perhaps via drag and drop) or dynamically adding more upload box.

I thought statically fixing (say 6) HTML upload input box is slightly limiting and the user have to click "Browse" button (6 times in this example) and navigating to the folder to pick the file.

What is the best practice to achieve this so users find it easy to use? Perhaps with some AJAX magic?

I also wouldn't mind having the user click "Upload more" to reveal (say 6 more) HTML upload input box. Was wondering if there is a better way!

Thank you.

答:
You've already hit the best answer — dynamically add more file inputs to the page as they are needed.

HTML file inputs will not let you select more than one file at a time.  Nor can you do "drag and drop" from a graphical file browser (if that's what you meant).

But you can add (or reveal) more of them dynamically.  You don't need "AJAX" to do this, just Javascript.

If you have your original input like so

```<code><div id="container">
    <input type="file"/>
</div>
</code>```

You can add another one with a script like this:

```<code>var container = document.getElementById("container");
var newFile = document.createElement("input");
newFile.type = "file";
container.appendChild( newFile );
</code>```

To deal with the files on the server, you'll need to look at Request.Files.  They will be listed in the collection in the physical order in which they were added.

Body:
You've already hit the best answer — dynamically add more file inputs to the page as they are needed.

HTML file inputs will not let you select more than one file at a time.  Nor can you do "drag and drop" from a graphical file browser (if that's what you meant).

But you can add (or reveal) more of them dynamically.  You don't need "AJAX" to do this, just Javascript.

If you have your original input like so

<div id="container">
    <input type="file"/>
</div>

You can add another one with a script like this:

var container = document.getElementById("container");
var newFile = document.createElement("input");
newFile.type = "file";
container.appendChild( newFile );

To deal with the files on the server, you'll need to look at Request.Files.  They will be listed in the collection in the physical order in which they were added.


问:
Chained UIView animation with each contain completion block within a loop
I want to do several animations in series within a loop. Each animation does "UI animation" first followed by "completion block". My question is how to add several such animations in series within a loop so that the executing sequence follows:  conditon->"UI animation 1" -> "completion block 1" -> condition-> "UI animation 2" -> "completion block 2" ->...-> condition->"UI animation n" -> "completion block n".

```<code> while(condition){
    [UIView animateWithDuration:0.3 animations:^{
        //UI animation
        CGRect frame = sourceView.frame;
        frame.origin = destPosition;
        view.frame = frame;
    } completion:^(BOOL finished) {
        //completion block
        self.currentBoard = destBoard;
    }];
 }
</code>```

sorry, I may not present my question clearly. I have updated my question as above, a while loop is added. The issue is that I find next condition test is executed before the completion block of previous animation

答:
You need to start UI Animation N in the completion block N-1.</p>

```<code>[UIView animateWithDuration:0.3 animations:^{
  // UI Animation 1
} completion:^(BOOL finished) {
  // Handle the completion of UI Animation 1

  // Start the next animation
  [UIView animateWithDuration:0.3 animations:^{
    // UI Animation 2
  } completion:^(BOOL finished) {
    // Completion block of animation 2
  }
}
</code>```

Body:
I want to do several animations in series within a loop. Each animation does "UI animation" first followed by "completion block". My question is how to add several such animations in series within a loop so that the executing sequence follows:  conditon->"UI animation 1" -> "completion block 1" -> condition-> "UI animation 2" -> "completion block 2" ->...-> condition->"UI animation n" -> "completion block n".

 while(condition){
    [UIView animateWithDuration:0.3 animations:^{
        //UI animation
        CGRect frame = sourceView.frame;
        frame.origin = destPosition;
        view.frame = frame;
    } completion:^(BOOL finished) {
        //completion block
        self.currentBoard = destBoard;
    }];
 }

sorry, I may not present my question clearly. I have updated my question as above, a while loop is added. The issue is that I find next condition test is executed before the completion block of previous animation

Body:
You need to start UI Animation N in the completion block N-1.

[UIView animateWithDuration:0.3 animations:^{
  // UI Animation 1
} completion:^(BOOL finished) {
  // Handle the completion of UI Animation 1

  // Start the next animation
  [UIView animateWithDuration:0.3 animations:^{
    // UI Animation 2
  } completion:^(BOOL finished) {
    // Completion block of animation 2
  }
}


问:
.NET exe not picking dll dependencies
I have developed an EXE again :)

The problem is it has refernces of SQLite dll file so I included the file on the same path. Now in Windows 8 it is running fine, but in Windows 7 it is not

The error is

System.IO.FileLoadException: Could not load file or assembly 'System.Data.SQLite, Version=1.0.90.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139' or one of its dependencies. The application has failed to start because its side-by-side configuration is incorrect. Please see the application event log or use the command-line sxstrace.exe tool for more detail. (Exception from HRESULT: 0x800736B1)
  File name: 'System.Data.SQLite, Version=1.0.90.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139' ---> System.Runtime.InteropServices.COMException (0x800736B1): The application has failed to start because its side-by-side configuration is incorrect. Please see the application event log or use the command-line sxstrace.exe tool for more detail.

I did everything I could but it is not running on Windows 7

It's a standalone EXE. No Setup.

EDIT:
This is what application event log says

Activation context generation failed for "C:\System.Data.SQLite.dll". Dependent Assembly Microsoft.VC80.CRT,processorArchitecture="x86",publicKeyToken="1fc8b3b9a1e18e3b",type="win32",version="8.0.50727.6195" could not be found. Please use sxstrace.exe for detailed diagnosis.

答:
Generally this error indicates that a dependent assembly is missing.

Activation context generation failed for "C:\System.Data.SQLite.dll".
  Dependent Assembly
  Microsoft.VC80.CRT,processorArchitecture="x86",publicKeyToken="1fc8b3b9a1e18e3b",type="win32",version="8.0.50727.6195"
  could not be found. Please use sxstrace.exe for detailed diagnosis.

This assembly is more commonly known as

Microsoft Visual C++ 2005 Redistributable Package (x86)

and can be downloaded from here.

But, often there is another cause. Today, for us, it was "Bit9 Security" which did not like us digitally signing the SQLite.dll assembly on our local machine and uploading the signed assembly to our server application folder with a different time stamp to the rest of the assemblies in the application folder.

The work around was to recompile the application, sign all the assemblies, upload and overwrite the existing application files.

Title: .NET exe not picking dll dependencies


问:
How to ensure a string length in Ruby
What is the proper way to ensure a string length in Ruby? The string is multi-byte (UTF8). The strings inputted can be either too short, exactly right, or too long. It would need respectively padding, nothing and slicing.

I can get there in two steps:

```<code>def ensure_length(str, length)
  str.ljust(length).slice(0, length)
end
</code>```

Is there a single method for this? And if it needs in two steps, what order is best: ljust then slice or vice versa, and why?

答:
Is not really better than your version, just an alternative:

```<code>'foo'[0...5].ljust(5)
#=> "foo  "
'foobar'[0...5].ljust(5)
#=> "fooba"
</code>```

Or as a method:

```<code>def ensure_length(str, length)
  str[0...length].ljust(length)
end
</code>```

Title: How to ensure a string length in Ruby

Body:
What is the proper way to ensure a string length in Ruby? The string is multi-byte (UTF8). The strings inputted can be either too short, exactly right, or too long. It would need respectively padding, nothing and slicing.

I can get there in two steps:

def ensure_length(str, length)
  str.ljust(length).slice(0, length)
end

Is there a single method for this? And if it needs in two steps, what order is best: ljust then slice or vice versa, and why?

Body:
Is not really better than your version, just an alternative:

'foo'[0...5].ljust(5)
#=> "foo  "
'foobar'[0...5].ljust(5)
#=> "fooba"

Or as a method:

def ensure_length(str, length)
  str[0...length].ljust(length)
end