问:
Why is onMessage() (JMS Listener) not called during unit tests
From console output below, as far as I could see, my embedded ActiveMQ was initialized correctly and it is answering at 61616 port.

When I run the test below, I assume the message is successfully sent because I can debug line-by-line and see both simpleSend() and sendMessage() been ran.

I was expecting to see onMessage been triggered twice but It is not really occurring.

In the code below, when I run the unit test, I understand that:
1 - an embedded ActiveMQ with its broker is started
2 - an instance of MyListener is passed to org.springframework.jms.listener.DefaultMessageListenerContainer

So, what I am missing here in order to test onMessage()?

Console

```<code> INFO | Using Persistence Adapter: MemoryPersistenceAdapter
 INFO | Apache ActiveMQ 5.14.1 (localhost, ID:win10-cha-55866-1509636415848-0:1) is starting
 INFO | Listening for connections at: tcp://127.0.0.1:61616
 INFO | Connector tcp://localhost:61616 started
 INFO | Apache ActiveMQ 5.14.1 (localhost, ID:win10-cha-55866-1509636415848-0:1) started
 INFO | For help or more information please see: http://activemq.apache.org
</code>```

Sender

```<code>import javax.jms.Queue;

import org.springframework.jms.core.JmsTemplate;

public class SampleJmsMessageSender {

    private JmsTemplate jmsTemplate;
    private Queue queue;

    public void setJmsTemplate(JmsTemplate jmsTemplate) {
        this.jmsTemplate = jmsTemplate;
    }

    public void setQueue(Queue queue) {
        this.queue = queue;
    }

    public void simpleSend() {
        jmsTemplate.send(queue, s -> s.createTextMessage("hello queue world"));
    }

    public void sendMessage(final MyPojo mp) {
        this.jmsTemplate.convertAndSend(mp);
    }
}
</code>```

EmbeddedActiveMQ.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:util="http://www.springframework.org/schema/util" xmlns:task="http://www.springframework.org/schema/task"
    xmlns:amq="http://activemq.apache.org/schema/core"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://activemq.apache.org/schema/core
                        http://activemq.apache.org/schema/core/activemq-core-5.2.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

    <!-- Embedded ActiveMQ Broker -->
    <amq:broker id="broker" useJmx="false" persistent="false"
        useShutdownHook="false">
        <amq:transportConnectors>
            <amq:transportConnector uri="tcp://localhost:61616" />
        </amq:transportConnectors>
    </amq:broker>
</beans>
</code>```

applicationContext.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:amq="http://activemq.apache.org/schema/core" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
  http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core.xsd">

    <!-- JmsTemplate Definition -->
    <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
        <property name="connectionFactory" ref="connectionFactory" />
        <property name="defaultDestination" ref="destinationQueue" />
        <property name="messageConverter" ref="myMessageConverter" />
    </bean>
    <bean id="amqConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
        <constructor-arg index="0" value="tcp://localhost:61616" />
    </bean>

    <!-- ConnectionFactory Definition -->
    <bean id="connectionFactory"
        class="org.springframework.jms.connection.SingleConnectionFactory">
        <constructor-arg ref="amqConnectionFactory" />

    </bean>

    <bean id="destinationQueue" class="org.apache.activemq.command.ActiveMQQueue">
        <constructor-arg index="0" value="IN_QUEUE" />
    </bean>

    <bean id="SampleJmsMessageSender" class="com.mypackage.spring.jms.SampleJmsMessageSender">
        <property name="queue" ref="destinationQueue" />
        <property name="jmsTemplate" ref="jmsTemplate" />
    </bean>

    <bean id="myMessageConverter" class="com.mypackage.spring.jms.SampleMessageConverter" />

    <!-- this is the Message-Driven POJO (MDP) -->
    <bean id="messageListener" class="com.mypackage.spring.jms.MyListener">
        <property name="jmsTemplate" ref="jmsTemplate" />
        <property name="queue" ref="destinationQueue" />
    </bean>

    <!-- and this is the message listener container -->
    <bean id="jmsContainer"
        class="org.springframework.jms.listener.DefaultMessageListenerContainer">
        <property name="connectionFactory" ref="connectionFactory" />
        <property name="destinationName" value="IN_QUEUE" />
        <property name="messageListener" ref="messageListener" />
    </bean>
</beans>
</code>```

Unit Test

```<code>import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class DefaultTextMessageSenderIntegrationTest {

    private static SampleJmsMessageSender messageProducer;

    @SuppressWarnings("resource")
    @BeforeClass
    public static void setUp() {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:EmbeddedActiveMQ.xml", "classpath:applicationContext.xml");
        messageProducer = (SampleJmsMessageSender) applicationContext.getBean("SampleJmsMessageSender");
    }

    @Test
    public void test1() {
        messageProducer.simpleSend();
    }

    @Test
    public void test2() {
        messageProducer.sendMessage(new MyPojo("name", 1));
    }
}
</code>```

Listener

```<code>import org.springframework.jms.core.JmsTemplate;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.Queue;
import javax.jms.TextMessage;
import java.util.Map;

public class MyListener implements MessageListener {

    private JmsTemplate jmsTemplate;
    private Queue queue;

    public void setJmsTemplate(JmsTemplate jmsTemplate) {
        this.jmsTemplate = jmsTemplate;
    }

    public void setQueue(Queue queue) {
        this.queue = queue;
    }
    @Override
    public void onMessage(Message message) {
        if (message instanceof TextMessage) {
            try {
                String msg = ((TextMessage) message).getText();
                System.out.println("Received message: " + msg);
            } catch (JMSException ex) {
                throw new RuntimeException(ex);
            }
        }
    }

    public MyPojo receiveMessage() throws JMSException {
        Map map = (Map) this.jmsTemplate.receiveAndConvert();
        return new MyPojo((String) map.get("name"), (Integer) map.get("age"));
    }
}
</code>```

pom.xml

```<code>   <properties>
        <springframework.version>4.3.4.RELEASE</springframework.version>
        <activemq.version>5.14.1</activemq.version>
        <maven-war-plugin.version>2.6</maven-war-plugin.version>
        <maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
        <junit.version>4.12</junit.version>
    </properties>

    <dependencies>

        <!-- Spring JMS -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jms</artifactId>
            <version>${springframework.version}</version>
            <exclusions>
                <exclusion>
                    <artifactId>commons-logging</artifactId>
                    <groupId>commons-logging</groupId>
                </exclusion>
            </exclusions>
        </dependency>

        <!-- ActiveMQ -->
        <dependency>
            <groupId>org.apache.activemq</groupId>
            <artifactId>activemq-all</artifactId>
            <version>${activemq.version}</version>
        </dependency>

        <!--  test -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>${maven-war-plugin.version}</version>
                    <configuration>
                        <warSourceDirectory>src/main/webapp</warSourceDirectory>
                        <warName>spring-jms</warName>
                        <failOnMissingWebXml>false</failOnMissingWebXml>
                    </configuration>
                </plugin>

                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>${maven-compiler-plugin.version}</version>
                    <configuration>
                        <source>1.8</source>
                        <target>1.8</target>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
        <finalName>spring-jms</finalName>
    </build>
</code>```

答:
your unit test stops before your listener (asynchronously) consume the message, you have to include that to the test by
Adding a Thread.sleep(2000); to delay the test stop

Or you add MyListener.receiveMessage() and remove the DMLC...

Or you put String msg = null; of MyListener as an instance variable and await in the test this value to be not null...

With actual code, in debug mode you can put a breakpoint on MyListener.onMessage to verify that the message is consumed

Body:
From console output below, as far as I could see, my embedded ActiveMQ was initialized correctly and it is answering at 61616 port.

When I run the test below, I assume the message is successfully sent because I can debug line-by-line and see both simpleSend() and sendMessage() been ran.

I was expecting to see onMessage been triggered twice but It is not really occurring.

In the code below, when I run the unit test, I understand that:
1 - an embedded ActiveMQ with its broker is started
2 - an instance of MyListener is passed to org.springframework.jms.listener.DefaultMessageListenerContainer

So, what I am missing here in order to test onMessage()?

Console

 INFO | Using Persistence Adapter: MemoryPersistenceAdapter
 INFO | Apache ActiveMQ 5.14.1 (localhost, ID:win10-cha-55866-1509636415848-0:1) is starting
 INFO | Listening for connections at: tcp://127.0.0.1:61616
 INFO | Connector tcp://localhost:61616 started
 INFO | Apache ActiveMQ 5.14.1 (localhost, ID:win10-cha-55866-1509636415848-0:1) started
 INFO | For help or more information please see: http://activemq.apache.org

Sender

import javax.jms.Queue;

import org.springframework.jms.core.JmsTemplate;

public class SampleJmsMessageSender {

    private JmsTemplate jmsTemplate;
    private Queue queue;

    public void setJmsTemplate(JmsTemplate jmsTemplate) {
        this.jmsTemplate = jmsTemplate;
    }

    public void setQueue(Queue queue) {
        this.queue = queue;
    }

    public void simpleSend() {
        jmsTemplate.send(queue, s -> s.createTextMessage("hello queue world"));
    }

    public void sendMessage(final MyPojo mp) {
        this.jmsTemplate.convertAndSend(mp);
    }
}

EmbeddedActiveMQ.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:util="http://www.springframework.org/schema/util" xmlns:task="http://www.springframework.org/schema/task"
    xmlns:amq="http://activemq.apache.org/schema/core"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://activemq.apache.org/schema/core
                        http://activemq.apache.org/schema/core/activemq-core-5.2.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

    <amq:broker id="broker" useJmx="false" persistent="false"
        useShutdownHook="false">
        <amq:transportConnectors>
            <amq:transportConnector uri="tcp://localhost:61616" />
        </amq:transportConnectors>
    </amq:broker>
</beans>

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:amq="http://activemq.apache.org/schema/core" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
  http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core.xsd">

    <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
        <property name="connectionFactory" ref="connectionFactory" />
        <property name="defaultDestination" ref="destinationQueue" />
        <property name="messageConverter" ref="myMessageConverter" />
    </bean>
    <bean id="amqConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
        <constructor-arg index="0" value="tcp://localhost:61616" />
    </bean>

    <bean id="connectionFactory"
        class="org.springframework.jms.connection.SingleConnectionFactory">
        <constructor-arg ref="amqConnectionFactory" />

    </bean>

    <bean id="destinationQueue" class="org.apache.activemq.command.ActiveMQQueue">
        <constructor-arg index="0" value="IN_QUEUE" />
    </bean>

    <bean id="SampleJmsMessageSender" class="com.mypackage.spring.jms.SampleJmsMessageSender">
        <property name="queue" ref="destinationQueue" />
        <property name="jmsTemplate" ref="jmsTemplate" />
    </bean>

    <bean id="myMessageConverter" class="com.mypackage.spring.jms.SampleMessageConverter" />

    <bean id="messageListener" class="com.mypackage.spring.jms.MyListener">
        <property name="jmsTemplate" ref="jmsTemplate" />
        <property name="queue" ref="destinationQueue" />
    </bean>

    <bean id="jmsContainer"
        class="org.springframework.jms.listener.DefaultMessageListenerContainer">
        <property name="connectionFactory" ref="connectionFactory" />
        <property name="destinationName" value="IN_QUEUE" />
        <property name="messageListener" ref="messageListener" />
    </bean>
