问:
Spring Boot Swagger 2 Configuration Error creating bean with name 'documentationPluginsBootstrapper'
I have problems with configuration of Swagger in my Spring Boot project.
I was following the basic instruction for this, and somehow it doesn's work.

Here it is:
pom.xml

```<code> <!--SWAGGER-->
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.4.0</version>
    </dependency>

    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.4.0</version>
    </dependency>
</code>```

Java Swagger Config:

```<code>@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
    return new Docket(DocumentationType.SWAGGER_2)
            .select()
            .apis(RequestHandlerSelectors.any())
            .paths(PathSelectors.any())
            .build();
    }
}
</code>```

And i am getting this Exception:

```<code>Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'documentationPluginsBootstrapper' defined in URL [jar:file:/C:/Users/Admin/.m2/repository/io/springfox/springfox-spring-web/2.4.0/springfox-spring-web-2.4.0.jar!/springfox/documentation/spring/web/plugins/DocumentationPluginsBootstrapper.class]: BeanPostProcessor before instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration': Initialization of bean failed; nested exception is java.lang.NoSuchMethodError: org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration.setBeanFactory(Lorg/springframework/beans/factory/BeanFactory;)V
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:471)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200)
at org.springframework.context.event.AbstractApplicationEventMulticaster.getApplicationListeners(AbstractApplicationEventMulticaster.java:165)
at org.springframework.boot.SpringApplication$SpringApplicationEventMulticaster.getApplicationListeners(SpringApplication.java:1007)
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:87)
at org.springframework.boot.SpringApplication.handleError(SpringApplication.java:379)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:367)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:920)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:909)
at configuration.main.Application.main(Application.java:34)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration': Initialization of bean failed; nested exception is java.lang.NoSuchMethodError: org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration.setBeanFactory(Lorg/springframework/beans/factory/BeanFactory;)V
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:547)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:354)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1094)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:989)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200)
at org.springframework.aop.framework.autoproxy.BeanFactoryAdvisorRetrievalHelper.findAdvisorBeans(BeanFactoryAdvisorRetrievalHelper.java:92)
at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.findCandidateAdvisors(AbstractAdvisorAutoProxyCreator.java:101)
at org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator.findCandidateAdvisors(AnnotationAwareAspectJAutoProxyCreator.java:85)
at org.springframework.aop.aspectj.autoproxy.AspectJAwareAdvisorAutoProxyCreator.shouldSkip(AspectJAwareAdvisorAutoProxyCreator.java:103)
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessBeforeInstantiation(AbstractAutoProxyCreator.java:285)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInstantiation(AbstractAutowireCapableBeanFactory.java:958)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.resolveBeforeInstantiation(AbstractAutowireCapableBeanFactory.java:930)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:465)
... 17 more
Caused by: java.lang.NoSuchMethodError: org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration.setBeanFactory(Lorg/springframework/beans/factory/BeanFactory;)V
at org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerByCGLIB$$93593f67.setBeanFactory(<generated>)
at org.springframework.context.annotation.ConfigurationClassPostProcessor$EnhancedConfigurationBeanPostProcessor.postProcessPropertyValues(ConfigurationClassPostProcessor.java:442)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
... 39 more
</code>```

答:
In SpringMVC, if you want to use Swagger2,you need add '@EnableWebMvc' in you config class,like this:</p>

```<code>@Configuration
@EnableSwagger2
@EnableWebMvc
public class Swagger2Config {
   ……
}
</code>```

Body:
I have problems with configuration of Swagger in my Spring Boot project.
I was following the basic instruction for this, and somehow it doesn's work.

Here it is:
pom.xml

    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.4.0</version>
    </dependency>

    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.4.0</version>
    </dependency>

Java Swagger Config:

@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
    return new Docket(DocumentationType.SWAGGER_2)
            .select()
            .apis(RequestHandlerSelectors.any())
            .paths(PathSelectors.any())
            .build();
    }
}

And i am getting this Exception:

Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'documentationPluginsBootstrapper' defined in URL [jar:file:/C:/Users/Admin/.m2/repository/io/springfox/springfox-spring-web/2.4.0/springfox-spring-web-2.4.0.jar!/springfox/documentation/spring/web/plugins/DocumentationPluginsBootstrapper.class]: BeanPostProcessor before instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration': Initialization of bean failed; nested exception is java.lang.NoSuchMethodError: org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration.setBeanFactory(Lorg/springframework/beans/factory/BeanFactory;)V
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:471)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200)
at org.springframework.context.event.AbstractApplicationEventMulticaster.getApplicationListeners(AbstractApplicationEventMulticaster.java:165)
at org.springframework.boot.SpringApplication$SpringApplicationEventMulticaster.getApplicationListeners(SpringApplication.java:1007)
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:87)
at org.springframework.boot.SpringApplication.handleError(SpringApplication.java:379)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:367)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:920)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:909)
at configuration.main.Application.main(Application.java:34)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration': Initialization of bean failed; nested exception is java.lang.NoSuchMethodError: org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration.setBeanFactory(Lorg/springframework/beans/factory/BeanFactory;)V
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:547)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:354)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1094)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:989)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200)
at org.springframework.aop.framework.autoproxy.BeanFactoryAdvisorRetrievalHelper.findAdvisorBeans(BeanFactoryAdvisorRetrievalHelper.java:92)
at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.findCandidateAdvisors(AbstractAdvisorAutoProxyCreator.java:101)
at org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator.findCandidateAdvisors(AnnotationAwareAspectJAutoProxyCreator.java:85)
at org.springframework.aop.aspectj.autoproxy.AspectJAwareAdvisorAutoProxyCreator.shouldSkip(AspectJAwareAdvisorAutoProxyCreator.java:103)
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessBeforeInstantiation(AbstractAutoProxyCreator.java:285)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInstantiation(AbstractAutowireCapableBeanFactory.java:958)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.resolveBeforeInstantiation(AbstractAutowireCapableBeanFactory.java:930)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:465)
... 17 more
Caused by: java.lang.NoSuchMethodError: org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration.setBeanFactory(Lorg/springframework/beans/factory/BeanFactory;)V
at org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerByCGLIB$$93593f67.setBeanFactory(<generated>)
at org.springframework.context.annotation.ConfigurationClassPostProcessor$EnhancedConfigurationBeanPostProcessor.postProcessPropertyValues(ConfigurationClassPostProcessor.java:442)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
... 39 more

Body:
In SpringMVC, if you want to use Swagger2,you need add '@EnableWebMvc' in you config class,like this:

@Configuration
@EnableSwagger2
@EnableWebMvc
public class Swagger2Config {
   ……
}


来源: stackexchange

问:
Laravel composer signal "11" error symfony osx
Anything I try to execute in Laravel, even minor files locally gives this message in composer:

[Symfony\Component\Process\Exception\RuntimeException]

  The process has been signaled with signal "11".

Using OSX 10.7.5

Any help appreciated, as always.

For example :

```<code>composer update
</code>```

typed in terminal retrieves the error message above

答:
Try:

Reinstall or upgrade PHP (Cli)

Make sure your .composer directory permission

This error message from laravel artisan is caused by Composer command error, you can try the same way from using command like:

```<code>composer dump-autoload -o
</code>```

It should also cause error relating from aristan optimize command which be trigger from post-update-cmd" in composer.json.

In my case, the error is segment fault via Cygwin PHP so that I change to use XAMPP PHP to run it and it worked.

ContentLicense: CC BY-SA 3.0

Body:
Anything I try to execute in Laravel, even minor files locally gives this message in composer:

[Symfony\Component\Process\Exception\RuntimeException]

  The process has been signaled with signal "11".

Using OSX 10.7.5

Any help appreciated, as always.

For example :

composer update

typed in terminal retrieves the error message above

Body:
Try:

Reinstall or upgrade PHP (Cli)

Make sure your .composer directory permission

This error message from laravel artisan is caused by Composer command error, you can try the same way from using command like:

composer dump-autoload -o

It should also cause error relating from aristan optimize command which be trigger from post-update-cmd" in composer.json.

In my case, the error is segment fault via Cygwin PHP so that I change to use XAMPP PHP to run it and it worked.


问:
Error: "Connection failed: SQLState: '08001' occurs when creating an ODBC connection on Microsoft SQL 2008 r 2
I have two sql server installed in same server.
SQL server 2012 express and SQL server 2008 r2.
After we moved to new office, we are not able to connect 2008 server but still able to connect 2012.

I have checked and confirmed that TCP/IP is enabled and the port is 1433 for both server.

SQL browser is also enabled

That is no firewall for blocking inbound and outbound from server, however I can't disable end user firewall as the option is being grey out by company IT.

ABC\SQLexpress2012 -  working
ABC\SQL2008 - doesn't not working

We managed to login Sql management studio in the machine itself. But both NT authentication and SQL authentication are not working in end user PC.

Any ideas from the experts here ?

答:
Change your SQL Server 2008 port

try this one

https://learn.microsoft.com/en-us/sql/database-engine/configure-windows/configure-a-server-to-listen-on-a-specific-tcp-port


问:
Missing git commit
It happens all the time at work, that someone accidentally commits something to master instead of to the intended feature branch, the person then tries to resolve it, only to have the changes suddenly disappear. I have searched thick and thin, and can find no documentation to shed light on why this happens, or how to remedy the situation.

Here are steps to reproduce:

```<code>$ git init
$ echo hello world > testfile
$ git add testfile
$ git commit -m 'init'
$ git branch A
$ echo abc >> testfile
$ git commit -am 'append abc'
$ git revert HEAD --no-edit
$ git checkout A
$ echo fff > secondfile
$ git add secondfile
$ git commit -m 'Add second file'
$ git cherry-pick master^
</code>```

At this point the git history looks like this:

```<code>$ git log --oneline --all --graph --decorate
* ac6f9b4 (HEAD -> A) append abc
* 54be952 Add second file
| * 9ba1f16 (master) Revert "append abc"
| * ef7c8d6 append abc
|/
* 65a885d init
</code>```

Watch then what happens when I rebase branch A on top of master:

```<code>$ git rebase master
$ git log --oneline --all --graph --decorate
* 9d08739 (HEAD -> A) Add second file
* 9ba1f16 (master) Revert "append abc"
* ef7c8d6 append abc
* 65a885d init
</code>```

What happened to the commit that was at the head of A, commit ac6f9b4? Where did it go? why wasn't it reapplied?

While this was just a small example with a single commit missing on the end, but sometimes we end up losing several commits from the middle of a long commit chain, and then they seem practically invisible :(

答:
Rebase doesn't re-apply commits that have already been applied in the new base -- here, it's your append abc change.  It's already in the master history. This is so often right that git does this without comment.  It's arguably at least worth mentioning in the presence of subsequent reverts.

To see whether anything you're rebasing is already part of the new base history (master, here),

```<code>git log --oneline --cherry ...master
</code>```

and look for =-marked commits.  Those are commits in master that match commits in your branch; rebase won't re-apply them.  Swap master... for ...master to see the local equivalents.

If you want an effectively blinded rebase, a first cut is

```<code>git checkout -B A master
git cherry-pick ..A@{1}      # < added the very important `..` by edit
</code>```

which just moves A onto master and then cherry-picks everything you just left behind.  To ignore merges (which you probably should), add --no-merges to the cherry-pick, it turns out when you ask cherry-pick for a series it just passes the whole set to git rev-list so you can use the machinery directly:

```<code>git cherry-pick --no-merges ..A@{1}  # just learned now that cherry-pick takes this
</code>```

Title: Missing git commit

Body:
It happens all the time at work, that someone accidentally commits something to master instead of to the intended feature branch, the person then tries to resolve it, only to have the changes suddenly disappear. I have searched thick and thin, and can find no documentation to shed light on why this happens, or how to remedy the situation.

Here are steps to reproduce:

$ git init
$ echo hello world > testfile
$ git add testfile
$ git commit -m 'init'
$ git branch A
$ echo abc >> testfile
$ git commit -am 'append abc'
$ git revert HEAD --no-edit
$ git checkout A
$ echo fff > secondfile
$ git add secondfile
$ git commit -m 'Add second file'
$ git cherry-pick master^

At this point the git history looks like this:

$ git log --oneline --all --graph --decorate
* ac6f9b4 (HEAD -> A) append abc
* 54be952 Add second file
| * 9ba1f16 (master) Revert "append abc"
| * ef7c8d6 append abc
|/
* 65a885d init

Watch then what happens when I rebase branch A on top of master:

$ git rebase master
$ git log --oneline --all --graph --decorate
* 9d08739 (HEAD -> A) Add second file
* 9ba1f16 (master) Revert "append abc"
* ef7c8d6 append abc
* 65a885d init

What happened to the commit that was at the head of A, commit ac6f9b4? Where did it go? why wasn't it reapplied?

While this was just a small example with a single commit missing on the end, but sometimes we end up losing several commits from the middle of a long commit chain, and then they seem practically invisible :(

Body:
Rebase doesn't re-apply commits that have already been applied in the new base -- here, it's your append abc change.  It's already in the master history. This is so often right that git does this without comment.  It's arguably at least worth mentioning in the presence of subsequent reverts.

To see whether anything you're rebasing is already part of the new base history (master, here),

git log --oneline --cherry ...master

and look for =-marked commits.  Those are commits in master that match commits in your branch; rebase won't re-apply them.  Swap master... for ...master to see the local equivalents.

If you want an effectively blinded rebase, a first cut is

git checkout -B A master
git cherry-pick ..A@{1}      # < added the very important `..` by edit

which just moves A onto master and then cherry-picks everything you just left behind.  To ignore merges (which you probably should), add --no-merges to the cherry-pick, it turns out when you ask cherry-pick for a series it just passes the whole set to git rev-list so you can use the machinery directly:

git cherry-pick --no-merges ..A@{1}  # just learned now that cherry-pick takes this


问:
How do I check if an object is "empty" or not?
The Cube class have two constructors, one which accepts three parameters that are converted into the tree attributes of the cube, and another one that doesn't require any parameter and therefore creates an "empty" cube. My question is how can a boolean method check if the cubes are valid or empty? Is there a way to do that without the need of checking each one of the attributes?</p>

```<code>class Application {

    public static void main(String[] args) {

        Cube c1 = new Cube(4, 3, 6);
        Cube c2 = new Cube();

        System.out.println(isNotEmpty(c1));
        System.out.println(isNotEmpty(c2));
    }

    public static boolean isNotEmpty(Cube cube) {
        if (/*cube attributes are NOT empty*/) {
            return true;
        } else {
            return false;
        }
    }

    public static class Cube {
        private int height;
        private int width;
        private int depth;

        public Cube() {}

        public Cube(int height, int width, int depth) {
            this.height = height;
            this.width = width;
            this.depth = depth;
        }

        public int getHeight() { return height; }
        public int getWidth() { return width; }
        public int getDepth() { return depth; }
    }
}
</code>```

答:
Since it appears that the only state which a Cube has are the height, width, and depth, then you could actually just use null to represent an empty Cube.

It doesn't make much sense to call a cube with no dimensions a cube in the first place.  Using null as a marker might make the most sense.

Body:
The Cube class have two constructors, one which accepts three parameters that are converted into the tree attributes of the cube, and another one that doesn't require any parameter and therefore creates an "empty" cube. My question is how can a boolean method check if the cubes are valid or empty? Is there a way to do that without the need of checking each one of the attributes?

class Application {

    public static void main(String[] args) {

        Cube c1 = new Cube(4, 3, 6);
        Cube c2 = new Cube();

        System.out.println(isNotEmpty(c1));
        System.out.println(isNotEmpty(c2));
    }

    public static boolean isNotEmpty(Cube cube) {
        if (/*cube attributes are NOT empty*/) {
            return true;
        } else {
            return false;
        }
    }

    public static class Cube {
        private int height;
        private int width;
        private int depth;

        public Cube() {}

        public Cube(int height, int width, int depth) {
            this.height = height;
            this.width = width;
            this.depth = depth;
        }

        public int getHeight() { return height; }
        public int getWidth() { return width; }
        public int getDepth() { return depth; }
    }
}


答:
Use a bool flag isEmptyCube  in the constructor. At the time of object creation, it will be automatically marked correctly whether it is blank or not.

```<code>public static class Cube {
        //...
        private boolean isEmptyCube;
        public Cube() {isEmptyCube = true;}
        public Cube(int hight, int width, int depth) {
            //...
            isEmptyCube = false;
        }
        public isCubeEmpty() { return isEmptyCube;}
</code>```

Title: How do I check if an object is "empty" or not?

Body:
Use a bool flag isEmptyCube  in the constructor. At the time of object creation, it will be automatically marked correctly whether it is blank or not.

public static class Cube {
        //...
        private boolean isEmptyCube;
        public Cube() {isEmptyCube = true;}
        public Cube(int hight, int width, int depth) {
            //...
            isEmptyCube = false;
        }
        public isCubeEmpty() { return isEmptyCube;}


问:
what does NoSuchElementException mean and how to solve?
We were given a .txt file full of names and were asked to put those names in alphabetical order by last name (bonus, if we can also sort by first name). We were tasked to create three different files, Person, SortName, and SortNameApp.

We have to use

```<code> Scanner input=new Scanner(new File(args[0]));
</code>```

to look for the file instead of using a BufferedReader.

this is what i have completed of each so far

Person:

```<code>class Person {
String firstName;
String lastName;
}
</code>```

SortNames:

```<code>class SortNames {

void sortNames(Person[] arr, int type) {
    if (type == 1) {
       int j;
       boolean flag = true; // will determine when the sort is finished
       Person temp;
       while (flag) {
           flag = false;
           for (j = 0; j < arr.length - 1; j++) {

               if (arr[j].lastName
                       .compareToIgnoreCase(arr[j + 1].lastName) > 0) { // ascending
                                                                           // sort
                   temp = arr[j];
                   arr[j] = arr[j + 1]; // swapping
                   arr[j + 1] = temp;
                   flag = true;
               }
           }
       }
       for (int k = 0; k < arr.length; k++)
           System.out.println(arr[k].firstName +"<-->"+arr[k].lastName);
   } else if (type == 2) {

       int j;
       boolean flag = true; // will determine when the sort is finished
       Person temp;
       while (flag) {
           flag = false;
           for (j = 0; j < arr.length - 1; j++) {

               if (arr[j].firstName
                       .compareToIgnoreCase(arr[j + 1].firstName) > 0) { // ascending
                                                                           // sort
                   temp = arr[j];
                   arr[j] = arr[j + 1]; // swapping
                   arr[j + 1] = temp;
                   flag = true;
               }
           }
       }
       for (int k = 0; k < arr.length; k++)
           System.out.println(arr[k].firstName +"<-->"+arr[k].lastName);
   }
  }

}
</code>```

SortNameApp:

```<code>import java.io.*;
import java.util.*;

public class SortNameApp {

  public static void main(String[] args) throws IOException {
   Scanner reader;

   try {

       Scanner input =new Scanner(new File(args[0]));
       int namesCount = Integer.parseInt(input.nextLine().trim());
       Person[] arr = new Person[namesCount];
       String line = null;
       int i = 0;
       while ((line = input.nextLine()) != null) {
           Person person = new Person();
           // System.out.println(line);
           person.firstName = line.split(" ")[0];
           person.lastName = line.substring(person.firstName.length(),
                   line.length()).trim();
           arr[i] = person;
           System.out.println(arr[i].firstName +" "+arr[i].lastName);
           i++;
       }
       System.out.println("---------------------");
       new SortNames().sortNames(arr, 1);// sort by last name
       System.out.println("---------------------");
       new SortNames().sortNames(arr, 2);// sort by first name
   } catch (FileNotFoundException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
   }
  }
 }
</code>```

As you can see, the line right here prints out the text file as it already is,

```<code>System.out.println(arr[i].firstName +" "+arr[i].lastName);
</code>```

But when it comes to applying the sorting algorithm into the code im left with this

```<code>Exception in thread "main" java.util.NoSuchElementException: No line found
 at java.util.Scanner.nextLine(Unknown Source)
 at SortNameApp.main(SortNameApp.java:16)
</code>```

My question is what exactly does this mean and whats one possible way to solve it? I'm really sorry if this is a basic knowledge question, but im fresh new to java so all this is foreign to me

答:
You're trying to use your Scanner as if it were a BufferedReader, but a Scanner isn't just a drop-in replacement for a BufferedReader.

Instead of the BufferedReader-style code:

```<code>while (line = input.nextLine()) != null) {
    ...
</code>```

you need to do this instead:

```<code>while (input.hasNextLine()){
    line = input.nextLine();
    ...
</code>```

Body:
We were given a .txt file full of names and were asked to put those names in alphabetical order by last name (bonus, if we can also sort by first name). We were tasked to create three different files, Person, SortName, and SortNameApp.

We have to use

 Scanner input=new Scanner(new File(args[0]));

to look for the file instead of using a BufferedReader.

this is what i have completed of each so far

Person:

class Person {
String firstName;
String lastName;
}

SortNames:

class SortNames {

void sortNames(Person[] arr, int type) {
    if (type == 1) {
       int j;
       boolean flag = true; // will determine when the sort is finished
       Person temp;
       while (flag) {
           flag = false;
           for (j = 0; j < arr.length - 1; j++) {

               if (arr[j].lastName
                       .compareToIgnoreCase(arr[j + 1].lastName) > 0) { // ascending
                                                                           // sort
                   temp = arr[j];
                   arr[j] = arr[j + 1]; // swapping
                   arr[j + 1] = temp;
                   flag = true;
               }
           }
       }
       for (int k = 0; k < arr.length; k++)
           System.out.println(arr[k].firstName +"<-->"+arr[k].lastName);
   } else if (type == 2) {

       int j;
       boolean flag = true; // will determine when the sort is finished
       Person temp;
       while (flag) {
           flag = false;
           for (j = 0; j < arr.length - 1; j++) {

               if (arr[j].firstName
                       .compareToIgnoreCase(arr[j + 1].firstName) > 0) { // ascending
                                                                           // sort
                   temp = arr[j];
                   arr[j] = arr[j + 1]; // swapping
                   arr[j + 1] = temp;
                   flag = true;
               }
           }
       }
       for (int k = 0; k < arr.length; k++)
           System.out.println(arr[k].firstName +"<-->"+arr[k].lastName);
   }
  }

}

SortNameApp:

import java.io.*;
import java.util.*;

public class SortNameApp {

  public static void main(String[] args) throws IOException {
   Scanner reader;

   try {

       Scanner input =new Scanner(new File(args[0]));
       int namesCount = Integer.parseInt(input.nextLine().trim());
       Person[] arr = new Person[namesCount];
       String line = null;
       int i = 0;
       while ((line = input.nextLine()) != null) {
           Person person = new Person();
           // System.out.println(line);
           person.firstName = line.split(" ")[0];
           person.lastName = line.substring(person.firstName.length(),
                   line.length()).trim();
           arr[i] = person;
           System.out.println(arr[i].firstName +" "+arr[i].lastName);
           i++;
       }
       System.out.println("---------------------");
       new SortNames().sortNames(arr, 1);// sort by last name
       System.out.println("---------------------");
       new SortNames().sortNames(arr, 2);// sort by first name
   } catch (FileNotFoundException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
   }
  }
 }

As you can see, the line right here prints out the text file as it already is,

System.out.println(arr[i].firstName +" "+arr[i].lastName);

But when it comes to applying the sorting algorithm into the code im left with this

Exception in thread "main" java.util.NoSuchElementException: No line found
 at java.util.Scanner.nextLine(Unknown Source)
 at SortNameApp.main(SortNameApp.java:16)

My question is what exactly does this mean and whats one possible way to solve it? I'm really sorry if this is a basic knowledge question, but im fresh new to java so all this is foreign to me

Body:
You're trying to use your Scanner as if it were a BufferedReader, but a Scanner isn't just a drop-in replacement for a BufferedReader.

Instead of the BufferedReader-style code:

while (line = input.nextLine()) != null) {
    ...

you need to do this instead:

while (input.hasNextLine()){
    line = input.nextLine();
    ...


答:
Either change one (or more) of your int fields to be an Integer Object, or introduce a new Boolean field isSet or get rid of your empty constructor

1) If you use an Integer Object you can test to see if it is null where -as int primitives have a default value of 0

2) If you have a Boolean field you can default it to false and set it to true in your proper constructor


问:
iOS Push Notification showing invalid token
I have been facing this invalid token when I test the iOS push notification.
It works fine if I build the project in development mode.
This are the following I used to create certificate.
1. I generate certSigningRequest and saved.
2. Generate all development, adhoc, distribution certificate and provisioning profiles.
3. Test in development works fine.
4. Archive in Adhoc mode and installed the app. Now fail to push by showing invalid token. enter image description here

Please suggest some help, I have been trying many days but still no solution.

Best regards

答:
Guys there is one update,
If I choose the server as gateway.push.apple.com, it works fine.
Success image</p>

ContentLicense: CC BY-SA 4.0


问:
Xamarin Forms Android not installing correctly
I am trying to install Visual Studio 2017 on 1 of my Windows 10 machines so I can use it as a build slave for my Xamarin.Forms project. However, it keeps failing to load Xamarin.Forms Android. I have reinstalled multiple times but to no avail. I have gotten it to work on 3 different Windows 10 computers. Any help would be appreciated.

Error it gives me when I try to open of Xamarin.Forms Android settings.

Here is the relevant entries in the Activity Log the above message pointed me to.

```<code><entry>
    <record>184</record>
    <time>2017/06/28 01:28:01.166</time>
    <type>Error</type>
    <source>VisualStudio</source>
    <description>LegacySitePackage failed for package [XamarinAndroidPackage]Source: 'Xamarin.VisualStudio.Android' Description: Object reference not set to an instance of an object.
System.NullReferenceException: Object reference not set to an instance of an object.
   at Xamarin.VisualStudio.Android.XamarinAndroidPackage.Initialize() in C:\d\lanes\4699\fec6f88f\source\xamarinvs\src\Core\VisualStudio.Android\XamarinAndroidPackage.cs:line 170
   at Microsoft.VisualStudio.Shell.Package.Microsoft.VisualStudio.Shell.Interop.IVsPackage.SetSite(IServiceProvider sp)</description>
    <guid>{296E6A4E-2BD5-44B7-A96D-8EE3D9CDA2F6}</guid>
    <hr>80004003 - E_POINTER</hr>
    <errorinfo></errorinfo>
</entry>
<entry>
  <record>185</record>
  <time>2017/06/28 01:28:01.183</time>
  <type>Error</type>
  <source>VisualStudio</source>
  <description>SetSite failed for package [XamarinAndroidPackage](null)</description>
  <guid>{296E6A4E-2BD5-44B7-A96D-8EE3D9CDA2F6}</guid>
  <hr>80004003 - E_POINTER</hr>
  <errorinfo></errorinfo>
</entry>
</code>```

Thank you for your time!

答: I worked with a guy from the Visual Studio support team but we could not figure out a solution. In the end I did the Window 10's Fresh Start and reinstalled Visual Studio. This time it worked.</p>

Body:
I am trying to install Visual Studio 2017 on 1 of my Windows 10 machines so I can use it as a build slave for my Xamarin.Forms project. However, it keeps failing to load Xamarin.Forms Android. I have reinstalled multiple times but to no avail. I have gotten it to work on 3 different Windows 10 computers. Any help would be appreciated.

Error it gives me when I try to open of Xamarin.Forms Android settings.

Here is the relevant entries in the Activity Log the above message pointed me to.

<entry>
    <record>184</record>
    <time>2017/06/28 01:28:01.166</time>
    <type>Error</type>
    <source>VisualStudio</source>
    <description>LegacySitePackage failed for package [XamarinAndroidPackage]Source: 'Xamarin.VisualStudio.Android' Description: Object reference not set to an instance of an object.
System.NullReferenceException: Object reference not set to an instance of an object.
   at Xamarin.VisualStudio.Android.XamarinAndroidPackage.Initialize() in C:\d\lanes\4699\fec6f88f\source\xamarinvs\src\Core\VisualStudio.Android\XamarinAndroidPackage.cs:line 170
   at Microsoft.VisualStudio.Shell.Package.Microsoft.VisualStudio.Shell.Interop.IVsPackage.SetSite(IServiceProvider sp)</description>
    <guid>{296E6A4E-2BD5-44B7-A96D-8EE3D9CDA2F6}</guid>

80004003 - E_POINTER

    <errorinfo></errorinfo>
</entry>
<entry>
  <record>185</record>
  <time>2017/06/28 01:28:01.183</time>
  <type>Error</type>
  <source>VisualStudio</source>
  <description>SetSite failed for package [XamarinAndroidPackage](null)</description>
  <guid>{296E6A4E-2BD5-44B7-A96D-8EE3D9CDA2F6}</guid>

80004003 - E_POINTER

  <errorinfo></errorinfo>
</entry>

Thank you for your time!


问:
Finding POIs that are near or contain a certain location
I have an application that does the following:

Receives a device's location

Fetches a route (collection of POIs, or Points of Interest) assigned to that device

Determines if the device is near any of the POIs in the route

The route's POIs can be either a point with a radius, in which case it should detect if the device is within the radius of the point; or a polygon, where it should detect if the device is inside of it.

Here is a sample of a route with 3 POIs, two of them are points with different radii, and the other one is a polygon:

https://jsonblob.com/285c86cd-61d5-11e7-ae4c-fd99f61d20b8

My current algorithm is programmed in PHP with a MySQL database. When a device sends a new location, the script loads all the POIs for its route from the database into memory, and then iterates through them. For POIs that are points, it uses the Haversine formula to find if the device is within the POI's radius, and for POIs that are polygons it uses a "point in polygon" algorithm to find if the device is inside of it or not.

I would like to rewrite the algorithm with the goal of using less computing resources than the current one. We receive about 100 locations per second and they each have to be checked against routes that have about 40 POIs on average.

I can use any language and database to do so, which ones would you recommend for the best possible performance?

答:
I'd use a database (e.g., Postgresql) that supports spatial queries.

That will let you create a spatial index that puts a bounding box around each POI. You can use this to do an initial check to (typically) eliminate the vast majority of POIs that aren't even close to the current position (i.e., where the current position isn't inside their bounding box).

Then when you've narrowed it down to a few POIs, you can test the few that are lest using roughly the algorithm you are now--but instead of testing 40 POIs per point, you might be testing only 2 or 3.

Exactly how well this will work will depend heavily upon how close to rectangular your POIs are. Circular is close enough that it tends to give pretty good results.

Others may depend--for example, a river that runs nearly north and south may work quite well. If you have a river that runs mostly diagonally, it may be worthwhile to break it up into a number of square/rectangular segments instead of treating the whole thing as a single feature, since the latter will create a bounding box with a lot of space that's quite a ways away from the river.


问:
Surprising behaviour of Python date and timedelta subtraction
I am trying to do some Python date and timedelta maths and stumbled upon this.

```<code>>>> import datetime
>>> dt = datetime.date(2000, 4, 20)
>>> td = datetime.timedelta(days=1)
>>> dt - td
datetime.date(2000, 4, 19)
>>> -(td) + dt
datetime.date(2000, 4, 19)
>>> dt - td == dt + (-td)
True
</code>```

So far so good, but when the timedelta also includes some hours it gets interesting.

```<code>>>> td = datetime.timedelta(days=1, hours=1)
>>> dt - td
datetime.date(2000, 4, 19)
>>> -(td) + dt
datetime.date(2000, 4, 18)
</code>```

or in a comparison:

```<code>>>> dt - td == dt + (-td)
False
</code>```

I would have expected that a - b == a + (-b), but this doesn't seem to work for date and timedelta. As far as I was able to track that down, this happens because adding/subtracting date and timedelta only considers the days field of timedelta, which is probably correct. However negating a timedelta considers all fields and may change the days field as well.

```<code>>>> -datetime.timedelta(days=1)
datetime.timedelta(-1)
>>> -datetime.timedelta(days=1, hours=1)
datetime.timedelta(-2, 82800)
</code>```

As can be seen in the second example, days=-2 after the negation, and therefore date + timedelta will actually subtract 2 days.

Should this be considered a bug in the python datetime module? Or is this rather some 'normal' behaviour which needs to be taken into account when doing things like that?

Internally the datetime module creates a new timedelta, with just the days field of the original timedelta object passed in, when subtracting a timedelta to a date object. Which equates to following, code that seems to be quite odd.

```<code>>>> dt + datetime.timedelta(-(-(-dt).days))
datetime.date(2000, 4, 18)
</code>```

I can't really sea a reason for just using the negated days field when doing date - timedelta subtractions.

Edit:

Here is the relevant code path in python datetime module:

```<code>class date:

    ...

    def __sub__(self, other):
        """Subtract two dates, or a date and a timedelta."""
        if isinstance(other, timedelta):
           return self + timedelta(-other.days)
        ...
</code>```

If it would just pass on -other then the condition a - b == a + (-b) would hold true. (It would change current behaviour though).

```<code>class date:

    ...

    def __sub__(self, other):
        """Subtract two dates, or a date and a timedelta."""
        if isinstance(other, timedelta):
           return self - other  # timedelta.__rsub__ would take care of negating other
        ...
</code>```

答:
Should this be considered a bug in the python datetime module? Or is
  this rather some 'normal' behaviour which needs to be taken into
  account when doing things like that?

No, this should not be considered a bug. A date does not track its state in terms of hours, minutes, and seconds, which is what would be needed for it to behave in the way you suggest it ought to.

I would consider the code you've presented to be a bug: the programmer is using the wrong datatype for the work they're trying to accomplish. If you want to keep track of time in days, hours, minutes and seconds, then you need a datetime object. (which will happily provide you with a date once you've done all of the arithmetic you care to do)

Body:
I am trying to do some Python date and timedelta maths and stumbled upon this.

>>> import datetime
>>> dt = datetime.date(2000, 4, 20)
>>> td = datetime.timedelta(days=1)
>>> dt - td
datetime.date(2000, 4, 19)
>>> -(td) + dt
datetime.date(2000, 4, 19)
>>> dt - td == dt + (-td)
True

So far so good, but when the timedelta also includes some hours it gets interesting.

>>> td = datetime.timedelta(days=1, hours=1)
>>> dt - td
datetime.date(2000, 4, 19)
>>> -(td) + dt
datetime.date(2000, 4, 18)

or in a comparison:

>>> dt - td == dt + (-td)
False

I would have expected that a - b == a + (-b), but this doesn't seem to work for date and timedelta. As far as I was able to track that down, this happens because adding/subtracting date and timedelta only considers the days field of timedelta, which is probably correct. However negating a timedelta considers all fields and may change the days field as well.

>>> -datetime.timedelta(days=1)
datetime.timedelta(-1)
>>> -datetime.timedelta(days=1, hours=1)
datetime.timedelta(-2, 82800)

As can be seen in the second example, days=-2 after the negation, and therefore date + timedelta will actually subtract 2 days.

Should this be considered a bug in the python datetime module? Or is this rather some 'normal' behaviour which needs to be taken into account when doing things like that?

Internally the datetime module creates a new timedelta, with just the days field of the original timedelta object passed in, when subtracting a timedelta to a date object. Which equates to following, code that seems to be quite odd.

>>> dt + datetime.timedelta(-(-(-dt).days))
datetime.date(2000, 4, 18)

I can't really sea a reason for just using the negated days field when doing date - timedelta subtractions.

Edit:

Here is the relevant code path in python datetime module:

class date:

    ...

    def __sub__(self, other):
        """Subtract two dates, or a date and a timedelta."""
        if isinstance(other, timedelta):
           return self + timedelta(-other.days)
        ...

If it would just pass on -other then the condition a - b == a + (-b) would hold true. (It would change current behaviour though).

class date:

    ...

    def __sub__(self, other):
        """Subtract two dates, or a date and a timedelta."""
        if isinstance(other, timedelta):
           return self - other  # timedelta.__rsub__ would take care of negating other
        ...


问:
Removing only first column in R using uploaded data
All, I'm very new to R and have no programming experience.  I'm using a loop to load hundreds of Excel sheets, perform a statistical test, and spit out the results.  So effectively hundreds of those regressions.  I'm using a "dummy header" in the first column of my Excel sheets so that I can save the R outputs by the names of the different Excel sheets.  I want to drop that dummy header from my regression, as it's interfering with some of the regressions.  I've tried using.

x<-mydata[,1]
newdata<-subset(mydata,select=-x))

But that doesn't work, it return's either

invalid argument to unary operator
Error in x[j] : invalid subscript type 'list'
or
Error: Unsupported index type: data.frame

depending on how I change the code.  Any help or insight would be much appreciated, thank you very much!

答:
If you are reading in csv files, you can use the skip argument within the read.csv function. If you have headers for the column names below the dummy header, you will want to set it to true.  If you don't have column headers then use the skip function and set headers to false.

```<code>#with headers
data<-read.csv("file.csv", skip=1, header=TRUE)

#without headers
data<-read.csv("file.csv", skip=1, header=FALSE)
</code>```

If you are using the read.xlsx function you should be able to use the the rowIndex argument.  You may have to set the length to a large number so all rows read in properly. Starting at row 2 will get rid of the top row.

```<code>sample<-read.xlsx("file.xlsx", sheetIndex = 1, rowIndex = 2:1000000)
</code>```

Body:
If you are reading in csv files, you can use the skip argument within the read.csv function. If you have headers for the column names below the dummy header, you will want to set it to true.  If you don't have column headers then use the skip function and set headers to false.

#with headers
data<-read.csv("file.csv", skip=1, header=TRUE)

#without headers
data<-read.csv("file.csv", skip=1, header=FALSE)

If you are using the read.xlsx function you should be able to use the the rowIndex argument.  You may have to set the length to a large number so all rows read in properly. Starting at row 2 will get rid of the top row.

sample<-read.xlsx("file.xlsx", sheetIndex = 1, rowIndex = 2:1000000)


问:
Cannot select PDF files in Chrome iOS using Dropbox
I have an issue using Wordpress's Media Manager whilst using iOS Chrome browser. It won't allow me to select any PDF files. It works fine in Safari but was wondering if there is any restrictions on Chrome, Dropbox or iOS which is stopping a user from selecting it.

I have checked that all the correct "accepted types" are correct. I'm sure it's not that. (Wordpress has added .pdf and application/pdf to type="file")

Code:
 iOS Chrome (59.0.3071.102)  This is the exact code for our File Input:

```<code><input id="html5_1bka" type="file" multiple="" accept="image/jpeg,.jpg,.jpeg,.jpe,image/gif,.gif,image/png,.png,image/bmp,.bmp,image/tiff,.tiff,.tif,.ico,.asf,.asx,video/x-ms-wmv,.wmv,.wmx,.wm,video/avi,.avi,.divx,video/x-flv,.flv,video/quicktime,.mov,.qt,video/mpeg,.mpeg,.mpg,.mpe,video/mp4,.mp4,video/x-m4v,.m4v,video/ogg,.ogv,video/webm,.webm,video/x-matroska,.mkv,video/3gpp,.3gp,.3gpp,video/3gpp2,.3g2,.3gp2,text/plain,.txt,.asc,.c,.cc,.h,.srt,text/csv,.csv,.tsv,.ics,.rtx,text/css,.css,text/html,.htm,.html,.vtt,.dfxp,audio/mpeg,.mp3,audio/x-m4a,.m4a,.m4b,.ra,.ram,audio/x-wav,.wav,audio/ogg,.ogg,.oga,.mid,.midi,audio/x-ms-wma,.wma,.wax,.mka,text/rtf,.rtf,application/x-javascript,.js,application/pdf,.pdf,.class,.tar,application/zip,.zip,.gz,.gzip,.rar,.7z,image/photoshop,.psd,.xcf,application/msword,.doc,application/vnd.ms-powerpoint,.pot,.pps,.ppt,.wri,.xla,application/vnd.ms-excel,.xls,.xlt,.xlw,.mdb,.mpp,application/vnd.openxmlformats-officedocument.wordprocessingml.document,.docx,.docm,application/vnd.openxmlformats-officedocument.wordprocessingml.template,.dotx,.dotm,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,.xlsx,.xlsm,.xlsb,.xltx,.xltm,.xlam,application/vnd.openxmlformats-officedocument.presentationml.presentation,.pptx,.pptm,application/vnd.openxmlformats-officedocument.presentationml.slideshow,.ppsx,.ppsm,application/vnd.openxmlformats-officedocument.presentationml.template,.potx,.potm,.ppam,.sldx,.sldm,.onetoc,.onetoc2,.onetmp,.onepkg,.oxps,.xps,.odt,.odp,.ods,.odg,.odc,.odb,.odf,.wp,.wpd,.key,.numbers,.pages,.bz2,.jpeg,.jpg,.mp4,.onetoc,.ppt,.tgz,.txz,.txt,.wpd,.xz,.jpe">
</code>```

Screen shots:

I've seen another site working and looking at the code I could see that they didn't specify an "accept" attribute. I remove it and tested. It still doesn't allow PDF selection. Totally stumped.

答:
Try removing all the file types in the accept attribute. Removing the entire attribute altogether didn't work for me.

Your input html should now look like:

```<code><input id="html5_1bka" type="file" multiple="" accept="">
</code>```

In order to fix this in Wordpress you might have to write a bit of custom JS to listen for wp.media, open event

How to Trigger some JavaScript when Media Popup is opened?

Body:
I have an issue using Wordpress's Media Manager whilst using iOS Chrome browser. It won't allow me to select any PDF files. It works fine in Safari but was wondering if there is any restrictions on Chrome, Dropbox or iOS which is stopping a user from selecting it.

I have checked that all the correct "accepted types" are correct. I'm sure it's not that. (Wordpress has added .pdf and application/pdf to type="file")

Code:
 iOS Chrome (59.0.3071.102)  This is the exact code for our File Input:

<input id="html5_1bka" type="file" multiple="" accept="image/jpeg,.jpg,.jpeg,.jpe,image/gif,.gif,image/png,.png,image/bmp,.bmp,image/tiff,.tiff,.tif,.ico,.asf,.asx,video/x-ms-wmv,.wmv,.wmx,.wm,video/avi,.avi,.divx,video/x-flv,.flv,video/quicktime,.mov,.qt,video/mpeg,.mpeg,.mpg,.mpe,video/mp4,.mp4,video/x-m4v,.m4v,video/ogg,.ogv,video/webm,.webm,video/x-matroska,.mkv,video/3gpp,.3gp,.3gpp,video/3gpp2,.3g2,.3gp2,text/plain,.txt,.asc,.c,.cc,.h,.srt,text/csv,.csv,.tsv,.ics,.rtx,text/css,.css,text/html,.htm,.html,.vtt,.dfxp,audio/mpeg,.mp3,audio/x-m4a,.m4a,.m4b,.ra,.ram,audio/x-wav,.wav,audio/ogg,.ogg,.oga,.mid,.midi,audio/x-ms-wma,.wma,.wax,.mka,text/rtf,.rtf,application/x-javascript,.js,application/pdf,.pdf,.class,.tar,application/zip,.zip,.gz,.gzip,.rar,.7z,image/photoshop,.psd,.xcf,application/msword,.doc,application/vnd.ms-powerpoint,.pot,.pps,.ppt,.wri,.xla,application/vnd.ms-excel,.xls,.xlt,.xlw,.mdb,.mpp,application/vnd.openxmlformats-officedocument.wordprocessingml.document,.docx,.docm,application/vnd.openxmlformats-officedocument.wordprocessingml.template,.dotx,.dotm,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,.xlsx,.xlsm,.xlsb,.xltx,.xltm,.xlam,application/vnd.openxmlformats-officedocument.presentationml.presentation,.pptx,.pptm,application/vnd.openxmlformats-officedocument.presentationml.slideshow,.ppsx,.ppsm,application/vnd.openxmlformats-officedocument.presentationml.template,.potx,.potm,.ppam,.sldx,.sldm,.onetoc,.onetoc2,.onetmp,.onepkg,.oxps,.xps,.odt,.odp,.ods,.odg,.odc,.odb,.odf,.wp,.wpd,.key,.numbers,.pages,.bz2,.jpeg,.jpg,.mp4,.onetoc,.ppt,.tgz,.txz,.txt,.wpd,.xz,.jpe">

Screen shots:

I've seen another site working and looking at the code I could see that they didn't specify an "accept" attribute. I remove it and tested. It still doesn't allow PDF selection. Totally stumped.

Body:
Try removing all the file types in the accept attribute. Removing the entire attribute altogether didn't work for me.

Your input html should now look like:

<input id="html5_1bka" type="file" multiple="" accept="">

In order to fix this in Wordpress you might have to write a bit of custom JS to listen for wp.media, open event

How to Trigger some JavaScript when Media Popup is opened?


问:
Working with json in Watson Python SDK
I am working on a project that will hopefully allow me to combine the Watson Python SDK implementation of speech-to-text...Watson Conversation...and text-to-speech. I am running into some problems though working with the Python 2.7 json data. I am actually trying to do two things:

1) I want to parse the json data just for the transcript values and it would be awesome if I could combine those values into an easily readable string format for use later in the program.

