问:
Parsing arguments in python with any order
I am trying to parse command line arguments and I have never done it before. I have tried a few things. The code below is the last thing that I tried, but I received the error: "unrecognized arguments". I want to be able to put something like

```<code>copy-column-csv.py cname=Quiz source=source.csv target=target.csv out=out.csv
</code>```

on the command line, but also have the ability to have it in any order. I am not sure how to go about this. Below is my code:

```<code>import argparse
import sys, re
import numpy as np
import smtplib
from random import randint
import csv
import math
import pandas as pd

parser = argparse.ArgumentParser()
parser.add_argument('-cname')
parser.add_argument('-source')
parser.add_argument('-target')
parser.add_argument('-out')
args = parser.parse_args()

#col = sys.argv[1]
#source = sys.argv[2]
#target = sys.argv[3]
#newtarg = sys.argv[4]

sourceFile = pd.read_csv(source)
targetFile = pd.read_csv(target)
del targetFile[cname]
targetFile[col] = pd.Series(sourceFile[col])
targetFile.to_csv(out, index = False)
</code>```

答:
Assuming well formed arguments, you could split sys.argv up into a dictionary:

```<code>args_dict = {}
for arg in sys.argv[1:]:
    split = arg.split('=')
    args_dict[split[0]] = split[1]
</code>```

args_dict will look like this:

```<code>{'cname': 'Quiz',
 'out': 'out.csv',
 'source': 'source.csv',
 'target': 'target.csv'}
</code>```

And you can access the elements like so:

```<code>print args_dict['cname']
print args_dict['out']
print args_dict['source']
print args_dict['target']
</code>```

Body:
I am trying to parse command line arguments and I have never done it before. I have tried a few things. The code below is the last thing that I tried, but I received the error: "unrecognized arguments". I want to be able to put something like

copy-column-csv.py cname=Quiz source=source.csv target=target.csv out=out.csv

on the command line, but also have the ability to have it in any order. I am not sure how to go about this. Below is my code:

import argparse
import sys, re
import numpy as np
import smtplib
from random import randint
import csv
import math
import pandas as pd

parser = argparse.ArgumentParser()
parser.add_argument('-cname')
parser.add_argument('-source')
parser.add_argument('-target')
parser.add_argument('-out')
args = parser.parse_args()

#col = sys.argv[1]
#source = sys.argv[2]
#target = sys.argv[3]
#newtarg = sys.argv[4]

sourceFile = pd.read_csv(source)
targetFile = pd.read_csv(target)
del targetFile[cname]
targetFile[col] = pd.Series(sourceFile[col])
targetFile.to_csv(out, index = False)

Body:
Assuming well formed arguments, you could split sys.argv up into a dictionary:

args_dict = {}
for arg in sys.argv[1:]:
    split = arg.split('=')
    args_dict[split[0]] = split[1]

args_dict will look like this:

{'cname': 'Quiz',
 'out': 'out.csv',
 'source': 'source.csv',
 'target': 'target.csv'}

And you can access the elements like so:

print args_dict['cname']
print args_dict['out']
print args_dict['source']
print args_dict['target']


来源: stackexchange

问:
Mapping this json to java object (pojo)
I have to map a json which would look like this, it's basicly an object, which can contain the same object again as a child, then that one can also contain the same object again. How would i be able to map this to java pojo's?

This is the json:

```<code>    {
"group": [
            {
                "name": "Beheerders",
                "desc": "Beheerders",
                "children" : [
                    "group" : [
                        {
                            "name": "Beheerders",
                            "desc": "Beheerders"
                        },
                        {
                            "name": "Beheerders",
                            "desc": "Beheerders"
                        },
                        {
                            "name": "Beheerders",
                            "desc": "Beheerders"
                            "children": [
                                "group" : [
                                {
                                    "name": "Beheerders",
                                    "desc": "Beheerders"
                                },
                                {
                                    "name": "Beheerders",
                                    "desc": "Beheerders"
                                }
                        }

            }
        ]
    }
</code>```

And i have these 4 pojo's:

Group.java

```<code>        private String name;
        private String desc;
        private Children children;

//getters & Setters & toString
</code>```

GroupList.java

```<code> private ArrayList<Group> group;

    public void setGroup(ArrayList<Group> group) {
        this.group = group;
    }

    public ArrayList<Group> getGroup() {
        return this.group;
    }
</code>```

Children.java

```<code>   private ArrayList<ChildrenGroup> group;

    public ArrayList<ChildrenGroup> getGroup() {
        return this.group;
    }

    public void setGroup(ArrayList<ChildrenGroup> group) {
        this.group = group;
    }
</code>```

childrengroup.java

```<code>    private String name;
    private String desc;
    private Children Children;

//Getters & Setters & toString
</code>```

This is not working for me, i always get this error:

com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token

答:
You can use online tools like jsonschema2pojo to generate POJO from your JSON.

If I'm understanding correctly you are trying to convert smth like the following:

```<code>{
  "g":[
    {
      "a":"1",
      "c":"2"
    },
    {
      "a":"2",
      "c":"3",
      "d":[
        {
          "g":[
            {"a":"3",
            "c":"4"},
            {"a":"5",
            "c":"6"}
            ]
        }
        ]
    }
  ]
}
</code>```

The output for this one will be:

