问:
Activiti hello world test
I am trying to make a simple Hello world application using Activiti 5.13 BPMN.  I made a dynamic web application project in eclipse and added my hello_world.bpmn diagram to the root folder and my test.java and activiti.cfg.xml files to the src folder.  The application is just suppose to print "Hello, world" to the console, but I cannot seem to get it to do this.  Below if all the files that I am using to run the application, also I am using a PostgreSQL database (I created all the necessary tables)

My hello_world.bpmn file is as following:

start event - > user script (groovy) - > end event

```<code><?xml version="1.0" encoding="UTF-8"?>
<definitions xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:activiti="http://activiti.org/bpmn" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:omgdc="http://www.omg.org/spec/DD/20100524/DC" xmlns:omgdi="http://www.omg.org/spec/DD/20100524/DI" typeLanguage="http://www.w3.org/2001/XMLSchema" expressionLanguage="http://www.w3.org/1999/XPath" targetNamespace="http://www.activiti.org/test">
  <process id="myProcess" name="My process" isExecutable="true">
    <startEvent id="startProcess" name="Start"></startEvent>
    <scriptTask id="scriptProcess" name="Hello world" scriptFormat="groovy" activiti:autoStoreVariables="true">
      <script>System.out.println("Hello, world this is the activiti process")</script>
    </scriptTask>
    <endEvent id="endProcess" name="End"></endEvent>
    <sequenceFlow id="flow1" sourceRef="startProcess" targetRef="scriptProcess"></sequenceFlow>
    <sequenceFlow id="flow2" sourceRef="scriptProcess" targetRef="endProcess"></sequenceFlow>
  </process>
  <bpmndi:BPMNDiagram id="BPMNDiagram_myProcess">
    <bpmndi:BPMNPlane bpmnElement="myProcess" id="BPMNPlane_myProcess">
      <bpmndi:BPMNShape bpmnElement="startProcess" id="BPMNShape_startProcess">
        <omgdc:Bounds height="35.0" width="35.0" x="110.0" y="220.0"></omgdc:Bounds>
      </bpmndi:BPMNShape>
      <bpmndi:BPMNShape bpmnElement="scriptProcess" id="BPMNShape_scriptProcess">
        <omgdc:Bounds height="55.0" width="105.0" x="210.0" y="210.0"></omgdc:Bounds>
      </bpmndi:BPMNShape>
      <bpmndi:BPMNShape bpmnElement="endProcess" id="BPMNShape_endProcess">
        <omgdc:Bounds height="35.0" width="35.0" x="390.0" y="220.0"></omgdc:Bounds>
      </bpmndi:BPMNShape>
      <bpmndi:BPMNEdge bpmnElement="flow1" id="BPMNEdge_flow1">
        <omgdi:waypoint x="145.0" y="237.0"></omgdi:waypoint>
        <omgdi:waypoint x="210.0" y="237.0"></omgdi:waypoint>
      </bpmndi:BPMNEdge>
      <bpmndi:BPMNEdge bpmnElement="flow2" id="BPMNEdge_flow2">
        <omgdi:waypoint x="315.0" y="237.0"></omgdi:waypoint>
        <omgdi:waypoint x="390.0" y="237.0"></omgdi:waypoint>
      </bpmndi:BPMNEdge>
    </bpmndi:BPMNPlane>
  </bpmndi:BPMNDiagram>
</definitions>
</code>```

My activiti.cfg.xml file is as following:

```<code><?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.springframework.org/schema/beans ;
   http://www.springframework.org/schema/beans/spring-beans.xsd">
 <bean id="processEngineConfiguration" class="org.activiti.engine.impl.cfg.StandaloneProcessEngineConfiguration">
 <!-- Database configurations  -->
 <property name="databaseType" value="postgres" />
 <property name="jdbcUrl" value="jdbc:postgresql://localhost:5432/postgres" />
 <property name="jdbcDriver" value="org.postgresql.Driver" />
 <property name="jdbcUsername" value="user1234" />
 <property name="jdbcPassword" value="password1234" />
 </bean>
</beans>
</code>```

My test.java file is as following:

```<code>public class test {
    public static void main(String[] args) {

        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();

        RuntimeService runtimeService = processEngine.getRuntimeService();
        RepositoryService repositoryService = processEngine.getRepositoryService();
        TaskService taskService = processEngine.getTaskService();
        ManagementService managementService = processEngine.getManagementService();
        IdentityService identityService = processEngine.getIdentityService();
        HistoryService historyService = processEngine.getHistoryService();
        FormService formService = processEngine.getFormService();

        runtimeService.startProcessInstanceByKey("myProcess");

        System.out.println("PRINT THIS MESSAGE");
    }
}
</code>```

When I run the application on my tomcat server I get the following results:

```<code>    11:34:14,359 [localhost-startStop-1] INFO  org.springframework.web.context.ContextLoader  - Root WebApplicationContext: initialization started
11:34:14,578 [localhost-startStop-1] INFO  org.springframework.web.context.support.XmlWebApplicationContext  - Refreshing Root WebApplicationContext: startup date [Wed Aug 21 11:34:14 CDT 2013]; root of context hierarchy
11:34:14,750 [localhost-startStop-1] INFO  org.springframework.beans.factory.xml.XmlBeanDefinitionReader  - Loading XML bean definitions from ServletContext resource [/WEB-INF/applicationContext.xml]
11:34:14,890 [localhost-startStop-1] INFO  org.springframework.beans.factory.xml.XmlBeanDefinitionReader  - Loading XML bean definitions from ServletContext resource [/WEB-INF/activiti-standalone-context.xml]
11:34:14,953 [localhost-startStop-1] INFO  org.springframework.beans.factory.xml.XmlBeanDefinitionReader  - Loading XML bean definitions from ServletContext resource [/WEB-INF/activiti-ui-context.xml]
11:34:15,328 [localhost-startStop-1] INFO  org.springframework.beans.factory.config.PropertyPlaceholderConfigurer  - Loading properties file from class path resource [db.properties]
11:34:15,343 [localhost-startStop-1] INFO  org.springframework.beans.factory.config.PropertyPlaceholderConfigurer  - Loading properties file from class path resource [ui.properties]
11:34:15,437 [localhost-startStop-1] INFO  org.springframework.beans.factory.support.DefaultListableBeanFactory  - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@caa278: defining beans [demoDataGenerator,dbProperties,dataSource,transactionManager,processEngineConfiguration,processEngine,repositoryService,runtimeService,taskService,historyService,managementService,identityService,activitiLoginHandler,activitiUiPropertyPlaceholder,navigatorManager,attachmentRendererManager,formPropertyRendererManager,variableRendererManager,componentFactories,processDefinitionFilterFactory,deploymentFilterFactory,navigationFragmentChangeListener,mainWindow,explorerApp,i18nManager,scopedTarget.messageSource,messageSource,notificationManager,viewManager,workflowDefinitionConversionFactory]; root of factory hierarchy
11:34:19,531 [localhost-startStop-1] INFO  org.activiti.engine.impl.ProcessEngineImpl  - ProcessEngine default created
11:34:19,531 [localhost-startStop-1] INFO  org.activiti.engine.impl.jobexecutor.JobExecutor  - Starting up the JobExecutor[org.activiti.engine.impl.jobexecutor.DefaultJobExecutor].
11:34:19,531 [Thread-1] INFO  org.activiti.engine.impl.jobexecutor.AcquireJobsRunnable  - JobExecutor[org.activiti.engine.impl.jobexecutor.DefaultJobExecutor] starting to acquire jobs
11:34:19,546 [localhost-startStop-1] INFO  org.activiti.explorer.demo.DemoDataGenerator  - Initializing demo groups
11:34:19,765 [localhost-startStop-1] INFO  org.activiti.explorer.demo.DemoDataGenerator  - Initializing demo users
11:34:19,921 [localhost-startStop-1] INFO  org.activiti.explorer.demo.DemoDataGenerator  - Initializing demo process definitions
11:34:19,937 [localhost-startStop-1] INFO  org.activiti.explorer.demo.DemoDataGenerator  - Initializing demo models
11:34:19,953 [localhost-startStop-1] INFO  org.activiti.explorer.demo.DemoDataGenerator  - Initializing demo report data
11:34:19,953 [Thread-2] INFO  org.activiti.engine.impl.jobexecutor.JobExecutor  - Shutting down the JobExecutor[org.activiti.engine.impl.jobexecutor.DefaultJobExecutor].
11:34:19,953 [Thread-1] INFO  org.activiti.engine.impl.jobexecutor.AcquireJobsRunnable  - JobExecutor[org.activiti.engine.impl.jobexecutor.DefaultJobExecutor] stopped job acquisition
11:34:20,281 [Thread-2] INFO  org.activiti.engine.impl.bpmn.deployer.BpmnDeployer  - Processing resource org/activiti/explorer/demo/process/VacationRequest.png
11:34:20,281 [Thread-2] INFO  org.activiti.engine.impl.bpmn.deployer.BpmnDeployer  - Processing resource org/activiti/explorer/demo/process/FixSystemFailureProcess.bpmn20.xml
11:34:20,484 [localhost-startStop-1] INFO  org.springframework.web.context.ContextLoader  - Root WebApplicationContext: initialization completed in 6109 ms
Aug 21, 2013 11:34:20 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8080"]
Aug 21, 2013 11:34:20 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-bio-8009"]
Aug 21, 2013 11:34:20 AM org.apache.catalina.startup.Catalina start
INFO: Server startup in 15043 ms
11:34:21,250 [Thread-2] INFO  org.activiti.engine.impl.bpmn.deployer.BpmnDeployer  - Processing resource org/activiti/explorer/demo/process/FixSystemFailureProcess.png
11:34:21,250 [Thread-2] INFO  org.activiti.engine.impl.bpmn.deployer.BpmnDeployer  - Processing resource org/activiti/explorer/demo/process/VacationRequest.bpmn20.xml
11:34:21,421 [Thread-2] INFO  org.activiti.engine.impl.bpmn.deployer.BpmnDeployer  - Processing resource org/activiti/explorer/demo/process/createTimersProcess.bpmn20.xml
11:34:21,484 [Thread-2] INFO  org.activiti.engine.impl.bpmn.deployer.BpmnDeployer  - Processing resource org/activiti/explorer/demo/process/simple-approval.simpleApprovalProcess.png
11:34:21,484 [Thread-2] INFO  org.activiti.engine.impl.bpmn.deployer.BpmnDeployer  - Processing resource org/activiti/explorer/demo/process/reviewSalesLead.bpmn20.xml
11:34:21,593 [Thread-2] INFO  org.activiti.engine.impl.bpmn.deployer.BpmnDeployer  - Processing resource org/activiti/explorer/demo/process/reviewSalesLead.reviewSaledLead.png
11:34:21,593 [Thread-2] INFO  org.activiti.engine.impl.bpmn.deployer.BpmnDeployer  - Processing resource org/activiti/explorer/demo/process/Helpdesk.png
11:34:21,593 [Thread-2] INFO  org.activiti.engine.impl.bpmn.deployer.BpmnDeployer  - Processing resource org/activiti/explorer/demo/process/Helpdesk.bpmn20.xml
11:34:21,656 [Thread-2] INFO  org.activiti.engine.impl.bpmn.deployer.BpmnDeployer  - Processing resource org/activiti/explorer/demo/process/simple-approval.bpmn20.xml
11:34:36,953 [Thread-2] INFO  org.activiti.engine.impl.jobexecutor.JobExecutor  - Starting up the JobExecutor[org.activiti.engine.impl.jobexecutor.DefaultJobExecutor].
11:34:36,953 [Thread-2] INFO  org.activiti.explorer.demo.DemoDataGenerator  - Demo report data generated
11:34:36,953 [Thread-4] INFO  org.activiti.engine.impl.jobexecutor.AcquireJobsRunnable  - JobExecutor[org.activiti.engine.impl.jobexecutor.DefaultJobExecutor] starting to acquire jobs
</code>```

