问:
why when l use maven to build myeclipse web project,it doesn't copy "test" package to tomcat?
l am developing a web project based on maven using myeclipse.
now, l am testing my project.
Project Structure:

but when l deploy the project to tomcat 7, l found a problem.
that is,in tomcat7/webapps/partysys,there is no "com.partysys.test" package but have "com.party.core" package!why? l want to know!  beacuse no com.party.test,so when l start tomcat7,it errors.

l configure pom.xml to deploy my project to tomcat7 automatically.

```<code><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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.partysys</groupId>
  <artifactId>party</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>party Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</version>
            <scope>test</scope>
        </dependency>
        <!-- Struts2 -->
        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-core</artifactId>
            <version>2.3.24</version>
        </dependency>

        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-spring-plugin</artifactId>
            <version>2.3.24.1</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>4.2.2.Final</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>4.2.4.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>4.2.4.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>4.2.4.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>4.2.4.RELEASE</version>
        </dependency>

        <!--  ApplicationContextInitializer -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.2.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.7</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.26</version>
        </dependency>

        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.4</version>
        </dependency>

        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.16</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.6.1</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-nop</artifactId>
            <version>1.6.4</version>
        </dependency>
        <dependency>
            <groupId>javassist</groupId>
            <artifactId>javassist</artifactId>
            <version>3.11.0.GA</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.0.1</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.3.1</version>
        </dependency>
    </dependencies>

  <build>
    <finalName>partysys</finalName>
    <pluginManagement>
        <plugins>
             <plugin>
                 <groupId>org.apache.maven.plugins</groupId>
                 <artifactId>maven-compiler-plugin</artifactId>
                 <version>3.2</version>
                 <configuration>
                     <source>1.8</source>
                     <target>1.8</target>
                 </configuration>
             </plugin>
             <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>2.4</version>
                    <configuration>
                        <warSourceDirectory>src/main/webapp</warSourceDirectory>
                        <warName>party</warName>
                        <failOnMissingWebXml>false</failOnMissingWebXml>
                    </configuration>
             </plugin>
             <plugin>
                 <groupId>org.apache.tomcat.maven</groupId>
                 <artifactId>tomcat7-maven-plugin</artifactId>
                 <version>2.2</version>
                 <configuration>
                     <path>/${project.build.finalName}</path>
                     <server>tomcat7</server>
                     <username>admin</username>
                     <password>admin</password>
                     <url>http://localhost:8425/manager/text</url>
                  </configuration>
             </plugin>
        </plugins>
    </pluginManagement>
  </build>
   <repositories>
        <repository>
            <id>people.apache.snapshots</id>
            <url>
                http://repository.apache.org/content/groups/snapshots-group/
            </url>
            <releases>
                <enabled>false</enabled>
            </releases>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
    </repositories>
    <!-- 插件库 -->
    <pluginRepositories>
        <pluginRepository>
            <id>apache.snapshots</id>
            <name>Apache Snapshots</name>
            <url>
                http://repository.apache.org/content/groups/snapshots-group/
            </url>
            <releases>
                <enabled>false</enabled>
            </releases>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>
</project>
</code>```

maven/conf/settings.xml:

```<code><server>
       <id>tomcat7</id>
       <username>admin</username>
       <password>admin</password>
    </server>
</code>```

tomcat/conf/tomcat-users.xml:

```<code> <role rolename="tomcat"/>
  <role rolename="manager"/>
  <role rolename="manager-gui"/>
  <role rolename="manager-script" />
  <role rolename="admin-gui"/>
  <role rolename="manager-jmx"/>
  <user username="tomcat" password="tomcat" roles="tomcat,manager,manager-script,admin-gui" />
  <user username="admin" password="admin" roles="manager-script,manager-jmx" />
</code>```

答:
My guess is that some maven plugin is confused about your package name (test) and does not include it into your final war/jar.

Two suggestions: 1) refactor your package name. Could you change it from com.partysys.test to com.partysys.check? (or anything else) 2) review your effective pom.

In eclipse, double-click your pom.xml. Among others, it will show to you a Effective POM, that is the pom that will be used. Review it and try to find if it has some instructions related to test (surefire plugin).

Body:
l am developing a web project based on maven using myeclipse.
now, l am testing my project.
Project Structure:

but when l deploy the project to tomcat 7, l found a problem.
that is,in tomcat7/webapps/partysys,there is no "com.partysys.test" package but have "com.party.core" package!why? l want to know!  beacuse no com.party.test,so when l start tomcat7,it errors.

l configure pom.xml to deploy my project to tomcat7 automatically.

<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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.partysys</groupId>
  <artifactId>party</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>party Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-core</artifactId>
            <version>2.3.24</version>
        </dependency>

        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-spring-plugin</artifactId>
            <version>2.3.24.1</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>4.2.2.Final</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>4.2.4.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>4.2.4.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>4.2.4.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>4.2.4.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.2.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.7</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.26</version>
        </dependency>

        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.4</version>
        </dependency>

        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.16</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.6.1</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-nop</artifactId>
            <version>1.6.4</version>
        </dependency>
        <dependency>
            <groupId>javassist</groupId>
            <artifactId>javassist</artifactId>
            <version>3.11.0.GA</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.0.1</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.3.1</version>
        </dependency>
    </dependencies>

  <build>
    <finalName>partysys</finalName>
    <pluginManagement>
        <plugins>
             <plugin>
                 <groupId>org.apache.maven.plugins</groupId>
                 <artifactId>maven-compiler-plugin</artifactId>
                 <version>3.2</version>
                 <configuration>
                     <source>1.8</source>
                     <target>1.8</target>
                 </configuration>
             </plugin>
             <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>2.4</version>
                    <configuration>
                        <warSourceDirectory>src/main/webapp</warSourceDirectory>
                        <warName>party</warName>
                        <failOnMissingWebXml>false</failOnMissingWebXml>
                    </configuration>
             </plugin>
             <plugin>
                 <groupId>org.apache.tomcat.maven</groupId>
                 <artifactId>tomcat7-maven-plugin</artifactId>
                 <version>2.2</version>
                 <configuration>
                     <path>/${project.build.finalName}</path>
                     <server>tomcat7</server>
                     <username>admin</username>
                     <password>admin</password>
                     <url>http://localhost:8425/manager/text</url>
                  </configuration>
             </plugin>
        </plugins>
    </pluginManagement>
  </build>
   <repositories>
        <repository>
            <id>people.apache.snapshots</id>
            <url>
                http://repository.apache.org/content/groups/snapshots-group/
            </url>
            <releases>
                <enabled>false</enabled>
            </releases>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
    </repositories>

    <pluginRepositories>
        <pluginRepository>
            <id>apache.snapshots</id>
            <name>Apache Snapshots</name>
            <url>
                http://repository.apache.org/content/groups/snapshots-group/
            </url>
            <releases>
                <enabled>false</enabled>
            </releases>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>
</project>

maven/conf/settings.xml:

<server>
       <id>tomcat7</id>
       <username>admin</username>
       <password>admin</password>
    </server>

tomcat/conf/tomcat-users.xml:

 <role rolename="tomcat"/>
  <role rolename="manager"/>
  <role rolename="manager-gui"/>
  <role rolename="manager-script" />
  <role rolename="admin-gui"/>
  <role rolename="manager-jmx"/>
  <user username="tomcat" password="tomcat" roles="tomcat,manager,manager-script,admin-gui" />
  <user username="admin" password="admin" roles="manager-script,manager-jmx" />


来源: stackexchange

问:
what's the differences between static initialization and dynamic initialization in Java?
Recently when I do some practice on LeetCode,I find some trick solution.It use an Object o to reference an arrayObject o = new Object[]{null,null};,I guess maybe it's because in java everything is object.But when I tried this way,it went wrong.Object o3 = {1,2};So I tried every way to initialization a array and I want to see the difference,like these

```<code>int arr[] = {1,2};
Object o = arr;
Object o1 = new int[2];
Object o2 = new int[]{1,2};
Object o3 = {1,2};
</code>```

Only the o3 will compile an error.I don't know if it's because the way of initialization.I know when I use static initialization it will allocate memory first,when use dynamic initialization it will not.Any other differences between them cause this error?When I use new to create a array.what did it do in jvm?Thanks in advance.

答:
The initializer {1,2} is shorthand for new int[] {1,2}. This shorthand can only be used as an initializer for a variable of type int[].1 For instance, while the following works:

```<code>int arr[] = {1,2};
</code>```

this doesn't:

```<code>int arr[];
arr = {1,2}; // ERROR
</code>```

Instead, you would need to use:

```<code>int arr[];
arr = new int[] {1,2};
</code>```

Similarly, you can use:

```<code>Object o3 = new int[] {1,2};
</code>```

P.S. The above applies to static as well as instance fields, and also to local variables. Java doesn't have such a distinction as "static vs. dynamic initialization". That's more C++ terminology.

 1Well, it could also be for a variable of type byte[], long[],
 float[], Integer[], etc., for which the literals 1 and 2 are assignment compatible. See the Section 10.6 of the Java Language Specification.

ContentLicense: CC BY-SA 3.0

Body:
Recently when I do some practice on LeetCode,I find some trick solution.It use an Object o to reference an arrayObject o = new Object[]{null,null};,I guess maybe it's because in java everything is object.But when I tried this way,it went wrong.Object o3 = {1,2};So I tried every way to initialization a array and I want to see the difference,like these

int arr[] = {1,2};
Object o = arr;
Object o1 = new int[2];
Object o2 = new int[]{1,2};
Object o3 = {1,2};

Only the o3 will compile an error.I don't know if it's because the way of initialization.I know when I use static initialization it will allocate memory first,when use dynamic initialization it will not.Any other differences between them cause this error?When I use new to create a array.what did it do in jvm?Thanks in advance.

Body:
The initializer {1,2} is shorthand for new int[] {1,2}. This shorthand can only be used as an initializer for a variable of type int[].1 For instance, while the following works:

int arr[] = {1,2};

this doesn't:

int arr[];
arr = {1,2}; // ERROR

Instead, you would need to use:

int arr[];
arr = new int[] {1,2};

Similarly, you can use:

Object o3 = new int[] {1,2};

P.S. The above applies to static as well as instance fields, and also to local variables. Java doesn't have such a distinction as "static vs. dynamic initialization". That's more C++ terminology.

 1Well, it could also be for a variable of type byte[], long[],
 float[], Integer[], etc., for which the literals 1 and 2 are assignment compatible. See the Section 10.6 of the Java Language Specification.