```<code>-----------------------------------com.example.D.java-----------------------------------

package com.example;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class D {

private List<G_> g = null;
private Map<String, Object> additionalProperties = new HashMap<String, Object>();

public List<G_> getG() {
return g;
}

public void setG(List<G_> g) {
this.g = g;
}

public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}

public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}

}
-----------------------------------com.example.Example.java-----------------------------------

package com.example;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Example {

private List<G> g = null;
private Map<String, Object> additionalProperties = new HashMap<String, Object>();

public List<G> getG() {
return g;
}

public void setG(List<G> g) {
this.g = g;
}

public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}

public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}

}
-----------------------------------com.example.G.java-----------------------------------

package com.example;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class G {

private String a;
private String c;
private List<D> d = null;
private Map<String, Object> additionalProperties = new HashMap<String, Object>();

public String getA() {
return a;
}

public void setA(String a) {
this.a = a;
}

public String getC() {
return c;
}

public void setC(String c) {
this.c = c;
}

public List<D> getD() {
return d;
}

public void setD(List<D> d) {
this.d = d;
}

public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}

public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}

}
-----------------------------------com.example.G_.java-----------------------------------

package com.example;

import java.util.HashMap;
import java.util.Map;

public class G_ {

private String a;
private String c;
private Map<String, Object> additionalProperties = new HashMap<String, Object>();

public String getA() {
return a;
}

public void setA(String a) {
this.a = a;
}

public String getC() {
return c;
}

public void setC(String c) {
this.c = c;
}

public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}

public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}

}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Mapping this json to java object (pojo)

Body:
I have to map a json which would look like this, it's basicly an object, which can contain the same object again as a child, then that one can also contain the same object again. How would i be able to map this to java pojo's?

This is the json:

    {
"group": [
            {
                "name": "Beheerders",
                "desc": "Beheerders",
                "children" : [
                    "group" : [
                        {
                            "name": "Beheerders",
                            "desc": "Beheerders"
                        },
                        {
                            "name": "Beheerders",
                            "desc": "Beheerders"
                        },
                        {
                            "name": "Beheerders",
                            "desc": "Beheerders"
                            "children": [
                                "group" : [
                                {
                                    "name": "Beheerders",
                                    "desc": "Beheerders"
                                },
                                {
                                    "name": "Beheerders",
                                    "desc": "Beheerders"
                                }
                        }

            }
        ]
    }

And i have these 4 pojo's:

Group.java

        private String name;
        private String desc;
        private Children children;

//getters & Setters & toString

GroupList.java

 private ArrayList<Group> group;

    public void setGroup(ArrayList<Group> group) {
        this.group = group;
    }

    public ArrayList<Group> getGroup() {
        return this.group;
    }

Children.java

   private ArrayList<ChildrenGroup> group;

    public ArrayList<ChildrenGroup> getGroup() {
        return this.group;
    }

    public void setGroup(ArrayList<ChildrenGroup> group) {
        this.group = group;
    }

childrengroup.java

    private String name;
    private String desc;
    private Children Children;

//Getters & Setters & toString

This is not working for me, i always get this error:

com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token

Body:
You can use online tools like jsonschema2pojo to generate POJO from your JSON.

If I'm understanding correctly you are trying to convert smth like the following:

{
  "g":[
    {
      "a":"1",
      "c":"2"
    },
    {
      "a":"2",
      "c":"3",
      "d":[
        {
          "g":[
            {"a":"3",
            "c":"4"},
            {"a":"5",
            "c":"6"}
            ]
        }
        ]
    }
  ]
}

The output for this one will be:

-----------------------------------com.example.D.java-----------------------------------

package com.example;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class D {

private List<G_> g = null;
private Map<String, Object> additionalProperties = new HashMap<String, Object>();

public List<G_> getG() {
return g;
}

public void setG(List<G_> g) {
this.g = g;
}

public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}

public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}

}
-----------------------------------com.example.Example.java-----------------------------------

package com.example;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Example {

private List<G> g = null;
private Map<String, Object> additionalProperties = new HashMap<String, Object>();

public List<G> getG() {
return g;
}

public void setG(List<G> g) {
this.g = g;
}

public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}

public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}

}
-----------------------------------com.example.G.java-----------------------------------

package com.example;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class G {

private String a;
private String c;
private List<D> d = null;
private Map<String, Object> additionalProperties = new HashMap<String, Object>();

public String getA() {
return a;
}

public void setA(String a) {
this.a = a;
}

public String getC() {
return c;
}

public void setC(String c) {
this.c = c;
}

public List<D> getD() {
return d;
}

public void setD(List<D> d) {
this.d = d;
}

public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}

public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}

}
-----------------------------------com.example.G_.java-----------------------------------

package com.example;

import java.util.HashMap;
import java.util.Map;

public class G_ {

private String a;
private String c;
private Map<String, Object> additionalProperties = new HashMap<String, Object>();

public String getA() {
return a;
}

public void setA(String a) {
this.a = a;
}

public String getC() {
return c;
}

public void setC(String c) {
this.c = c;
}

public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}

public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}

}


问:
php 'ISSET' function not working. OR the code skips my if statements
The not working and i get the same error output as defined in the last else statement.

I am new to Php, please help me out. What am I doing wrong?

HERE IS THE CODE

```<code><form action="imagespace.php?groupid=<?php echo $_GET['groupid'] ;?>" method = "POST">
<input type="button" name="Up-Vote" value ="Up-Vote" class="up-votes" />
<input type="button" name="Down-Vote" value="Down-Vote" class="down-votes" />
</form>
<?php

$emailid=$_SESSION['emailid'];
$groupid = $_GET['groupid'];
$emailid = mysqli_real_escape_string($con,$emailid);
$groupid = mysqli_real_escape_string($con,$emailid);

if(isset($_POST['Up-Vote']))
    { echo ' trial';
    $query = "INSERT into VOTES (emailid, groupid, vote) values ('$emailid','$groupid', '1') ";
    $query_run = mysqli_query($con,$query);
    if($query_run)
    {echo 'upvoted';}
    }

else if(isset($_POST['Down-Vote']))
    {
        $query = "INSERT into VOTES (emailid, groupid, vote) values ('$emailid','$groupid', '0') ";
        $query_run = mysqli_query($con,$query);
        if($query_run)
        {echo 'downvoted';}
    }
else{
echo 'error' ;
}
}
?>

</body>
</html>
</code>```

答:
In addition to the supplied answer(s), I would like to suggest doin the following:

```<code>// Before anything else, start your session
if (!isset($_SESSION)) {
    session_start();
}

// Next, check if your form is actually submitted
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['...'])) {

    } elseif (isset($_POST['...'])) {

    }
}
?>

<!-- Keep PHP and html seperated -->
<form>
...
</form>
</code>```

By looking at your form, i notice that you are using type='button'. I suggest one of the following:

```<code><input type="submit" ... />

<button type="submit">...</button>
</code>```

Body:
The not working and i get the same error output as defined in the last else statement.

I am new to Php, please help me out. What am I doing wrong?

HERE IS THE CODE

<form action="imagespace.php?groupid=<?php echo $_GET['groupid'] ;?>" method = "POST">
<input type="button" name="Up-Vote" value ="Up-Vote" class="up-votes" />
<input type="button" name="Down-Vote" value="Down-Vote" class="down-votes" />
</form>
<?php

$emailid=$_SESSION['emailid'];
$groupid = $_GET['groupid'];
$emailid = mysqli_real_escape_string($con,$emailid);
$groupid = mysqli_real_escape_string($con,$emailid);

if(isset($_POST['Up-Vote']))
    { echo ' trial';
    $query = "INSERT into VOTES (emailid, groupid, vote) values ('$emailid','$groupid', '1') ";
    $query_run = mysqli_query($con,$query);
    if($query_run)
    {echo 'upvoted';}
    }

else if(isset($_POST['Down-Vote']))
    {
        $query = "INSERT into VOTES (emailid, groupid, vote) values ('$emailid','$groupid', '0') ";
        $query_run = mysqli_query($con,$query);
        if($query_run)
        {echo 'downvoted';}
    }
else{
echo 'error' ;
}
}
?>

Body:
In addition to the supplied answer(s), I would like to suggest doin the following:

// Before anything else, start your session
if (!isset($_SESSION)) {
    session_start();
}

// Next, check if your form is actually submitted
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['...'])) {

    } elseif (isset($_POST['...'])) {

    }
}
?>

<!-- Keep PHP and html seperated -->
<form>
...
</form>

By looking at your form, i notice that you are using type='button'. I suggest one of the following:

<input type="submit" ... />

<button type="submit">...</button>


问:
How to listen to topic using spring boot jms
I am trying to listen to topic using the below snippet. However its listening to queue by default. There is no xml config in this case. I am completely relying on annotations. Moreover I have relied completely on the AutoConfiguration provided by Spring boot. I am not sure how to set the destination type as topic, In JmsListener. Spring JMS gurus please help.</p>

```<code>    @Component
    public class MyTopicListener {

        @JmsListener(destination = "${trans.alert.topic}")
        public void receiveMessage(TransactionAlert alert) {
            logger.info("AlertSubscriberEmail :: Sending Email => <" + alert + ">");
        }
    }
</code>```

答:
The answer marked correct is ALMOST correct. It still wont work because:

```<code>factory.setPubSubDomain(true)
</code>```

must come AFTER:

```<code>configurer.configure(factory, connectionFactory);
</code>```

Otherwise the pubSubDomain flag being set to true is lost when configuring the defaults and that factory instance will still work with queues and not topics.

Body:
I am trying to listen to topic using the below snippet. However its listening to queue by default. There is no xml config in this case. I am completely relying on annotations. Moreover I have relied completely on the AutoConfiguration provided by Spring boot. I am not sure how to set the destination type as topic, In JmsListener. Spring JMS gurus please help.

    @Component
    public class MyTopicListener {

        @JmsListener(destination = "${trans.alert.topic}")
        public void receiveMessage(TransactionAlert alert) {
            logger.info("AlertSubscriberEmail :: Sending Email => <" + alert + ">");
        }
    }

Body:
The answer marked correct is ALMOST correct. It still wont work because:

factory.setPubSubDomain(true)

must come AFTER:

configurer.configure(factory, connectionFactory);

Otherwise the pubSubDomain flag being set to true is lost when configuring the defaults and that factory instance will still work with queues and not topics.


问:
Duplicate entry for key 'PRIMARY' php
I have the following datatables:

When I enter the data to the participantes_atividades table it shows me this error:

Duplicate entry for key 'PRIMARY

```<code>$sql = "INSERT INTO participantes_atividades (cd_p,cd_ati) VALUES ('$p','$cd')";