答:
I have written a super detailed blog post on this, which starting from the setup, shows how to create not one but two fully working (although, simple) workflows.

You can check it out here and see if it helps.

The first example to print "Hello Activiti" should be what you are looking for.

Title: Activiti hello world test

Body:
I am trying to make a simple Hello world application using Activiti 5.13 BPMN.  I made a dynamic web application project in eclipse and added my hello_world.bpmn diagram to the root folder and my test.java and activiti.cfg.xml files to the src folder.  The application is just suppose to print "Hello, world" to the console, but I cannot seem to get it to do this.  Below if all the files that I am using to run the application, also I am using a PostgreSQL database (I created all the necessary tables)

My hello_world.bpmn file is as following:

start event - > user script (groovy) - > end event

<?xml version="1.0" encoding="UTF-8"?>
<definitions xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:activiti="http://activiti.org/bpmn" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:omgdc="http://www.omg.org/spec/DD/20100524/DC" xmlns:omgdi="http://www.omg.org/spec/DD/20100524/DI" typeLanguage="http://www.w3.org/2001/XMLSchema" expressionLanguage="http://www.w3.org/1999/XPath" targetNamespace="http://www.activiti.org/test">
  <process id="myProcess" name="My process" isExecutable="true">
    <startEvent id="startProcess" name="Start"></startEvent>

    </scriptTask>
    <endEvent id="endProcess" name="End"></endEvent>
    <sequenceFlow id="flow1" sourceRef="startProcess" targetRef="scriptProcess"></sequenceFlow>
    <sequenceFlow id="flow2" sourceRef="scriptProcess" targetRef="endProcess"></sequenceFlow>
  </process>
  <bpmndi:BPMNDiagram id="BPMNDiagram_myProcess">
    <bpmndi:BPMNPlane bpmnElement="myProcess" id="BPMNPlane_myProcess">
      <bpmndi:BPMNShape bpmnElement="startProcess" id="BPMNShape_startProcess">
        <omgdc:Bounds height="35.0" width="35.0" x="110.0" y="220.0"></omgdc:Bounds>
      </bpmndi:BPMNShape>
      <bpmndi:BPMNShape bpmnElement="scriptProcess" id="BPMNShape_scriptProcess">
        <omgdc:Bounds height="55.0" width="105.0" x="210.0" y="210.0"></omgdc:Bounds>
      </bpmndi:BPMNShape>
      <bpmndi:BPMNShape bpmnElement="endProcess" id="BPMNShape_endProcess">
        <omgdc:Bounds height="35.0" width="35.0" x="390.0" y="220.0"></omgdc:Bounds>
      </bpmndi:BPMNShape>
      <bpmndi:BPMNEdge bpmnElement="flow1" id="BPMNEdge_flow1">
        <omgdi:waypoint x="145.0" y="237.0"></omgdi:waypoint>
        <omgdi:waypoint x="210.0" y="237.0"></omgdi:waypoint>
      </bpmndi:BPMNEdge>
      <bpmndi:BPMNEdge bpmnElement="flow2" id="BPMNEdge_flow2">
        <omgdi:waypoint x="315.0" y="237.0"></omgdi:waypoint>
        <omgdi:waypoint x="390.0" y="237.0"></omgdi:waypoint>
      </bpmndi:BPMNEdge>
    </bpmndi:BPMNPlane>
  </bpmndi:BPMNDiagram>
</definitions>

My activiti.cfg.xml file is as following:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.springframework.org/schema/beans ;
   http://www.springframework.org/schema/beans/spring-beans.xsd">
 <bean id="processEngineConfiguration" class="org.activiti.engine.impl.cfg.StandaloneProcessEngineConfiguration">

 <property name="databaseType" value="postgres" />
 <property name="jdbcUrl" value="jdbc:postgresql://localhost:5432/postgres" />
 <property name="jdbcDriver" value="org.postgresql.Driver" />
 <property name="jdbcUsername" value="user1234" />
 <property name="jdbcPassword" value="password1234" />
 </bean>
</beans>

My test.java file is as following:

public class test {
    public static void main(String[] args) {

        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();

        RuntimeService runtimeService = processEngine.getRuntimeService();
        RepositoryService repositoryService = processEngine.getRepositoryService();
        TaskService taskService = processEngine.getTaskService();
        ManagementService managementService = processEngine.getManagementService();
        IdentityService identityService = processEngine.getIdentityService();
        HistoryService historyService = processEngine.getHistoryService();
        FormService formService = processEngine.getFormService();

        runtimeService.startProcessInstanceByKey("myProcess");

        System.out.println("PRINT THIS MESSAGE");
    }
}

When I run the application on my tomcat server I get the following results:

    11:34:14,359 [localhost-startStop-1] INFO  org.springframework.web.context.ContextLoader  - Root WebApplicationContext: initialization started
11:34:14,578 [localhost-startStop-1] INFO  org.springframework.web.context.support.XmlWebApplicationContext  - Refreshing Root WebApplicationContext: startup date [Wed Aug 21 11:34:14 CDT 2013]; root of context hierarchy
11:34:14,750 [localhost-startStop-1] INFO  org.springframework.beans.factory.xml.XmlBeanDefinitionReader  - Loading XML bean definitions from ServletContext resource [/WEB-INF/applicationContext.xml]
11:34:14,890 [localhost-startStop-1] INFO  org.springframework.beans.factory.xml.XmlBeanDefinitionReader  - Loading XML bean definitions from ServletContext resource [/WEB-INF/activiti-standalone-context.xml]
11:34:14,953 [localhost-startStop-1] INFO  org.springframework.beans.factory.xml.XmlBeanDefinitionReader  - Loading XML bean definitions from ServletContext resource [/WEB-INF/activiti-ui-context.xml]
11:34:15,328 [localhost-startStop-1] INFO  org.springframework.beans.factory.config.PropertyPlaceholderConfigurer  - Loading properties file from class path resource [db.properties]
11:34:15,343 [localhost-startStop-1] INFO  org.springframework.beans.factory.config.PropertyPlaceholderConfigurer  - Loading properties file from class path resource [ui.properties]
11:34:15,437 [localhost-startStop-1] INFO  org.springframework.beans.factory.support.DefaultListableBeanFactory  - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@caa278: defining beans [demoDataGenerator,dbProperties,dataSource,transactionManager,processEngineConfiguration,processEngine,repositoryService,runtimeService,taskService,historyService,managementService,identityService,activitiLoginHandler,activitiUiPropertyPlaceholder,navigatorManager,attachmentRendererManager,formPropertyRendererManager,variableRendererManager,componentFactories,processDefinitionFilterFactory,deploymentFilterFactory,navigationFragmentChangeListener,mainWindow,explorerApp,i18nManager,scopedTarget.messageSource,messageSource,notificationManager,viewManager,workflowDefinitionConversionFactory]; root of factory hierarchy
11:34:19,531 [localhost-startStop-1] INFO  org.activiti.engine.impl.ProcessEngineImpl  - ProcessEngine default created
11:34:19,531 [localhost-startStop-1] INFO  org.activiti.engine.impl.jobexecutor.JobExecutor  - Starting up the JobExecutor[org.activiti.engine.impl.jobexecutor.DefaultJobExecutor].
11:34:19,531 [Thread-1] INFO  org.activiti.engine.impl.jobexecutor.AcquireJobsRunnable  - JobExecutor[org.activiti.engine.impl.jobexecutor.DefaultJobExecutor] starting to acquire jobs
11:34:19,546 [localhost-startStop-1] INFO  org.activiti.explorer.demo.DemoDataGenerator  - Initializing demo groups
11:34:19,765 [localhost-startStop-1] INFO  org.activiti.explorer.demo.DemoDataGenerator  - Initializing demo users
11:34:19,921 [localhost-startStop-1] INFO  org.activiti.explorer.demo.DemoDataGenerator  - Initializing demo process definitions
11:34:19,937 [localhost-startStop-1] INFO  org.activiti.explorer.demo.DemoDataGenerator  - Initializing demo models
11:34:19,953 [localhost-startStop-1] INFO  org.activiti.explorer.demo.DemoDataGenerator  - Initializing demo report data
11:34:19,953 [Thread-2] INFO  org.activiti.engine.impl.jobexecutor.JobExecutor  - Shutting down the JobExecutor[org.activiti.engine.impl.jobexecutor.DefaultJobExecutor].
11:34:19,953 [Thread-1] INFO  org.activiti.engine.impl.jobexecutor.AcquireJobsRunnable  - JobExecutor[org.activiti.engine.impl.jobexecutor.DefaultJobExecutor] stopped job acquisition
11:34:20,281 [Thread-2] INFO  org.activiti.engine.impl.bpmn.deployer.BpmnDeployer  - Processing resource org/activiti/explorer/demo/process/VacationRequest.png
11:34:20,281 [Thread-2] INFO  org.activiti.engine.impl.bpmn.deployer.BpmnDeployer  - Processing resource org/activiti/explorer/demo/process/FixSystemFailureProcess.bpmn20.xml
11:34:20,484 [localhost-startStop-1] INFO  org.springframework.web.context.ContextLoader  - Root WebApplicationContext: initialization completed in 6109 ms
Aug 21, 2013 11:34:20 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8080"]
Aug 21, 2013 11:34:20 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-bio-8009"]
Aug 21, 2013 11:34:20 AM org.apache.catalina.startup.Catalina start
INFO: Server startup in 15043 ms
11:34:21,250 [Thread-2] INFO  org.activiti.engine.impl.bpmn.deployer.BpmnDeployer  - Processing resource org/activiti/explorer/demo/process/FixSystemFailureProcess.png
11:34:21,250 [Thread-2] INFO  org.activiti.engine.impl.bpmn.deployer.BpmnDeployer  - Processing resource org/activiti/explorer/demo/process/VacationRequest.bpmn20.xml
11:34:21,421 [Thread-2] INFO  org.activiti.engine.impl.bpmn.deployer.BpmnDeployer  - Processing resource org/activiti/explorer/demo/process/createTimersProcess.bpmn20.xml
11:34:21,484 [Thread-2] INFO  org.activiti.engine.impl.bpmn.deployer.BpmnDeployer  - Processing resource org/activiti/explorer/demo/process/simple-approval.simpleApprovalProcess.png
11:34:21,484 [Thread-2] INFO  org.activiti.engine.impl.bpmn.deployer.BpmnDeployer  - Processing resource org/activiti/explorer/demo/process/reviewSalesLead.bpmn20.xml
11:34:21,593 [Thread-2] INFO  org.activiti.engine.impl.bpmn.deployer.BpmnDeployer  - Processing resource org/activiti/explorer/demo/process/reviewSalesLead.reviewSaledLead.png
11:34:21,593 [Thread-2] INFO  org.activiti.engine.impl.bpmn.deployer.BpmnDeployer  - Processing resource org/activiti/explorer/demo/process/Helpdesk.png
11:34:21,593 [Thread-2] INFO  org.activiti.engine.impl.bpmn.deployer.BpmnDeployer  - Processing resource org/activiti/explorer/demo/process/Helpdesk.bpmn20.xml
11:34:21,656 [Thread-2] INFO  org.activiti.engine.impl.bpmn.deployer.BpmnDeployer  - Processing resource org/activiti/explorer/demo/process/simple-approval.bpmn20.xml
11:34:36,953 [Thread-2] INFO  org.activiti.engine.impl.jobexecutor.JobExecutor  - Starting up the JobExecutor[org.activiti.engine.impl.jobexecutor.DefaultJobExecutor].
11:34:36,953 [Thread-2] INFO  org.activiti.explorer.demo.DemoDataGenerator  - Demo report data generated
11:34:36,953 [Thread-4] INFO  org.activiti.engine.impl.jobexecutor.AcquireJobsRunnable  - JobExecutor[org.activiti.engine.impl.jobexecutor.DefaultJobExecutor] starting to acquire jobs