</beans>

Unit Test

import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class DefaultTextMessageSenderIntegrationTest {

    private static SampleJmsMessageSender messageProducer;

    @SuppressWarnings("resource")
    @BeforeClass
    public static void setUp() {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:EmbeddedActiveMQ.xml", "classpath:applicationContext.xml");
        messageProducer = (SampleJmsMessageSender) applicationContext.getBean("SampleJmsMessageSender");
    }

    @Test
    public void test1() {
        messageProducer.simpleSend();
    }

    @Test
    public void test2() {
        messageProducer.sendMessage(new MyPojo("name", 1));
    }
}

Listener

import org.springframework.jms.core.JmsTemplate;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.Queue;
import javax.jms.TextMessage;
import java.util.Map;

public class MyListener implements MessageListener {

    private JmsTemplate jmsTemplate;
    private Queue queue;

    public void setJmsTemplate(JmsTemplate jmsTemplate) {
        this.jmsTemplate = jmsTemplate;
    }

    public void setQueue(Queue queue) {
        this.queue = queue;
    }
    @Override
    public void onMessage(Message message) {
        if (message instanceof TextMessage) {
            try {
                String msg = ((TextMessage) message).getText();
                System.out.println("Received message: " + msg);
            } catch (JMSException ex) {
                throw new RuntimeException(ex);
            }
        }
    }

    public MyPojo receiveMessage() throws JMSException {
        Map map = (Map) this.jmsTemplate.receiveAndConvert();
        return new MyPojo((String) map.get("name"), (Integer) map.get("age"));
    }
}

pom.xml

   <properties>
        <springframework.version>4.3.4.RELEASE</springframework.version>
        <activemq.version>5.14.1</activemq.version>
        <maven-war-plugin.version>2.6</maven-war-plugin.version>
        <maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
        <junit.version>4.12</junit.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jms</artifactId>
            <version>${springframework.version}</version>
            <exclusions>
                <exclusion>
                    <artifactId>commons-logging</artifactId>
                    <groupId>commons-logging</groupId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.apache.activemq</groupId>
            <artifactId>activemq-all</artifactId>
            <version>${activemq.version}</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>${maven-war-plugin.version}</version>
                    <configuration>
                        <warSourceDirectory>src/main/webapp</warSourceDirectory>
                        <warName>spring-jms</warName>
                        <failOnMissingWebXml>false</failOnMissingWebXml>
                    </configuration>
                </plugin>

                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>${maven-compiler-plugin.version}</version>
                    <configuration>
                        <source>1.8</source>
                        <target>1.8</target>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
        <finalName>spring-jms</finalName>
    </build>


来源: stackexchange

答:
Your output format is frankly pretty bizarre and requires reversing the order of indices a lot, (and makes the output fairly useless for indexing the original array) but this works:

```<code>def find_boxes(np_matrix):
    np_mat = np_matrix[::-1, :]  # reversed in expected output
    def find_extent(arr, val):
        xn = arr.size
        x0 = np.flatnonzero(arr == 1)
        xi = np.searchsorted(x0, val, side = 'right')
        if xi == x0.size:
            x1 = x0[xi-1]
            x2 = xn - 1
        elif xi == 0:
            x1 = 0
            x2 = x0[xi]
        else:
            x1 = x0[xi-1]
            x2 = x0[xi]
        return np.array([x1, x2])

    green = np.where(np_mat == 2)
    green = tuple(g[np.argsort(green[-1])] for g in green)
    coords = np.empty((green[0].size, 2, 4))

    for i, (x, y) in enumerate(zip(*green)):
        coords[i, 0] =   np.tile(find_extent(np_mat[x, :], y),       2)
        coords[i, 1] = np.repeat(find_extent(np_mat[:, y], x)[::-1], 2)  # reversed again
    return np.stack(green)[::-1].T, coords.swapaxes(1,2).astype(int)
    # reversed again and transposed
</code>```

Testing:

```<code>find_boxes(np_matrix)
Out:
(array([[ 0,  0],
        [ 7, 12],
        [16, 27],
        [29, 21],
        [34,  7]], dtype=int32),
 array([[[ 0,  6],
         [ 2,  6],
         [ 0,  0],
         [ 2,  0]],

        [[ 3, 14],
         [ 9, 14],
         [ 3,  7],
         [ 9,  7]],

        [[12, 31],
         [23, 31],
         [12, 24],
         [23, 24]],

        [[25, 22],
         [32, 22],
         [25, 15],
         [32, 15]],

        [[33, 13],
         [35, 13],
         [33,  0],
         [35,  0]]]))
</code>```

ContentLicense: CC BY-SA 3.0

Title: Get coordinates of squares in numpy matrix

Body:
Given the following numpy matrix