问:
Pandas: How can I add two timestamp values?
I am trying to add more than two timestamp values and I expect to see output in minutes/seconds. How can I add two timestamps? I basically want to do: '1995-07-01 00:00:01' + '1995-07-01 00:05:06' and see if total time>=60minutes.
I tried this code: df['timestamp'][0]+df['timestamp'][1]. I referred this post but my timestamps are coming from dataframe.
Head of my dataframe column looks like this:

0   1995-07-01 00:00:01
1   1995-07-01 00:00:06
2   1995-07-01 00:00:09
3   1995-07-01 00:00:09
4   1995-07-01 00:00:09
Name: timestamp, dtype: datetime64[ns]```

I am getting this error:
TypeError: unsupported operand type(s) for +: 'Timestamp' and 'Timestamp'

答:
The problem is that adding Timestamps makes no sense.  What if they were on different days?  What you want are the sum of Timedeltas.  We can create Timedeltas by subtracting a common date from the whole series.  Let's subtract the minimum date.  Then sum up the Timedeltas.  Let s be your series of Timestamps

```<code>s.sub(s.dt.date.min()).sum().total_seconds()

34.0
</code>```

Body:
I am trying to add more than two timestamp values and I expect to see output in minutes/seconds. How can I add two timestamps? I basically want to do: '1995-07-01 00:00:01' + '1995-07-01 00:05:06' and see if total time>=60minutes.
I tried this code: df['timestamp'][0]+df['timestamp'][1]. I referred this post but my timestamps are coming from dataframe.
Head of my dataframe column looks like this:

0   1995-07-01 00:00:01
1   1995-07-01 00:00:06
2   1995-07-01 00:00:09
3   1995-07-01 00:00:09
4   1995-07-01 00:00:09
Name: timestamp, dtype: datetime64[ns]

I am getting this error:
TypeError: unsupported operand type(s) for +: 'Timestamp' and 'Timestamp'

Body:
The problem is that adding Timestamps makes no sense.  What if they were on different days?  What you want are the sum of Timedeltas.  We can create Timedeltas by subtracting a common date from the whole series.  Let's subtract the minimum date.  Then sum up the Timedeltas.  Let s be your series of Timestamps

s.sub(s.dt.date.min()).sum().total_seconds()

34.0


问:
AttributeError: 'module' object has no attribute 'image_data_format'
I have tried to run my first demo using keras with tensorflow backend but failed:

Traceback (most recent call last):
  File "mnist_cnn.py", line 26, in <module>
    if K.image_data_format() == 'channels_first':
AttributeError: 'module' object has no attribute 'image_data_format'

keras version: 1.2.1
tensorflow version: 1.0.1

How to fix?

答: update keras to 2.0.2 and it fixed.

Body: update keras to 2.0.2 and it fixed.


问:
Generalized Desktop directory
Simple enough, off of my last question, I am trying to make a directory change to a players desktop or file that is similar for all, as in C:\\Users\\USERNAME\\Desktop\\Tester File but the how would I make it so that USERNAME is the username of the person's computer? I tried using %USERNAME% but I don't really know how to do that, and it didn't work, and anyway the % gave an error message (I cannot remember the message, I think it was syntax error)

I also tried using ~, but it proved to be ineffective, but it may be due to my lack of experience.

EDIT
I solved this issue, thanks to some very great help from @pstatix so thank you.

By using user = getpass.getuser() I was able to do something like 'C:\Users' + user + '\Documents' it made this all user friendly! Thanks!

答:
Have you tried the getpass module? getpass documentation here.

```<code>import getpass
usr = getpass.getuser()
print usr
</code>```

Edit: For user specified example

You may also be interested in using the os module? os documentation here.

```<code>import os
usr = os.getlogin()
path = os.path.join('..', 'Users', usr, 'Desktop', 'Tester File')
os.chdir(path)
</code>```

Using os.environ for environment variables may also prove useful. os.environ documentation here For example:

```<code>import os

def getUserName():
    # set possible environment variables
    for name in ('LOGNAME', 'USER', 'LNAME', 'USERNAME'):
        usr = os.environ.get(name)
        if user:
            return usr #return the variable

if __name__ == '__main__':
    usr = getUserName()
    # do remainder below
</code>```

Title: Generalized Desktop directory

Body:
Have you tried the getpass module? getpass documentation here.

import getpass
usr = getpass.getuser()
print usr

Edit: For user specified example

You may also be interested in using the os module? os documentation here.

import os
usr = os.getlogin()
path = os.path.join('..', 'Users', usr, 'Desktop', 'Tester File')
os.chdir(path)

Using os.environ for environment variables may also prove useful. os.environ documentation here For example:

import os

def getUserName():
    # set possible environment variables
    for name in ('LOGNAME', 'USER', 'LNAME', 'USERNAME'):
        usr = os.environ.get(name)
        if user:
            return usr #return the variable

if __name__ == '__main__':
    usr = getUserName()
    # do remainder below


问:
How to configure Spring JavaMailSender for SES using SMTP?
We are trying to configure Spring JavaMailSender to work with Amazon's SES service using SMTP, but we are getting this error:

```<code>javax.mail.MessagingException: Could not connect to SMTP host: email-smtp.us-east-1.amazonaws.com, port: 465, response: -1
</code>```

This is our configuration:

```<code><bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
    <property name="host" value="email-smtp.us-east-1.amazonaws.com" />
    <property name="port" value="465" />
    <property name="username" value="..." />
    <property name="password" value="..." />
    <property name="javaMailProperties">
        <props>
            <prop key="mail.smtp.auth">true</prop>
            <prop key="mail.smtp.ssl.enable">true</prop>
        </props>
    </property>
</bean>
</code>```

Any ideas what could be wrong? Thanks in advance.

PS: We already tried the solution here: Could not connect to SMTP host: email-smtp.us-east-1.amazonaws.com, port: 465, response: -1 without any luck.

答:
This question is quite old, but in case someone needs the Spring boot configuration, this is what worked for me:</p>

```<code>mail:
    host: email-smtp.us-west-2.amazonaws.com
    port: 465
    username: <username>
    password: <pwd>

    properties:
        mail.smtp.auth: true
        mail.smtp.starttls.enable: true
        mail.smtp.starttls.required: true
        mail.smtp.ssl.enable: true
        mail.transport.protocol: smtps
        mail.smtp.from: no-reply@yourdomain.com