2) The other thing I need to do is manipulate the json in a way that would allow me to use it as input for the conversation or text-to-speech sections. Basically, how can I convert whats provided in the json into acceptable input for the other Watson modules?

What I've tried so far:
I read the Python 2.7 json docs and tried to convert it back into a Python dictionary which sort of worked? All of the key:value pairs had a "u" before them and none of the regular dictionary methods seemed to work on them. Also, they don't look like the standard Key:Value combinations. I was able to put all of the json data in one variable though. I'll post my code below (ignore the print statements as I was just checking to see how the data looked at each step), but it's mostly just what you can get from the github examples section.

** Just a quick final question too: Is the Python SDK limited in any way compared to the other ones (Java, JScript, etc) because it seems like their output is much easier to work with?

```<code>import json
from os.path import join, dirname
from watson_developer_cloud import SpeechToTextV1

speech_to_text = SpeechToTextV1(
    username='###########',
    password='###########,
    x_watson_learning_opt_out=True
)

with open(join(dirname(__file__), '/home/user/Desktop/output.wav'),'rb') as audio_file:

    json_str = (json.dumps(speech_to_text.recognize(audio_file, content_type='audio/wav', timestamps=False, word_confidence=False,
model='en-US_NarrowbandModel'), indent=2))

print json_str

json_dict = json.loads(json_str)

print json_dict

def main(args):
    return 0

if __name__ == '__main__':
    import sys
    sys.exit(main(sys.argv))
</code>```