if (mysqli_query($connect, $sql) or die (mysqli_error($connect)))
</code>```

答:
Problem solved, i had the click event repeated and it was
duplo registo do evento click sobre o elemento, e consequente dupla chamada do ajax para remover e adicionar o registo</p>

Title: Duplicate entry for key 'PRIMARY' php

Body:
I have the following datatables:

When I enter the data to the participantes_atividades table it shows me this error:

Duplicate entry for key 'PRIMARY

$sql = "INSERT INTO participantes_atividades (cd_p,cd_ati) VALUES ('$p','$cd')";

if (mysqli_query($connect, $sql) or die (mysqli_error($connect)))


问:
is it possible to know if the url is redirecting
I'm developing in java an application which verifies if one site is online.
I get the http response by:

```<code>URL url = new URL("http://www.example.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
</code>```

But when I access the URL it is redirecting and the HTTP response is always 301. I want to get the new URL that the site was redirected. Is it possible?

答:
You can access to the header using this :</p>

```<code>String redirectUrl = connection.getHeaderField("Location");
</code>```

Body:
I'm developing in java an application which verifies if one site is online.
I get the http response by:

URL url = new URL("http://www.example.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();

But when I access the URL it is redirecting and the HTTP response is always 301. I want to get the new URL that the site was redirected. Is it possible?

Body:
You can access to the header using this :

String redirectUrl = connection.getHeaderField("Location");


问:
How do I print the elements in a list in a loop?
I'm trying to understand how for loops work. I create a list which looks like below:

```<code>> ldf

[[1]] [1] "David_T2.png"

[[2]] [1] "David_T3.png"

[[3]] [1] "COLOn_T2.png"

[[4]] [1] "COLOn_T4.png"
</code>```

and create a loop like this:

```<code>for (i in 1:length(ldf)){
 for (j in 2:length(ldf)){
 print(ldf[[i]])
 print(ldf[[j]])
}
}
</code>```

But I don't get the expected result I would like that it prints the first, then the second, then the thirds file and so on; instead, I obtain this:

```<code>[1] "David_T2.png"
[1] "David_T3.png"
[1] "David_T2.png"
[1] "COLOn_T2.png"
[1] "David_T2.png"
[1] "COLOn_T4.png"
[1] "David_T2.png"
</code>```

And I can't understand why.

答:
You only need a single loop to iterate over the elements. Having a second, nested loop causes your innermost statements to be executed for each pair of elements in the list, rather than for each element once.

Furthermore, there’s no need to iterate over indices; you can iterate over the list items directly:

```<code>for (item in ldf) {
    message(item)
}
</code>```

Note that I’ve used message instead of print here, as this is more suitable.

However, this can also be written without a loop, by using lapply: lapply is a function that takes another function (here, print), and just calls it on every element:

```<code>lapply(ldf, message)
</code>```

Body:
I'm trying to understand how for loops work. I create a list which looks like below:

> ldf

[[1]] [1] "David_T2.png"

[[2]] [1] "David_T3.png"

[[3]] [1] "COLOn_T2.png"

[[4]] [1] "COLOn_T4.png"

and create a loop like this:

for (i in 1:length(ldf)){
 for (j in 2:length(ldf)){
 print(ldf[[i]])
 print(ldf[[j]])
}
}

But I don't get the expected result I would like that it prints the first, then the second, then the thirds file and so on; instead, I obtain this:

[1] "David_T2.png"
[1] "David_T3.png"
[1] "David_T2.png"
[1] "COLOn_T2.png"
[1] "David_T2.png"
[1] "COLOn_T4.png"
[1] "David_T2.png"

And I can't understand why.

Body:
You only need a single loop to iterate over the elements. Having a second, nested loop causes your innermost statements to be executed for each pair of elements in the list, rather than for each element once.

Furthermore, there’s no need to iterate over indices; you can iterate over the list items directly:

for (item in ldf) {
    message(item)
}

Note that I’ve used message instead of print here, as this is more suitable.

However, this can also be written without a loop, by using lapply: lapply is a function that takes another function (here, print), and just calls it on every element:

lapply(ldf, message)


问:
Can I use `tf.nn.dropout` to implement DropConnect?
I (think) that I grasp the basics of DropOut and the use of the TensorFlow API in implementing it. But the normalization that's linked to the dropout probability in tf.nn.dropout seems not to be a part of DropConnect. Is that correct? If so, does normalizing do any "harm" or can I simply apply tf.nn.dropout to my weights to implement DropConnect?

答:
Answer

Yes, you can use tf.nn.dropout to do DropConnect, just use tf.nn.dropout to wrap your weight matrix instead of your post matrix multiplication.  You can then undo the weight change by multiplying by the dropout like so

```<code>dropConnect = tf.nn.dropout( m1, keep_prob ) * keep_prob
</code>```

Code Example

Here is a code example that calculates the XOR function using drop connect.  I've also commented out the code that does dropout that you can sub in and compare the output.

```<code>### imports
import tensorflow as tf

### constant data
x  = [[0.,0.],[1.,1.],[1.,0.],[0.,1.]]
y_ = [[1.,0.],[1.,0.],[0.,1.],[0.,1.]]

### induction

# Layer 0 = the x2 inputs
x0 = tf.constant( x  , dtype=tf.float32 )
y0 = tf.constant( y_ , dtype=tf.float32 )

keep_prob = tf.placeholder( dtype=tf.float32 )

# Layer 1 = the 2x12 hidden sigmoid
m1 = tf.Variable( tf.random_uniform( [2,12] , minval=0.1 , maxval=0.9 , dtype=tf.float32  ))
b1 = tf.Variable( tf.random_uniform( [12]   , minval=0.1 , maxval=0.9 , dtype=tf.float32  ))

########## DROP CONNECT
# - use this to preform "DropConnect" flavor of dropout
dropConnect = tf.nn.dropout( m1, keep_prob ) * keep_prob
h1 = tf.sigmoid( tf.matmul( x0, dropConnect ) + b1 )

########## DROP OUT
# - uncomment this to use "regular" dropout
#h1 = tf.nn.dropout( tf.sigmoid( tf.matmul( x0,m1 ) + b1 ) , keep_prob )

# Layer 2 = the 12x2 softmax output
m2 = tf.Variable( tf.random_uniform( [12,2] , minval=0.1 , maxval=0.9 , dtype=tf.float32  ))
b2 = tf.Variable( tf.random_uniform( [2]   , minval=0.1 , maxval=0.9 , dtype=tf.float32  ))
y_out = tf.nn.softmax( tf.matmul( h1,m2 ) + b2 )

# loss : sum of the squares of y0 - y_out
loss = tf.reduce_sum( tf.square( y0 - y_out ) )

# training step : discovered learning rate of 1e-2 through experimentation
train = tf.train.AdamOptimizer(1e-2).minimize(loss)

### training
# run 5000 times using all the X and Y
# print out the loss and any other interesting info
with tf.Session() as sess:
  sess.run( tf.initialize_all_variables() )
  print "\nloss"
  for step in range(5000) :
    sess.run(train,feed_dict={keep_prob:0.5})
    if (step + 1) % 100 == 0 :
      print sess.run(loss,feed_dict={keep_prob:1.})

  results = sess.run([m1,b1,m2,b2,y_out,loss],feed_dict={keep_prob:1.})
  labels  = "m1,b1,m2,b2,y_out,loss".split(",")
  for label,result in zip(*(labels,results)) :
    print ""
    print label
    print result

print ""
</code>```

Output

Both flavors are able to correctly separate the input into the correct output

```<code>y_out
[[  7.05891490e-01   2.94108540e-01]
 [  9.99605477e-01   3.94574134e-04]
 [  4.99370173e-02   9.50062990e-01]
 [  4.39682379e-02   9.56031740e-01]]
</code>```

Here you can see the output from dropConnect was able to correctly classify Y as true,true,false,false.

Body:
Answer

Yes, you can use tf.nn.dropout to do DropConnect, just use tf.nn.dropout to wrap your weight matrix instead of your post matrix multiplication.  You can then undo the weight change by multiplying by the dropout like so

dropConnect = tf.nn.dropout( m1, keep_prob ) * keep_prob

Code Example

Here is a code example that calculates the XOR function using drop connect.  I've also commented out the code that does dropout that you can sub in and compare the output.

### imports
import tensorflow as tf

### constant data
x  = [[0.,0.],[1.,1.],[1.,0.],[0.,1.]]
y_ = [[1.,0.],[1.,0.],[0.,1.],[0.,1.]]

### induction

# Layer 0 = the x2 inputs
x0 = tf.constant( x  , dtype=tf.float32 )
y0 = tf.constant( y_ , dtype=tf.float32 )

keep_prob = tf.placeholder( dtype=tf.float32 )

# Layer 1 = the 2x12 hidden sigmoid
m1 = tf.Variable( tf.random_uniform( [2,12] , minval=0.1 , maxval=0.9 , dtype=tf.float32  ))
b1 = tf.Variable( tf.random_uniform( [12]   , minval=0.1 , maxval=0.9 , dtype=tf.float32  ))

########## DROP CONNECT
# - use this to preform "DropConnect" flavor of dropout
dropConnect = tf.nn.dropout( m1, keep_prob ) * keep_prob
h1 = tf.sigmoid( tf.matmul( x0, dropConnect ) + b1 )

########## DROP OUT
# - uncomment this to use "regular" dropout
#h1 = tf.nn.dropout( tf.sigmoid( tf.matmul( x0,m1 ) + b1 ) , keep_prob )

# Layer 2 = the 12x2 softmax output
m2 = tf.Variable( tf.random_uniform( [12,2] , minval=0.1 , maxval=0.9 , dtype=tf.float32  ))
b2 = tf.Variable( tf.random_uniform( [2]   , minval=0.1 , maxval=0.9 , dtype=tf.float32  ))
y_out = tf.nn.softmax( tf.matmul( h1,m2 ) + b2 )

# loss : sum of the squares of y0 - y_out
loss = tf.reduce_sum( tf.square( y0 - y_out ) )

# training step : discovered learning rate of 1e-2 through experimentation
train = tf.train.AdamOptimizer(1e-2).minimize(loss)

### training
# run 5000 times using all the X and Y
# print out the loss and any other interesting info
with tf.Session() as sess:
  sess.run( tf.initialize_all_variables() )
  print "\nloss"
  for step in range(5000) :
    sess.run(train,feed_dict={keep_prob:0.5})
    if (step + 1) % 100 == 0 :
      print sess.run(loss,feed_dict={keep_prob:1.})

  results = sess.run([m1,b1,m2,b2,y_out,loss],feed_dict={keep_prob:1.})
  labels  = "m1,b1,m2,b2,y_out,loss".split(",")
  for label,result in zip(*(labels,results)) :
    print ""
    print label
    print result

print ""

Output

Both flavors are able to correctly separate the input into the correct output

y_out
[[  7.05891490e-01   2.94108540e-01]
 [  9.99605477e-01   3.94574134e-04]
 [  4.99370173e-02   9.50062990e-01]
 [  4.39682379e-02   9.56031740e-01]]

Here you can see the output from dropConnect was able to correctly classify Y as true,true,false,false.


问:
Is @$array['possibly_missing_key'] an anti-pattern?
Is it OK to use @ when extracting a possibly missing value from a PHP array? Example:

```<code>$value = @$array['possibly_missing_key'];
</code>```

The intended behavior:

```<code>if (isset($array['possibly_missing_key'])) {
    $value = $array['possibly_missing_key'];
} else {
    $value = null;
}
</code>```

I want to know, before spreading the usage pattern.

答:
The third option:

```<code>$value = (isset($array['key']) ? $array['key'] : null);
</code>```

I know this doesn't directly answer the question; I would have put it as a comment, except it really needed to be formatted.

The idea here is that if you're trying to make your code shorter by using a one-liner instead of an if-else block, then you can still get it into a succinct one-liner using a ternary operator, giving you the best of both worlds.

ContentLicense: CC BY-SA 2.5

Body:
Is it OK to use @ when extracting a possibly missing value from a PHP array? Example:

$value = @$array['possibly_missing_key'];

The intended behavior:

if (isset($array['possibly_missing_key'])) {
    $value = $array['possibly_missing_key'];
} else {
    $value = null;
}

I want to know, before spreading the usage pattern.

Body:
The third option:

$value = (isset($array['key']) ? $array['key'] : null);

I know this doesn't directly answer the question; I would have put it as a comment, except it really needed to be formatted.

The idea here is that if you're trying to make your code shorter by using a one-liner instead of an if-else block, then you can still get it into a succinct one-liner using a ternary operator, giving you the best of both worlds.


问:
How to display empty chart instead of "no data available" in ssrs 2008
I inserted a pie chart in my SSRS 2008 report. When there is no data coming from sql, it basically shows "no data available", but what I would like it to display is an empty chart instead. I could not find a way to provide this. Any help would be appreciated</p>

答:
This is how I solved the problem for myself, though I was not using a pie chart. For my dataset query, I'd add a column called ShowRow. For any valid data, the ShowRow value would be 1. I would union that data with a row that matched the original data and if we had valid data, then showRow would be zero, else 1.

```<code>WITH ChartData as
(
SELECT Sales, Month, Year, 1 as ShowRow
)
SELECT * FROM ChartData
UNION
SELECT NULL,NULL,NULL,
CASE WHEN (SELECT COUNT(*) FROM ChartData) > 0
    THEN 0
    ELSE 1
END as ShowRow
</code>```

Then in the dataset properties, I added a filter to only show rows where ShowRow = 1. This nicely showed my legend values and chart frame without showing any data.

Body:
This is how I solved the problem for myself, though I was not using a pie chart. For my dataset query, I'd add a column called ShowRow. For any valid data, the ShowRow value would be 1. I would union that data with a row that matched the original data and if we had valid data, then showRow would be zero, else 1.

WITH ChartData as
(
SELECT Sales, Month, Year, 1 as ShowRow
)
SELECT * FROM ChartData
UNION
SELECT NULL,NULL,NULL,
CASE WHEN (SELECT COUNT(*) FROM ChartData) > 0
    THEN 0
    ELSE 1
END as ShowRow

Then in the dataset properties, I added a filter to only show rows where ShowRow = 1. This nicely showed my legend values and chart frame without showing any data.


问:
Programmatically Navigate using react-router
I am developing an application in which I check if the user is not loggedIn. I have to display the login form, else dispatch an action that would change the route and load other component. Here is my code:

render() {
    if (isLoggedIn) {
        // dispatch an action to change the route
    }
    // return login component
    <Login />
}
```

How can I achieve this as I cannot change states inside the render function.

答:
In react-router version 4:</p>

```<code>import React from 'react'
import { BrowserRouter as Router, Route, Redirect} from 'react-router-dom'

const Example = () => (

  if (isLoggedIn) {
    <OtherComponent />

  } else {

    <Router>
      <Redirect push to="/login" />
      <Route path="/login" component={Login}/>
    </Router>

  }
)

const Login = () => (
    <h1>Form Components</h1>
    ...
)

export default Example;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am developing an application in which I check if the user is not loggedIn. I have to display the login form, else dispatch an action that would change the route and load other component. Here is my code:

render() {
    if (isLoggedIn) {
        // dispatch an action to change the route
    }
    // return login component
    <Login />
}

How can I achieve this as I cannot change states inside the render function.

Body:
In react-router version 4:

import React from 'react'
import { BrowserRouter as Router, Route, Redirect} from 'react-router-dom'

const Example = () => (

  if (isLoggedIn) {
    <OtherComponent />

  } else {

    <Router>
      <Redirect push to="/login" />
      <Route path="/login" component={Login}/>
    </Router>

  }
)

const Login = () => (
    <h1>Form Components</h1>
    ...
)

export default Example;


问:
LINQ to SQL: Reusing DataContext
I have a number of static methods that perform simple operations like insert or delete a record. All these methods follow this template of using:

```<code>public static UserDataModel FromEmail(string email)
{
    using (var db = new MyWebAppDataContext())
    {
        db.ObjectTrackingEnabled = false;
        return (from u in db.UserDataModels
                where u.Email == email
                select u).Single();
    }
}
</code>```

I also have a few methods that need to perform multiple operations that use a DataContext:

```<code>public static UserPreferencesDataModel Preferences(string email)
{
    return UserDataModel.Preferences(UserDataModel.FromEmail(email));
}

private static UserPreferencesViewModel Preferences(UserDataModel user)
{
    using(var db = new MyWebAppDataContext())
    {
        var preferences = (from u in db.UserDataModels
                          where u == user
                          select u.Preferences).Single();

        return new UserPreferencesViewModel(preferences);
    }
}
</code>```

I like that I can divide simple operations into faux-stored procedures in my data models with static methods like FromEmail(), but I'm concerned about the cost of having Preferences() invoking two connections (right?) via the two using DataContext statements.

Do I need to be? Is what I'm doing less efficient than using a single using(var db = new MyWebAppDataContext()) statement?

答: I also think creating a new DataContext each time is the correct way but this link explains different approaches for handling the data context. Linq to SQL DataContext Lifetime Management</p>

Title: LINQ to SQL: Reusing DataContext

Body:
I have a number of static methods that perform simple operations like insert or delete a record. All these methods follow this template of using:

public static UserDataModel FromEmail(string email)
{
    using (var db = new MyWebAppDataContext())
    {
        db.ObjectTrackingEnabled = false;
        return (from u in db.UserDataModels
                where u.Email == email
                select u).Single();
    }
}

I also have a few methods that need to perform multiple operations that use a DataContext:

public static UserPreferencesDataModel Preferences(string email)
{
    return UserDataModel.Preferences(UserDataModel.FromEmail(email));
}

private static UserPreferencesViewModel Preferences(UserDataModel user)
{
    using(var db = new MyWebAppDataContext())
    {
        var preferences = (from u in db.UserDataModels
                          where u == user
                          select u.Preferences).Single();

        return new UserPreferencesViewModel(preferences);
    }
}

I like that I can divide simple operations into faux-stored procedures in my data models with static methods like FromEmail(), but I'm concerned about the cost of having Preferences() invoking two connections (right?) via the two using DataContext statements.

Do I need to be? Is what I'm doing less efficient than using a single using(var db = new MyWebAppDataContext()) statement?


问:
How to define configparser in python 3
I'm working on a project that will log into the site and will comment the user generated content.

I use selenium, chrome driver and python 3. All credentials user name, password and chromedriver location is configured in a separate config.ini file.

Here's the python script:

```<code>#!/usr/bin/python
import os
import time
import getpass
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from configparser import ConfigParser

# Reading configuration file
config = configparser.ConfigParser()
config.sections()

parser = ConfigParser()
parser.read('config.ini')
parameters = {}

for pairs in parser.sections():         # Parse the configuration file
    for name, value in parser.items(pairs):
        parameters[name] = value

# Automating your browser
chromedriver  = parameters["path"]
os.environ["webdriver.chrome.driver"] = chromedriver

#Uncomment this block if you don't want images to load(makes the procss a little bit faster)
'''
chromeOptions = webdriver.ChromeOptions()
prefs = {"profile.managed_default_content_settings.images":2}
chromeOptions.add_experimental_option("prefs",prefs)
browser = webdriver.Chrome(chromedriver, chrome_options=chromeOptions)
'''

browser = webdriver.Chrome(chromedriver)
browser.set_window_size(1120, 550)
browser.get("http://www.website.com")       # website home page
time.sleep(3)

# Logging into website
form = browser.find_element_by_class_name('regular_login')
email = form.find_element_by_name("email")
password = form.find_element_by_name("password")
email.send_keys(parameters["email_id"])
try:
    pass_word = parameters["pass_word"]
except:
    pass_word = getpass.getpass()               # If you want to enter password on terminal
password.send_keys(pass_word)
password.send_keys(Keys.RETURN)
time.sleep(2)

# Fetching answers page of t6he user
answers_url = "https://www.website.com/" + parameters["username"] + "/answers"
browser.get(answers_url)

 #commenting answers one by one from top to bottom
counter=0
while True:
    try:
        elem=browser.find_element_by_xpath("//*[@action_click='enter']")
        counter=counter+1
        elem.click()
        time.sleep(4)
    except:
        break

print (str(counter) +" answers commented..")
</code>```

I keep getting,

```<code> config = configparser.ConfigParser()
NameError: name 'configparser' is not defined
</code>```

Please, can anyone answer how can I define the configure.

答:
This error occurs because you haven't actually imported configparser. You have imported something from configparser but haven't actually imported configparser itself.

There are two solutions for this.

1) You can either define it by importing the module. import configparser

2) Or do as you have done 3 lines down from the error and use config = ConfigParser()

If you are using other parts of configparser then I would recommend to import the whole module and go with option 1. If you're only using ConfigParser then I would go with option 2.

Title: How to define configparser in python 3

Body:
I'm working on a project that will log into the site and will comment the user generated content.

I use selenium, chrome driver and python 3. All credentials user name, password and chromedriver location is configured in a separate config.ini file.

Here's the python script:

#!/usr/bin/python
import os
import time
import getpass
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from configparser import ConfigParser

# Reading configuration file
config = configparser.ConfigParser()
config.sections()

parser = ConfigParser()
parser.read('config.ini')
parameters = {}

for pairs in parser.sections():         # Parse the configuration file
    for name, value in parser.items(pairs):
        parameters[name] = value

# Automating your browser
chromedriver  = parameters["path"]
os.environ["webdriver.chrome.driver"] = chromedriver

#Uncomment this block if you don't want images to load(makes the procss a little bit faster)
'''
chromeOptions = webdriver.ChromeOptions()
prefs = {"profile.managed_default_content_settings.images":2}
chromeOptions.add_experimental_option("prefs",prefs)
browser = webdriver.Chrome(chromedriver, chrome_options=chromeOptions)
'''

browser = webdriver.Chrome(chromedriver)
browser.set_window_size(1120, 550)
browser.get("http://www.website.com")       # website home page
time.sleep(3)

# Logging into website
form = browser.find_element_by_class_name('regular_login')
email = form.find_element_by_name("email")
password = form.find_element_by_name("password")
email.send_keys(parameters["email_id"])
try:
    pass_word = parameters["pass_word"]
except:
    pass_word = getpass.getpass()               # If you want to enter password on terminal
password.send_keys(pass_word)
password.send_keys(Keys.RETURN)
time.sleep(2)

# Fetching answers page of t6he user
answers_url = "https://www.website.com/" + parameters["username"] + "/answers"
browser.get(answers_url)

 #commenting answers one by one from top to bottom
counter=0
while True:
    try:
        elem=browser.find_element_by_xpath("//*[@action_click='enter']")
        counter=counter+1
        elem.click()
        time.sleep(4)
    except:
        break

print (str(counter) +" answers commented..")

I keep getting,

 config = configparser.ConfigParser()
NameError: name 'configparser' is not defined

Please, can anyone answer how can I define the configure.


问:
ADB Install Fails With INSTALL_FAILED_TEST_ONLY
I am having issues installing an apk to my device.

```<code>adb install <.apk>
</code>```

Using the above command returns the following:

```<code>5413 KB/s (99747 bytes in 0.017s)
        pkg: /data/local/tmp/AppClient.TestOnly.App3.apk
Failure [INSTALL_FAILED_TEST_ONLY]
</code>```

Any idea on what might cause this issue?

It definitely recognizes the device.  Could it be an issue with the apk?

答:
In my case was by uploading an APK, that although it was signed with production certificate and was a release variant, was generated by the run play button from Android studio.
Problem solved after generating APK from Gradle or from Build APK menu option.</p>

Body:
I am having issues installing an apk to my device.

adb install <.apk>

Using the above command returns the following:

5413 KB/s (99747 bytes in 0.017s)
        pkg: /data/local/tmp/AppClient.TestOnly.App3.apk
Failure [INSTALL_FAILED_TEST_ONLY]

Any idea on what might cause this issue?

It definitely recognizes the device.  Could it be an issue with the apk?


问:
w3c markup validator ampersand (&) error
Is there any workaround for the w3c validation error for an & present in urls or some other place in HTML markup?

It says:

& did not start a character reference. (& probably should have been escaped as &.)

The ampersand in my case is a part of a url for gravatar thumbnail. This is the problematic part of a url:

c91588793296e2?s=50&d=http%3A%2F%.

答:
Use & for literal ampersands, even in URLs.

http://htmlhelp.com/tools/validator/problems.html#amp

Body:
Use &amp; for literal ampersands, even in URLs.

http://htmlhelp.com/tools/validator/problems.html#amp


问:
.htaccess Removing .php from URL and add trailing slash
I have a filesystem of PHP files and folder and want to make the URLs nicer but can't seem to find the right combo. This works to make the admin.php work as just admin but I can't find a good way to add the trailing slash and redirect it to the pretty URL if someone hits the PHP URL.

```<code>#Remove .php
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule !.*\.php$ %{REQUEST_FILENAME}.php [L]
</code>```

Wanted:

```<code>domain/admin.php => domain/admin/
domain/admin     => domain/admin/
</code>```

Virtual and Real subfolders too?

```<code> domain/folder/   => loads index.php if exists otherwise loads folder.php in root
</code>```

If anyone has any tips I'd appreciate it!

Thanks!

答:
You can solve all 3 tasks using these 2 rewrite rules in your site root .htaccess:</p>

```<code>RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule [^/]$ %{REQUEST_URI}/ [L,R=301]

RewriteCond %{DOCUMENT_ROOT}/$1/index.php !-f
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^(.+?)/?$ $1.php [L]
</code>```

Body:
I have a filesystem of PHP files and folder and want to make the URLs nicer but can't seem to find the right combo. This works to make the admin.php work as just admin but I can't find a good way to add the trailing slash and redirect it to the pretty URL if someone hits the PHP URL.

#Remove .php
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule !.*\.php$ %{REQUEST_FILENAME}.php [L]

Wanted:

domain/admin.php => domain/admin/
domain/admin     => domain/admin/

Virtual and Real subfolders too?

 domain/folder/   => loads index.php if exists otherwise loads folder.php in root

If anyone has any tips I'd appreciate it!

Thanks!

Body:
You can solve all 3 tasks using these 2 rewrite rules in your site root .htaccess:

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule [^/]$ %{REQUEST_URI}/ [L,R=301]

RewriteCond %{DOCUMENT_ROOT}/$1/index.php !-f
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^(.+?)/?$ $1.php [L]


问:
Importing external js library in Vue.js Single File Component
I have the following Single File Component in Vue.js.

The plasmid tag is meant to get rendered by the angularplasmid.complete.min.js file but isn't for some reason. Is this the correct way to import a library in a component?

I am restructuring an old Vue project to be better designed but I know that the plasmid tag renders on here (which doesn't use single file components): https://github.com/asselinpaul/dnaviewer/blob/master/app/index.html

Any help much appreciated.

```<code><template>
<div id="DNA Plasmid">
    <h3>Plasmid Visualisation</h3>
    <div class="section">
        <plasmid id='p1' plasmidheight="800" plasmidwidth="800" v-bind:sequencelength="sequenceLength">
            <plasmidtrack id='t1' radius="200" width="55">
                <trackmarker v-for="(bound, index) in bounds" class='marker' v-bind:start="bound.start" v-bind:end="bound.end" v-bind:style="{ fill: bound.color }" v-bind:key="bound.start">
                    <markerlabel v-bind:text="bound.name" v-bind:vadjust='bound.vadjust' style='font-size:12px'></markerlabel>
                </trackmarker>
                <tracklabel v-bind:text="name" style='font-size:25px;font-weight:bold'></tracklabel>
            </plasmidtrack>
        </plasmid>
    </div>
</div>

</template>

<script>
import './angularplasmid.complete.min.js'

...
</code>```

答:
You definitely can't reasonably combine angular functions with Vue. Plus, angular use its own dependency system.

Beside, you can use import in a single-file component exactly the same way than in any script. But of course be sure that your imported script is actually exporting something (or is relevant to execute as a module, which is probably not the case here).

Here is a reminder of the syntax:

```<code>import defaultMember from "module-name";
import * as name from "module-name";
import { member } from "module-name";
import { member as alias } from "module-name";
import { member1 , member2 } from "module-name";
import { member1 , member2 as alias2 , [...] } from "module-name";
import defaultMember, { member [ , [...] ] } from "module-name";
import defaultMember, * as name from "module-name";
import "module-name";
</code>```

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import

Note that the commonJS require() and module.exports are also perfectly fine in a single-file component.

Body:
I have the following Single File Component in Vue.js.

The plasmid tag is meant to get rendered by the angularplasmid.complete.min.js file but isn't for some reason. Is this the correct way to import a library in a component?

I am restructuring an old Vue project to be better designed but I know that the plasmid tag renders on here (which doesn't use single file components): https://github.com/asselinpaul/dnaviewer/blob/master/app/index.html

Any help much appreciated.

<template>

Plasmid Visualisation

        <plasmid id='p1' plasmidheight="800" plasmidwidth="800" v-bind:sequencelength="sequenceLength">
            <plasmidtrack id='t1' radius="200" width="55">
                <trackmarker v-for="(bound, index) in bounds" class='marker' v-bind:start="bound.start" v-bind:end="bound.end" v-bind:style="{ fill: bound.color }" v-bind:key="bound.start">
                    <markerlabel v-bind:text="bound.name" v-bind:vadjust='bound.vadjust' style='font-size:12px'></markerlabel>
                </trackmarker>
                <tracklabel v-bind:text="name" style='font-size:25px;font-weight:bold'></tracklabel>
            </plasmidtrack>
        </plasmid>

</template>

Body:
You definitely can't reasonably combine angular functions with Vue. Plus, angular use its own dependency system.

Beside, you can use import in a single-file component exactly the same way than in any script. But of course be sure that your imported script is actually exporting something (or is relevant to execute as a module, which is probably not the case here).

Here is a reminder of the syntax:

import defaultMember from "module-name";
import * as name from "module-name";
import { member } from "module-name";
import { member as alias } from "module-name";
import { member1 , member2 } from "module-name";
import { member1 , member2 as alias2 , [...] } from "module-name";
import defaultMember, { member [ , [...] ] } from "module-name";
import defaultMember, * as name from "module-name";
import "module-name";

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import

Note that the commonJS require() and module.exports are also perfectly fine in a single-file component.


问:
why does java Charset need extra import?
I am teaching myself a little about Files and I/O in Java, based on this tutorial: Oracle Tutorial

Now, after writing some examples to understand input and output, I got a question regarding the import of certain libraries.

I created the following example program, and I ask myself why the program says:

Cannot find symbol - class Charset

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

public class test
{

public static void main(String[] args)
{
    Charset charset = Charset.forName("US-ASCII");
}

}
</code>```

I know that the solution is to import the following
    import java.nio.charset.*;

But why do I have to import it, if I already got the parent library?

答:
But why do I have to import it, if I already got the parent library?

No you are not, imagine packages as folders and sub folder defining a path...

When you import this

java.nio.file.*;

You are accessing all classes in that "path"

But Charset is in the  java.nio.charset folder....wich is actually another totally different path...

You mean importing all from a parent package like

java.nio.*;

Body:
I am teaching myself a little about Files and I/O in Java, based on this tutorial: Oracle Tutorial

Now, after writing some examples to understand input and output, I got a question regarding the import of certain libraries.

I created the following example program, and I ask myself why the program says:

Cannot find symbol - class Charset

import java.nio.*;

public class test
{

public static void main(String[] args)
{
    Charset charset = Charset.forName("US-ASCII");
}

}

I know that the solution is to import the following
    import java.nio.charset.*;

But why do I have to import it, if I already got the parent library?


问:
Swift Protocol of a particular class
I want to define a variable which of the type UIViewController that conforms to P1.

Question:

Should I modify the protocol or the v1 type ?

How should I do this ?

Code:

```<code>protocol P1 {

    func f1();
}

var v1 : P1 //But needs to be a UIViewController which conforms to `P1`
</code>```

答:
In Swift 4 you can use the new & sign to make a variable that is conforming a protocol AND a class, the syntax is like this:</p>

```<code>let vc: UIViewController & P1
</code>```

Title: Swift Protocol of a particular class

Body:
I want to define a variable which of the type UIViewController that conforms to P1.

Question:

Should I modify the protocol or the v1 type ?

How should I do this ?

Code:

protocol P1 {

    func f1();
}

var v1 : P1 //But needs to be a UIViewController which conforms to `P1`

Body:
In Swift 4 you can use the new & sign to make a variable that is conforming a protocol AND a class, the syntax is like this:

let vc: UIViewController & P1


问:
How do I use enums in TSQL without hard coding magic number all over my SQL scripts/procs?
We have enums in our C# code:

```<code>public enum JobStatus
{
  Ready = 0,
  Running = 1,
  Cancelling = 2,
}
</code>```

These values are also stored in database fields, and we have lots of TSQL (mostly stored procs, as well as some batches and SSIS) that also processes the data:

```<code>SELECT TOP 1 @JobSID = JobSID
FROM Job
WHERE Status = 0 /* JobStatus.Ready */
ORDER BY SubmitDate ASC

CREATE TABLE ImportCrossEffect(
    /* lots deleted */
    Source tinyint
      DEFAULT 1 NOT NULL -- 0: Unknown (default), 1:Imported, 2:Keyed
)
</code>```

How do I avoid hard coding the “magic numbers” in the TSQL?

How do I remove the risk of the enumerations not matching on the C# and TSQL sides?

(I have included the C# tag, as I would like solution that “single sourced”  the definitions of the enums on both the C# and TSQL sides)

Updates:

We don't have tables in the database with the Enum names in them, the values are just stored in tiny int columns.

I was hoping for something like a SQL pre-processor that would "expand" all the enum to there "magic value".

答: In one project we defined an attribute that applied to every enum member that stored the table and value expected in the database and the unit tests verified the link. Messy though.</p>

Body:
We have enums in our C# code:

public enum JobStatus
{
  Ready = 0,
  Running = 1,
  Cancelling = 2,
}

These values are also stored in database fields, and we have lots of TSQL (mostly stored procs, as well as some batches and SSIS) that also processes the data:

SELECT TOP 1 @JobSID = JobSID
FROM Job
WHERE Status = 0 /* JobStatus.Ready */
ORDER BY SubmitDate ASC

CREATE TABLE ImportCrossEffect(
    /* lots deleted */
    Source tinyint
      DEFAULT 1 NOT NULL -- 0: Unknown (default), 1:Imported, 2:Keyed
)

How do I avoid hard coding the “magic numbers” in the TSQL?

How do I remove the risk of the enumerations not matching on the C# and TSQL sides?

(I have included the C# tag, as I would like solution that “single sourced”  the definitions of the enums on both the C# and TSQL sides)

Updates:

We don't have tables in the database with the Enum names in them, the values are just stored in tiny int columns.

I was hoping for something like a SQL pre-processor that would "expand" all the enum to there "magic value".


问:
Database does not accept decimal values in live
I am using the following bit of code to insert some data into a database:

```<code>internal int InsertSample(Sample sample)
{
    using (var db = new OleDbConnection(connectionString))
    {
        var query = Constants.InsertNewSample;
        return db.Execute(query, sample);
    }
}
</code>```

And it works fine when I run it locally through Visual Studio.

However, when I publish the site and try inserting, I get an error:

Data type mismatch in criteria expression.

Stack trace

```<code>[OleDbException (0x80040e07): Data type mismatch in criteria expression.]
   System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(OleDbHResult hr) +1138392
   System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, Object& executeResult) +247
   System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult) +208
   System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior behavior, Object& executeResult) +58
   System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method) +162
   System.Data.OleDb.OleDbCommand.ExecuteNonQuery() +107
   Dapper.SqlMapper.ExecuteCommand(IDbConnection cnn, CommandDefinition& command, Action`2 paramReader) +93
   Dapper.SqlMapper.ExecuteImpl(IDbConnection cnn, CommandDefinition& command) +758
   MVCQCPage.Helpers.Access.InsertSample(Sample sample) +208
</code>```

But this only happens if the value of Sample.MassOff is in decimal format (e.g. 1.6).

If this value is passed as an integer (e.g. 5), it works without any issue when debugging and after publishing.

How is this possible????

The data type in the database is numeric, and the data type of Sample.MassOff is string.

Let me know if I can provide any more details.

答: I had a similar issue. I passed decimal values through. The problem was with parsing the separator dot / comma. The whole thing was a mess... I just ended up encrypting it into a string representation back and forth :)</p>

Body:
I am using the following bit of code to insert some data into a database:

internal int InsertSample(Sample sample)
{
    using (var db = new OleDbConnection(connectionString))
    {
        var query = Constants.InsertNewSample;
        return db.Execute(query, sample);
    }
}

And it works fine when I run it locally through Visual Studio.

However, when I publish the site and try inserting, I get an error:

Data type mismatch in criteria expression.

Stack trace

[OleDbException (0x80040e07): Data type mismatch in criteria expression.]
   System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(OleDbHResult hr) +1138392
   System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, Object& executeResult) +247
   System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult) +208
   System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior behavior, Object& executeResult) +58
   System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method) +162
   System.Data.OleDb.OleDbCommand.ExecuteNonQuery() +107
   Dapper.SqlMapper.ExecuteCommand(IDbConnection cnn, CommandDefinition& command, Action`2 paramReader) +93
   Dapper.SqlMapper.ExecuteImpl(IDbConnection cnn, CommandDefinition& command) +758
   MVCQCPage.Helpers.Access.InsertSample(Sample sample) +208

But this only happens if the value of Sample.MassOff is in decimal format (e.g. 1.6).

If this value is passed as an integer (e.g. 5), it works without any issue when debugging and after publishing.

How is this possible????

The data type in the database is numeric, and the data type of Sample.MassOff is string.

Let me know if I can provide any more details.


问:
Popup windows that automatically close in Selenium Webdriver
My Selenium Webdriver test is something like:

Click button -> this opens popup window

Iterate through all window handles and switch to popup window

Fill out form on popup window and submit.

At this point, the popup window might automatically close if the input was valid or it will stay open if there is an error on the form.

My question is, if the window automatically closes and that was the window handle I had focus on, what happens exactly? Is there a way for me to detect that the window has closed?

Thanks

答: The windows handles keeps the record of pop of window even if it closes automatically. So you have to switch to the parent window. And then use the print statement for Windows.title  to check which window is opened.</p>


问:
ArrayList not able to add elements due to the function call
While running the below snippet the loop executes properly, but the elements are not added for some reason.</p>

```<code>for(i=5;i<=500;i++) {
    x.add(i);
    check(x,i);
}

public static void check(ArrayList<Integer> x,Integer i){
    for(int j=0;j<x.size();j++){
        for(int k=0;k<x.size();k++){
            if(x.get(j)!=i&& x.get(k)!=i){
                if(x.contains(x.get(k)+x.get(j)))
                    x.remove(Integer.valueOf(i));
            }
        }
    }
}
</code>```

答:
The assignment was rather interesting, but the way you tried to do was really too expensive (and very wrong, because you modified the list during iteration)

So here's a bit of improvement :

```<code>public static void main(String[] args) {
    List<Integer> list = new ArrayList<>();
    IntStream.range(5, 500)
        .filter(i -> !check(list,i))    // check first
        .forEach( i -> list.add(i));    // add after
    System.out.println(list);
}
// we assume (rightly so) that list is ordered
private static boolean check(List<Integer> list, int value) {
    boolean found = false;
    for(int j=0; j < list.size(); j++){
        Integer leftSide = list.get(j);
        if(leftSide > value/2){
            break;                  // as the check is symmetrical, stop after value/2 has been overtaken
        }
        Integer complementaryValue = value - leftSide;
        for(int k=j+1; k < list.size(); k++){  // iterate over the rest of the list (because right is necessarily > left)
            Integer rightSide = list.get(k);
            if(rightSide > complementaryValue){
                break;              // no need to continue further
            }
            if(complementaryValue.equals(rightSide)){
                found = true;
                System.out.println(value+" = "+leftSide+" + "+rightSide);
                break;
            }
        }
        if(found){
            break;  // or return true
        }
    }
    return found;
}
</code>```

You can try it.

This is still far from optimal, work can still be done on the inner loop. A dichotomic search for the complementary value would be way better.

The final list is

[5, 6, 7, 8, 9, 10, 20, 21, 22, 23, 24, 35, 36, 37, 38, 39, 50, 51, 52, 53, 54, 65, 66, 67, 68, 69, 80, 81, 82, 83, 84, 95, 96, 97, 98, 99, 110, 111, 112, 113, 114, 125, 126, 127, 128, 129, 140, 141, 142, 143, 144, 155, 156, 157, 158, 159, 170, 171, 172, 173, 174, 185, 186, 187, 188, 189, 200, 201, 202, 203, 204, 215, 216, 217, 218, 219, 230, 231, 232, 233, 234, 245, 246, 247, 248, 249, 260, 261, 262, 263, 264, 275, 276, 277, 278, 279, 290, 291, 292, 293, 294, 305, 306, 307, 308, 309, 320, 321, 322, 323, 324, 335, 336, 337, 338, 339, 350, 351, 352, 353, 354, 365, 366, 367, 368, 369, 380, 381, 382, 383, 384, 395, 396, 397, 398, 399, 410, 411, 412, 413, 414, 425, 426, 427, 428, 429, 440, 441, 442, 443, 444, 455, 456, 457, 458, 459, 470, 471, 472, 473, 474, 485, 486, 487, 488, 489]

Body:
While running the below snippet the loop executes properly, but the elements are not added for some reason.

for(i=5;i<=500;i++) {
    x.add(i);
    check(x,i);
}

public static void check(ArrayList<Integer> x,Integer i){
    for(int j=0;j<x.size();j++){
        for(int k=0;k<x.size();k++){
            if(x.get(j)!=i&& x.get(k)!=i){
                if(x.contains(x.get(k)+x.get(j)))
                    x.remove(Integer.valueOf(i));
            }
        }
    }
}

Body:
The assignment was rather interesting, but the way you tried to do was really too expensive (and very wrong, because you modified the list during iteration)

So here's a bit of improvement :

public static void main(String[] args) {
    List<Integer> list = new ArrayList<>();
    IntStream.range(5, 500)
        .filter(i -> !check(list,i))    // check first
        .forEach( i -> list.add(i));    // add after
    System.out.println(list);
}
// we assume (rightly so) that list is ordered
private static boolean check(List<Integer> list, int value) {
    boolean found = false;
    for(int j=0; j < list.size(); j++){
        Integer leftSide = list.get(j);
        if(leftSide > value/2){
            break;                  // as the check is symmetrical, stop after value/2 has been overtaken
        }
        Integer complementaryValue = value - leftSide;
        for(int k=j+1; k < list.size(); k++){  // iterate over the rest of the list (because right is necessarily > left)
            Integer rightSide = list.get(k);
            if(rightSide > complementaryValue){
                break;              // no need to continue further
            }
            if(complementaryValue.equals(rightSide)){
                found = true;
                System.out.println(value+" = "+leftSide+" + "+rightSide);
                break;
            }
        }
        if(found){
            break;  // or return true
        }
    }
    return found;
}

You can try it.

This is still far from optimal, work can still be done on the inner loop. A dichotomic search for the complementary value would be way better.

The final list is

[5, 6, 7, 8, 9, 10, 20, 21, 22, 23, 24, 35, 36, 37, 38, 39, 50, 51, 52, 53, 54, 65, 66, 67, 68, 69, 80, 81, 82, 83, 84, 95, 96, 97, 98, 99, 110, 111, 112, 113, 114, 125, 126, 127, 128, 129, 140, 141, 142, 143, 144, 155, 156, 157, 158, 159, 170, 171, 172, 173, 174, 185, 186, 187, 188, 189, 200, 201, 202, 203, 204, 215, 216, 217, 218, 219, 230, 231, 232, 233, 234, 245, 246, 247, 248, 249, 260, 261, 262, 263, 264, 275, 276, 277, 278, 279, 290, 291, 292, 293, 294, 305, 306, 307, 308, 309, 320, 321, 322, 323, 324, 335, 336, 337, 338, 339, 350, 351, 352, 353, 354, 365, 366, 367, 368, 369, 380, 381, 382, 383, 384, 395, 396, 397, 398, 399, 410, 411, 412, 413, 414, 425, 426, 427, 428, 429, 440, 441, 442, 443, 444, 455, 456, 457, 458, 459, 470, 471, 472, 473, 474, 485, 486, 487, 488, 489]


问:
iPhone: Using Alerts to Help Debugging
I've been building a rather complex system and there's come the time now where I want more concise debugging. I would like to display the contents of a variable (for this example an NSString called v_string) in a notification window (the kind of window that appear when you receive an SMS text).

Is there an easy way to just call an alert with a variable?

Thanks in Advance,

Dan

答:
Alert window is cumbersome.  Use NSLog instead:

```<code>NSLog(@"Variable is: %@", v_string);
</code>```

And in Xcode's console you will see that text.

Title: iPhone: Using Alerts to Help Debugging

Body:
Alert window is cumbersome.  Use NSLog instead:

NSLog(@"Variable is: %@", v_string);

And in Xcode's console you will see that text.


问:
Selenium Robot Framework Web Locator
I am trying to find an element that RF can locate. I tried Click Element, Click Link, and Mouse Down with now luck.

```<code><a class="navHREF " href="#" onclick="return swap_interior_nav('6');">
    <span class="glyphicon glyphicon-circle-arrow-down" id="span_1_6"></span>
    Inventory
</a>
</code>```

I have tried the below XPath and can’t seem to make it work

```<code>//a[contains(.,'Inventory')]
</code>```

I can make it work with below, however, this link dynamic based on user permissions so the order can change of this function.

```<code>html/body/div[4]/div[2]/div[2]/ul/li[6]/a
</code>```

答:
Your solution was close and perhaps inspired from this SO Question. The main issue you have is that your trying to access the first text node, whereas you need the second one. The below example works on the provided code.</p>

```<code>//a[text()[contains(.,'Inventory')]]
</code>```

Title: Selenium Robot Framework Web Locator

Body:
I am trying to find an element that RF can locate. I tried Click Element, Click Link, and Mouse Down with now luck.

    Inventory

I have tried the below XPath and can’t seem to make it work

//a[contains(.,'Inventory')]

I can make it work with below, however, this link dynamic based on user permissions so the order can change of this function.

html/body/div[4]/div[2]/div[2]/ul/li[6]/a

Body:
Your solution was close and perhaps inspired from this SO Question. The main issue you have is that your trying to access the first text node, whereas you need the second one. The below example works on the provided code.

//a[text()[contains(.,'Inventory')]]