问:
Run spring boot with jdk9 using jigsaw modules
What's wrong with this application. I thought the mix of classpath jars and module jars are valid. For all jars not having an explicit module-info become an automatic module? When I delete my module-info.java it works. Because IDEA using the classpath for this case.

Java(TM) SE Runtime Environment (build 9+176)

IntelliJ IDEA 2017.1.4

module-info.java

```<code>module test {
    requires spring.boot.autoconfigure;
    requires spring.boot;
}
</code>```

App.java

```<code>package com.foo.test;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App {

    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}
</code>```

pom.xml

```<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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.foo.test</groupId>
    <artifactId>test</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.M2</version>
    </parent>

    <name>test</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.9</maven.compiler.source>
        <maven.compiler.target>1.9</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/libs-milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>
</project>
</code>```

Exception in thread "main" java.lang.IllegalArgumentException: Cannot
  instantiate interface
  org.springframework.context.ApplicationContextInitializer :
  org.springframework.boot.context.ConfigurationWarningsApplicationContextInitializer
    at
  spring.boot@2.0.0.M2/org.springframework.boot.SpringApplication.createSpringFactoriesInstances(SpringApplication.java:439)
    at
  spring.boot@2.0.0.M2/org.springframework.boot.SpringApplication.getSpringFactoriesInstances(SpringApplication.java:418)
    at
  spring.boot@2.0.0.M2/org.springframework.boot.SpringApplication.getSpringFactoriesInstances(SpringApplication.java:409)
    at
  spring.boot@2.0.0.M2/org.springframework.boot.SpringApplication.(SpringApplication.java:266)
    at
  spring.boot@2.0.0.M2/org.springframework.boot.SpringApplication.(SpringApplication.java:247)
    at
  spring.boot@2.0.0.M2/org.springframework.boot.SpringApplication.run(SpringApplication.java:1245)
    at
  spring.boot@2.0.0.M2/org.springframework.boot.SpringApplication.run(SpringApplication.java:1233)
    at test/com.foo.test.App.main(App.java:10) Caused by:
  java.lang.NoClassDefFoundError: java/sql/SQLException     at
  spring.beans@5.0.0.RC2/org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:145)
    at
  spring.boot@2.0.0.M2/org.springframework.boot.SpringApplication.createSpringFactoriesInstances(SpringApplication.java:435)
    ... 7 more Caused by: java.lang.ClassNotFoundException:
  java.sql.SQLException     at
  java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:582)
    at
  java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:185)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:496)
    ... 9 more

答:
This is almost certainly because you are missing the jdbc driver jar for MySql. you need to use this dependency :-</p>

```<code><dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version>6.0.5</version>
</dependency>
</code>```

Body:
What's wrong with this application. I thought the mix of classpath jars and module jars are valid. For all jars not having an explicit module-info become an automatic module? When I delete my module-info.java it works. Because IDEA using the classpath for this case.

Java(TM) SE Runtime Environment (build 9+176)

IntelliJ IDEA 2017.1.4

module-info.java

module test {
    requires spring.boot.autoconfigure;
    requires spring.boot;
}

App.java

package com.foo.test;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App {

    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.foo.test</groupId>
    <artifactId>test</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.M2</version>
    </parent>

    <name>test</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.9</maven.compiler.source>
        <maven.compiler.target>1.9</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/libs-milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>
</project>

Exception in thread "main" java.lang.IllegalArgumentException: Cannot
  instantiate interface
  org.springframework.context.ApplicationContextInitializer :
  org.springframework.boot.context.ConfigurationWarningsApplicationContextInitializer
    at
  spring.boot@2.0.0.M2/org.springframework.boot.SpringApplication.createSpringFactoriesInstances(SpringApplication.java:439)
    at
  spring.boot@2.0.0.M2/org.springframework.boot.SpringApplication.getSpringFactoriesInstances(SpringApplication.java:418)
    at
  spring.boot@2.0.0.M2/org.springframework.boot.SpringApplication.getSpringFactoriesInstances(SpringApplication.java:409)
    at
  spring.boot@2.0.0.M2/org.springframework.boot.SpringApplication.(SpringApplication.java:266)
    at
  spring.boot@2.0.0.M2/org.springframework.boot.SpringApplication.(SpringApplication.java:247)
    at
  spring.boot@2.0.0.M2/org.springframework.boot.SpringApplication.run(SpringApplication.java:1245)
    at
  spring.boot@2.0.0.M2/org.springframework.boot.SpringApplication.run(SpringApplication.java:1233)
    at test/com.foo.test.App.main(App.java:10) Caused by:
  java.lang.NoClassDefFoundError: java/sql/SQLException     at
  spring.beans@5.0.0.RC2/org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:145)
    at
  spring.boot@2.0.0.M2/org.springframework.boot.SpringApplication.createSpringFactoriesInstances(SpringApplication.java:435)
    ... 7 more Caused by: java.lang.ClassNotFoundException:
  java.sql.SQLException     at
  java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:582)
    at
  java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:185)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:496)
    ... 9 more

Body:
This is almost certainly because you are missing the jdbc driver jar for MySql. you need to use this dependency :-

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


来源: stackexchange

问:
how to get the co-ordinates of an underlying image of a picture box
I have a picture box with an image associated with it.

The size mode of the PictureBox has been set to CenterImage

My question is how can I get the image co-ordinates for that underlying image.

Regards

答:
I think your best bet is to calculate it yourself using a formula like this:

```<code>int xOffset = (pictureBox1.Width / 2) - (pictureBox1.Image.Width / 2);
int yOffset = (pictureBox1.Height / 2) - (pictureBox1.Image.Height / 2);
</code>```

xOffset and yOffset should equal the (x,y) of the image from the top left corner of the picture box. Keep in mind, the formula above uses integer math and it could truncate values.

ContentLicense: CC BY-SA 2.5

Body:
I think your best bet is to calculate it yourself using a formula like this:

int xOffset = (pictureBox1.Width / 2) - (pictureBox1.Image.Width / 2);
int yOffset = (pictureBox1.Height / 2) - (pictureBox1.Image.Height / 2);

xOffset and yOffset should equal the (x,y) of the image from the top left corner of the picture box. Keep in mind, the formula above uses integer math and it could truncate values.


问:
Add and delete Celery periodic tasks at runtime
I've been battling with this task all day.

I have a Django app. I use Celery for asynchronous tasks. Occasionally, I want to create a periodic task. The number of times that tasks will run unknown, but it will need to be deleted later. So the task could be like this:

```<code>@shared_task
def foobar_task(id):
    if this_should_run:
        do_task()
    else:
        PeriodicTask.objects.get(name='{} task'.format(id)).delete()
</code>```

My app is running. I have celery beat running in a Docker container, run using using celery --app=myproject beat --loglevel=info --scheduler=django. I have another container running the standard celery worker.

So now I want to dynamically create my periodic task. I have a view/API endpoint that triggers something like this:

```<code>schedule, _ = IntervalSchedule.objects.get_or_create(every=15, period=IntervalSchedule.SECONDS)
PeriodicTask.objects.create(interval=schedule,
                            name='{} task'.format(id),
                            task='myapp.tasks.foobar_task')
</code>```

In the Django admin, I can see the periodic task has been created. However, watching the logs for both the celery container and celery beat container, nothing happens.

Why is celery beat not picking up that there's a new periodic task? I don't want to have to restart celery beat every time a new task is created or deleted.

Note: I am using Django 1.11.2, PostgreSQL, Celery 4.0.2, Django Celery Beat 1.0.1.

答:
You can create a custom scheduler like the one below, adapted from this answer.

```<code>from django_celery_beat.schedulers import DatabaseScheduler

class AutoUpdateScheduler(DatabaseScheduler):

    def tick(self, *args, **kwargs):
        if self.schedule_changed():
            self.sync()
            self._heap = None
            new_schedule = self.all_as_schedule()

            if new_schedule:
                to_add = [x for x in new_schedule.keys() if x not in self.schedule.keys()]
                to_remove = [x for x in self.schedule.keys() if x not in new_schedule.keys()]
                for key in to_add:
                    self.schedule[key] = new_schedule[key]
                for key in to_remove:
                    del self.schedule[key]

        super(AutoUpdateScheduler, self).tick(*args, **kwargs)

    @property
    def schedule(self):
        if not self._initial_read and not self._schedule:
            self._initial_read = True
            self._schedule = self.all_as_schedule()
        return self._schedule
</code>```

When you run celery beat, point it to this class:

```<code>celery --app=myproject beat --loglevel=info --scheduler=myproject.scheduler.AutoUpdateScheduler
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I've been battling with this task all day.

I have a Django app. I use Celery for asynchronous tasks. Occasionally, I want to create a periodic task. The number of times that tasks will run unknown, but it will need to be deleted later. So the task could be like this:

@shared_task
def foobar_task(id):
    if this_should_run:
        do_task()
    else:
        PeriodicTask.objects.get(name='{} task'.format(id)).delete()

My app is running. I have celery beat running in a Docker container, run using using celery --app=myproject beat --loglevel=info --scheduler=django. I have another container running the standard celery worker.

So now I want to dynamically create my periodic task. I have a view/API endpoint that triggers something like this:

schedule, _ = IntervalSchedule.objects.get_or_create(every=15, period=IntervalSchedule.SECONDS)
PeriodicTask.objects.create(interval=schedule,
                            name='{} task'.format(id),
                            task='myapp.tasks.foobar_task')

In the Django admin, I can see the periodic task has been created. However, watching the logs for both the celery container and celery beat container, nothing happens.

Why is celery beat not picking up that there's a new periodic task? I don't want to have to restart celery beat every time a new task is created or deleted.

Note: I am using Django 1.11.2, PostgreSQL, Celery 4.0.2, Django Celery Beat 1.0.1.

Body:
You can create a custom scheduler like the one below, adapted from this answer.

from django_celery_beat.schedulers import DatabaseScheduler

class AutoUpdateScheduler(DatabaseScheduler):

    def tick(self, *args, **kwargs):
        if self.schedule_changed():
            self.sync()
            self._heap = None
            new_schedule = self.all_as_schedule()

            if new_schedule:
                to_add = [x for x in new_schedule.keys() if x not in self.schedule.keys()]
                to_remove = [x for x in self.schedule.keys() if x not in new_schedule.keys()]
                for key in to_add:
                    self.schedule[key] = new_schedule[key]
                for key in to_remove:
                    del self.schedule[key]

        super(AutoUpdateScheduler, self).tick(*args, **kwargs)

    @property
    def schedule(self):
        if not self._initial_read and not self._schedule:
            self._initial_read = True
            self._schedule = self.all_as_schedule()
        return self._schedule

When you run celery beat, point it to this class:

celery --app=myproject beat --loglevel=info --scheduler=myproject.scheduler.AutoUpdateScheduler


问:
Symfony and Netbeans PHP
I have used CRUD to generate actions for an entity. However, I would like to modify the edit action; for instance, a user select 'inactive' represented by 1 for State then they will be shown an error message otherwise they can proceed to updating that row. Within the entity these are the variables state, paypid, startDate, endDate.

This is what the edit action currently looks like.

```<code>public function editAction($Paypid)
{
    $em = $this->getDoctrine()->getManager();

    $entity = $em->getRepository('comtwclagripayrollBundle:Payrollperiod')->find($Paypid);

    if (!$entity) {
        throw $this->createNotFoundException('Unable to find Payrollperiod entity.');
    }

    $editForm = $this->createEditForm($entity);
    $deleteForm = $this->createDeleteForm($Paypid);

    return array(
        'entity'      => $entity,
        'edit_form'   => $editForm->createView(),
        'delete_form' => $deleteForm->createView(),
    );
}
</code>```

This is the payroll period entity

namespace com\twcl\agripayrollBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * Payrollperiod
 * @ORM\Entity(repositoryClass="com\twcl\agripayrollBundle\Entity\PayPeriodRepository")
 *
 *
 */
class Payrollperiod
{
    /**
     * @var \DateTime
     */
    private $startdate;

```<code>/**
 * @var \DateTime
 */