来源: stackexchange

问:
Hibernate: entities mapping
I have an entity, let's call it "Question". This entity has set of "Answer" entities. So, for example:

Question: "How old are you?"

Answer: "16", "15", "21", "26"

The correct answer is "21".

This mapping looks like:

Question:

```<code>@OneToMany(cascade = CascadeType.ALL, mappedBy = "question")
private Set<Answer> answers;
</code>```

Answer:

```<code>@ManyToOne
@JoinColumn(name = "question_id")
private Question question;
</code>```

It's very clear. But then, I would like to have question where are several parts and even more answers, e.g.:

Question: x = 1, please attach correct variants:

Parts:

x + 1

x + 2

2 * (x + 1)

Answers:

2

12

51

3

4

123

So, how could I map such cases? I would like to implement it as clear as possible and not to corrupt my db structure. Thank you.

答: Is it necessary that "parts" exists? Couldn't you assume "parts" as anothers Questions?</p>

ContentLicense: CC BY-SA 3.0

Title: Hibernate: entities mapping

Body:
I have an entity, let's call it "Question". This entity has set of "Answer" entities. So, for example:

Question: "How old are you?"

Answer: "16", "15", "21", "26"

The correct answer is "21".

This mapping looks like:

Question:

@OneToMany(cascade = CascadeType.ALL, mappedBy = "question")
private Set<Answer> answers;

Answer:

@ManyToOne
@JoinColumn(name = "question_id")
private Question question;

It's very clear. But then, I would like to have question where are several parts and even more answers, e.g.:

Question: x = 1, please attach correct variants:

Parts:

x + 1

x + 2

2 * (x + 1)

Answers:

2

12

51

3

4

123

So, how could I map such cases? I would like to implement it as clear as possible and not to corrupt my db structure. Thank you.


问:
combine/merge html table rows into one from mysql and php pivot table
I have a mysql table with a plain schedule:

```<code>    +-------------+--------------+------+-----+-------------------+-----------------------------+
    | Field       | Type         | Null | Key | Default           | Extra                       |
    +-------------+--------------+------+-----+-------------------+-----------------------------+
    | id          | int(11)      | NO   | PRI | NULL              | auto_increment              |
    | identity    | int(11)      | NO   | MUL | NULL              |
    | start       | datetime     | YES  | MUL | NULL              |                             |
    | end         | datetime     | YES  | MUL | NULL              |
    +-------------+--------------+------+-----+-------------------+-----------------------------+
</code>```

i have a php script:

```<code>$begin = new DateTime( $_SESSION['start'] );
$end = new DateTime( $_SESSION['end'] );
$interval = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($begin, $interval, $end);

foreach ( $period as $dt )
  $massivequery[]= "case(date(start)) when '".$dt->format( "Y-m-d" )."' then hour(timediff(end,start)) end as '".$dt->format( "Y-m-d" )."'";

$view_start = $_SESSION['start'];
$view_end = $_SESSION['end'];

$result = mysqli_query($con,"
select schedule.identity,".implode(',',$massivequery)." from schedule join names on schedule.id_code=names.id_code where schedule.away is null and schedule.errand is null and date(schedule.start) between '".$view_start."' and '".$view_end."'
");

echo "<table align='center' border='1'>";

$i = 0;
while($row = $result->fetch_assoc())
{
    if ($i == 0) {
      $i++;
      echo "<tr>";
      foreach ($row as $key => $value) {
        echo "<th>" . $key . "</th>";
      }
      echo "</tr>";
    }
    echo "<tr>";
    foreach ($row as $value) {
      echo "<td id='".$row['identity']."'>" . $value . "</td>";
    }
    echo "</tr>";
}
echo "</table>";
</code>```

The problem is that this gives me almost perfect table that I need. It's pivoted, all the table headings are correct but the problem is that it gives sa separate row for each day a person is on schedule. i would like the rows with the same id merged into one row. i do not mean colspan or rowspan.
The table i am getting

```<code><table align="center" border="1">
<tbody>
<tr><th>identity</th>
<th>2017-03-20</th>
<th>2017-03-21</th>
<th>2017-03-22</th></tr>

<tr><td id="12345">12345</td>
<td id="12345">8</td>
<td id="12345"></td>
<td id="12345"></td></tr>

<tr><td id="12345">12345</td>
<td id="12345"></td>
<td id="12345">8</td>
<td id="12345"></td></tr>

<tr><td id="12345">12345</td>
<td id="12345"></td>
<td id="12345"></td>
<td id="12345">8</td></tr>

</tbody></table>
</code>```

The table i would like to get instead

```<code><table align="center" border="1">
<tbody>
<tr><th>identity</th>
<th>2017-03-20</th>
<th>2017-03-21</th>
<th>2017-03-22</th></tr>

<tr><td id="12345">12345</td>
<td id="12345">8</td>
<td id="12345">8</td>
<td id="12345">8</td></tr>

</tbody></table>
</code>```

This here is just a simple example with simple data. i actually have ca 40-50 different identities and the usual length is 30 not 3 days. the query is dependant on another application so i have to be able to use session variables for stating the time period. that's why i cannot manually build up a proper mysql query (or atleast i do not know how).
once again, i'm pretty sure that there is some kind of super elegant and easy way to do this with jquery but i am failing to see how.

答:
I just had to edit the mysql query for it to work. too simple.

i edited this (added group_concat() function with separator ' + '):

```<code>$massivequery[]= "group_concat(case(date(start)) when '".$dt->format( "Y-m-d" )."' then hour(timediff(end,start)) end SEPARATOR ' + ') as '".$dt->format( "Y-m-d" )."'";
</code>```

and this ( added group by):

```<code>select schedule.identity,".implode(',',$massivequery)." from schedule join names on schedule.id_code=names.id_code where schedule.away is null and schedule.errand is null and date(schedule.start) between '".$view_start."' and '".$view_end."' group by schedule.identity
</code>```

now i have a fully dynamic pivot table.

Body:
I have a mysql table with a plain schedule:

    +-------------+--------------+------+-----+-------------------+-----------------------------+
    | Field       | Type         | Null | Key | Default           | Extra                       |
    +-------------+--------------+------+-----+-------------------+-----------------------------+
    | id          | int(11)      | NO   | PRI | NULL              | auto_increment              |
    | identity    | int(11)      | NO   | MUL | NULL              |
    | start       | datetime     | YES  | MUL | NULL              |                             |
    | end         | datetime     | YES  | MUL | NULL              |
    +-------------+--------------+------+-----+-------------------+-----------------------------+

i have a php script:

$begin = new DateTime( $_SESSION['start'] );
$end = new DateTime( $_SESSION['end'] );
$interval = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($begin, $interval, $end);

foreach ( $period as $dt )
  $massivequery[]= "case(date(start)) when '".$dt->format( "Y-m-d" )."' then hour(timediff(end,start)) end as '".$dt->format( "Y-m-d" )."'";

$view_start = $_SESSION['start'];
$view_end = $_SESSION['end'];