答:
The issue appears to me that you are dumping your JSON to a string, then trying to access it as an object.

Using the following sample code, it works.

```<code>from os.path import join, dirname
from watson_developer_cloud import SpeechToTextV1

speech_to_text = SpeechToTextV1(
    username='....',
    password='....',
    x_watson_learning_opt_out=True
)

with open('../blog/ihaveadream.wav','rb') as audio_file:
    response = speech_to_text.recognize(audio_file, content_type='audio/wav', timestamps=False, word_confidence=False, model='en-US_NarrowbandModel')

print json.dumps(response, indent=2)
</code>```

This returns the following:

```<code>{
  "results": [
    {
      "alternatives": [
        {
          "confidence": 1.0,
          "transcript": "I still have a dream "
        }
      ],
      "final": true
    },
    {
      "alternatives": [
        {
          "confidence": 0.999,
          "transcript": "it is a dream deeply rooted in the American dream I have a dream "
        }
      ],
      "final": true
    },
    {
      "alternatives": [
        {
          "confidence": 1.0,
          "transcript": "that one day this nation will rise up and live out the true meaning of its creed we hold these truths to be self evident that all men are created equal "
        }
      ],
      "final": true
    }
  ],
  "result_index": 0,
  "warnings": [
    "Unknown arguments: continuous."
  ]
}
</code>```