private $enddate;

/**
 * @var integer
 */
private $state;

/**
 * @var integer
 */
private $paypid;

/**
 * Set startdate
 *
 * @param \DateTime $startdate
 * @return Payrollperiod
 */
public function setStartdate($startdate)
{
    $this->startdate = $startdate;

    return $this;
}

/**
 * Get startdate
 *
 * @return \DateTime
 */
public function getStartdate()
{
    return $this->startdate;
}

/**
 * Set enddate
 *
 * @param \DateTime $enddate
 * @return Payrollperiod
 */
public function setEnddate($enddate)
{
    $this->enddate = $enddate;

    return $this;
}

/**
 * Get enddate
 *
 * @return \DateTime
 */
public function getEnddate()
{
    return $this->enddate;
}

/**
 * Set state
 *
 * @param integer $state
 * @return Payrollperiod
 */
public function setState($state)
{
    $this->state = $state;

    return $this;
}

/**
 * Get state
 *
 * @return integer
 */
public function getState()
{
    return $this->state;
}

/**
 * Get paypid
 *
 * @return integer
 */
public function getPaypid()
{
    return $this->paypid;
}

public function setPayid($payid){
    $this->paypid = $payid;
</code>```

}
    /**
     * Render a payrollPeriodID as a string.
     *
     * @return string
     */

```<code>public function __toString()
{
 return (string) $this->getstartDate()->format('d-M-y').'/'.$this->getendDate()->format('d-M-y');

}

public function __construct()
{
   $this->PayrollperiodType = new \Doctrine\Common\Collection\ArrayCollection();
}
</code>```

}

Can someone assist me with this issue?

答:
There could be multiple different ways of handling this. Normally when you generate methods using symfony or doctrine cmds such as generate:doctrine:crud, it is boilerplate code to get you going a bit faster and you will update it to meet your needs.

There are a few approaches here, but it depends on the approach and business logic you want. If you are only allowing entities that are currently in an 'Active' state to be edited, then the following will work.

You can create a custom repository class and have a method that queries for the entity based on the $Paypid provided and $state = 1.

```<code>public function findByPaypidAndActiveState($Paypid)
{
    return $this->getEntityManager()
        ->createQuery(
            'SELECT p FROM comtwclagripayrollBundle:Payrollperiod
                WHERE paypid = :paypid AND state = :state'
        )
        ->setParameter('paypid', $Paypid)
        ->setParameter('state', 0)
        ->getResult();
}
</code>```

Then in the editAction, you will query using this method instead of the using find()

Another way would be to modify the query in the editAction to find by criteria other than the id

```<code>{
    //....
    $entity = $em->getRepository('comtwclagripayrollBundle:Payrollperiod')
        ->findBy(['paypid' => $Paypid, 'state' => 0]);
}
</code>```

From here, you can adjust your error messaging to what you want. The throw $this->createNotFoundException('Unable to find Payrollperiod entity.'); is just boilerplate code by generating crud. This just basically returns a 404 response, which doesn't sound like what you need.

If you are using sessions, you could add a flash message to the session and display it to the user as the error message.

So overall something like this could be a possible solution

```<code>public function editAction($Paypid)
{
    $em = $this->getDoctrine()->getManager();

    $entity = $em->getRepository('comtwclagripayrollBundle:Payrollperiod')
        ->findBy(['paypid' => $Paypid, 'state' => 0]);

    if (!$entity) {
        $this->addFlash(
        'notice',
        'You cannot edit an inactive Payroll Period'
        );

        return $this->redirectToRoute('some_route_of_your_choosing');
    }

    $editForm = $this->createEditForm($entity);
    $deleteForm = $this->createDeleteForm($Paypid);

    return array(
        'entity'      => $entity,
        'edit_form'   => $editForm->createView(),
        'delete_form' => $deleteForm->createView(),
    );
}
</code>```

Title: Symfony and Netbeans PHP

Body:
I have used CRUD to generate actions for an entity. However, I would like to modify the edit action; for instance, a user select 'inactive' represented by 1 for State then they will be shown an error message otherwise they can proceed to updating that row. Within the entity these are the variables state, paypid, startDate, endDate.

This is what the edit action currently looks like.

public function editAction($Paypid)
{
    $em = $this->getDoctrine()->getManager();

    $entity = $em->getRepository('comtwclagripayrollBundle:Payrollperiod')->find($Paypid);

    if (!$entity) {
        throw $this->createNotFoundException('Unable to find Payrollperiod entity.');
    }

    $editForm = $this->createEditForm($entity);
    $deleteForm = $this->createDeleteForm($Paypid);

    return array(
        'entity'      => $entity,
        'edit_form'   => $editForm->createView(),
        'delete_form' => $deleteForm->createView(),
    );
}

This is the payroll period entity

namespace com\twcl\agripayrollBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * Payrollperiod
 * @ORM\Entity(repositoryClass="com\twcl\agripayrollBundle\Entity\PayPeriodRepository")
 *
 *
 */
class Payrollperiod
{
    /**
     * @var \DateTime
     */
    private $startdate;

/**
 * @var \DateTime
 */
private $enddate;

/**
 * @var integer
 */
private $state;

/**
 * @var integer
 */
private $paypid;

/**
 * Set startdate
 *
 * @param \DateTime $startdate
 * @return Payrollperiod
 */
public function setStartdate($startdate)
{
    $this->startdate = $startdate;

    return $this;
}

/**
 * Get startdate
 *
 * @return \DateTime
 */
public function getStartdate()
{
    return $this->startdate;
}

/**
 * Set enddate
 *
 * @param \DateTime $enddate
 * @return Payrollperiod
 */
public function setEnddate($enddate)
{
    $this->enddate = $enddate;

    return $this;
}

/**
 * Get enddate
 *
 * @return \DateTime
 */
public function getEnddate()
{
    return $this->enddate;
}

/**
 * Set state
 *
 * @param integer $state
 * @return Payrollperiod
 */
public function setState($state)
{
    $this->state = $state;

    return $this;
}

/**
 * Get state
 *
 * @return integer
 */
public function getState()
{
    return $this->state;
}

/**
 * Get paypid
 *
 * @return integer
 */
public function getPaypid()
{
    return $this->paypid;
}

public function setPayid($payid){
    $this->paypid = $payid;

}
    /**
     * Render a payrollPeriodID as a string.
     *
     * @return string
     */

public function __toString()
{
 return (string) $this->getstartDate()->format('d-M-y').'/'.$this->getendDate()->format('d-M-y');

}

public function __construct()
{
   $this->PayrollperiodType = new \Doctrine\Common\Collection\ArrayCollection();
}

}

Can someone assist me with this issue?

Body:
There could be multiple different ways of handling this. Normally when you generate methods using symfony or doctrine cmds such as generate:doctrine:crud, it is boilerplate code to get you going a bit faster and you will update it to meet your needs.

There are a few approaches here, but it depends on the approach and business logic you want. If you are only allowing entities that are currently in an 'Active' state to be edited, then the following will work.

You can create a custom repository class and have a method that queries for the entity based on the $Paypid provided and $state = 1.

public function findByPaypidAndActiveState($Paypid)
{
    return $this->getEntityManager()
        ->createQuery(
            'SELECT p FROM comtwclagripayrollBundle:Payrollperiod
                WHERE paypid = :paypid AND state = :state'
        )
        ->setParameter('paypid', $Paypid)
        ->setParameter('state', 0)
        ->getResult();
}

Then in the editAction, you will query using this method instead of the using find()

Another way would be to modify the query in the editAction to find by criteria other than the id

{
    //....
    $entity = $em->getRepository('comtwclagripayrollBundle:Payrollperiod')
        ->findBy(['paypid' => $Paypid, 'state' => 0]);
}

From here, you can adjust your error messaging to what you want. The throw $this->createNotFoundException('Unable to find Payrollperiod entity.'); is just boilerplate code by generating crud. This just basically returns a 404 response, which doesn't sound like what you need.

If you are using sessions, you could add a flash message to the session and display it to the user as the error message.

So overall something like this could be a possible solution

public function editAction($Paypid)
{
    $em = $this->getDoctrine()->getManager();

    $entity = $em->getRepository('comtwclagripayrollBundle:Payrollperiod')
        ->findBy(['paypid' => $Paypid, 'state' => 0]);

    if (!$entity) {
        $this->addFlash(
        'notice',
        'You cannot edit an inactive Payroll Period'
        );

        return $this->redirectToRoute('some_route_of_your_choosing');
    }

    $editForm = $this->createEditForm($entity);
    $deleteForm = $this->createDeleteForm($Paypid);

    return array(
        'entity'      => $entity,
        'edit_form'   => $editForm->createView(),
        'delete_form' => $deleteForm->createView(),
    );
}


问:
In Netty 4.1, when are the handlers in the pipeline removed after closing the channel on the server?
So, we are in the process of migrating from Netty 3.9 to Netty 4.1 on our production servers. There seems to be a difference in the way the ChannelHandlers are added and removed from the pipeline in both the versions. Specifically, after closing a channel on the server, I am logging the ChannelHandlers present in the pipeline at some point. While in Netty 4.1, the pipeline sometimes shows few or none of the handlers, in Netty 3.9, all the handlers are always present. All this after closing the channel reference. Is this expected? When does Netty (both in 3.9 and 4.1) remove all the handlers in the pipeline after a channel is closed?

答: In netty 4.x we remove all the handlers after each other from the pipeline when a channel is closed. This way we also execute handlerRemoved(...) which may is needed to release memory etc.


问:
Passing a 2d-array from Julia to Fortran
I'm having trouble passing a 2d-array from Julia to Fortran.

Passing that 2d-array to a C function works fine though.

Here is the C code:

```<code>#include <stdio.h>
double meanFilter(int **arr, int row, int col)
{
    int i, j, sum=0;
    float mean;
    for (i=0; i<row; i=i+1)
        for (j=0; j<col; j=j+1) {
             sum = sum + arr[i][j];
             printf("%d %d %d %d\n", i, j, arr[i][j], sum);
         }
    mean = (double)sum / (row * col);
    printf("mean=%f\n", mean);
    return mean;
}
</code>```

that i compile with

```<code>icc -o myclib.so myclib.c -fPIC -shared
</code>```

and the Julia code where I call the C function:

```<code>x = zeros(Cint,5,5)
for i=1:5
    for j=1:5
        x[i,j] = i * j
        print(x[i,j], " ")
    end
    println()
end

refAr = [Ref(x,i) for i=1:size(x,1):length(x)]

aMean = ccall((:meanFilter, :myclib), Float64, (Ptr{Ptr{Cint}}, Cint, Cint), refAr, 5, 5)
println("mean_c=",aMean)
</code>```

and I get this output:

```<code>1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
0 0 1 1
0 1 2 3
0 2 3 6
0 3 4 10
0 4 5 15
1 0 2 17
1 1 4 21
1 2 6 27
1 3 8 35
1 4 10 45
2 0 3 48
2 1 6 54
2 2 9 63
2 3 12 75
2 4 15 90
3 0 4 94
3 1 8 102
3 2 12 114
3 3 16 130
3 4 20 150
4 0 5 155
4 1 10 165
4 2 15 180
4 3 20 200
4 4 25 225
mean=9.000000
mean_c=9.0
</code>```

Here is the Fortran version:

```<code>real(kind=8) function meanFilter(arr, row, col)
    integer, intent(in) :: row, col
    integer, dimension(row,col), intent(in) :: arr
    integer :: i, j, sum

    sum = 0

    do j=1, col
        do i = 1, row
            sum = sum + arr(i,j)
            write(*,*) i, j, arr(i,j), sum
        enddo
    enddo
    meanFilter = real(sum,8)/(row*col)
    write(*,*) "mean=", meanFilter
end function meanFilter
</code>```

that I compile like this:

```<code>ifort -o myflib.so myflib.f90 -assume byterecl -shared -fPIC
</code>```

and the Julia code

```<code>x = zeros(Cint,5,5)
for i=1:5
    for j=1:5
        x[i,j] = i * j
        print(x[i,j], " ")
    end
    println()
end

refAr = [Ref(x,i) for i=1:size(x,1):length(x)]

aMean = ccall((:simplemodule_mp_meanfilter_, :myflib), Float64, (Ptr{Ptr{Cint}}, Cint, Cint), refAr, 5, 5)
println("mean_f=",aMean)
</code>```

and I get this output:

```<code>signal (11): Segmentation fault
while loading ./fortran_call_in_julia.jl, in expression starting on line 56
simplemodule_mp_meanfilter_ at ./myflib.so (unknown line)
anonymous at ./<missing> (unknown line)
unknown function (ip: 0x2ab08d75fcfa)
unknown function (ip: 0x2ab08d73b606)
jl_load at /usr/bin/../lib64/libjulia.so.0.6 (unknown line)
unknown function (ip: 0x2ab0991bd4e5)
unknown function (ip: 0x2ab0991bd6bb)
jl_apply_generic at /usr/bin/../lib64/libjulia.so.0.6 (unknown line)
unknown function (ip: 0x2ab0990625bf)
unknown function (ip: 0x2ab09906262b)
jl_apply_generic at /usr/bin/../lib64/libjulia.so.0.6 (unknown line)
unknown function (ip: 0x2ab0991c6315)
unknown function (ip: 0x2ab0991c87f4)
unknown function (ip: 0x2ab0991c9288)
jl_apply_generic at /usr/bin/../lib64/libjulia.so.0.6 (unknown line)
unknown function (ip: 0x401d90)
unknown function (ip: 0x401592)
__libc_start_main at /usr/bin/../lib64/libc.so.6 (unknown line)
unknown function (ip: 0x401649)
Allocations: 1664692 (Pool: 1663483; Big: 1209); GC: 1
Segmentation fault (core dumped)
</code>```

So, what is it I'm doing wrong for the fortran version?

答:
Fortran uses call by reference even for simple integral arguments. Additionaly you are creating redundant layer of indirection here (in the both C and Fortran versions). So corrected julia wrapper for your fortran code should be:

```<code>x = zeros(Cint,5,5)
for i=1:5
    for j=1:5
        x[i,j] = i * j
        print(x[i,j], " ")
    end
    println()
end

aMean = ccall((:meanfilter_, "./tst.so"), Float64, (Ref{Cint}, Ref{Cint}, Ref{Cint}), x, 5, 5)
println("mean_f=",aMean)
</code>```

I tested this with gfortran so your name mangling may differ.

Body:
I'm having trouble passing a 2d-array from Julia to Fortran.

Passing that 2d-array to a C function works fine though.

Here is the C code:

#include <stdio.h>
double meanFilter(int **arr, int row, int col)
{
    int i, j, sum=0;
    float mean;
    for (i=0; i<row; i=i+1)
        for (j=0; j<col; j=j+1) {
             sum = sum + arr[i][j];
             printf("%d %d %d %d\n", i, j, arr[i][j], sum);
         }
    mean = (double)sum / (row * col);
    printf("mean=%f\n", mean);
    return mean;
}

that i compile with

icc -o myclib.so myclib.c -fPIC -shared

and the Julia code where I call the C function:

x = zeros(Cint,5,5)
for i=1:5
    for j=1:5
        x[i,j] = i * j
        print(x[i,j], " ")
    end
    println()
end

refAr = [Ref(x,i) for i=1:size(x,1):length(x)]

aMean = ccall((:meanFilter, :myclib), Float64, (Ptr{Ptr{Cint}}, Cint, Cint), refAr, 5, 5)
println("mean_c=",aMean)

and I get this output:

1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
0 0 1 1
0 1 2 3
0 2 3 6
0 3 4 10
0 4 5 15
1 0 2 17
1 1 4 21
1 2 6 27
1 3 8 35
1 4 10 45
2 0 3 48
2 1 6 54
2 2 9 63
2 3 12 75
2 4 15 90
3 0 4 94
3 1 8 102
3 2 12 114
3 3 16 130
3 4 20 150
4 0 5 155
4 1 10 165
4 2 15 180
4 3 20 200
4 4 25 225
mean=9.000000
mean_c=9.0

Here is the Fortran version:

real(kind=8) function meanFilter(arr, row, col)
    integer, intent(in) :: row, col
    integer, dimension(row,col), intent(in) :: arr
    integer :: i, j, sum

    sum = 0

    do j=1, col
        do i = 1, row
            sum = sum + arr(i,j)
            write(*,*) i, j, arr(i,j), sum
        enddo
    enddo
    meanFilter = real(sum,8)/(row*col)
    write(*,*) "mean=", meanFilter
end function meanFilter

that I compile like this:

ifort -o myflib.so myflib.f90 -assume byterecl -shared -fPIC

and the Julia code

x = zeros(Cint,5,5)
for i=1:5
    for j=1:5
        x[i,j] = i * j
        print(x[i,j], " ")
    end
    println()
end

refAr = [Ref(x,i) for i=1:size(x,1):length(x)]

aMean = ccall((:simplemodule_mp_meanfilter_, :myflib), Float64, (Ptr{Ptr{Cint}}, Cint, Cint), refAr, 5, 5)
println("mean_f=",aMean)

and I get this output:

signal (11): Segmentation fault
while loading ./fortran_call_in_julia.jl, in expression starting on line 56
simplemodule_mp_meanfilter_ at ./myflib.so (unknown line)
anonymous at ./<missing> (unknown line)
unknown function (ip: 0x2ab08d75fcfa)
unknown function (ip: 0x2ab08d73b606)
jl_load at /usr/bin/../lib64/libjulia.so.0.6 (unknown line)
unknown function (ip: 0x2ab0991bd4e5)
unknown function (ip: 0x2ab0991bd6bb)
jl_apply_generic at /usr/bin/../lib64/libjulia.so.0.6 (unknown line)
unknown function (ip: 0x2ab0990625bf)
unknown function (ip: 0x2ab09906262b)
jl_apply_generic at /usr/bin/../lib64/libjulia.so.0.6 (unknown line)
unknown function (ip: 0x2ab0991c6315)
unknown function (ip: 0x2ab0991c87f4)
unknown function (ip: 0x2ab0991c9288)
jl_apply_generic at /usr/bin/../lib64/libjulia.so.0.6 (unknown line)
unknown function (ip: 0x401d90)
unknown function (ip: 0x401592)
__libc_start_main at /usr/bin/../lib64/libc.so.6 (unknown line)
unknown function (ip: 0x401649)
Allocations: 1664692 (Pool: 1663483; Big: 1209); GC: 1
Segmentation fault (core dumped)

So, what is it I'm doing wrong for the fortran version?

Body:
Fortran uses call by reference even for simple integral arguments. Additionaly you are creating redundant layer of indirection here (in the both C and Fortran versions). So corrected julia wrapper for your fortran code should be:

x = zeros(Cint,5,5)
for i=1:5
    for j=1:5
        x[i,j] = i * j
        print(x[i,j], " ")
    end
    println()
end

aMean = ccall((:meanfilter_, "./tst.so"), Float64, (Ref{Cint}, Ref{Cint}, Ref{Cint}), x, 5, 5)
println("mean_f=",aMean)

I tested this with gfortran so your name mangling may differ.


问:
XSLT - Pushing an element to the bottom of the page
I would like to know what are the methods of pushing a block element at the bottom of the page. I am aware of the <fo:region-after> object, but I don't know how to use this for a single page, because the element I want to push to the bottom of the page will happen only on one page and only if a condition is met.

The block I want to push is this:

```<code><fo:block font-size="0" margin-top="10mm" margin-bottom="10mm" margin-left="-10mm">
    <fo:external-graphic width="190mm" content-width="scale-to-fit">
        <xsl:attribute name="src">
            url('./test.jpg')
        </xsl:attribute>
    </fo:external-graphic>
</fo:block>
</code>```

The page configuration looks like this:

```<code><xsl:template match="/">
    <fo:root xsl:use-attribute-sets="body" xmlns:fo="http://www.w3.org/1999/XSL/Format">
        <fo:layout-master-set>
            <fo:simple-page-master master-name="first"
                page-height="297mm"
                page-width="210mm"
                margin-top="0mm"
                margin-bottom="0mm"
                margin-left="0mm"
                margin-right="0mm">
                <fo:region-body margin-bottom="0" margin-top="0mm" />
                <fo:region-before region-name="header-first" extent="0mm" />
                <fo:region-after region-name="footer-first" extent="20mm" />
            </fo:simple-page-master>
            <fo:simple-page-master master-name="rest"
                page-height="297mm"
                page-width="210mm"
                margin-top="20mm"
                margin-bottom="20mm"
                margin-left="20mm"
                margin-right="20mm">
                <fo:region-body margin-bottom="0" margin-top="0" />
                <fo:region-before region-name="header-rest" extent="0" />
                <fo:region-after region-name="footer-rest" extent="0mm" />
            </fo:simple-page-master>
            <fo:page-sequence-master master-name="document">
                <fo:repeatable-page-master-alternatives>
                    <fo:conditional-page-master-reference
                        page-position="first"
                        master-reference="first" />
                    <fo:conditional-page-master-reference
                        page-position="rest"
                        master-reference="rest" />
                </fo:repeatable-page-master-alternatives>
            </fo:page-sequence-master>
        </fo:layout-master-set>
        <fo:page-sequence id="sequenceID" master-reference="document">
            <fo:static-content flow-name="header-first">
                <fo:block></fo:block>
            </fo:static-content>
            <fo:static-content flow-name="header-rest">
                <xsl:call-template name="header">
                    <xsl:with-param name="attribute-set"></xsl:with-param>
                </xsl:call-template>
            </fo:static-content>
            <fo:static-content flow-name="footer-first">
                <xsl:call-template name="footer-first" />
            </fo:static-content>
            <fo:static-content flow-name="footer-rest">
                <xsl:call-template name="footer-rest" />
            </fo:static-content>
            <fo:flow flow-name="xsl-region-body">
                <xsl:apply-templates select="//PRINTED_SECTIONS" />
            </fo:flow>
        </fo:page-sequence>
    </fo:root>
</xsl:template>
</code>```

答:
If you are using AH Formatter, you can float the graphic to the bottom of the fo:region-body by using fo:float with axf:float-y="bottom".  See https://www.antennahouse.com/product/ahf64/ahf-float.html and "Arranging floats in any positions in a page (axf:float-reference=”page”)" from https://www.antennahouse.com/antenna1/comprehensive-xsl-fo-tutorials-and-samples-collection/

You can put the graphic in an fo:footnote.  You might need to also generate an empty fo:static-content with flow-name="xsl-footnote-separator" to override the formatter's default, if the default is to output a horizontal line or similar as the footnote separator.  See https://www.w3.org/TR/xsl11/#fo_page-sequence and other references to 'xsl-footnote-separator'.

Body:
I would like to know what are the methods of pushing a block element at the bottom of the page. I am aware of the <fo:region-after> object, but I don't know how to use this for a single page, because the element I want to push to the bottom of the page will happen only on one page and only if a condition is met.

The block I want to push is this:

<fo:block font-size="0" margin-top="10mm" margin-bottom="10mm" margin-left="-10mm">
    <fo:external-graphic width="190mm" content-width="scale-to-fit">
        <xsl:attribute name="src">
            url('./test.jpg')
        </xsl:attribute>
    </fo:external-graphic>
</fo:block>

The page configuration looks like this:

<xsl:template match="/">
    <fo:root xsl:use-attribute-sets="body" xmlns:fo="http://www.w3.org/1999/XSL/Format">
        <fo:layout-master-set>
            <fo:simple-page-master master-name="first"
                page-height="297mm"
                page-width="210mm"
                margin-top="0mm"
                margin-bottom="0mm"
                margin-left="0mm"
                margin-right="0mm">
                <fo:region-body margin-bottom="0" margin-top="0mm" />
                <fo:region-before region-name="header-first" extent="0mm" />
                <fo:region-after region-name="footer-first" extent="20mm" />
            </fo:simple-page-master>
            <fo:simple-page-master master-name="rest"
                page-height="297mm"
                page-width="210mm"
                margin-top="20mm"
                margin-bottom="20mm"
                margin-left="20mm"
                margin-right="20mm">
                <fo:region-body margin-bottom="0" margin-top="0" />
                <fo:region-before region-name="header-rest" extent="0" />
                <fo:region-after region-name="footer-rest" extent="0mm" />
            </fo:simple-page-master>
            <fo:page-sequence-master master-name="document">
                <fo:repeatable-page-master-alternatives>
                    <fo:conditional-page-master-reference
                        page-position="first"
                        master-reference="first" />
                    <fo:conditional-page-master-reference
                        page-position="rest"
                        master-reference="rest" />
                </fo:repeatable-page-master-alternatives>
            </fo:page-sequence-master>
        </fo:layout-master-set>
        <fo:page-sequence id="sequenceID" master-reference="document">
            <fo:static-content flow-name="header-first">
                <fo:block></fo:block>
            </fo:static-content>
            <fo:static-content flow-name="header-rest">
                <xsl:call-template name="header">
                    <xsl:with-param name="attribute-set"></xsl:with-param>
                </xsl:call-template>
            </fo:static-content>
            <fo:static-content flow-name="footer-first">
                <xsl:call-template name="footer-first" />
            </fo:static-content>
            <fo:static-content flow-name="footer-rest">
                <xsl:call-template name="footer-rest" />
            </fo:static-content>
            <fo:flow flow-name="xsl-region-body">
                <xsl:apply-templates select="//PRINTED_SECTIONS" />
            </fo:flow>
        </fo:page-sequence>
    </fo:root>
</xsl:template>


问:
Open bootstrap modal with vue.js 2.0
Does anyone know how to open a bootstrap modal with vue 2.0? Before vue.js I would simply open the modal by using jQuery: $('#myModal').modal('show');

However, is there a proper way I should do this in Vue?

Thank you.

答:
I did an amalgam of the Vue.js Modal example and the Bootstrap 3.* live demo.

Basically, I used the Vue.js modal example but replaced (sorta) the Vue.js "html" part with the bootstrap modal html markup, save one thing (I think). I had to strip the outer div from the bootstrap 3, then it just worked, voila!

So the relevant code is regarding bootstrap. Just strip the outer div from the bootstrap markup and it should work. So...

ugh, a site for developers and i can't easily paste in code? This has been a serious continuing problem for me. Am i the only one? Based on history, I'm prolly an idiot and there's an easy way to paste in code, please advise. Every time i try, it's a horrible hack of formatting, at best.
i'll provide a sample jsfiddle of how i did it if requested.

Title: Open bootstrap modal with vue.js 2.0

ContentLicense: CC BY-SA 4.0


问:
Sabre SOAP API using cURL
Is there any example for creating session using SOAP API (cURL)? I need an example to create session using cURL.

```<code>$input_xml = '<?xml version="1.0" encoding="UTF-8"?><SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:eb="http://www.ebxml.org/namespaces/messageHeader" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:xsd="http://www.w3.org/1999/XMLSchema">
<SOAP-ENV:Header>
    <eb:MessageHeader SOAP-ENV:mustUnderstand="1" eb:version="1.0">
        <eb:ConversationId/>
        <eb:From>
            <eb:PartyId type="urn:x12.org:IO5:01">999999</eb:PartyId>
        </eb:From>
        <eb:To>
            <eb:PartyId type="urn:x12.org:IO5:01">123123</eb:PartyId>
        </eb:To>
        <eb:CPAId>IPCC</eb:CPAId>
        <eb:Service eb:type="OTA">SessionCreateRQ</eb:Service>
        <eb:Action>SessionCreateRQ</eb:Action>
        <eb:MessageData>
            <eb:MessageId>1000</eb:MessageId>
            <eb:Timestamp>2001-02-15T11:15:12Z</eb:Timestamp>
            <eb:TimeToLive>2001-02-15T11:15:12Z</eb:TimeToLive>
        </eb:MessageData>
    </eb:MessageHeader>
    <wsse:Security xmlns:wsse="http://schemas.xmlsoap.org/ws/2002/12/secext" xmlns:wsu="http://schemas.xmlsoap.org/ws/2002/12/utility">
        <wsse:UsernameToken>
            <wsse:Username>USERNAME</wsse:Username>
            <wsse:Password>PASSWORD</wsse:Password>
            <Organization>IPCC</Organization>
            <Domain>DEFAULT</Domain>
        </wsse:UsernameToken>
    </wsse:Security>
</SOAP-ENV:Header>
<SOAP-ENV:Body><eb:Manifest SOAP-ENV:mustUnderstand="1" eb:version="1.0">
    <eb:Reference xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="cid:rootelement" xlink:type="simple"/>
    </eb:Manifest>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>';

$action = 'SessionCreateRQ';
$url = 'https://webservices.sabre.com';
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $soapXML);