</code>```

Body:
We are trying to configure Spring JavaMailSender to work with Amazon's SES service using SMTP, but we are getting this error:

javax.mail.MessagingException: Could not connect to SMTP host: email-smtp.us-east-1.amazonaws.com, port: 465, response: -1

This is our configuration:

<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
    <property name="host" value="email-smtp.us-east-1.amazonaws.com" />
    <property name="port" value="465" />
    <property name="username" value="..." />
    <property name="password" value="..." />
    <property name="javaMailProperties">
        <props>
            <prop key="mail.smtp.auth">true</prop>
            <prop key="mail.smtp.ssl.enable">true</prop>
        </props>
    </property>
</bean>

Any ideas what could be wrong? Thanks in advance.

PS: We already tried the solution here: Could not connect to SMTP host: email-smtp.us-east-1.amazonaws.com, port: 465, response: -1 without any luck.

Body:
This question is quite old, but in case someone needs the Spring boot configuration, this is what worked for me:

mail:
    host: email-smtp.us-west-2.amazonaws.com
    port: 465
    username: <username>
    password: <pwd>

    properties:
        mail.smtp.auth: true
        mail.smtp.starttls.enable: true
        mail.smtp.starttls.required: true
        mail.smtp.ssl.enable: true
        mail.transport.protocol: smtps
        mail.smtp.from: no-reply@yourdomain.com


问:
How can I most efficiently get these group_by stats in MYSQL statement
Suppose I have a MySQL table that was created like this:

```<code>CREATE TABLE `my_table` (
  `my_id` char(32) NOT NULL,
  `my_boolean_field` tinyint(1) DEFAULT NULL,
  PRIMARY KEY (`my_id`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
</code>```

This table is very large. It has approximately 10 million rows in it. my_boolean_field's only possible values are 1, 0 and null.

Now separately, I have a list of 500 IDs. Let's call this my_list. They are in a text file separated by newlines. The name of that file is myfile.txt. The entries in this file are too long to include in a single where clause of an SQL statement.

I want to answer the following questions:

How many of the rows in my_table have and ID that is in my_list and my_boolean_field is null.

How many of the rows in my_table have and ID that is in my_list and my_boolean_field==1.

How many of the rows in my_table have and ID that is in my_list and my_boolean_field==0.

How many of the rows in my_table have and ID that is not in my_list and my_boolean_field is null.

How many of the rows in my_table have and ID that is not in my_list and my_boolean_field==1.

How many of the rows in my_table have and ID that is not in my_list and my_boolean_field==0.

What is the most performant way to get the above 6 counts??

答:
```<code>CREATE TABLE list (
    `my_id` char(32) NOT NULL
);

LOAD DATA INFILE ... -- get the 500 rows into `list`.

SELECT
    SUM(my_boolean_field IS NULL),
    SUM(my_boolean_field = 0),
    SUM(my_boolean_field = 1),
    SUM(my_boolean_field IS NOT NULL),
    SUM(my_boolean_field != 0),
    SUM(my_boolean_field != 1)
FROM tbl  AS t
JOIN list AS l ON t.my_id = l.my_id;
</code>```

It will do the 500 lookups, tallying the 6 counters as it goes.

Body:
Suppose I have a MySQL table that was created like this:

CREATE TABLE `my_table` (
  `my_id` char(32) NOT NULL,
  `my_boolean_field` tinyint(1) DEFAULT NULL,
  PRIMARY KEY (`my_id`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

This table is very large. It has approximately 10 million rows in it. my_boolean_field's only possible values are 1, 0 and null.

Now separately, I have a list of 500 IDs. Let's call this my_list. They are in a text file separated by newlines. The name of that file is myfile.txt. The entries in this file are too long to include in a single where clause of an SQL statement.

I want to answer the following questions:

How many of the rows in my_table have and ID that is in my_list and my_boolean_field is null.

How many of the rows in my_table have and ID that is in my_list and my_boolean_field==1.

How many of the rows in my_table have and ID that is in my_list and my_boolean_field==0.

How many of the rows in my_table have and ID that is not in my_list and my_boolean_field is null.

How many of the rows in my_table have and ID that is not in my_list and my_boolean_field==1.

How many of the rows in my_table have and ID that is not in my_list and my_boolean_field==0.

What is the most performant way to get the above 6 counts??

Body:
CREATE TABLE list (
    `my_id` char(32) NOT NULL
);

LOAD DATA INFILE ... -- get the 500 rows into `list`.

SELECT
    SUM(my_boolean_field IS NULL),
    SUM(my_boolean_field = 0),
    SUM(my_boolean_field = 1),
    SUM(my_boolean_field IS NOT NULL),
    SUM(my_boolean_field != 0),
    SUM(my_boolean_field != 1)
FROM tbl  AS t
JOIN list AS l ON t.my_id = l.my_id;

It will do the 500 lookups, tallying the 6 counters as it goes.


问:
math.pi not working as expected in pygame
I'm trying to draw an oscillating rectangle in pygame.

When I use

```<code>particle.pos[0] = 100 * math.sin(188.5 * t) + screen_width / 2
</code>```

it works as I expect it to, but when I use

```<code>omega = 2*math.pi*fps
particle.pos[0] = 100 * math.sin(omega * t) + screen_width / 2
</code>```

the rectangle is drawn, but doesn't move. I've confirmed that omega is about 188.5 and that both omega and 188.5 are floats. The only thing I can think of is that math.pi is somehow causing the problem, but I don't know why.

edit:
The whole thing

```<code>import sys
import math
import pygame
from pygame.locals import *

pygame.init()

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)

fps = 30
fpsClock = pygame.time.Clock()

screen_width, screen_height = 640, 480
screen = pygame.display.set_mode((screen_width, screen_height))

class Particle:
    """Particle"""
    def __init__(self, size, pos, particlecolor):
        self.size = size
        self.pos = pos
        self.particlecolor = particlecolor

    def draw(self):
        pygame.draw.rect(screen, GREEN, [self.pos, self.size])

particle = Particle([10, 10], [screen_width * .25, screen_height * .5], GREEN)

t = 0
omega = 2*math.pi*fps

while True:
    t += 1
    screen.fill(BLACK)

    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

    particle.pos[0] = 100 * math.sin(omega * t) + screen_width / 2
    # particle.pos[0] = 100 * math.sin(188.5 * t) + screen_width / 2

    particle.draw()

    pygame.display.flip()
fpsClock.tick(fps)
</code>```

答:
The problem is that you use multiples of 2*math.pi radians as your angle (that would be 360° (a full circle)) so you get almost the same result from the expression 100 * math.sin(omega * t) + screen_width / 2.

```<code>print 100 * math.sin(omega * t) + screen_width / 2
</code>```

Output:

```<code>319.99999999999784
319.9999999999957
319.99999999998784
319.99999999999136
319.9999999999949
319.99999999997567
319.99999999997925
</code>```

Try omega = 0.1 radians to get a nice result.

Body:
I'm trying to draw an oscillating rectangle in pygame.

When I use

particle.pos[0] = 100 * math.sin(188.5 * t) + screen_width / 2

it works as I expect it to, but when I use

omega = 2*math.pi*fps
particle.pos[0] = 100 * math.sin(omega * t) + screen_width / 2

the rectangle is drawn, but doesn't move. I've confirmed that omega is about 188.5 and that both omega and 188.5 are floats. The only thing I can think of is that math.pi is somehow causing the problem, but I don't know why.

edit:
The whole thing

import sys
import math
import pygame
from pygame.locals import *

pygame.init()

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)

fps = 30
fpsClock = pygame.time.Clock()

screen_width, screen_height = 640, 480
screen = pygame.display.set_mode((screen_width, screen_height))

class Particle:
    """Particle"""
    def __init__(self, size, pos, particlecolor):
        self.size = size
        self.pos = pos
        self.particlecolor = particlecolor

    def draw(self):
        pygame.draw.rect(screen, GREEN, [self.pos, self.size])

particle = Particle([10, 10], [screen_width * .25, screen_height * .5], GREEN)

t = 0
omega = 2*math.pi*fps

while True:
    t += 1
    screen.fill(BLACK)

    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

    particle.pos[0] = 100 * math.sin(omega * t) + screen_width / 2
    # particle.pos[0] = 100 * math.sin(188.5 * t) + screen_width / 2

    particle.draw()

    pygame.display.flip()
fpsClock.tick(fps)

Body:
The problem is that you use multiples of 2*math.pi radians as your angle (that would be 360° (a full circle)) so you get almost the same result from the expression 100 * math.sin(omega * t) + screen_width / 2.

print 100 * math.sin(omega * t) + screen_width / 2

Output:

319.99999999999784
319.9999999999957
319.99999999998784
319.99999999999136
319.9999999999949
319.99999999997567
319.99999999997925

Try omega = 0.1 radians to get a nice result.


问:
failed because: de.measite.minidns.hla.ResolutionUnsuccessfulException: Asking for xxxx. IN AAAA yielded an error response NX_DOMAIN
After I upgraded smack to 4.2.0 I am getting connection issue.

```<code>The following addresses failed: 'xxxx:5222' failed because:

de.measite.minidns.hla.ResolutionUnsuccessfulException: Asking for xxxx.    IN  A yielded an error response NX_DOMAIN, '52.90.233.38:5222' failed because: de.measite.minidns.hla.ResolutionUnsuccessfulException: Asking for xxxx. IN  AAAA yielded an error response NX_DOMAIN
</code>```

the issue happen when host is set in connection configuration builder.

example :

```<code>.setHost(ServiceConstants.CHAT_SERVER)
</code>```

See https://github.com/igniterealtime/Smack/wiki/Smack-4.2-Readme-and-Upgrade-Guide

This is my final configuration, it worked after Davood Falahati help !

```<code>InetAddress inetAddress = InetAddress.getByName(ServiceConstants.CHAT_SERVER);
            XMPPTCPConnectionConfiguration.Builder builder = XMPPTCPConnectionConfiguration.builder()
                    .setXmppDomain(JidCreate.from(ServiceConstants.CHAT_SERVER).asDomainBareJid())
                    .setPort(5222)
                    .setHostAddress(inetAddress)
                    .setDebuggerEnabled(true)
                    .setSendPresence(true)
</code>```

答:
This problem mainly occurs in local networks when the xmpp server is not configured in local DNS. To solve the problem, explicitly address the xmpp server and use

setHostAddress(InetAddress address)

see my answer here

Body:
After I upgraded smack to 4.2.0 I am getting connection issue.

The following addresses failed: 'xxxx:5222' failed because:

de.measite.minidns.hla.ResolutionUnsuccessfulException: Asking for xxxx.    IN  A yielded an error response NX_DOMAIN, '52.90.233.38:5222' failed because: de.measite.minidns.hla.ResolutionUnsuccessfulException: Asking for xxxx. IN  AAAA yielded an error response NX_DOMAIN

the issue happen when host is set in connection configuration builder.

example :

.setHost(ServiceConstants.CHAT_SERVER)

See https://github.com/igniterealtime/Smack/wiki/Smack-4.2-Readme-and-Upgrade-Guide

This is my final configuration, it worked after Davood Falahati help !

InetAddress inetAddress = InetAddress.getByName(ServiceConstants.CHAT_SERVER);
            XMPPTCPConnectionConfiguration.Builder builder = XMPPTCPConnectionConfiguration.builder()
                    .setXmppDomain(JidCreate.from(ServiceConstants.CHAT_SERVER).asDomainBareJid())
                    .setPort(5222)
                    .setHostAddress(inetAddress)
                    .setDebuggerEnabled(true)
                    .setSendPresence(true)


问:
What's the correct way of sharing functionality between activities?
Suppose I'm building an Android app, and I have two separate activities. Both do similar things, but maybe the layout is diferent. Let's say I have a button in each activity, and both buttons do the same thing, but I don't want to be redundant about it.
Could I just define a public method in one of the activities and then call that method from the other one too?
Even further, could I create some java class PublicMethods and just put in it all the methods that I want to share between activities?
I haven't seen this anywhere else, I think, so I suppose there is a good reason not to do this, but I can't figure out what it is.
Is this bad practice? If so, why? And if this is the case, what would be a good way to solve this problem?</p>

答: Since you're not very specific about what you are trying to achieve I'm guessing mayb you could just create an object and then call it from the activities and pass parameters determined on what you are trying to make it do, and even just send what you want through the activies by using intent putExtra and just used the Extra in your activity.</p>


问:
Connecting JSON to a Datatable
I am using DataTable and have a source which returns JSON and this data is stored in a variable 'myJson' which has first name, last name and contact type in the following format:

```<code>var myJson = "[
       {
           "fname" : "Smith",
          "lname" : "Hardy",
         "contactType" : "Permanent"
      }, {
        "fname" : "Justin",
        "lname" : "Joshua",
        "contactType" : "Permanent"
    }, {
        "fname" : "Linda",
        "lname" : "Gary",
        "contactType" : "Temporary"
    }, {
        "fname" : "Dan",
        "lname" : "Kevin",
        "contactType" : "Temporary"
    }, {
        "fname" : "Linda",
        "lname" : "Jenman",
        "contactType" : "Temporary"
    }, {
        "fname" : "Willams",
        "lname" : "Steve",
        "contactType" : "Temporary"
    }, {
        "fname" : "Dan",
        "lname" : "Kevin",
        "contactType" : "Temporary"
    }, {
        "fname" : "Robert",
        "lname" : "Ryan",
        "contactType" : "Temporary"
    }, {
        "fname" : "Richard",
        "lname" : "Kevin",
        "contactType" : "Temporary"
    }, {
        "fname" : "Evon",
        "lname" : "Godwin",
        "contactType" : "Permanent"
    }, {
        "fname" : "Charles",
        "lname" : "Ben",
        "contactType" : "Temporary"
    }
]"
</code>```

Here is my JavaScript code to connect to JSON and display data in the DataTable.

      $(document).ready(function() {
       $('#tblEmployees').DataTable( {
          //how to connect to JSON to display data in DdataTable
       } );
   } );```
</div>
</div>
</p>

<p>Below is my Table HTML markup to display the information:</p>

```

       First Name
       Last Name
       Contact Type

```

What is the best way to connect JSON to my DataTable?

Title: Connecting JSON to a Datatable

Body:
I am using DataTable and have a source which returns JSON and this data is stored in a variable 'myJson' which has first name, last name and contact type in the following format:

var myJson = "[
       {
           "fname" : "Smith",
          "lname" : "Hardy",
         "contactType" : "Permanent"
      }, {
        "fname" : "Justin",
        "lname" : "Joshua",
        "contactType" : "Permanent"
    }, {
        "fname" : "Linda",
        "lname" : "Gary",
        "contactType" : "Temporary"
    }, {
        "fname" : "Dan",
        "lname" : "Kevin",
        "contactType" : "Temporary"
    }, {
        "fname" : "Linda",
        "lname" : "Jenman",
        "contactType" : "Temporary"
    }, {
        "fname" : "Willams",
        "lname" : "Steve",
        "contactType" : "Temporary"
    }, {
        "fname" : "Dan",
        "lname" : "Kevin",
        "contactType" : "Temporary"
    }, {
        "fname" : "Robert",
        "lname" : "Ryan",
        "contactType" : "Temporary"
    }, {
        "fname" : "Richard",
        "lname" : "Kevin",
        "contactType" : "Temporary"
    }, {
        "fname" : "Evon",
        "lname" : "Godwin",
        "contactType" : "Permanent"
    }, {
        "fname" : "Charles",
        "lname" : "Ben",
        "contactType" : "Temporary"
    }
]"

Here is my JavaScript code to connect to JSON and display data in the DataTable.

      $(document).ready(function() {
       $('#tblEmployees').DataTable( {
          //how to connect to JSON to display data in DdataTable
       } );
   } );

Below is my Table HTML markup to display the information:

       First Name
       Last Name
       Contact Type

What is the best way to connect JSON to my DataTable?

Body:
Try this:

$(document).ready(function() {
    var data = [];
    data.push(
        [1,"Sasha","Brenna","0800 1111"],
        [2,"Sage","Mia","(01012) 405872"],
        [3,"Chelsea","Allistair","076 0578 0265"],
        [4,"Uta","Savannah","070 1247 5884"],
        [5,"Remedios","Berk","0995 181 0007"],
        [6,"Ruby","Wayne","0800 1111"],
        [7,"Faith","Fredericka","(01709) 099879"],
        [8,"Myra","Harrison","070 4241 9576"],
        [9,"Drake","Miriam","0800 733635"],
        [10,"Reed","Shannon","076 8597 5067"]
    );

    $('#data_table').DataTable( {
        data: data
    });
});

Working Fiddle


问:
Handling multiple AJAX call in jquery
I have a tab structure in my website.

On click of each tab, a AJAX will be called, with a unique URL.

But whenever the consecutive tabs are being clicked, and a ajax is being triggered, the call is going to error instead of success.

Only the tab which is loaded on load is fetching proper output.