So if you wanted to access the top level response you can do the following.

```<code>print 'Confidence: {}'.format(response['results'][0]['alternatives'][0]['confidence'])
print 'Transcript: {}'.format(response['results'][0]['alternatives'][0]['transcript'])
</code>```

The output of that would be:

```<code>Confidence: 1.0
Transcript: I still have a dream
</code>```

Title: Working with json in Watson Python SDK

Body:
I am working on a project that will hopefully allow me to combine the Watson Python SDK implementation of speech-to-text...Watson Conversation...and text-to-speech. I am running into some problems though working with the Python 2.7 json data. I am actually trying to do two things:

1) I want to parse the json data just for the transcript values and it would be awesome if I could combine those values into an easily readable string format for use later in the program.

2) The other thing I need to do is manipulate the json in a way that would allow me to use it as input for the conversation or text-to-speech sections. Basically, how can I convert whats provided in the json into acceptable input for the other Watson modules?

What I've tried so far:
I read the Python 2.7 json docs and tried to convert it back into a Python dictionary which sort of worked? All of the key:value pairs had a "u" before them and none of the regular dictionary methods seemed to work on them. Also, they don't look like the standard Key:Value combinations. I was able to put all of the json data in one variable though. I'll post my code below (ignore the print statements as I was just checking to see how the data looked at each step), but it's mostly just what you can get from the github examples section.

** Just a quick final question too: Is the Python SDK limited in any way compared to the other ones (Java, JScript, etc) because it seems like their output is much easier to work with?

import json
from os.path import join, dirname
from watson_developer_cloud import SpeechToTextV1

speech_to_text = SpeechToTextV1(
    username='###########',
    password='###########,
    x_watson_learning_opt_out=True
)

with open(join(dirname(__file__), '/home/user/Desktop/output.wav'),'rb') as audio_file:

    json_str = (json.dumps(speech_to_text.recognize(audio_file, content_type='audio/wav', timestamps=False, word_confidence=False,
model='en-US_NarrowbandModel'), indent=2))