$data = curl_exec($ch);
if(curl_error($ch)) {
    echo "Curl error: " . curl_error($ch);
} else {
    echo $data;
}
</code>```

I got this error:

soap-env:Client.InvalidEbXmlMessageUnable to create envelope from given source: Error on line 2 of document : The processing instruction target matching "[xX][mM][lL]" is not allowed. Nested exception: The processing instruction target matching "[xX][mM][lL]" is not allowed.javax.xml.soap.SOAPException: Unable to create envelope from given source: Error on line 2 of document : The processing instruction target matching "[xX][mM][lL]" is not allowed. Nested exception: The processing instruction target matching "[xX][mM][lL]" is not allowed.

答:
I don't know about cURL but the XML is not entirely correct.

You have:

```<code><SOAP-ENV:Body>
    <eb:Manifest SOAP-ENV:mustUnderstand="1" eb:version="1.0">
        <eb:Reference xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="cid:rootelement" xlink:type="simple"/>
    </eb:Manifest>
</SOAP-ENV:Body>
</code>```

But it should be:

```<code><SOAP-ENV:Body>
    <SessionCreateRQ returnContextID="true">
        <POS>
            <Source PseudoCityCode="IPCC"/>
        </POS>
    </SessionCreateRQ>
</SOAP-ENV:Body>
</code>```

The Manifest element is meant to be used when handling SOAP with attachments, which does not seem to be the case.

Title: Sabre SOAP API using cURL

Body:
Is there any example for creating session using SOAP API (cURL)? I need an example to create session using cURL.

$input_xml = '<?xml version="1.0" encoding="UTF-8"?><SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:eb="http://www.ebxml.org/namespaces/messageHeader" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:xsd="http://www.w3.org/1999/XMLSchema">
<SOAP-ENV:Header>
    <eb:MessageHeader SOAP-ENV:mustUnderstand="1" eb:version="1.0">
        <eb:ConversationId/>
        <eb:From>
            <eb:PartyId type="urn:x12.org:IO5:01">999999</eb:PartyId>
        </eb:From>
        <eb:To>
            <eb:PartyId type="urn:x12.org:IO5:01">123123</eb:PartyId>
        </eb:To>
        <eb:CPAId>IPCC</eb:CPAId>
        <eb:Service eb:type="OTA">SessionCreateRQ</eb:Service>
        <eb:Action>SessionCreateRQ</eb:Action>
        <eb:MessageData>
            <eb:MessageId>1000</eb:MessageId>
            <eb:Timestamp>2001-02-15T11:15:12Z</eb:Timestamp>
            <eb:TimeToLive>2001-02-15T11:15:12Z</eb:TimeToLive>
        </eb:MessageData>
    </eb:MessageHeader>
    <wsse:Security xmlns:wsse="http://schemas.xmlsoap.org/ws/2002/12/secext" xmlns:wsu="http://schemas.xmlsoap.org/ws/2002/12/utility">
        <wsse:UsernameToken>
            <wsse:Username>USERNAME</wsse:Username>
            <wsse:Password>PASSWORD</wsse:Password>
            <Organization>IPCC</Organization>
            <Domain>DEFAULT</Domain>
        </wsse:UsernameToken>
    </wsse:Security>
</SOAP-ENV:Header>
<SOAP-ENV:Body><eb:Manifest SOAP-ENV:mustUnderstand="1" eb:version="1.0">
    <eb:Reference xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="cid:rootelement" xlink:type="simple"/>
    </eb:Manifest>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>';

$action = 'SessionCreateRQ';
$url = 'https://webservices.sabre.com';
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $soapXML);

$data = curl_exec($ch);
if(curl_error($ch)) {
    echo "Curl error: " . curl_error($ch);
} else {
    echo $data;
}

I got this error:

soap-env:Client.InvalidEbXmlMessageUnable to create envelope from given source: Error on line 2 of document : The processing instruction target matching "[xX][mM][lL]" is not allowed. Nested exception: The processing instruction target matching "[xX][mM][lL]" is not allowed.javax.xml.soap.SOAPException: Unable to create envelope from given source: Error on line 2 of document : The processing instruction target matching "[xX][mM][lL]" is not allowed. Nested exception: The processing instruction target matching "[xX][mM][lL]" is not allowed.

Body:
I don't know about cURL but the XML is not entirely correct.

You have:

<SOAP-ENV:Body>
    <eb:Manifest SOAP-ENV:mustUnderstand="1" eb:version="1.0">
        <eb:Reference xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="cid:rootelement" xlink:type="simple"/>
    </eb:Manifest>
</SOAP-ENV:Body>

But it should be:

<SOAP-ENV:Body>
    <SessionCreateRQ returnContextID="true">
        <POS>
            <Source PseudoCityCode="IPCC"/>
        </POS>
    </SessionCreateRQ>
</SOAP-ENV:Body>

The Manifest element is meant to be used when handling SOAP with attachments, which does not seem to be the case.


问:
How to delete a table in SQLAlchemy?
I want to delete a table using SQLAlchemy.

Since I am testing over and over again, I want to delete the table my_users so that I can start from scratch every single time.

So far I am using SQLAlchemy to execute raw SQL through the engine.execute() method:

```<code>sql = text('DROP TABLE IF EXISTS my_users;')
result = engine.execute(sql)
</code>```

However, I wonder if there is some standard way to do so. The only one I could find is drop_all(), but it deletes all the structure, not only one specific table:

```<code>Base.metadata.drop_all(engine)   # all tables are deleted
</code>```

For example, given this very basic example. It consists on a SQLite infrastructure with a single table my_users in which I add some content.

```<code>from sqlalchemy import create_engine, Column, Integer, String, text
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base