On switching tabs, (in case the first tab's URL is fetching huge data), it is going to error.

I have also used .abort(), but I don't think it is serving the purpose.

I may be missing something. Could any one suggest any solutions.  Here is my sample code:

```<code>$(document).ready(function () {
  xhr = $.ajax({
      url: "www.something.com",
      type: "GET",
      cache: true,
      success: function (response) {
         alert("successful");
      },
      error: function (e) {
          alert("Oops Something went wrong");
      }
  });

});

$("#stickertab").click(function (e) {
  appUrl = "www.nothing.com";

  $("#show_Sticker").empty();
  if (xhr != null) xhr.abort();
  xhr = $.ajax({
      url: appUrl,
      type: "GET",
      cache: true,
      success: function (response) {
         alert("successful");
      },
      error: function (e) {
          alert(" Oops Something went wrong");
      }
  });

});
</code>```

This is the error I am getting:

```<code>e = Object {readyState: 0, status: 0, statusText: "abort"}
</code>```

答:
Add e.preventDefault() to your function.

```<code>$("#stickertab").click(function (e) {

  e.preventDefault(); // <-- here

  appUrl = "www.nothing.com";

  $("#show_Sticker").empty();
  if (xhr != null) xhr.abort();
  xhr = $.ajax({
      url: appUrl,
      type: "GET",
      cache: true,
      success: function (response) {
         alert("successful");
      },
      error: function (e) {
          alert(" Oops Something went wrong");
      }
  });

});
</code>```

Title: Handling multiple AJAX call in jquery

Body:
I have a tab structure in my website.

On click of each tab, a AJAX will be called, with a unique URL.

But whenever the consecutive tabs are being clicked, and a ajax is being triggered, the call is going to error instead of success.

Only the tab which is loaded on load is fetching proper output.

On switching tabs, (in case the first tab's URL is fetching huge data), it is going to error.

I have also used .abort(), but I don't think it is serving the purpose.

I may be missing something. Could any one suggest any solutions.  Here is my sample code:

$(document).ready(function () {
  xhr = $.ajax({
      url: "www.something.com",
      type: "GET",
      cache: true,
      success: function (response) {
         alert("successful");
      },
      error: function (e) {
          alert("Oops Something went wrong");
      }
  });

});

$("#stickertab").click(function (e) {
  appUrl = "www.nothing.com";

  $("#show_Sticker").empty();
  if (xhr != null) xhr.abort();
  xhr = $.ajax({
      url: appUrl,
      type: "GET",
      cache: true,
      success: function (response) {
         alert("successful");
      },
      error: function (e) {
          alert(" Oops Something went wrong");
      }
  });

});

This is the error I am getting:

e = Object {readyState: 0, status: 0, statusText: "abort"}

Body:
Add e.preventDefault() to your function.

$("#stickertab").click(function (e) {

  e.preventDefault(); // <-- here

  appUrl = "www.nothing.com";

  $("#show_Sticker").empty();
  if (xhr != null) xhr.abort();
  xhr = $.ajax({
      url: appUrl,
      type: "GET",
      cache: true,
      success: function (response) {
         alert("successful");
      },
      error: function (e) {
          alert(" Oops Something went wrong");
      }
  });

});


问:
Cfparam for a struct
```<code> <cfparam name="instance.params.sel_isCriteriaChanged" default="false">
</code>```

Here instance is a global structure but "sel_isCriteriaChanged" inside that is created using form variable. But in certain form i dont have that variable. It'll be undefined in that case.
So in that case how to set the variable to false as default value.

I am using this variable inside CFC file

答:
If I understand your problem correctly, you might do something like the following:

```<code><cfset instance.params.sel_isCriteriaChanged = structKeyExists(form, "sel_isCriteriaChanged") ? form.sel_isCriteriaChanged : false />
</code>```

This is shorthand for:

```<code><cfif structKeyExists(form, "sel_isCriteriaChanged")>
    <cfset instance.params.sel_isCriteriaChanged = form.sel_isCriteriaChanged />
<cfelse>
     <cfset instance.params.sel_isCriteriaChanged = false />
</cfif>
</code>```

I like the terseness of the ternary operator ? : and I try to avoid using <cfparam> if possible. Hope this helps.

Title: Cfparam for a struct

Body:
 <cfparam name="instance.params.sel_isCriteriaChanged" default="false">

Here instance is a global structure but "sel_isCriteriaChanged" inside that is created using form variable. But in certain form i dont have that variable. It'll be undefined in that case.
So in that case how to set the variable to false as default value.

I am using this variable inside CFC file

Body:
If I understand your problem correctly, you might do something like the following:

<cfset instance.params.sel_isCriteriaChanged = structKeyExists(form, "sel_isCriteriaChanged") ? form.sel_isCriteriaChanged : false />

This is shorthand for:

<cfif structKeyExists(form, "sel_isCriteriaChanged")>
    <cfset instance.params.sel_isCriteriaChanged = form.sel_isCriteriaChanged />
<cfelse>
     <cfset instance.params.sel_isCriteriaChanged = false />
</cfif>

I like the terseness of the ternary operator ? : and I try to avoid using <cfparam> if possible. Hope this helps.


问:
How to create a conversion of Fahrenheit to Celsius in java
The code should output a table for Fahrenheit and Celsius:

```<code>public static void main(String[] args) {
    System.out.println("Fahrenheit\tCelsius");
    System.out.println("=======================");
     for(int temp = -45; temp <= 120; temp += 5) //for(int i = 0; i <= 100; i+= 10)
        {
            System.out.printf("%5d       |", temp);
            double sum = (temp + (9.0/5.0)) * 32;
            System.out.printf("%5d", (int) sum );
            System.out.println();
        }
}
</code>```

答:
A better way would be to use the decimal format class

```<code>import java.text.DecimalFormat;

int numberToPrint = 10.234;
DecimalFormat threePlaces = new DecimalFormat("##.#");  //formats to 1 decimal place
System.out.println(threePlaces.format(numberToPrint));
</code>```

Should print:

```<code>10.2
</code>```

Body:
The code should output a table for Fahrenheit and Celsius:

public static void main(String[] args) {
    System.out.println("Fahrenheit\tCelsius");
    System.out.println("=======================");
     for(int temp = -45; temp <= 120; temp += 5) //for(int i = 0; i <= 100; i+= 10)
        {
            System.out.printf("%5d       |", temp);
            double sum = (temp + (9.0/5.0)) * 32;
            System.out.printf("%5d", (int) sum );
            System.out.println();
        }
}

Body:
A better way would be to use the decimal format class

import java.text.DecimalFormat;

int numberToPrint = 10.234;
DecimalFormat threePlaces = new DecimalFormat("##.#");  //formats to 1 decimal place
System.out.println(threePlaces.format(numberToPrint));

Should print:

10.2


问:
Java program for all walking paths of a square grid
I'm trying to write a program that outputs (in the console) all possible paths (in (x1,x1) --> (x2,x2) --> etc.. format) for navigating a grid of size NxN, from top-left to bottom-right; i.e. from (0,0) to (N-1,N-1). You can only move down or right; i.e. from (0,0) to (0,1) or to (1,0). I want the program to output each time a full path set is found (i.e. all moves from top-left to bottom-right), and what that path set is.

It seems as though the best way to write this is with a recursive method inputting each move into an arrayList (see the buildPath method - the last method in the program), which is where I'm having trouble.

To make it slightly more complicated, I'm also generating random grid positions that are "off-limits" and as such can't be passed through.
That said, I can probably work that part out for myself once we/I figure out how to actually get the thing working with any paths at all.

How would I implement a recursive method to determine which paths are possible? Any help is appreciated (even pseudo-code would be better than nothing)!

Here is my code so far (the simple bits are in pseudo-code to make it easier to work through, but let me know if I should put the full code in):

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

public class RecursiveAlgorithm {

    public static ArrayList<Integer> allPaths = new ArrayList<Integer>();
    public static ArrayList<String> pathSet = new ArrayList<String>();
    public static int path;
    public static int N, M, x = 0, y = 0;
    public static String nString, mString;
    public static boolean grid[][];
    public static int right, down;

    @SuppressWarnings("resource")
    public static void main(String[] args) {

        //sets the current position to (0,0)
        right = 0;
        down = 0;

        Input value of N (size of grid)

        Input value of M (number of off-limits locations)

        offLimits(N, M); //calls offLimits method to randomly generate off-limits locations

        buildPath(right, down, allPaths, N); //calls buildPath method

    }

    public static void offLimits (int N, int M) {

        int mCount = 0;
        if (M == 0){
        } else {
            while (mCount < (M + 1)) {
              //int range1 = (max - min) + 1;
                int range1 = ((N-1) - 1) + 1;
                int range2 = ((N-1) - 0) + 1;
                int random1 = (int)((Math.random() * range1) + 1);
                int random2 = (int)(Math.random() * range2);

                //if an 'off-limits' point is generated at the finish point, move it to either 1 place to the left or 1 place above
                if ((random1 == N-1) && (random2 == N-1)) {
                    int switchSelect = (int)(Math.random() * 2);
                    while (switchSelect > 0) {
                        switch (switchSelect){

                        case 1: random1--;
                                break;

                        case 2: random2--;
                                break;

                        }
                    }
                }
                //sets a grid position to 'off-limits' (i.e. random1 = 1, random2 = 2 --> (1, 2) is 'off-limits')
                grid[random1][random2] = true;
                //counts the amount of off-limits grid locations generated
                mCount++;
            }
        }

    }

    public static ArrayList<String> buildPath (int right, int down, ArrayList<Integer> allPaths, int N) {

        //Updates path with current location (right, down)

        /***** FROM HERE ON IS WHERE I AM HAVING TROUBLE *****/

        //Stopping Condition
        if ((right == N-1) && (down == N-1)) { //robot cannot go right
            allPaths.add(path);
            return pathSet;
        }
        //Recursive Steps
        if (right == N-1) { //robot cannot go right
            buildPath (right, down + 1, allPaths, N);

        } else if (down == N-1) { //robot cannot go down
            buildPath (right + 1, down, allPaths, N);
        } else { //robot CAN go right or go down
                buildPath (right + 1, down, allPaths, N);
                //pathSet.add(Integer.toString(right));
                //pathSet.add(Integer.toString(down));
                buildPath (right, down + 1, allPaths, N);

            if (grid[x][y] == false) {
                //valid new position (substitute x and y for proposed new path step)

            } else if (grid[x][y] == true) {
                //off-limits position (substitute x and y for proposed new path step)

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

答:
You're on the right track, but headed toward a solution more complex than needed. Here's one approach that finds them allowing all 4 compass directions (not just right and down). See how simple you can make it by removing code.

```<code>import java.util.LinkedHashSet;

class Experimental {
  static class PathFinder {
    final int gridSize;
    final boolean [] [] isBlocked;
    final Coord goal;
    final LinkedHashSet<Coord> path = new LinkedHashSet<>();
    final Random gen = new Random();

    PathFinder(int gridSize, int nBlocked) {
      this.gridSize = gridSize;
      this.isBlocked = new boolean[gridSize][gridSize];
      this.goal = new Coord(gridSize - 1, gridSize - 1);
      // This gets really inefficient if nBlocked is too big.
      for (int n = 0; n < nBlocked; ++n) {
        int x, y;
        do {
          x = gen.nextInt(gridSize);
          y = gen.nextInt(gridSize);
        } while (isBlocked[x][y] || (x == gridSize - 1 && y == gridSize - 1));
        isBlocked[x][y] = true;
      }
    }

    void searchFrom(Coord coord) {
      if (path.contains(coord)) return;
      path.add(coord);
      if (coord.equals(goal)) System.out.println(path);
      if (coord.x > 0 && !isBlocked[coord.x - 1][coord.y])
        searchFrom(new Coord(coord.x - 1, coord.y));
      if (coord.y > 0 && !isBlocked[coord.x][coord.y - 1])
        searchFrom(new Coord(coord.x, coord.y - 1));
      if (coord.x < gridSize - 1 && !isBlocked[coord.x + 1][coord.y])
        searchFrom(new Coord(coord.x + 1, coord.y));
      if (coord.y < gridSize - 1 && !isBlocked[coord.x][coord.y + 1])
        searchFrom(new Coord(coord.x, coord.y + 1));
      path.remove(coord);
    }

    void printAllPaths() {
      searchFrom(new Coord(0, 0));
    }

    static class Coord {
      final int x, y;
      public Coord(int x, int y) {
        this.x = x;
        this.y = y;
      }
      @Override
      public boolean equals(Object obj) {
        if (obj instanceof Coord) {
          Coord other = (Coord) obj;
          return x == other.x && y == other.y;
        }
        return false;
      }
      @Override
      public int hashCode() {
        return Integer.hashCode(x) ^ Integer.hashCode(-y);
      }
      @Override
      public String toString() {
        return '(' + Integer.toString(x) + ',' + Integer.toString(y) + ')';
      }
    }
  }

  public static void main(String[] args) {
    new PathFinder(4, new boolean [] [] {
      { false, false, false, false },
      { false, false, true, false },
      { true, false, false, false },
      { false, false, false, false },
    }).printAllPaths();
  }
}
</code>```

One hint: The linked hash set is a reasonable choice for the path here because we need to look "backward" at each step to make sure we're not about to visit a location already visited. The set makes the lookups O(1), while the linking ensures order is maintained, which normal hash sets don't. Your problem is different.

Body:
I'm trying to write a program that outputs (in the console) all possible paths (in (x1,x1) --> (x2,x2) --> etc.. format) for navigating a grid of size NxN, from top-left to bottom-right; i.e. from (0,0) to (N-1,N-1). You can only move down or right; i.e. from (0,0) to (0,1) or to (1,0). I want the program to output each time a full path set is found (i.e. all moves from top-left to bottom-right), and what that path set is.

It seems as though the best way to write this is with a recursive method inputting each move into an arrayList (see the buildPath method - the last method in the program), which is where I'm having trouble.

To make it slightly more complicated, I'm also generating random grid positions that are "off-limits" and as such can't be passed through.
That said, I can probably work that part out for myself once we/I figure out how to actually get the thing working with any paths at all.

How would I implement a recursive method to determine which paths are possible? Any help is appreciated (even pseudo-code would be better than nothing)!

Here is my code so far (the simple bits are in pseudo-code to make it easier to work through, but let me know if I should put the full code in):

import java.util.*;

public class RecursiveAlgorithm {

    public static ArrayList<Integer> allPaths = new ArrayList<Integer>();
    public static ArrayList<String> pathSet = new ArrayList<String>();
    public static int path;
    public static int N, M, x = 0, y = 0;
    public static String nString, mString;
    public static boolean grid[][];
    public static int right, down;

    @SuppressWarnings("resource")
    public static void main(String[] args) {

        //sets the current position to (0,0)
        right = 0;
        down = 0;

        Input value of N (size of grid)

        Input value of M (number of off-limits locations)

        offLimits(N, M); //calls offLimits method to randomly generate off-limits locations

        buildPath(right, down, allPaths, N); //calls buildPath method

    }

    public static void offLimits (int N, int M) {

        int mCount = 0;
        if (M == 0){
        } else {
            while (mCount < (M + 1)) {
              //int range1 = (max - min) + 1;
                int range1 = ((N-1) - 1) + 1;
                int range2 = ((N-1) - 0) + 1;
                int random1 = (int)((Math.random() * range1) + 1);
                int random2 = (int)(Math.random() * range2);

                //if an 'off-limits' point is generated at the finish point, move it to either 1 place to the left or 1 place above
                if ((random1 == N-1) && (random2 == N-1)) {
                    int switchSelect = (int)(Math.random() * 2);
                    while (switchSelect > 0) {
                        switch (switchSelect){

                        case 1: random1--;
                                break;

                        case 2: random2--;
                                break;

                        }
                    }
                }
                //sets a grid position to 'off-limits' (i.e. random1 = 1, random2 = 2 --> (1, 2) is 'off-limits')
                grid[random1][random2] = true;
                //counts the amount of off-limits grid locations generated
                mCount++;
            }
        }

    }

    public static ArrayList<String> buildPath (int right, int down, ArrayList<Integer> allPaths, int N) {

        //Updates path with current location (right, down)

        /***** FROM HERE ON IS WHERE I AM HAVING TROUBLE *****/

        //Stopping Condition
        if ((right == N-1) && (down == N-1)) { //robot cannot go right
            allPaths.add(path);
            return pathSet;
        }
        //Recursive Steps
        if (right == N-1) { //robot cannot go right
            buildPath (right, down + 1, allPaths, N);

        } else if (down == N-1) { //robot cannot go down
            buildPath (right + 1, down, allPaths, N);
        } else { //robot CAN go right or go down
                buildPath (right + 1, down, allPaths, N);
                //pathSet.add(Integer.toString(right));
                //pathSet.add(Integer.toString(down));
                buildPath (right, down + 1, allPaths, N);

            if (grid[x][y] == false) {
                //valid new position (substitute x and y for proposed new path step)

            } else if (grid[x][y] == true) {
                //off-limits position (substitute x and y for proposed new path step)

            }
        }
        return pathSet;
    }
}

Body:
You're on the right track, but headed toward a solution more complex than needed. Here's one approach that finds them allowing all 4 compass directions (not just right and down). See how simple you can make it by removing code.

import java.util.LinkedHashSet;

class Experimental {
  static class PathFinder {
    final int gridSize;
    final boolean [] [] isBlocked;
    final Coord goal;
    final LinkedHashSet<Coord> path = new LinkedHashSet<>();
    final Random gen = new Random();

    PathFinder(int gridSize, int nBlocked) {
      this.gridSize = gridSize;
      this.isBlocked = new boolean[gridSize][gridSize];
      this.goal = new Coord(gridSize - 1, gridSize - 1);
      // This gets really inefficient if nBlocked is too big.
      for (int n = 0; n < nBlocked; ++n) {
        int x, y;
        do {
          x = gen.nextInt(gridSize);
          y = gen.nextInt(gridSize);
        } while (isBlocked[x][y] || (x == gridSize - 1 && y == gridSize - 1));
        isBlocked[x][y] = true;
      }
    }

    void searchFrom(Coord coord) {
      if (path.contains(coord)) return;
      path.add(coord);
      if (coord.equals(goal)) System.out.println(path);
      if (coord.x > 0 && !isBlocked[coord.x - 1][coord.y])
        searchFrom(new Coord(coord.x - 1, coord.y));
      if (coord.y > 0 && !isBlocked[coord.x][coord.y - 1])
        searchFrom(new Coord(coord.x, coord.y - 1));
      if (coord.x < gridSize - 1 && !isBlocked[coord.x + 1][coord.y])
        searchFrom(new Coord(coord.x + 1, coord.y));
      if (coord.y < gridSize - 1 && !isBlocked[coord.x][coord.y + 1])
        searchFrom(new Coord(coord.x, coord.y + 1));
      path.remove(coord);
    }

    void printAllPaths() {
      searchFrom(new Coord(0, 0));
    }

    static class Coord {
      final int x, y;
      public Coord(int x, int y) {
        this.x = x;
        this.y = y;
      }
      @Override
      public boolean equals(Object obj) {
        if (obj instanceof Coord) {
          Coord other = (Coord) obj;
          return x == other.x && y == other.y;
        }
        return false;
      }
      @Override
      public int hashCode() {
        return Integer.hashCode(x) ^ Integer.hashCode(-y);
      }
      @Override
      public String toString() {
        return '(' + Integer.toString(x) + ',' + Integer.toString(y) + ')';
      }
    }
  }

  public static void main(String[] args) {
    new PathFinder(4, new boolean [] [] {
      { false, false, false, false },
      { false, false, true, false },
      { true, false, false, false },
      { false, false, false, false },
    }).printAllPaths();
  }
}

One hint: The linked hash set is a reasonable choice for the path here because we need to look "backward" at each step to make sure we're not about to visit a location already visited. The set makes the lookups O(1), while the linking ensures order is maintained, which normal hash sets don't. Your problem is different.


问:
jabber-net chat conversation
I'm making simple XMPP client using Jabber-Net. To send simple message i'm using a way from example code, i.e.:

```<code>jabber.protocol.client.Message msg = new jabber.protocol.client.Message(jc.Document);
msg.To = "adress@jabber.com";
msg.Body = "hello world";
jc.Write(msg);
</code>```

it works fine, but I would like to send chat message.
I mean that in PSI (http://psi-im.org/) i can send to somebody simple message or talk to him on chat (its another kind of form for that). How can it be done in jabber-net?

答:
```<code>msg.Type = jabber.protocol.client.MessageType.Chat;
</code>```

ContentLicense: CC BY-SA 2.5

Title: jabber-net chat conversation

Body:
I'm making simple XMPP client using Jabber-Net. To send simple message i'm using a way from example code, i.e.:

jabber.protocol.client.Message msg = new jabber.protocol.client.Message(jc.Document);
msg.To = "adress@jabber.com";
msg.Body = "hello world";
jc.Write(msg);

it works fine, but I would like to send chat message.
I mean that in PSI (http://psi-im.org/) i can send to somebody simple message or talk to him on chat (its another kind of form for that). How can it be done in jabber-net?


问:
Why won't anything show up in my Swift Playground?
I have a pong game in a Swift Playground that I made by following a tutorial online but my assistant editor won't show anything! Where is my pong game!? My code is below the image, which shows that nothing is showing up.

```<code>import SpriteKit
import PlaygroundSupport

// Declare some global constants
let width = 800 as CGFloat
let height = 1200 as CGFloat
let racketHeight = 150 as CGFloat
let ballRadius = 20 as CGFloat

// Three types of collision objects possible
enum CollisionTypes: UInt32 {
    case Ball = 1
    case Wall = 2
    case Racket = 4
}

// Racket direction
enum Direction: Int {
    case None = 0
    case Up = 1
    case Down = 2
}

// Make a SpriteKit scene
class gameScene: SKScene, SKPhysicsContactDelegate {
    let racketSpeed = 500.0
    var direction = Direction.None
    var score = 0
    var gameRunning = false

    // Screen elements
    var racket: SKShapeNode?
    var ball: SKShapeNode?
    let scoreLabel = SKLabelNode()

    // Initialize objects during first start
    override func sceneDidLoad() {
        super.sceneDidLoad()
        scoreLabel.fontSize = 40
        scoreLabel.position = CGPoint(x: width/2, y: height - 100)
        self.addChild(scoreLabel)

        createWalls()
        createBall(position: CGPoint(x: width / 2, y: height / 2))
        createRacket()
        startNewGame()
        self.physicsWorld.contactDelegate = self
    }

    // Create the ball sprite
    func createBall(position: CGPoint) {
        let physicsBody = SKPhysicsBody(circleOfRadius: ballRadius)
        ball = SKShapeNode(circleOfRadius: ballRadius)
        physicsBody.categoryBitMask = CollisionTypes.Ball.rawValue
        physicsBody.collisionBitMask = CollisionTypes.Wall.rawValue | CollisionTypes.Ball.rawValue | CollisionTypes.Racket.rawValue
        physicsBody.affectedByGravity = false
        physicsBody.restitution = 1
        physicsBody.linearDamping = 0
        physicsBody.velocity = CGVector(dx: -500, dy: 500)
        ball!.physicsBody = physicsBody
        ball!.position = position
        ball!.fillColor = SKColor.white
    }

    // Create the walls
    func createWalls() {
        createWall(rect: CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: ballRadius, height: height)))
        createWall(rect: CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: width, height: ballRadius)))
        createWall(rect: CGRect(origin: CGPoint(x: 0, y: height - ballRadius), size: CGSize(width: width, height: ballRadius)))
    }

    func createWall(rect: CGRect) {
        let node = SKShapeNode(rect: rect)
        node.fillColor = SKColor.white
        node.physicsBody = getWallPhysicsbody(rect: rect)
        self.addChild(node)
    }

    // Create the physics objetcs to handle wall collisions
    func getWallPhysicsbody(rect: CGRect) -> SKPhysicsBody {
        let physicsBody = SKPhysicsBody(rectangleOf: rect.size, center: CGPoint(x: rect.midX, y: rect.midY))
        physicsBody.affectedByGravity = false
        physicsBody.isDynamic = false
        physicsBody.collisionBitMask = CollisionTypes.Ball.rawValue
        physicsBody.categoryBitMask = CollisionTypes.Wall.rawValue
        return physicsBody
    }

    // Create the racket sprite
    func createRacket() {
        racket =  SKShapeNode(rect: CGRect(origin: CGPoint.zero, size: CGSize(width: ballRadius, height: racketHeight)))
        self.addChild(racket!)
        racket!.fillColor = SKColor.white
        let physicsBody = SKPhysicsBody(rectangleOf: racket!.frame.size, center: CGPoint(x: racket!.frame.midX, y: racket!.frame.midY))
        physicsBody.affectedByGravity = false
        physicsBody.isDynamic = false
        physicsBody.collisionBitMask = CollisionTypes.Ball.rawValue
        physicsBody.categoryBitMask = CollisionTypes.Racket.rawValue
        physicsBody.contactTestBitMask = CollisionTypes.Ball.rawValue
        racket!.physicsBody = physicsBody
    }

    // Start a new game
    func startNewGame() {
        score = 0
        scoreLabel.text = "0"
        racket!.position = CGPoint(x: width - ballRadius * 2, y: height / 2)
        let startLabel = SKLabelNode(text: "Game Over")
        startLabel.position = CGPoint(x: width / 2, y: height / 2)
        startLabel.fontSize = 160
        self.addChild(startLabel)

        // Animated countdown
        let fadeIn = SKAction.fadeIn(withDuration: 0.5)
        let fadeOut = SKAction.fadeOut(withDuration: 0.5)
        startLabel.text = "3"
        startLabel.run(SKAction.sequence([fadeIn, fadeOut]), completion: {
            startLabel.text = "2"
            startLabel.run(SKAction.sequence([fadeIn, fadeOut]), completion: {
                startLabel.text = "1"
                startLabel.run(SKAction.sequence([fadeIn, fadeOut]), completion: {
                    startLabel.text = "0"
                    startLabel.run(SKAction.sequence([fadeIn, fadeOut]), completion: {
                        startLabel.removeFromParent()
                        self.gameRunning = true
                        self.ball!.position = CGPoint(x: 30, y: height / 2)
                        self.addChild(self.ball!)
                    })
                })
            })
        })
    }

    // Handle touch events to move the racket
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        for touch in touches {
            let location = touch.location(in: self)
            if location.y > height / 2 {
                direction = Direction.Up
            } else if location.y < height / 2{
                direction = Direction.Down
            }
        }
    }

    // Stop racket movement
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        direction = Direction.None
    }

    // Game loop:
    var dt = TimeInterval(0)
    override func update(_ currentTime: TimeInterval) {
        if gameRunning {
            super.update(currentTime)
            checkGameOver()
            if dt > 0 {
                moveRacket(dt: currentTime - dt)
            }
            dt = currentTime
        }
    }

    // Move the racket up or down
    func moveRacket(dt: TimeInterval) {
        if direction == Direction.Up && racket!.position.y < height - racketHeight {
            racket!.position.y = racket!.position.y + CGFloat(racketSpeed * dt)
        } else if direction == Direction.Down && racket!.position.y > 0 {
            racket!.position.y = racket!.position.y - CGFloat(racketSpeed * dt)
        }
    }

    // Check if the ball is still on screen
    // Game Over animation
    func checkGameOver() {
        if ball!.position.x > CGFloat(width) {
            gameRunning = false
            ball!.removeFromParent()
            let gameOverLabel = SKLabelNode(text: "Game Over")
            gameOverLabel.position = CGPoint(x: width / 2, y: height / 2)
            gameOverLabel.fontSize = 80
            self.addChild(gameOverLabel)

            // Game Over animation
            let rotateAction = SKAction.rotate(byAngle: CGFloat(M_PI), duration: 1)
            let fadeInAction = SKAction.fadeIn(withDuration: 2)
            gameOverLabel.run(SKAction.repeat(rotateAction, count: 2))
            gameOverLabel.run(SKAction.scale(to: 0, duration: 2.5), completion: {
                gameOverLabel.removeFromParent()
                self.startNewGame()
            })
        }
    }

    // Detect collisions between ball and racket to increase the score
    func didBegin(_ contact: SKPhysicsContact) {
        if contact.bodyA.categoryBitMask == CollisionTypes.Racket.rawValue || contact.bodyB.categoryBitMask == CollisionTypes.Racket.rawValue {
            score += 1
            scoreLabel.text = String(score)
        }
    }
}

//Initialize the playground and start the scene:
let skView = SKView(frame: CGRect(origin: CGPoint.zero, size: CGSize(width: width, height: height)))
let scene = gameScene(size: skView.frame.size)
skView.presentScene(scene)

PlaygroundPage.current.liveView = skView
</code>```

答:
This happens to me sometimes. Playgrounds with SpriteKit just would not show anything in the Timeline view - you do have the Timeline view open, right? If you don't, tap the "Show the Assistant editor" button on the toolbar to open the Timeline view.

If you have the Timeline view open and nothing shows, try shutting down Xcode and restarting it. That generally resolves this issue for me.

Body:
I have a pong game in a Swift Playground that I made by following a tutorial online but my assistant editor won't show anything! Where is my pong game!? My code is below the image, which shows that nothing is showing up.

import SpriteKit
import PlaygroundSupport

// Declare some global constants
let width = 800 as CGFloat
let height = 1200 as CGFloat
let racketHeight = 150 as CGFloat
let ballRadius = 20 as CGFloat

// Three types of collision objects possible
enum CollisionTypes: UInt32 {
    case Ball = 1
    case Wall = 2
    case Racket = 4
}

// Racket direction
enum Direction: Int {
    case None = 0
    case Up = 1
    case Down = 2
}

// Make a SpriteKit scene
class gameScene: SKScene, SKPhysicsContactDelegate {
    let racketSpeed = 500.0
    var direction = Direction.None
    var score = 0
    var gameRunning = false

    // Screen elements
    var racket: SKShapeNode?
    var ball: SKShapeNode?
    let scoreLabel = SKLabelNode()

    // Initialize objects during first start
    override func sceneDidLoad() {
        super.sceneDidLoad()
        scoreLabel.fontSize = 40
        scoreLabel.position = CGPoint(x: width/2, y: height - 100)
        self.addChild(scoreLabel)

        createWalls()
        createBall(position: CGPoint(x: width / 2, y: height / 2))
        createRacket()
        startNewGame()
        self.physicsWorld.contactDelegate = self
    }

    // Create the ball sprite
    func createBall(position: CGPoint) {
        let physicsBody = SKPhysicsBody(circleOfRadius: ballRadius)
        ball = SKShapeNode(circleOfRadius: ballRadius)
        physicsBody.categoryBitMask = CollisionTypes.Ball.rawValue
        physicsBody.collisionBitMask = CollisionTypes.Wall.rawValue | CollisionTypes.Ball.rawValue | CollisionTypes.Racket.rawValue
        physicsBody.affectedByGravity = false
        physicsBody.restitution = 1
        physicsBody.linearDamping = 0
        physicsBody.velocity = CGVector(dx: -500, dy: 500)
        ball!.physicsBody = physicsBody
        ball!.position = position
        ball!.fillColor = SKColor.white
    }

    // Create the walls
    func createWalls() {
        createWall(rect: CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: ballRadius, height: height)))
        createWall(rect: CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: width, height: ballRadius)))
        createWall(rect: CGRect(origin: CGPoint(x: 0, y: height - ballRadius), size: CGSize(width: width, height: ballRadius)))
    }

    func createWall(rect: CGRect) {
        let node = SKShapeNode(rect: rect)
        node.fillColor = SKColor.white
        node.physicsBody = getWallPhysicsbody(rect: rect)
        self.addChild(node)
    }

    // Create the physics objetcs to handle wall collisions
    func getWallPhysicsbody(rect: CGRect) -> SKPhysicsBody {
        let physicsBody = SKPhysicsBody(rectangleOf: rect.size, center: CGPoint(x: rect.midX, y: rect.midY))
        physicsBody.affectedByGravity = false
        physicsBody.isDynamic = false
        physicsBody.collisionBitMask = CollisionTypes.Ball.rawValue
        physicsBody.categoryBitMask = CollisionTypes.Wall.rawValue
        return physicsBody
    }

    // Create the racket sprite
    func createRacket() {
        racket =  SKShapeNode(rect: CGRect(origin: CGPoint.zero, size: CGSize(width: ballRadius, height: racketHeight)))
        self.addChild(racket!)
        racket!.fillColor = SKColor.white
        let physicsBody = SKPhysicsBody(rectangleOf: racket!.frame.size, center: CGPoint(x: racket!.frame.midX, y: racket!.frame.midY))
        physicsBody.affectedByGravity = false
        physicsBody.isDynamic = false
        physicsBody.collisionBitMask = CollisionTypes.Ball.rawValue
        physicsBody.categoryBitMask = CollisionTypes.Racket.rawValue
        physicsBody.contactTestBitMask = CollisionTypes.Ball.rawValue
        racket!.physicsBody = physicsBody
    }

    // Start a new game
    func startNewGame() {
        score = 0
        scoreLabel.text = "0"
        racket!.position = CGPoint(x: width - ballRadius * 2, y: height / 2)
        let startLabel = SKLabelNode(text: "Game Over")
        startLabel.position = CGPoint(x: width / 2, y: height / 2)
        startLabel.fontSize = 160
        self.addChild(startLabel)

        // Animated countdown
        let fadeIn = SKAction.fadeIn(withDuration: 0.5)
        let fadeOut = SKAction.fadeOut(withDuration: 0.5)
        startLabel.text = "3"
        startLabel.run(SKAction.sequence([fadeIn, fadeOut]), completion: {
            startLabel.text = "2"
            startLabel.run(SKAction.sequence([fadeIn, fadeOut]), completion: {
                startLabel.text = "1"
                startLabel.run(SKAction.sequence([fadeIn, fadeOut]), completion: {
                    startLabel.text = "0"
                    startLabel.run(SKAction.sequence([fadeIn, fadeOut]), completion: {
                        startLabel.removeFromParent()
                        self.gameRunning = true
                        self.ball!.position = CGPoint(x: 30, y: height / 2)
                        self.addChild(self.ball!)
                    })
                })
            })
        })
    }

    // Handle touch events to move the racket
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        for touch in touches {
            let location = touch.location(in: self)
            if location.y > height / 2 {
                direction = Direction.Up
            } else if location.y < height / 2{
                direction = Direction.Down
            }
        }
    }

    // Stop racket movement
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        direction = Direction.None
    }

    // Game loop:
    var dt = TimeInterval(0)
    override func update(_ currentTime: TimeInterval) {
        if gameRunning {
            super.update(currentTime)
            checkGameOver()
            if dt > 0 {
                moveRacket(dt: currentTime - dt)
            }
            dt = currentTime
        }
    }

    // Move the racket up or down
    func moveRacket(dt: TimeInterval) {
        if direction == Direction.Up && racket!.position.y < height - racketHeight {
            racket!.position.y = racket!.position.y + CGFloat(racketSpeed * dt)
        } else if direction == Direction.Down && racket!.position.y > 0 {
            racket!.position.y = racket!.position.y - CGFloat(racketSpeed * dt)
        }
    }

    // Check if the ball is still on screen
    // Game Over animation
    func checkGameOver() {
        if ball!.position.x > CGFloat(width) {
            gameRunning = false
            ball!.removeFromParent()
            let gameOverLabel = SKLabelNode(text: "Game Over")
            gameOverLabel.position = CGPoint(x: width / 2, y: height / 2)
            gameOverLabel.fontSize = 80
            self.addChild(gameOverLabel)

            // Game Over animation
            let rotateAction = SKAction.rotate(byAngle: CGFloat(M_PI), duration: 1)
            let fadeInAction = SKAction.fadeIn(withDuration: 2)
            gameOverLabel.run(SKAction.repeat(rotateAction, count: 2))
            gameOverLabel.run(SKAction.scale(to: 0, duration: 2.5), completion: {
                gameOverLabel.removeFromParent()
                self.startNewGame()
            })
        }
    }

    // Detect collisions between ball and racket to increase the score
    func didBegin(_ contact: SKPhysicsContact) {
        if contact.bodyA.categoryBitMask == CollisionTypes.Racket.rawValue || contact.bodyB.categoryBitMask == CollisionTypes.Racket.rawValue {
            score += 1
            scoreLabel.text = String(score)
        }
    }
}

//Initialize the playground and start the scene:
let skView = SKView(frame: CGRect(origin: CGPoint.zero, size: CGSize(width: width, height: height)))
let scene = gameScene(size: skView.frame.size)
skView.presentScene(scene)

PlaygroundPage.current.liveView = skView


问:
Update cell value if separate value matches list in Pandas
I have a pandas dataframe with order numbers, items, and if the item was returned or not.

```<code>df = pd.DataFrame({'order_number': [1001, 1002, 1003, 1004],
'item': ['table', 'chair', 'sofa', 'armchair'], 'returned': [0,0,0,0]})

        item  order_number  returned
0     table          1001       0
1     chair          1002       0
2      sofa          1003       0
3  armchair          1004       0
</code>```

I also have a list with orders that have been returned:

```<code>lst = [1001, 1004]
</code>```

I'm not sure how to change the returned column value for only those rows with order numbers in the list. Any help would be great!

答:
You can use isin method with loc to modify the items:

```<code># use isin method to create a logical series and use loc to modify return column at
# corresponding rows
df.loc[df.order_number.isin(lst), "returned"] = 1

df
#      item   order_number  returned
#0    table           1001  1
#1    chair           1002  0
#2     sofa           1003  0
#3 armchair           1004  1
</code>```

Body:
I have a pandas dataframe with order numbers, items, and if the item was returned or not.

df = pd.DataFrame({'order_number': [1001, 1002, 1003, 1004],
'item': ['table', 'chair', 'sofa', 'armchair'], 'returned': [0,0,0,0]})

        item  order_number  returned
0     table          1001       0
1     chair          1002       0
2      sofa          1003       0
3  armchair          1004       0

I also have a list with orders that have been returned:

lst = [1001, 1004]

I'm not sure how to change the returned column value for only those rows with order numbers in the list. Any help would be great!

Body:
You can use isin method with loc to modify the items:

# use isin method to create a logical series and use loc to modify return column at
# corresponding rows
df.loc[df.order_number.isin(lst), "returned"] = 1

df
#      item   order_number  returned
#0    table           1001  1
#1    chair           1002  0
#2     sofa           1003  0
#3 armchair           1004  1


问:
Visual studio community 2017 LNK2019 unresolved external symbol
I've been looking around for the whole day and I find no solution. Im using opengl extensions glew, glfw and glm. Visual Studio Community 2017 throws up the exception: Severity    Code    Description Project File    Line    Suppression State
Error   LNK2019 unresolved external symbol __imp__glewInit@0 referenced in function _main   Name Directory.

My project is located: C:\Users\timbucktoo\Desktop\Projects\Scape\Scape
My extensions are located: C:\Users\timbucktoo\Desktop\Projects\Scape\Scape\OpenGL Exetensions Binaries\unzipped

I have the c++ include directories added:             C:\Users\timbucktoo\Desktop\Projects\Scape\Scape\OpenGL Exetensions     Binaries\unzipped\glm-0.9.8.4 %281%29\glm;

C:\Users\timbucktoo\Desktop\Projects\Scape\Scape\OpenGL Exetensions Binaries\unzipped\glfw-3.2.1.bin.WIN64\glfw-3.2.1.bin.WIN64\include;

C:\Users\timbucktoo\Desktop\Projects\Scape\Scape\OpenGL Exetensions Binaries\unzipped\glew-2.0.0-win32\glew-2.0.0\include;

I have the Linker general library directories added:
C:\Users\timbucktoo\Desktop\Projects\Scape\Scape\OpenGL Exetensions Binaries\unzipped\glew-2.0.0-win32\glew-2.0.0\lib\Release\x64;

Visual studio has told me I have a x86 machine, I am not fully aware of what this means but from what I have assumed this machine is running 64-bit windows.

I have tried mixing up all the options like the different add directories/libraries option and I can come up with no solution. This may have been asked before but not on the visual studio community 2017. Please help. THanks. :)

Oh and here is the code which I also tried using the pragma comment with glew32.lib.

```<code>#include <stdlib.h>
#include <stdio.h>
#include <GL\glew.h>
#include <GLFW\glfw3.h>
#include <glm\glm.hpp>

int main()
{
    if (!glfwInit())
    {
        fprintf(stderr, "Failed to initialize GLFW\n");
        return -1;
    }
    glfwWindowHint(GLFW_SAMPLES, 4); // 4x antialiasing
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); // We want OpenGL 3.3
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // To make MacOS             happy; should not be needed
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); //We don't want the old OpenGL

                                                               // Open a window and create its OpenGL context
GLFWwindow* window; // (In the accompanying source code, this variable is global)
window = glfwCreateWindow(1024, 768, "Tutorial 01", NULL, NULL);
if (window == NULL) {
    fprintf(stderr, "Failed to open GLFW window. If you have an Intel GPU, they are not 3.3 compatible. Try the 2.1 version of the tutorials.\n");
    glfwTerminate();
    return -1;
}
glfwMakeContextCurrent(window); // Initialize GLEW
glewExperimental = true; // Needed in core profile
if (glewInit() != GLEW_OK) {
    fprintf(stderr, "Failed to initialize GLEW\n");
    return -1;
}

// Ensure we can capture the escape key being pressed below
glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE);

do {
    // Draw nothing, see you in tutorial 2 !

    // Swap buffers
    glfwSwapBuffers(window);
    glfwPollEvents();

} // Check if the ESC key was pressed or the window was closed
while (glfwGetKey(window, GLFW_KEY_ESCAPE) != GLFW_PRESS &&
    glfwWindowShouldClose(window) == 0);
</code>```

}