import numpy as np
np_matrix = np.array([[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
                    ,[0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0]
                    ,[0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0]
                    ,[0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0]
                    ,[0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0]
                    ,[0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,2,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0]
                    ,[0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0]
                    ,[0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0]
                    ,[0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0]
                    ,[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
                    ,[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,0,0,0]
                    ,[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,2,0,0,1,0,0,0]
                    ,[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0]
                    ,[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0]
                    ,[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0]
                    ,[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0]
                    ,[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0]
                    ,[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,0,0,0]
                    ,[0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
                    ,[0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1]
                    ,[0,0,0,1,0,0,0,2,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0]
                    ,[0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0]
                    ,[0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0]
                    ,[0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0]
                    ,[0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0]
                    ,[0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,0]
                    ,[1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0]
                    ,[0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0]
                    ,[0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0]
                    ,[0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0]
                    ,[0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0]
                    ,[0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0]
                    ,[2,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0]])

print(np_matrix)
print(np_matrix.shape)

which can be represented as an image.

Here are a few assumptions about the input matrix:

The matrix shape can vary. It is not a fixed size.

The number of squares varies from matrix to matrix. But there is always at least one square in the matrix.

For each green dot there is a square around it and squares have a single dot inside them. The dot inside the square is marked with number 2

Squares are sequential on the X axis and square's borders never overlap the borders of other squares. Squares borders are marked with number 1

The white space is marked with number 0

I have two questions. In the most efficient way how can i get an array with the coordinates of all the green dots? And how can i get an array with all the corners for the squares around a green dot?

Here is the result i am looking after for this example:

green_dots_coordinates = [
    [0,0],  # dot 1 with coordinates x1, y1 inside square 1
    [7,12], # dot 2 with coordinates x2, y2 inside square 2
    [16,27],# dot 3 with coordinates x3, y3 inside square 3
    [29,21],# dot 4 with coordinates x4, y4 inside square 4
    [34,7], # dot 5 with coordinates x5, y5 inside square 5
]

sqaures_corners_coordinates = [
    #square nr 1
    [
        [0,6], # x1, y1
        [2,6], # x2, y2
        [0,0], # x3, y3
        [2,0], # x4, y4
    ],

    #square nr 2
    [
        [3,14], # x1, y1
        [9,14], # x2, y2
        [3,7], # x3, y3
        [9,7], # x4, y4
    ],

    #square nr 3
    [
        [12,31], # x1, y1
        [23,31], # x2, y2
        [12,24], # x3, y3
        [23,24], # x4, y4
    ],

    #square nr 4
    [
        [25,22], # x1, y1
        [32,22], # x2, y2
        [25,15], # x3, y3
        [32,15], # x4, y4
    ]

    ,#square nr 5
    [
        [33,13], # x1, y1
        [35,13], # x2, y2
        [33,0], # x3, y3
        [35,0], # x4, y4
    ],

]

Body:
Your output format is frankly pretty bizarre and requires reversing the order of indices a lot, (and makes the output fairly useless for indexing the original array) but this works:

def find_boxes(np_matrix):
    np_mat = np_matrix[::-1, :]  # reversed in expected output
    def find_extent(arr, val):
        xn = arr.size
        x0 = np.flatnonzero(arr == 1)
        xi = np.searchsorted(x0, val, side = 'right')
        if xi == x0.size:
            x1 = x0[xi-1]
            x2 = xn - 1
        elif xi == 0:
            x1 = 0
            x2 = x0[xi]
        else:
            x1 = x0[xi-1]
            x2 = x0[xi]
        return np.array([x1, x2])

    green = np.where(np_mat == 2)
    green = tuple(g[np.argsort(green[-1])] for g in green)
    coords = np.empty((green[0].size, 2, 4))

    for i, (x, y) in enumerate(zip(*green)):
        coords[i, 0] =   np.tile(find_extent(np_mat[x, :], y),       2)
        coords[i, 1] = np.repeat(find_extent(np_mat[:, y], x)[::-1], 2)  # reversed again
    return np.stack(green)[::-1].T, coords.swapaxes(1,2).astype(int)
    # reversed again and transposed

Testing:

find_boxes(np_matrix)
Out:
(array([[ 0,  0],
        [ 7, 12],
        [16, 27],
        [29, 21],
        [34,  7]], dtype=int32),
 array([[[ 0,  6],
         [ 2,  6],
         [ 0,  0],
         [ 2,  0]],

        [[ 3, 14],
         [ 9, 14],
         [ 3,  7],
         [ 9,  7]],

        [[12, 31],
         [23, 31],
         [12, 24],
         [23, 24]],

        [[25, 22],
         [32, 22],
         [25, 15],
         [32, 15]],

        [[33, 13],
         [35, 13],
         [33,  0],
         [35,  0]]]))


问:
Linux script for probing ssh connection in a loop and start log command after connect
I have a host machine that gets rebooted or reconnected quite a few times.
I want to have a script running on my dev machine that continuously tries to log into that machine and if successful runs a specific command (tailing the log data).
Edit: To clarify, the connection needs to stay open. The log command keeps tailing until I stop it manually.

What I have so far

```<code>#!/bin/bash

IP=192.168.178.1

if (("$#" >= 1))
then
  IP=$1
fi

LOOP=1

trap 'echo "stopping"; LOOP=0' INT

while (( $LOOP==1 ))
do
if ping -c1 $IP
then
  echo "Host $IP reached"
  sshpass -p 'password' ssh -o ConnectTimeout=10 -q user@$IP '<command would go here>'
else
  echo "Host $IP unreachable"
fi
sleep 1

done
</code>```

The LOOP flag is not really used. The script is ended via CTRL-C.
Now this works if I do NOT add a command to be executed after the ssh and instead start the log output manually. On a disconnect the script keeps probing the connection and logs back in once the host is available again.
Also when I disconnect from the host (CTRL-D) the script will log right back into the host if CTRL-C is not pressed fast enough.
When I add a command to be executed after ssh the loop is broken. So pressing (CTRL-C) does not only stop the log but also disconnects and ends the script on the dev machine.

I guess I have to spawn another shell somewhere or something like that?

1) I want the script to keep probing, log in and run a command completely automatically and fall back to probing when the connection breaks.
2) I want to be able to stop the log on the host (CTRL-C) and thereby fall back to a logged in ssh connection to use it manually.

How do I fix this?

答:
Not really sure what you are saying.

Also, you should disable PasswordAuthentication in /etc/ssh/sshd_config and log by adding the public key of your home computer to `~/.ssh/authorized_keys

! /bin/sh

```<code>while [ true ];
do
    RESPONSE=`ssh -i /home/user/.ssh/id_host user@$IP 'tail /home/user/log.txt'`

    echo $RESPONSE

    sleep 10
done
</code>```

Body:
I have a host machine that gets rebooted or reconnected quite a few times.
I want to have a script running on my dev machine that continuously tries to log into that machine and if successful runs a specific command (tailing the log data).
Edit: To clarify, the connection needs to stay open. The log command keeps tailing until I stop it manually.

What I have so far

#!/bin/bash

IP=192.168.178.1

if (("$#" >= 1))
then
  IP=$1
fi

LOOP=1

trap 'echo "stopping"; LOOP=0' INT

while (( $LOOP==1 ))
do
if ping -c1 $IP
then
  echo "Host $IP reached"
  sshpass -p 'password' ssh -o ConnectTimeout=10 -q user@$IP '<command would go here>'
else
  echo "Host $IP unreachable"
fi
sleep 1

done

The LOOP flag is not really used. The script is ended via CTRL-C.
Now this works if I do NOT add a command to be executed after the ssh and instead start the log output manually. On a disconnect the script keeps probing the connection and logs back in once the host is available again.
Also when I disconnect from the host (CTRL-D) the script will log right back into the host if CTRL-C is not pressed fast enough.
When I add a command to be executed after ssh the loop is broken. So pressing (CTRL-C) does not only stop the log but also disconnects and ends the script on the dev machine.

I guess I have to spawn another shell somewhere or something like that?

1) I want the script to keep probing, log in and run a command completely automatically and fall back to probing when the connection breaks.
2) I want to be able to stop the log on the host (CTRL-C) and thereby fall back to a logged in ssh connection to use it manually.

How do I fix this?

Body:
Not really sure what you are saying.

Also, you should disable PasswordAuthentication in /etc/ssh/sshd_config and log by adding the public key of your home computer to `~/.ssh/authorized_keys

! /bin/sh

while [ true ];
do
    RESPONSE=`ssh -i /home/user/.ssh/id_host user@$IP 'tail /home/user/log.txt'`

    echo $RESPONSE

    sleep 10
done


问:
How do I calculate the DFT with dt=0.02?
Now I'm trying to understand how does DFT work.
So I've implemented with matlab this to do as the below matlab code.

the function is

and

```<code>clear all
clc

N=8;
dt=0.02;
fs=1/dt;
T=0.16;
tspan = (0:N-1)/fs;
y = 5+cos(2*pi*12.5*tspan)+sin(2*pi*18.75*tspan);

X=zeros(1,N);

for k = 0:N-1
    for n = 0:N-1
        X(k+1) = X(k+1) + y(n+1)*exp(-j*(2*pi/N)*k*n);
    end
end

x_mag = abs(X);
plot(0:N-1,x_mag);
</code>```

I was expecting the result as this

but I've got

What am I supposed to do get correct result?

update

If I've added N to 80 from 8, then I've got the below graph but
this result also seemed to be wrong.

frequency is appeared as 20 and 30 not 12.5 and 18.75.

Update #1

I found something rules with the below the Matlab code. When I run with N=350 then
enter image description here

```<code>   dt=0.02
    fs=1/dt % hz = 1/0.02 (delta T)

     N=350;

     tspan = (0:N-1)*dt;
     y = 5+cos(2*pi*12.5*tspan)+sin(2*pi*18.75*tspan);

    X=y;

    X=zeros(1,N);

    for k = 0:N-1
        for n = 0:N-1
            X(k+1) = X(k+1) + y(n+1)*exp(-j*(2*pi/N)*k*n);
        end
    end

    x_mag = abs(X);
    plot(0:N-1,x_mag);
</code>```

and when I have N=50 then I can the below graph
enter image description here

I think When I have N=50, it seems to be more correct result.

But I can't understand How do we decide the proper N?

答:
You're getting the exact result that you should get. Read the description of the function here.

So wats happening ist you are sampling 80 points in time, that means you get 80 poins in frequency space. Since your function is real, not complex, the DFT is symmetric and arraged around the midpoint of 80 samples, meaning around 40.

(And you are also plotting in index-space, not frequency space!)

From 40 you have the symmetric Fourier transform with positive and negaive frequencies the same (real function in time space). If you count from 40, you probably get the peaks at exactly 12.5 (52.5) and 18.75 (58.75) Hz as you wanted to.

Hope this helps.

Some code from the documentation:

```<code>Y = fft(X);
P2 = abs(Y/L);
P1 = P2(1:L/2+1);
P1(2:end-1) = 2*P1(2:end-1);

f = Fs*(0:(L/2))/L;
plot(f,P1)
title('Single-Sided Amplitude Spectrum of X(t)')
xlabel('f (Hz)')
ylabel('|P1(f)|')
</code>```

Body:
Now I'm trying to understand how does DFT work.
So I've implemented with matlab this to do as the below matlab code.

the function is

and

clear all
clc

N=8;
dt=0.02;
fs=1/dt;
T=0.16;
tspan = (0:N-1)/fs;
y = 5+cos(2*pi*12.5*tspan)+sin(2*pi*18.75*tspan);

X=zeros(1,N);

for k = 0:N-1
    for n = 0:N-1
        X(k+1) = X(k+1) + y(n+1)*exp(-j*(2*pi/N)*k*n);
    end
end

x_mag = abs(X);
plot(0:N-1,x_mag);

I was expecting the result as this

but I've got

What am I supposed to do get correct result?

update

If I've added N to 80 from 8, then I've got the below graph but
this result also seemed to be wrong.

frequency is appeared as 20 and 30 not 12.5 and 18.75.

Update #1

I found something rules with the below the Matlab code. When I run with N=350 then
enter image description here

   dt=0.02
    fs=1/dt % hz = 1/0.02 (delta T)

     N=350;

     tspan = (0:N-1)*dt;
     y = 5+cos(2*pi*12.5*tspan)+sin(2*pi*18.75*tspan);

    X=y;

    X=zeros(1,N);

    for k = 0:N-1
        for n = 0:N-1
            X(k+1) = X(k+1) + y(n+1)*exp(-j*(2*pi/N)*k*n);
        end
    end

    x_mag = abs(X);
    plot(0:N-1,x_mag);

and when I have N=50 then I can the below graph
enter image description here

I think When I have N=50, it seems to be more correct result.

But I can't understand How do we decide the proper N?

Body:
You're getting the exact result that you should get. Read the description of the function here.

So wats happening ist you are sampling 80 points in time, that means you get 80 poins in frequency space. Since your function is real, not complex, the DFT is symmetric and arraged around the midpoint of 80 samples, meaning around 40.

(And you are also plotting in index-space, not frequency space!)

From 40 you have the symmetric Fourier transform with positive and negaive frequencies the same (real function in time space). If you count from 40, you probably get the peaks at exactly 12.5 (52.5) and 18.75 (58.75) Hz as you wanted to.

Hope this helps.

Some code from the documentation:

Y = fft(X);
P2 = abs(Y/L);
P1 = P2(1:L/2+1);
P1(2:end-1) = 2*P1(2:end-1);

f = Fs*(0:(L/2))/L;
plot(f,P1)
title('Single-Sided Amplitude Spectrum of X(t)')
xlabel('f (Hz)')
ylabel('|P1(f)|')


问:
project loading issue
I have an issue while trying to load a C# project

```<code>var project = new Project(xmlProject, null, null, ProjectCollection.GlobalProjectCollection, ProjectLoadSettings.Default);
</code>```

Failure - An equivalent project (a project with the same global properties and tools version) is already present in the project collection

What is the best way to deal with this problem ?

答:
You can unload the project after working with it:

```<code>ProjectCollection.GlobalProjectCollection.UnloadProject(project);
</code>```

Or you check the loaded projects:

```<code>ProjectCollection.GlobalProjectCollection.GetLoadedProjects(projectFilePath)
</code>```

Title: project loading issue

Body:
I have an issue while trying to load a C# project

var project = new Project(xmlProject, null, null, ProjectCollection.GlobalProjectCollection, ProjectLoadSettings.Default);

Failure - An equivalent project (a project with the same global properties and tools version) is already present in the project collection

What is the best way to deal with this problem ?

Body:
You can unload the project after working with it:

ProjectCollection.GlobalProjectCollection.UnloadProject(project);

Or you check the loaded projects:

ProjectCollection.GlobalProjectCollection.GetLoadedProjects(projectFilePath)


问:
How to calculate dp for LDPI,MDPI,HDPI,XXHDPI,XXXHDPI in android
i have screen which is deisgned in XHDPI .

I have to convert all padding ,margin value of dp into LDPI,MDPI,HDPI,XXHDPI,XXXHDPI

Can any one please suggest me how  i will calculate dp value for follwing screen suppose i have paddingTop in xhdpi is 56dp then what value we have give for ldpi,mdpi, xxhdpi and  xxxhdpi

please suggest me.

答:
Density-independent pixel (dp)

A virtual pixel unit that you should use when defining UI layout, to express layout dimensions or position in a density-independent way.
The density-independent pixel is equivalent to one physical pixel on a 160 dpi screen, which is the baseline density assumed by the system for a "medium" density screen. At runtime, the system transparently handles any scaling of the dp units, as necessary, based on the actual density of the screen in use. The conversion of dp units to screen pixels is simple: px = dp * (dpi / 160). For example, on a 240 dpi screen, 1 dp equals 1.5 physical pixels. You should always use dp units when defining your application's UI, to ensure proper display of your UI on screens with different densities.

If you want to know what's 56dp in xhdpi, that's 56dp in ldpi, mdpi, hdpi, xxhdpi, xxxhdpi as well - as the definition says, it's density-independent pixels.

When you work with a design, you want to know one thing:

What's the baseline scale for the design?

Some quick answers: It's usually 1x, 2x or in rare cases 3x

Android defines the following densities:

ldpi (low) ~120dpi

mdpi (medium) ~160dpi

hdpi (high) ~240dpi

xhdpi (extra-high) ~320dpi

xxhdpi (extra-extra-high) ~480dpi

xxxhdpi (extra-extra-extra-high) ~640dpi

There are some rare cases in-between, like tvdpi, but in 99% of the cases you can just simply ignore those.

When designers say 1x, they usually refer to mdpi, 2x (or retina) refers to xhdpi and 3x design is done in xxhdpi.

Once you know the baseline, you know how to translate the pixel values from the design document to dip (density-independent pixel).

The formula is quite simple, but if you doubt yourself, feel free to try one of the online converter tools:

https://pixplicity.com/dp-px-converter

http://angrytools.com/android/pixelcalc/

The formula is as follows: dp = px / (dpi / 160) where dpi is the current screen density and px is the value in the base (1x) density.

Or the other way around.

Also, remember to read the Best Practices from the Android Developers page!

If you still end up using px in your dimensions file which are not recommended, please take a look at this answer to know how to create different values folder for different screens.


问:
how to format time with jquery/javascript
I have a JSON feed that drupal spits out time in this format:   2010-12-16T04:41:35Z

How do I go about formating it to X minutes/hours ago?

答:
Take a look at the timeago jQuery plugin which can be used programtically like </p>

```<code>var t = jQuery.timeago("2010-12-16T04:41:35Z");
</code>```

<p>or on HTML elements like </p>

```<code><time class="timeago" datetime="2008-07-17T09:24:17Z">July 17, 2008</time>
<script type="javascript">
  jQuery(document).ready(function() {
    jQuery("time.timeago").timeago();
  });
</script>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Take a look at the timeago jQuery plugin which can be used programtically like

var t = jQuery.timeago("2010-12-16T04:41:35Z");

or on HTML elements like

<time class="timeago" datetime="2008-07-17T09:24:17Z">July 17, 2008</time>
<script type="javascript">
  jQuery(document).ready(function() {
    jQuery("time.timeago").timeago();
  });
</script>


问:
Container vs Panel in Extjs
I have a question about Extjs

I have read the official document on Sencha doc but I have some confusion about 2 kinds of Component .That's the Container and the Panel.

What is the difference between Container and Panel? Which should be used in which case?

Any answer are very appreciated.

答:
Andrei I has explained the process pretty well and here is one more documentation. On this documentation, Sencha team details how to choose correct class to extend for three of these widgets: Component, Container & Panel.

Which Class To Extend

Choosing the best class to extend is mainly a matter of efficiency,
  and which capabilities the base class must provide.

Title: Container vs Panel in Extjs


问:
sql time weighted average
I have a table of times and temperatures taken at those times - there is a row for every time the temperature changed. I want the weighted average of the temperature - if it was 1 degree for an hour, and 2 degrees for 9 hours, the weighted average temperature is 1.9 degrees. I know how to calculate weighted averages, and I know a little about select ... over ... order by ... group by, and I think this is how it can be done, but I just can't see how to get what I want.

Here's some data ... many thanks for any help.

```<code>create table dbo.Temps (EffectiveDateTime datetime2(7), Temp float)

insert into dbo.Temps values('2017-04-25 13:51:45.2630000', 0.19)

insert into dbo.Temps values('2017-04-25 14:13:24.1590000', 0.29)

insert into dbo.Temps values('2017-04-25 14:53:10.2590000', 0.39)

insert into dbo.Temps values('2017-04-25 13:46:27.0650000', 0.49)

insert into dbo.Temps values('2017-04-25 14:10:50.2670000', 0.59)

insert into dbo.Temps values('2017-04-25 14:48:10.7570000', 0.69)

insert into dbo.Temps values('2017-04-25 14:04:42.9650000', 0.79)

insert into dbo.Temps values('2017-04-25 14:27:59.5590000', 0.89)

insert into dbo.Temps values('2017-04-25 14:56:38.8550000', 0.99)

insert into dbo.Temps values('2017-04-25 14:08:11.8580000', 1.09)

insert into dbo.Temps values('2017-04-25 14:33:39.4540000', 1.19)
</code>```

答:
You should find the time interval first. You say hours, but I am using minutes in order to be more accurate - you can change this setting other date part:

```<code>WITH DataSource AS
(
    SELECT ROW_NUMBER() OVER (ORDER BY [EffectiveDateTime] ASC) AS [RowID]
          ,*
    FROM Temps
)
SELECT TS.[Temp]
      ,DATEDIFF(MINUTE, TS.[EffectiveDateTime], TE.[EffectiveDateTime])
FROM DataSource TS
INNER JOIN DataSource TE
    ON TS.[RowID] = TE.[RowID] - 1;
</code>```

This will give you how many minutes the temp as particular degree:

The final query will be to sum this values SUM(temp * minutes) and divided them to all minutes:

```<code>WITH DataSource AS
(
    SELECT ROW_NUMBER() OVER (ORDER BY [EffectiveDateTime] ASC) AS [RowID]
          ,*
    FROM Temps
)
SELECT SUM(TS.[Temp] * DATEDIFF(MINUTE, TS.[EffectiveDateTime], TE.[EffectiveDateTime])) / SUM(DATEDIFF(MINUTE, TS.[EffectiveDateTime], TE.[EffectiveDateTime]))
FROM DataSource TS
INNER JOIN DataSource TE
    ON TS.[RowID] = TE.[RowID] - 1
</code>```

Title: sql time weighted average

Body:
I have a table of times and temperatures taken at those times - there is a row for every time the temperature changed. I want the weighted average of the temperature - if it was 1 degree for an hour, and 2 degrees for 9 hours, the weighted average temperature is 1.9 degrees. I know how to calculate weighted averages, and I know a little about select ... over ... order by ... group by, and I think this is how it can be done, but I just can't see how to get what I want.

Here's some data ... many thanks for any help.

create table dbo.Temps (EffectiveDateTime datetime2(7), Temp float)

insert into dbo.Temps values('2017-04-25 13:51:45.2630000', 0.19)

insert into dbo.Temps values('2017-04-25 14:13:24.1590000', 0.29)

insert into dbo.Temps values('2017-04-25 14:53:10.2590000', 0.39)

insert into dbo.Temps values('2017-04-25 13:46:27.0650000', 0.49)

insert into dbo.Temps values('2017-04-25 14:10:50.2670000', 0.59)

insert into dbo.Temps values('2017-04-25 14:48:10.7570000', 0.69)

insert into dbo.Temps values('2017-04-25 14:04:42.9650000', 0.79)

insert into dbo.Temps values('2017-04-25 14:27:59.5590000', 0.89)

insert into dbo.Temps values('2017-04-25 14:56:38.8550000', 0.99)

insert into dbo.Temps values('2017-04-25 14:08:11.8580000', 1.09)

insert into dbo.Temps values('2017-04-25 14:33:39.4540000', 1.19)

Body:
You should find the time interval first. You say hours, but I am using minutes in order to be more accurate - you can change this setting other date part:

WITH DataSource AS
(
    SELECT ROW_NUMBER() OVER (ORDER BY [EffectiveDateTime] ASC) AS [RowID]
          ,*
    FROM Temps
)
SELECT TS.[Temp]
      ,DATEDIFF(MINUTE, TS.[EffectiveDateTime], TE.[EffectiveDateTime])
FROM DataSource TS
INNER JOIN DataSource TE
    ON TS.[RowID] = TE.[RowID] - 1;

This will give you how many minutes the temp as particular degree:

The final query will be to sum this values SUM(temp * minutes) and divided them to all minutes:

WITH DataSource AS
(
    SELECT ROW_NUMBER() OVER (ORDER BY [EffectiveDateTime] ASC) AS [RowID]
          ,*
    FROM Temps
)
SELECT SUM(TS.[Temp] * DATEDIFF(MINUTE, TS.[EffectiveDateTime], TE.[EffectiveDateTime])) / SUM(DATEDIFF(MINUTE, TS.[EffectiveDateTime], TE.[EffectiveDateTime]))
FROM DataSource TS
INNER JOIN DataSource TE
    ON TS.[RowID] = TE.[RowID] - 1


答:
You are probably looking at something like this, assuming your version of SQL Server supports the LEAD function:

```<code>;with cte as
(select *, lead(effectivedatetime) over (order by effectivedatetime) timelead
from dbo.temps)

,processed as
(select *, datediff(mi,effectivedatetime,timelead)/cast(60 as decimal(10,2)) as hrdiff
from cte)

select sum(hrdiff*temp)/sum(hrdiff)
from processed
</code>```

It first uses LEAD to get next temperature reading, them gets the time difference in hours and finally calculates a weighted average. Of course, you will need to adjust for precision for the above.

SQLFiddle Demo

Title: sql time weighted average

Body:
You are probably looking at something like this, assuming your version of SQL Server supports the LEAD function:

;with cte as
(select *, lead(effectivedatetime) over (order by effectivedatetime) timelead
from dbo.temps)

,processed as
(select *, datediff(mi,effectivedatetime,timelead)/cast(60 as decimal(10,2)) as hrdiff
from cte)

select sum(hrdiff*temp)/sum(hrdiff)
from processed

It first uses LEAD to get next temperature reading, them gets the time difference in hours and finally calculates a weighted average. Of course, you will need to adjust for precision for the above.

SQLFiddle Demo


问:
Android: How do I work with IntArrays in Parcelable?
In my app I have a class CurrentGame, which I set up according to the example in this question: Android Class Parcelable with ArrayList

However, I don't know how to add the intArray scoresRnd to the Parcel Constructor.

When I add this line, for example, it gets underlined in red:

```<code>this.scoresRnd = parcel.readArray(null);
</code>```

...and I get this error message "Incompatible types. Required: Int[]. Found: java.lang.Object[]". Can you please help me? Thanks!
(Also, please point out any other mistakes in my code)

```<code>public class CurrentGame implements Parcelable{
    private int rnd;
    private int[] scoresRnd;
    private ArrayList<int[]> scoreList;

    public CurrentGame(){
        super();
        this.rnd = 0;
        this.scoresRnd = new int[]{0,0,0,0};
        this.scoreList = new ArrayList<>();
    }

    public CurrentGame (Parcel parcel){
        this.scoreList = parcel.readArrayList(null);
        this.rnd = parcel.readInt();
        //WHAT DO I PUT HERE FOR THE INTARRAY???

    }

    @Override
    public int describeContents() {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public void writeToParcel(Parcel parcel, int i) {
        // TODO Auto-generated method stub
        parcel.writeList(this.scoreList);
        parcel.writeInt(this.rnd);
    }

    public static final Creator<CurrentGame> CREATOR = new Creator<CurrentGame>() {

        @Override
        public CurrentGame createFromParcel(Parcel parcel) {
            // TODO Auto-generated method stub
            return new CurrentGame(parcel);
        }

        @Override
        public CurrentGame[] newArray(int i) {
            // TODO Auto-generated method stub
            return new CurrentGame[i];
        }
    };

    public void expandList(int[] scoresRnd){
        scoreList.add(scoresRnd);
    }

    public void setRound(int rnd){
        this.rnd=rnd;
    }

    public int getRound(){
        return rnd;
    }

    public ArrayList<int[]> getScoreList(){
        return scoreList;
    }
}
</code>```

答:
Try this </p>

```<code>@Override
public int describeContents() {
    return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeInt(this.rnd);
    dest.writeIntArray(this.scoresRnd);
    dest.writeList(this.scoreList);
}

public s() {
}

protected s(Parcel in) {
    this.rnd = in.readInt();
    this.scoresRnd = in.createIntArray();
    this.scoreList = new ArrayList<int[]>();
    in.readList(this.scoreList, int[].class.getClassLoader());
}

public static final Parcelable.Creator<s> CREATOR = new Parcelable.Creator<s>() {
    @Override
    public s createFromParcel(Parcel source) {
        return new s(source);
    }

    @Override
    public s[] newArray(int size) {
        return new s[size];
    }
};
</code>```

Body:
In my app I have a class CurrentGame, which I set up according to the example in this question: Android Class Parcelable with ArrayList

However, I don't know how to add the intArray scoresRnd to the Parcel Constructor.

When I add this line, for example, it gets underlined in red:

this.scoresRnd = parcel.readArray(null);

...and I get this error message "Incompatible types. Required: Int[]. Found: java.lang.Object[]". Can you please help me? Thanks!
(Also, please point out any other mistakes in my code)

public class CurrentGame implements Parcelable{
    private int rnd;
    private int[] scoresRnd;
    private ArrayList<int[]> scoreList;

    public CurrentGame(){
        super();
        this.rnd = 0;
        this.scoresRnd = new int[]{0,0,0,0};
        this.scoreList = new ArrayList<>();
    }

    public CurrentGame (Parcel parcel){
        this.scoreList = parcel.readArrayList(null);
        this.rnd = parcel.readInt();
        //WHAT DO I PUT HERE FOR THE INTARRAY???

    }

    @Override
    public int describeContents() {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public void writeToParcel(Parcel parcel, int i) {
        // TODO Auto-generated method stub
        parcel.writeList(this.scoreList);
        parcel.writeInt(this.rnd);
    }

    public static final Creator<CurrentGame> CREATOR = new Creator<CurrentGame>() {

        @Override
        public CurrentGame createFromParcel(Parcel parcel) {
            // TODO Auto-generated method stub
            return new CurrentGame(parcel);
        }

        @Override
        public CurrentGame[] newArray(int i) {
            // TODO Auto-generated method stub
            return new CurrentGame[i];
        }
    };

    public void expandList(int[] scoresRnd){
        scoreList.add(scoresRnd);
    }

    public void setRound(int rnd){
        this.rnd=rnd;
    }

    public int getRound(){
        return rnd;
    }

    public ArrayList<int[]> getScoreList(){
        return scoreList;
    }
}

Body:
Try this

@Override
public int describeContents() {
    return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeInt(this.rnd);
    dest.writeIntArray(this.scoresRnd);
    dest.writeList(this.scoreList);
}

public s() {
}

protected s(Parcel in) {
    this.rnd = in.readInt();
    this.scoresRnd = in.createIntArray();
    this.scoreList = new ArrayList<int[]>();
    in.readList(this.scoreList, int[].class.getClassLoader());
}

public static final Parcelable.Creator<s> CREATOR = new Parcelable.Creator<s>() {
    @Override
    public s createFromParcel(Parcel source) {
        return new s(source);
    }

    @Override
    public s[] newArray(int size) {
        return new s[size];
    }
};


问:
How to enable netbeans intellisense/autocomplete for protractor?
I'm creating html5 project using netbeans IDE, and set-up all related testing configuration for protractor.

when i create new test file (.js), and type something like element or element(by.), netbeans tooltips "No Sugestion"

how to enable netbeans intelisense/autocomplete for protractor?
according to netbeans wiki, protractor supported since 8.1 http://wiki.netbeans.org/NewAndNoteworthyNB81#Protractor

I use netbeans 8.2

答: Instead of netbeans, you can use webstorm, which have rich support for .js, .ts and protractor itself...</p>

ContentLicense: CC BY-SA 4.0


问:
Django query case-insensitive list match
I have a list of names that I want to match case insensitive, is there a way to do it without using a loop like below?</p>

```<code>a = ['name1', 'name2', 'name3']
result = any([Name.objects.filter(name__iexact=name) for name in a])
</code>```

答:
Another way to this using django query functions  and annotation</p>

```<code>from django.db.models.functions import Lower
Record.objects.annotate(name_lower=Lower('name')).filter(name_lower__in=['two', 'one']
</code>```

Body:
I have a list of names that I want to match case insensitive, is there a way to do it without using a loop like below?

a = ['name1', 'name2', 'name3']
result = any([Name.objects.filter(name__iexact=name) for name in a])

Body:
Another way to this using django query functions  and annotation

from django.db.models.functions import Lower
Record.objects.annotate(name_lower=Lower('name')).filter(name_lower__in=['two', 'one']


问:
Assign font with using
What is the difference between these two lines of code with Fonts?

```<code>lblName.Font = new Font("Arial", 12f);
</code>```

and

```<code>using(Font font = new Font("Arial", 12f))
    lblName.Font = font;
</code>```

which one is better keeping memory more empty? which one is faster ? etc

答:
```<code>lblName.Font = new Font("Arial", 12f);
</code>```

This will create a new font and makes the label use that font. If you have multiple labels, you may want to create only one font and set all the labels to the one font, but other than that, this is as good as it gets.

```<code>using(Font font = new Font("Arial", 12f))
    lblName.Font = font;
</code>```

This is creating a font and making the label use it. And then, as the usingblock ends, .Dispose() will be called on the font, making it release all it's unmanaged resources (like I guess an HFONT windows handle). So you label hasn't been painted on screen yet, but it has an invalid font object to do so and will probably show nothing or throw exceptions or revert back to a known good standard.

So long story short: the second one is wrong. Don't use resources after you have disposed them.

Title: Assign font with using

Body:
What is the difference between these two lines of code with Fonts?

lblName.Font = new Font("Arial", 12f);

and

using(Font font = new Font("Arial", 12f))
    lblName.Font = font;

which one is better keeping memory more empty? which one is faster ? etc

Body:
lblName.Font = new Font("Arial", 12f);

This will create a new font and makes the label use that font. If you have multiple labels, you may want to create only one font and set all the labels to the one font, but other than that, this is as good as it gets.

using(Font font = new Font("Arial", 12f))
    lblName.Font = font;

This is creating a font and making the label use it. And then, as the usingblock ends, .Dispose() will be called on the font, making it release all it's unmanaged resources (like I guess an HFONT windows handle). So you label hasn't been painted on screen yet, but it has an invalid font object to do so and will probably show nothing or throw exceptions or revert back to a known good standard.

So long story short: the second one is wrong. Don't use resources after you have disposed them.


问:
android alert dialog not showing
I am trying to show an alert inside of an onTouchListener but I can't get it to show. I am pretty new at this but I have been following some good tutorials to no avail.
This is part of the code...any ideas why this alert won't show?

```<code>mSwitcher.setOnTouchListener(new OnTouchListener()
{
   public void onItemClick(AdapterView<?> parent, View v, int position, long id)
   {
   }

   @Override public boolean onTouch(View v, MotionEvent event)
   {
      // the attempt at the alert
      AlertDialog.Builder builder = new AlertDialog.Builder(this);
      builder.setMessage("Are you sure you want to exit?")
             .setCancelable(false)
             .setPositiveButton("Yes", new DialogInterface.OnClickListener()
                {
                   public void onClick(DialogInterface dialog, int id)
                   {
                      MyActivity.this.finish();
                   }
                })
             .setNegativeButton("No", new DialogInterface.OnClickListener()
                {
                   public void onClick(DialogInterface dialog, int id)
                   {
                      dialog.cancel();
                   }
                });
      AlertDialog alert = builder.create();
      return false;
   }
});
</code>```

I think my structure is ok, but I can't even compile.

答:
Try changing

```<code>AlertDialog alert = builder.create();
</code>```

to

```<code>AlertDialog alert = builder.show();
</code>```

Title: android alert dialog not showing

Body:
I am trying to show an alert inside of an onTouchListener but I can't get it to show. I am pretty new at this but I have been following some good tutorials to no avail.
This is part of the code...any ideas why this alert won't show?

mSwitcher.setOnTouchListener(new OnTouchListener()
{
   public void onItemClick(AdapterView<?> parent, View v, int position, long id)
   {
   }

   @Override public boolean onTouch(View v, MotionEvent event)
   {
      // the attempt at the alert
      AlertDialog.Builder builder = new AlertDialog.Builder(this);
      builder.setMessage("Are you sure you want to exit?")
             .setCancelable(false)
             .setPositiveButton("Yes", new DialogInterface.OnClickListener()
                {
                   public void onClick(DialogInterface dialog, int id)
                   {
                      MyActivity.this.finish();
                   }
                })
             .setNegativeButton("No", new DialogInterface.OnClickListener()
                {
                   public void onClick(DialogInterface dialog, int id)
                   {
                      dialog.cancel();
                   }
                });
      AlertDialog alert = builder.create();
      return false;
   }
});

I think my structure is ok, but I can't even compile.

Body:
Try changing

AlertDialog alert = builder.create();

to

AlertDialog alert = builder.show();


问:
two shared_ptr from same enable_shared_from_this instance
Given this class which is enable_shared_from_this:

```<code>class connection : public std::enable_shared_from_this<connection>
{
   //...
};
</code>```

Suppose I create two instances of std::shared_ptr from the same connection* as follows:

```<code>std::shared_ptr<connection> rc(new connection);

std::shared_ptr<connection> fc(rc.get(), [](connection const * c) {
                                   std::cout << "fake delete" << std::endl;
                               });
</code>```

So far its good, as  the resource { connection* } is owned by a single shared_ptr — rc to be precise, and fc just have a fake deleter.

After that, I do this:

```<code>auto sc = fc->shared_from_this();
//OR auto sc = rc->shared_from_this(); //does not make any difference!
</code>```

Now which shared_ptr — rc or fc — would sc  share its reference-count with? In other words,

```<code>std::cout << rc->use_count() << std::endl;
std::cout << fc->use_count() << std::endl;
</code>```

What should these print? I tested this code and found rc seems to have 2 references while fc just 1.

My question is, why is that? and what should be the correct behavior and its rationale?

I'm using C++11 and GCC 4.7.3.

答:
On C++11 (and more generally, before C++17)

the only thing we know is that:

[util.smartptr.enab] shared_from_this();:

Requires: enable_shared_from_this shall be an accessible base class of T. *this shall be a subobject of an object t of type T. There shall be at least one shared_ptr instance p that owns &t.

Returns: A shared_ptr object r that shares ownership with p.

Postconditions: r.get() == this.

that if read literally, implies that it's unspecified if fc->shared_from_this() returns a copy of rc or fc (although sane implementations will simply assign to the internal weak_ptr once, hence the behaviour should be the same as in the c++17 case, as you observed).

From C++17 on

the situation is clear: enable_shared_from_this is essentially a weak_ptr that gets assigned by the first shared_ptr constructor (or make_shared factory) that sees it's in an expired state.

Hence, rc sets the weak_ptr, fc doesn't, fc->shared_from_this() returns a copy of rc. fc.get() will return a zombie pointer as soon as all rc copies get destroyed. Your observed behaviour is the right one.

Note that all shared_ptr constructors taking a non null pointer (and at most a deleter and/or an allocator) will own the pointer and manage its lifetime, as if it were constructed anew, the only difference being that only the first one will assign to enable_shared_from_this's weak_ptr, if any.

Body:
Given this class which is enable_shared_from_this:

class connection : public std::enable_shared_from_this<connection>
{
   //...
};

Suppose I create two instances of std::shared_ptr from the same connection* as follows:

std::shared_ptr<connection> rc(new connection);

std::shared_ptr<connection> fc(rc.get(), [](connection const * c) {
                                   std::cout << "fake delete" << std::endl;
                               });

So far its good, as  the resource { connection* } is owned by a single shared_ptr — rc to be precise, and fc just have a fake deleter.

After that, I do this:

auto sc = fc->shared_from_this();
//OR auto sc = rc->shared_from_this(); //does not make any difference!

Now which shared_ptr — rc or fc — would sc  share its reference-count with? In other words,

std::cout << rc->use_count() << std::endl;
std::cout << fc->use_count() << std::endl;

What should these print? I tested this code and found rc seems to have 2 references while fc just 1.

My question is, why is that? and what should be the correct behavior and its rationale?

I'm using C++11 and GCC 4.7.3.


问:
Fixing Xcode 9 issue: "iPhone is busy: Preparing debugger support for iPhone"
I'm looking for more information on the message below. Xcode 9 seems to be hanging for a couple minutes already...

How can I tell Xcode 9 to quickly recognize my previously used device updated to iOS 11?

.Alex’s iPhone is busy: Preparing debugger support for .Alex’s iPhone

Xcode will continue when .Alex’s iPhone is finished.

答:
Restarting Xcode worked for me (quit and start again).

What didn't work for me:

waiting for an hour on one device

waiting for an hour on another device

restarting devices

unpairing/pairing devices


问:
Tkinter GUI for caesar cipher doesn't work as intended
I made a tkinter GUI for the caesar cipher program but it doesn't work properly.
I type my message in the first entry box, enter the key in the second one, then click encrypt/decrypt, and the result shows up in the third entry box. But i never get the correct results.

Also sometimes if i use a key that is higher than 6, or enter multiple words, i get the following error:

```<code>Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\PC\AppData\Local\Programs\Python\Python35-32\lib\tkinter\__init__.py", line 1549, in __call__
return self.func(*args)
File "C:/Users/PC/PycharmProjects/oyun/sezarUIing.py", line 33, in Encrypt
self.translation = self.translation + self.LETTERS[sayı]
IndexError: string index out of range
</code>```

here is the code:

```<code>from tkinter import *

class Sezar(Frame):
    def __init__(self,pencere):
        Frame.__init__(self,pencere)
        self.pencere = pencere

        self.Lab1 = Label(pencere, text="Enter your message: ",relief= GROOVE, width=20).place(x=20,y=30)

        self.Lab2 = Label(pencere, text="Enter key: ", relief=GROOVE, width=20).place(x=20, y=90)

        self.Ent1 = Entry(pencere,width=30)
        self.Ent1.place(x=170,y=30)

        self.Ent2 = Entry(pencere,width=30)
        self.Ent2.place(x=170,y=90)

        self.But1 = Button(pencere, text="Encrypt", relief=GROOVE,font="bold",command= self.Encrypt).place(x=50,y=150)
        self.But1 = Button(pencere, text="Decrypt", relief=GROOVE, font="bold",command= self.Decrypt).place(x=110, y=150)

        self.RESULT = Entry(pencere, width=30)
        self.RESULT.place(x=170,y=200)

        self.LETTERS = "abcdefghijklmnopqrstuvwxyz"
        self.translation = ""

    def Encrypt(self):
        for num in self.Ent1.get():
            if num in self.LETTERS:
                sayı = self.LETTERS.find(num)
                sayı = sayı + int(self.Ent2.get())
                self.translation = self.translation + self.LETTERS[sayı]
                self.RESULT.insert(0,self.translation)
            else:
                self.translation = self.translation + num

    def Decrypt(self):
        for num in self.Ent1.get():
            if num in self.LETTERS:
                sayı = self.LETTERS.find(num)
                sayı = sayı - int(self.Ent2.get())
                if sayı >= 0:
                    sayı = sayı - len(self.LETTERS)
                elif sayı <= 0:
                    sayı = sayı + len(self.LETTERS)
                self.translation = self.translation + self.LETTERS[sayı]
                self.RESULT.insert(0,self.translation)
            else:
                self.translation = self.translation + num

if __name__ == "__main__":
    root = Tk()
    root.title("Sezar")
    root.geometry("400x300+50+50")
    Sezar(root).pack(side="top",fill = "both")
    root.mainloop()
</code>```

He is an example of the error and what is expected

Example of the error:
Error

Intended result: Expected

答:
Your error message was due to you not using modular arithmetic in your Encrypt() method (you had implemented such in your Decrypt() method.)

Other problems include not clearing self.RESULT before adding new text; not clearing self.translation before appending the results from a new translation; not controlling letter case; not updating self.RESULT at an appropriate place in your code (if text ends in a number, it's not reflected in the translation).

Below's my rework of your code addressing the above issues:

```<code>from tkinter import *

class Sezar(Frame):
    LETTERS = "abcdefghijklmnopqrstuvwxyz"

    def __init__(self, pencere):
        Frame.__init__(self, pencere)
        self.pencere = pencere

        Label(pencere, text="Enter your message: ", relief=GROOVE, width=20).place(x=20, y=30)
        self.Ent1 = Entry(pencere, width=30)
        self.Ent1.place(x=170, y=30)

        Label(pencere, text="Enter key: ", relief=GROOVE, width=20).place(x=20, y=90)
        self.Ent2 = Entry(pencere, width=30)
        self.Ent2.place(x=170, y=90)

        Button(pencere, text="Encrypt", relief=GROOVE, font="bold", command=self.Encrypt).place(x=50, y=150)
        Button(pencere, text="Decrypt", relief=GROOVE, font="bold", command=self.Decrypt).place(x=110, y=150)

        self.RESULT = Entry(pencere, width=30)
        self.RESULT.place(x=170, y=200)

    def Encrypt(self):
        key = int(self.Ent2.get())
        length = len(self.LETTERS)

        translation = ''

        for character in self.Ent1.get():
            if character.lower() in self.LETTERS:
                sayı = self.LETTERS.find(character.lower())
                sayı = (sayı + key) % length
                translation += self.LETTERS[sayı]
            else:
                translation += character

        self.RESULT.delete(0, END)
        self.RESULT.insert(0, translation)

    def Decrypt(self):
        key = int(self.Ent2.get())
        length = len(self.LETTERS)

        translation = ''

        for character in self.Ent1.get():
            if character.lower() in self.LETTERS:
                sayı = self.LETTERS.find(character.lower())
                sayı = (sayı - key) % length
                translation += self.LETTERS[sayı]
            else:
                translation += character

        self.RESULT.delete(0, END)
        self.RESULT.insert(0, translation)

if __name__ == "__main__":
    root = Tk()
    root.title("Sezar")
    root.geometry("400x300+50+50")
    Sezar(root).pack(side="top", fill="both")
    root.mainloop()
</code>```

Body:
I made a tkinter GUI for the caesar cipher program but it doesn't work properly.
I type my message in the first entry box, enter the key in the second one, then click encrypt/decrypt, and the result shows up in the third entry box. But i never get the correct results.

Also sometimes if i use a key that is higher than 6, or enter multiple words, i get the following error:

Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\PC\AppData\Local\Programs\Python\Python35-32\lib\tkinter\__init__.py", line 1549, in __call__
return self.func(*args)
File "C:/Users/PC/PycharmProjects/oyun/sezarUIing.py", line 33, in Encrypt
self.translation = self.translation + self.LETTERS[sayı]
IndexError: string index out of range

here is the code:

from tkinter import *

class Sezar(Frame):
    def __init__(self,pencere):
        Frame.__init__(self,pencere)
        self.pencere = pencere

        self.Lab1 = Label(pencere, text="Enter your message: ",relief= GROOVE, width=20).place(x=20,y=30)

        self.Lab2 = Label(pencere, text="Enter key: ", relief=GROOVE, width=20).place(x=20, y=90)

        self.Ent1 = Entry(pencere,width=30)
        self.Ent1.place(x=170,y=30)

        self.Ent2 = Entry(pencere,width=30)
        self.Ent2.place(x=170,y=90)

        self.But1 = Button(pencere, text="Encrypt", relief=GROOVE,font="bold",command= self.Encrypt).place(x=50,y=150)
        self.But1 = Button(pencere, text="Decrypt", relief=GROOVE, font="bold",command= self.Decrypt).place(x=110, y=150)

        self.RESULT = Entry(pencere, width=30)
        self.RESULT.place(x=170,y=200)

        self.LETTERS = "abcdefghijklmnopqrstuvwxyz"
        self.translation = ""

    def Encrypt(self):
        for num in self.Ent1.get():
            if num in self.LETTERS:
                sayı = self.LETTERS.find(num)
                sayı = sayı + int(self.Ent2.get())
                self.translation = self.translation + self.LETTERS[sayı]
                self.RESULT.insert(0,self.translation)
            else:
                self.translation = self.translation + num

    def Decrypt(self):
        for num in self.Ent1.get():
            if num in self.LETTERS:
                sayı = self.LETTERS.find(num)
                sayı = sayı - int(self.Ent2.get())
                if sayı >= 0:
                    sayı = sayı - len(self.LETTERS)
                elif sayı <= 0:
                    sayı = sayı + len(self.LETTERS)
                self.translation = self.translation + self.LETTERS[sayı]
                self.RESULT.insert(0,self.translation)
            else:
                self.translation = self.translation + num

if __name__ == "__main__":
    root = Tk()
    root.title("Sezar")
    root.geometry("400x300+50+50")
    Sezar(root).pack(side="top",fill = "both")
    root.mainloop()

He is an example of the error and what is expected

Example of the error:
Error

Intended result: Expected

Body:
Your error message was due to you not using modular arithmetic in your Encrypt() method (you had implemented such in your Decrypt() method.)

Other problems include not clearing self.RESULT before adding new text; not clearing self.translation before appending the results from a new translation; not controlling letter case; not updating self.RESULT at an appropriate place in your code (if text ends in a number, it's not reflected in the translation).

Below's my rework of your code addressing the above issues:

from tkinter import *

class Sezar(Frame):
    LETTERS = "abcdefghijklmnopqrstuvwxyz"

    def __init__(self, pencere):
        Frame.__init__(self, pencere)
        self.pencere = pencere

        Label(pencere, text="Enter your message: ", relief=GROOVE, width=20).place(x=20, y=30)
        self.Ent1 = Entry(pencere, width=30)
        self.Ent1.place(x=170, y=30)

        Label(pencere, text="Enter key: ", relief=GROOVE, width=20).place(x=20, y=90)
        self.Ent2 = Entry(pencere, width=30)
        self.Ent2.place(x=170, y=90)

        Button(pencere, text="Encrypt", relief=GROOVE, font="bold", command=self.Encrypt).place(x=50, y=150)
        Button(pencere, text="Decrypt", relief=GROOVE, font="bold", command=self.Decrypt).place(x=110, y=150)

        self.RESULT = Entry(pencere, width=30)
        self.RESULT.place(x=170, y=200)

    def Encrypt(self):
        key = int(self.Ent2.get())
        length = len(self.LETTERS)

        translation = ''

        for character in self.Ent1.get():
            if character.lower() in self.LETTERS:
                sayı = self.LETTERS.find(character.lower())
                sayı = (sayı + key) % length
                translation += self.LETTERS[sayı]
            else:
                translation += character

        self.RESULT.delete(0, END)
        self.RESULT.insert(0, translation)

    def Decrypt(self):
        key = int(self.Ent2.get())
        length = len(self.LETTERS)

        translation = ''

        for character in self.Ent1.get():
            if character.lower() in self.LETTERS:
                sayı = self.LETTERS.find(character.lower())
                sayı = (sayı - key) % length
                translation += self.LETTERS[sayı]
            else:
                translation += character

        self.RESULT.delete(0, END)
        self.RESULT.insert(0, translation)

if __name__ == "__main__":
    root = Tk()
    root.title("Sezar")
    root.geometry("400x300+50+50")
    Sezar(root).pack(side="top", fill="both")
    root.mainloop()


问:
employee daily sales submission form with respect to ID
After login, an employee has to update his daily product sales. For the purpose I have made 02 tables named registration and dailysales. Table registration verifies the userID and password for login of user and has link to enter daily sales in 'dailysales' table. How can I insert the userID of logged-in user from table 'registration' to table 'dailysales' automatically. Note: In Table 'dailysales' employee also has to put daily sales of products from html form. In below coding how can i add userID and user Name of logged-in user automatically alongwith entry of products.

coding for dailysales is as under:-

```<code><?php
require('config.php');

//Start the Session
session_start();

if((isset($_POST['diaper']) && !empty($_POST['diaper']))
&& (isset($_POST['babylotion']) && !empty($_POST['babylotion']))
&& (isset($_POST['nfacewash']) && !empty($_POST['nfacewash']))
&& (isset($_POST['facewash']) && !empty($_POST['facewash']))
&& (isset($_POST['hremover']) && !empty($_POST['hremover']))){
$Diaper = $_POST ['diaper'];
$BabyLotion = $_POST ['babylotion'];
$Neem_fw = $_POST ['nfacewash'];
$Facewash = $_POST ['facewash'];
$Hair_remover = $_POST ['hremover'];
}
$sql= "INSERT INTO dailyrecord (babydiaper,babylotion,hairremover,neemfw,neetfw) VALUES ('$Diaper','$BabyLotion','$Neem_fw','$Facewash','$Hair_remover')";

if (mysqli_query ($connection, $sql)){
    echo '<script>alert("Congratulations! You Have Successfully added your sale!");</script>';
    }
else{
        echo '<script>alert("Sorry! Please fill the fields marked with *!");</script>';

    }

?>
</code>```

Coding for login is as under:-

```<code><?php

//Start the Session
session_start();
require('config.php');

// If the form is submitted or not.
// If the form is submitted
if (isset($_POST['id']) and isset($_POST['password'])){
// Assigning posted values to variables.
$E_id = $_POST['id'];
$P_word = $_POST['password'];

// Check if username is empty
    if(empty(trim($_POST["id"]))){
        $username_err = 'Please enter username.';
    } else{
        $U_name = trim($_POST["id"]);
    }

    // Check if password is empty
    if(empty(trim($_POST['password']))){
        $password_err = 'Please enter your password.';
    } else{
        $P_word = trim($_POST['password']);
    }

// Checking the values are existing in the database or not
$query = "SELECT * FROM registeration WHERE employee_id='$E_id' and password='$P_word'";

$result = mysqli_query($connection, $query);
$count = mysqli_num_rows($result);
// If the posted values are equal to the database values, then session will be created for the user.
if ($count == 1){
$_SESSION['id'] = $E_id;
}else{
//If the login credentials doesn't match, he will be shown with an error message.
$fmsg = "Invalid Login Credentials.";
}
}
//if the user is logged in Greets the user with message
if (isset($_SESSION['id'])){
$E_id = $_SESSION['id'];
echo "<center><table border='2' style='background-color:#FFFFFF;border-collapse:collapse;border:2px solid #6699FF;color:#000000;width:60%'>
<tr>
<th>Distributor</th>
<th>Designation</th>
<th>City</th>
<th>Visiting Area</th>
</tr>";

while($row = mysqli_fetch_array($result))
{
echo "<tr\t\t\t>";
echo "<td>" . $row['emp_name'] . "&nbsp". $row['f_name'] . "</td>";
echo "<td>" . $row['designation'] . "</td>";
echo "<td>" . $row['city'] . "</td>";
echo "<td>" . $row['varea'] . "</td>";
echo "</tr>";
}
echo "</center></table>";
echo "<br>";
echo "<a href='logout.php'>Logout</a>";
}
else{

echo '<center>Invalied Username or Password</center>';
}
?>
</code>```

答:
In your daily sales code, you can use the $_SESSION['id'] to get the id

```<code>$id=$_SESSION['id'];
</code>```

So you can use it in your $sql. You need to create a column id in your dailyrecord table with foreign key to your registeration table (so both id's are equal)

```<code>$sql= "INSERT INTO dailyrecord (id,babydiaper,babylotion,hairremover,neemfw,neetfw) VALUES ($id,'$Diaper','$BabyLotion','$Neem_fw','$Facewash','$Hair_remover')";
</code>```

Anyways, you should use prepared statements to avoid sql injection for your $sql

Body:
After login, an employee has to update his daily product sales. For the purpose I have made 02 tables named registration and dailysales. Table registration verifies the userID and password for login of user and has link to enter daily sales in 'dailysales' table. How can I insert the userID of logged-in user from table 'registration' to table 'dailysales' automatically. Note: In Table 'dailysales' employee also has to put daily sales of products from html form. In below coding how can i add userID and user Name of logged-in user automatically alongwith entry of products.

coding for dailysales is as under:-

<?php
require('config.php');

//Start the Session
session_start();

if((isset($_POST['diaper']) && !empty($_POST['diaper']))
&& (isset($_POST['babylotion']) && !empty($_POST['babylotion']))
&& (isset($_POST['nfacewash']) && !empty($_POST['nfacewash']))
&& (isset($_POST['facewash']) && !empty($_POST['facewash']))
&& (isset($_POST['hremover']) && !empty($_POST['hremover']))){
$Diaper = $_POST ['diaper'];
$BabyLotion = $_POST ['babylotion'];
$Neem_fw = $_POST ['nfacewash'];
$Facewash = $_POST ['facewash'];
$Hair_remover = $_POST ['hremover'];
}
$sql= "INSERT INTO dailyrecord (babydiaper,babylotion,hairremover,neemfw,neetfw) VALUES ('$Diaper','$BabyLotion','$Neem_fw','$Facewash','$Hair_remover')";

if (mysqli_query ($connection, $sql)){
    echo '';
    }
else{
        echo '';

    }

?>

Coding for login is as under:-

<?php

//Start the Session
session_start();
require('config.php');

// If the form is submitted or not.
// If the form is submitted
if (isset($_POST['id']) and isset($_POST['password'])){
// Assigning posted values to variables.
$E_id = $_POST['id'];
$P_word = $_POST['password'];

// Check if username is empty
    if(empty(trim($_POST["id"]))){
        $username_err = 'Please enter username.';
    } else{
        $U_name = trim($_POST["id"]);
    }

    // Check if password is empty
    if(empty(trim($_POST['password']))){
        $password_err = 'Please enter your password.';
    } else{
        $P_word = trim($_POST['password']);
    }

// Checking the values are existing in the database or not
$query = "SELECT * FROM registeration WHERE employee_id='$E_id' and password='$P_word'";

$result = mysqli_query($connection, $query);
$count = mysqli_num_rows($result);
// If the posted values are equal to the database values, then session will be created for the user.
if ($count == 1){
$_SESSION['id'] = $E_id;
}else{
//If the login credentials doesn't match, he will be shown with an error message.
$fmsg = "Invalid Login Credentials.";
}
}
//if the user is logged in Greets the user with message
if (isset($_SESSION['id'])){
$E_id = $_SESSION['id'];
echo "

Distributor
Designation
City
Visiting Area

";

while($row = mysqli_fetch_array($result))
{
echo "
";
echo "" . $row['emp_name'] . "&nbsp". $row['f_name'] . "	";
echo "" . $row['designation'] . "	";
echo "" . $row['city'] . "	";
echo "" . $row['varea'] . "	";
echo "
";
}
echo "
";
echo "
";
echo "Logout";
}
else{

echo 'Invalied Username or Password';
}
?>

Body:
In your daily sales code, you can use the $_SESSION['id'] to get the id

$id=$_SESSION['id'];

So you can use it in your $sql. You need to create a column id in your dailyrecord table with foreign key to your registeration table (so both id's are equal)

$sql= "INSERT INTO dailyrecord (id,babydiaper,babylotion,hairremover,neemfw,neetfw) VALUES ($id,'$Diaper','$BabyLotion','$Neem_fw','$Facewash','$Hair_remover')";

Anyways, you should use prepared statements to avoid sql injection for your $sql


问:
jQuery show hide parent item on click by class
I am having trouble to toggle (show/hide) div based on button clicked to the list item.

When I tried, it affects to all divs at once. Here is my code. I want toggole per item bases.

```<code><div class="list-item">
    <div class="list-content">
        <div class="list-updates">
            <a href="#" class="list-avatar"><img
                        src="images/avatar/avatar_<?php echo ( $i <= 8 ? '0' : NULL ) . $avatars[ $i ] ?>.jpg"
                        alt="user-avatar" width="40"
                        height="40"></a>
            <a href="#"><i class="material-icons"><?php echo get_icon( $update[ $i ] ) ?></i></a>
        </div>
        <div class="item-title"><a href="#"><?php echo $questions[ $i ] ?></a>
        </div>
        <div class="ans-box">
            <div class="ans-count"><?php echo $ans[ $i ] ?></div>
            <span><i class="material-icons meta-info-btn">keyboard_arrow_down</i></span>
        </div>
    </div>

    <div class="metas">
        <div class="update-info"><a href="#">commented</a> 1 hour ago in <a href="#">Plugins</a> by
            <a href="#">gurjyot</a>
        </div>
        <div class="counters">
            <span class="votes"><i class="material-icons">arrow_upward</i> +1245</span>
            <span class="views"><i class="material-icons">remove_red_eye</i> 50.2k</span>
        </div>
    </div>
</div><!-- list-item -->

$('.list-content .meta-info-btn').click(function () {
    alert('Clicked and found!');
    $(this).closest('.metas').slideToggle();
});
</code>```

答:
Try this

$('.list-content .meta-info-btn').click(function () {
    var id = $(this).parent().attr('class');
    alert(id);
    $('#'+id).slideToggle();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="list-item">
    <div class="list-content">
        <div class="list-updates">
            <img
                        src="images/avatar/avatar_<?php echo ( $i <= 8 ? '0' : NULL ) . $avatars[ $i ] ?>.jpg"
                        alt="user-avatar" width="40"
                        height="40">
            <i class="material-icons"><?php echo get_icon( $update[ $i ] ) ?></i>
        </div>
        <div class="item-title"><?php echo $questions[ $i ] ?>
        </div>
        <div class="ans-box">
            <div class="ans-count"><?php echo $ans[ $i ] ?></div>
            <span class="item-1"><i class="material-icons meta-info-btn">keyboard_arrow_down</i></span>
        </div>
    </div>

    <div class="metas" id="item-1">
        <div class="update-info">commented 1 hour ago in Plugins by
            gurjyot
        </div>
        <div class="counters">
            <span class="votes"><i class="material-icons">arrow_upward</i> +1245</span>
            <span class="views"><i class="material-icons">remove_red_eye</i> 50.2k</span>
        </div>
    </div>
</div><!-- list-item --></code>```

Body:
I am having trouble to toggle (show/hide) div based on button clicked to the list item.

When I tried, it affects to all divs at once. Here is my code. I want toggole per item bases.

            <img
                        src="images/avatar/avatar_<?php echo ( $i <= 8 ? '0' : NULL ) . $avatars[ $i ] ?>.jpg"
                        alt="user-avatar" width="40"
                        height="40">
            <?php echo get_icon( $update[ $i ] ) ?>

<?php echo $questions[ $i ] ?>

<?php echo $ans[ $i ] ?>

            keyboard_arrow_down

commented 1 hour ago in Plugins by
            gurjyot

            arrow_upward +1245
            remove_red_eye 50.2k

$('.list-content .meta-info-btn').click(function () {
    alert('Clicked and found!');
    $(this).closest('.metas').slideToggle();
});

Body:
Try this

$('.list-content .meta-info-btn').click(function () {
    var id = $(this).parent().attr('class');
    alert(id);
    $('#'+id).slideToggle();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="list-item">
    <div class="list-content">
        <div class="list-updates">
            <a href="#" class="list-avatar"><img
                        src="images/avatar/avatar_<?php echo ( $i <= 8 ? '0' : NULL ) . $avatars[ $i ] ?>.jpg"
                        alt="user-avatar" width="40"
                        height="40"></a>
            <a href="#"><i class="material-icons"><?php echo get_icon( $update[ $i ] ) ?></i></a>
        </div>
        <div class="item-title"><a href="#"><?php echo $questions[ $i ] ?></a>
        </div>
        <div class="ans-box">
            <div class="ans-count"><?php echo $ans[ $i ] ?></div>
            <span class="item-1"><i class="material-icons meta-info-btn">keyboard_arrow_down</i></span>
        </div>
    </div>

    <div class="metas" id="item-1">
        <div class="update-info"><a href="#">commented</a> 1 hour ago in <a href="#">Plugins</a> by
            <a href="#">gurjyot</a>
        </div>
        <div class="counters">
            <span class="votes"><i class="material-icons">arrow_upward</i> +1245</span>
            <span class="views"><i class="material-icons">remove_red_eye</i> 50.2k</span>
        </div>
    </div>
</div><!-- list-item -->


问:
I want to use bool on button, if i click on button image of imageview changed and if again click on button then image reverse using Swift
my code is:
func PickUpCarCost() {

```<code>        imgCheck.image = UIImage(named: "uncheck.png")
        imgUnCheck.image = UIImage(named: "uncheck.png")
        if CarPickUpButton?.tag == 1 {
            imgCheck.image = UIImage(named: "check.png")
           self.pickupChargelabel.text=self.PickUpFare.text!
        }
        else {
            imgUnCheck.image = UIImage(named: "uncheck.png")

        }

}
</code>```

in this i wants take bool like if button selectes image view image will be check.png if unselect image view image will be uncheck.png how to code for this in swift.

答:
You can you isSelected variable. And add different image for button state.</p>

```<code>imgCheck.setImage(UIImage(named: "uncheck.png"), for: .selected)
imgCheck.setImage(UIImage(named: "check.png"), for: .normal)
</code>```

Body:
my code is:
func PickUpCarCost() {

        imgCheck.image = UIImage(named: "uncheck.png")
        imgUnCheck.image = UIImage(named: "uncheck.png")
        if CarPickUpButton?.tag == 1 {
            imgCheck.image = UIImage(named: "check.png")
           self.pickupChargelabel.text=self.PickUpFare.text!
        }
        else {
            imgUnCheck.image = UIImage(named: "uncheck.png")

        }

}

in this i wants take bool like if button selectes image view image will be check.png if unselect image view image will be uncheck.png how to code for this in swift.

Body:
You can you isSelected variable. And add different image for button state.

imgCheck.setImage(UIImage(named: "uncheck.png"), for: .selected)
imgCheck.setImage(UIImage(named: "check.png"), for: .normal)


问:
How to play html5 video play m3U8 on mobile and desktop?
I have HLS m3u8 that plays well on IOS and Android with html5 <video>

But does not play on desktop PC or desktop MAC (Chrome, Firefox)

How to play m3u8 on desktop PCs ?

Is there a streaming format of video that would play both on desktop and mobile ?

答:
take a look on hls.js project at https://github.com/video-dev/hls.js/
it solves exactly this problem.

here's a small sample on how to use it.

```<code><script src="https://cdn.jsdelivr.net/npm/hls.js@latest"></script>
<video id="video"></video>
<script>
  if(Hls.isSupported()) {
    var video = document.getElementById('video');
    var hls = new Hls();
    hls.loadSource('https://video-dev.github.io/streams/x36xhzz/x36xhzz.m3u8');
    hls.attachMedia(video);
    hls.on(Hls.Events.MANIFEST_PARSED,function() {
      video.play();
  });
 }
</script>
</code>```

once the manifest is parsed, you can use all the regular events, properties and method of the original html5 video element.

you may find their demo here: https://video-dev.github.io/hls.js/demo/

Body:
take a look on hls.js project at https://github.com/video-dev/hls.js/
it solves exactly this problem.

here's a small sample on how to use it.

<script src="https://cdn.jsdelivr.net/npm/hls.js@latest"></script>
<video id="video"></video>
<script>
  if(Hls.isSupported()) {
    var video = document.getElementById('video');
    var hls = new Hls();
    hls.loadSource('https://video-dev.github.io/streams/x36xhzz/x36xhzz.m3u8');
    hls.attachMedia(video);
    hls.on(Hls.Events.MANIFEST_PARSED,function() {
      video.play();
  });
 }
</script>

once the manifest is parsed, you can use all the regular events, properties and method of the original html5 video element.

you may find their demo here: https://video-dev.github.io/hls.js/demo/


问:
In a While loop (php-mysql) can I have it display an entry once that has duplicates?
What I am trying to achieve is for instance I have a 2 companies that have posted 5 products. One company posted 1 product and the second company posted 4 products.

In my while loop it will show the first company that posted one product once and the second company that posted four products 4 times. What I want to do is have it just show the 2 companies that have posted products once. So if there are 5 companies all who have posted multiple products, they will not be multiplied by the amount of products they have posted but just display once as long as they have at least one product posted. Is it possible to achieve that from a query?

```<code><?php
include("database.php");
$id=$_GET['id'];
$query="SELECT * FROM dproducts, thevendor WHERE dproducts.vendor_id=thevendor.thevendor_id AND dproducts.active='1'";
$result=mysql_query($query) or die(mysql_error());
$num_rows = 0;
while($row = mysql_fetch_assoc($result))
{
$num_rows++;
?>
<br><?php echo $row['company_name']; ?><br>
<?php } ?>
</code>```

答:
You can use

SELECT DISTINCT(vendor_id) FROM ...

Or you could use GROUP BY

Body:
What I am trying to achieve is for instance I have a 2 companies that have posted 5 products. One company posted 1 product and the second company posted 4 products.

In my while loop it will show the first company that posted one product once and the second company that posted four products 4 times. What I want to do is have it just show the 2 companies that have posted products once. So if there are 5 companies all who have posted multiple products, they will not be multiplied by the amount of products they have posted but just display once as long as they have at least one product posted. Is it possible to achieve that from a query?

<?php
include("database.php");
$id=$_GET['id'];
$query="SELECT * FROM dproducts, thevendor WHERE dproducts.vendor_id=thevendor.thevendor_id AND dproducts.active='1'";
$result=mysql_query($query) or die(mysql_error());
$num_rows = 0;
while($row = mysql_fetch_assoc($result))
{
$num_rows++;
?>

<?php echo $row['company_name']; ?>

<?php } ?>


答: I think something on this page will help you. There's a couple formatting jQuery plugins toward the bottom. Good luck!</p>

Title: how to format time with jquery/javascript

Body:
I have a JSON feed that drupal spits out time in this format:   2010-12-16T04:41:35Z

How do I go about formating it to X minutes/hours ago?