问:
Spring Boot 1.5.2 sample returns 404
So I pulled down the Spring Boot Sample Web JSP example. I imported into Eclipse and I tweaked the POM so that it pulled in the parent POM properly but everything else is untouched. But when I hit the URL I get a 404. Below is the POM and is the only thing I've changed. I'm using Eclipse Luna to run it as a Spring App. The log didn't seem to show anything other than resource not found. Verified that the controller's method is getting called, so it's after the "welcome" view name being returned.

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <!-- Your own application should inherit from spring-boot-starter-parent -->
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.2.RELEASE</version>
        <relativePath />
    </parent>
    <artifactId>spring-boot-sample-web-jsp</artifactId>
    <packaging>war</packaging>
    <name>Spring Boot Web JSP Sample</name>
    <description>Spring Boot Web JSP Sample</description>
    <url>http://projects.spring.io/spring-boot/</url>
    <organization>
        <name>Pivotal Software, Inc.</name>
        <url>http://www.spring.io</url>
    </organization>
    <properties>
        <java.version>1.7</java.version>
        <main.basedir>${basedir}/../..</main.basedir>
        <m2eclipse.wtp.contextRoot>/</m2eclipse.wtp.contextRoot>
    </properties>
    <dependencies>
        <!-- Compile -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>
        <!-- Provided -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>provided</scope>
        </dependency>
        <!-- Test -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <configuration>
                    <useSystemClassLoader>false</useSystemClassLoader>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