答:
LNK2019 unresolved external symbol __imp__glewInit@0 referenced in function _main

This tells you that it can't find the external symbol. Which is because you aren't linking glew32.lib.

As you're using MSVC / Visual Studio, try adding glew32.lib to your project directory. Then add glew32.lib under Project Properties -> Configuration Properties -> Linker -> Input -> Additional Dependencies. Since you're using MSVC you can also (as you already mentioned) add the following:

```<code>#pragma comment(lib, "glew32.lib")
</code>```

If you have glew32.lib in your project directory and added the line above to your .cpp file. Then that linker error shouldn't come.

Now (given your example) just add something like glClear() and you then get something akin to:

LNK2019 unresolved external symbol __imp__glClear@4 referenced in function _main

Then that's because you also need to add opengl32.lib to your linker.

```<code>#pragma comment(lib, "opengl32.lib")
</code>```

If you get a linker error like this:

LNK4272: library machine type 'X86' conflicts with target machine type 'x64'

It means that you're building for x64 but some of your libraries are built for x86. In other words you might be using the x64 version of glew32.lib, while you actually need to use the x86 version of glew32.lib.

If your code compiles but when the application is run you get something like:

The program can't start because glew32.dll is missing from your computer.

Then add the glew32.dll to your project directory.

Again version matter, so if the application crashes saying something like:

The application was unable to start correctly (0xc000007b)

Then like before your application might be built for x86, but the glew32.dll is the one built for x64.

Verify everything above, and it should compile and run.

Last but not least. Instead of using GLEW I highly recommend switching to GLAD instead. GLEW is old and broken and as far as I can tell not really supported anymore.

Additionally GLAD is way easier to setup and use. You go to the generator, select the version you want to target, press generate and download an implementation (.c) file and a few headers (.h). That's it. No libs to link against, no dll's to carry around or anything.

I have a x86 machine, I am not fully aware of what this means

x86 is an instruction set architecture. However x86 is more commonly used to refer to 32-bit. Whereas x64 is used to refer to 64-bit. The architecture is the same, it's just 64-bit instead of 32-bit. The 64-bit version of the x86 architecture is also called
x86-64 or AMD64.

This also means that a 64-bit CPU can execute 32-bit instructions. But a 32-bit CPU can't execute 64-bit instructions. Which is why applications usually target 32-bit computers.

Body:
I've been looking around for the whole day and I find no solution. Im using opengl extensions glew, glfw and glm. Visual Studio Community 2017 throws up the exception: Severity    Code    Description Project File    Line    Suppression State
Error   LNK2019 unresolved external symbol __imp__glewInit@0 referenced in function _main   Name Directory.