$result = mysqli_query($con,"
select schedule.identity,".implode(',',$massivequery)." from schedule join names on schedule.id_code=names.id_code where schedule.away is null and schedule.errand is null and date(schedule.start) between '".$view_start."' and '".$view_end."'
");

echo "
";

$i = 0;
while($row = $result->fetch_assoc())
{
    if ($i == 0) {
      $i++;
      echo "
";
      foreach ($row as $key => $value) {
        echo "" . $key . "	";
      }
      echo "
";
    }
    echo "
";
    foreach ($row as $value) {
      echo "" . $value . "	";
    }
    echo "
";
}
echo "
";

The problem is that this gives me almost perfect table that I need. It's pivoted, all the table headings are correct but the problem is that it gives sa separate row for each day a person is on schedule. i would like the rows with the same id merged into one row. i do not mean colspan or rowspan.
The table i am getting

identity
2017-03-20
2017-03-21
2017-03-22

12345
8

12345

8

12345

8

The table i would like to get instead

identity
2017-03-20
2017-03-21
2017-03-22

12345
8
8
8

This here is just a simple example with simple data. i actually have ca 40-50 different identities and the usual length is 30 not 3 days. the query is dependant on another application so i have to be able to use session variables for stating the time period. that's why i cannot manually build up a proper mysql query (or atleast i do not know how).
once again, i'm pretty sure that there is some kind of super elegant and easy way to do this with jquery but i am failing to see how.

Body:
I just had to edit the mysql query for it to work. too simple.

i edited this (added group_concat() function with separator ' + '):

$massivequery[]= "group_concat(case(date(start)) when '".$dt->format( "Y-m-d" )."' then hour(timediff(end,start)) end SEPARATOR ' + ') as '".$dt->format( "Y-m-d" )."'";

and this ( added group by):

select schedule.identity,".implode(',',$massivequery)." from schedule join names on schedule.id_code=names.id_code where schedule.away is null and schedule.errand is null and date(schedule.start) between '".$view_start."' and '".$view_end."' group by schedule.identity

now i have a fully dynamic pivot table.


问:
How to programmatically enable/disable network interfaces? (Windows XP)
I need to enable/disable completely network interfaces from a script in Windows XP. I'm looking for a python solution, but any general way (eg WMI, some command-line à la netsh, some windows call) is welcome and will be adjusted. Thanks.</p>

答:
I found this .VBS script on the internet. It has the cool advantage of actually working on machines where I cannot get NETSH to work for this purpose.</p>

```<code>Const ssfCONTROLS = 3

sConnectionName = "Local Area Connection"

sEnableVerb = "En&able"
sDisableVerb = "Disa&ble"

set shellApp = createobject("shell.application")
set oControlPanel = shellApp.Namespace(ssfCONTROLS)

set oNetConnections = nothing
for each folderitem in oControlPanel.items
  if folderitem.name = "Network Connections" then
        set oNetConnections = folderitem.getfolder: exit for
end if
next

if oNetConnections is nothing then
msgbox "Couldn't find 'Network Connections' folder"
wscript.quit
end if

set oLanConnection = nothing
for each folderitem in oNetConnections.items
if lcase(folderitem.name) = lcase(sConnectionName) then
set oLanConnection = folderitem: exit for
end if
next

if oLanConnection is nothing then
msgbox "Couldn't find '" & sConnectionName & "' item"
wscript.quit
end if

bEnabled = true
set oEnableVerb = nothing
set oDisableVerb = nothing
s = "Verbs: " & vbcrlf
for each verb in oLanConnection.verbs
s = s & vbcrlf & verb.name
if verb.name = sEnableVerb then
set oEnableVerb = verb
bEnabled = false
end if
if verb.name = sDisableVerb then
set oDisableVerb = verb
end if
next

'debugging displays left just in case...
'
'msgbox s ': wscript.quit
'msgbox "Enabled: " & bEnabled ': wscript.quit

'not sure why, but invokeverb always seemed to work
'for enable but not disable.
'
'saving a reference to the appropriate verb object
'and calling the DoIt method always seems to work.
'
if bEnabled then
' oLanConnection.invokeverb sDisableVerb
oDisableVerb.DoIt
else
' oLanConnection.invokeverb sEnableVerb
oEnableVerb.DoIt
end if

'adjust the sleep duration below as needed...
'
'if you let the oLanConnection go out of scope
'and be destroyed too soon, the action of the verb
'may not take...
'
wscript.sleep 1000
</code>```

OwnerDisplayName: ΤΖΩΤΖΙΟΥ

ContentLicense: CC BY-SA 2.5

Body:
I found this .VBS script on the internet. It has the cool advantage of actually working on machines where I cannot get NETSH to work for this purpose.

Const ssfCONTROLS = 3

sConnectionName = "Local Area Connection"

sEnableVerb = "En&able"
sDisableVerb = "Disa&ble"

set shellApp = createobject("shell.application")
set oControlPanel = shellApp.Namespace(ssfCONTROLS)

set oNetConnections = nothing
for each folderitem in oControlPanel.items
  if folderitem.name = "Network Connections" then
        set oNetConnections = folderitem.getfolder: exit for
end if
next

if oNetConnections is nothing then
msgbox "Couldn't find 'Network Connections' folder"
wscript.quit
end if

set oLanConnection = nothing
for each folderitem in oNetConnections.items
if lcase(folderitem.name) = lcase(sConnectionName) then
set oLanConnection = folderitem: exit for
end if
next

if oLanConnection is nothing then
msgbox "Couldn't find '" & sConnectionName & "' item"
wscript.quit
end if

bEnabled = true
set oEnableVerb = nothing
set oDisableVerb = nothing
s = "Verbs: " & vbcrlf
for each verb in oLanConnection.verbs
s = s & vbcrlf & verb.name
if verb.name = sEnableVerb then
set oEnableVerb = verb
bEnabled = false
end if
if verb.name = sDisableVerb then
set oDisableVerb = verb
end if
next

'debugging displays left just in case...
'
'msgbox s ': wscript.quit
'msgbox "Enabled: " & bEnabled ': wscript.quit

'not sure why, but invokeverb always seemed to work
'for enable but not disable.
'
'saving a reference to the appropriate verb object
'and calling the DoIt method always seems to work.
'
if bEnabled then
' oLanConnection.invokeverb sDisableVerb
oDisableVerb.DoIt
else
' oLanConnection.invokeverb sEnableVerb
oEnableVerb.DoIt
end if

'adjust the sleep duration below as needed...
'
'if you let the oLanConnection go out of scope
'and be destroyed too soon, the action of the verb
'may not take...
'
wscript.sleep 1000


问:
How to remove exterior punctuation from a string using regular expressions
Given a string like below, remove any leading and trailing punctuation via regular expressions:

```<code>String a = "!?Don't.;, .:delete !the@ $actual string%";
String b = "Hyphenated-words, too!";
</code>```

I know that the regex [\P{Alnum}] will target all non-alphanumeric characters, but how do I target ONLY the leading and trailing punctuation so I get...

```<code>a = "Don't delete the actual string";
b = "Hyphenated-words too";
</code>```

... instead of:

```<code>a = "Dont delete the actual string";
b = "Hyphenated words too";
</code>```

I just need the regular expression; not the actual code to remove the punctuation.

答:
You want to match punctuation that is adjacent to a) a whitespace character OR b) the beginning or end.

your pattern preceded by (?<=^|\s) positive lookbehind, or

your pattern followed by (?=\s|$) positive lookahead

To shorten the pattern, we could reword this a little bit to say that our punctuation block must either a) not preceded by some character that's not a whitespace or b) not followed by a  character that's not a whitespace.

your pattern preceded by (?<!\S) negative lookbehind, or

your pattern followed by (?!\S) negative lookahead

As a final note, you should use \p{Punct} instead of [\P{Alnum}] to match punctuation. See the comment by sln for details.

Here is an example usage:

```<code>String a = "!?Don't.;, .:delete !the@ $actual string%";
String b = "Hyphenated-words, too!";
String regex = "(?:(?<!\\S)\\p{Punct}+)|(?:\\p{Punct}+(?!\\S))";
System.out.println(a.replaceAll(regex, ""));
System.out.println(b.replaceAll(regex, ""));
</code>```

Output:

Don't delete the actual string

Hyphenated-words too

Body:
Given a string like below, remove any leading and trailing punctuation via regular expressions:

String a = "!?Don't.;, .:delete !the@ $actual string%";
String b = "Hyphenated-words, too!";

I know that the regex [\P{Alnum}] will target all non-alphanumeric characters, but how do I target ONLY the leading and trailing punctuation so I get...

a = "Don't delete the actual string";
b = "Hyphenated-words too";

... instead of:

a = "Dont delete the actual string";
b = "Hyphenated words too";

I just need the regular expression; not the actual code to remove the punctuation.

Body:
You want to match punctuation that is adjacent to a) a whitespace character OR b) the beginning or end.

your pattern preceded by (?<=^|\s) positive lookbehind, or

your pattern followed by (?=\s|$) positive lookahead

To shorten the pattern, we could reword this a little bit to say that our punctuation block must either a) not preceded by some character that's not a whitespace or b) not followed by a  character that's not a whitespace.

your pattern preceded by (?<!\S) negative lookbehind, or

your pattern followed by (?!\S) negative lookahead

As a final note, you should use \p{Punct} instead of [\P{Alnum}] to match punctuation. See the comment by sln for details.

Here is an example usage:

String a = "!?Don't.;, .:delete !the@ $actual string%";
String b = "Hyphenated-words, too!";
String regex = "(?:(?<!\\S)\\p{Punct}+)|(?:\\p{Punct}+(?!\\S))";
System.out.println(a.replaceAll(regex, ""));
System.out.println(b.replaceAll(regex, ""));

Output:

Don't delete the actual string

Hyphenated-words too


问:
C# WPF MVVM TabItem HeaderTemplate won't work?
I am currently working on an application with a TabControl, and every tab has a ViewModel which inherits from ITabViewModel, which has two properties: HeaderText and HeaderImage. I would like these to be set from each ViewModel. Thus, I attempted to use a HeaderTemplate style, but this did not work. Could anyone tell me how I could get this to work?

```<code><TabControl>
    <TabControl.Resources>
        <Style TargetType="TabItem" BasedOn="{StaticResource {x:Type TabItem}}">
            <Setter Property="HeaderTemplate">
                <Setter.Value>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal">
                            <Image Source="{Binding HeaderImage}" Height="20" Margin="5, 0"/>
                            <TextBlock Text="{Binding HeaderText}"/>
                        </StackPanel>
                    </DataTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </TabControl.Resources>

    <TabItem DataContext="{Binding ViewModelStart}">

    </TabItem>

    <TabItem DataContext="{Binding ViewModelStartupManager}">

    </TabItem>
</TabControl>
</code>```

答:
You need to set the Header property of aTabItem for the HeaderTemplate to get applied:

```<code><TabItem DataContext="{Binding ViewModelStart}" Header="{Binding}">

</TabItem>

<TabItem DataContext="{Binding ViewModelStartupManager}" Header="{Binding}">

</TabItem>
</code>```

This works:

```<code><TabControl>
    <TabControl.Resources>
        <Style TargetType="TabItem" BasedOn="{StaticResource {x:Type TabItem}}">
            <Setter Property="HeaderTemplate">
                <Setter.Value>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal">
                            <Image Source="{Binding HeaderImage}" Height="20" Margin="5, 0"/>
                            <TextBlock Text="{Binding HeaderText}"/>
                        </StackPanel>
                    </DataTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </TabControl.Resources>

    <TabItem DataContext="{Binding ViewModelStart}" Header="{Binding}">

    </TabItem>

    <TabItem DataContext="{Binding ViewModelStartupManager}" Header="{Binding}">

    </TabItem>
</TabControl>
</code>```

Body:
I am currently working on an application with a TabControl, and every tab has a ViewModel which inherits from ITabViewModel, which has two properties: HeaderText and HeaderImage. I would like these to be set from each ViewModel. Thus, I attempted to use a HeaderTemplate style, but this did not work. Could anyone tell me how I could get this to work?

<TabControl>
    <TabControl.Resources>

    </TabControl.Resources>

    <TabItem DataContext="{Binding ViewModelStart}">

    </TabItem>

    <TabItem DataContext="{Binding ViewModelStartupManager}">

    </TabItem>
</TabControl>

Body:
You need to set the Header property of aTabItem for the HeaderTemplate to get applied:

<TabItem DataContext="{Binding ViewModelStart}" Header="{Binding}">

</TabItem>

<TabItem DataContext="{Binding ViewModelStartupManager}" Header="{Binding}">

</TabItem>

This works:

<TabControl>
    <TabControl.Resources>
        <Style TargetType="TabItem" BasedOn="{StaticResource {x:Type TabItem}}">
            <Setter Property="HeaderTemplate">
                <Setter.Value>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal">
                            <Image Source="{Binding HeaderImage}" Height="20" Margin="5, 0"/>
                            <TextBlock Text="{Binding HeaderText}"/>
                        </StackPanel>
                    </DataTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </TabControl.Resources>

    <TabItem DataContext="{Binding ViewModelStart}" Header="{Binding}">

    </TabItem>

    <TabItem DataContext="{Binding ViewModelStartupManager}" Header="{Binding}">

    </TabItem>
</TabControl>


问:
Express server serves my static files but does not handle requests to my API. What is happening?
I built a small app on top of a company's API. I created my own API to interact with their's. My app uses React-Create-App to scaffold, with Redux, and the server is Experss/Node.js. It works totally fine on localhost but when I deploy it on Heroku, it serves the bundle but doesn't hand any user http requests to the server. It returns a 404 not found. Heroku gives no errors in their logs.

My post install script runs the build, which bundles the app. I have set environment port variable in the heroku dashboard as well.

package.json

{
  "name": "event.me",
  "version": "0.1.0",
  "private": true,
    "engines":{
    "node": "7.2.1",
    "npm": "3.10.10"
  },
  "dependencies": {
    "axios": "^0.15.3",
    "body-parser": "^1.17.1",
    "express": "^4.15.2",
    "moment": "^2.18.1",
    "react": "^15.4.2",
    "react-dom": "^15.4.2",
    "react-progressbar.js": "^0.2.0",
    "react-redux": "^5.0.3",
    "react-router": "^3.0.0",
    "react-router-dom": "^4.0.0",
    "redux": "^3.6.0",
    "redux-logger": "^3.0.0",
    "redux-thunk": "^2.2.0"
  },
  "devDependencies": {
    "eslint": "^3.18.0",
    "eslint-config-airbnb": "^14.1.0",
    "eslint-plugin-jsx-a11y": "^4.0.0",
    "eslint-plugin-react": "^6.9.0",
    "eslint-plugin-import": "^2.2.0",
    "nodemon": "^1.11.0",
    "react-scripts": "0.9.5"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject",
    "server": "node server/server.js",
    "postinstall": "npm run build"
  }
}```
</div>
</div>
</p>

<p>server.js file
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const routes = require('./routes');

const app = express();

app.use(express.static(path.resolve(__dirname, '..', 'build')));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use('/api', routes);
const port = process.env.PORT || 8080;

app.listen(port, () => console.log(`Listening on ${port}`));</code>```

routes.js

const routes = require('express').Router();
const users = require('./controllers/users.js');
const events = require('./controllers/events.js');

routes.post('/sigin', users.signin);
routes.post('/signup', users.signup);
routes.get('/events', events.getAll);
routes.post('/events', events.attendEvent);
routes.delete('/events', events.flakeEvent);
routes.patch('/events', events.updateEvent);
routes.delete('/singleevent', events.deleteEvent);
routes.post('/createevent', events.createEvent);

module.exports = routes;```

答:
If you are using Create React App, one of the things you must do if you want Webpack to be used as proxy when calling your API is to set in your package.json:

```<code>...
"proxy": "http://localhost:3030",
...
</code>```

Thus you use Webpack included in Create React App to proxy all the calls to your API and do not need an extra server.
For Heroku deployment you need to change localhost for Heroku URL and 3030 for your established port in Express server (process.env.PORT).

That's where I think the problem lies.

Also, you have to route your non API petitions to your index.html.
Add this to your server.js.

```<code>app.get('*', (req, res) => {
    const way = path.join(__dirname, 'build', 'index.html');
    res.sendFile(way);
  });
</code>```

Body:
I built a small app on top of a company's API. I created my own API to interact with their's. My app uses React-Create-App to scaffold, with Redux, and the server is Experss/Node.js. It works totally fine on localhost but when I deploy it on Heroku, it serves the bundle but doesn't hand any user http requests to the server. It returns a 404 not found. Heroku gives no errors in their logs.

My post install script runs the build, which bundles the app. I have set environment port variable in the heroku dashboard as well.

package.json

{
  "name": "event.me",
  "version": "0.1.0",
  "private": true,
    "engines":{
    "node": "7.2.1",
    "npm": "3.10.10"
  },
  "dependencies": {
    "axios": "^0.15.3",
    "body-parser": "^1.17.1",
    "express": "^4.15.2",
    "moment": "^2.18.1",
    "react": "^15.4.2",
    "react-dom": "^15.4.2",
    "react-progressbar.js": "^0.2.0",
    "react-redux": "^5.0.3",
    "react-router": "^3.0.0",
    "react-router-dom": "^4.0.0",
    "redux": "^3.6.0",
    "redux-logger": "^3.0.0",
    "redux-thunk": "^2.2.0"
  },
  "devDependencies": {
    "eslint": "^3.18.0",
    "eslint-config-airbnb": "^14.1.0",
    "eslint-plugin-jsx-a11y": "^4.0.0",
    "eslint-plugin-react": "^6.9.0",
    "eslint-plugin-import": "^2.2.0",
    "nodemon": "^1.11.0",
    "react-scripts": "0.9.5"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject",
    "server": "node server/server.js",
    "postinstall": "npm run build"
  }
}

server.js file

const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const routes = require('./routes');

const app = express();

app.use(express.static(path.resolve(__dirname, '..', 'build')));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use('/api', routes);
const port = process.env.PORT || 8080;

app.listen(port, () => console.log(`Listening on ${port}`));

routes.js

const routes = require('express').Router();
const users = require('./controllers/users.js');
const events = require('./controllers/events.js');

routes.post('/sigin', users.signin);
routes.post('/signup', users.signup);
routes.get('/events', events.getAll);
routes.post('/events', events.attendEvent);
routes.delete('/events', events.flakeEvent);
routes.patch('/events', events.updateEvent);
routes.delete('/singleevent', events.deleteEvent);
routes.post('/createevent', events.createEvent);

module.exports = routes;

Body:
If you are using Create React App, one of the things you must do if you want Webpack to be used as proxy when calling your API is to set in your package.json:

...
"proxy": "http://localhost:3030",
...

Thus you use Webpack included in Create React App to proxy all the calls to your API and do not need an extra server.
For Heroku deployment you need to change localhost for Heroku URL and 3030 for your established port in Express server (process.env.PORT).

That's where I think the problem lies.

Also, you have to route your non API petitions to your index.html.
Add this to your server.js.

app.get('*', (req, res) => {
    const way = path.join(__dirname, 'build', 'index.html');
    res.sendFile(way);
  });


问:
Using find fact in CLIPS
I have a fact

```<code>(is-started TRUE)
</code>```

I want to find if the fact exists with

```<code>(any-factp ((?is (is-started TRUE))) TRUE)
</code>```

but this gives me Missing function declaration for is-started.

How can i determine if this fact exists with any-factp?

答:
The fields of an implied deftemplate fact can be accessed using the implicitly defined multifield slot named implied:</p>

```<code>CLIPS> (assert (is-started TRUE))
<Fact-1>
CLIPS> (any-factp ((?f is-started)) TRUE)
TRUE
CLIPS> (any-factp ((?f is-started)) (eq ?f:implied (create$ TRUE)))
TRUE
CLIPS> (any-factp ((?f is-started)) (eq ?f:implied (create$)))
FALSE
CLIPS>
</code>```

Title: Using find fact in CLIPS

Body:
I have a fact

(is-started TRUE)

I want to find if the fact exists with

(any-factp ((?is (is-started TRUE))) TRUE)

but this gives me Missing function declaration for is-started.

How can i determine if this fact exists with any-factp?

Body:
The fields of an implied deftemplate fact can be accessed using the implicitly defined multifield slot named implied:

CLIPS> (assert (is-started TRUE))
<Fact-1>
CLIPS> (any-factp ((?f is-started)) TRUE)
TRUE
CLIPS> (any-factp ((?f is-started)) (eq ?f:implied (create$ TRUE)))
TRUE
CLIPS> (any-factp ((?f is-started)) (eq ?f:implied (create$)))
FALSE
CLIPS>


问:
Trying to get any response when connecting from Android to my web service (SOAP 1.1)
This is my only class where i get connected to my web service :

```<code>    public class Main extends Activity {
    /** Called when the activity is first created. */

 private static final String SOAP_ACTION="http://tempuri.org/getme/TSM/LogOn";
 private static final String METHOD_NAME="LogOn";
 private static final String NAMESPACE="http://tempuri.org/getme/TSM/";
 private static final String URL="http://theking/eget/WebService/WSAuth.asmx";

 @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        TextView tv = (TextView) findViewById(R.id.TextView01);

        SoapObject Request = new SoapObject(NAMESPACE, METHOD_NAME);
        Request.addProperty("strUsername", "Test");
        Request.addProperty("strPassword", "Test123");
        Request.addProperty("strMessage", "hello");

        SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        soapEnvelope.dotNet = true;
        soapEnvelope.setOutputSoapObject(Request);

        AndroidHttpTransport aht = new AndroidHttpTransport(URL);
        try
        {
         aht.call(SOAP_ACTION, soapEnvelope);
         SoapObject response = (SoapObject)soapEnvelope.getResponse();
            String LogonResult =  response.getProperty(0).toString();
            String MessageResult =  response.getProperty(1).toString();
         tv.setText("Status : " + LogonResult + " Message: " + MessageResult);
        }
        catch(Exception e)
        {
         e.printStackTrace();
        }

    } }
</code>```

I think it breaks before the TRY tag.. all i get on the virtual screen is : false.
Any solutions.. i don't know where is the problem ?

The following is a sample SOAP request and response.

```<code><soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <LogOn xmlns="http://tempuri.org/getme/TSM">
      <strUsername>string</strUsername>
      <strPassword>string</strPassword>
      <strMessage>string</strMessage>
    </LogOn>
  </soap:Body>
</soap:Envelope>

    <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <LogOnResponse xmlns="http://tempuri.org/getme/TSM">
      <LogOnResult>int</LogOnResult>
      <strMessage>string</strMessage>
    </LogOnResponse>
  </soap:Body>