print json_str

json_dict = json.loads(json_str)

print json_dict

def main(args):
    return 0

if __name__ == '__main__':
    import sys
    sys.exit(main(sys.argv))

Body:
The issue appears to me that you are dumping your JSON to a string, then trying to access it as an object.

Using the following sample code, it works.

from os.path import join, dirname
from watson_developer_cloud import SpeechToTextV1

speech_to_text = SpeechToTextV1(
    username='....',
    password='....',
    x_watson_learning_opt_out=True
)

with open('../blog/ihaveadream.wav','rb') as audio_file:
    response = speech_to_text.recognize(audio_file, content_type='audio/wav', timestamps=False, word_confidence=False, model='en-US_NarrowbandModel')

print json.dumps(response, indent=2)

This returns the following:

{
  "results": [
    {
      "alternatives": [
        {
          "confidence": 1.0,
          "transcript": "I still have a dream "
        }
      ],
      "final": true
    },
    {
      "alternatives": [
        {
          "confidence": 0.999,
          "transcript": "it is a dream deeply rooted in the American dream I have a dream "
        }
      ],
      "final": true
    },
    {
      "alternatives": [
        {
          "confidence": 1.0,
          "transcript": "that one day this nation will rise up and live out the true meaning of its creed we hold these truths to be self evident that all men are created equal "
        }
      ],
      "final": true
    }
  ],
  "result_index": 0,
  "warnings": [
    "Unknown arguments: continuous."
  ]
}

So if you wanted to access the top level response you can do the following.

print 'Confidence: {}'.format(response['results'][0]['alternatives'][0]['confidence'])
print 'Transcript: {}'.format(response['results'][0]['alternatives'][0]['transcript'])

The output of that would be:

Confidence: 1.0
Transcript: I still have a dream


问:
Does throwing an Exception have to cause the program to terminate
Does throwing an Exception have to cause the program to terminate?

I think its no, I just want to make sure

答: No, it does not have to cause it to terminate. You could catch the exception and do something useful with it, like show a message to the user that an error occurred and why.</p>

ContentLicense: CC BY-SA 2.5


问:
How do I make an image provided by an api as the background image of my div in jQuery and node?
I am trying to create a search engine for movies with an api provided by the movie database (tmdbs). I want to have a div popup for each movie that has a title similar to the one the user types in to the database. Right now I chose the movie Lucy as my experiment. I want the poster image provided in the first result of the api when I search for Lucy to be the background image of the div I am creating, I cannot seem to be able to accomplish this. My ultimate goal is to create a series of results with divs that have background images as provided by the first 20 results in the api. Here is my code:

```<code>$('#search').keypress(function(e) {
        if (e.which == 13) {
            var movie = $('#search-input').val();
            $('form#login').submit();
            console.log('onclick fun', movie)
            makeCall(movie);
            return false;
        }
    });

    function makeCall(aMovie) {
        console.log('makecall', aMovie);

        link = url + aMovie;
        console.log(link);
        $.ajax({
            method: "GET",
            url: link,
            success: function(data) {
                console.log("the data -->", data);
                getData(data);
            },
        })
    }

    function getData(responseData) {
        var poster = responseData.results[0].poster_path;
        appendToDom(poster);
    }

    function appendToDom(poster) {
        var aPoster = $('<div>');
        var movie_poster = 'https://image.tmdb.org/t/p/w1280' + poster;
        console.log(movie_poster);
        aPoster.css({
            'float': 'left',
            'margin': 10,
            'margin-left': 37,
            'margin-top': 20,
            'width': 200,
            'height': 300,
            'font-size': 36,
            'color': 'black',
            'background-size': '200px 300px',
            'background-image': 'https://image.tmdb.org/t/p/w1280/rwn876MeqienhOVSSjtUPnwxn0Z.jpg' //'url("./../images/question.jpg")'
        })
        $(main).append(aPoster);
    }
</code>```

Here is a screenshot of what I'm looking for. Instead of the question marks I want the movie posters to come up.

enter image description here

I'm really sorry for the long post. I hope someone can help me:)

Thanks a lot in advance!

答:
var aPoster = $('');

and

var aPoster = $('div');

return totally different values. Might want to check that.

Body:
I am trying to create a search engine for movies with an api provided by the movie database (tmdbs). I want to have a div popup for each movie that has a title similar to the one the user types in to the database. Right now I chose the movie Lucy as my experiment. I want the poster image provided in the first result of the api when I search for Lucy to be the background image of the div I am creating, I cannot seem to be able to accomplish this. My ultimate goal is to create a series of results with divs that have background images as provided by the first 20 results in the api. Here is my code:

$('#search').keypress(function(e) {
        if (e.which == 13) {
            var movie = $('#search-input').val();
            $('form#login').submit();
            console.log('onclick fun', movie)
            makeCall(movie);
            return false;
        }
    });

    function makeCall(aMovie) {
        console.log('makecall', aMovie);

        link = url + aMovie;
        console.log(link);
        $.ajax({
            method: "GET",
            url: link,
            success: function(data) {
                console.log("the data -->", data);
                getData(data);
            },
        })
    }

    function getData(responseData) {
        var poster = responseData.results[0].poster_path;
        appendToDom(poster);
    }

    function appendToDom(poster) {
        var aPoster = $('
');
        var movie_poster = 'https://image.tmdb.org/t/p/w1280' + poster;
        console.log(movie_poster);
        aPoster.css({
            'float': 'left',
            'margin': 10,
            'margin-left': 37,
            'margin-top': 20,
            'width': 200,
            'height': 300,
            'font-size': 36,
            'color': 'black',
            'background-size': '200px 300px',
            'background-image': 'https://image.tmdb.org/t/p/w1280/rwn876MeqienhOVSSjtUPnwxn0Z.jpg' //'url("./../images/question.jpg")'
        })
        $(main).append(aPoster);
    }

Here is a screenshot of what I'm looking for. Instead of the question marks I want the movie posters to come up.

enter image description here

I'm really sorry for the long post. I hope someone can help me:)

Thanks a lot in advance!


问:
npm install -g dredd@stable fails on CircleCI due to npm ERR! code ECONNRESET
I have a project on CircleCI which started going red (due to failure on installing dredd) at some point. Currently the same exact project (same code, same circle.yml) may fail or succeed at random it seems.

The failure is always in the phase npm install -g dredd@stable with the following error which repeats itself several times and eventually fails the build:

```<code>make: Leaving directory /opt/circleci/nodejs/v4.2.6/lib/node_modules/dredd/node_modules/dredd-transactions/node_modules/fury-adapter-apib-parser/node_modules/drafter/node_modules/protagonist/build'
npm ERR! Linux 3.13.0-117-generic
npm ERR! argv "/opt/circleci/nodejs/v4.2.6/bin/node" "/opt/circleci/nodejs/v4.2.6/bin/npm" "install" "-g" "dredd@stable"
npm ERR! node v4.2.6
npm ERR! npm  v2.14.12
npm ERR! code ECONNRESET
npm ERR! errno ECONNRESET
npm ERR! syscall read
npm ERR! network read ECONNRESET
npm ERR! network This is most likely not a problem with npm itself
npm ERR! network and is related to network connectivity.
npm ERR! network In most cases you are behind a proxy or have bad network settings.
npm ERR! network
npm ERR! network If you are behind a proxy, please make sure that the
npm ERR! network 'proxy' config is set properly.  See: 'npm help config'
</code>```

If I try to rerun the build several times it will succeed at  some point (going Green). The dredd installation then shows up something like this:

```<code>make: Leaving directory /opt/circleci/nodejs/v4.2.6/lib/node_modules/dredd/node_modules/dredd-transactions/node_modules/fury-adapter-apib-parser/node_modules/drafter/node_modules/protagonist/build'
/opt/circleci/nodejs/v4.2.6/bin/dredd -> /opt/circleci/nodejs/v4.2.6/lib/node_modules/dredd/bin/dredd
dredd@3.4.5 /opt/circleci/nodejs/v4.2.6/lib/node_modules/dredd
├── caseless@0.12.0
├── clone@2.1.1
├── file@0.2.2
</code>```

etc', basically installing dredd successfully and moving on to test the build.

Since it seems to fail randomly I don't think the proxy has anything to do with it. Here is the circle.yml file for reference:

```<code>machine:
  environment:
    APIARY_API_KEY: "123456789ab12cd1234a1a1a123a123a"
  ruby:
    version: 2.3.1
dependencies:
  pre:
    - npm install -g dredd@stable
    - gem install apiaryio
    - pip install dredd_hooks
database:
  override:
    - bundle exec rake db:create db:schema:load db:seed
test:
  pre:
    - apiary fetch --api-name=ourAPIName --output=api-description.yml
    - dredd
</code>```

Any help would be most welcome.

答:
I've run into the same issue.  One fix I found was to change the registry for npm to use HTTP instead of HTTPS.  In my circle.yml file I changed my dependencies from:

```<code>dependencies:
  pre:
    - npm install -g dredd@4.1.1
</code>```

to

```<code>dependencies:
  pre:
    - npm config set registry http://registry.npmjs.org/
    - npm install -g dredd@4.1.1
</code>```

Body:
I have a project on CircleCI which started going red (due to failure on installing dredd) at some point. Currently the same exact project (same code, same circle.yml) may fail or succeed at random it seems.

The failure is always in the phase npm install -g dredd@stable with the following error which repeats itself several times and eventually fails the build:

make: Leaving directory /opt/circleci/nodejs/v4.2.6/lib/node_modules/dredd/node_modules/dredd-transactions/node_modules/fury-adapter-apib-parser/node_modules/drafter/node_modules/protagonist/build'
npm ERR! Linux 3.13.0-117-generic
npm ERR! argv "/opt/circleci/nodejs/v4.2.6/bin/node" "/opt/circleci/nodejs/v4.2.6/bin/npm" "install" "-g" "dredd@stable"
npm ERR! node v4.2.6
npm ERR! npm  v2.14.12
npm ERR! code ECONNRESET
npm ERR! errno ECONNRESET
npm ERR! syscall read
npm ERR! network read ECONNRESET
npm ERR! network This is most likely not a problem with npm itself
npm ERR! network and is related to network connectivity.
npm ERR! network In most cases you are behind a proxy or have bad network settings.
npm ERR! network
npm ERR! network If you are behind a proxy, please make sure that the
npm ERR! network 'proxy' config is set properly.  See: 'npm help config'

If I try to rerun the build several times it will succeed at  some point (going Green). The dredd installation then shows up something like this:

make: Leaving directory /opt/circleci/nodejs/v4.2.6/lib/node_modules/dredd/node_modules/dredd-transactions/node_modules/fury-adapter-apib-parser/node_modules/drafter/node_modules/protagonist/build'
/opt/circleci/nodejs/v4.2.6/bin/dredd -> /opt/circleci/nodejs/v4.2.6/lib/node_modules/dredd/bin/dredd
dredd@3.4.5 /opt/circleci/nodejs/v4.2.6/lib/node_modules/dredd
├── caseless@0.12.0
├── clone@2.1.1
├── file@0.2.2

etc', basically installing dredd successfully and moving on to test the build.

Since it seems to fail randomly I don't think the proxy has anything to do with it. Here is the circle.yml file for reference:

machine:
  environment:
    APIARY_API_KEY: "123456789ab12cd1234a1a1a123a123a"
  ruby:
    version: 2.3.1
dependencies:
  pre:
    - npm install -g dredd@stable
    - gem install apiaryio
    - pip install dredd_hooks
database:
  override:
    - bundle exec rake db:create db:schema:load db:seed
test:
  pre:
    - apiary fetch --api-name=ourAPIName --output=api-description.yml
    - dredd

Any help would be most welcome.

Body:
I've run into the same issue.  One fix I found was to change the registry for npm to use HTTP instead of HTTPS.  In my circle.yml file I changed my dependencies from:

dependencies:
  pre:
    - npm install -g dredd@4.1.1

to

dependencies:
  pre:
    - npm config set registry http://registry.npmjs.org/
    - npm install -g dredd@4.1.1


问:
Is it possible to listen for function calls in C# (i.e. treat C# function calls as events)?
I would like to log when functions in my app are called. Is there a way I can listen for functions called and run code on such events?

If so, where do I start looking at how to do this?

答:
If you do not want to scatter your methods with log, consider using an AOP(Aspect Oriented Programming) library to do so.

Here is a blog illustrating this.


问:
Selecting Parent's Child in jQuery
I think all I need is a selector, but can't find one. I want to select the anchor tag, but can only select the li using .parent()...

jQuery:

```<code>$("nav ul li > ul").parent().append('<span class="arrow">↓</span>');
</code>```

HTML:

```<code><li><a href="#">The Events</a>
  <ul>
    <li><a href="#">Schedule</a></li>
    <li><a href="#">Buy Tickets</a></li>
    <li><a href="#">Features</a></li>
  </ul>
</li>
</code>```

The code above puts the arrow on the right lis, but one level to high. I need to target the li's a tag.

答:
Answered myself. Using .children("a") I was able to select the anchor. Final code looked like:

```<code>$("nav ul li > ul").parent().children("a").append('<span class="arrow">↓</span>');
</code>```

Title: Selecting Parent's Child in jQuery

Body:
I think all I need is a selector, but can't find one. I want to select the anchor tag, but can only select the li using .parent()...

jQuery:

$("nav ul li > ul").parent().append('↓');

HTML:

The Events

Schedule

Buy Tickets

Features

The code above puts the arrow on the right lis, but one level to high. I need to target the li's a tag.

Body:
Answered myself. Using .children("a") I was able to select the anchor. Final code looked like:

$("nav ul li > ul").parent().children("a").append('<span class="arrow">&darr;</span>');


问:
'pop' method in Ruby
I've created a 'pop' method to take the last node off of a linked list. However, the issue I'm receiving is that it's not removing the node, it's simply telling me the data in the node that should be removed.

I should preface with I'm using test driven development and the test was written to say 'assert_equal "blop", list.pop. "blop" is the value of the last node. It's great that I got my method to tell me that, but it still doesn't remove the node.

```<code>def pop
 @count -= 1
 return_string = ""
 current_node = @head
 until current_node.next_node == nil
  current_node = current_node.next_node
 end
 return_string << current_node.data + " "
 return_string.strip
 current_node.next_node = Node.new(data)
end
</code>```

My question is how do I return the value of what's being removed, as well as, removing the value from the linked list.

答:
```<code>until current_node.next_node == nil
    current_node = current_node.next_node
end
</code>```

When that loop finishes, current_node is pointing to the last node (the node for which the next node is `nil).

That's the node you should remove, but in order to remove that one, you should point the previous node's next_node to nil.

However, at that point you don't have a reference to the previous node.

You could have another variable to track the previous node so that you can then remove it once you exit the loop.

You can check this related question (not Ruby specific) for ideas on the algorithm.

Linked List implementation for a stack

As a side note, one of the answers on that one implements this as making pop remove the first node of the list (and push add the node to the beginning), which makes it easier (and faster, since you don't go over the whole list each time).

Title: 'pop' method in Ruby

Body:
I've created a 'pop' method to take the last node off of a linked list. However, the issue I'm receiving is that it's not removing the node, it's simply telling me the data in the node that should be removed.

I should preface with I'm using test driven development and the test was written to say 'assert_equal "blop", list.pop. "blop" is the value of the last node. It's great that I got my method to tell me that, but it still doesn't remove the node.

def pop
 @count -= 1
 return_string = ""
 current_node = @head
 until current_node.next_node == nil
  current_node = current_node.next_node
 end
 return_string << current_node.data + " "
 return_string.strip
 current_node.next_node = Node.new(data)
end

My question is how do I return the value of what's being removed, as well as, removing the value from the linked list.

Body:
until current_node.next_node == nil
    current_node = current_node.next_node
end

When that loop finishes, current_node is pointing to the last node (the node for which the next node is `nil).

That's the node you should remove, but in order to remove that one, you should point the previous node's next_node to nil.

However, at that point you don't have a reference to the previous node.

You could have another variable to track the previous node so that you can then remove it once you exit the loop.

You can check this related question (not Ruby specific) for ideas on the algorithm.

Linked List implementation for a stack

As a side note, one of the answers on that one implements this as making pop remove the first node of the list (and push add the node to the beginning), which makes it easier (and faster, since you don't go over the whole list each time).


问:
Connect Docker Containers: Frontend to GraphQL Backend via Docker Compose on the same Host
Suppose I'm on a host machine with docker-compose running 2 containers/services:

backend graphql (ports: 8000:8000)

frontend react (ports: 8081:8081)

In the frontend container, where my react + apollo code lives, I need to set this const:

```<code>// frontend container code
export const APOLLO = {
    uri: 'http://0.0.0.0:8000/graphql' // << not working, what to use here?
};
</code>```

However, the uri value is not able to connect successfully to the backend graphql endpoint. I'm receiving errors such as Error Network error: request to http://0.0.0.0:8000/graphql failed, reason: connect ECONNREFUSED 0.0.0.0:8000

The containers work fine on their own. I am able to navigate to http://0.0.0.0:8000, http://0.0.0.0:8000/graphql, http://0.0.0.0:8081 to interact with them individually. I am also able to enter each container and reach the other via their service name-spaces with ping backend or ping frontend.

However, when I do uri: 'http://backend:8000/graphql' or uri: 'http://backend/graphql' in my code, i get the error Error Network error: only absolute urls are supported.

On docker inspect backend, I get the backend container's IP address as: '172.18.0.5'. Which i tried to plug into the uri as uri: 'http://172.18.0.5/graphql', but I get Error Network error: Network request failed with status 403 - "Forbidden"

How should I connect backend docker container to the frontend within the code given these scenarios?

Thanks!

答:
Fixed it by running the servers locally instead of Docker and found that backend was rejecting frontend entry due to CORS headers not set. Whitelisted frontends' ip and it worked. Tested again in Docker containers with the backend ip http://172.18.0.5/graphql and connection was perfect.

Hope this helps!

Edit: Referring to the container name in the url hostname i.e. http://backend/graphql also works thanks to the docker network bridge setup by docker compose. This is a better solution than hardcoding the docker container ip above.

Body:
Suppose I'm on a host machine with docker-compose running 2 containers/services:

backend graphql (ports: 8000:8000)

frontend react (ports: 8081:8081)

In the frontend container, where my react + apollo code lives, I need to set this const:

// frontend container code
export const APOLLO = {
    uri: 'http://0.0.0.0:8000/graphql' // << not working, what to use here?
};

However, the uri value is not able to connect successfully to the backend graphql endpoint. I'm receiving errors such as Error Network error: request to http://0.0.0.0:8000/graphql failed, reason: connect ECONNREFUSED 0.0.0.0:8000

The containers work fine on their own. I am able to navigate to http://0.0.0.0:8000, http://0.0.0.0:8000/graphql, http://0.0.0.0:8081 to interact with them individually. I am also able to enter each container and reach the other via their service name-spaces with ping backend or ping frontend.

However, when I do uri: 'http://backend:8000/graphql' or uri: 'http://backend/graphql' in my code, i get the error Error Network error: only absolute urls are supported.

On docker inspect backend, I get the backend container's IP address as: '172.18.0.5'. Which i tried to plug into the uri as uri: 'http://172.18.0.5/graphql', but I get Error Network error: Network request failed with status 403 - "Forbidden"

How should I connect backend docker container to the frontend within the code given these scenarios?

Thanks!


问:
Loading xib file into an custom NSView gets embedded inside another custom NSView
I have a custom NSView (called Header) that I am able to load during runtime. However, this custom NSView (Header) gets embedded inside another custom NSView at run time that is bigger and it produces extra space at the bottom (I don't want this extra space). Is there another way to load a xib file that will not have this issue?

This is how it looks like:

Here is how I'm loading the xib file:

```<code>import Cocoa

class Header: NSView {

  @IBOutlet var view: Header!
  @IBOutlet weak var dateLabel: NSTextField!
  override func draw(_ dirtyRect: NSRect) {
    super.draw(dirtyRect)

    // Drawing code here.
  }
  override init(frame frameRect: NSRect) {
    super.init(frame: frameRect)
    var topLevelObjects = NSArray()
    Bundle.main.loadNibNamed("Header", owner: self, topLevelObjects: &topLevelObjects)

    let view = ((topLevelObjects as Array).filter { $0 is NSView })[0] as! NSView
    self.frame = NSRect(x: 0, y:0, width: view.frame.width, height: view.frame.height)
    self.addSubview(self.view)
  }

  required init?(coder: NSCoder) {
    super.init(coder: coder)
  }
}
</code>```

答:
Why you don't add your own header using constraints and views. Is too easy.

```<code>let mainContainer = UIView()
mainContainer.backgroundColor = UIColor.blue
mainContainer.translatesAutoresizingMaskIntoConstraints = false

self.view.addSubview(mainContainer)

let views = ["mainContainer" : mainContainer]

let metrics = ["mainContainerWidth" : self.view.bounds.width]

self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[mainContainer]|", options: [], metrics: metrics, views: views))

self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[mainContainer]|", options: [], metrics: metrics, views: views))
</code>```

Here are a couple of examples of using VF.

I hope this help.

https://github.com/CristianCardosoA/Auto-layout-VF

Body:
I have a custom NSView (called Header) that I am able to load during runtime. However, this custom NSView (Header) gets embedded inside another custom NSView at run time that is bigger and it produces extra space at the bottom (I don't want this extra space). Is there another way to load a xib file that will not have this issue?

This is how it looks like:

Here is how I'm loading the xib file:

import Cocoa

class Header: NSView {

  @IBOutlet var view: Header!
  @IBOutlet weak var dateLabel: NSTextField!
  override func draw(_ dirtyRect: NSRect) {
    super.draw(dirtyRect)

    // Drawing code here.
  }
  override init(frame frameRect: NSRect) {
    super.init(frame: frameRect)
    var topLevelObjects = NSArray()
    Bundle.main.loadNibNamed("Header", owner: self, topLevelObjects: &topLevelObjects)

    let view = ((topLevelObjects as Array).filter { $0 is NSView })[0] as! NSView
    self.frame = NSRect(x: 0, y:0, width: view.frame.width, height: view.frame.height)
    self.addSubview(self.view)
  }

  required init?(coder: NSCoder) {
    super.init(coder: coder)
  }
}

Body:
Why you don't add your own header using constraints and views. Is too easy.

let mainContainer = UIView()
mainContainer.backgroundColor = UIColor.blue
mainContainer.translatesAutoresizingMaskIntoConstraints = false

self.view.addSubview(mainContainer)

let views = ["mainContainer" : mainContainer]

let metrics = ["mainContainerWidth" : self.view.bounds.width]

self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[mainContainer]|", options: [], metrics: metrics, views: views))

self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[mainContainer]|", options: [], metrics: metrics, views: views))

Here are a couple of examples of using VF.

I hope this help.

https://github.com/CristianCardosoA/Auto-layout-VF


问:
New to programing. Trying to add the same text to the end of all data entries in a column using python 3
I am hoping to use Python 3 to write this program but I will use whatever language is best for the job. I have DB named "places" in MySQL. In this DB there is a column containing street names and the number of homes under the column header "locations". I want to add the text ", New York City, NY" to the end of every current record in the column. I know how to write the code for connecting the DB to the program, however, I just am unsure what commands to use to get my desired result. Thank you for the help.

答:
You would use the concat function to add the desired text to the column.

This should be doable in any language that has a module that allows direct SQL interaction with MySQL, including Python 3.


问:
Proper handling of request_uri in double nginx reverse proxy?
So, essentially I am running Joomla in a Docker php7-fpm container, then I have an nginx container where a joomla.conf file is defined as follows:

```<code>#https://docs.joomla.org/nginx

server {
  listen 8081;

  error_log  /var/log/nginx/error.log;
  access_log /var/log/nginx/access.log;

  server_name php-docker.local;

  root /usr/src/joomla;
  index index.php index.html index.htm default.html default.htm;

  location / {
    try_files $uri $uri/ /index.php?$args;
  }

  # deny running scripts inside writable directories
  location ~* /(images|cache|media|logs|tmp)/.*\.(php|pl|py|jsp|asp|sh|cgi)$ {
    return 403;
    error_page 403 /403_error.html;
  }

  location ~ \.php$ {
    fastcgi_pass  joomla:9000;
    fastcgi_index index.php;
    fastcgi_split_path_info ^(.+\.php)(/.+)$;

    include fastcgi_params;
    #include /etc/nginx/fastcgi.conf;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_param PATH_INFO $fastcgi_path_info;
  }
}
</code>```

And this works as expected... going to http://:8081 loads everything correctly.

Now, 8081 is just temporarily exposed in the nginx container, what I essentially want to do is setup a reverse proxy such that http:///joomla will be the final endpoint.

For this, I am struggling with the following conf file:

```<code>server{

  listen 80;
  server_name _;

  location /joomla/ {
    proxy_pass          http://localhost:8081/;

    proxy_set_header    Referer           $http_referer;
    proxy_set_header    X-Forwarded-Port  $server_port;
    proxy_set_header    X-Forwarded-Proto $http_x_forwarded_proto;
    proxy_set_header    Host              $host;
    proxy_set_header    X-Forwarded-For   $proxy_add_x_forwarded_for;
    proxy_set_header    X-Forwarded-Host  $host;
  }

}
</code>```

What happens is that the HTML is served correctly, however, none of the assets are. This is because the URLs in Joomla are generated by a JURI class, which seems to rely on $request_uri, which by when it appears to arrive to Joomla is already lost.

https://github.com/joomla/joomla-cms/blob/6ab2a6e9010e7e04c260b9eba17dc76e866dd3e6/libraries/joomla/uri/uri.php#L87

So every link or reference to a file, script, or css renders like this:

http://localhost/login

http://localhost/images/headers/maple.jpg

Instead of:

http://localhost/joomla/login

http://localhost/joomla/images/headers/maple.jpg

However, when I access the second set of URL, I can access the link/asset without a problem... but of course once again, no images, templates, js or links being rendered correctly.

I prefer not to touch joomla.conf unless something is wrong, as for site.conf I would only like to translate URI segments to map requests to other applications, e.g.:

```<code>/joomla -> localhost:8081
/phpbb -> localhost:8082
/someapp -> localhost:8083
</code>```

答:
The cleanest solution would be to modify your upstreams to provide unique paths for all the resources.

It is generally a much easier task to remove parts of a URL from the upstream (with a unique prefix) than to add extra parts to a non-unique one.  This is because you can always catch the longer URL and know exactly what it refers to, subsequently returning a 301 or 302 redirect to a shorter and more concise version.

On the other hand, faced with a short request URL, like /, it would be difficult to know for sure which app it may refer to (unless you look into the $http_referer variable, too, and then conditionally issue the redirect based on where the URL request comes from), or unless you implement some sort of spaghetti rules to detect which individual URLs refer to which applications (if you go this route, the map directive may come in handy).

Additionally, consider that, security-wise and when cookies get involved, it is not the best practice to run multiple independent applications on a single domain — a compromise in one application can easily lead to security violations in all the other ones.

Body:
So, essentially I am running Joomla in a Docker php7-fpm container, then I have an nginx container where a joomla.conf file is defined as follows:

#https://docs.joomla.org/nginx

server {
  listen 8081;

  error_log  /var/log/nginx/error.log;
  access_log /var/log/nginx/access.log;

  server_name php-docker.local;

  root /usr/src/joomla;
  index index.php index.html index.htm default.html default.htm;

  location / {
    try_files $uri $uri/ /index.php?$args;
  }

  # deny running scripts inside writable directories
  location ~* /(images|cache|media|logs|tmp)/.*\.(php|pl|py|jsp|asp|sh|cgi)$ {
    return 403;
    error_page 403 /403_error.html;
  }

  location ~ \.php$ {
    fastcgi_pass  joomla:9000;
    fastcgi_index index.php;
    fastcgi_split_path_info ^(.+\.php)(/.+)$;

    include fastcgi_params;
    #include /etc/nginx/fastcgi.conf;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_param PATH_INFO $fastcgi_path_info;
  }
}

And this works as expected... going to http://:8081 loads everything correctly.

Now, 8081 is just temporarily exposed in the nginx container, what I essentially want to do is setup a reverse proxy such that http:///joomla will be the final endpoint.

For this, I am struggling with the following conf file:

server{

  listen 80;
  server_name _;

  location /joomla/ {
    proxy_pass          http://localhost:8081/;

    proxy_set_header    Referer           $http_referer;
    proxy_set_header    X-Forwarded-Port  $server_port;
    proxy_set_header    X-Forwarded-Proto $http_x_forwarded_proto;
    proxy_set_header    Host              $host;
    proxy_set_header    X-Forwarded-For   $proxy_add_x_forwarded_for;
    proxy_set_header    X-Forwarded-Host  $host;
  }

}

What happens is that the HTML is served correctly, however, none of the assets are. This is because the URLs in Joomla are generated by a JURI class, which seems to rely on $request_uri, which by when it appears to arrive to Joomla is already lost.

https://github.com/joomla/joomla-cms/blob/6ab2a6e9010e7e04c260b9eba17dc76e866dd3e6/libraries/joomla/uri/uri.php#L87

So every link or reference to a file, script, or css renders like this:

http://localhost/login

http://localhost/images/headers/maple.jpg

Instead of:

http://localhost/joomla/login

http://localhost/joomla/images/headers/maple.jpg

However, when I access the second set of URL, I can access the link/asset without a problem... but of course once again, no images, templates, js or links being rendered correctly.

I prefer not to touch joomla.conf unless something is wrong, as for site.conf I would only like to translate URI segments to map requests to other applications, e.g.:

/joomla -> localhost:8081
/phpbb -> localhost:8082
/someapp -> localhost:8083