</code>```

And this is a snippet of my log

```<code>.w.s.m.m.a.ServletInvocableHandlerMethod : Method [sample.jsp.WelcomeController.welcome] returned [welcome]
o.s.w.s.v.ContentNegotiatingViewResolver : Requested media types are [text/html, application/xhtml+xml, image/webp, application/xml;q=0.9, */*;q=0.8] based on Accept header types and producible media types [*/*])
o.s.w.servlet.view.BeanNameViewResolver  : No matching bean found for view name 'welcome'
o.s.b.f.s.DefaultListableBeanFactory     : Invoking afterPropertiesSet() on bean with name 'welcome'
o.s.w.s.v.InternalResourceViewResolver   : Cached view [welcome]
o.s.w.s.v.ContentNegotiatingViewResolver : Returning [org.springframework.web.servlet.view.JstlView: name 'welcome'; URL [/WEB-INF/jsp/welcome.jsp]] based on requested media type 'text/html'
o.s.web.servlet.DispatcherServlet        : Rendering view [org.springframework.web.servlet.view.JstlView: name 'welcome'; URL [/WEB-INF/jsp/welcome.jsp]] in DispatcherServlet with name 'dispatcherServlet'
o.s.web.servlet.view.JstlView            : Rendering view with name 'welcome' with model {time=Wed Mar 15 13:59:42 EDT 2017, message=Hello Phil} and static attributes {}
o.s.web.servlet.view.JstlView            : Added model object 'time' of type [java.util.Date] to request in view with name 'welcome'
o.s.web.servlet.view.JstlView            : Added model object 'message' of type [java.lang.String] to request in view with name 'welcome'
o.s.web.servlet.view.JstlView            : Forwarding to resource [/WEB-INF/jsp/welcome.jsp] in InternalResourceView 'welcome'
o.apache.catalina.core.StandardWrapper   :   Returning non-STM instance
o.s.web.servlet.DispatcherServlet        : Bound request context to thread: org.apache.catalina.core.ApplicationHttpRequest@1077e52
o.s.web.servlet.DispatcherServlet        : DispatcherServlet with name 'dispatcherServlet' processing GET request for [/WEB-INF/jsp/welcome.jsp]
o.s.web.servlet.DispatcherServlet        : Testing handler map [org.springframework.web.servlet.handler.SimpleUrlHandlerMapping@6cee48] in DispatcherServlet with name 'dispatcherServlet'
o.s.w.s.handler.SimpleUrlHandlerMapping  : No handler mapping found for [/WEB-INF/jsp/welcome.jsp]
o.s.web.servlet.DispatcherServlet        : Testing handler map [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping@190641d] in DispatcherServlet with name 'dispatcherServlet'
s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /WEB-INF/jsp/welcome.jsp
o.a.c.loader.WebappClassLoaderBase       : getResource(org/springframework/mail/javamail/mime.types)
o.a.c.loader.WebappClassLoaderBase       :   Delegating to parent classloader sun.misc.Launcher$AppClassLoader@a4be02
o.a.c.loader.WebappClassLoaderBase       :     findResource(org/springframework/mail/javamail/mime.types)
o.a.c.loader.WebappClassLoaderBase       :     --> Resource not found, returning null
o.a.c.loader.WebappClassLoaderBase       :   --> Resource not found, returning null
.PathExtensionContentNegotiationStrategy : Loading default Java Activation Framework FileTypeMap
javax.activation                         : MimetypesFileTypeMap: load HOME
javax.activation                         : MimetypesFileTypeMap: load SYS
javax.activation                         : MimetypesFileTypeMap: load JAR
o.a.c.loader.WebappClassLoaderBase       :     findResources(META-INF/mime.types)
</code>```

答:
Try to remove the <scope>provide</scope> element of spring-boot-starter-tomcat and tomcat-embed-jasper.
I met this problem too and it fix my issue by doing that.

Title: Spring Boot 1.5.2 sample returns 404

Body:
So I pulled down the Spring Boot Sample Web JSP example. I imported into Eclipse and I tweaked the POM so that it pulled in the parent POM properly but everything else is untouched. But when I hit the URL I get a 404. Below is the POM and is the only thing I've changed. I'm using Eclipse Luna to run it as a Spring App. The log didn't seem to show anything other than resource not found. Verified that the controller's method is getting called, so it's after the "welcome" view name being returned.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>

        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.2.RELEASE</version>
        <relativePath />
    </parent>
    <artifactId>spring-boot-sample-web-jsp</artifactId>
    <packaging>war</packaging>
    <name>Spring Boot Web JSP Sample</name>
    <description>Spring Boot Web JSP Sample</description>
    <url>http://projects.spring.io/spring-boot/</url>
    <organization>
        <name>Pivotal Software, Inc.</name>
        <url>http://www.spring.io</url>
    </organization>
    <properties>
        <java.version>1.7</java.version>
        ${basedir}/../..
        <m2eclipse.wtp.contextRoot>/</m2eclipse.wtp.contextRoot>
    </properties>
    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <configuration>
                    <useSystemClassLoader>false</useSystemClassLoader>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

And this is a snippet of my log

.w.s.m.m.a.ServletInvocableHandlerMethod : Method [sample.jsp.WelcomeController.welcome] returned [welcome]
o.s.w.s.v.ContentNegotiatingViewResolver : Requested media types are [text/html, application/xhtml+xml, image/webp, application/xml;q=0.9, */*;q=0.8] based on Accept header types and producible media types [*/*])
o.s.w.servlet.view.BeanNameViewResolver  : No matching bean found for view name 'welcome'
o.s.b.f.s.DefaultListableBeanFactory     : Invoking afterPropertiesSet() on bean with name 'welcome'
o.s.w.s.v.InternalResourceViewResolver   : Cached view [welcome]
o.s.w.s.v.ContentNegotiatingViewResolver : Returning [org.springframework.web.servlet.view.JstlView: name 'welcome'; URL [/WEB-INF/jsp/welcome.jsp]] based on requested media type 'text/html'
o.s.web.servlet.DispatcherServlet        : Rendering view [org.springframework.web.servlet.view.JstlView: name 'welcome'; URL [/WEB-INF/jsp/welcome.jsp]] in DispatcherServlet with name 'dispatcherServlet'
o.s.web.servlet.view.JstlView            : Rendering view with name 'welcome' with model {time=Wed Mar 15 13:59:42 EDT 2017, message=Hello Phil} and static attributes {}
o.s.web.servlet.view.JstlView            : Added model object 'time' of type [java.util.Date] to request in view with name 'welcome'
o.s.web.servlet.view.JstlView            : Added model object 'message' of type [java.lang.String] to request in view with name 'welcome'
o.s.web.servlet.view.JstlView            : Forwarding to resource [/WEB-INF/jsp/welcome.jsp] in InternalResourceView 'welcome'
o.apache.catalina.core.StandardWrapper   :   Returning non-STM instance
o.s.web.servlet.DispatcherServlet        : Bound request context to thread: org.apache.catalina.core.ApplicationHttpRequest@1077e52
o.s.web.servlet.DispatcherServlet        : DispatcherServlet with name 'dispatcherServlet' processing GET request for [/WEB-INF/jsp/welcome.jsp]
o.s.web.servlet.DispatcherServlet        : Testing handler map [org.springframework.web.servlet.handler.SimpleUrlHandlerMapping@6cee48] in DispatcherServlet with name 'dispatcherServlet'
o.s.w.s.handler.SimpleUrlHandlerMapping  : No handler mapping found for [/WEB-INF/jsp/welcome.jsp]
o.s.web.servlet.DispatcherServlet        : Testing handler map [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping@190641d] in DispatcherServlet with name 'dispatcherServlet'
s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /WEB-INF/jsp/welcome.jsp
o.a.c.loader.WebappClassLoaderBase       : getResource(org/springframework/mail/javamail/mime.types)
o.a.c.loader.WebappClassLoaderBase       :   Delegating to parent classloader sun.misc.Launcher$AppClassLoader@a4be02
o.a.c.loader.WebappClassLoaderBase       :     findResource(org/springframework/mail/javamail/mime.types)
o.a.c.loader.WebappClassLoaderBase       :     --> Resource not found, returning null
o.a.c.loader.WebappClassLoaderBase       :   --> Resource not found, returning null
.PathExtensionContentNegotiationStrategy : Loading default Java Activation Framework FileTypeMap
javax.activation                         : MimetypesFileTypeMap: load HOME
javax.activation                         : MimetypesFileTypeMap: load SYS
javax.activation                         : MimetypesFileTypeMap: load JAR
o.a.c.loader.WebappClassLoaderBase       :     findResources(META-INF/mime.types)


来源: stackexchange

问:
Hierarchy Climbing and Descending Unity
I have the following hierarchy on my Player prefab for what will be a very simple multiplayer shooter.

It works this way, the Controller object has the scripts that deal with player input, the PlayerShip object has all of the turning, moving, shooting scripts etc and the Camera is just as it sounds, a camera with a few scripts on it for moving it about.

When a new Player is instantiated the Control script needs to locate its relevant PlayerShip, simple enough.

This can be achieved using the following code:

```<code>_playerShip = gameObject.transform.parent.gameObject.transform.FindChild("PlayerShip").GetComponent<PlayerShip>();
</code>```

Which works fine, the only thing is, to me that looks very clunky, inelegant and brittle. Consequently, I'm wondering if there's a better, more efficient, less ugly way of achieving the same thing?

答:
First of all,

```<code>_playerShip = gameObject.transform.parent.gameObject.transform.FindChild("playerShip").GetComponent<PlayerShip>();
</code>```

is redundant. That can be reduced to

```<code>_playerShip = gameObject.transform.parent.FindChild("playerShip").GetComponent<PlayerShip>();
</code>```

or even use '/' just like you do with folder names.

```<code>_playerShip = GameObject.Find("Player/playerShip").GetComponent<PlayerShip>();
</code>```

Now, instead of instantiating the Object and searching for it later on, you can actually instantiate it and retrieve the reference at the-same time.

```<code>GameObject obj = Instantiate(prefab,Vector3.zero,Quaternion.identity) as GameObject;
_playerShip = obj.GetComponent<PlayerShip>();
</code>```

If it is a network game that you instantiate with Network.Instantiate:

```<code>GameObject obj = Network.Instantiate(prefab,Vector3.zero,Quaternion.identity,0) as GameObject;
_playerShip = obj.GetComponent<PlayerShip>();
</code>```

Now, send the PlayerShip reference to the Control script.

ContentLicense: CC BY-SA 3.0

Title: Hierarchy Climbing and Descending Unity

Body:
I have the following hierarchy on my Player prefab for what will be a very simple multiplayer shooter.

It works this way, the Controller object has the scripts that deal with player input, the PlayerShip object has all of the turning, moving, shooting scripts etc and the Camera is just as it sounds, a camera with a few scripts on it for moving it about.

When a new Player is instantiated the Control script needs to locate its relevant PlayerShip, simple enough.

This can be achieved using the following code:

_playerShip = gameObject.transform.parent.gameObject.transform.FindChild("PlayerShip").GetComponent<PlayerShip>();

Which works fine, the only thing is, to me that looks very clunky, inelegant and brittle. Consequently, I'm wondering if there's a better, more efficient, less ugly way of achieving the same thing?

Body:
First of all,

_playerShip = gameObject.transform.parent.gameObject.transform.FindChild("playerShip").GetComponent<PlayerShip>();

is redundant. That can be reduced to

_playerShip = gameObject.transform.parent.FindChild("playerShip").GetComponent<PlayerShip>();

or even use '/' just like you do with folder names.

_playerShip = GameObject.Find("Player/playerShip").GetComponent<PlayerShip>();

Now, instead of instantiating the Object and searching for it later on, you can actually instantiate it and retrieve the reference at the-same time.

GameObject obj = Instantiate(prefab,Vector3.zero,Quaternion.identity) as GameObject;
_playerShip = obj.GetComponent<PlayerShip>();

If it is a network game that you instantiate with Network.Instantiate:

GameObject obj = Network.Instantiate(prefab,Vector3.zero,Quaternion.identity,0) as GameObject;
_playerShip = obj.GetComponent<PlayerShip>();

Now, send the PlayerShip reference to the Control script.


问:
Randomly generated multidimensional Boolean pointer error
I have this function randomly generating true/false values and assigning them to a multidimensional pointer, then returning the pointer. </p>

```<code>bool** generateMap()
{

    int randNum = 0;
    int X = 7;
    int Y = 7;

    bool** MAP = new bool*[X];
    for (int i = 0; i < X; ++i)
        MAP[i] = new bool[Y];

    for (int x = 0; x < 8; x++)
    {
        int rooms = 0;
        for (int y = 0; y < 8; y++)
        {
                if (rooms < 10)
                {
                    randNum = rand() % 6;
                    switch (randNum)
                    {
                    case 0:
                        MAP[x][y] = true;
                        ++rooms;
                        break;
                    case 1:
                        MAP[x][y] = false;
                        break;
                    case 2:
                        MAP[x][y] = false;
                        break;
                    case 3:
                        MAP[x][y] = false;
                        break;
                    case 4:
                        MAP[x][y] = false;
                        break;
                    case 5:
                        MAP[x][y] = false;
                        break;
                    default:
                        break;
                    }
                }
                else
                {

                }
        }
    }
    return MAP;
}
</code>```

<p>It compiles but there is a run time error, what is wrong with my code? </p>

答:
X and Y both equal 7, but then you say: for (int x = 0; x < 8; x++) - so you are running off the end of the arrays. The arrays go 0..6 but you access index 7.

You would be much better off with for (int x = 0; x < X; x++) - that is the whole point of making those values symbolic rather than just hardcoding 7.

You also stop setting values once you hit "10 rooms" - a comment about using the default value is probably in order (why not break the loop once you have populated 10 rooms?) - last but not least: by using a for in this way, there is no guarantee you'll actually get any rooms. They could all come up false...

Body:
I have this function randomly generating true/false values and assigning them to a multidimensional pointer, then returning the pointer.

bool** generateMap()
{

    int randNum = 0;
    int X = 7;
    int Y = 7;

    bool** MAP = new bool*[X];
    for (int i = 0; i < X; ++i)
        MAP[i] = new bool[Y];

    for (int x = 0; x < 8; x++)
    {
        int rooms = 0;
        for (int y = 0; y < 8; y++)
        {
                if (rooms < 10)
                {
                    randNum = rand() % 6;
                    switch (randNum)
                    {
                    case 0:
                        MAP[x][y] = true;
                        ++rooms;
                        break;
                    case 1:
                        MAP[x][y] = false;
                        break;
                    case 2:
                        MAP[x][y] = false;
                        break;
                    case 3:
                        MAP[x][y] = false;
                        break;
                    case 4:
                        MAP[x][y] = false;
                        break;
                    case 5:
                        MAP[x][y] = false;
                        break;
                    default:
                        break;
                    }
                }
                else
                {

                }
        }
    }
    return MAP;
}

It compiles but there is a run time error, what is wrong with my code?


问:
spring batch Semi-written records count
Is there a way to get the number of written records before an exception occurs in a chunk in spring batch? For example, if my commit interval is 1000, and the first 900 writes are successful, and 901st record failed leading to chunkError, I wanted to update an audit file as 900. Is there any attribute that I can use from stepExecution for this?</p>

答:
Afaik, starting from Spring Batch 2, API related to chunk-oriented processing has changed.

ItemWriter is taking the whole chunk of items as a list.  Therefore, unless the ItemWriter implementation you are using records down the failing item, there is no way the Step itself can know about it as it is all hidden within the ItemWriter.

You may need to check the ItemWriter implementation you are using to see if it is saving any info in anywhere (e.g. in ChunkContext / StepExecutionContext etc)

Title: spring batch Semi-written records count


问:
pandas regex match all items between two sets of white spaces
How can I match everything to include special characters between exactly 3 white spaces to the left and exactly 3 white spaces to the right of a colon? Example denoted with W as a white space.

Example match:

```<code>\\s\\s\\sdata\\sstuff:\\s\\sfound\\ssome([%$)Data\\sas\\swhiteSpace\\s\\s\\s
   data stuff:  found some([%$)Data as whiteSpace
</code>```

Example nonMatch:

```<code>\\s\\sdata\sstuff:\\s\\sfound\\sno\\sdatacause\\sno\\s3\\sspaces\\sbefore\\sor\\safter\\s\\s
  data stuff:  found no datacause no 3 spaces before or after
</code>```

The intent is to expand this to seperate columns from a single column of a pandas dataframe.

Expected output:

```<code>data stuff                                data stuff 2
found some([%$)Data as whiteSpace         if i had more examples for data stuff 2 it would show here
extra random data to add into a outputdf  if i had more examples for data stuff 2 it would show here
</code>```

Original thought was to use something like this but this doesnt quite work.

```<code>"(\\s\\s\\s(.*?)\\:\\s\\s(.*?)\\s\\s\\s)"
</code>```

答:
```<code>(?:^|[^ ])   (.*?)   (?:$|[^ ])
</code>```

Break it down!

(?:^|[^ ]) - Match anything that is either not a space or is the beginning of a line

x   (.*?)  x match anything that is between 3 spaces on either side (x's added so spaces don't disapear)

(?:$|[^ ]) match anything that is not a space or is at the end of a line

Example in regexr

Body:
How can I match everything to include special characters between exactly 3 white spaces to the left and exactly 3 white spaces to the right of a colon? Example denoted with W as a white space.

Example match:

\\s\\s\\sdata\\sstuff:\\s\\sfound\\ssome([%$)Data\\sas\\swhiteSpace\\s\\s\\s
   data stuff:  found some([%$)Data as whiteSpace

Example nonMatch:

\\s\\sdata\sstuff:\\s\\sfound\\sno\\sdatacause\\sno\\s3\\sspaces\\sbefore\\sor\\safter\\s\\s
  data stuff:  found no datacause no 3 spaces before or after

The intent is to expand this to seperate columns from a single column of a pandas dataframe.

Expected output:

data stuff                                data stuff 2
found some([%$)Data as whiteSpace         if i had more examples for data stuff 2 it would show here
extra random data to add into a outputdf  if i had more examples for data stuff 2 it would show here

Original thought was to use something like this but this doesnt quite work.

"(\\s\\s\\s(.*?)\\:\\s\\s(.*?)\\s\\s\\s)"

Body:
(?:^|[^ ])   (.*?)   (?:$|[^ ])

Break it down!

(?:^|[^ ]) - Match anything that is either not a space or is the beginning of a line

x   (.*?)  x match anything that is between 3 spaces on either side (x's added so spaces don't disapear)

(?:$|[^ ]) match anything that is not a space or is at the end of a line

Example in regexr


问:
mongoose schema add new field dynamically, but undefined error?
First of all sorry for my terrible english.

In Node.js, I use mongodb using mongoose.

```<code>const TestASchema = new mongoose.Schema({
  name: {
    type: String
  }
});
TestA = mongoose.model('TestA', TestASchema);
const TestBSchema = new mongoose.Schema({
  name: {
    type: String
  }
});
TestB = mongoose.model('TestB', TestBSchema);
</code>```

In test code,

```<code>mongoose.model('TestA').schema.add({
  abc: {
    type: String,
    default: ''
  }
});
TestA = mongoose.model('TestA');

_testA = {
  name: 'TESTA'
};
testA = new TestA(_testA);

_testB = {
  name: 'TESTB'
};
testB = new TestB(_testB);
testA
.save()
.then(() => testB.save())
.then(() => done())
.catch(chainError => done(chainError));
</code>```

and then,

```<code>const testB2 = new TestB({ name: 'TESTB2' });
const testB3 = new TestB({ name: 'TESTB3' });
testB2
.save()
.then(() => testB3.save())
.then(() => {
  //testA.update({ $pushAll: { values: [testB2, testB3] } });
  testA.set('abc', 'asdfasdf');
  testA
  .save()
  .then((savedTestA) => {
    console.log(savedTestA);
    done();
  });
});
</code>```

it works good. and console log is

```<code>{ __v: 0,
  name: 'TESTA',
  abc: 'asdfasdf',
  testbsa: [],
  _id: 58d9fd904ae344082c38ccf2 }
</code>```

THE PROBLEM is why i can not access using testA.abc but testA.set('abc', '...')?

If I set using testA.abc, not happened. also, console.log(testA.abc) is undefined.

The abc field is just my for my test, real field is testbsa. It's array so it is hard to set value using set function.

1) How can i access using dot? ex) testA.abc
2) If Q1 is impossible, How can i PUSH the value some kind of set?
ex) testA.set('testbsa', values: [])

答:
I solved.

The point is where I register the mongoose plugin.

Once mongoose model is registered, there is no way to switch same model with newly registered plugin.

Body:
First of all sorry for my terrible english.

In Node.js, I use mongodb using mongoose.

const TestASchema = new mongoose.Schema({
  name: {
    type: String
  }
});
TestA = mongoose.model('TestA', TestASchema);
const TestBSchema = new mongoose.Schema({
  name: {
    type: String
  }
});
TestB = mongoose.model('TestB', TestBSchema);

In test code,

mongoose.model('TestA').schema.add({
  abc: {
    type: String,
    default: ''
  }
});
TestA = mongoose.model('TestA');

_testA = {
  name: 'TESTA'
};
testA = new TestA(_testA);

_testB = {
  name: 'TESTB'
};
testB = new TestB(_testB);
testA
.save()
.then(() => testB.save())
.then(() => done())
.catch(chainError => done(chainError));

and then,

const testB2 = new TestB({ name: 'TESTB2' });
const testB3 = new TestB({ name: 'TESTB3' });
testB2
.save()
.then(() => testB3.save())
.then(() => {
  //testA.update({ $pushAll: { values: [testB2, testB3] } });
  testA.set('abc', 'asdfasdf');
  testA
  .save()
  .then((savedTestA) => {
    console.log(savedTestA);
    done();
  });
});

it works good. and console log is

{ __v: 0,
  name: 'TESTA',
  abc: 'asdfasdf',
  testbsa: [],
  _id: 58d9fd904ae344082c38ccf2 }

THE PROBLEM is why i can not access using testA.abc but testA.set('abc', '...')?

If I set using testA.abc, not happened. also, console.log(testA.abc) is undefined.

The abc field is just my for my test, real field is testbsa. It's array so it is hard to set value using set function.

1) How can i access using dot? ex) testA.abc
2) If Q1 is impossible, How can i PUSH the value some kind of set?
ex) testA.set('testbsa', values: [])


问:
shifting everything down in an array as a form of deletion java iterable
so I'm trying to remove an element from an array by shifting everything down after I remove it and this is what I have so far

```<code>for (int i = 0; i < numShapes; i++){
     shapes[i] = shapes[i-1];
     numShapes--;
}
</code>```

so if my array contained
Joe Jen Jess

and I called my .next() and .remove() method it'd look like

Joe Jess null

my .next() method returns the next item in my iterator and my remove method is meant to remove the item

```<code>remove method
 public void remove() throws IllegalStateException {
     if (cursor <= numShapes-1 || cursor == 0){
        throw new IllegalStateException();
     }
     if (numShapes == 0){ throw new NoSuchElementException(); }

     for (int i = 0; i < numShapes; i++){
     shapes[i] = shapes[i-1];
     numShapes--;
}
</code>```

is the implementation of remove correct? does it properly shift the elements once removed?

答:
You need to find the index of the element you want to delete and then shift the other elements using that index and set the last value as null as below sample code:

```<code>int index = -1;
String searchStr = "FindMe";

for (int i = 0; i < array.length; i++) {
    if (searchStr.equals(array[i])) {
        index = i;
        break;
    }
}

if (index > -1) {
    for (int i = index; i < array.length - 1; i++) {
        array[i] = array[i+1];
    }
}

array[array.length - 1] = null;
</code>```

Body:
so I'm trying to remove an element from an array by shifting everything down after I remove it and this is what I have so far

for (int i = 0; i < numShapes; i++){
     shapes[i] = shapes[i-1];
     numShapes--;
}

so if my array contained
Joe Jen Jess

and I called my .next() and .remove() method it'd look like

Joe Jess null

my .next() method returns the next item in my iterator and my remove method is meant to remove the item

remove method
 public void remove() throws IllegalStateException {
     if (cursor <= numShapes-1 || cursor == 0){
        throw new IllegalStateException();
     }
     if (numShapes == 0){ throw new NoSuchElementException(); }

     for (int i = 0; i < numShapes; i++){
     shapes[i] = shapes[i-1];
     numShapes--;
}

is the implementation of remove correct? does it properly shift the elements once removed?

Body:
You need to find the index of the element you want to delete and then shift the other elements using that index and set the last value as null as below sample code:

int index = -1;
String searchStr = "FindMe";

for (int i = 0; i < array.length; i++) {
    if (searchStr.equals(array[i])) {
        index = i;
        break;
    }
}

if (index > -1) {
    for (int i = index; i < array.length - 1; i++) {
        array[i] = array[i+1];
    }
}

array[array.length - 1] = null;


问:
How to add d3.js to angular2
Here is part of my packagke.json:

```<code>"dependencies": {
    "@angular/common": "2.3.0",
    "@angular/compiler": "2.3.0",
    "@angular/compiler-cli": "2.3.0",
    "@angular/core": "2.3.0",
    "@angular/forms": "2.3.0",
    "@angular/http": "2.3.0",
    "@angular/platform-browser": "2.3.0",
    "@angular/platform-browser-dynamic": "2.3.0",
    "@angular/platform-server": "2.3.0",
    "@angular/router": "3.3.0",
    "@angular/upgrade": "2.3.0",
    "angular2-in-memory-web-api": "0.0.21",
    "bootstrap": "^3.3.6",
    "core-js": "^2.4.1",
    "d3": "4.5.0",
    "reflect-metadata": "^0.1.8",
    "rollup-plugin-includepaths": "^0.2.1",
    "rxjs": "5.0.0-beta.12",
    "systemjs": "0.19.41",
    "zone.js": "^0.7.2"
  },
  "devDependencies": {
    "@types/core-js": "^0.9.34",
    "@types/d3": "4.5.0",
</code>```

Here is my system.config.js file:

```<code>paths: {
    'npm':'node_modules',
    'home':  getDocumentBase()
},
// map tells the System loader where to look for things
map: {
  // our app is within the app folder
  app: 'app',

  // angular bundles
  '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
  '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
  '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
  '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
  '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
  '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
  '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
  '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',

  // other libraries
  'rxjs':                       'npm:rxjs',
  'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js',
  'd3': 'npm:d3/build/d3.min.js'

},
</code>```

The npm package is installed fine, and the typings have been installed to node_modules/@types, but when i try to import d3

```<code>import * as D3 from 'd3';
</code>```

I get cannot find module 'd3'.

tsc -v
Version 2.0.10
npm -v
3.10.10

What am I doing wrong here?

THanks!

答:
Try adding the following to src/typings.d.ts:

```<code>declare module 'd3' {
  export * from 'd3-array';
  export * from 'd3-axis';
  export * from 'd3-brush';
  export * from 'd3-chord';
  export * from 'd3-collection';
  export * from 'd3-color';
  export * from 'd3-dispatch';
  export * from 'd3-drag';
  export * from 'd3-dsv';
  export * from 'd3-ease';
  export * from 'd3-force';
  export * from 'd3-format';
  export * from 'd3-geo';
  export * from 'd3-hierarchy';
  export * from 'd3-interpolate';
  export * from 'd3-path';
  export * from 'd3-polygon';
  export * from 'd3-quadtree';
  export * from 'd3-queue';
  export * from 'd3-random';
  export * from 'd3-request';
  export * from 'd3-scale';
  export * from 'd3-selection';
  export * from 'd3-shape';
  export * from 'd3-time';
  export * from 'd3-time-format';
  export * from 'd3-timer';
  export * from 'd3-transition';
  export * from 'd3-voronoi';
  export * from 'd3-zoom';
}
</code>```

It worked for me with the early 2.x angular packages.

However, when angular/cli 1.0 was released I created a new project (which automatically added 4.0), installed d3 and @types/d3 but did not create the typings entry above and it works fine. (I also use webpack - I haven't used systemjs since the CLI switched to webpack)

Good luck!

Title: How to add d3.js to angular2

Body:
Here is part of my packagke.json:

"dependencies": {
    "@angular/common": "2.3.0",
    "@angular/compiler": "2.3.0",
    "@angular/compiler-cli": "2.3.0",
    "@angular/core": "2.3.0",
    "@angular/forms": "2.3.0",
    "@angular/http": "2.3.0",
    "@angular/platform-browser": "2.3.0",
    "@angular/platform-browser-dynamic": "2.3.0",
    "@angular/platform-server": "2.3.0",
    "@angular/router": "3.3.0",
    "@angular/upgrade": "2.3.0",
    "angular2-in-memory-web-api": "0.0.21",
    "bootstrap": "^3.3.6",
    "core-js": "^2.4.1",
    "d3": "4.5.0",
    "reflect-metadata": "^0.1.8",
    "rollup-plugin-includepaths": "^0.2.1",
    "rxjs": "5.0.0-beta.12",
    "systemjs": "0.19.41",
    "zone.js": "^0.7.2"
  },
  "devDependencies": {
    "@types/core-js": "^0.9.34",
    "@types/d3": "4.5.0",

Here is my system.config.js file:

paths: {
    'npm':'node_modules',
    'home':  getDocumentBase()
},
// map tells the System loader where to look for things
map: {
  // our app is within the app folder
  app: 'app',

  // angular bundles
  '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
  '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
  '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
  '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
  '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
  '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
  '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
  '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',

  // other libraries
  'rxjs':                       'npm:rxjs',
  'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js',
  'd3': 'npm:d3/build/d3.min.js'

},

The npm package is installed fine, and the typings have been installed to node_modules/@types, but when i try to import d3

import * as D3 from 'd3';

I get cannot find module 'd3'.

tsc -v
Version 2.0.10
npm -v
3.10.10

What am I doing wrong here?

THanks!

Body:
Try adding the following to src/typings.d.ts:

declare module 'd3' {
  export * from 'd3-array';
  export * from 'd3-axis';
  export * from 'd3-brush';
  export * from 'd3-chord';
  export * from 'd3-collection';
  export * from 'd3-color';
  export * from 'd3-dispatch';
  export * from 'd3-drag';
  export * from 'd3-dsv';
  export * from 'd3-ease';
  export * from 'd3-force';
  export * from 'd3-format';
  export * from 'd3-geo';
  export * from 'd3-hierarchy';
  export * from 'd3-interpolate';
  export * from 'd3-path';
  export * from 'd3-polygon';
  export * from 'd3-quadtree';
  export * from 'd3-queue';
  export * from 'd3-random';
  export * from 'd3-request';
  export * from 'd3-scale';
  export * from 'd3-selection';
  export * from 'd3-shape';
  export * from 'd3-time';
  export * from 'd3-time-format';
  export * from 'd3-timer';
  export * from 'd3-transition';
  export * from 'd3-voronoi';
  export * from 'd3-zoom';
}

It worked for me with the early 2.x angular packages.

However, when angular/cli 1.0 was released I created a new project (which automatically added 4.0), installed d3 and @types/d3 but did not create the typings entry above and it works fine. (I also use webpack - I haven't used systemjs since the CLI switched to webpack)

Good luck!


问:
Instruments Leaks - Not showing my source code
I am attempting to analyze an iPhone application using the Leaks application and everything appears to be working fine, except for when I try to view detailed information about a particular memory leak. Leaks does not appear to be loading my source code.  Looking at the stack view on the right, I can see calls that reference iPhone frameworks, but anything that is referencing source code that I've written is empty.  The screenshot below illustrates my point.  The blocks that are light blue should be referencing my source code.  Has anyone ever had this problem? Is Leaks just not finding my source code/symbols correctly?  Thanks!

EDIT: I am compiling the app using the 'Device - iPhone OS 2.2' with the Debug configuration. I launch Leaks by selecting Run->Start With Performance Tool->Leaks from within Xcode. How would one go about 'making the symbol files available' for Leaks?

(source: andrewgarrison.com)

答:
For iOS 4.0 and higher, the way to fix symbols and turn those useless memory addresses into beautiful file names, function names and line numbers is as follows:

In Xcode, go to Run -> Run with Performance Tool and choose your instrument

After Instruments loads, hit the Stop button to stop recording. Go to File -> Re-Symbolicate Document.

In the new window, click Path and click the plus (+) button to add a new path. Navigate to the folder containing your project file and click Open. Click Symbolicate.

Profit!

I was looking for this for a good month before I finally came upon the solution. I hope this helps some of you!

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 2.5


问:
Want a stored procedure for comma seperated string which is of a column (has 20000 rows ) in a table
I have a table with 20000 rows, and a column that has comma-separated strings in it. I want split each of the comma-separated strings from each row and insert them into a temp table row by row without any duplicates. I want to create a stored procedure for this table with has table name and column as parameters to that stored procedure.

Here is the table

```<code>CREATE TABLE [dbo].[Campaign]
(
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [MISC] [nvarchar](4000) NULL,

    PRIMARY KEY CLUSTERED ([ID] ASC)
                WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
                      IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,
                      ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
</code>```

Here is the data which has

```<code>insert into Campaign(MISC)
values ('h101,h202,h506,h707,h112,h566'),
       ('h101,h102,h508,h113,h456,h678'),
       ('h110,h880,h432,h111,h102,h509,h213'),
       ('h456,h609,h432,h456,h678,h101,h807')
</code>```

I have a the login for single string but I don't know how to deal with these 20000 rows of comma-separated strings in the given column - any help?

答:
A Cross Apply with a a Parse should do the trick

Option 1 - With a UDF

```<code>Select A.ID
      ,B.*
  From Campaign A
  Cross Apply [dbo].[tvf-Str-Parse-8K](A.Misc,',') B
</code>```

Option 2 - Without a UDF

```<code>Select A.ID
      ,B.*
  From Campaign A
  Cross Apply (
                Select RetSeq = Row_Number() over (Order By (Select null))
                      ,RetVal = LTrim(RTrim(B.i.value('(./text())[1]', 'varchar(max)')))
                From  (Select x = Cast('<x>' + replace((Select replace(A.Misc,',','§§Split§§') as [*] For XML Path('')),'§§Split§§','</x><x>')+'</x>' as xml).query('.')) as A
                Cross Apply x.nodes('x') AS B(i)
              ) B
</code>```

Both Return

```<code>ID  RetSeq RetVal
1   1       h101
1   2       h202
1   3       h506
1   4       h707
1   5       h112
1   6       h566
2   1       h101
2   2       h102
2   3       h508
...
4   3       h432
4   4       h456
4   5       h678
4   6       h101
4   7       h807
</code>```

The UDF if Needed

```<code>CREATE FUNCTION [dbo].[tvf-Str-Parse-8K] (@String varchar(max),@Delimiter varchar(25))
Returns Table
As
Return (
    with   cte1(N)   As (Select 1 From (Values(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) N(N)),
           cte2(N)   As (Select Top (IsNull(DataLength(@String),0)) Row_Number() over (Order By (Select NULL)) From (Select N=1 From cte1 a,cte1 b,cte1 c,cte1 d) A ),
           cte3(N)   As (Select 1 Union All Select t.N+DataLength(@Delimiter) From cte2 t Where Substring(@String,t.N,DataLength(@Delimiter)) = @Delimiter),
           cte4(N,L) As (Select S.N,IsNull(NullIf(CharIndex(@Delimiter,@String,s.N),0)-S.N,8000) From cte3 S)

    Select RetSeq = Row_Number() over (Order By A.N)
          ,RetVal = LTrim(RTrim(Substring(@String, A.N, A.L)))
    From   cte4 A
);
--Orginal Source http://www.sqlservercentral.com/articles/Tally+Table/72993/
--Much faster than str-Parse, but limited to 8K
--Select * from [dbo].[udf-Str-Parse-8K]('Dog,Cat,House,Car',',')
--Select * from [dbo].[udf-Str-Parse-8K]('John||Cappelletti||was||here','||')
--Performance On a 5,000 random sample -8K 77.8ms, -1M 79ms (+1.16), -- 91.66ms (+13.8)
</code>```

Body:
I have a table with 20000 rows, and a column that has comma-separated strings in it. I want split each of the comma-separated strings from each row and insert them into a temp table row by row without any duplicates. I want to create a stored procedure for this table with has table name and column as parameters to that stored procedure.

Here is the table

CREATE TABLE [dbo].[Campaign]
(
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [MISC] [nvarchar](4000) NULL,

    PRIMARY KEY CLUSTERED ([ID] ASC)
                WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
                      IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,
                      ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

Here is the data which has

insert into Campaign(MISC)
values ('h101,h202,h506,h707,h112,h566'),
       ('h101,h102,h508,h113,h456,h678'),
       ('h110,h880,h432,h111,h102,h509,h213'),
       ('h456,h609,h432,h456,h678,h101,h807')

I have a the login for single string but I don't know how to deal with these 20000 rows of comma-separated strings in the given column - any help?

Body:
A Cross Apply with a a Parse should do the trick

Option 1 - With a UDF

Select A.ID
      ,B.*
  From Campaign A
  Cross Apply [dbo].[tvf-Str-Parse-8K](A.Misc,',') B

Option 2 - Without a UDF

Select A.ID
      ,B.*
  From Campaign A
  Cross Apply (
                Select RetSeq = Row_Number() over (Order By (Select null))
                      ,RetVal = LTrim(RTrim(B.i.value('(./text())[1]', 'varchar(max)')))
                From  (Select x = Cast('<x>' + replace((Select replace(A.Misc,',','§§Split§§') as [*] For XML Path('')),'§§Split§§','</x><x>')+'</x>' as xml).query('.')) as A
                Cross Apply x.nodes('x') AS B(i)
              ) B

Both Return

ID  RetSeq RetVal
1   1       h101
1   2       h202
1   3       h506
1   4       h707
1   5       h112
1   6       h566
2   1       h101
2   2       h102
2   3       h508
...
4   3       h432
4   4       h456
4   5       h678
4   6       h101
4   7       h807

The UDF if Needed

CREATE FUNCTION [dbo].[tvf-Str-Parse-8K] (@String varchar(max),@Delimiter varchar(25))
Returns Table
As
Return (
    with   cte1(N)   As (Select 1 From (Values(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) N(N)),
           cte2(N)   As (Select Top (IsNull(DataLength(@String),0)) Row_Number() over (Order By (Select NULL)) From (Select N=1 From cte1 a,cte1 b,cte1 c,cte1 d) A ),
           cte3(N)   As (Select 1 Union All Select t.N+DataLength(@Delimiter) From cte2 t Where Substring(@String,t.N,DataLength(@Delimiter)) = @Delimiter),
           cte4(N,L) As (Select S.N,IsNull(NullIf(CharIndex(@Delimiter,@String,s.N),0)-S.N,8000) From cte3 S)

    Select RetSeq = Row_Number() over (Order By A.N)
          ,RetVal = LTrim(RTrim(Substring(@String, A.N, A.L)))
    From   cte4 A
);
--Orginal Source http://www.sqlservercentral.com/articles/Tally+Table/72993/
--Much faster than str-Parse, but limited to 8K
--Select * from [dbo].[udf-Str-Parse-8K]('Dog,Cat,House,Car',',')
--Select * from [dbo].[udf-Str-Parse-8K]('John||Cappelletti||was||here','||')
--Performance On a 5,000 random sample -8K 77.8ms, -1M 79ms (+1.16), -- 91.66ms (+13.8)


问:
Render JSON response using Django's render()
I am working my way through Django's tutorial but failing to display an API response using Django's render() function.

models.py

```<code>...
class MF_Version():
    def get_MF_Version(self):
        url = 'https://www.mediafire.com/api/1.5/system/get_version.php?response_format=json'
        r = requests.get(url)
        return r
...
</code>```

views.py

```<code>...
def view_Version(request):
    hr = HttpResponse(MF_Version().get_MF_Version())
    return render(request, 'mediafire/version.html', {'hr': hr})
    # return hr
...
</code>```

version.html

```<code>{% if 1 %}
    {{ hr }}
{% endif %}
</code>```

Browser output:

```<code><HttpResponse status_code=200, "text/html; charset=utf-8">
</code>```

MefiaFire response:

```<code>{"response":{"action":"system\/get_version","current_api_version":"1.5","result":"Success"}}
</code>```

If I comment out return render(...) in the view.py file and replace it with return hr, I do see the JSON response from MediaFire, but I cannot figure out how to access action, current_api_version and result in the HTML template.

Any help is appreciated.

答:
Use JsonResponse, which is available since Django 1.7

```<code>from django.http import JsonResponse

def view_Version(request):
    return JsonResponse(MF_Version().get_MF_Version())
</code>```

You don't need render at all.

If you need render write it as follows (untested):

```<code>{% for x in hr %}
    {{ x }}: {{ hr.x }}
{% endfor %}
</code>```

and your python code will look like:

```<code>import json
from django.http import JsonResponse

def view_Version(request):
    hr = JsonResponse(MF_Version().get_MF_Version())
    return render(request, 'mediafire/version.html', {'hr': json.loads(hr)})
</code>```

Body:
I am working my way through Django's tutorial but failing to display an API response using Django's render() function.

models.py

...
class MF_Version():
    def get_MF_Version(self):
        url = 'https://www.mediafire.com/api/1.5/system/get_version.php?response_format=json'
        r = requests.get(url)
        return r
...

views.py

...
def view_Version(request):
    hr = HttpResponse(MF_Version().get_MF_Version())
    return render(request, 'mediafire/version.html', {'hr': hr})
    # return hr
...

version.html

{% if 1 %}
    {{ hr }}
{% endif %}

Browser output:

<HttpResponse status_code=200, "text/html; charset=utf-8">

MefiaFire response:

{"response":{"action":"system\/get_version","current_api_version":"1.5","result":"Success"}}

If I comment out return render(...) in the view.py file and replace it with return hr, I do see the JSON response from MediaFire, but I cannot figure out how to access action, current_api_version and result in the HTML template.

Any help is appreciated.

Body:
Use JsonResponse, which is available since Django 1.7

from django.http import JsonResponse

def view_Version(request):
    return JsonResponse(MF_Version().get_MF_Version())

You don't need render at all.

If you need render write it as follows (untested):

{% for x in hr %}
    {{ x }}: {{ hr.x }}
{% endfor %}

and your python code will look like:

import json
from django.http import JsonResponse

def view_Version(request):
    hr = JsonResponse(MF_Version().get_MF_Version())
    return render(request, 'mediafire/version.html', {'hr': json.loads(hr)})


问:
How do I remove the white background and title of my pop up window?
I need to remove  the white background and the blue panel

答:
TWO way to remove toolbar

In your activity.java

1、extends Activity is instead of extends AppCompatActivity

2、still use extends AppCompatActivityand put getSupportActionBar().hide(); in your onCreate method.

remove the white backgroud  have three way

1、Try to adjust your xml

2、put android:theme="@android:style/Theme.Translucent" in your AndroidManifest

3、set alpha to your activity v.getBackground().setAlpha(0);

//v is Id of your activity View v = findViewById(R.id.activity);


问:
Spring Boot JPA bootstrapping the database
When using Spring Boot JPA (Hibernate), what is the best way to bootstrap the database with some seed data (MySQL in this case)? For example in Grails you can use the bootstrap.groovy file to accomplish this. I couldn't feel out a real consensus out there on what the best way to go about this is as in best practices.

答: You can simply create a file in resources folder, named it schema.sql and put your MySQL DB script in there. When your application start, schema.sql will be loaded automatically


问:
How to get NHibernate SchemaExport to create SQL Server Timestamp columns?
I'm using the NHibernate HBM2DDL SchemaExport tool to generate my database from my entity objects, and I want to use SQL Server Timestamp columns for optimisitic concurrency.

I've added properties to my entity object that look like this:

public virtual byte[] Timestamp { get; set; }

NHibernate will generate the Timestamp column, but the type is varbinary(8000).  I would rather use the Timestamp type in SQL Server because that will increment itself if someone changes something in the database (outside of NHibernate).  Anyone know if this possible and how I can make this work?

(FWIW, I have followed the instructions found here for getting timestamp columns to work with Fluent NHibernate, but it doesn't appear that this stuff would have anything to do with the SchemaExport.)

答:
Using FluentNHibernate, I got this to work:
(Some of the values are purposely not-named-to-convention, to avoid ambiguity.)

```<code>public partial class PetStore //: IPetStore
{

    public PetStore()
    { /*Constructor*/      }

    public virtual Guid? PetStoreUUID { get; set; }
    public virtual byte[] TheVersionProperty { get; set; }
    public virtual string PetStoreName { get; set; }
    public virtual DateTime CreateDate { get; set; }

}

public class PetStoreMap : ClassMap<PetStore>
{
    public PetStoreMap()
    {
        Id(x => x.PetStoreUUID).GeneratedBy.GuidComb();

        OptimisticLock.Version();
        Version(x => x.TheVersionProperty)
            .Column("MyVersionColumn")
            .Not.Nullable()
            .CustomSqlType("timestamp")
            .Generated.Always();

            Map(x => x.PetStoreName);
            Map(x => x.CreateDate);
    }
}
</code>```

My tests worked, and I did not get the dreaded
"“Cannot update a timestamp column”"
exception.

My DDL shows up as :

```<code>CREATE TABLE [dbo].[PetStore](
    [PetStoreUUID] [uniqueidentifier] NOT NULL,
    [MyVersionColumn] [timestamp] NOT NULL,
    [PetStoreName] [nvarchar](255) NULL,
    [CreateDate] [datetime] NULL)
</code>```

Body:
Using FluentNHibernate, I got this to work:
(Some of the values are purposely not-named-to-convention, to avoid ambiguity.)

public partial class PetStore //: IPetStore
{

    public PetStore()
    { /*Constructor*/      }

    public virtual Guid? PetStoreUUID { get; set; }
    public virtual byte[] TheVersionProperty { get; set; }
    public virtual string PetStoreName { get; set; }
    public virtual DateTime CreateDate { get; set; }

}

public class PetStoreMap : ClassMap<PetStore>
{
    public PetStoreMap()
    {
        Id(x => x.PetStoreUUID).GeneratedBy.GuidComb();

        OptimisticLock.Version();
        Version(x => x.TheVersionProperty)
            .Column("MyVersionColumn")
            .Not.Nullable()
            .CustomSqlType("timestamp")
            .Generated.Always();

            Map(x => x.PetStoreName);
            Map(x => x.CreateDate);
    }
}

My tests worked, and I did not get the dreaded
"“Cannot update a timestamp column”"
exception.

My DDL shows up as :

CREATE TABLE [dbo].[PetStore](
    [PetStoreUUID] [uniqueidentifier] NOT NULL,
    [MyVersionColumn] [timestamp] NOT NULL,
    [PetStoreName] [nvarchar](255) NULL,
    [CreateDate] [datetime] NULL)


问:
How to extract multiple words from a line using shell script
I need to extract the name of root CN of a website stored inside a file as shown below.

```<code>google.com   CN=Google Internet Authority G2
youtube.com   CN=Google Internet Authority G2
</code>```

I want to extract this portion from the line "Google Internet Authority G2" and count the occurrence in the file.

I tried using this command, but I don't know the proper regex to be used for it. Can somebody help?

```<code>cat RootCertificates | tr -d '*CN='  | sort | uniq -c
</code>```

答:
If you are guaranteed to have CN= on every line, a simple cut would suffice and there is no need for a regex:

```<code>cut -f2 -d= RootCertificates | sort | uniq -c
</code>```

For your file, the output is:

```<code>  2 Google Internet Authority G2
</code>```

Body:
I need to extract the name of root CN of a website stored inside a file as shown below.

google.com   CN=Google Internet Authority G2
youtube.com   CN=Google Internet Authority G2

I want to extract this portion from the line "Google Internet Authority G2" and count the occurrence in the file.

I tried using this command, but I don't know the proper regex to be used for it. Can somebody help?

cat RootCertificates | tr -d '*CN='  | sort | uniq -c

Body:
If you are guaranteed to have CN= on every line, a simple cut would suffice and there is no need for a regex:

cut -f2 -d= RootCertificates | sort | uniq -c

For your file, the output is:

  2 Google Internet Authority G2


问:
What is the difference between ActivityTestRule and IntentTestRule
while exploring Testing I came across ActivityTestRule and IntentTestRule as far as i have understood is this that IntentTestRule are an extension of ActivityTestRule and are used in Espresso Intents.

But at the core what is the real purpose of using these testing rules.

答:
The purpose is:

to initialize Espresso-Intents before each test annotated with @Test and
  releases Espresso-Intents after each test run. The following code snippet is an example of an IntentsTestRule:

```<code>@Rule
public IntentsTestRule<MyActivity> intentsTestRule =
        new IntentsTestRule<>(MyActivity.class);
</code>```

Alternatively,

you can use ActivityTestRule instead of IntentsTestRule and then in
  your @Before and @After manually call Intents.init() and
  Intents.release() respectively.

```<code>@Override
protected void afterActivityLaunched() {
    Intents.init();
    super.afterActivityLaunched();
}

@Override
protected void afterActivityFinished() {
    super.afterActivityFinished();
    Intents.release();
}
</code>```

And the purpose of Espresso-intents is

to enable validation and stubbing of Intents sent out by the
  application under test. It’s like Mockito, but for Android Intents.

Body:
The purpose is:

to initialize Espresso-Intents before each test annotated with @Test and
  releases Espresso-Intents after each test run. The following code snippet is an example of an IntentsTestRule:

@Rule
public IntentsTestRule<MyActivity> intentsTestRule =
        new IntentsTestRule<>(MyActivity.class);

Alternatively,

you can use ActivityTestRule instead of IntentsTestRule and then in
  your @Before and @After manually call Intents.init() and
  Intents.release() respectively.

@Override
protected void afterActivityLaunched() {
    Intents.init();
    super.afterActivityLaunched();
}

@Override
protected void afterActivityFinished() {
    super.afterActivityFinished();
    Intents.release();
}

And the purpose of Espresso-intents is

to enable validation and stubbing of Intents sent out by the
  application under test. It’s like Mockito, but for Android Intents.


问:
Unexpected Non-Void Value In Void Function (Swift 3.0)
I am trying to return the annotations array but I'm getting the error below at my return statement.

Unexpected non-void value in void function

I have done some research and found that I might be trying to return with-in a completion handler but can't seem to find a way around it.

```<code>func getAnnotations() {

    //The php file connects the Database and Swift
    let request = NSMutableURLRequest(url: NSURL(string: "https://test.com/pull.php")! as URL)

    //Receiver's HTTP request method
    request.httpMethod = "POST"

    let task = URLSession.shared.dataTask(with: request as URLRequest) {
        old_data, response, error in

        //Error Checking
        if error != nil {
            print("error=\(error)")
            return
        }

        //Response string built up
        let responseString = NSString(data: old_data!, encoding: String.Encoding.utf8.rawValue)
        print("responseString = \(responseString)")

        //Manipulating JSON data
        do {
            if let new_data = old_data,
            let json = try JSONSerialization.jsonObject(with: new_data) as? [String: Any],
            let buildings = json["buildings"] as? [[String: Any]] {

                var annotations: [ARAnnotation] = []

                for building in buildings {

                    let BUILDING_ID = "BuildingID"
                    let BUILDING_NAME = "BuildingName"
                    let BUILDING_INFO = "BuildingInfo"
                    let BUILDING_LAT = "Latitude"
                    let BUILDING_LNG = "Longitude"

                    let IdString:String = building[BUILDING_ID] as! String
                    let NameString:String = building[BUILDING_NAME] as! String
                    let InfoString:String = building[BUILDING_INFO] as! String

                    let LatString:String = building[BUILDING_LAT] as! String
                    let LatDouble:Double = Double(LatString)!

                    let LngString:String = building[BUILDING_LNG] as! String
                    let LngDouble:Double = Double(LngString)!

                    let location:CLLocationCoordinate2D = CLLocationCoordinate2DMake(LatDouble, LngDouble)

                    let annotation = ARAnnotation()
                    annotation.location = CLLocation(latitude: LatDouble, longitude: LngDouble)
                    annotation.title = "POI: \(NameString)"
                    annotations.append(annotation)

                    return annotations
                    //error
                }
            }
        } catch {
            print(error)
        }
    }
    task.resume()
}
</code>```

My goal of this function is to be able to pull out the variables holding my data (annotations, location, NameString, InfoString...) and use them in another function.

If there is another way rather than a simple return I would love to hear.

Thanks

答:
This is a Network task, you shouldn't return anything. Because, it takes some time to load data, so you always get an empty array when you call the function. Let use a closure as a completion handler, like this:

```<code>func getAnnotations(completion: @escaping (_ annotations: [ARAnnotation], _ error: Error?) -> Void) {

    //The php file connects the Database and Swift
    let request = NSMutableURLRequest(url: NSURL(string: "https://test.com/pull.php")! as URL)

    //Receiver's HTTP request method
    request.httpMethod = "POST"

    let task = URLSession.shared.dataTask(with: request as URLRequest) {
        old_data, response, error in

        //Error Checking
        if error != nil {
            print("error=\(error)")
            return
        }

        //Response string built up
        let responseString = NSString(data: old_data!, encoding: String.Encoding.utf8.rawValue)
        print("responseString = \(responseString)")

        //Manipulating JSON data
        do {
            if let new_data = old_data,
                let json = try JSONSerialization.jsonObject(with: new_data) as? [String: Any],
                let buildings = json["buildings"] as? [[String: Any]] {

                var annotations: [ARAnnotation] = []

                for building in buildings {

                    let BUILDING_ID = "BuildingID"
                    let BUILDING_NAME = "BuildingName"
                    let BUILDING_INFO = "BuildingInfo"
                    let BUILDING_LAT = "Latitude"
                    let BUILDING_LNG = "Longitude"

                    let IdString:String = building[BUILDING_ID] as! String
                    let NameString:String = building[BUILDING_NAME] as! String
                    let InfoString:String = building[BUILDING_INFO] as! String

                    let LatString:String = building[BUILDING_LAT] as! String
                    let LatDouble:Double = Double(LatString)!

                    let LngString:String = building[BUILDING_LNG] as! String
                    let LngDouble:Double = Double(LngString)!

                    let location:CLLocationCoordinate2D = CLLocationCoordinate2DMake(LatDouble, LngDouble)

                    let annotation = ARAnnotation()
                    annotation.location = CLLocation(latitude: LatDouble, longitude: LngDouble)
                    annotation.title = "POI: \(NameString)"
                    annotations.append(annotation)

                    completion(annotations, nil)
                    //error
                }
            }
        } catch {
            print(error)
            completion([], error)
        }
    }
    task.resume()
}
</code>```

And use it like this:

```<code>getAnnotations() { (annotations, error) in

    // TODO: something
    print("annotations: \(annotations), error: \(error)")
}
</code>```

Body:
I am trying to return the annotations array but I'm getting the error below at my return statement.

Unexpected non-void value in void function

I have done some research and found that I might be trying to return with-in a completion handler but can't seem to find a way around it.

func getAnnotations() {

    //The php file connects the Database and Swift
    let request = NSMutableURLRequest(url: NSURL(string: "https://test.com/pull.php")! as URL)

    //Receiver's HTTP request method
    request.httpMethod = "POST"

    let task = URLSession.shared.dataTask(with: request as URLRequest) {
        old_data, response, error in

        //Error Checking
        if error != nil {
            print("error=\(error)")
            return
        }

        //Response string built up
        let responseString = NSString(data: old_data!, encoding: String.Encoding.utf8.rawValue)
        print("responseString = \(responseString)")

        //Manipulating JSON data
        do {
            if let new_data = old_data,
            let json = try JSONSerialization.jsonObject(with: new_data) as? [String: Any],
            let buildings = json["buildings"] as? [[String: Any]] {

                var annotations: [ARAnnotation] = []

                for building in buildings {

                    let BUILDING_ID = "BuildingID"
                    let BUILDING_NAME = "BuildingName"
                    let BUILDING_INFO = "BuildingInfo"
                    let BUILDING_LAT = "Latitude"
                    let BUILDING_LNG = "Longitude"

                    let IdString:String = building[BUILDING_ID] as! String
                    let NameString:String = building[BUILDING_NAME] as! String
                    let InfoString:String = building[BUILDING_INFO] as! String

                    let LatString:String = building[BUILDING_LAT] as! String
                    let LatDouble:Double = Double(LatString)!

                    let LngString:String = building[BUILDING_LNG] as! String
                    let LngDouble:Double = Double(LngString)!

                    let location:CLLocationCoordinate2D = CLLocationCoordinate2DMake(LatDouble, LngDouble)

                    let annotation = ARAnnotation()
                    annotation.location = CLLocation(latitude: LatDouble, longitude: LngDouble)
                    annotation.title = "POI: \(NameString)"
                    annotations.append(annotation)

                    return annotations
                    //error
                }
            }
        } catch {
            print(error)
        }
    }
    task.resume()
}

My goal of this function is to be able to pull out the variables holding my data (annotations, location, NameString, InfoString...) and use them in another function.

If there is another way rather than a simple return I would love to hear.

Thanks

Body:
This is a Network task, you shouldn't return anything. Because, it takes some time to load data, so you always get an empty array when you call the function. Let use a closure as a completion handler, like this:

func getAnnotations(completion: @escaping (_ annotations: [ARAnnotation], _ error: Error?) -> Void) {

    //The php file connects the Database and Swift
    let request = NSMutableURLRequest(url: NSURL(string: "https://test.com/pull.php")! as URL)

    //Receiver's HTTP request method
    request.httpMethod = "POST"

    let task = URLSession.shared.dataTask(with: request as URLRequest) {
        old_data, response, error in

        //Error Checking
        if error != nil {
            print("error=\(error)")
            return
        }

        //Response string built up
        let responseString = NSString(data: old_data!, encoding: String.Encoding.utf8.rawValue)
        print("responseString = \(responseString)")

        //Manipulating JSON data
        do {
            if let new_data = old_data,
                let json = try JSONSerialization.jsonObject(with: new_data) as? [String: Any],
                let buildings = json["buildings"] as? [[String: Any]] {

                var annotations: [ARAnnotation] = []

                for building in buildings {

                    let BUILDING_ID = "BuildingID"
                    let BUILDING_NAME = "BuildingName"
                    let BUILDING_INFO = "BuildingInfo"
                    let BUILDING_LAT = "Latitude"
                    let BUILDING_LNG = "Longitude"

                    let IdString:String = building[BUILDING_ID] as! String
                    let NameString:String = building[BUILDING_NAME] as! String
                    let InfoString:String = building[BUILDING_INFO] as! String

                    let LatString:String = building[BUILDING_LAT] as! String
                    let LatDouble:Double = Double(LatString)!

                    let LngString:String = building[BUILDING_LNG] as! String
                    let LngDouble:Double = Double(LngString)!

                    let location:CLLocationCoordinate2D = CLLocationCoordinate2DMake(LatDouble, LngDouble)

                    let annotation = ARAnnotation()
                    annotation.location = CLLocation(latitude: LatDouble, longitude: LngDouble)
                    annotation.title = "POI: \(NameString)"
                    annotations.append(annotation)

                    completion(annotations, nil)
                    //error
                }
            }
        } catch {
            print(error)
            completion([], error)
        }
    }
    task.resume()
}

And use it like this:

getAnnotations() { (annotations, error) in

    // TODO: something
    print("annotations: \(annotations), error: \(error)")
}


问:
How to draw on top of an image in Java?
I used JFrame to import and display an image, and used mousemotionlistener to detect the mouse clicks, and I want to be able to draw on top of the image. I want to be able to, if the user makes a click, make that pixel a certain color while preserving the rest of the image, however, I couldn't find out how to use Graphics to do so without deleting the rest of the image or opening a new window. </p>

```<code>public class Simple extends JFrame{
  static ImageIcon icon;
  static JFrame myframe;
  static JLabel mylabel;
  static BufferedImage image = null;
  public static void main(String[] args) {
    try{
      image = ImageIO.read(new File("mypic.png"));
    }
    catch (IOException e) {
      e.printStackTrace();
    }
    icon=new ImageIcon(image);
    myframe=new JFrame();
    myframe.setSize(200,200);
    myframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    mylabel=new JLabel();
    mylabel.setIcon(icon);
    myframe.getContentPane().add(mylabel);
    myframe.pack();
    Container container = myframe.getContentPane();
    MouseMotionEvents3 mousemotion = new MouseMotionEvents3();
    container.add(mousemotion);
    myframe.setVisible(true);
    while(1 == 1) {
      if(mousemotion.signal == true) {
        System.out.println("second message");
        mousemotion.signal = false;
      }
    }
  }
}
  class MouseMotionEvents3 extends JPanel implements MouseListener,
    MouseMotionListener {
    public boolean signal;
    public MouseMotionEvents3() {
      addMouseListener(this);
      addMouseMotionListener(this);
      signal = false;
    }
    public void mouseClicked(MouseEvent me) {
     // System.out.println("i hate you");
    }

    public void mouseEntered(MouseEvent me) {
    }

    public void mouseExited(MouseEvent me) {
    }

    public void mousePressed(MouseEvent me) {
      signal = true;
      System.out.println("message");
    }

    public void mouseReleased(MouseEvent me) {
    }

    public void mouseDragged(MouseEvent me) {
    }

    public void mouseMoved(MouseEvent me) {
    }
  }
</code>```

答:
I would highly recommend that you start by having a read through Performing Custom Painting and the 2D Graphics Trail, they will provide you with a starting point.

There are a number of ways you might achieve this, this example simply keeps track of the click points and draws dots over the top of the image

```<code>import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private List<Point> points;
        private BufferedImage image;

        public TestPane() {
            points = new ArrayList<>(25);
            try {
                image = ImageIO.read(new File("/Users/shanewhitehead/Desktop/Screen Shot 2017-03-09 at 1.55.18 pm.png"));
            } catch (IOException ex) {
                ex.printStackTrace();
            }

            addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    points.add(e.getPoint());
                    repaint();
                }
            });
        }

        @Override
        public Dimension getPreferredSize() {
            return image == null ? new Dimension(200, 200) : new Dimension(image.getWidth(), image.getHeight());
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            if (image != null) {
                g2d.drawImage(image, 0, 0, this);
            }
            g2d.setColor(Color.RED);
            for (Point p : points) {
                g2d.fillOval(p.x - 4, p.y - 4, 8, 8);
            }
            g2d.dispose();
        }

    }

}
</code>```

This example draws the dots directly to the image itself...

```<code>import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private BufferedImage image;

        public TestPane() {
            try {
                image = ImageIO.read(new File("/Users/shanewhitehead/Desktop/Screen Shot 2017-03-09 at 1.55.18 pm.png"));
            } catch (IOException ex) {
                ex.printStackTrace();
            }

            addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    if (image != null) {
                        Point p = e.getPoint();
                        Graphics2D g2d = image.createGraphics();
                        g2d.setColor(Color.RED);
                        g2d.fillOval(p.x - 4, p.y - 4, 8, 8);
                        g2d.dispose();
                        repaint();
                    }
                }
            });
        }

        @Override
        public Dimension getPreferredSize() {
            return image == null ? new Dimension(200, 200) : new Dimension(image.getWidth(), image.getHeight());
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            g2d.drawImage(image, 0, 0, this);
            g2d.dispose();
        }

    }

}
</code>```

In both cases, they simply make use of the Graphics2D API

Title: How to draw on top of an image in Java?

Body:
I used JFrame to import and display an image, and used mousemotionlistener to detect the mouse clicks, and I want to be able to draw on top of the image. I want to be able to, if the user makes a click, make that pixel a certain color while preserving the rest of the image, however, I couldn't find out how to use Graphics to do so without deleting the rest of the image or opening a new window.

public class Simple extends JFrame{
  static ImageIcon icon;
  static JFrame myframe;
  static JLabel mylabel;
  static BufferedImage image = null;
  public static void main(String[] args) {
    try{
      image = ImageIO.read(new File("mypic.png"));
    }
    catch (IOException e) {
      e.printStackTrace();
    }
    icon=new ImageIcon(image);
    myframe=new JFrame();
    myframe.setSize(200,200);
    myframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    mylabel=new JLabel();
    mylabel.setIcon(icon);
    myframe.getContentPane().add(mylabel);
    myframe.pack();
    Container container = myframe.getContentPane();
    MouseMotionEvents3 mousemotion = new MouseMotionEvents3();
    container.add(mousemotion);
    myframe.setVisible(true);
    while(1 == 1) {
      if(mousemotion.signal == true) {
        System.out.println("second message");
        mousemotion.signal = false;
      }
    }
  }
}
  class MouseMotionEvents3 extends JPanel implements MouseListener,
    MouseMotionListener {
    public boolean signal;
    public MouseMotionEvents3() {
      addMouseListener(this);
      addMouseMotionListener(this);
      signal = false;
    }
    public void mouseClicked(MouseEvent me) {
     // System.out.println("i hate you");
    }

    public void mouseEntered(MouseEvent me) {
    }

    public void mouseExited(MouseEvent me) {
    }

    public void mousePressed(MouseEvent me) {
      signal = true;
      System.out.println("message");
    }

    public void mouseReleased(MouseEvent me) {
    }

    public void mouseDragged(MouseEvent me) {
    }

    public void mouseMoved(MouseEvent me) {
    }
  }

Body:
I would highly recommend that you start by having a read through Performing Custom Painting and the 2D Graphics Trail, they will provide you with a starting point.

There are a number of ways you might achieve this, this example simply keeps track of the click points and draws dots over the top of the image

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private List<Point> points;
        private BufferedImage image;

        public TestPane() {
            points = new ArrayList<>(25);
            try {
                image = ImageIO.read(new File("/Users/shanewhitehead/Desktop/Screen Shot 2017-03-09 at 1.55.18 pm.png"));
            } catch (IOException ex) {
                ex.printStackTrace();
            }

            addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    points.add(e.getPoint());
                    repaint();
                }
            });
        }

        @Override
        public Dimension getPreferredSize() {
            return image == null ? new Dimension(200, 200) : new Dimension(image.getWidth(), image.getHeight());
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            if (image != null) {
                g2d.drawImage(image, 0, 0, this);
            }
            g2d.setColor(Color.RED);
            for (Point p : points) {
                g2d.fillOval(p.x - 4, p.y - 4, 8, 8);
            }
            g2d.dispose();
        }

    }

}

This example draws the dots directly to the image itself...

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private BufferedImage image;

        public TestPane() {
            try {
                image = ImageIO.read(new File("/Users/shanewhitehead/Desktop/Screen Shot 2017-03-09 at 1.55.18 pm.png"));
            } catch (IOException ex) {
                ex.printStackTrace();
            }

            addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    if (image != null) {
                        Point p = e.getPoint();
                        Graphics2D g2d = image.createGraphics();
                        g2d.setColor(Color.RED);
                        g2d.fillOval(p.x - 4, p.y - 4, 8, 8);
                        g2d.dispose();
                        repaint();
                    }
                }
            });
        }

        @Override
        public Dimension getPreferredSize() {
            return image == null ? new Dimension(200, 200) : new Dimension(image.getWidth(), image.getHeight());
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            g2d.drawImage(image, 0, 0, this);
            g2d.dispose();
        }

    }

}

In both cases, they simply make use of the Graphics2D API


问:
json array parsing in javascript
I have a json array printed out from php file.
And then tried to get elements by parsing it. But I am confused where is wrong.</p>

```<code>    <?php

    $json = array("a1", "a2", "a3", "a4", "a5".......);
    echo json_encode($json);

    ?>

    <script>
    $.ajax({
    /*other codes*/

    success : function(data){

            var json = parseJSON(data);
            for(var i = 0 ; i < json.length; i++){
               alert(json[i]);
            }

            }
</code>```

答:
Use

```<code>$.ajax({
        dataType: "json",
        ...
</code>```

The response (data) is in JSON.

Title: json array parsing in javascript

Body:
I have a json array printed out from php file.
And then tried to get elements by parsing it. But I am confused where is wrong.

    <?php

    $json = array("a1", "a2", "a3", "a4", "a5".......);
    echo json_encode($json);

    ?>

Body:
Use

$.ajax({
        dataType: "json",
        ...

The response (data) is in JSON.


问:
Where Firebase stored ID's every subscribed device?
My app is subscribing to Firebase Cloud Messaging. I want to have get all devices tokens whose are subscribing. Where can I find them?</p>

答:
There is currently no API to retrieve all the Registration tokens for your app from the Server side or from the Firebase Console. It's the developer's (you) responsibility to send and store the Registration tokens to your App Server, which is generated from the Client App side.

 From my answer here.


问:
Cloud Functions for Firebase child_added
I'm trying out Cloud Functions for Firebase, creating a function which will add a nickname when a new user is added to the database (not on auth).
From the Firebase Documention I've found that I need to use:

```<code>ref.on("child_added", function(snapshot, prevChildKey) {
    //Something
})
</code>```

, but I cannot even get the function to deploy. My code is:

```<code>const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

var ref = admin.database().ref("/users");

ref.on("child_added", function(snapshot, prevChildKey) {
  console.log(snapshot)
})
</code>```

Can someone help me?

Update:

After working on it this is now my code:

```<code>const functions = require('firebase-functions');
// Import Admin SDK
var admin = require("firebase-admin");
admin.initializeApp(functions.config().firebase);

var db = admin.database();
var ref = db.ref('users');
var childs = [];
var nicknames = [];

exports.newUser = functions.database.ref('users').onWrite(event => {
    const data = event.data.val();
    ref.on("child_added", function(snapshot, childKey) {
        if (!childs.includes(childKey)) {
            childs.push(childKey);
        };
        for (i in childs) {
            if (childs[i] == null) {
                childs.splice(i, 1);
            };
        };
    });

    ref.once("value", function(snapshot) {
        for (i in childs) {
            var child = data[childs[i]];
            if (!child.hasOwnProperty("nickname")) {
                console.log("Child does not have nickname: " + childs[i]);
                ref.child(childs[i]).update({
                    nickname: "user"+childs[i]
                });
            };
        };
    });
});
</code>```

Based on what Doug Stevenson has replied, I still need to figure out how to only do this if there's actually a new child being added (new user)

答:
I figured it out. Here's the code I used:

```<code>const functions = require('firebase-functions');
var admin = require("firebase-admin");
admin.initializeApp(functions.config().firebase);

var childs = [];
var nicknames = [];

exports.newUser = functions.database.ref('users').onWrite(event => {
    ref.on("child_added", function(snapshot, childKey) {
        if (!childs.includes(childKey)) {
            childs.push(childKey);
        }
    });
});
</code>```

I would like it only to be called when a child is added and not every time something is written to the database (to limit usage)

Body:
I'm trying out Cloud Functions for Firebase, creating a function which will add a nickname when a new user is added to the database (not on auth).
From the Firebase Documention I've found that I need to use:

ref.on("child_added", function(snapshot, prevChildKey) {
    //Something
})

, but I cannot even get the function to deploy. My code is:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

var ref = admin.database().ref("/users");

ref.on("child_added", function(snapshot, prevChildKey) {
  console.log(snapshot)
})

Can someone help me?

Update:

After working on it this is now my code:

const functions = require('firebase-functions');
// Import Admin SDK
var admin = require("firebase-admin");
admin.initializeApp(functions.config().firebase);

var db = admin.database();
var ref = db.ref('users');
var childs = [];
var nicknames = [];

exports.newUser = functions.database.ref('users').onWrite(event => {
    const data = event.data.val();
    ref.on("child_added", function(snapshot, childKey) {
        if (!childs.includes(childKey)) {
            childs.push(childKey);
        };
        for (i in childs) {
            if (childs[i] == null) {
                childs.splice(i, 1);
            };
        };
    });

    ref.once("value", function(snapshot) {
        for (i in childs) {
            var child = data[childs[i]];
            if (!child.hasOwnProperty("nickname")) {
                console.log("Child does not have nickname: " + childs[i]);
                ref.child(childs[i]).update({
                    nickname: "user"+childs[i]
                });
            };
        };
    });
});

Based on what Doug Stevenson has replied, I still need to figure out how to only do this if there's actually a new child being added (new user)

Body:
I figured it out. Here's the code I used:

const functions = require('firebase-functions');
var admin = require("firebase-admin");
admin.initializeApp(functions.config().firebase);

var childs = [];
var nicknames = [];

exports.newUser = functions.database.ref('users').onWrite(event => {
    ref.on("child_added", function(snapshot, childKey) {
        if (!childs.includes(childKey)) {
            childs.push(childKey);
        }
    });
});

I would like it only to be called when a child is added and not every time something is written to the database (to limit usage)


问:
Unrecognized option "csrf_provider" under "security.firewalls.main.form_login" despite csrf enabled
After setting up the FOSUser Bundle I have experienced this error

Unrecognized option "csrf_provider" under "security.firewalls.main.form_login"

Now I know how to use google and the two main things that could cause the problem are

Not enabling the csrf_protection in config.yml

Not properly setting the csrf_provider in security.yml

The problem here is the fact that both of these options are properly set for me.

Here is the config.yml

```<code>imports:
    - { resource: parameters.yml }
    - { resource: security.yml }
    - { resource: services.yml }

# Put parameters here that don't need to change on each machine where the app is deployed
# http://symfony.com/doc/current/best_practices/configuration.html#application-related-configuration
parameters:
    locale: en

framework:
    #esi:             ~
    #translator:      { fallbacks: ["%locale%"] }
    secret:          "%secret%"
    router:
        resource: "%kernel.root_dir%/config/routing.yml"
        strict_requirements: ~
    form:            ~
    csrf_protection:
        enabled: true
    validation:      { enable_annotations: true }
    #serializer:      { enable_annotations: true }
    templating:
        engines: ['twig']
    default_locale:  "%locale%"
    trusted_hosts:   ~
    trusted_proxies: ~
    session:
        # http://symfony.com/doc/current/reference/configuration/framework.html#handler-id
        handler_id:  session.handler.native_file
        save_path:   "%kernel.root_dir%/../var/sessions/%kernel.environment%"
    fragments:       ~
    http_method_override: true
    assets: ~
    php_errors:
        log: true

# Twig Configuration
twig:
    debug:            "%kernel.debug%"
    strict_variables: "%kernel.debug%"

# Doctrine Configuration
doctrine:
    dbal:
        driver:   pdo_mysql
        host:     "%database_host%"
        port:     "%database_port%"
        dbname:   "%database_name%"
        user:     "%database_user%"
        password: "%database_password%"
        charset:  UTF8
        # if using pdo_sqlite as your database driver:
        #   1. add the path in parameters.yml
        #     e.g. database_path: "%kernel.root_dir%/../var/data/data.sqlite"
        #   2. Uncomment database_path in parameters.yml.dist
        #   3. Uncomment next line:
        #path:     "%database_path%"

    orm:
        auto_generate_proxy_classes: "%kernel.debug%"
        naming_strategy: doctrine.orm.naming_strategy.underscore
        auto_mapping: true

# Swiftmailer Configuration
swiftmailer:
    transport: "%mailer_transport%"
    host:      "%mailer_host%"
    username:  "%mailer_user%"
    password:  "%mailer_password%"
    spool:     { type: memory }

fos_user:
    db_driver: orm
    firewall_name: main
    user_class: AppBundle\Entity\User
</code>```

And security.yml

```<code>security:
    encoders:
        FOS\UserBundle\Model\UserInterface: bcrypt

    role_hierarchy:
        ROLE_ADMIN:       ROLE_USER
        ROLE_SUPER_ADMIN: ROLE_ADMIN

    providers:
        fos_userbundle:
            id: fos_user.user_provider.username

    firewalls:
       main:
           pattern: ^/
           form_login:
               provider: fos_userbundle
               csrf_provider: security.csrf.token_manager
               # csrf_provider: form.csrf_provider
               # my syomfony is 3.1 I believe
           logout:       true
           anonymous:    true

    access_control:
        - { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/admin/, role: ROLE_ADMIN }
</code>```

I will also throw in the routing.yml which is the one from the FOS bundle setup

```<code>app:
    resource: "@AppBundle/Controller/"
    type:     annotation

fos_user_security:
    resource: "@FOSUserBundle/Resources/config/routing/security.xml"

fos_user_profile:
    resource: "@FOSUserBundle/Resources/config/routing/profile.xml"
    prefix: /profile

fos_user_register:
    resource: "@FOSUserBundle/Resources/config/routing/registration.xml"
    prefix: /register

fos_user_resetting:
    resource: "@FOSUserBundle/Resources/config/routing/resetting.xml"
    prefix: /resetting

fos_user_change_password:
    resource: "@FOSUserBundle/Resources/config/routing/change_password.xml"
    prefix: /profile
</code>```

And with all that I'm still getting this issue. It's happeing upon clearing the cache in console so...clearing the cache isn't really a fix to this issue.

Has anyone else experienced this issue?

答:
Replace csrf_provider with csrf_token_generator in your security.yml file, this will fix your problem!

Check this link for more information https://symfony.com/doc/master/bundles/FOSUserBundle/index.html#step-4-configure-your-application-s-security-yml

Body:
After setting up the FOSUser Bundle I have experienced this error

Unrecognized option "csrf_provider" under "security.firewalls.main.form_login"

Now I know how to use google and the two main things that could cause the problem are

Not enabling the csrf_protection in config.yml

Not properly setting the csrf_provider in security.yml

The problem here is the fact that both of these options are properly set for me.

Here is the config.yml

imports:
    - { resource: parameters.yml }
    - { resource: security.yml }
    - { resource: services.yml }

# Put parameters here that don't need to change on each machine where the app is deployed
# http://symfony.com/doc/current/best_practices/configuration.html#application-related-configuration
parameters:
    locale: en

framework:
    #esi:             ~
    #translator:      { fallbacks: ["%locale%"] }
    secret:          "%secret%"
    router:
        resource: "%kernel.root_dir%/config/routing.yml"
        strict_requirements: ~
    form:            ~
    csrf_protection:
        enabled: true
    validation:      { enable_annotations: true }
    #serializer:      { enable_annotations: true }
    templating:
        engines: ['twig']
    default_locale:  "%locale%"
    trusted_hosts:   ~
    trusted_proxies: ~
    session:
        # http://symfony.com/doc/current/reference/configuration/framework.html#handler-id
        handler_id:  session.handler.native_file
        save_path:   "%kernel.root_dir%/../var/sessions/%kernel.environment%"
    fragments:       ~
    http_method_override: true
    assets: ~
    php_errors:
        log: true

# Twig Configuration
twig:
    debug:            "%kernel.debug%"
    strict_variables: "%kernel.debug%"

# Doctrine Configuration
doctrine:
    dbal:
        driver:   pdo_mysql
        host:     "%database_host%"
        port:     "%database_port%"
        dbname:   "%database_name%"
        user:     "%database_user%"
        password: "%database_password%"
        charset:  UTF8
        # if using pdo_sqlite as your database driver:
        #   1. add the path in parameters.yml
        #     e.g. database_path: "%kernel.root_dir%/../var/data/data.sqlite"
        #   2. Uncomment database_path in parameters.yml.dist
        #   3. Uncomment next line:
        #path:     "%database_path%"

    orm:
        auto_generate_proxy_classes: "%kernel.debug%"
        naming_strategy: doctrine.orm.naming_strategy.underscore
        auto_mapping: true

# Swiftmailer Configuration
swiftmailer:
    transport: "%mailer_transport%"
    host:      "%mailer_host%"
    username:  "%mailer_user%"
    password:  "%mailer_password%"
    spool:     { type: memory }

fos_user:
    db_driver: orm
    firewall_name: main
    user_class: AppBundle\Entity\User

And security.yml

security:
    encoders:
        FOS\UserBundle\Model\UserInterface: bcrypt

    role_hierarchy:
        ROLE_ADMIN:       ROLE_USER
        ROLE_SUPER_ADMIN: ROLE_ADMIN

    providers:
        fos_userbundle:
            id: fos_user.user_provider.username

    firewalls:
       main:
           pattern: ^/
           form_login:
               provider: fos_userbundle
               csrf_provider: security.csrf.token_manager
               # csrf_provider: form.csrf_provider
               # my syomfony is 3.1 I believe
           logout:       true
           anonymous:    true

    access_control:
        - { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/admin/, role: ROLE_ADMIN }

I will also throw in the routing.yml which is the one from the FOS bundle setup

app:
    resource: "@AppBundle/Controller/"
    type:     annotation

fos_user_security:
    resource: "@FOSUserBundle/Resources/config/routing/security.xml"

fos_user_profile:
    resource: "@FOSUserBundle/Resources/config/routing/profile.xml"
    prefix: /profile

fos_user_register:
    resource: "@FOSUserBundle/Resources/config/routing/registration.xml"
    prefix: /register

fos_user_resetting:
    resource: "@FOSUserBundle/Resources/config/routing/resetting.xml"
    prefix: /resetting

fos_user_change_password:
    resource: "@FOSUserBundle/Resources/config/routing/change_password.xml"
    prefix: /profile

And with all that I'm still getting this issue. It's happeing upon clearing the cache in console so...clearing the cache isn't really a fix to this issue.

Has anyone else experienced this issue?