问:
Weird ClassCastException while deploying WAR to WildFly 11
I am facing a weird issue: when I deploy my WAR file on WildFly I get the following error:

[2017-11-27 01:15:17,777] Artifact JSFDemo:war: Artifact is being deployed, please wait...
  Connected to server

  [2017-11-27 01:15:18,427] Artifact JSFDemo:war: Error during artifact deployment. See server log for details.

  [2017-11-27 01:15:18,428] Artifact JSFDemo:war: java.lang.Exception: {"WFLYCTL0080: Failed services" => {"jboss.persistenceunit.\"JSFDemo.war#demo_unit\"" => "java.lang.ClassCastException: org.dom4j.DocumentFactory cannot be cast to org.dom4j.DocumentFactory
      Caused by: java.lang.ClassCastException: org.dom4j.DocumentFactory cannot be cast to org.dom4j.DocumentFactory"}}

I believe the problem is related to one of my dependencies. WAR is built on POM file with depedencies inherited from the parent one which is shown below.

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

<groupId>org.abondar.experimental</groupId>
<artifactId>JavaEEDemo</artifactId>
<packaging>pom</packaging>
<version>1.0</version>
<modules>
    <module>BasicCDI</module>
    <module>BeanValidation</module>
    <module>ORMDemo</module>
    <module>EJBDemo</module>
    <module>JSFDemo</module>
    <module>DocumentDemo</module>
</modules>
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.jboss.arquillian</groupId>
            <artifactId>arquillian-bom</artifactId>
            <version>1.1.14.Final</version>
            <scope>import</scope>
            <type>pom</type>
        </dependency>
    </dependencies>
</dependencyManagement>
<dependencies>
    <dependency>
        <groupId>javax</groupId>
        <artifactId>javaee-api</artifactId>
        <version>8.0</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.jboss.weld.se</groupId>
        <artifactId>weld-se-core</artifactId>
        <version>3.0.1.Final</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
    <dependency>
        <groupId>org.apache.derby</groupId>
        <artifactId>derby</artifactId>
        <version>10.14.1.0</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.apache.derby</groupId>
        <artifactId>derbyclient</artifactId>
        <version>10.14.1.0</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.2.12.Final</version>
        <exclusions>
            <exclusion>
                <groupId>dom4j</groupId>
                <artifactId>dom4j</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.hibernate.javax.persistence</groupId>
        <artifactId>hibernate-jpa-2.1-api</artifactId>
        <version>1.0.0.Final</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>5.2.12.Final</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate.validator</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>6.0.5.Final</version>
     </dependency>

    <dependency>
        <groupId>org.glassfish</groupId>
        <artifactId>javax.el</artifactId>
        <version>3.0.0</version>
    </dependency>
    <dependency>
        <groupId>org.jboss.arquillian.junit</groupId>
        <artifactId>arquillian-junit-container</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.jboss.arquillian.protocol</groupId>
        <artifactId>arquillian-protocol-servlet</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.jboss.arquillian.container</groupId>
        <artifactId>arquillian-container-test-api</artifactId>
        <version>1.1.14.Final</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.jboss.arquillian.core/arquillian-core-impl-base -->
    <dependency>
        <groupId>org.jboss.arquillian.core</groupId>
        <artifactId>arquillian-core-impl-base</artifactId>
        <version>1.1.14.Final</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>javax.xml.bind</groupId>
        <artifactId>jaxb-api</artifactId>
        <version>2.3.0</version>
    </dependency>
    <dependency>
        <groupId>com.sun.xml.bind</groupId>
        <artifactId>jaxb-impl</artifactId>
        <version>2.3.0</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jaxb</groupId>
        <artifactId>jaxb-runtime</artifactId>
        <version>2.3.0</version>
    </dependency>
    <dependency>
        <groupId>javax.activation</groupId>
        <artifactId>activation</artifactId>
        <version>1.1.1</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish</groupId>
        <artifactId>javax.json</artifactId>
        <version>1.1.2</version>
    </dependency>
</dependencies>
<build>
    <!--for web related demos-->
    <plugins>
        <plugin>
            <groupId>org.wildfly.plugins</groupId>
            <artifactId>wildfly-maven-plugin</artifactId>
            <version>1.2.1.Final</version>
            <configuration>
                <skip>true</skip>
            </configuration>
        </plugin>
    </plugins>
</build>
</project>
</code>```

That's the child POM file:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>JavaEEDemo</artifactId>
        <groupId>org.abondar.experimental</groupId>
        <version>1.0</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <packaging>war</packaging>
    <artifactId>JSFDemo</artifactId>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.7.0</version>
                <configuration>
                    <jdkToolchain>
                        <version>[1.8,9)</version>
                    </jdkToolchain>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.2.0</version>
                <configuration>
                    <skip>false</skip>
                    <warSourceDirectory>src/main/webapp</warSourceDirectory>
                    <warName>JSFDemo</warName>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.wildfly.plugins</groupId>
                <artifactId>wildfly-maven-plugin</artifactId>
                <version>1.2.1.Final</version>
                <configuration>
                    <hostname>localhost</hostname>
                    <port>9990</port>
                    <username>user</username>
                    <password>password</password>
                    <filename>${project.build.finalName}.war</filename>
                </configuration>
                <executions>
                    <execution>
                        <phase>install</phase>
                        <goals>
                            <goal>deploy</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>
</code>```

I have tried making hibernate-core scope provided and exclude dom4j from it. What is the exact workaround with my POM structure?

答:
The reason you get this error is because you have the class org.dom4j.DocumentFactory loaded from two different classloaders.

Most likely it is provided in WildFly and you packaged it in a JAR in the lib-directory of your WAR file. So look into the WAR and change your POM until it is not included anymore.

To find out why it is included, mvn dependency:tree within your war-module can help.

If you can't figure it out from looking at the WAR-file, set logging of the category org.jboss.modules to TRACE and search the logfile which classloaders load the class org.dom4j.DocumentFactory.

Body:
I am facing a weird issue: when I deploy my WAR file on WildFly I get the following error:

[2017-11-27 01:15:17,777] Artifact JSFDemo:war: Artifact is being deployed, please wait...
  Connected to server

  [2017-11-27 01:15:18,427] Artifact JSFDemo:war: Error during artifact deployment. See server log for details.

  [2017-11-27 01:15:18,428] Artifact JSFDemo:war: java.lang.Exception: {"WFLYCTL0080: Failed services" => {"jboss.persistenceunit.\"JSFDemo.war#demo_unit\"" => "java.lang.ClassCastException: org.dom4j.DocumentFactory cannot be cast to org.dom4j.DocumentFactory
      Caused by: java.lang.ClassCastException: org.dom4j.DocumentFactory cannot be cast to org.dom4j.DocumentFactory"}}

I believe the problem is related to one of my dependencies. WAR is built on POM file with depedencies inherited from the parent one which is shown below.

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

<groupId>org.abondar.experimental</groupId>
<artifactId>JavaEEDemo</artifactId>
<packaging>pom</packaging>
<version>1.0</version>
<modules>
    <module>BasicCDI</module>
    <module>BeanValidation</module>
    <module>ORMDemo</module>
    <module>EJBDemo</module>
    <module>JSFDemo</module>
    <module>DocumentDemo</module>
</modules>
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.jboss.arquillian</groupId>
            <artifactId>arquillian-bom</artifactId>
            <version>1.1.14.Final</version>
            <scope>import</scope>
            <type>pom</type>
        </dependency>
    </dependencies>
</dependencyManagement>
<dependencies>
    <dependency>
        <groupId>javax</groupId>
        <artifactId>javaee-api</artifactId>
        <version>8.0</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.jboss.weld.se</groupId>
        <artifactId>weld-se-core</artifactId>
        <version>3.0.1.Final</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
    <dependency>
        <groupId>org.apache.derby</groupId>
        <artifactId>derby</artifactId>
        <version>10.14.1.0</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.apache.derby</groupId>
        <artifactId>derbyclient</artifactId>
        <version>10.14.1.0</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.2.12.Final</version>
        <exclusions>
            <exclusion>
                <groupId>dom4j</groupId>
                <artifactId>dom4j</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.hibernate.javax.persistence</groupId>
        <artifactId>hibernate-jpa-2.1-api</artifactId>
        <version>1.0.0.Final</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>5.2.12.Final</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate.validator</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>6.0.5.Final</version>
     </dependency>

    <dependency>
        <groupId>org.glassfish</groupId>
        <artifactId>javax.el</artifactId>
        <version>3.0.0</version>
    </dependency>
    <dependency>
        <groupId>org.jboss.arquillian.junit</groupId>
        <artifactId>arquillian-junit-container</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.jboss.arquillian.protocol</groupId>
        <artifactId>arquillian-protocol-servlet</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.jboss.arquillian.container</groupId>
        <artifactId>arquillian-container-test-api</artifactId>
        <version>1.1.14.Final</version>
    </dependency>

    <dependency>
        <groupId>org.jboss.arquillian.core</groupId>
        <artifactId>arquillian-core-impl-base</artifactId>
        <version>1.1.14.Final</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>javax.xml.bind</groupId>
        <artifactId>jaxb-api</artifactId>
        <version>2.3.0</version>
    </dependency>
    <dependency>
        <groupId>com.sun.xml.bind</groupId>
        <artifactId>jaxb-impl</artifactId>
        <version>2.3.0</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jaxb</groupId>
        <artifactId>jaxb-runtime</artifactId>
        <version>2.3.0</version>
    </dependency>
    <dependency>
        <groupId>javax.activation</groupId>
        <artifactId>activation</artifactId>
        <version>1.1.1</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish</groupId>
        <artifactId>javax.json</artifactId>
        <version>1.1.2</version>
    </dependency>
</dependencies>
<build>

    <plugins>
        <plugin>
            <groupId>org.wildfly.plugins</groupId>
            <artifactId>wildfly-maven-plugin</artifactId>
            <version>1.2.1.Final</version>
            <configuration>
                <skip>true</skip>
            </configuration>
        </plugin>
    </plugins>
</build>
</project>

That's the child POM file:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>JavaEEDemo</artifactId>
        <groupId>org.abondar.experimental</groupId>
        <version>1.0</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <packaging>war</packaging>
    <artifactId>JSFDemo</artifactId>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.7.0</version>
                <configuration>
                    <jdkToolchain>
                        <version>[1.8,9)</version>
                    </jdkToolchain>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.2.0</version>
                <configuration>
                    <skip>false</skip>
                    <warSourceDirectory>src/main/webapp</warSourceDirectory>
                    <warName>JSFDemo</warName>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.wildfly.plugins</groupId>
                <artifactId>wildfly-maven-plugin</artifactId>
                <version>1.2.1.Final</version>
                <configuration>
                    <hostname>localhost</hostname>
                    <port>9990</port>
                    <username>user</username>
                    <password>password</password>
                    <filename>${project.build.finalName}.war</filename>
                </configuration>
                <executions>
                    <execution>
                        <phase>install</phase>
                        <goals>
                            <goal>deploy</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

I have tried making hibernate-core scope provided and exclude dom4j from it. What is the exact workaround with my POM structure?


来源: stackexchange

问:
CN_match deprecated in favor of peer_name
I'm attempting to send a POST request from one server to another in PHP via SSL. It works correctly when i use CN_match in my context options. However I get a deprecation message in my error log:

PHP Deprecated:  the 'CN_match' SSL context option is deprecated in favor of 'peer_name'

The problem is that if I change CN_match to peer_name as suggested the request fails completely with this message:

failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request.

Using an invalid value for peer_name results in an expected error:

Peer certificate CN='localhost' did not match expected CN='test'

Clearly it is matching correctly when I specify 'localhost'. Am I missing some other configuration that is required when using peer_name instead of CN_match ?

Using MAMP, PHP 5.6.27

```<code>$userdata = array(
    'action'            => 'add-user',
    'name'              => $name,
    'email'             => $email,
    'username'          => $username,
    'password'          => $password);

// use key 'http' even if you send the request to https://...
$options = array(
    'http' => array(
        'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
        'method'  => 'POST',
        'content' => http_build_query($userdata)
    ),
    'ssl' => array(
        'verify_peer'       => true,
        'cafile'            => /path/to/file.pem,
        'verify_depth'      => 5,
        'allow_self_signed' => true,
        'peer_name'         => 'localhost'
    )
);

$context  = stream_context_create($options);
$data = file_get_contents('https://localhost/add-user.php', false, $context);
</code>```

答:
Using curl was the only solution I could find:

```<code>$url = 'https://some.domain.com/file.php';
$pem_file = '/absolute/path/to/certificate.pem';

$userdata = array(
    'action'            => 'add-user',
    'name'              => $name,
    'email'             => $email,
    'username'          => $username,
    'password'          => $password);

$curl_req = curl_init();
curl_setopt($curl_req, CURLOPT_URL, $url);
curl_setopt($curl_req, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl_req, CURLOPT_POST, true);
curl_setopt($curl_req, CURLOPT_HTTPHEADER, array('Content-type: application/x-www-form-urlencoded'));
curl_setopt($curl_req, CURLOPT_POSTFIELDS, http_build_query($userdata));
curl_setopt($curl_req, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($curl_req, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($curl_req, CURLOPT_CAINFO, $pem_file);

$response = curl_exec($curl_req);
curl_close($curl_req);
</code>```

In addition it took me a while to figure out how to structure the certificate.pem file. You need to stack the certificate(s) starting with your specific certificate and proceeding through any intermediate certificates and ending with the CA certificate:

```<code>-----BEGIN CERTIFICATE-----
<your site certificate>
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
<intermediate certificate>
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
<CA certificate>
-----END CERTIFICATE-----
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm attempting to send a POST request from one server to another in PHP via SSL. It works correctly when i use CN_match in my context options. However I get a deprecation message in my error log:

PHP Deprecated:  the 'CN_match' SSL context option is deprecated in favor of 'peer_name'

The problem is that if I change CN_match to peer_name as suggested the request fails completely with this message:

failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request.

Using an invalid value for peer_name results in an expected error:

Peer certificate CN='localhost' did not match expected CN='test'

Clearly it is matching correctly when I specify 'localhost'. Am I missing some other configuration that is required when using peer_name instead of CN_match ?

Using MAMP, PHP 5.6.27

$userdata = array(
    'action'            => 'add-user',
    'name'              => $name,
    'email'             => $email,
    'username'          => $username,
    'password'          => $password);

// use key 'http' even if you send the request to https://...
$options = array(
    'http' => array(
        'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
        'method'  => 'POST',
        'content' => http_build_query($userdata)
    ),
    'ssl' => array(
        'verify_peer'       => true,
        'cafile'            => /path/to/file.pem,
        'verify_depth'      => 5,
        'allow_self_signed' => true,
        'peer_name'         => 'localhost'
    )
);

$context  = stream_context_create($options);
$data = file_get_contents('https://localhost/add-user.php', false, $context);

Body:
Using curl was the only solution I could find:

$url = 'https://some.domain.com/file.php';
$pem_file = '/absolute/path/to/certificate.pem';

$userdata = array(
    'action'            => 'add-user',
    'name'              => $name,
    'email'             => $email,
    'username'          => $username,
    'password'          => $password);

$curl_req = curl_init();
curl_setopt($curl_req, CURLOPT_URL, $url);
curl_setopt($curl_req, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl_req, CURLOPT_POST, true);
curl_setopt($curl_req, CURLOPT_HTTPHEADER, array('Content-type: application/x-www-form-urlencoded'));
curl_setopt($curl_req, CURLOPT_POSTFIELDS, http_build_query($userdata));
curl_setopt($curl_req, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($curl_req, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($curl_req, CURLOPT_CAINFO, $pem_file);

$response = curl_exec($curl_req);
curl_close($curl_req);

In addition it took me a while to figure out how to structure the certificate.pem file. You need to stack the certificate(s) starting with your specific certificate and proceeding through any intermediate certificates and ending with the CA certificate:

-----BEGIN CERTIFICATE-----
<your site certificate>
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
<intermediate certificate>
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
<CA certificate>
-----END CERTIFICATE-----


问:
bind method on click event of "LabelLink" control in WPF - Caliburn
Hi I have problem to bind method on click event of "LabelLink" control. I use pseudeo LabelLink control, I think everybody know this solution with textBox and hyperlink.

Here is my code:

```<code><TextBlock Margin="10,12,10,4">
    <Hyperlink Name="RegLink"
               NavigateUri="http://registracia.azet.sk/"
               Micro:Message.Attach="[Event Click]=[Action OpenDefaultBrowser(NavigateUri)]"
               FontSize="12">Registrácia</Hyperlink>
</code>```

Problem is that I can bind method only on framework element.

I get this compile error:

```<code>Cannot attach type "ActionMessage" to type "Hyperlink". Instances of type "ActionMessage" can only be attached to objects of type "FrameworkElement".
</code>```

I search with google, bud didn’t find any suitable solution.

Thank for advice.

I try make a fake linkLabel with textBlock or Label control but they don’t have click event handler.

答:
You can embed your Hyperlink in a Button that doesn't look like a button in order to get a Click event that occurs on a FrameworkElement:

```<code><Grid>
    <Grid.Resources>
        <Style x:Key="HyperlinkButton" TargetType="Button">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="Button">
                        <ContentPresenter/>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Grid.Resources>
    <StackPanel>
        <Button Name="button1" Style="{StaticResource HyperlinkButton}" Click="Button_Click" Focusable="False">
            <TextBlock>
                <Hyperlink NavigateUri="http://www.stackoverflow.com" Focusable="False">
                    StackOverflow
                </Hyperlink>
            </TextBlock>
        </Button>
    </StackPanel>
</Grid>
</code>```

Perhaps you can adapt this technique to Caliburn.Micro.

ContentLicense: CC BY-SA 2.5

Body:
Hi I have problem to bind method on click event of "LabelLink" control. I use pseudeo LabelLink control, I think everybody know this solution with textBox and hyperlink.

Here is my code:

<TextBlock Margin="10,12,10,4">
    <Hyperlink Name="RegLink"
               NavigateUri="http://registracia.azet.sk/"
               Micro:Message.Attach="[Event Click]=[Action OpenDefaultBrowser(NavigateUri)]"
               FontSize="12">Registrácia</Hyperlink>

Problem is that I can bind method only on framework element.

I get this compile error:

Cannot attach type "ActionMessage" to type "Hyperlink". Instances of type "ActionMessage" can only be attached to objects of type "FrameworkElement".

I search with google, bud didn’t find any suitable solution.

Thank for advice.

I try make a fake linkLabel with textBlock or Label control but they don’t have click event handler.

Body:
You can embed your Hyperlink in a Button that doesn't look like a button in order to get a Click event that occurs on a FrameworkElement:

<Grid>
    <Grid.Resources>
        <Style x:Key="HyperlinkButton" TargetType="Button">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="Button">
                        <ContentPresenter/>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Grid.Resources>
    <StackPanel>
        <Button Name="button1" Style="{StaticResource HyperlinkButton}" Click="Button_Click" Focusable="False">
            <TextBlock>
                <Hyperlink NavigateUri="http://www.stackoverflow.com" Focusable="False">
                    StackOverflow
                </Hyperlink>
            </TextBlock>
        </Button>
    </StackPanel>
</Grid>

Perhaps you can adapt this technique to Caliburn.Micro.


问:
Python Split a phrase into words on space and symbols
I'm writing a program where I need to test whether a phrase such as "red car" is present in a variety of sentences: "I bought a new red car", "RED! CAR!", "red#$%^car".

I'm having trouble finding a way to separate out the words from the symbols in the last example.

My code so far is:

```<code>exclude = set(string.punctuation)

text = text.lower
text = ''.join(ch for ch in text if ch not in exclude)
text = text.split()

for word in phrase:
    found = False
    for e2 in text:
        if word == e2:
           found = True
           break
    if not found:
       return False
return True
</code>```

This causes the last example to be 'redcar' so the words aren't split.

All the questions I found on here were talking about delimiters not splitting out two words that are joined by a bunch of symbols.

Should I just use text.split for each individual symbol?

I was thinking of something like:

```<code>for ch in exclude:
    text = text.split(ch)
</code>```

but I was hoping there is a cleaner way to do it.

答:
This problem is pretty much tailor made for a regular expression, such as:

```<code>import re
red_car = re.compile(r"\bred\W{1,5}car\b", re.I)

if red_car.search("I bought a red#$%^car yesterday"):
    print("found a red car")
</code>```

The important components of the regular expression are:

```<code>\b     matches a word boundary at start and end so as not to match "tired carrot"
\W     matches any non-word character between "red" and "car"
{1,5}  matches from one to five occurrences of \W between "red" and "car"
re.I   makes the regex ignore case (match "RED car" etc.)
</code>```

Body:
I'm writing a program where I need to test whether a phrase such as "red car" is present in a variety of sentences: "I bought a new red car", "RED! CAR!", "red#$%^car".

I'm having trouble finding a way to separate out the words from the symbols in the last example.

My code so far is:

exclude = set(string.punctuation)

text = text.lower
text = ''.join(ch for ch in text if ch not in exclude)
text = text.split()

for word in phrase:
    found = False
    for e2 in text:
        if word == e2:
           found = True
           break
    if not found:
       return False
return True

This causes the last example to be 'redcar' so the words aren't split.

All the questions I found on here were talking about delimiters not splitting out two words that are joined by a bunch of symbols.

Should I just use text.split for each individual symbol?

I was thinking of something like:

for ch in exclude:
    text = text.split(ch)

but I was hoping there is a cleaner way to do it.

Body:
This problem is pretty much tailor made for a regular expression, such as:

import re
red_car = re.compile(r"\bred\W{1,5}car\b", re.I)

if red_car.search("I bought a red#$%^car yesterday"):
    print("found a red car")

The important components of the regular expression are:

\b     matches a word boundary at start and end so as not to match "tired carrot"
\W     matches any non-word character between "red" and "car"
{1,5}  matches from one to five occurrences of \W between "red" and "car"
re.I   makes the regex ignore case (match "RED car" etc.)


问:
prevent automatically page scroll up when using jquery fadein/out founction on fixed position div
I have a web page and I want to make a div that appears on the right side of screen by click a button (both div and button have fixed position)
I made it appear by using jQuery fadein/out

it works fine but when I click the button, the page slides to top automatically

htmlCode:

```<code><div class="fixedDiv">
    <div class="fixedDiv liveSupportFrame" style="background: #f8aa00;display: none" id="lsf">
        <div class="container" style="background-color:#d8d6d6;">
        ............
        </div>
    </div>

    <a class="btn btn-warning sideBtn" onclick="showOrHideLiveSupport();" role="button" href="#">FAQ</a>
</code>```

CSS code:

```<code>.fixedDiv{
position: fixed;
bottom: 25%;
right: 0em;
}
.fixedDiv .liveSupportFrame{
margin-right: 2em;
margin-bottom: 1em;
font-size:1.6vw;
bottom: 30%;
}
</code>```

JS code:

```<code>        var isLsfOpen = 0;
    function showOrHideLiveSupport() {
       if(!isLsfOpen){
           showLiveSupport()
       }
       else{
           hideLiveSupport()
       }
    }
    function showLiveSupport() {
        $('#lsf').fadeIn();

        isLsfOpen=true;
    }
    function hideLiveSupport() {
        $('#lsf').fadeOut();
        isLsfOpen=false;
    }
</code>```

答: That's because of href="#". Use event.preventDefault(); in your handler.

Body:
I have a web page and I want to make a div that appears on the right side of screen by click a button (both div and button have fixed position)
I made it appear by using jQuery fadein/out

it works fine but when I click the button, the page slides to top automatically

htmlCode:

        ............

    FAQ

CSS code:

.fixedDiv{
position: fixed;
bottom: 25%;
right: 0em;
}
.fixedDiv .liveSupportFrame{
margin-right: 2em;
margin-bottom: 1em;
font-size:1.6vw;
bottom: 30%;
}

JS code:

        var isLsfOpen = 0;
    function showOrHideLiveSupport() {
       if(!isLsfOpen){
           showLiveSupport()
       }
       else{
           hideLiveSupport()
       }
    }
    function showLiveSupport() {
        $('#lsf').fadeIn();

        isLsfOpen=true;
    }
    function hideLiveSupport() {
        $('#lsf').fadeOut();
        isLsfOpen=false;
    }


问:
How can I center a multiple line text on an image in this case?
I have an image that takes up the whole screen. Now I want to have centered text over it. The method that I'm using works great for single line text but when I have two lines, it centers the longest line and aligns all other lines to the left of the longest one. How can I make all of them centered?

Here's the class that I'm using to center my text over the image:

```<code>.centered {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
</code>```

答:
and if the tests adding each line in a block of
 would be easier for you and would allow you to center content without problem
for example

.centered {
  position: absolute;
  display:block;
  width:100%;
  text-align:center;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1 class="centered">
    <p>lorem ipsun</p>
    <p>holamigo</p>
  </h1></code>```

Body:
I have an image that takes up the whole screen. Now I want to have centered text over it. The method that I'm using works great for single line text but when I have two lines, it centers the longest line and aligns all other lines to the left of the longest one. How can I make all of them centered?

Here's the class that I'm using to center my text over the image:

.centered {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

Body:
and if the tests adding each line in a block of <p> would be easier for you and would allow you to center content without problem
for example

.centered {
  position: absolute;
  display:block;
  width:100%;
  text-align:center;

}

<h1 class="centered">
    <p>lorem ipsun</p>
    <p>holamigo</p>
  </h1>


问:
What's the easiest way to create an Excel table with C#?
I have some tabular data that I'd like to turn into an Excel table.

Software available:

.NET 4 (C#)

Excel 2010 (using the Excel API is OK)

I prefer not to use any 3rd party libraries

Information about the data:

A couple million rows

5 columns, all strings (very simple and regular table structure)

In my script I'm currently using a nested List data structure but I can change that

Performance of the script is not critical

Searching online gives many results, and I'm confused whether I should use OleDb, ADO RecordSets, or something else. Some of these technologies seem like overkill for my scenario, and some seem like they might be obsolete.

What is the very simplest way to do this?

Edit: this is a one-time script I intend to run from my attended desktop.

答:
I once read that the easiest way to create an Excel table was to actualy write a HTML table, including its structure and data, and simply name the file .xls.

Excel will be able to convert it, but it will display a warning saying that the content does not match the extension.


问:
PHP MySQL optimal way to perform multiple dependent queries
I need to query (read) some data, and analyze it before performing another query (read) on a different table.

I've looked at mysqli multiple statements but they don't have documentation for situations where the second query depends on the result of the first query.

It seems my current code of doing two queries might not be optimal. Is there a more optimal way to do this?

```<code>//FIRST QUERY
$query1= "SELECT color FROM products WHERE type = '$productType';";
$result = $conn->query($query1);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $colorProduct = $row["color"];
    }
}

//ANALYZE SEARCH RESULT FROM FIRST QUERY
if ($colorProduct == "green") {
    $colorType = "greenColorType";
}
//a lot more analysis

//SECOND QUERY
$query2 = "SELECT price FROM Vendors WHERE color = '$colorType';";
$result2 = $conn->query($query2);

if ($result2->num_rows > 0) {
    while($row = $result2->fetch_assoc()) {
        $priceOfProduct = priceOfProduct . $row["price"];
    }
}

$conn->close();
</code>```

Thank you in advance.

答:
First, you have to add a "and" to the "where" clause : SELECT color FROM products WHERE type = '$productType' and color = 'green'

Then you have to join or to add a sub query in SQL.

In fact, you should do only one SQL request.

Body:
I need to query (read) some data, and analyze it before performing another query (read) on a different table.

I've looked at mysqli multiple statements but they don't have documentation for situations where the second query depends on the result of the first query.

It seems my current code of doing two queries might not be optimal. Is there a more optimal way to do this?

//FIRST QUERY
$query1= "SELECT color FROM products WHERE type = '$productType';";
$result = $conn->query($query1);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $colorProduct = $row["color"];
    }
}

//ANALYZE SEARCH RESULT FROM FIRST QUERY
if ($colorProduct == "green") {
    $colorType = "greenColorType";
}
//a lot more analysis

//SECOND QUERY
$query2 = "SELECT price FROM Vendors WHERE color = '$colorType';";
$result2 = $conn->query($query2);

if ($result2->num_rows > 0) {
    while($row = $result2->fetch_assoc()) {
        $priceOfProduct = priceOfProduct . $row["price"];
    }
}

$conn->close();

Thank you in advance.


问:
How to use FirebaseAuthUI in swift 3
How to properly use FirebaseAuthUI in swift 3

so far i tried using this
app delegate.swift

```<code>import UIKit
import CoreData
import Firebase
import FirebaseAuth
import GoogleSignIn
import FBSDKLoginKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        FIRApp.configure()

        return true
    }

    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
        // Saves changes in the application's managed object context before the application terminates.
        self.saveContext()
    }

    func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {

        let handled = FBSDKApplicationDelegate.sharedInstance().application(app, open: url, sourceApplication: options[UIApplicationOpenURLOptionsKey.sourceApplication] as! String, annotation: options[UIApplicationOpenURLOptionsKey.annotation])

        return handled || GIDSignIn.sharedInstance().handle(
            url,
            sourceApplication: options[UIApplicationOpenURLOptionsKey.sourceApplication] as! String,
            annotation: options[UIApplicationOpenURLOptionsKey.annotation])
    }

    // MARK: - Core Data stack

    lazy var persistentContainer: NSPersistentContainer = {
        /*
         The persistent container for the application. This implementation
         creates and returns a container, having loaded the store for the
         application to it. This property is optional since there are legitimate
         error conditions that could cause the creation of the store to fail.
        */
        let container = NSPersistentContainer(name: "Kwiz")
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

                /*
                 Typical reasons for an error here include:
                 * The parent directory does not exist, cannot be created, or disallows writing.
                 * The persistent store is not accessible, due to permissions or data protection when the device is locked.
                 * The device is out of space.
                 * The store could not be migrated to the current model version.
                 Check the error message to determine what the actual problem was.
                 */
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        return container
    }()

    // MARK: - Core Data Saving support

    func saveContext () {
        let context = persistentContainer.viewContext
        if context.hasChanges {
            do {
                try context.save()
            } catch {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                let nserror = error as NSError
                fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
            }
        }
    }

}
</code>```

//MY ViewController.swift

```<code>import UIKit
import Firebase
import FirebaseAuthUI
import FirebaseDatabaseUI
import FirebaseGoogleAuthUI
import FirebaseFacebookAuthUI
import FBSDKCoreKit
import FBSDKLoginKit

class ViewController: UIViewController, FIRAuthUIDelegate {

    var kFacebookAppID = "54b1f4cbd01223477eb54122caeec604"

    override func viewDidLoad() {
        super.viewDidLoad()
       checkLoggedIn()
    }

    func checkLoggedIn() {
        FIRAuth.auth()?.addStateDidChangeListener { auth, user in
            if user != nil {
                // User is signed in.
            } else {
                // No user is signed in.
                self.login()
            }
        }
    }

    func login() {
        let authUI = FIRAuthUI.init(auth: FIRAuth.auth()!)
        let options = FIRApp.defaultApp()?.options
        let clientId = options?.clientID
        let googleProvider = FIRGoogleAuthUI(clientID: clientId!)
        let facebookProvider = FIRFacebookAuthUI(appID: kFacebookAppID)
        authUI?.delegate = self
        authUI?.providers = [googleProvider, facebookProvider]
        let authViewController = authUI?.authViewController()
        self.present(authViewController!, animated: true, completion: nil)
    }

    @IBAction func logoutUser(_ sender: AnyObject) {
        try! FIRAuth.auth()!.signOut()
    }

    func authUI(_ authUI: FIRAuthUI, didSignInWith user: FIRUser?, error: Error?) {
        if error != nil {
            //Problem signing in

        }else {
            login()

        }
    }

    func application(app: UIApplication, openURL url: NSURL, options: [String: AnyObject]) -> Bool {
        let sourceApplication = options[UIApplicationOpenURLOptionUniversalLinksOnly] as! String
        return FIRAuthUI.default()!.handleOpen(url as URL, sourceApplication: sourceApplication )
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}
</code>```

but it gives me this error.
use of undeclared type 'FIRAuthUIDelegate

i read this iOS firebase: FIRAuthUIDelegate.authUI not being called but i don't have idea how.

The FirebaseAuthUI docu is in obj-c https://github.com/firebase/FirebaseUI-iOS
Could you help me how use FirebaseAuthUI or an example project is really appreciated. Thanks

答: The documentation referenced in the question for FirebaseUI-iOS/FirebaseAuthUI now includes Swift reference code. The protocol needed in the ViewController is FUIAuthDelegate from FirebaseUI-iOS and not FIRAuthUIDelegate from firebase-ios-sdk.

Title: How to use FirebaseAuthUI in swift 3

Body:
How to properly use FirebaseAuthUI in swift 3

so far i tried using this
app delegate.swift

import UIKit
import CoreData
import Firebase
import FirebaseAuth
import GoogleSignIn
import FBSDKLoginKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        FIRApp.configure()

        return true
    }

    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
        // Saves changes in the application's managed object context before the application terminates.
        self.saveContext()
    }

    func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {

        let handled = FBSDKApplicationDelegate.sharedInstance().application(app, open: url, sourceApplication: options[UIApplicationOpenURLOptionsKey.sourceApplication] as! String, annotation: options[UIApplicationOpenURLOptionsKey.annotation])

        return handled || GIDSignIn.sharedInstance().handle(
            url,
            sourceApplication: options[UIApplicationOpenURLOptionsKey.sourceApplication] as! String,
            annotation: options[UIApplicationOpenURLOptionsKey.annotation])
    }

    // MARK: - Core Data stack

    lazy var persistentContainer: NSPersistentContainer = {
        /*
         The persistent container for the application. This implementation
         creates and returns a container, having loaded the store for the
         application to it. This property is optional since there are legitimate
         error conditions that could cause the creation of the store to fail.
        */
        let container = NSPersistentContainer(name: "Kwiz")
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

                /*
                 Typical reasons for an error here include:
                 * The parent directory does not exist, cannot be created, or disallows writing.
                 * The persistent store is not accessible, due to permissions or data protection when the device is locked.
                 * The device is out of space.
                 * The store could not be migrated to the current model version.
                 Check the error message to determine what the actual problem was.
                 */
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        return container
    }()

    // MARK: - Core Data Saving support

    func saveContext () {
        let context = persistentContainer.viewContext
        if context.hasChanges {
            do {
                try context.save()
            } catch {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                let nserror = error as NSError
                fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
            }
        }
    }

}

//MY ViewController.swift

import UIKit
import Firebase
import FirebaseAuthUI
import FirebaseDatabaseUI
import FirebaseGoogleAuthUI
import FirebaseFacebookAuthUI
import FBSDKCoreKit
import FBSDKLoginKit

class ViewController: UIViewController, FIRAuthUIDelegate {

    var kFacebookAppID = "54b1f4cbd01223477eb54122caeec604"

    override func viewDidLoad() {
        super.viewDidLoad()
       checkLoggedIn()
    }

    func checkLoggedIn() {
        FIRAuth.auth()?.addStateDidChangeListener { auth, user in
            if user != nil {
                // User is signed in.
            } else {
                // No user is signed in.
                self.login()
            }
        }
    }

    func login() {
        let authUI = FIRAuthUI.init(auth: FIRAuth.auth()!)
        let options = FIRApp.defaultApp()?.options
        let clientId = options?.clientID
        let googleProvider = FIRGoogleAuthUI(clientID: clientId!)
        let facebookProvider = FIRFacebookAuthUI(appID: kFacebookAppID)
        authUI?.delegate = self
        authUI?.providers = [googleProvider, facebookProvider]
        let authViewController = authUI?.authViewController()
        self.present(authViewController!, animated: true, completion: nil)
    }

    @IBAction func logoutUser(_ sender: AnyObject) {
        try! FIRAuth.auth()!.signOut()
    }

    func authUI(_ authUI: FIRAuthUI, didSignInWith user: FIRUser?, error: Error?) {
        if error != nil {
            //Problem signing in

        }else {
            login()

        }
    }

    func application(app: UIApplication, openURL url: NSURL, options: [String: AnyObject]) -> Bool {
        let sourceApplication = options[UIApplicationOpenURLOptionUniversalLinksOnly] as! String
        return FIRAuthUI.default()!.handleOpen(url as URL, sourceApplication: sourceApplication )
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

but it gives me this error.
use of undeclared type 'FIRAuthUIDelegate

i read this iOS firebase: FIRAuthUIDelegate.authUI not being called but i don't have idea how.

The FirebaseAuthUI docu is in obj-c https://github.com/firebase/FirebaseUI-iOS
Could you help me how use FirebaseAuthUI or an example project is really appreciated. Thanks


问:
kafka streams app - ignore old messages on restart
I deal with timeseries data for a live application. So old data has no significance. I just want to process data received after the stream app has started and not from previously committed offset. What is the correct way to ignore old records on kafka stream app after restart?

With kafka consumer API I generally used the seekToEnd() method to skip forward to the latest record. Is there a equivalent mechanism for streams?
I want to avoid filtering through all messages since last commit to ignore old messages.

答:
You can create another consumer using Kafka Consumer API with groupId same as the applicationId for kafka-streams and use that consumer to do a seekToEnd() before starting your stream. Disable autoCommit for this special consumer and commit the offset manually after seekToEnd(). Then try starting your stream.

Make sure the stream has not started until your offsets from reset consumer are committed.


问:
What is the purpose of nesting dispatch_async(dispatch_get_main_queue()^{}) ?
I've inherited some code that has this rather unusual nested sequence. The usual paradigm would have a single dispatch to the main queue to update the UI. The code, shown below, nests a dispatch to the main queue within another dispatch to the main queue.

```<code>- (void)viewDidLoad
{
// Setup some data
// Adjust UI

 dispatch_async(myBackgroundQueue, ^{
   while(Do_some_time_consuming_work) {

     // Time consuming work goes here

     if (things_are_going_slowly) {

        dispatch_async(dispatch_get_main_queue(), ^{    // <- one of these two seems redundant
          dispatch_async(dispatch_get_main_queue(), ^{  // <- one of these two seems redundant

            stillWorkingLabel.hidden = NO; //Let user know the work is still ongoing
          });
        });
     )

   // Finish time-consuming work
   }

  });

}
</code>```

What is the purpose, if any, of nesting dispatch_async(dispatch_get_main_queue()? This nested sequence shows up in several places in the app. It seems to me that only one dispatch to the main queue is needed.

I think I've read all of the relevant questions on related topics here and via Google search, but I haven't found anyone suggesting nesting two identical dispatches.

The app works well, with the UI updating as expected in the above example and in other places in the code.

Most of the app's code uses the usual non-nested version of the above scheme, and of course it also works just fine.

I'm inclined to just replace these nested calls with a single dispatch, but maybe I'm missing something here. Any advice would be appreciated.

答:
Nesting two dispatch_queues for the main doesn't make any sense , the straight forward way is that </p>

```<code>   dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

 // perform long task here

 dispatch_async(dispatch_get_main_queue(), ^(){

  //Add method, task you want perform on mainQueue
 //Control UIView, IBOutlet all here

});  });
</code>```

Body:
I've inherited some code that has this rather unusual nested sequence. The usual paradigm would have a single dispatch to the main queue to update the UI. The code, shown below, nests a dispatch to the main queue within another dispatch to the main queue.

- (void)viewDidLoad
{
// Setup some data
// Adjust UI

 dispatch_async(myBackgroundQueue, ^{
   while(Do_some_time_consuming_work) {

     // Time consuming work goes here

     if (things_are_going_slowly) {

        dispatch_async(dispatch_get_main_queue(), ^{    // <- one of these two seems redundant
          dispatch_async(dispatch_get_main_queue(), ^{  // <- one of these two seems redundant

            stillWorkingLabel.hidden = NO; //Let user know the work is still ongoing
          });
        });
     )

   // Finish time-consuming work
   }

  });

}

What is the purpose, if any, of nesting dispatch_async(dispatch_get_main_queue()? This nested sequence shows up in several places in the app. It seems to me that only one dispatch to the main queue is needed.

I think I've read all of the relevant questions on related topics here and via Google search, but I haven't found anyone suggesting nesting two identical dispatches.

The app works well, with the UI updating as expected in the above example and in other places in the code.

Most of the app's code uses the usual non-nested version of the above scheme, and of course it also works just fine.

I'm inclined to just replace these nested calls with a single dispatch, but maybe I'm missing something here. Any advice would be appreciated.

Body:
Nesting two dispatch_queues for the main doesn't make any sense , the straight forward way is that

   dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

 // perform long task here

 dispatch_async(dispatch_get_main_queue(), ^(){

  //Add method, task you want perform on mainQueue
 //Control UIView, IBOutlet all here

});  });


问:
How do I use Django piston to return a response in text/plain?
I want to NOT serialize anything. I just want to return what is equivalent to HttpResponse(blah)

答:
Sounds like you want a string emitter, and not one of the built-in JSONEmitter, XMLEmitter, etc.

Have a look at the docs for emitters: https://bitbucket.org/jespern/django-piston/wiki/Documentation

And the existing emitter definitions here:
https://bitbucket.org/jespern/django-piston/src/c4b2d21db51a/piston/emitters.py

A definition of a plain text emitter might look like this:

```<code>from piston.emitters import Emitter
from piston.utils import Mimer

class TextEmitter(Emitter):
    def render(self, request):
        return self.construct()
Emitter.register('text', TextEmitter)
Mimer.register('text', None, ('text/plain',))
</code>```

You'd get your resource to use this emitter in your urls.py like so:

```<code>urlpatterns = patterns('',
   url(r'^blogposts$', resource_here, { 'emitter_format': 'text' }),
)
</code>```

Body:
Sounds like you want a string emitter, and not one of the built-in JSONEmitter, XMLEmitter, etc.

Have a look at the docs for emitters: https://bitbucket.org/jespern/django-piston/wiki/Documentation

And the existing emitter definitions here:
https://bitbucket.org/jespern/django-piston/src/c4b2d21db51a/piston/emitters.py

A definition of a plain text emitter might look like this:

from piston.emitters import Emitter
from piston.utils import Mimer

class TextEmitter(Emitter):
    def render(self, request):
        return self.construct()
Emitter.register('text', TextEmitter)
Mimer.register('text', None, ('text/plain',))

You'd get your resource to use this emitter in your urls.py like so:

urlpatterns = patterns('',
   url(r'^blogposts$', resource_here, { 'emitter_format': 'text' }),
)


问:
R - Compare 2 matrices to find rows which rows aren't in both
I have two large matrices in R of differing sizes, 371 x 1502 (A) and 371 x 1207 (B).

All of matrix B is included in A. A also contains many other rows mixed in. I am looking for a way to create a new matrix, C, which contains all the rows in A not found in B.

I am sure there is a way to do this using data.tables and keys but I can't for the life of me figure it out.

example data:

```<code>a = t(matrix(c(1,2,3,4,5,6,7,8,9), nrow = 3))
b = t(matrix(c(1,2,3,7,8,9), nrow = 3))
</code>```

Any help is appreciated,

Thanks.

答:
Is this what you want?

Using dplyr::anti_join:

```<code>require(dplyr);
anti_join(as.data.frame(a), as.data.frame(b));
#  V1 V2 V3
#1  4  5  6
</code>```

Using data.table::fsetdiff:

```<code>require(data.table);
fsetdiff(as.data.table(a), as.data.table(b));
#   V1 V2 V3
#1:  4  5  6
</code>```

Sample data

```<code># Your sample data
a = t(matrix(c(1,2,3,4,5,6,7,8,9), nrow = 3))
b = t(matrix(c(1,2,3,7,8,9), nrow = 3));
</code>```

Body:
I have two large matrices in R of differing sizes, 371 x 1502 (A) and 371 x 1207 (B).

All of matrix B is included in A. A also contains many other rows mixed in. I am looking for a way to create a new matrix, C, which contains all the rows in A not found in B.

I am sure there is a way to do this using data.tables and keys but I can't for the life of me figure it out.

example data:

a = t(matrix(c(1,2,3,4,5,6,7,8,9), nrow = 3))
b = t(matrix(c(1,2,3,7,8,9), nrow = 3))

Any help is appreciated,

Thanks.

Body:
Is this what you want?

Using dplyr::anti_join:

require(dplyr);
anti_join(as.data.frame(a), as.data.frame(b));
#  V1 V2 V3
#1  4  5  6

Using data.table::fsetdiff:

require(data.table);
fsetdiff(as.data.table(a), as.data.table(b));
#   V1 V2 V3
#1:  4  5  6

Sample data

# Your sample data
a = t(matrix(c(1,2,3,4,5,6,7,8,9), nrow = 3))
b = t(matrix(c(1,2,3,7,8,9), nrow = 3));


问:
How to define type for props
Code:

```<code>let component = ReasonReact.statelessComponent("Page");
type matchParams = {.
  id: int
};
type match = {.
  params: matchParams
};
type userProps = {.
  match: match
};
let home = <Home />;
let user = (~props:userProps) => <User id=props.match.params.id />;
let make = (_children) => {
  ...component,
  render: (_self) =>
    <div> <Route key="home" exact=false path="/home" component=home />
    <Route key="user" exact=false path="/user/:id" component=user /> </div>
};
</code>```

Output:

Unbound record field match

on row

```<code>let user = (~props:userProps) => <User id=props.match.params.id />;
</code>```

how to define type, what i do wrong?

答:
The error is caused by match being a reserved keyword. You should have gotten a better error message though, and I'd consider this a bug in Reason. To solve it, if you need it to compile to match on the JS side, you can use _match instead, otherwise just use a different name.

You also (probably) have a few other problems:

let home = <Home /> is not a function like user. It will probably need to be let home = () => <Home/>

You're defining a record type as the props that will be given to you by the component function. But you'll probably be given a JS object instead of a record. See the Reason guide which explains the difference.

Title: How to define type for props

Body:
Code:

let component = ReasonReact.statelessComponent("Page");
type matchParams = {.
  id: int
};
type match = {.
  params: matchParams
};
type userProps = {.
  match: match
};
let home = <Home />;
let user = (~props:userProps) => <User id=props.match.params.id />;
let make = (_children) => {
  ...component,
  render: (_self) =>

 <Route key="home" exact=false path="/home" component=home />
    <Route key="user" exact=false path="/user/:id" component=user />

};

Output:

Unbound record field match

on row

let user = (~props:userProps) => <User id=props.match.params.id />;

how to define type, what i do wrong?


问:
Change data-percent in js
I'm trying to create a program in JS in order to change some data-percent when you click on a region of a map. Basically I'm using a jqvmap as Map and a progressbar to display some info for each region that the user clicks.
that what I'm working with:

HTML

```<code><h1>Edificable surface</h1>
      <div class="skillbar clearfix" data-percent="0%">
      <div class="skillbar-title" style="background: #27ae60;"><span>Job</span></div>
      <div class="skillbar-bar" style="background: #2ecc71;"></div>
      <div class="skill-bar-percent">100%</div>
      </div> <!-- End Skill Bar -->
</code>```

JavaScript

```<code>jQuery(document).ready(function(){
  jQuery('.skillbar').each(function(){
    jQuery(this).find('.skillbar-bar').animate({
      width:jQuery(this).attr('data-percent')
    },6000);
  });
});

jQuery(document).ready(function () {
        jQuery('#vmap').vectorMap({
          map: 'europe_en',
          enableZoom: false,
          showTooltip: true,
          onRegionClick: function (element, code, region) {
            if (!touch_detect()) {
              // we're not on a mobile device, handle the click
              var message = 'You clicked "' + region + '" which has the code: ' + code.toUpperCase();
              document.getElementById('indi').innerHTML = 'You clicked "' + region + '".';
            }
            if (region == 'United Kingdom') {
            document.getElementByClassName('skillbar clearfix').setAttribute('data-percent', '50%');
          } else {
            document.getElementByClassName('skillbar clearfix').setAttribute('data-percent', '0');
          }
          },
          onRegionOver: function (element, code, region) {
            if (touch_detect()) {
              /// we're not on a mobile device, handle the click
              var message = 'You clicked "' + region + '" which has the code: ' + code.toUpperCase();
              document.getElementById('indi').innerHTML = 'You clicked "' + region + '".';
            }
        },
        });
      });
</code>```

the first if statement works properly and every time I click on a region it display the region that I have clicked but the second one ( if region = 'United Kingdom')..... " doesn't work even if it looks like correct.
Do you have any tips for me?
Thanks :)

答:
HTML:

```

<p>JavaScript:</p>

<pre class="lang-js prettyprint-override"><code>var value = 50;
$("#chart").attr("data-percent", value.toString());
</code>```

Title: Change data-percent in js

Body:
I'm trying to create a program in JS in order to change some data-percent when you click on a region of a map. Basically I'm using a jqvmap as Map and a progressbar to display some info for each region that the user clicks.
that what I'm working with:

HTML

Edificable surface

Job

100%

JavaScript

jQuery(document).ready(function(){
  jQuery('.skillbar').each(function(){
    jQuery(this).find('.skillbar-bar').animate({
      width:jQuery(this).attr('data-percent')
    },6000);
  });
});

jQuery(document).ready(function () {
        jQuery('#vmap').vectorMap({
          map: 'europe_en',
          enableZoom: false,
          showTooltip: true,
          onRegionClick: function (element, code, region) {
            if (!touch_detect()) {
              // we're not on a mobile device, handle the click
              var message = 'You clicked "' + region + '" which has the code: ' + code.toUpperCase();
              document.getElementById('indi').innerHTML = 'You clicked "' + region + '".';
            }
            if (region == 'United Kingdom') {
            document.getElementByClassName('skillbar clearfix').setAttribute('data-percent', '50%');
          } else {
            document.getElementByClassName('skillbar clearfix').setAttribute('data-percent', '0');
          }
          },
          onRegionOver: function (element, code, region) {
            if (touch_detect()) {
              /// we're not on a mobile device, handle the click
              var message = 'You clicked "' + region + '" which has the code: ' + code.toUpperCase();
              document.getElementById('indi').innerHTML = 'You clicked "' + region + '".';
            }
        },
        });
      });

the first if statement works properly and every time I click on a region it display the region that I have clicked but the second one ( if region = 'United Kingdom')..... " doesn't work even if it looks like correct.
Do you have any tips for me?
Thanks :)

Body:
HTML:

<div id="chart" class="chart-circle" data-percent="100"></div>

JavaScript:

var value = 50;
$("#chart").attr("data-percent", value.toString());


问:
vb.net dropdown list cannot pop up the details after I did selection
what I want to do is after I select the name from the dropdown list, the details which are related with the user can pop up in the textboxes. I created a view at sql alreaday called VEditUser. But after I run the code, try catch always tell incorrect syntax near " = ".  Can somebody tell me where is wrong?

Dim MyConnection As New SqlConnection
Dim Command As New SqlCommand
Dim Datareader As SqlDataReader

Try

'Create a connection to the SQL server
MyConnection.ConnectionString = "server=(local);database=dbSQL1;Trusted_Connection=yes"
MyConnection.Open()
Command.CommandText = "SELECT strFirstName, strLastName, strAddress, strCity, intStateID, strZipcode, strEmail, strCellPhone, intServiceGroupID, intRoleID, intStatusID, strLoginName FROM VEditUser = " & ddlCustomer.SelectedValue

Command.Connection = MyConnection
Datareader = Command.ExecuteReader

Try
    If Datareader.HasRows Then

        Datareader.Read()

        txtFirstName.Text = Datareader.Item("strFirstName")
        txtLastName.Text = Datareader.Item("strLastName")
        txtAddress.Text = Datareader.Item("strAddress")
        txtCity.Text = Datareader.Item("strCity")
        dpdState.Text = Datareader.Item("intStateID")
        txtZipcode.Text = Datareader.Item("strZipcode")
        txtEmail.Text = Datareader.Item("strEmail")
        txtCellPhone.Text = Datareader.Item("strCellPhone")
        dpdServiceGroup.Text = Datareader.Item("intServiceGroupID")
        dpdRole.Text = Datareader.Item("intRoleID")
        dpdStatus.Text = Datareader.Item("intStatusID")
        txtUserName.Text = Datareader.Item("strLoginName")
    End If

Catch ex As Exception

End Try

MyConnection.Close() 'Close the connection.
```

答:
The quick answer is that you are missing the where from your Sql:

change:

```<code>Command.CommandText = "SELECT strFirstName, strLastName, strAddress, strCity, intStateID, strZipcode, strEmail, strCellPhone, intServiceGroupID, intRoleID, intStatusID, strLoginName FROM VEditUser = " & ddlCustomer.SelectedValue
</code>```

to

```<code>Command.CommandText = "SELECT strFirstName, strLastName, strAddress, strCity, intStateID, strZipcode, strEmail, strCellPhone, intServiceGroupID, intRoleID, intStatusID, strLoginName FROM VEditUser WHERE strLoginName  = " & ddlCustomer.SelectedValue
</code>```

For example.  If strLoginName is not the value in the dropdown then replace as appropriate

The slightly longer answer is that you should be protecting yourself from Sql Injection by always sanitising your inputs, and using parameterized queries.  In the example you have provided you can achieve this by using the following:

```<code>Command.CommandText = "SELECT strFirstName, strLastName, strAddress, strCity, intStateID, strZipcode, strEmail, strCellPhone, intServiceGroupID, intRoleID, intStatusID, strLoginName FROM VEditUser WHERE strLoginName = @customer"

cmd.Parameters.Add("@customer", SqlDbType.VarChar, 50).Value = ddlCustomer.SelectedValue

Command.Connection = MyConnection
</code>```

Body:
The quick answer is that you are missing the where from your Sql:

change:

Command.CommandText = "SELECT strFirstName, strLastName, strAddress, strCity, intStateID, strZipcode, strEmail, strCellPhone, intServiceGroupID, intRoleID, intStatusID, strLoginName FROM VEditUser = " & ddlCustomer.SelectedValue

to

Command.CommandText = "SELECT strFirstName, strLastName, strAddress, strCity, intStateID, strZipcode, strEmail, strCellPhone, intServiceGroupID, intRoleID, intStatusID, strLoginName FROM VEditUser WHERE strLoginName  = " & ddlCustomer.SelectedValue

For example.  If strLoginName is not the value in the dropdown then replace as appropriate

The slightly longer answer is that you should be protecting yourself from Sql Injection by always sanitising your inputs, and using parameterized queries.  In the example you have provided you can achieve this by using the following:

Command.CommandText = "SELECT strFirstName, strLastName, strAddress, strCity, intStateID, strZipcode, strEmail, strCellPhone, intServiceGroupID, intRoleID, intStatusID, strLoginName FROM VEditUser WHERE strLoginName = @customer"

cmd.Parameters.Add("@customer", SqlDbType.VarChar, 50).Value = ddlCustomer.SelectedValue

Command.Connection = MyConnection


问:
Javascript: code with no animation with requestAnimationFrame?
I am learning Javacript and test the code from the book (below). It should animate an image but doesn't. I add print out using alert which shows that the function is executed only once. What goes wrong?

```<code><!doctype html>
<html>
<head>
  <title> My home page </title>
  <script>
var cat = document.querySelector("img");
var angle = 0, lastTime = null;
var count = 0;
function animate(time) {
  //alert(count);
  //++count;
  if (lastTime != null)
    angle += (time - lastTime) * 0.001;
  lastTime = time ;
  cat.style.top = (Math.sin(angle) * 20) + "px";
  cat.style.left = (Math.cos(angle) * 200) + "px";
  requestAnimationFrame(animate);
}
  </script>
</head>
<body>
  <p style ="text-align: center">
    <img src ="img/cat.jpg" style ="position: relative">
  </p >
</body>
<script>requestAnimationFrame(animate);</script>
</html>
</code>```

Thank you for the help.

答:
If you look at the console, you will see that the cat is undefined.

This happens because var cat = document.querySelector("img"); is run in the head element and so the img does not exist yet.

If you move the code at the end of the body it will work.

Or you could run your code when the DOMContentLoaded event is fired.

<!doctype html>

  <title> My home page </title>

```

Body:
I am learning Javacript and test the code from the book (below). It should animate an image but doesn't. I add print out using alert which shows that the function is executed only once. What goes wrong?

<!doctype html>

  <title> My home page </title>

Thank you for the help.

Body:
If you look at the console, you will see that the cat is undefined.

This happens because var cat = document.querySelector("img"); is run in the head element and so the img does not exist yet.

If you move the code at the end of the body it will work.

Or you could run your code when the DOMContentLoaded event is fired.

<!doctype html>
<html>
<head>
  <title> My home page </title>
</head>
<body>
  <p style ="text-align: center">
    <img src ="img/cat.jpg" style ="position: relative">
  </p >
</body>
<script>
var cat = document.querySelector("img");
var angle = 0, lastTime = null;
var count = 0;
function animate(time) {
  //alert(count);
  //++count;
  if (lastTime != null)
    angle += (time - lastTime) * 0.001;
  lastTime = time ;
  cat.style.top = (Math.sin(angle) * 20) + "px";
  cat.style.left = (Math.cos(angle) * 200) + "px";
  requestAnimationFrame(animate);
}
</script>
<script>requestAnimationFrame(animate);</script>
</html>


问:
How to use arbitrary directory as static directory in Reactjs
I have a website written in React.

The website itself works fine.

I also have blog which is based on Wordpress.

When I put blog contents on blog directory, React show the 404 not found page because all contents but static is managed by React.

I think if I could set one more directory called blog as static directory, I can put all Wordpress related files on the directory.

But I was struggling to do that.

Is there any options or setting files for react-scripts build?

like react-scripts build --static-directories static,blog

Could you please help me?

/index.html
/static/* < static contents
/blog/* < also static contents.

Thanks in advance.

[UPDATE] even though i put static file on static directory, I could not access it. It turned out I need to import that static file from Reactjs file...

答:
[SOLVED] Problem was 2 folds.

Server-side and client-side.

First, I edited the .htaccess file not to rewrite anything.
RewriteEngine off

Now Safari can understand "my domain/blog/" correctly.

But Chrome still treat "my domain/blog/" in ReactJS.

I don't understand why but I can see correct no-React contents only once after deleting cache. But once I open React contents, Chrome start treating "my domain/blog/" as React contents again.

Then I checked source code again and found that I used a React Router's feature called Switch. It seems Switch is doing rewriting thing in React.

So I removed the Switch tag and finally problem solved.


问:
How to Sanitise the logged data when using log4j2?
I need to validate the logs currently being written using log4j2 for sanitizing the input passed to it. I see ESAPI API provides an option to sanitize the input passed to it.

My question is I am not sure how I can use the ESAPI with logging methods.

Is there something like a filter or interceptor which I need to add for while logging in my methods to transparently filter and sanitise the logged text accordingly or should I write a custom Logger Class which extends the base Logger class and then logs accordingly by wrapping the call to ESAPI api.

If anyone has faced a similar issue can you please help me on this.

答:
I’m guessing that with “sanitise” you mean things like obfuscating password strings and perhaps replacing IDs with tokens.

Log4j2 provides a Rewrite appender that allows you to replace a LogEvent with another LogEvent before it’s passed to the destination (e.g. File) Appender.

Alternatively you can use Log4j2 Filters to prevent some log events from going to certain (or all) appenders. This may be too drastic for your needs.


问:
Trace the IPAddress
I like to know the IP address of the system from which user is connected to MSTSC or remote system. Here is my problem:-

I have web application wich run on intranet and when user need to access that webapplication they need to login to their office PC. Now to access their office PC user need to connect thorugh VPN. Now i want to know his IP address from which he has done the VPN when he access the webapplication. Your help is appriciated

Thanks,
Pankaj

答: Create a VB6 application with fancy animation and an "ENHANCE" button.

Title: Trace the IPAddress


问:
Button onClick method works on second click only
I have trouble on onClick method in my activity. I use layoutInflater in onClick method and change layout to another layout on button click, that's ok. But i have a my own method in onClick. It doesn't work on first click. It works only on second click.

```<code>   @Override
public void onClick(View v) {
    getTextA();
    mFrameLayout.removeAllViews();
    LayoutInflater layoutInflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    v = layoutInflater.inflate(R.layout.soru, null);
    mFrameLayout.addView(v);
    Button bt = new Button(this);
    bt.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
    mFrameLayout.addView(bt);
    bt.setText(textA);
}
</code>```

textA comes from getTextA() method, but on second click. Why ? Anyone can help me ?

答:
I solved the problem. Problem is in layoutinflater inside onClick method. So i put that layoutinflater codes to new method call getQuestion(). And call getQuestion() method in my getTextA() method. its solved.

I use layoutinflater because this method still in a fragment. Using a new fragment causes Nestedfragments. Thanks for your answers.

Here is the code

```<code>public void onClick(View v) {
    getTextA();
}`

public void getTextA(){
  //Method details.
  getQuestion();
}

public void getQuestion(){
mFrameLayout.removeAllViews();
LayoutInflater layoutInflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = layoutInflater.inflate(R.layout.soru, null);
mFrameLayout.addView(v);
Button bt = new Button(this);
bt.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
mFrameLayout.addView(bt);
bt.setText(textA);
}
</code>```

Body:
I have trouble on onClick method in my activity. I use layoutInflater in onClick method and change layout to another layout on button click, that's ok. But i have a my own method in onClick. It doesn't work on first click. It works only on second click.

   @Override
public void onClick(View v) {
    getTextA();
    mFrameLayout.removeAllViews();
    LayoutInflater layoutInflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    v = layoutInflater.inflate(R.layout.soru, null);
    mFrameLayout.addView(v);
    Button bt = new Button(this);
    bt.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
    mFrameLayout.addView(bt);
    bt.setText(textA);
}

textA comes from getTextA() method, but on second click. Why ? Anyone can help me ?

Body:
I solved the problem. Problem is in layoutinflater inside onClick method. So i put that layoutinflater codes to new method call getQuestion(). And call getQuestion() method in my getTextA() method. its solved.

I use layoutinflater because this method still in a fragment. Using a new fragment causes Nestedfragments. Thanks for your answers.

Here is the code

public void onClick(View v) {
    getTextA();
}`

public void getTextA(){
  //Method details.
  getQuestion();
}

public void getQuestion(){
mFrameLayout.removeAllViews();
LayoutInflater layoutInflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = layoutInflater.inflate(R.layout.soru, null);
mFrameLayout.addView(v);
Button bt = new Button(this);
bt.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
mFrameLayout.addView(bt);
bt.setText(textA);
}


问:
Searching for a Key in Multivalue Dictionaries in C#
I want to set up a lookup table like so:

```<code> Key           Value
 -----         ------------------
 Cat           Lion, Tiger, Cheetah
 Fish          Dolphin, Whale
 Dog .         Pitbull, Doberman
</code>```

An input of "Lion" would return the key "Cat"

I have set up 3 possible ways to initialize the data:

A Dictionary:

```<code>var map = new Dictionary<string,string>
{
    ["Dolphin"] = "Fish",
    ["Lion"] = "Cat",
    //....
};
</code>```

A HashSet:

```<code>var data = new Dictionary<string, HashSet<string>>
{
    {"cat", new HashSet<string> {"Lion", "Tiger", "Cheetah"}},
    {"fish", new HashSet<string> {"Dolphin", "Whale"}},
    {"Dog", new HashSet<string> {"Pitbull", "Doberman"}}
};
</code>```

A tuple:

```<code>var data = new List<Tuple<string, List<string>>>
{
    Tuple.Create<string,List<string>> ("Cat", new List<string> { "Cheetah", "Lion" }),
    Tuple.Create<string,List<string>> ("Dog", new List<string> { "Doberman", "Pitbull" }),
    Tuple.Create<string,List<string>> ("Fish", new List<string> { "Dolphin", "Whale" }),

};
</code>```

Given an animal, I want to return its type.
I know for the dictionary I can call the ContainsKey method.

Is there something similar for the other two options?

The data set isn't that big, (~15 keys that have 10 or so values), so I'm also wondering if one option would be better than the other in terms of performance.

答:
Use the Dictionary<string, string> option.

```<code>var animalToType = new Dictionary<string,string>
{
    ["Dolphin"] = "Fish",
    ["Lion"] = "Cat",
    //....
};
var lionType = animalToType["Lion"];
</code>```

The other options are not going to be as simple. They will all involve loops, whether directly or hidden by Linq calls.

Body:
I want to set up a lookup table like so:

 Key           Value
 -----         ------------------
 Cat           Lion, Tiger, Cheetah
 Fish          Dolphin, Whale
 Dog .         Pitbull, Doberman

An input of "Lion" would return the key "Cat"

I have set up 3 possible ways to initialize the data:

A Dictionary:

var map = new Dictionary<string,string>
{
    ["Dolphin"] = "Fish",
    ["Lion"] = "Cat",
    //....
};

A HashSet:

var data = new Dictionary<string, HashSet<string>>
{
    {"cat", new HashSet<string> {"Lion", "Tiger", "Cheetah"}},
    {"fish", new HashSet<string> {"Dolphin", "Whale"}},
    {"Dog", new HashSet<string> {"Pitbull", "Doberman"}}
};

A tuple:

var data = new List<Tuple<string, List<string>>>
{
    Tuple.Create<string,List<string>> ("Cat", new List<string> { "Cheetah", "Lion" }),
    Tuple.Create<string,List<string>> ("Dog", new List<string> { "Doberman", "Pitbull" }),
    Tuple.Create<string,List<string>> ("Fish", new List<string> { "Dolphin", "Whale" }),

};

Given an animal, I want to return its type.
I know for the dictionary I can call the ContainsKey method.

Is there something similar for the other two options?

The data set isn't that big, (~15 keys that have 10 or so values), so I'm also wondering if one option would be better than the other in terms of performance.

Body:
Use the Dictionary<string, string> option.

var animalToType = new Dictionary<string,string>
{
    ["Dolphin"] = "Fish",
    ["Lion"] = "Cat",
    //....
};
var lionType = animalToType["Lion"];

The other options are not going to be as simple. They will all involve loops, whether directly or hidden by Linq calls.


问:
EF Code First self rating by DataAnnotations or fluent API
I have one class:

```<code>[Table(nameof(User), Schema = "Administration")]
public class User : IBaseModel
{
    [Key]
    public int UserId { get; set; }

    #region IBaseModel

    public int AddedBy { get; set; }
    [ForeignKey("AddedBy")]
    public virtual User UserAddedBy { get; set; }

    public int ModifiedBy { get; set; }
    [ForeignKey("ModifiedBy")]
    public virtual User UserModifiedBy { get; set; }

    #endregion
}
</code>```

I try create self relation for this table (who AddedBy and who ModifiedBy item)

When my class look like above and I try use Add-Migration init on Package Manager Console it returns error:

Unable to determine the principal end of an association between the
  types 'abc.Administration.User' and 'abc.Administration.User'.
  The principal end of this association must be explicitly configured
  using either the relationship fluent API or data annotations.

after this error I try use fluent API and on method OnModelCreating (in my context) I wrote:

```<code>    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Administration.User>().HasOptional(e => e.UserAddedBy).WithMany().HasForeignKey(m => m.AddedBy);
        modelBuilder.Entity<Administration.User>().HasOptional(e => e.UserModifiedBy).WithMany().HasForeignKey(m => m.ModifiedBy);
    }
</code>```

and again try Add-Migration init but again I saw error message:

One or more validation errors were detected during model generation:

abc.User_UserAddedBy: : Multiplicity conflicts with the referential
  constraint in Role 'User_UserAddedBy_Target' in relationship
  'User_UserAddedBy'. Because all of the properties in the Dependent
  Role are non-nullable, multiplicity of the Principal Role must be '1'.
  abc.User_UserModifiedBy: : Multiplicity conflicts with the referential
  constraint in Role 'User_UserModifiedBy_Target' in relationship
  'User_UserModifiedBy'. Because all of the properties in the Dependent
  Role are non-nullable, multiplicity of the Principal Role must be '1'.

I found information to add Required to attribute before virtual properites but it did not help.

答:
Because all of the properties in the Dependent Role are non-nullable,
  multiplicity of the Principal Role must be '1'.

Try using int? instead of int.

Body:
I have one class:

[Table(nameof(User), Schema = "Administration")]
public class User : IBaseModel
{
    [Key]
    public int UserId { get; set; }

    #region IBaseModel

    public int AddedBy { get; set; }
    [ForeignKey("AddedBy")]
    public virtual User UserAddedBy { get; set; }

    public int ModifiedBy { get; set; }
    [ForeignKey("ModifiedBy")]
    public virtual User UserModifiedBy { get; set; }

    #endregion
}

I try create self relation for this table (who AddedBy and who ModifiedBy item)

When my class look like above and I try use Add-Migration init on Package Manager Console it returns error:

Unable to determine the principal end of an association between the
  types 'abc.Administration.User' and 'abc.Administration.User'.
  The principal end of this association must be explicitly configured
  using either the relationship fluent API or data annotations.

after this error I try use fluent API and on method OnModelCreating (in my context) I wrote:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Administration.User>().HasOptional(e => e.UserAddedBy).WithMany().HasForeignKey(m => m.AddedBy);
        modelBuilder.Entity<Administration.User>().HasOptional(e => e.UserModifiedBy).WithMany().HasForeignKey(m => m.ModifiedBy);
    }

and again try Add-Migration init but again I saw error message:

One or more validation errors were detected during model generation:

abc.User_UserAddedBy: : Multiplicity conflicts with the referential
  constraint in Role 'User_UserAddedBy_Target' in relationship
  'User_UserAddedBy'. Because all of the properties in the Dependent
  Role are non-nullable, multiplicity of the Principal Role must be '1'.
  abc.User_UserModifiedBy: : Multiplicity conflicts with the referential
  constraint in Role 'User_UserModifiedBy_Target' in relationship
  'User_UserModifiedBy'. Because all of the properties in the Dependent
  Role are non-nullable, multiplicity of the Principal Role must be '1'.

I found information to add Required to attribute before virtual properites but it did not help.


问:
Jest with styled components themeProvider
I'm referring to this github project and I'm trying to write a simple test of KeyPad.js component.

I have seen the issues opened on this matter and one suggested solution is to pass the theme as prop to the component. This solution wouldn't work with enzyme.

The problem in my case is that children components receives the theme through ThemeProvider and to be able to make the test works I would need to add theme prop to all.

Example:

```<code>const tree = renderer.create(
        <KeyPad
            theme={theme}
            cancel={()=> true}
            confirm={()=> true}
            validation={()=> true}
            keyValid={()=>true} />
      ).toJSON();
      expect(tree).toMatchSnapshot();
</code>```

KeyPad's render method would change like this, with theme prop everywhere

```<code>render() {
        let { displayRule, validation, label, confirm, cancel, theme, keyValid, dateFormat } = this.props
        return (
            <Container theme={theme}>
                <Content theme={theme}>
                    <Header theme={theme}>
                        <CancelButton theme={theme} onClick={cancel}>
                            <MdCancel />
                        </CancelButton>
                        <Label>{label}</Label>
                        <ConfirmButton theme={theme} onClick={() => confirm(this.state.input)} disabled={!validation(this.state.input)}>
                            <MdCheck />
                        </ConfirmButton>
                    </Header>
                    <Display
                        theme={theme}
                        value={this.state.input}
                        displayRule={displayRule}
                        dateFormat={dateFormat}
                        cancel={this.cancelLastInsert} />
                    <Keys>
                        {[7, 8, 9, 4, 5, 6, 1, 2, 3, '-', 0, '.'].map( key => (
                            <Button
                                theme={theme}
                                key={`button-${key}`}
                                theme={theme}
                                click={(key) => this.handleClick(key) }
                                value={key}
                                disabled={!keyValid(this.state.input, key, dateFormat)} />
                        ))}
                    </Keys>
                </Content>
            </Container>
        )
    }
</code>```

I don't like this solution. Anybody can help me with this?

Thanks

答:
I would just destructure the callback's props argument and add a default value for theme. This way, any prop you might access from theme will not throw with Cannot read property ... of undefined and will return undefined.
It will mess up your styles but I don't think you care too much about that in your unit tests.

```<code>...
color: ${({ theme = {} }) => theme.background};
...
</code>```

Body:
I'm referring to this github project and I'm trying to write a simple test of KeyPad.js component.

I have seen the issues opened on this matter and one suggested solution is to pass the theme as prop to the component. This solution wouldn't work with enzyme.

The problem in my case is that children components receives the theme through ThemeProvider and to be able to make the test works I would need to add theme prop to all.

Example:

const tree = renderer.create(
        <KeyPad
            theme={theme}
            cancel={()=> true}
            confirm={()=> true}
            validation={()=> true}
            keyValid={()=>true} />
      ).toJSON();
      expect(tree).toMatchSnapshot();

KeyPad's render method would change like this, with theme prop everywhere

render() {
        let { displayRule, validation, label, confirm, cancel, theme, keyValid, dateFormat } = this.props
        return (
            <Container theme={theme}>
                <Content theme={theme}>

                        <CancelButton theme={theme} onClick={cancel}>
                            <MdCancel />
                        </CancelButton>
                        {label}
                        <ConfirmButton theme={theme} onClick={() => confirm(this.state.input)} disabled={!validation(this.state.input)}>
                            <MdCheck />
                        </ConfirmButton>

                    <Display
                        theme={theme}
                        value={this.state.input}
                        displayRule={displayRule}
                        dateFormat={dateFormat}
                        cancel={this.cancelLastInsert} />
                    <Keys>
                        {[7, 8, 9, 4, 5, 6, 1, 2, 3, '-', 0, '.'].map( key => (
                            <Button
                                theme={theme}
                                key={`button-${key}`}
                                theme={theme}
                                click={(key) => this.handleClick(key) }
                                value={key}
                                disabled={!keyValid(this.state.input, key, dateFormat)} />
                        ))}
                    </Keys>
                </Content>
            </Container>
        )
    }

I don't like this solution. Anybody can help me with this?

Thanks

Body:
I would just destructure the callback's props argument and add a default value for theme. This way, any prop you might access from theme will not throw with Cannot read property ... of undefined and will return undefined.
It will mess up your styles but I don't think you care too much about that in your unit tests.

...
color: ${({ theme = {} }) => theme.background};
...


问:
how to set index.html to another page, not homepage
I want to show index.html on special page '/chess', not on home page '/'.

Simple

```<code>app.get('/chess', function(req, res) {
 res.sendFile(__dirname + '/public/index.html');

});
</code>```

doesn't work.

I get the below error

答:
To create more of the "game center" try the approach of making realchess a router that gets imported to the main app.js

below is how I was able to achieve the desired result

rename app.js to chess.js
chess.js

```<code>var express = require('express');
var app = express();
app.use(express.static('public'));
app.use(express.static('dashboard'));
var http = require('http').Server(app);
var io = require('socket.io')(http);
var port = process.env.PORT || 3000;

... rest of code ...

http.listen(port, function() {
    console.log('listening on *: ' + port);
});
</code>```

becomes

```<code>module.exports = function(server){
    var express = require('express');
    var app = express.Router();
    app.use(express.static('public'));
    app.use(express.static('dashboard'));
    var io = require('socket.io')(server);

    ... rest of code ...

    return app;
}
</code>```

remove lines 145-147 and add module.exports = app;

create a new app.js

```<code>const express = require("express");
const app = express();
const http = require('http').Server(app);
const chess = require("./chess")(http);
const port = process.env.PORT || 3000;

app
    .get("/", (req, res) => {
        res.sendFile(__dirname + "/public/selector.html");
    })
    .use("/", express.static("public"))
    .use("/chess",chess);

http.listen(port, function () {
    console.log('listening on *: ' + port);
});
</code>```

this will mound the chess router on the /chess directory, and allow you to mount a selector.html at /.  Following a similar patter you could mount other games

Body:
I want to show index.html on special page '/chess', not on home page '/'.

Simple

app.get('/chess', function(req, res) {
 res.sendFile(__dirname + '/public/index.html');

});

doesn't work.

I get the below error

Body:
To create more of the "game center" try the approach of making realchess a router that gets imported to the main app.js

below is how I was able to achieve the desired result

rename app.js to chess.js
chess.js

var express = require('express');
var app = express();
app.use(express.static('public'));
app.use(express.static('dashboard'));
var http = require('http').Server(app);
var io = require('socket.io')(http);
var port = process.env.PORT || 3000;

... rest of code ...

http.listen(port, function() {
    console.log('listening on *: ' + port);
});

becomes

module.exports = function(server){
    var express = require('express');
    var app = express.Router();
    app.use(express.static('public'));
    app.use(express.static('dashboard'));
    var io = require('socket.io')(server);

    ... rest of code ...

    return app;
}

remove lines 145-147 and add module.exports = app;

create a new app.js

const express = require("express");
const app = express();
const http = require('http').Server(app);
const chess = require("./chess")(http);
const port = process.env.PORT || 3000;

app
    .get("/", (req, res) => {
        res.sendFile(__dirname + "/public/selector.html");
    })
    .use("/", express.static("public"))
    .use("/chess",chess);

http.listen(port, function () {
    console.log('listening on *: ' + port);
});

this will mound the chess router on the /chess directory, and allow you to mount a selector.html at /.  Following a similar patter you could mount other games