</soap:Envelope>
</code>```

答:
make sure that in your android application config file you have allowed remote access.

Also try pasting the URL into a browser and see whether it is correct.

Also set a breakpoint or log in a file to determine whether the service will get invoked.

Body:
This is my only class where i get connected to my web service :

    public class Main extends Activity {
    /** Called when the activity is first created. */

 private static final String SOAP_ACTION="http://tempuri.org/getme/TSM/LogOn";
 private static final String METHOD_NAME="LogOn";
 private static final String NAMESPACE="http://tempuri.org/getme/TSM/";
 private static final String URL="http://theking/eget/WebService/WSAuth.asmx";

 @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        TextView tv = (TextView) findViewById(R.id.TextView01);

        SoapObject Request = new SoapObject(NAMESPACE, METHOD_NAME);
        Request.addProperty("strUsername", "Test");
        Request.addProperty("strPassword", "Test123");
        Request.addProperty("strMessage", "hello");

        SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        soapEnvelope.dotNet = true;
        soapEnvelope.setOutputSoapObject(Request);

        AndroidHttpTransport aht = new AndroidHttpTransport(URL);
        try
        {
         aht.call(SOAP_ACTION, soapEnvelope);
         SoapObject response = (SoapObject)soapEnvelope.getResponse();
            String LogonResult =  response.getProperty(0).toString();
            String MessageResult =  response.getProperty(1).toString();
         tv.setText("Status : " + LogonResult + " Message: " + MessageResult);
        }
        catch(Exception e)
        {
         e.printStackTrace();
        }

    } }

I think it breaks before the TRY tag.. all i get on the virtual screen is : false.
Any solutions.. i don't know where is the problem ?

The following is a sample SOAP request and response.

<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <LogOn xmlns="http://tempuri.org/getme/TSM">
      <strUsername>string</strUsername>
      <strPassword>string</strPassword>
      <strMessage>string</strMessage>
    </LogOn>
  </soap:Body>
</soap:Envelope>

    <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <LogOnResponse xmlns="http://tempuri.org/getme/TSM">
      <LogOnResult>int</LogOnResult>
      <strMessage>string</strMessage>
    </LogOnResponse>
  </soap:Body>
</soap:Envelope>


问:
In python, how do I open a new window by clicking a button in a main window using .py files created from .ui files made in QtDesigner?
I have two .py files created from .ui files made in QtDesigner. One is a main window for the program, and the other is a widget that allows users to input information and I'm calling it the "evaluation" widget.

I have a button in the main window called "btn_StartNew", which is meant to open the widget window to allow the user to start a new evaluation. I'm having troubles with opening the main window, and adding the function to the "btn_StartNew" button that opens the "evaluation" widget.

The code I have right now opens both the main window and the evaluation widget in the same window when I run the code:

```<code>import sys
from PyQt4 import QtCore, QtGui
from wid_Main import Ui_wid_Main
from wid_Eval_v2 import Ui_wid_Eval

class Win_Eval(QtGui.QWidget):
     def __init__(self, parent=None):
        super(Win_Eval, self).__init__(parent)

        self.ui=Ui_wid_Eval()
        self.ui.setupUi(self)