engine = create_engine('sqlite://', echo=False)
Base = declarative_base()

class User(Base):
    __tablename__ = "my_users"

    id = Column(Integer, primary_key=True)
    name = Column(String)

    def __init__(self, name):
        self.name = name

# Create all the tables in the database which are
# defined by Base's subclasses such as User
Base.metadata.create_all(engine)

# Construct a sessionmaker factory object
session = sessionmaker()

# Bind the sessionmaker to engine
session.configure(bind=engine)

# Generate a session to work with
s = session()

# Add some content
s.add(User('myname'))
s.commit()

# Fetch the data
print(s.query(User).filter(User.name == 'myname').one().name)
</code>```

For this specific case, drop_all() would work, but it won't be convenient from the moment I start having more than one table and I want to keep the other ones.

答:
Below is example code you can execute in iPython to test the creation and deletion of a table on Postgres

```<code>from sqlalchemy import * # imports all needed modules from sqlalchemy

engine = create_engine('postgresql://python:python@127.0.0.1/production') # connection properties stored

metadata = MetaData() # stores the 'production' database's metadata

users = Table('users', metadata,
Column('user_id', Integer),
Column('first_name', String(150)),
Column('last_name', String(150)),
Column('email', String(255)),
schema='python') # defines the 'users' table structure in the 'python' schema of our connection to the 'production' db