My project is located: C:\Users\timbucktoo\Desktop\Projects\Scape\Scape
My extensions are located: C:\Users\timbucktoo\Desktop\Projects\Scape\Scape\OpenGL Exetensions Binaries\unzipped

I have the c++ include directories added:             C:\Users\timbucktoo\Desktop\Projects\Scape\Scape\OpenGL Exetensions     Binaries\unzipped\glm-0.9.8.4 %281%29\glm;

C:\Users\timbucktoo\Desktop\Projects\Scape\Scape\OpenGL Exetensions Binaries\unzipped\glfw-3.2.1.bin.WIN64\glfw-3.2.1.bin.WIN64\include;

C:\Users\timbucktoo\Desktop\Projects\Scape\Scape\OpenGL Exetensions Binaries\unzipped\glew-2.0.0-win32\glew-2.0.0\include;

I have the Linker general library directories added:
C:\Users\timbucktoo\Desktop\Projects\Scape\Scape\OpenGL Exetensions Binaries\unzipped\glew-2.0.0-win32\glew-2.0.0\lib\Release\x64;

Visual studio has told me I have a x86 machine, I am not fully aware of what this means but from what I have assumed this machine is running 64-bit windows.

I have tried mixing up all the options like the different add directories/libraries option and I can come up with no solution. This may have been asked before but not on the visual studio community 2017. Please help. THanks. :)

Oh and here is the code which I also tried using the pragma comment with glew32.lib.

#include <stdlib.h>
#include <stdio.h>
#include <GL\glew.h>
#include <GLFW\glfw3.h>
#include <glm\glm.hpp>

int main()
{
    if (!glfwInit())
    {
        fprintf(stderr, "Failed to initialize GLFW\n");
        return -1;
    }
    glfwWindowHint(GLFW_SAMPLES, 4); // 4x antialiasing
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); // We want OpenGL 3.3
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // To make MacOS             happy; should not be needed
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); //We don't want the old OpenGL

                                                               // Open a window and create its OpenGL context
GLFWwindow* window; // (In the accompanying source code, this variable is global)
window = glfwCreateWindow(1024, 768, "Tutorial 01", NULL, NULL);
if (window == NULL) {
    fprintf(stderr, "Failed to open GLFW window. If you have an Intel GPU, they are not 3.3 compatible. Try the 2.1 version of the tutorials.\n");
    glfwTerminate();
    return -1;
}
glfwMakeContextCurrent(window); // Initialize GLEW
glewExperimental = true; // Needed in core profile
if (glewInit() != GLEW_OK) {
    fprintf(stderr, "Failed to initialize GLEW\n");
    return -1;
}

// Ensure we can capture the escape key being pressed below
glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE);

do {
    // Draw nothing, see you in tutorial 2 !

    // Swap buffers
    glfwSwapBuffers(window);
    glfwPollEvents();

} // Check if the ESC key was pressed or the window was closed
while (glfwGetKey(window, GLFW_KEY_ESCAPE) != GLFW_PRESS &&
    glfwWindowShouldClose(window) == 0);

}

Body:
LNK2019 unresolved external symbol __imp__glewInit@0 referenced in function _main

This tells you that it can't find the external symbol. Which is because you aren't linking glew32.lib.

As you're using MSVC / Visual Studio, try adding glew32.lib to your project directory. Then add glew32.lib under Project Properties -> Configuration Properties -> Linker -> Input -> Additional Dependencies. Since you're using MSVC you can also (as you already mentioned) add the following:

#pragma comment(lib, "glew32.lib")

If you have glew32.lib in your project directory and added the line above to your .cpp file. Then that linker error shouldn't come.

Now (given your example) just add something like glClear() and you then get something akin to:

LNK2019 unresolved external symbol __imp__glClear@4 referenced in function _main

Then that's because you also need to add opengl32.lib to your linker.

#pragma comment(lib, "opengl32.lib")

If you get a linker error like this:

LNK4272: library machine type 'X86' conflicts with target machine type 'x64'

It means that you're building for x64 but some of your libraries are built for x86. In other words you might be using the x64 version of glew32.lib, while you actually need to use the x86 version of glew32.lib.

If your code compiles but when the application is run you get something like:

The program can't start because glew32.dll is missing from your computer.

Then add the glew32.dll to your project directory.

Again version matter, so if the application crashes saying something like:

The application was unable to start correctly (0xc000007b)

Then like before your application might be built for x86, but the glew32.dll is the one built for x64.

Verify everything above, and it should compile and run.

Last but not least. Instead of using GLEW I highly recommend switching to GLAD instead. GLEW is old and broken and as far as I can tell not really supported anymore.

Additionally GLAD is way easier to setup and use. You go to the generator, select the version you want to target, press generate and download an implementation (.c) file and a few headers (.h). That's it. No libs to link against, no dll's to carry around or anything.

I have a x86 machine, I am not fully aware of what this means

x86 is an instruction set architecture. However x86 is more commonly used to refer to 32-bit. Whereas x64 is used to refer to 64-bit. The architecture is the same, it's just 64-bit instead of 32-bit. The 64-bit version of the x86 architecture is also called
x86-64 or AMD64.

This also means that a 64-bit CPU can execute 32-bit instructions. But a 32-bit CPU can't execute 64-bit instructions. Which is why applications usually target 32-bit computers.