class Win_Main(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(Win_Main, self).__init__(parent)

        self.ui=Ui_wid_Main()
        self.ui.setupUi(self)

        #RUN "start new eval" button
        self.ui.btn_StartNew.clicked.connect(self.btn_StartNew_click)
        self.dialog = Win_Eval(self)

   def btn_StartNew_click(self):
        self.dialog.show()

def main():
    app = QtGui.QApplication(sys.argv)
    main = Win_Main()
    main.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()
</code>```

Where wid_Main and Ui_wid_Main are the main window file and the main window class, respectively. And wid_Eval_v2 and Ui_wid_Eval are the evaluation widget file and class, respectively.

Any help would be much appreciated!

答:
You must change:

```<code>self.dialog = Win_Eval(self)
</code>```

to

```<code>self.dialog = Win_Eval()
</code>```

Body:
I have two .py files created from .ui files made in QtDesigner. One is a main window for the program, and the other is a widget that allows users to input information and I'm calling it the "evaluation" widget.

I have a button in the main window called "btn_StartNew", which is meant to open the widget window to allow the user to start a new evaluation. I'm having troubles with opening the main window, and adding the function to the "btn_StartNew" button that opens the "evaluation" widget.

The code I have right now opens both the main window and the evaluation widget in the same window when I run the code:

import sys
from PyQt4 import QtCore, QtGui
from wid_Main import Ui_wid_Main
from wid_Eval_v2 import Ui_wid_Eval

class Win_Eval(QtGui.QWidget):
     def __init__(self, parent=None):
        super(Win_Eval, self).__init__(parent)

        self.ui=Ui_wid_Eval()
        self.ui.setupUi(self)

class Win_Main(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(Win_Main, self).__init__(parent)

        self.ui=Ui_wid_Main()
        self.ui.setupUi(self)

        #RUN "start new eval" button
        self.ui.btn_StartNew.clicked.connect(self.btn_StartNew_click)
        self.dialog = Win_Eval(self)

   def btn_StartNew_click(self):
        self.dialog.show()

def main():
    app = QtGui.QApplication(sys.argv)
    main = Win_Main()
    main.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

Where wid_Main and Ui_wid_Main are the main window file and the main window class, respectively. And wid_Eval_v2 and Ui_wid_Eval are the evaluation widget file and class, respectively.

Any help would be much appreciated!

Body:
You must change:

self.dialog = Win_Eval(self)

to

self.dialog = Win_Eval()


问:
Exception format for parsers written in Node.js
I'm writing parsers in Node.js for some file formats. When a parser detects an error, an exception will be thrown. For the exact format of the exception, I figure it would be best if I go with something that's already a de facto standard. So I looked at Acorn and Esprima to see what kind of exceptions they throw... and they disagree on format.

So what is the closest thing to a standard/preferred parser exception format?

答: The closet thing to a true standard that I know of, assuming your parser runs in a shell, is to return a non-zero exit code from your process if the parsing was unsuccessful.  Other than that, not sure how there could be too much of a standard outside of some uber-parsing protocol, because different file formats can have very different semantics and syntax and so very different semantic or syntax errors.</p>


问:
Regex in Python?
I have a string:

```<code>line = "https://dbwebb.se/kunskap/uml#sequence, ftp://bth.com:32/files/im.jpeg, file://localhost:8585/zipit, http://v2-dbwebb.se/do%hack"
</code>```

I want to get this result:

```<code>[('https', 'dbwebb.se', ''), ('ftp', 'bth.com', '32'), ('file', 'localhost', '8585'), ('http', 'v2-dbwebb.se', '')]
</code>```

I tried this:

```<code>match = re.findall("(^[a-z]+[^://](^[a-z]+\d))", line)
</code>```

I'm a beginner in Python.  If there is somebody who can explain, it would be very nice :D

答:
Python urlparse is the module you need to do all of the work, it has a urlparse constructor function that will parse a URL. The interesting parts of the URL can then be extracted from this object as attribute names. Here is the code:

```<code>
import urlparse

line = "https://dbwebb.se/kunskap/uml#sequence, ftp://bth.com:32/files/im.jpeg,file://localhost:8585/zipit, http://v2-dbwebb.se/do%hack"

# you want the port as a string so adjust it here
def port2str(port):
    if port: return str(port)
    else: return ''

urls = [x.strip() for x in line.split(',')]
result = map(lambda u: (u.scheme, u.hostname, port2str(u.port)), map(lambda url: urlparse.urlparse(url), urls))
print result

</code>```

The code first breaks your input to an array of strings; note that they need to be clean up (stripped) as some have leading spaces which would break the parser. Then this array is converted to an array of parsed url objects, which is then converted to an array of tuples you want. The reason this is done in two steps here is that unfortunately the python lambda is very restrictive -- it cannot contain statements.
(I assumed the \file was a typo)

Title: Regex in Python?

Body:
I have a string:

line = "https://dbwebb.se/kunskap/uml#sequence, ftp://bth.com:32/files/im.jpeg, file://localhost:8585/zipit, http://v2-dbwebb.se/do%hack"

I want to get this result:

[('https', 'dbwebb.se', ''), ('ftp', 'bth.com', '32'), ('file', 'localhost', '8585'), ('http', 'v2-dbwebb.se', '')]

I tried this:

match = re.findall("(^[a-z]+[^://](^[a-z]+\d))", line)

I'm a beginner in Python.  If there is somebody who can explain, it would be very nice :D

Body:
Python urlparse is the module you need to do all of the work, it has a urlparse constructor function that will parse a URL. The interesting parts of the URL can then be extracted from this object as attribute names. Here is the code:

import urlparse

line = "https://dbwebb.se/kunskap/uml#sequence, ftp://bth.com:32/files/im.jpeg,file://localhost:8585/zipit, http://v2-dbwebb.se/do%hack"

# you want the port as a string so adjust it here
def port2str(port):
    if port: return str(port)
    else: return ''

urls = [x.strip() for x in line.split(',')]
result = map(lambda u: (u.scheme, u.hostname, port2str(u.port)), map(lambda url: urlparse.urlparse(url), urls))
print result

The code first breaks your input to an array of strings; note that they need to be clean up (stripped) as some have leading spaces which would break the parser. Then this array is converted to an array of parsed url objects, which is then converted to an array of tuples you want. The reason this is done in two steps here is that unfortunately the python lambda is very restrictive -- it cannot contain statements.
(I assumed the \file was a typo)


问:
Multiple "sed" actions on previous results
Have this input:

```<code>bar foo
foo ABC/DEF
BAR ABC
ABC foo DEF
foo bar
</code>```

on the above I need do 4 (sequential) actions:

select only lines containing "foo" (lowercase)

on the selected lines, remove everything but UPPERCASE letters

delete empty lines (if some is created by the previous action)

and on the remaining from the above - enclose every char with [x]

I'm able to solve the above, but need two sed invocations piped together. Script:

```<code>#!/bin/bash
data() {
cat <<EOF
bar foo
foo ABC/DEF
BAR ABC
ABC foo DEF
foo bar
EOF
}

echo "Result OK"
data | sed -n '/foo/s/[^A-Z]//gp' | sed '/^\s*$/d;s/./[&]/g'

# in the above it is solved using 2 sed invocations
# trying to solve it using only one invocation,
# but the following doesn't do what i need.. :( :(

echo "Variant 2 - trying to use only ONE invocation of sed"
data | sed -n '/foo/s/[^A-Z]//g;/^\s*$/d;s/./[&]/gp'
</code>```

output from the above:

```<code>Result OK
[A][B][C][D][E][F]
[A][B][C][D][E][F]
Variant 2 - trying to use only ONE invocation of sed
[A][B][C][D][E][F]
[B][A][R][ ][A][B][C]
[A][B][C][D][E][F]
</code>```

The variant 2 should be also only

```<code>[A][B][C][D][E][F]
[A][B][C][D][E][F]
</code>```

It is possible to solve the above using only by one sed invocation?

Body:
Have this input:

bar foo
foo ABC/DEF
BAR ABC
ABC foo DEF
foo bar

on the above I need do 4 (sequential) actions:

select only lines containing "foo" (lowercase)

on the selected lines, remove everything but UPPERCASE letters

delete empty lines (if some is created by the previous action)

and on the remaining from the above - enclose every char with [x]

I'm able to solve the above, but need two sed invocations piped together. Script:

#!/bin/bash
data() {
cat <<EOF
bar foo
foo ABC/DEF
BAR ABC
ABC foo DEF
foo bar
EOF
}

echo "Result OK"
data | sed -n '/foo/s/[^A-Z]//gp' | sed '/^\s*$/d;s/./[&]/g'

# in the above it is solved using 2 sed invocations
# trying to solve it using only one invocation,
# but the following doesn't do what i need.. :( :(

echo "Variant 2 - trying to use only ONE invocation of sed"
data | sed -n '/foo/s/[^A-Z]//g;/^\s*$/d;s/./[&]/gp'

output from the above:

Result OK
[A][B][C][D][E][F]
[A][B][C][D][E][F]
Variant 2 - trying to use only ONE invocation of sed
[A][B][C][D][E][F]
[B][A][R][ ][A][B][C]
[A][B][C][D][E][F]

The variant 2 should be also only

[A][B][C][D][E][F]
[A][B][C][D][E][F]

It is possible to solve the above using only by one sed invocation?

Body:
sed -n '/foo/{s/[^A-Z]//g;/^$/d;s/./[&]/g;p;}' inputfile

Output:

[A][B][C][D][E][F]
[A][B][C][D][E][F]


问:
Relation of c# name space and file
How is a C# namespace related to the physical representation of the program in files and folders?

When one uses a using directive, e.g.:

```<code>using MyNameSpace;
</code>```

Where does does the C# compiler look for that namespace? Is there some documentation which covers the relationship of logical entities like namespaces and classes with their physical representations?

My .csproj file just contains

```<code><Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp1.1</TargetFramework>
  </PropertyGroup>

</Project>
</code>```

Nevertheless it seems to compile all .cs files in the project. I am using Visual Studio Code and want to understand the magic that is going on.

答: The page Additions to the csproj format for .NET Core from the .NET core guide explains that the SDK referenced in the .csproj file contains definitions of globbing expressions (i.e., **/*.cs) which are used to locate source files in the project.

Title: Relation of c# name space and file

Body:
How is a C# namespace related to the physical representation of the program in files and folders?

When one uses a using directive, e.g.:

using MyNameSpace;

Where does does the C# compiler look for that namespace? Is there some documentation which covers the relationship of logical entities like namespaces and classes with their physical representations?

My .csproj file just contains

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp1.1</TargetFramework>
  </PropertyGroup>

</Project>

Nevertheless it seems to compile all .cs files in the project. I am using Visual Studio Code and want to understand the magic that is going on.


问:
Directly using a list saved in an auxiliary file
Is there a way to save a list in an auxiliary file and then manipulate it directly, without having to download it, manipulate it, and then rewriting the file?

Namely, I would like to be able to do e.g. something like this:

```<code>L = open('file')
L.append(0)
L.close()
</code>```

What is the correct way to do it? Is there a specific class for it?

I solved the problem using shelve (a pickle-based library) as follows:

```<code>import shelve

f = shelve.open('list.db',writeback=True)
f['0'] = the list I want
L = f['0']

Manipulate L however I want

f.close()
</code>```

答:
depending in what you are doing, you can save each element in your list in a line of your file, thus making easy to append new stuff to the file, for example

lets said this is yours original file

```<code>>>> data = [1,2,3]
>>> with open("test file.txt","w") as file:
        file.write("\n".join(map(str,data)))

5
>>>
</code>```

and this is the new stuff you want to add, then you only need to open the file in append mode ("a")

```<code>>>> new_data = [4,5,6]
>>> with open("test file.txt","a") as file:
        file.write("\n")
        file.write("\n".join(map(str,new_data)))

1
5
>>>
</code>```

now the file have both data, which you can recover at any time, like this for example

```<code>>>> with open("test file.txt") as file:
        [int(line) for line in file]

[1, 2, 3, 4, 5, 6]
>>>
</code>```

Body:
Is there a way to save a list in an auxiliary file and then manipulate it directly, without having to download it, manipulate it, and then rewriting the file?

Namely, I would like to be able to do e.g. something like this:

L = open('file')
L.append(0)
L.close()

What is the correct way to do it? Is there a specific class for it?

I solved the problem using shelve (a pickle-based library) as follows:

import shelve

f = shelve.open('list.db',writeback=True)
f['0'] = the list I want
L = f['0']

Manipulate L however I want

f.close()

Body:
depending in what you are doing, you can save each element in your list in a line of your file, thus making easy to append new stuff to the file, for example

lets said this is yours original file

>>> data = [1,2,3]
>>> with open("test file.txt","w") as file:
        file.write("\n".join(map(str,data)))

5
>>>

and this is the new stuff you want to add, then you only need to open the file in append mode ("a")

>>> new_data = [4,5,6]
>>> with open("test file.txt","a") as file:
        file.write("\n")
        file.write("\n".join(map(str,new_data)))

1
5
>>>

now the file have both data, which you can recover at any time, like this for example

>>> with open("test file.txt") as file:
        [int(line) for line in file]

[1, 2, 3, 4, 5, 6]
>>>


问:
A noob programmers first try
Hey so I am currently trying to get a plane to move on a window, from each extremity to the other, following this order: from upper left to upper right, from upper right to lower right, from lower right to lower left followed by lower left to upper left. This project is forced to have an accelerated movement from the upper right to the lower right and from the lower left to the upper left. I used a switch case just like I would in java but it doesn't seem to be stopping when the plane hits the windows max width.. any help would be appreciated ...</p>

```<code>    var ctx;
var img;
var larg = 1200;
var alt = 560;
var xAviao = 0;
var yAviao = 0;
c = 1

// Parâmetros do movimento acelerado
var x0 = 0;
var y0 = 0;
var v0 = 0;
var a = 120;    // 120 px/s2
var t = 0;

function init() {
canvas = document.getElementById("cvs");
ctx = canvas.getContext("2d");

canvas.setAttribute("width", larg);
canvas.setAttribute("height", alt);

img = new Image();
img.src = "aviao.png";

gameLoop();
}

function gameLoop() {
window.requestAnimationFrame(gameLoop);
update();
render();
}

function update() {
var direction = 1;
if( xAviao > ( larg - img.Width ) )
    {
        y0 = 0;
        a = 120;
        t = 0;
        xAviao = ( larg - img.Width );
        direcao = 2;
    }
    else if ( yAviao > alt - img.Height )
    {
        yAviao = alt - aviao.Height;
        direction = 3;
    }
    else if ( xAviao < 0 )
    {
        xAviao = 0;
        t = 0;
        y0 = yAviao;
        a= -120;
        direction = 4;
    }
    else if ( yAviao < 0 )
    {
        yAviao = 0;
        direction = 1;
    }

switch(direction){
    case 1:

        xAviao +=10 ;
    console.log(c);
    break;
    case 2:
        t += 1/60;  // time increases 60 seconds per 60 frames
        yAviao = Math.floor( y0 + v0*t + a*t*t );
    break;
    case 3:
        xAviao -= 10;
    break;
    case 4:
        t += 1/60;  // time increases 60 seconds per 60 frames
        yAviao = Math.floor( y0 + v0*t + a*t*t );
    break;
    }
}

function render() {
// Retângulo do fundo
ctx.fillStyle = "#FFA060";
ctx.beginPath();
ctx.rect(0,0,larg,alt);
ctx.fill();

// Desenha o avião
if(img != undefined)
    ctx.drawImage(img, xAviao, yAviao);
}
</code>```

答: I think that you have a simple typo in the first if statememt in the update function. Shouldn't direcao = 2 be direction = 2?

Title: A noob programmers first try

Body:
Hey so I am currently trying to get a plane to move on a window, from each extremity to the other, following this order: from upper left to upper right, from upper right to lower right, from lower right to lower left followed by lower left to upper left. This project is forced to have an accelerated movement from the upper right to the lower right and from the lower left to the upper left. I used a switch case just like I would in java but it doesn't seem to be stopping when the plane hits the windows max width.. any help would be appreciated ...

    var ctx;
var img;
var larg = 1200;
var alt = 560;
var xAviao = 0;
var yAviao = 0;
c = 1

// Parâmetros do movimento acelerado
var x0 = 0;
var y0 = 0;
var v0 = 0;
var a = 120;    // 120 px/s2
var t = 0;

function init() {
canvas = document.getElementById("cvs");
ctx = canvas.getContext("2d");

canvas.setAttribute("width", larg);
canvas.setAttribute("height", alt);

img = new Image();
img.src = "aviao.png";

gameLoop();
}

function gameLoop() {
window.requestAnimationFrame(gameLoop);
update();
render();
}

function update() {
var direction = 1;
if( xAviao > ( larg - img.Width ) )
    {
        y0 = 0;
        a = 120;
        t = 0;
        xAviao = ( larg - img.Width );
        direcao = 2;
    }
    else if ( yAviao > alt - img.Height )
    {
        yAviao = alt - aviao.Height;
        direction = 3;
    }
    else if ( xAviao < 0 )
    {
        xAviao = 0;
        t = 0;
        y0 = yAviao;
        a= -120;
        direction = 4;
    }
    else if ( yAviao < 0 )
    {
        yAviao = 0;
        direction = 1;
    }

switch(direction){
    case 1:

        xAviao +=10 ;
    console.log(c);
    break;
    case 2:
        t += 1/60;  // time increases 60 seconds per 60 frames
        yAviao = Math.floor( y0 + v0*t + a*t*t );
    break;
    case 3:
        xAviao -= 10;
    break;
    case 4:
        t += 1/60;  // time increases 60 seconds per 60 frames
        yAviao = Math.floor( y0 + v0*t + a*t*t );
    break;
    }
}

function render() {
// Retângulo do fundo
ctx.fillStyle = "#FFA060";
ctx.beginPath();
ctx.rect(0,0,larg,alt);
ctx.fill();

// Desenha o avião
if(img != undefined)
    ctx.drawImage(img, xAviao, yAviao);
}


答:
You can use this regular expression:

(?:[^\w\s]*)(\S*?)[^\w\s]*(?=\s|$)

And substitute by

$1

For your sample input, the output is:

Don't delete the actual string

  Hyphenated-words too

NB: I have used \w, but if you need the more precise definition of alphanumeric, then replace the two \w by \p{Alnum}.

Title: How to remove exterior punctuation from a string using regular expressions

Body:
Given a string like below, remove any leading and trailing punctuation via regular expressions:

String a = "!?Don't.;, .:delete !the@ $actual string%";
String b = "Hyphenated-words, too!";

I know that the regex [\P{Alnum}] will target all non-alphanumeric characters, but how do I target ONLY the leading and trailing punctuation so I get...

a = "Don't delete the actual string";
b = "Hyphenated-words too";

... instead of:

a = "Dont delete the actual string";
b = "Hyphenated words too";

I just need the regular expression; not the actual code to remove the punctuation.


问:
React/redux child update child (<select> update <select>)
I have container, binded with connect() to my store.

```<code>// GetActiveAccount.jsx
const VisibleActiveAccountsList = connect(
    mapStateToProps,
    mapDispatchToProps
)(ActiveAccountsSelector)
</code>```

ActiveAccountsSelector is the presentational component. Inside this presentational component I load two child presentational components which are only

```<code>    //activeAccountSelector render method
    return(
            <div>
                    <GatewaySelector gateways={gateways} onSelectGateway={ (e) => {
                            console.log(e.target.value);
                        }
                    }/>
                    <PairSelector gateway={gateways[0]} onSelectPair={ (e) => {
                            console.log(e.target.value);
                        }
                    }/>

            </div>
        )
</code>```

What I want is that the selected value on gatewaySelector determine the value passed to PairSelector and update it when changed.

What is the right way to do that ? Going through actions seems way overkill for a simple select change update.

I guess I have to manager that in the parent (activeAccountSelector) but how ? It seems not advised to change state without going through the whole process (actions,reducers ...etc) shall I do that changing parents props ?

答:
Yes. You have to manage that in state of the parent component. Simply, you can change set the value for gateway property of PairSelector from parent's state and change the state when gateway change in GatewaySelector.

Redux suggest to using react state for the state that doesn't matter to the app globally. Read this comment from the Redux author for more information.

```<code>class ActiveAccountSelector extends React.Component{

  contructor(props){
    super(props);
    this.state = { selectedGateway: null};
    this.onSelectGateway = this.onSelectGateway.bind(this);
  }

  onSelectGateway(e){
    this.setState({ selectedGateway: e.target.value });
  }

  render(){}
    ....
    return(
      <div>
        <form>
          <GatewaySelector gateways={gateways} onSelectGateway={ this.onSelectGateway}
          }/>
          <PairSelector gateway={this.state.selectedGateway} onSelectPair={ (e) => {
            console.log(e.target.value);
          }}/>
          </form>
      </div>
    );
  }

}
</code>```

Body:
I have container, binded with connect() to my store.

// GetActiveAccount.jsx
const VisibleActiveAccountsList = connect(
    mapStateToProps,
    mapDispatchToProps
)(ActiveAccountsSelector)

ActiveAccountsSelector is the presentational component. Inside this presentational component I load two child presentational components which are only

    //activeAccountSelector render method
    return(

                    <GatewaySelector gateways={gateways} onSelectGateway={ (e) => {
                            console.log(e.target.value);
                        }
                    }/>
                    <PairSelector gateway={gateways[0]} onSelectPair={ (e) => {
                            console.log(e.target.value);
                        }
                    }/>

        )

What I want is that the selected value on gatewaySelector determine the value passed to PairSelector and update it when changed.

What is the right way to do that ? Going through actions seems way overkill for a simple select change update.

I guess I have to manager that in the parent (activeAccountSelector) but how ? It seems not advised to change state without going through the whole process (actions,reducers ...etc) shall I do that changing parents props ?

Body:
Yes. You have to manage that in state of the parent component. Simply, you can change set the value for gateway property of PairSelector from parent's state and change the state when gateway change in GatewaySelector.

Redux suggest to using react state for the state that doesn't matter to the app globally. Read this comment from the Redux author for more information.

class ActiveAccountSelector extends React.Component{

  contructor(props){
    super(props);
    this.state = { selectedGateway: null};
    this.onSelectGateway = this.onSelectGateway.bind(this);
  }

  onSelectGateway(e){
    this.setState({ selectedGateway: e.target.value });
  }

  render(){}
    ....
    return(
      <div>
        <form>
          <GatewaySelector gateways={gateways} onSelectGateway={ this.onSelectGateway}
          }/>
          <PairSelector gateway={this.state.selectedGateway} onSelectPair={ (e) => {
            console.log(e.target.value);
          }}/>
          </form>
      </div>
    );
  }

}


问:
Blackberry application description text error for more than 255 characters
I am using the BlackBerry_JDE_PluginFull_1.1.2.201004161203-16 (BlackBerry JRE 5.0.0). Previously i had used the BlackBerry JDE as i shifted to Eclipse plugin since BB JDE is not supporting on importing the external jars to project and creation of single cod for same.

So I have imported my BB JDE 5.0.0 proj to Eclipse plugin using Blackberry Legacy project it successfully imported but it gives error in BlackBerry_App_Descriptor.xml at Application Description.

What i noticed:
If Application description text length more 255 it gives error. If app description is less than or equal to 255 then it doesn't gives an error. My app description is upto 288.
The same thing works in BB JDE.

Can any one help me on this.

Thanks,

答:
I haven't tried this but my guess would be that you view the App Descriptor, click on "Internationalized resource bundle available", and set the "Description ID" to a description you have in your localization file.  </p>

<p>Note: This only applies to the visual app descriptor.  If you're actually editing the XML then I would recommend switching to the visual view.  </p>

Body:
I haven't tried this but my guess would be that you view the App Descriptor, click on "Internationalized resource bundle available", and set the "Description ID" to a description you have in your localization file.

Note: This only applies to the visual app descriptor.  If you're actually editing the XML then I would recommend switching to the visual view.


问:
Python global vs local variables?
I'm having trouble understanding why my code works the way it does. Right now, I'm initializing a global variable i set to 0, so it makes sense that if I print it anywhere outside my function, I should get 0.

When I print i inside the function, I get 6 and 12 after calling the function twice. I think this is because the global i is 0, but some local i variable isn't. However, when I'm calling reach_load with i as a parameter, aren't I passing in the global value of i (0)?

```<code>import sys