users.create(engine) # creates the users table

users.drop(engine) # drops the users table
</code>```

You can also preview my article on Wordpress with this same example and screenshots: oscarvalles.wordpress.com (search for SQL Alchemy).

Title: How to delete a table in SQLAlchemy?

Body:
I want to delete a table using SQLAlchemy.

Since I am testing over and over again, I want to delete the table my_users so that I can start from scratch every single time.

So far I am using SQLAlchemy to execute raw SQL through the engine.execute() method:

sql = text('DROP TABLE IF EXISTS my_users;')
result = engine.execute(sql)

However, I wonder if there is some standard way to do so. The only one I could find is drop_all(), but it deletes all the structure, not only one specific table:

Base.metadata.drop_all(engine)   # all tables are deleted

For example, given this very basic example. It consists on a SQLite infrastructure with a single table my_users in which I add some content.

from sqlalchemy import create_engine, Column, Integer, String, text
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base

engine = create_engine('sqlite://', echo=False)
Base = declarative_base()

class User(Base):
    __tablename__ = "my_users"

    id = Column(Integer, primary_key=True)
    name = Column(String)

    def __init__(self, name):
        self.name = name

# Create all the tables in the database which are
# defined by Base's subclasses such as User
Base.metadata.create_all(engine)

# Construct a sessionmaker factory object
session = sessionmaker()

# Bind the sessionmaker to engine
session.configure(bind=engine)

# Generate a session to work with
s = session()

# Add some content
s.add(User('myname'))
s.commit()

# Fetch the data
print(s.query(User).filter(User.name == 'myname').one().name)

For this specific case, drop_all() would work, but it won't be convenient from the moment I start having more than one table and I want to keep the other ones.

Body:
Below is example code you can execute in iPython to test the creation and deletion of a table on Postgres

from sqlalchemy import * # imports all needed modules from sqlalchemy

engine = create_engine('postgresql://python:python@127.0.0.1/production') # connection properties stored

metadata = MetaData() # stores the 'production' database's metadata

users = Table('users', metadata,
Column('user_id', Integer),
Column('first_name', String(150)),
Column('last_name', String(150)),
Column('email', String(255)),
schema='python') # defines the 'users' table structure in the 'python' schema of our connection to the 'production' db

users.create(engine) # creates the users table

users.drop(engine) # drops the users table

You can also preview my article on Wordpress with this same example and screenshots: oscarvalles.wordpress.com (search for SQL Alchemy).


问:
Like static resource, is it possible to serve JSPs which are placed out side of webapps
I am using Struts2 in my application with Tomcat.

I am serving static resource of my application by placing them outside of webapps with setting in server.xml.

Now I have to serve JSPs in same way, which are outside of  my context. Is it possible? Or is there any way to achieve this?

答:
JSPs get compiled into servlets (hence java classes) that are executed by a JSP container using a fairly complex life-cycle, which you can read about here: https://www.tutorialspoint.com/jsp/jsp_life_cycle.htm

So the short answer is: no.  You can't serve JSP pages outside your web app, since one of the primary functions of that web app is to compile and execute JSPs.

As the other answer suggests, you can access java resources using a variety of mechanisms, but you are always going to need something that looks like a JSP container to render JSPs.

You'll have to move onto a different technology if you want to serve more of your app from something like a content delivery network.

You might look into creating a purely client side app that talks to the back end via REST, graphql, or web sockets.


问:
Custom preprocessing in caret
I use caret for my Machine Learning pipelines. When I have to perform some preprocessing that is not avaliable in the preProcess function, is it possible to create a custom function that can be used instead of the default methods?

答:
Not yet, but I'm 80% done with an interface to caret that uses recipes as the model specification tool. That would allow you to create custom preprocessing methods.

If you want to try it, use the recipe_integration branch of caret on github.

Title: Custom preprocessing in caret


答:
It seems you mean something like below regex (I don't see a reason to repeat a pattern like \s?.{1,15} except its limitation here).

Find:

```<code>(?:(^\[[^][]*],$)\R*){9}\K(?1)
</code>```

Replace with:

```<code>ANY THING
</code>```

Live demo

Title: How can i match 1 every 10 results using regex?

Body:
I have the following regex:

(^\[\s?.{1,15}\s?.{1,15}\s?\]\,$)

On my test file, i got 35k matches. I want to make a interval between the matches. In another words, "match" 1 every 10 matches.

Example:

[-51.039,-19.777], (match)
[-51.039,-19.777],
[-51.039,-19.777],
[-51.039,-19.777],
[-51.039,-19.777],
[-51.039,-19.777],
[-51.039,-19.777],
[-51.039,-19.777],
[-51.039,-19.777],
[-51.039,-19.777],
[-51.039,-19.777],
[-51.039,-19.777], (match)

Body:
It seems you mean something like below regex (I don't see a reason to repeat a pattern like \s?.{1,15} except its limitation here).

Find:

(?:(^\[[^][]*],$)\R*){9}\K(?1)

Replace with:

ANY THING

Live demo


问:
Converting string to time in PHP in this example
I have a string for a date and a string for a time. I need to convert them to the format Y-m-d h:i

This is what I have so far. I am converting the date string to date format:

```<code>$fechasolucion = $_POST['fecha'];
$date = date("Y-m-d",strtotime($fechasolucion));
</code>```

Now I need to include the string $hora (19:29) to the time part of the given date.

I need to get at the end this output:

```<code>$fecha = "2017-07-01"
$hora = "19:29"

$date = "2017-07-01 19:29"
</code>```

答:
You can concatinate the two variables $fecha and $hora and then convert it to time.

```<code><?php
    $fecha = "2017-07-01";
    $hora = "19:29";

    $date_string = $fecha . ' ' . $hora;
    $time = strtotime( $date_string );

    echo date( 'Y-m-d H:i', $time );
?>
</code>```

Output:

```<code>2017-07-01 19:29
</code>```

Body:
I have a string for a date and a string for a time. I need to convert them to the format Y-m-d h:i

This is what I have so far. I am converting the date string to date format:

$fechasolucion = $_POST['fecha'];
$date = date("Y-m-d",strtotime($fechasolucion));

Now I need to include the string $hora (19:29) to the time part of the given date.

I need to get at the end this output:

$fecha = "2017-07-01"
$hora = "19:29"

$date = "2017-07-01 19:29"

Body:
You can concatinate the two variables $fecha and $hora and then convert it to time.

<?php
    $fecha = "2017-07-01";
    $hora = "19:29";

    $date_string = $fecha . ' ' . $hora;
    $time = strtotime( $date_string );

    echo date( 'Y-m-d H:i', $time );
?>

Output:

2017-07-01 19:29


问:
i want to get the core data object based on object ID
i have a Message entity when i fetch the particular item based on objectID

i use this to access but it's showing error

```<code>let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.managedObjectContext.objectWithID(objectID
</code>```

答:
Try this</p>

```<code>do {
   let message = try managedObjectContext.objectWithID(objectID)
}catch let err{
  print(err)
}
</code>```

Body:
i have a Message entity when i fetch the particular item based on objectID

i use this to access but it's showing error

let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.managedObjectContext.objectWithID(objectID

Body:
Try this

do {
   let message = try managedObjectContext.objectWithID(objectID)
}catch let err{
  print(err)
}


问:
Split string by spaces into an array
I want to have a user type some words, and get them converted to an array. I want to split by word. Here is an example:

"15 17 21 46" → [15, 17, 21, 46]

Stuff like split("") and scan make an array out of every single letter.

I would prefer doing it without using YAML. Also, take note in the example that it doesn't include the spaces but it uses those as breaks between values.

Is it possible to do what I did in the example above where I have a bunch of numbers with spaces and those get converted directly to integers? I feel like the spaces might interrupt it in case I do something like to_i.

This question is similar to String to Array in Ruby, but it does not have an answer.

答:
String#split doesn't actually need an argument if you want to split around whitespaces :

```<code>"15 17 21 46".split
#=> ["15", "17", "21", "46"]
</code>```

If you want to specify an argument, you need to use a space, not an empty string :

```<code>"15 17 21 46".split(' ')
#=> ["15", "17", "21", "46"]
</code>```

And if you want to convert those strings to integers :

```<code>"15 17 21 46".split(' ').map(&:to_i)
#=> [15, 17, 21, 46]
</code>```

Title: Split string by spaces into an array

Body:
String#split doesn't actually need an argument if you want to split around whitespaces :

"15 17 21 46".split
#=> ["15", "17", "21", "46"]

If you want to specify an argument, you need to use a space, not an empty string :

"15 17 21 46".split(' ')
#=> ["15", "17", "21", "46"]

And if you want to convert those strings to integers :

"15 17 21 46".split(' ').map(&:to_i)
#=> [15, 17, 21, 46]


问:
camel netty4 message 1024 truncated..how can i solve it?
i made a camel netty4 server program.and client sent 1119 byte message but my decoder truncated by 1024/95

here is my code.

```<code>@ChannelHandler.Sharable
    public static class BytesDecoder extends MessageToMessageDecoder<ByteBuf> {

        @Override
        protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception {
                    System.out.println("BytesDecoder readableBytes:"+msg.readableBytes());
            if (msg.isReadable()) {
                byte[] bytes = new byte[msg.readableBytes()];
                int readerIndex = msg.readerIndex();
                msg.getBytes(readerIndex, bytes);
                out.add(bytes);
            }
        }

    }
</code>```

result ===>

BytesDecoder readableBytes:1024

BytesDecoder readableBytes:95

I want to get a full message byte 1119 byte.

答:
Actually I already replied to this question on the netty mailinglist.

There is not guarantee that you will received all the data in one read call. Thus you will need to account for this by extending ByteToMessageDecoder and only read the bytes once there are at least 1024 readable.

For more example and details please see the javadocs of ByteToMessageDecoder.

Body:
i made a camel netty4 server program.and client sent 1119 byte message but my decoder truncated by 1024/95

here is my code.

@ChannelHandler.Sharable
    public static class BytesDecoder extends MessageToMessageDecoder<ByteBuf> {

        @Override
        protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception {
                    System.out.println("BytesDecoder readableBytes:"+msg.readableBytes());
            if (msg.isReadable()) {
                byte[] bytes = new byte[msg.readableBytes()];
                int readerIndex = msg.readerIndex();
                msg.getBytes(readerIndex, bytes);
                out.add(bytes);
            }
        }

    }

result ===>

BytesDecoder readableBytes:1024

BytesDecoder readableBytes:95

I want to get a full message byte 1119 byte.


问:
Mysql database change event
I need  to call bash script when mysql database schema has changed. As example queries:

```<code>ALTER TABLE, CREATE TABLE, DROP TABLE
</code>```

it possible?

答:
Don't think that's possible any way. You could have probably use a DDL Trigger but MySQL doesn't support one. See worklog https://dev.mysql.com/worklog/task/?id=2418.

Though you can write a stored procedure to perform the business logic and call that procedure but capturing the DDL event isn't possible AFAIK. You should also check on Event Scheduler in MySQL

Title: Mysql database change event

Body:
I need  to call bash script when mysql database schema has changed. As example queries:

ALTER TABLE, CREATE TABLE, DROP TABLE

it possible?


问:
WCF minimal client app.config settings
What are the minimal client settings i need to do for a streamlined WCF config in the app.config?

The default one is this:

```<code>    <bindings>
        <wsHttpBinding>
            <binding name="WSHttpBinding_IService" closeTimeout="00:01:00"
                openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
                bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard"
                maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
                messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true"
                allowCookies="false">
                <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
                    maxBytesPerRead="4096" maxNameTableCharCount="16384" />
                <reliableSession ordered="true" inactivityTimeout="00:10:00"
                    enabled="false" />
                <security mode="Message">
                    <transport clientCredentialType="Windows" proxyCredentialType="None"
                        realm="" />
                    <message clientCredentialType="Windows" negotiateServiceCredential="true"
                        algorithmSuite="Default" establishSecurityContext="true" />
                </security>
            </binding>
        </wsHttpBinding>
    </bindings>
</code>```

What can I exclude, and how much of that do i need?

Edit: Should i just start ripping out parts till it breaks? I was hoping to find some good optimized wsHttpBindings that people have good luck with.

答:
I think you'll find that all of that is optional. All of those things in that particular binding are the defaults anyway.

In fact I think specifying the binding at all in the endpoint would be optional in this case.

OwnerDisplayName: Tom Anderson

Title: WCF minimal client app.config settings

Body:
What are the minimal client settings i need to do for a streamlined WCF config in the app.config?

The default one is this:

    <bindings>
        <wsHttpBinding>
            <binding name="WSHttpBinding_IService" closeTimeout="00:01:00"
                openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
                bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard"
                maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
                messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true"
                allowCookies="false">
                <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
                    maxBytesPerRead="4096" maxNameTableCharCount="16384" />
                <reliableSession ordered="true" inactivityTimeout="00:10:00"
                    enabled="false" />
                <security mode="Message">
                    <transport clientCredentialType="Windows" proxyCredentialType="None"
                        realm="" />
                    <message clientCredentialType="Windows" negotiateServiceCredential="true"
                        algorithmSuite="Default" establishSecurityContext="true" />
                </security>
            </binding>
        </wsHttpBinding>
    </bindings>

What can I exclude, and how much of that do i need?

Edit: Should i just start ripping out parts till it breaks? I was hoping to find some good optimized wsHttpBindings that people have good luck with.

LastEditorDisplayName: Tom Anderson


问:
crash in Visual Studio when attempting to send an email from Android
My Xamarin application is crashing when attempting to send an email from Android. Here's my code:

```<code>public class EmailHelper : Activity, IEmail
{
...
    private bool CreateEmail(string attachment)
    {
        var email = new Intent(Intent.ActionSend);
        SettingsDataAdapter mySettingsDataAdapter = App.MySettingsDataAdapter;
        email.PutExtra(Android.Content.Intent.ExtraEmail, new string[] { "test@test.com"});
        email.PutExtra(Android.Content.Intent.ExtraSubject, "test email");
        email.PutExtra(Android.Content.Intent.ExtraText, "see attachment");
        email.SetType("message/rfc822");
        var file = new Java.IO.File(attachment);
        file.SetReadable(true, false);
        var uri = Android.Net.Uri.FromFile(file);
        email.PutExtra(Intent.ExtraStream, uri);
        email.SetFlags(ActivityFlags.NewTask);
        StartActivity(email);
        return true;
    }
...
}
</code>```

and the first error in the output window is:

```<code>attempt to invoke virtual method 'android.app.activitythread$applicationthread android.app.activitythread.getapplicationthread()' on a null object reference
</code>```

Any ideas? Thanks in advance!

答:
Found out after more digging that an Activity cannot be started without a context. I ended up changing

```<code>StartActivity(email);
</code>```

with

```<code>((Activity)Forms.Context).StartActivity(email);
</code>```

and that specific error went away.

Just a side note that the next error I hit was "no provider found", which was due to not having an email app configured in the emulator.

Body:
My Xamarin application is crashing when attempting to send an email from Android. Here's my code:

public class EmailHelper : Activity, IEmail
{
...
    private bool CreateEmail(string attachment)
    {
        var email = new Intent(Intent.ActionSend);
        SettingsDataAdapter mySettingsDataAdapter = App.MySettingsDataAdapter;
        email.PutExtra(Android.Content.Intent.ExtraEmail, new string[] { "test@test.com"});
        email.PutExtra(Android.Content.Intent.ExtraSubject, "test email");
        email.PutExtra(Android.Content.Intent.ExtraText, "see attachment");
        email.SetType("message/rfc822");
        var file = new Java.IO.File(attachment);
        file.SetReadable(true, false);
        var uri = Android.Net.Uri.FromFile(file);
        email.PutExtra(Intent.ExtraStream, uri);
        email.SetFlags(ActivityFlags.NewTask);
        StartActivity(email);
        return true;
    }
...
}

and the first error in the output window is:

attempt to invoke virtual method 'android.app.activitythread$applicationthread android.app.activitythread.getapplicationthread()' on a null object reference

Any ideas? Thanks in advance!

Body:
Found out after more digging that an Activity cannot be started without a context. I ended up changing

StartActivity(email);

with

((Activity)Forms.Context).StartActivity(email);

and that specific error went away.

Just a side note that the next error I hit was "no provider found", which was due to not having an email app configured in the emulator.


问:
Node.js http.get xml is returned 'escaped'
I am working on a simple AWS Lambda function in Javascript (Node 6.x) which should 'proxy' an RSS of an italian news provider.

This is the code of the function:

```<code>var http = require("http")

exports.handler = (event, context, callback) => {
    http.get("http://www.milanotoday.it/rss/", (response) => {
        response.setEncoding("utf8")

        let xml = ""
        response.on("data", (chunk) => { xml += chunk })
        response.on("end", () => { callback(null, xml) })
    })
}
</code>```

It works, or at least it loads the response inside the xml variable.
I can't get why the string is something like this:

```<code>"<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<rss version=\"2.0\" xmlns:content=\"http://purl.org/rss/1.0/modules/content/\"...
</code>```

It seems to be sort of 'escaped'.

Can somebody help me?
Thank you in advance...

答:
http.get is probably working just fine. If you run your code outside of the AWS ecosystem, you'll see that you are getting unescaped XML from http.get. The problem is that Lambda wants you to return JSON so when you pass the string to the callback it gets escaped.

If you are running this function through API Gateway you can do a transform in the integration response. The way to do this is to return an object from your lambda:

```<code>callback(null, {myXML: xml}))
</code>```

Then in the API Gateway go to the integration response area under your GET (or POST) resource and click the arrow next to the 200 response. This should reveal an area for body mappings. You want to add a mapping for application/xml and then add something like:

```<code>#set($inputRoot = $input.path('$'))
$inputRoot.myXML
</code>```

This should get you nice clean XML. It's a little hard to describe so I'll post a screen shot that might help:

Body:
I am working on a simple AWS Lambda function in Javascript (Node 6.x) which should 'proxy' an RSS of an italian news provider.

This is the code of the function:

var http = require("http")

exports.handler = (event, context, callback) => {
    http.get("http://www.milanotoday.it/rss/", (response) => {
        response.setEncoding("utf8")

        let xml = ""
        response.on("data", (chunk) => { xml += chunk })
        response.on("end", () => { callback(null, xml) })
    })
}

It works, or at least it loads the response inside the xml variable.
I can't get why the string is something like this:

"<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<rss version=\"2.0\" xmlns:content=\"http://purl.org/rss/1.0/modules/content/\"...

It seems to be sort of 'escaped'.

Can somebody help me?
Thank you in advance...

Body:
http.get is probably working just fine. If you run your code outside of the AWS ecosystem, you'll see that you are getting unescaped XML from http.get. The problem is that Lambda wants you to return JSON so when you pass the string to the callback it gets escaped.

If you are running this function through API Gateway you can do a transform in the integration response. The way to do this is to return an object from your lambda:

callback(null, {myXML: xml}))

Then in the API Gateway go to the integration response area under your GET (or POST) resource and click the arrow next to the 200 response. This should reveal an area for body mappings. You want to add a mapping for application/xml and then add something like:

#set($inputRoot = $input.path('$'))
$inputRoot.myXML

This should get you nice clean XML. It's a little hard to describe so I'll post a screen shot that might help:


问:
Swift - Sort a subset of an array
I currently have a tableview with a lot of users, but I would like to sort the users in a specific order, not just ascending or descending. Let's say I have an array with the following users.

```<code>"User1", "1st grade"
"User2", "1st grade"
"User3", "kids"
"User4", "6th grade"
"User5", "5th grade"
"User6", "2nd grade"
"User7", "kids"
"User8", "juniors"
</code>```

How can I order my array so that all the students who are in kids class are the first to be displayed, followed by all the classes with numbers (in order) and then all the Juniors.

I want an array that can display this

```<code>"User3", "kids"
"User7", "kids"
"User1", "1st grade"
"User2", "1st grade"
"User6", "2nd grade"
"User5", "5th grade"
"User4", "6th grade"
"User8", "juniors"
</code>```

Edit:
Updated the text to make clear that the array has two columns, not just one string.

Was able to achieve it by using the line below

```<code>let sortedArray =
self.userArray.sorted(by: { $0.SchoolGrade!.gradeLongName().contains("Kids") ||
$1.SchoolGrade!.gradeLongName().contains("Juniors") })
</code>```

答:
Swift has a sort algorithm that lets you sort using a closure. The closure should return true if the first arguement comes before the second argument.

```<code>let sortedArray = user.sorted(by: {

    ($0.gradeLongName().contains("kids")
     || $1.gradeLongName()contains("juniors")
     || $0.gradeLongName() < $1.gradeLongName())
    && !($0.gradeLongName().contains("kids") && $1.gradeLongName().contains("kids"))
    && !($0.gradeLongName().contains("juniors") && $1.gradeLongName().contains("juniors"))
})
</code>```

Should do the trick. The closure says two elements are in the right order if the first one has kids in it, the second one has juniors in it or they are alphabetically in the right order. The last two subexpressions make the closure return false when two elements both have kids or both have juniors which is a requirement for the API

You can also use trailing closure syntax here:

```<code>let sortedArray = user.sorted{ ($0.gradeLongName().contains("kids")
     || $1.gradeLongName()contains("juniors")
     || $0.gradeLongName() < $1.gradeLongName())
    && !($0.gradeLongName().contains("kids") && $1.gradeLongName().contains("kids")
    && !(($0.gradeLongName().contains("juniors") && $1.gradeLongName().contains("juniors")) }
</code>```

Also you can do an in place sort on a mutable array with sort(by:)

API docs are here: https://developer.apple.com/documentation/swift/array/2296815-sorted

Title: Swift - Sort a subset of an array

Body:
I currently have a tableview with a lot of users, but I would like to sort the users in a specific order, not just ascending or descending. Let's say I have an array with the following users.

"User1", "1st grade"
"User2", "1st grade"
"User3", "kids"
"User4", "6th grade"
"User5", "5th grade"
"User6", "2nd grade"
"User7", "kids"
"User8", "juniors"

How can I order my array so that all the students who are in kids class are the first to be displayed, followed by all the classes with numbers (in order) and then all the Juniors.

I want an array that can display this

"User3", "kids"
"User7", "kids"
"User1", "1st grade"
"User2", "1st grade"
"User6", "2nd grade"
"User5", "5th grade"
"User4", "6th grade"
"User8", "juniors"

Edit:
Updated the text to make clear that the array has two columns, not just one string.

Was able to achieve it by using the line below

let sortedArray =
self.userArray.sorted(by: { $0.SchoolGrade!.gradeLongName().contains("Kids") ||
$1.SchoolGrade!.gradeLongName().contains("Juniors") })

Body:
Swift has a sort algorithm that lets you sort using a closure. The closure should return true if the first arguement comes before the second argument.

let sortedArray = user.sorted(by: {

    ($0.gradeLongName().contains("kids")
     || $1.gradeLongName()contains("juniors")
     || $0.gradeLongName() < $1.gradeLongName())
    && !($0.gradeLongName().contains("kids") && $1.gradeLongName().contains("kids"))
    && !($0.gradeLongName().contains("juniors") && $1.gradeLongName().contains("juniors"))
})

Should do the trick. The closure says two elements are in the right order if the first one has kids in it, the second one has juniors in it or they are alphabetically in the right order. The last two subexpressions make the closure return false when two elements both have kids or both have juniors which is a requirement for the API

You can also use trailing closure syntax here:

let sortedArray = user.sorted{ ($0.gradeLongName().contains("kids")
     || $1.gradeLongName()contains("juniors")
     || $0.gradeLongName() < $1.gradeLongName())
    && !($0.gradeLongName().contains("kids") && $1.gradeLongName().contains("kids")
    && !(($0.gradeLongName().contains("juniors") && $1.gradeLongName().contains("juniors")) }

Also you can do an in place sort on a mutable array with sort(by:)

API docs are here: https://developer.apple.com/documentation/swift/array/2296815-sorted


问:
Type info in AST in Purescript
I'm working with Purescript AST. Dump-corefn gives out incomplete info about program: there's no info about types in corefn.json-file.
What could you advise for getting full AST without type removing?
Thank you.

Example given here.

答: There is already an issue for this in the compiler. You would need to modify the compiler if you need type information. The only option right now is to fork the compiler if you want the full AST.</p>

Title: Type info in AST in Purescript


问:
recursively delete all JSON keys with null values and delete parent key if all child keys are deleted
I'm trying to recursively delete null values in a JSON object and all Subobjects.  If the subobjects keys are all deleted, then I want that subobject to be deleted as well.

ie.

```<code>x = {
  "applicant": {
    'first_name': null,
    'last_name': null,
    'employment_type': null
  },
  'phone': 1123123,
  'branch': null,
  'industry': {
    'id': 1,
    'name': null
  },
  "status": "333"
}
</code>```

should turn into this:

```<code>x = {
    'phone': 1123123,
    'industry': {
         "id": 1
     },
     "status": "333"
    }
</code>```

Here is the function that I wrote to delete all keys with null values:

```<code>function delKeys(app){
  for(key in app){
    if(app[key] !== null && typeof(app[key]) === 'object'){
      delKeys(app[key])
    }
    if(app[key] === null){
      delete app[key]
      }
  }
</code>```

But this doesn't delete the parent key with no children:

so instead of the result above, I get this:

```<code>x = {
    "applicant":{},
    "phone":1123123,
    "industry":{
       'id': 1
     }
     "status": "333"
     }
</code>```

As you can see, it doesn't delete the applicant key. How would I check for that within the function? or does it need to be written in a separate function that I call AFTER calling delKeys()?

Also, does anyone see this hitting maximum recursion depth? I've tried with bigger JSON objects and it seems to be hitting max recursion depth. I would really appreciate help with debugging that

thank you.

答:
After

```<code>delKeys(app[key]);
</code>```

you should

```<code>delete app[key];
</code>```

app[key] is an empty object, not === null, so it won't get picked up by the following if block.

Body:
I'm trying to recursively delete null values in a JSON object and all Subobjects.  If the subobjects keys are all deleted, then I want that subobject to be deleted as well.

ie.

x = {
  "applicant": {
    'first_name': null,
    'last_name': null,
    'employment_type': null
  },
  'phone': 1123123,
  'branch': null,
  'industry': {
    'id': 1,
    'name': null
  },
  "status": "333"
}

should turn into this:

x = {
    'phone': 1123123,
    'industry': {
         "id": 1
     },
     "status": "333"
    }

Here is the function that I wrote to delete all keys with null values:

function delKeys(app){
  for(key in app){
    if(app[key] !== null && typeof(app[key]) === 'object'){
      delKeys(app[key])
    }
    if(app[key] === null){
      delete app[key]
      }
  }

But this doesn't delete the parent key with no children:

so instead of the result above, I get this:

x = {
    "applicant":{},
    "phone":1123123,
    "industry":{
       'id': 1
     }
     "status": "333"
     }

As you can see, it doesn't delete the applicant key. How would I check for that within the function? or does it need to be written in a separate function that I call AFTER calling delKeys()?

Also, does anyone see this hitting maximum recursion depth? I've tried with bigger JSON objects and it seems to be hitting max recursion depth. I would really appreciate help with debugging that

thank you.

Body:
After

delKeys(app[key]);

you should

delete app[key];

app[key] is an empty object, not === null, so it won't get picked up by the following if block.


问:
unable to delete a last file in folder while deleting folder using php
I am calling my php function from some other website which delete a folder on my server in background.

This is a function which I am using to delete a folder.

```<code>public static function remove($dir)
        {
            if (is_dir($dir)) {
                $diropen = opendir($dir);
                while($d = readdir($diropen)) {
                    if ($d!= '.' && $d != '..') {
                        self::remove($dir . "/$d");
                    }
                }
                @rmdir($dir);
            } elseif (is_file($dir)) {
                @unlink($dir);
            }
        }
</code>```

If I am having three files in folder then it deletes only two and unable to delete last file or unlink fails on last file.

If I am having two files then it deletes only one file.

I have checked writable permission using is_writable it is true for all files.

Can somebody please help me out. or how to debug this behavior as this function is getting called in background.

答: my directory was open in some other function , so I closedir my folder and then above function working fine.

Body:
I am calling my php function from some other website which delete a folder on my server in background.

This is a function which I am using to delete a folder.

public static function remove($dir)
        {
            if (is_dir($dir)) {
                $diropen = opendir($dir);
                while($d = readdir($diropen)) {
                    if ($d!= '.' && $d != '..') {
                        self::remove($dir . "/$d");
                    }
                }
                @rmdir($dir);
            } elseif (is_file($dir)) {
                @unlink($dir);
            }
        }

If I am having three files in folder then it deletes only two and unable to delete last file or unlink fails on last file.

If I am having two files then it deletes only one file.

I have checked writable permission using is_writable it is true for all files.

Can somebody please help me out. or how to debug this behavior as this function is getting called in background.


问:
UNRESOLVED_REFERENCE in widget (TextView) resolved to error element in android-kotlin
How to update the text of Textview in kotlin. Set Text on-create function works but when I tried outside main fun it says unresolved ref.

How can I declare widget for reuse TextView for update the Text Value?
I don't have exp with kotlin. Can somebody help me?

```<code>class MediaPickedActivity : AppCompatActivity() {

    val fullName = "Test User"
    var score = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_media_picked)

        val Tv_test = findViewById(R.id.tv_text) as TextView

        Tv_test.setText("$fullName :: $score ")

        if (score in 0..300) {
            score = 5
            setText()
        }

    }

    private fun setText() {
        // Error is here. I can't set text.
        Tv_test.setText("$fullName :: $score ")
    }

}
</code>```

答:
On top of what @zsmb13 said, you can also use the Kotlin Android Extensions plugin (since you included it as one of the topics) which is super convenient for minimizing potential findViewById() bugs, excluding the use of View fields/member variables, and etc. as follows:

First apply the plugin in your local build.gradle file:

apply plugin: 'kotlin-android-extensions'

Next, import the widget properties for a certain layout in your Activity class:

import kotlinx.android.synthetic.main.<layout>.*

... and then your Activity would be as follows:

```<code>import kotlinx.android.synthetic.main.activity_media_picked.*

class MediaPickedActivity : AppCompatActivity() {

    val fullName = "Test User"
    var score = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_media_picked)

        // Simply references via the TextView's ID, and sets its text.
        tv_text.setText("$fullName :: $score ")

        if (score in 0..300) {
            score = 5
            setText()
        }

    }

    private fun setText() {
        tv_text.setText("$fullName :: $score ")
    }

}
</code>```

Body:
How to update the text of Textview in kotlin. Set Text on-create function works but when I tried outside main fun it says unresolved ref.

How can I declare widget for reuse TextView for update the Text Value?
I don't have exp with kotlin. Can somebody help me?

class MediaPickedActivity : AppCompatActivity() {

    val fullName = "Test User"
    var score = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_media_picked)

        val Tv_test = findViewById(R.id.tv_text) as TextView

        Tv_test.setText("$fullName :: $score ")

        if (score in 0..300) {
            score = 5
            setText()
        }

    }

    private fun setText() {
        // Error is here. I can't set text.
        Tv_test.setText("$fullName :: $score ")
    }

}

Body:
On top of what @zsmb13 said, you can also use the Kotlin Android Extensions plugin (since you included it as one of the topics) which is super convenient for minimizing potential findViewById() bugs, excluding the use of View fields/member variables, and etc. as follows:

First apply the plugin in your local build.gradle file:

apply plugin: 'kotlin-android-extensions'

Next, import the widget properties for a certain layout in your Activity class:

import kotlinx.android.synthetic.main.<layout>.*

... and then your Activity would be as follows:

import kotlinx.android.synthetic.main.activity_media_picked.*

class MediaPickedActivity : AppCompatActivity() {

    val fullName = "Test User"
    var score = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_media_picked)

        // Simply references via the TextView's ID, and sets its text.
        tv_text.setText("$fullName :: $score ")

        if (score in 0..300) {
            score = 5
            setText()
        }

    }

    private fun setText() {
        tv_text.setText("$fullName :: $score ")
    }

}


问:
Angular 2 101: defining and using a variable
All I'm trying to do is get my head around Angular 2 syntax. The examples I find seem to use different methods.

Look at foo:

Is this how I set up every single variable I want to use?

I define it using : syntax, and specify its type?
Then later I refer to it with this.?

```<code>export class SwitchClientComponent implements OnInit {
    filterString: string = '';
    foo: string ='';

    ngOnInit() {

        this.foo = localStorage.getItem('bar') || '!';
    }
</code>```

.

```<code>    <span>[{{foo}}]</span>
</code>```

答:
It should be just {{foo}} without the square brackets []

```<code><span>{{foo}}</span>
</code>```

Body:
All I'm trying to do is get my head around Angular 2 syntax. The examples I find seem to use different methods.

Look at foo:

Is this how I set up every single variable I want to use?

I define it using : syntax, and specify its type?
Then later I refer to it with this.?

export class SwitchClientComponent implements OnInit {
    filterString: string = '';
    foo: string ='';

    ngOnInit() {

        this.foo = localStorage.getItem('bar') || '!';
    }

.

    [{{foo}}]

Body:
It should be just {{foo}} without the square brackets []

<span>{{foo}}</span>


问:
Get substring within a string
I come to find some guidance on accomplishing the following:

I have a variable with content like this:

```<code>varname = asdfiuytgy12$gggsy22.oihbcxew
</code>```

or

```<code>varname = oiujedc$thisisit.oiju
</code>```

which $ and . are exactly my partters and I need to get what is within them so gggsy22 or thisisit.

I need to use batch to create a simple bat file. I hope someone can provide some guidance.

Edit - (from comment section)

Actually a friend of mine helped and it did work but with a quite amount of lines:

```<code>Set "sstr=$"
SET stemp=%nameVar%&SET pos=0

:loop
SET /a pos+=1
echo %stemp%|FINDSTR /b /c:"%sstr%" >NUL
IF ERRORLEVEL 1 (
    SET stemp=%stemp:~1%
    IF DEFINED stemp GOTO loop
    SET pos=0
)
Set "pos1=%pos%"
Set "sstr=."
SET stemp=%nameVar%&SET pos=0

:loop
SET /a pos+=1
echo %stemp%|FINDSTR /b /c:"%sstr%" >NUL
IF ERRORLEVEL 1 (
    SET stemp=%stemp:~1%
    IF DEFINED stemp GOTO loop
    SET pos=0
)
Set "pos2=%pos%"
set /a "pos2=%pos2%-%pos1%-1"
call set env=%%nameVar:~%pos1%,%pos2%%%
</code>```

答:
```<code>@echo off
set "varname=asdfiuytgy12$gggsy22.oihbcxew"
for /f "tokens=2 delims=$." %%a in ("%varname%") do set "sub=%%a"
</code>```

Title: Get substring within a string

Body:
I come to find some guidance on accomplishing the following:

I have a variable with content like this:

varname = asdfiuytgy12$gggsy22.oihbcxew

or

varname = oiujedc$thisisit.oiju

which $ and . are exactly my partters and I need to get what is within them so gggsy22 or thisisit.

I need to use batch to create a simple bat file. I hope someone can provide some guidance.

Edit - (from comment section)

Actually a friend of mine helped and it did work but with a quite amount of lines:

Set "sstr=$"
SET stemp=%nameVar%&SET pos=0

:loop
SET /a pos+=1
echo %stemp%|FINDSTR /b /c:"%sstr%" >NUL
IF ERRORLEVEL 1 (
    SET stemp=%stemp:~1%
    IF DEFINED stemp GOTO loop
    SET pos=0
)
Set "pos1=%pos%"
Set "sstr=."
SET stemp=%nameVar%&SET pos=0

:loop
SET /a pos+=1
echo %stemp%|FINDSTR /b /c:"%sstr%" >NUL
IF ERRORLEVEL 1 (
    SET stemp=%stemp:~1%
    IF DEFINED stemp GOTO loop
    SET pos=0
)
Set "pos2=%pos%"
set /a "pos2=%pos2%-%pos1%-1"
call set env=%%nameVar:~%pos1%,%pos2%%%