d = {}
size_0 = sys.getsizeof(d)
i = 0

def reach_load(d, size_0, i):
    size_0 = sys.getsizeof(d)
    while size_0 == sys.getsizeof(d):
        d[i] = i
        i += 1
    print(i)

reach_load(d, size_0, i)
reach_load(d, size_0, i)
</code>```

答: I think you've confused two things here: The global i doesn't change, but d does (as it's mutable). i starts off as 0 each time you call reach_load, but since the dictionary is bigger, the while loop will run longer and therefore, a higher number will be printed.

Title: Python global vs local variables?

Body:
I'm having trouble understanding why my code works the way it does. Right now, I'm initializing a global variable i set to 0, so it makes sense that if I print it anywhere outside my function, I should get 0.

When I print i inside the function, I get 6 and 12 after calling the function twice. I think this is because the global i is 0, but some local i variable isn't. However, when I'm calling reach_load with i as a parameter, aren't I passing in the global value of i (0)?

import sys

d = {}
size_0 = sys.getsizeof(d)
i = 0

def reach_load(d, size_0, i):
    size_0 = sys.getsizeof(d)
    while size_0 == sys.getsizeof(d):
        d[i] = i
        i += 1
    print(i)

reach_load(d, size_0, i)
reach_load(d, size_0, i)


问:
UIButton TapGestureRecognizer not firing
The purpose of this bit of code is to animate a UIView to a certain location on the screen. Unfortunately, it simply is not registering the tap. Am I suppose to set the delegate to something in my setup? Any help would be appreciated!</p>

```<code>public class NoteCardView:UIView {
internal var titleLabelTapGestureRecognizer: UITapGestureRecognizer?
@IBInspectable var delegate: NoteCardViewDelegate?

public func setup(positionX:CGFloat, positionY: CGFloat, view: UIView, cardValue: Int) {
    self.titleLabelTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(NoteCardView.handleTitleLabelTap(_:)))
    self.addGestureRecognizer(titleLabelTapGestureRecognizer!)
}

func handleTitleLabelTap(_ recognizer:UITapGestureRecognizer) {
    self.delegate?.noteCardViewTitleLabelDidRecieveTap(self)
}
}

public protocol NoteCardViewDelegate {
func noteCardViewTitleLabelDidRecieveTap(_ view: NoteCardView!) -> Bool
}

extension MainViewController: NoteCardViewDelegate {
func noteCardViewTitleLabelDidRecieveTap(_ view: NoteCardView!) -> Bool {
    let card:NoteCardView = (view)
    UIView.animate(withDuration: 0.5, delay: 0.0, options: UIViewAnimationOptions.curveEaseInOut, animations: {

        card.titleLabel.leftAnchor.constraint(equalTo: card.titleLabel.leftAnchor, constant: (self.elementPlacement / 4) + 20)

        card.titleLabel.bottomAnchor.constraint(equalTo: card.titleLabel.bottomAnchor, constant: 100)

    }, completion: { (finished: Bool) in

        self.elementPlacement = (self.elementPlacement + 1)
        card.titleLabelTapGestureRecognizer!.isEnabled = !(self.elementPlacement == 5)
    })
    return true
}
}
</code>```

答:
You should enable userInteraction in your view. </p>

```<code>view.isUserInteractionEnabled = true
</code>```

Body:
The purpose of this bit of code is to animate a UIView to a certain location on the screen. Unfortunately, it simply is not registering the tap. Am I suppose to set the delegate to something in my setup? Any help would be appreciated!

public class NoteCardView:UIView {
internal var titleLabelTapGestureRecognizer: UITapGestureRecognizer?
@IBInspectable var delegate: NoteCardViewDelegate?

public func setup(positionX:CGFloat, positionY: CGFloat, view: UIView, cardValue: Int) {
    self.titleLabelTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(NoteCardView.handleTitleLabelTap(_:)))
    self.addGestureRecognizer(titleLabelTapGestureRecognizer!)
}

func handleTitleLabelTap(_ recognizer:UITapGestureRecognizer) {
    self.delegate?.noteCardViewTitleLabelDidRecieveTap(self)
}
}

public protocol NoteCardViewDelegate {
func noteCardViewTitleLabelDidRecieveTap(_ view: NoteCardView!) -> Bool
}

extension MainViewController: NoteCardViewDelegate {
func noteCardViewTitleLabelDidRecieveTap(_ view: NoteCardView!) -> Bool {
    let card:NoteCardView = (view)
    UIView.animate(withDuration: 0.5, delay: 0.0, options: UIViewAnimationOptions.curveEaseInOut, animations: {

        card.titleLabel.leftAnchor.constraint(equalTo: card.titleLabel.leftAnchor, constant: (self.elementPlacement / 4) + 20)

        card.titleLabel.bottomAnchor.constraint(equalTo: card.titleLabel.bottomAnchor, constant: 100)

    }, completion: { (finished: Bool) in

        self.elementPlacement = (self.elementPlacement + 1)
        card.titleLabelTapGestureRecognizer!.isEnabled = !(self.elementPlacement == 5)
    })
    return true
}
}

Body:
You should enable userInteraction in your view.

view.isUserInteractionEnabled = true