问:
How to calculate cost and theta with fmin_ncg
I am following Andrew NG course on coursera and I wanted to implement that same logic on python. I am trying to compute cost and theta with

```<code>scipy.optimize.fmin_ncg
</code>```

Here's a code

```<code>import numpy as np

from scipy.optimize import fmin_ncg

def sigmoid(z):
    return (1 / (1 + np.exp(-z))).reshape(-1, 1)

def compute_cost(theta, X, y):
    m = len(y)
    hypothesis = sigmoid(np.dot(X, theta))
    cost = (1 / m) * np.sum(np.dot(-y.T, (np.log(hypothesis))) - np.dot((1 - y.T), np.log(1 - hypothesis)))
    return cost

def compute_gradient(theta, X, y):
    m = len(y)
    hypothesis = sigmoid(np.dot(X, theta))
    gradient = (1 / m) * np.dot(X.T, (hypothesis - y))
    return gradient

def main():
    data = np.loadtxt("data/data1.txt", delimiter=",")  # 100, 3

    X = data[:, 0:2]
    y = data[:, 2:]
    m, n = X.shape

    initial_theta = np.zeros((n + 1, 1))
    X = np.column_stack((np.ones(m), X))
    mr = fmin_ncg(compute_cost, initial_theta, compute_gradient, args=(X, y), full_output=True)
    print(mr)

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

When I try to run this I get and error / exception like below

```<code>Traceback (most recent call last):
  File "/file/path/without_regression.py", line 78, in <module>
    main()
  File "/file/path/without_regression.py", line 66, in main
    mr = fmin_ncg(compute_cost, initial_theta, compute_gradient, args=(X, y), full_output=True)
  File "/usr/local/anaconda3/envs/ml/lib/python3.6/site-packages/scipy/optimize/optimize.py", line 1400, in fmin_ncg
    callback=callback, **opts)
  File "/usr/local/anaconda3/envs/ml/lib/python3.6/site-packages/scipy/optimize/optimize.py", line 1497, in _minimize_newtoncg
    dri0 = numpy.dot(ri, ri)
ValueError: shapes (3,1) and (3,1) not aligned: 1 (dim 1) != 3 (dim 0)
</code>```

I don't understand this error. May be because I am beginner this to not verbose for me.

How to use scipy.optimize.fmin_ncg or any other minimization technique such as scipy.optimize.minimize(...) to compute cost and theta?

答:
As mentioned in the comments:

Without having a reference to the docs right now, you should always use single-dimension arrays.

Relevant SO-question

```<code>import numpy as np
a = np.random.random(size=(3,1))   # NOT TO USE!
a.shape  # (3, 1)
a.ndim   # 2
b = np.random.random(size=3)       # TO USE!
b.shape  # (3,)
b.ndim   # 1
</code>```

This applies to your x0 (if not using python-lists) and your gradient.

A quick hack (=dropping dim in gradient) like:

```<code>gradient = (1 / m) * np.dot(X.T, (hypothesis - y)).ravel()  # .ravel()!
...
initial_theta = np.zeros(n + 1)  # drop extra-dim
</code>```

makes the code run:

```<code>Optimization terminated successfully.
         Current function value: 0.203498
         Iterations: 27
         Function evaluations: 71
         Gradient evaluations: 229
         Hessian evaluations: 0
(array([-25.13045417,   0.20598475,   0.2012217 ]), 0.2034978435366513, 71, 229, 0, 0)
</code>```

Extra: during debugging i also checked the calculation of the gradient itself against numerical-differentiation (recommended!), which looks good using x0:

```<code>from scipy.optimize import check_grad as cg
print(cg(compute_cost, compute_gradient, initial_theta, X, y))
# 1.24034933954e-05
</code>```

Body:
I am following Andrew NG course on coursera and I wanted to implement that same logic on python. I am trying to compute cost and theta with

scipy.optimize.fmin_ncg

Here's a code

import numpy as np

from scipy.optimize import fmin_ncg

def sigmoid(z):
    return (1 / (1 + np.exp(-z))).reshape(-1, 1)

def compute_cost(theta, X, y):
    m = len(y)
    hypothesis = sigmoid(np.dot(X, theta))
    cost = (1 / m) * np.sum(np.dot(-y.T, (np.log(hypothesis))) - np.dot((1 - y.T), np.log(1 - hypothesis)))
    return cost

def compute_gradient(theta, X, y):
    m = len(y)
    hypothesis = sigmoid(np.dot(X, theta))
    gradient = (1 / m) * np.dot(X.T, (hypothesis - y))
    return gradient

def main():
    data = np.loadtxt("data/data1.txt", delimiter=",")  # 100, 3

    X = data[:, 0:2]
    y = data[:, 2:]
    m, n = X.shape

    initial_theta = np.zeros((n + 1, 1))
    X = np.column_stack((np.ones(m), X))
    mr = fmin_ncg(compute_cost, initial_theta, compute_gradient, args=(X, y), full_output=True)
    print(mr)

if __name__ == "__main__":
    main()

When I try to run this I get and error / exception like below

Traceback (most recent call last):
  File "/file/path/without_regression.py", line 78, in <module>
    main()
  File "/file/path/without_regression.py", line 66, in main
    mr = fmin_ncg(compute_cost, initial_theta, compute_gradient, args=(X, y), full_output=True)
  File "/usr/local/anaconda3/envs/ml/lib/python3.6/site-packages/scipy/optimize/optimize.py", line 1400, in fmin_ncg
    callback=callback, **opts)
  File "/usr/local/anaconda3/envs/ml/lib/python3.6/site-packages/scipy/optimize/optimize.py", line 1497, in _minimize_newtoncg
    dri0 = numpy.dot(ri, ri)
ValueError: shapes (3,1) and (3,1) not aligned: 1 (dim 1) != 3 (dim 0)

I don't understand this error. May be because I am beginner this to not verbose for me.

How to use scipy.optimize.fmin_ncg or any other minimization technique such as scipy.optimize.minimize(...) to compute cost and theta?

Body:
As mentioned in the comments:

Without having a reference to the docs right now, you should always use single-dimension arrays.

Relevant SO-question

import numpy as np
a = np.random.random(size=(3,1))   # NOT TO USE!
a.shape  # (3, 1)
a.ndim   # 2
b = np.random.random(size=3)       # TO USE!
b.shape  # (3,)
b.ndim   # 1

This applies to your x0 (if not using python-lists) and your gradient.

A quick hack (=dropping dim in gradient) like:

gradient = (1 / m) * np.dot(X.T, (hypothesis - y)).ravel()  # .ravel()!
...
initial_theta = np.zeros(n + 1)  # drop extra-dim

makes the code run:

Optimization terminated successfully.
         Current function value: 0.203498
         Iterations: 27
         Function evaluations: 71
         Gradient evaluations: 229
         Hessian evaluations: 0
(array([-25.13045417,   0.20598475,   0.2012217 ]), 0.2034978435366513, 71, 229, 0, 0)

Extra: during debugging i also checked the calculation of the gradient itself against numerical-differentiation (recommended!), which looks good using x0:

from scipy.optimize import check_grad as cg
print(cg(compute_cost, compute_gradient, initial_theta, X, y))
# 1.24034933954e-05


来源: stackexchange

问:
How to pass parameters with `include`?
I have a PHP script called customers.php that is passed a parameter via the URL, e.g.:

http://www.mysite,com/customers.php?employeeId=1

Inside my customers.php script, I pick up the parameter thus:

```<code>$employeeId = $_GET['employeeId'];
</code>```

That works just fine. I also have an HTML file with a form that inputs the parameter, and runs another php script, viz:

```<code><form method="post" action="listcustomers.php">
  Employee ID:  <input name="employeeId" type="text"><br>
  <input type="submit" value="Show">
</form>
</code>```

Then in my listcustomers.php script, I pick up the parameter so:

```<code>$employeeId = $_POST['employeeId'];
</code>```

So far so good. But his is where I am stuck. I want to run my customers.php script, and pass it the parameter that I pave picked up in the form. I am sure this is really simple, but just cannot get it to work. I have tried:

```<code>include "customers.php?employeeId=$employeeId&password=password";
</code>```

But that does not work. Nor does anything else that I have tried. Please help me.

答:
You can use $GLOBALS to solve this issue as well.

```<code> $tit = "Hello";

 $GLOBALS["docTitle"] =  $tit;

 include ("my.php");
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to pass parameters with `include`?

Body:
I have a PHP script called customers.php that is passed a parameter via the URL, e.g.:

http://www.mysite,com/customers.php?employeeId=1

Inside my customers.php script, I pick up the parameter thus:

$employeeId = $_GET['employeeId'];

That works just fine. I also have an HTML file with a form that inputs the parameter, and runs another php script, viz:

<form method="post" action="listcustomers.php">
  Employee ID:  <input name="employeeId" type="text">

  <input type="submit" value="Show">
</form>

Then in my listcustomers.php script, I pick up the parameter so:

$employeeId = $_POST['employeeId'];

So far so good. But his is where I am stuck. I want to run my customers.php script, and pass it the parameter that I pave picked up in the form. I am sure this is really simple, but just cannot get it to work. I have tried:

include "customers.php?employeeId=$employeeId&password=password";

But that does not work. Nor does anything else that I have tried. Please help me.

Body:
You can use $GLOBALS to solve this issue as well.

 $tit = "Hello";

 $GLOBALS["docTitle"] =  $tit;

 include ("my.php");


问:
Monitor changes in files on Windows using .NET Core 2.0
Before you send me links to here, here and maybe here bear with me.

I'd like to write a service that monitors changes of a given set of files and I started with the simplest thing writing console application that monitors directory in order to continue with my POC. However, I got stuck trying to extract the actual changes that were made. (Yes, I managed to handle the event in the FileSystemWatcher class, but as far as I see the API of the class I am unable to track the actual changes)

Do you know if there is a way to do so? Maybe without so much pain or unnecessary operations.

I am currently using .NET Core 2.0, but any version of .NET Core will do.

EDIT: The files I need to monitor are text based, basically I want to implement git diff functionality and report the changes.

答:
The short answer is no, there is no API that will tell you which part of the file was modified.  All you can get from the OS is a notification that a change has occurred to a file, not the nature or location of that change beyond what you get from the FileSystemWatcher.

To detect the nature of the change you need to be able to compare the contents of the file before and after the change.  In most cases you won't have access to the prior state of the file.  You could use shadow copies to access the prior state of the file, but that has issues of its own.

If you're monitoring only a small number of files then you can do some sort of fingerprinting - block level hashing for instance - to detect the location of the change.  You'll still need a before and after to detect the particular change.

That said...

It is in principle possible to hook into the Windows APIs that are used to actually write data to the disk.  I haven't tried this with .NET but I've used Detours in the past to do similar things.  Be aware that API hooking is dangerous territory, and if you get it wrong you can kill your computer.  Here be dragons.  If you want to go this route I strongly suggest that you write your code with an eye towards minimising delays.


问:
How to generate random numbers in many ranges
I am wondering how to generate random numbers in the following way in R:

```<code> randomly choose 1 number between 1 and 15
 randomly choose 1 number between 16 and 30
 ...
 randomly choose 1 number between 86 and 100
</code>```

I know that I can do this with a loop but I am wondering if there is any non-loop way to do this. I tried to google around but didn't find much helpful.

答:
First off, 100 is not divisible by 15 so this answer will go up to 105 instead.

Start by creating a matrix of integers 1:105 with 105/15 rows. Then we simply sample one column for each row.  This way we get a random value from each of our ranges without using a loop.

```<code>## set up
n <- 105
m <- matrix(1:n, nrow=n/15, byrow=TRUE)
## execute
m[cbind(1:nrow(m), sample(ncol(m), nrow(m)))]
# [1]   5  23  33  51  74  77 103
</code>```

Here we can see a run of 10 replications.  Each column is one sample.

```<code>replicate(10, m[cbind(seq(nrow(m)), sample(ncol(m), nrow(m)))])
#      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
# [1,]    4   11   10    3    8    5   14   11    5    15
# [2,]   20   20   17   23   25   25   24   19   23    19
# [3,]   45   34   42   35   35   42   32   38   39    44
# [4,]   55   54   49   55   54   46   53   60   47    46
# [5,]   67   73   61   62   75   66   67   62   61    69
# [6,]   83   83   78   79   77   89   79   87   87    86
# [7,]   91  102   95  104   96   94   93   95  100    97
</code>```

Body:
I am wondering how to generate random numbers in the following way in R:

 randomly choose 1 number between 1 and 15
 randomly choose 1 number between 16 and 30
 ...
 randomly choose 1 number between 86 and 100

I know that I can do this with a loop but I am wondering if there is any non-loop way to do this. I tried to google around but didn't find much helpful.

Body:
First off, 100 is not divisible by 15 so this answer will go up to 105 instead.

Start by creating a matrix of integers 1:105 with 105/15 rows. Then we simply sample one column for each row.  This way we get a random value from each of our ranges without using a loop.

## set up
n <- 105
m <- matrix(1:n, nrow=n/15, byrow=TRUE)
## execute
m[cbind(1:nrow(m), sample(ncol(m), nrow(m)))]
# [1]   5  23  33  51  74  77 103

Here we can see a run of 10 replications.  Each column is one sample.

replicate(10, m[cbind(seq(nrow(m)), sample(ncol(m), nrow(m)))])
#      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
# [1,]    4   11   10    3    8    5   14   11    5    15
# [2,]   20   20   17   23   25   25   24   19   23    19
# [3,]   45   34   42   35   35   42   32   38   39    44
# [4,]   55   54   49   55   54   46   53   60   47    46
# [5,]   67   73   61   62   75   66   67   62   61    69
# [6,]   83   83   78   79   77   89   79   87   87    86
# [7,]   91  102   95  104   96   94   93   95  100    97


问:
No qualifying bean of type found for dependency in Spring Boot single table
I am beginner with Spring Boot.

UserController.java

```<code>  @Controller
  @ComponentScan("com.foo.dto")
  public class UserController {

  @Autowired
  UserRepository userRepository;

  @RequestMapping("/test")
  public void test() {
       System.out.println("PLEASE RUN");
  }
</code>```

UserRepository extends CrudRepository

```<code>@Repository
public interface UserRepository extends CrudRepository<User, Long> {

    List<User> findByLastName(String lastName);

    List<User> findByAccNameAndPassword(String accName, String password);
}
</code>```

User.java

```<code>@Entity
    public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
    @NotNull
    private String firstName;
    @NotNull
    private String lastName;
    @NotNull
    private Date dob;
    @NotNull
    private String phone;
    @NotNull
    private String email;
    @NotNull
    private boolean isEmployer;
    @NotNull
    private String accountName;
    @NotNull
    private String password;

    protected User() {
    }

    public User(String firstName, String lastName, Date dob, String email, String phone, String accName,
            String password) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.dob = dob;
        this.email = email;
        this.phone = phone;
        this.accountName = accName;
        this.password = password;
        this.isEmployer = false;

    }
</code>```

Is throwing exception when I try to RUN the application.

Exception thrown:

org.springframework.beans.factory.NoSuchBeanDefinitionException: No
  qualifying bean of type [com.foo.dto.UserRepository] found for
  dependency: expected at least 1 bean which qualifies as autowire
  candidate for this dependency. Dependency annotations:
  {@org.springframework.beans.factory.annotation.Autowired(required=true)

答:
I think you need to enable it in your configuration

```<code>@EnableJpaRepositories("com.foo.dto")
</code>```

in your @Configuration file.

Body:
I am beginner with Spring Boot.

UserController.java

  @Controller
  @ComponentScan("com.foo.dto")
  public class UserController {

  @Autowired
  UserRepository userRepository;

  @RequestMapping("/test")
  public void test() {
       System.out.println("PLEASE RUN");
  }

UserRepository extends CrudRepository

@Repository
public interface UserRepository extends CrudRepository<User, Long> {

    List<User> findByLastName(String lastName);

    List<User> findByAccNameAndPassword(String accName, String password);
}

User.java

@Entity
    public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
    @NotNull
    private String firstName;
    @NotNull
    private String lastName;
    @NotNull
    private Date dob;
    @NotNull
    private String phone;
    @NotNull
    private String email;
    @NotNull
    private boolean isEmployer;
    @NotNull
    private String accountName;
    @NotNull
    private String password;

    protected User() {
    }

    public User(String firstName, String lastName, Date dob, String email, String phone, String accName,
            String password) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.dob = dob;
        this.email = email;
        this.phone = phone;
        this.accountName = accName;
        this.password = password;
        this.isEmployer = false;

    }

Is throwing exception when I try to RUN the application.

Exception thrown:

org.springframework.beans.factory.NoSuchBeanDefinitionException: No
  qualifying bean of type [com.foo.dto.UserRepository] found for
  dependency: expected at least 1 bean which qualifies as autowire
  candidate for this dependency. Dependency annotations:
  {@org.springframework.beans.factory.annotation.Autowired(required=true)

Body:
I think you need to enable it in your configuration

@EnableJpaRepositories("com.foo.dto")

in your @Configuration file.


问:
GIT: Changed File Names With Certain Extension
When I want to get a list of the files I have changed so for, I use this command:

```<code>git diff --name-only
</code>```

But many times, I get many files that I don't care about right now. For example, if I am uploading to my PHP server, I usually just want the list of .php files. I tried this:

```<code>git diff --name-only **/*.php
</code>```

But unfortunately, it only shows me files in the first sub-directory. So looks like it is not interpreting the double star as recursive.

Any idea?

答:
```<code>git diff --name-only '**/*.php'
</code>```

(note the quotes)

Edit

Most POSIX shells don't support that pattern. From your comment, I gather that git doesn't either (I cannot test right now).

A workaround could be

```<code>git diff --name-only $(find . -name \*.php)
</code>```

ContentLicense: CC BY-SA 2.5

Body:
When I want to get a list of the files I have changed so for, I use this command:

git diff --name-only

But many times, I get many files that I don't care about right now. For example, if I am uploading to my PHP server, I usually just want the list of .php files. I tried this:

git diff --name-only **/*.php

But unfortunately, it only shows me files in the first sub-directory. So looks like it is not interpreting the double star as recursive.

Any idea?

Body:
git diff --name-only '**/*.php'

(note the quotes)

Edit

Most POSIX shells don't support that pattern. From your comment, I gather that git doesn't either (I cannot test right now).

A workaround could be

git diff --name-only $(find . -name \*.php)


问:
How to capitalise the first letter of each word after reversing a string
I want to make everything lowercase for when the string is reversed but then capitalise the first letter of each word after. I have reversed the string but after many attempts, the only outcome I can get is to then capitalise the entire reversed string.</p>

```<code>function titleCase(str) {
var reversed = str.toLowerCase().split('').reverse();
var newArr = [];
for (var i = 0; i < reversed.length; i++) {
    var firstLetter = reversed[i].charAt(0).toUpperCase();
    var restOfWord = reversed[i].slice(1);
        newArr[i] = firstLetter + restOfWord;
 }
 return newArr.join('');
}
</code>```

答:
You can just use replace and some fancy regex to do what you want.

var sentence = "hello i am a world 12321321 ;[/>?]"
console.log(sentence);
function titleCase(str) {
 return str.toLowerCase().split('').reverse().join('').replace(/\b\w/mg,
   (match)=>{return match.toUpperCase();}
 );
}
console.log(titleCase(sentence));```

Body:
I want to make everything lowercase for when the string is reversed but then capitalise the first letter of each word after. I have reversed the string but after many attempts, the only outcome I can get is to then capitalise the entire reversed string.

function titleCase(str) {
var reversed = str.toLowerCase().split('').reverse();
var newArr = [];
for (var i = 0; i < reversed.length; i++) {
    var firstLetter = reversed[i].charAt(0).toUpperCase();
    var restOfWord = reversed[i].slice(1);
        newArr[i] = firstLetter + restOfWord;
 }
 return newArr.join('');
}


问:
Reshaping only some columns into a single column
```<code>import pandas as pd
from datetime import datetime

df = pd.DataFrame({'origin': ['japan', 'japan','japan','japan'],
                       'pastime': ['baseball', 'sumo', 'keirin', 'football'],
                       datetime(2000,1,1) : [4,5,4,5],
                   datetime(2005,1,1) : [4, 3, 2, 1],
                   datetime(2010,1,1) : [4, 2, 2, 1]
                  })
</code>```

My dataframe has lots of date-labelled columns:

```<code>Index(['origin','pastime', 2000-01-01 00:00:00,
       2005-01-01 00:00:00, 2010-01-01 00:00:00],
      dtype='object')
</code>```

I would like to reshape the dataframe to have columns: origin, pastime, date, value

Where the first entry row would be:

```<code>origin = japan
pastime = baseball
date = 2001-01-01
value = 4
</code>```

I've seen examples using stack to push columns into the rows as an index,  but in my case, it pushes the 'origin' and 'pastime' columns down too.

How would I do this transformation?

答:
I think you're looking for melt:

```<code>df.melt(['origin', 'pastime'], var_name='date')

   origin   pastime       date  value
0   japan  baseball 2005-01-01      4
1   japan      sumo 2005-01-01      3
2   japan    keirin 2005-01-01      2
3   japan  football 2005-01-01      1
4   japan  baseball 2010-01-01      4
5   japan      sumo 2010-01-01      2
6   japan    keirin 2010-01-01      2
7   japan  football 2010-01-01      1
8   japan  baseball 2000-01-01      4
9   japan      sumo 2000-01-01      5
10  japan    keirin 2000-01-01      4
11  japan  football 2000-01-01      5
</code>```

Body:
import pandas as pd
from datetime import datetime

df = pd.DataFrame({'origin': ['japan', 'japan','japan','japan'],
                       'pastime': ['baseball', 'sumo', 'keirin', 'football'],
                       datetime(2000,1,1) : [4,5,4,5],
                   datetime(2005,1,1) : [4, 3, 2, 1],
                   datetime(2010,1,1) : [4, 2, 2, 1]
                  })

My dataframe has lots of date-labelled columns:

Index(['origin','pastime', 2000-01-01 00:00:00,
       2005-01-01 00:00:00, 2010-01-01 00:00:00],
      dtype='object')

I would like to reshape the dataframe to have columns: origin, pastime, date, value

Where the first entry row would be:

origin = japan
pastime = baseball
date = 2001-01-01
value = 4

I've seen examples using stack to push columns into the rows as an index,  but in my case, it pushes the 'origin' and 'pastime' columns down too.

How would I do this transformation?

Body:
I think you're looking for melt:

df.melt(['origin', 'pastime'], var_name='date')

   origin   pastime       date  value
0   japan  baseball 2005-01-01      4
1   japan      sumo 2005-01-01      3
2   japan    keirin 2005-01-01      2
3   japan  football 2005-01-01      1
4   japan  baseball 2010-01-01      4
5   japan      sumo 2010-01-01      2
6   japan    keirin 2010-01-01      2
7   japan  football 2010-01-01      1
8   japan  baseball 2000-01-01      4
9   japan      sumo 2000-01-01      5
10  japan    keirin 2000-01-01      4
11  japan  football 2000-01-01      5


问:
Create a new script tag (Shopify) Error: Invalid URI "/"
Based on this tutorial, I tried the below code. I'm trying to add a new script to the web page.

```<code>request.post(accessTokenRequestUrl, {
      json: accessTokenPayload
  })
  .then((accessTokenResponse) => {
          const accessToken = accessTokenResponse.access_token;
          // DONE: Use access token to make API call to 'shop' endpoint
          const shopRequestUrl = 'https://' + shop + '/admin/shop.json';
          const shopRequestHeaders = {
              'X-Shopify-Access-Token': accessToken,
              'Content-Type': 'application/json'
          };

          const createScriptTagUrl = 'https://' + shop + '/admin/script_tags.json';
          const scriptTagBody = {
              "script_tag": {
                  "event": "onload",
                  "src": "https:\/\/djavaskripped.org\/fancy.js"
              }
          }

          request.get(shopRequestUrl, {
                  headers: shopRequestHeaders
              })
              .then((shopResponse) => {
                  res.status(200).end(shopResponse);
              })
              .catch((error) => {
                  res.status(error.statusCode).send(error.error.error_description);
              });
          request.post(createScriptTagUrl, {
                  json: scriptTagBody
              }, {
                  headers: shopRequestHeaders
              })
              .then((scriptResponse) => {
                  res.status(200).end(scriptResponse);
              })
              .catch((error) => {
                  res.status(error.statusCode).send(error.error.error_description);
              });
</code>```

However, I get RequestError: Error: Invalid URI "/"

Am I missing anything? Or is the src value is having some problem?

答:
Fixed using the below code. Basically, the request body was supposed to be sent as JSON. </p>

```<code>request.post({
    url: createScriptTagUrl,
    body: scriptTagBody,
    headers: shopRequestHeaders,
    json: true
}, function(error, response, body) {
    if (!error) {
        console.log(body)
    }
});
</code>```

Body:
Based on this tutorial, I tried the below code. I'm trying to add a new script to the web page.

request.post(accessTokenRequestUrl, {
      json: accessTokenPayload
  })
  .then((accessTokenResponse) => {
          const accessToken = accessTokenResponse.access_token;
          // DONE: Use access token to make API call to 'shop' endpoint
          const shopRequestUrl = 'https://' + shop + '/admin/shop.json';
          const shopRequestHeaders = {
              'X-Shopify-Access-Token': accessToken,
              'Content-Type': 'application/json'
          };

          const createScriptTagUrl = 'https://' + shop + '/admin/script_tags.json';
          const scriptTagBody = {
              "script_tag": {
                  "event": "onload",
                  "src": "https:\/\/djavaskripped.org\/fancy.js"
              }
          }

          request.get(shopRequestUrl, {
                  headers: shopRequestHeaders
              })
              .then((shopResponse) => {
                  res.status(200).end(shopResponse);
              })
              .catch((error) => {
                  res.status(error.statusCode).send(error.error.error_description);
              });
          request.post(createScriptTagUrl, {
                  json: scriptTagBody
              }, {
                  headers: shopRequestHeaders
              })
              .then((scriptResponse) => {
                  res.status(200).end(scriptResponse);
              })
              .catch((error) => {
                  res.status(error.statusCode).send(error.error.error_description);
              });

However, I get RequestError: Error: Invalid URI "/"

Am I missing anything? Or is the src value is having some problem?

Body:
Fixed using the below code. Basically, the request body was supposed to be sent as JSON.

request.post({
    url: createScriptTagUrl,
    body: scriptTagBody,
    headers: shopRequestHeaders,
    json: true
}, function(error, response, body) {
    if (!error) {
        console.log(body)
    }
});


问:
Python: Comparing two Directories for Different Filenames
I have to compare two directories with .xyz files in them. One directory has original files (names xa02-1-1-1-1, xa02-1-1-1-2 etc.). I process all these files (molecules) and each file gives rise to 3 new files whose file names just have -1, -2, -3 added at the end. (e.g., xa02-1-1-1-1 would give rise to xa02-1-1-1-1-1, xa02-1-1-1-1-2, and xa02-1-1-1-1-3). During this operation some files just produce two new files and don't produce the 3rd or some produce just one new file and some even do not produce any output. I want to compare first folder with the new one seeing which files have not generated 3 new files. Basically I want t list of the files in the first folder which did not give rise to 3 new files.
I did not find how to do it with Python so I printed all the filenames using bash without the extensions. Now I have two text files with all the filenames and I compare those two text files. I am trying to remove the last -1, -2, -3 from the new list and see if an item in original file is present in the new list less than 3 times. The code still gives me count 1 for all the files.
Can anyone please guide me on that how to do it efficiently using Python. I need this for my PhD research as doing this manually takes days just to compare two folders because of lots of files (molecules) in them.
Here is the code I wrote:

```<code># Define the lists which contain the filenames to compare
originals = "orig-files.txt"
next_step_filenames = "new-files.txt"

def read_input_file(input_filename):
    f = open(input_filename, 'r')
    fr = f.readlines()
    f.close()
    return fr
# Read the files with filenames and without extensions
original_files = read_input_file(originals)
next_step_files = read_input_file(next_step_filenames)

original_files_trimmed = []  # Removing the last \n from every line
for a in original_files:
    original_files_trimmed.append(a[:-1])

next_step_files_trimmed = []  # A list with the last -1, -2, -3 removed
for i in next_step_files:
    next_step_files_trimmed.append(i[:-3])

Final_list = [] # List for Files who generate <3 files
for m in original_files_trimmed:
    for n in next_step_files_trimmed:
        count = 0
        if m in n:
            count =+ 1
            if count < 3:
                Final_list.append(m)

for b in Final_list:
    print(b)
</code>```

And here are the files with names in them.
orig-files.txt

```<code>xa02-1-1-1-1
xa02-1-1-1-2
xa02-1-1-2-3
xa02-1-3-3-3
xa06-3-1-2-1
xa07-1-2-1-1
</code>```

new-files.txt

```<code>xa02-1-1-1-1-1
xa02-1-1-1-1-2
xa02-1-1-1-1-3
xa02-1-1-1-2-1
xa02-1-1-1-2-2
xa02-1-1-1-2-3
xa02-1-1-2-3-1
xa02-1-3-3-3-1
xa02-1-3-3-3-2
xa06-3-1-2-1-1
xa06-3-1-2-1-2
xa06-3-1-2-1-3
</code>```

You can see in the files that xa02-1-1-2-3 and xa02-1-3-3-3 generate 1 and 2 files, respectively while xa07-1-2-1-1 did not generate any output file. I want the output to look like this:

```<code>xa02-1-1-2-3   1
xa02-1-3-3-3   2
xa07-1-2-1-1   0
</code>```

Please help me here. I would be highly thankful for any help.

答:
Here is one implementation:</p>

```<code>def updateHash(d, key):
    if key not in d.keys():
        d[key] = 3
    else:
        d[key] -= 1

originals = "orig-files.txt"
next_step_filenames = "new-files.txt"

originals_list = []
with open(originals, 'r') as f:
    originals_list = f.read().splitlines()

next_step_list = []
with open(next_step_filenames, 'r') as f:
    next_step_list = f.read().splitlines()

expected_list = []
d = {}
for orig in originals_list:
    if orig + '-1' not in next_step_list:
        updateHash(d, orig)
    if orig + '-2' not in next_step_list:
        updateHash(d, orig)
    if orig + '-3' not in next_step_list:
        updateHash(d, orig)

print d
</code>```

Body:
I have to compare two directories with .xyz files in them. One directory has original files (names xa02-1-1-1-1, xa02-1-1-1-2 etc.). I process all these files (molecules) and each file gives rise to 3 new files whose file names just have -1, -2, -3 added at the end. (e.g., xa02-1-1-1-1 would give rise to xa02-1-1-1-1-1, xa02-1-1-1-1-2, and xa02-1-1-1-1-3). During this operation some files just produce two new files and don't produce the 3rd or some produce just one new file and some even do not produce any output. I want to compare first folder with the new one seeing which files have not generated 3 new files. Basically I want t list of the files in the first folder which did not give rise to 3 new files.
I did not find how to do it with Python so I printed all the filenames using bash without the extensions. Now I have two text files with all the filenames and I compare those two text files. I am trying to remove the last -1, -2, -3 from the new list and see if an item in original file is present in the new list less than 3 times. The code still gives me count 1 for all the files.
Can anyone please guide me on that how to do it efficiently using Python. I need this for my PhD research as doing this manually takes days just to compare two folders because of lots of files (molecules) in them.
Here is the code I wrote:

# Define the lists which contain the filenames to compare
originals = "orig-files.txt"
next_step_filenames = "new-files.txt"

def read_input_file(input_filename):
    f = open(input_filename, 'r')
    fr = f.readlines()
    f.close()
    return fr
# Read the files with filenames and without extensions
original_files = read_input_file(originals)
next_step_files = read_input_file(next_step_filenames)

original_files_trimmed = []  # Removing the last \n from every line
for a in original_files:
    original_files_trimmed.append(a[:-1])

next_step_files_trimmed = []  # A list with the last -1, -2, -3 removed
for i in next_step_files:
    next_step_files_trimmed.append(i[:-3])

Final_list = [] # List for Files who generate <3 files
for m in original_files_trimmed:
    for n in next_step_files_trimmed:
        count = 0
        if m in n:
            count =+ 1
            if count < 3:
                Final_list.append(m)

for b in Final_list:
    print(b)

And here are the files with names in them.
orig-files.txt

xa02-1-1-1-1
xa02-1-1-1-2
xa02-1-1-2-3
xa02-1-3-3-3
xa06-3-1-2-1
xa07-1-2-1-1

new-files.txt

xa02-1-1-1-1-1
xa02-1-1-1-1-2
xa02-1-1-1-1-3
xa02-1-1-1-2-1
xa02-1-1-1-2-2
xa02-1-1-1-2-3
xa02-1-1-2-3-1
xa02-1-3-3-3-1
xa02-1-3-3-3-2
xa06-3-1-2-1-1
xa06-3-1-2-1-2
xa06-3-1-2-1-3

You can see in the files that xa02-1-1-2-3 and xa02-1-3-3-3 generate 1 and 2 files, respectively while xa07-1-2-1-1 did not generate any output file. I want the output to look like this:

xa02-1-1-2-3   1
xa02-1-3-3-3   2
xa07-1-2-1-1   0

Please help me here. I would be highly thankful for any help.

Body:
Here is one implementation:

def updateHash(d, key):
    if key not in d.keys():
        d[key] = 3
    else:
        d[key] -= 1

originals = "orig-files.txt"
next_step_filenames = "new-files.txt"

originals_list = []
with open(originals, 'r') as f:
    originals_list = f.read().splitlines()

next_step_list = []
with open(next_step_filenames, 'r') as f:
    next_step_list = f.read().splitlines()

expected_list = []
d = {}
for orig in originals_list:
    if orig + '-1' not in next_step_list:
        updateHash(d, orig)
    if orig + '-2' not in next_step_list:
        updateHash(d, orig)
    if orig + '-3' not in next_step_list:
        updateHash(d, orig)

print d


问:
Add 2 TextView into LinearLayout(one align left and one align right)
Here is what I've done so far:

```<code>LinearLayout category_layout = new LinearLayout(getActivity());
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams (LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(15, 5, 5, 10);
category_layout.setLayoutParams(params);
//Add Category Title
TextView category_title = new TextView(getActivity());
category_title.setText("MEN " + i);
category_title.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
category_title.setPadding(10,0,0,0); category_title.setTextColor(getResources().getColor(R.color.text_color));
category_title.setTypeface(null, Typeface.BOLD);
category_layout.addView(category_title);
TextView category_more = new TextView(getActivity());
category_more.setText("MORE");
LinearLayout.LayoutParams lp_ineer_ver = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
lp_ineer_ver.gravity = Gravity.RIGHT;
category_more.setLayoutParams(lp_ineer_ver);
category_more.setPadding(0,0,10,0);
category_more.setTextColor(getResources().getColor(R.color.text_color));
category_more.setTypeface(null, Typeface.BOLD);
category_more.setGravity(Gravity.RIGHT);
category_layout.addView(category_more);
</code>```

Now the TextView "More" don't show up,but If I try to comment the line

```<code>category_layout.addView(category_title);
</code>```

then it show and align right perfectly. What happened? Any idea, Please help!!!

答:
Try this:

You need to set width to Wrap content in first textview.

```<code>category_title.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
</code>```

sample code

```<code>LinearLayout category_layout = new LinearLayout(getActivity());
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams
(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(15, 5, 5, 10);
category_layout.setLayoutParams(params);

 //Add Category Title
 TextView category_title = new TextView(getActivity());
 category_title.setText("MEN " + i);
 category_title.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
 category_title.setPadding(10,0,0,0);
 category_title.setTextColor(getResources().getColor(R.color.text_color));
 category_title.setTypeface(null, Typeface.BOLD);
 category_layout.addView(category_title);

 TextView category_more = new TextView(getActivity());
 category_more.setText("MORE");
 LinearLayout.LayoutParams lp_ineer_ver = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
 lp_ineer_ver.gravity = Gravity.RIGHT;
 category_more.setLayoutParams(lp_ineer_ver);
 category_more.setPadding(0,0,10,0);
 category_more.setTextColor(getResources().getColor(R.color.text_color));
 category_more.setTypeface(null, Typeface.BOLD);
 category_more.setGravity(Gravity.RIGHT);

 category_layout.addView(category_more);
</code>```

Body:
Here is what I've done so far:

LinearLayout category_layout = new LinearLayout(getActivity());
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams (LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(15, 5, 5, 10);
category_layout.setLayoutParams(params);
//Add Category Title
TextView category_title = new TextView(getActivity());
category_title.setText("MEN " + i);
category_title.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
category_title.setPadding(10,0,0,0); category_title.setTextColor(getResources().getColor(R.color.text_color));
category_title.setTypeface(null, Typeface.BOLD);
category_layout.addView(category_title);
TextView category_more = new TextView(getActivity());
category_more.setText("MORE");
LinearLayout.LayoutParams lp_ineer_ver = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
lp_ineer_ver.gravity = Gravity.RIGHT;
category_more.setLayoutParams(lp_ineer_ver);
category_more.setPadding(0,0,10,0);
category_more.setTextColor(getResources().getColor(R.color.text_color));
category_more.setTypeface(null, Typeface.BOLD);
category_more.setGravity(Gravity.RIGHT);
category_layout.addView(category_more);

Now the TextView "More" don't show up,but If I try to comment the line

category_layout.addView(category_title);

then it show and align right perfectly. What happened? Any idea, Please help!!!

Body:
Try this:

You need to set width to Wrap content in first textview.

category_title.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT));

sample code

LinearLayout category_layout = new LinearLayout(getActivity());
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams
(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(15, 5, 5, 10);
category_layout.setLayoutParams(params);

 //Add Category Title
 TextView category_title = new TextView(getActivity());
 category_title.setText("MEN " + i);
 category_title.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
 category_title.setPadding(10,0,0,0);
 category_title.setTextColor(getResources().getColor(R.color.text_color));
 category_title.setTypeface(null, Typeface.BOLD);
 category_layout.addView(category_title);

 TextView category_more = new TextView(getActivity());
 category_more.setText("MORE");
 LinearLayout.LayoutParams lp_ineer_ver = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
 lp_ineer_ver.gravity = Gravity.RIGHT;
 category_more.setLayoutParams(lp_ineer_ver);
 category_more.setPadding(0,0,10,0);
 category_more.setTextColor(getResources().getColor(R.color.text_color));
 category_more.setTypeface(null, Typeface.BOLD);
 category_more.setGravity(Gravity.RIGHT);

 category_layout.addView(category_more);


问:
Angular 2 and MVC Routing together
I've built an Angular 2 SPA project with Visual Studio 2017 and I've got the following routing stuff code. Could someone please, explain to me what's the discrete role of each of the below routings:

```<code>app.UseMvc(routes =>
      {
          routes.MapRoute(
             name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
          routes.MapSpaFallbackRoute(
                name: "spa-fallback",
                defaults: new { controller = "Home", action = "Index" });
});
</code>```

If I delete either the first or the second route everything works the same like having both routes. So what is the use of having two routes?

答:
The first route is a standard MVC route that says if you get a request for "example.com/accounts/delete/123", call the "delete" action on the "accounts" controller and pass "123" as the value for the "id" argument.

The second route is for handling SPA (single page application) routes which happen to be sent to the server. Normally when you click on an internal link in an Angular app, the Angular router will intercept it and not send a request to the server. But if you were to copy, save and later paste that link as an URL in the browser, it will be sent to the server.

This "fall back route" tells the server that if it gets a route that does not exist on the server, to instead send back to the browser the result of the "Index" action on the "Home" controller. It does this because the SPA template uses that method to return the HTML that contains the Angular app tag. Therefore the Angular app will get re-loaded and eventually the internal link that was requested will be routed to.

Unless you added additional controllers on the server, or an additional action method to the Home controller, you only have one single action method and one single controller on the server. This is the reason that you can currently delete either route and your app still works. Except that if you deleted the second route, you would most likely get a 404 error, if you copy and paste an internal SPA link into the browser.

Title: Angular 2 and MVC Routing together

Body:
I've built an Angular 2 SPA project with Visual Studio 2017 and I've got the following routing stuff code. Could someone please, explain to me what's the discrete role of each of the below routings:

app.UseMvc(routes =>
      {
          routes.MapRoute(
             name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
          routes.MapSpaFallbackRoute(
                name: "spa-fallback",
                defaults: new { controller = "Home", action = "Index" });
});

If I delete either the first or the second route everything works the same like having both routes. So what is the use of having two routes?


问:
SKPhysicsBody containment test?
Any simple method to test if an SKPhysicsBody entirely contains another?

Something like bodyA contains every point of bodyB, or so.

Just wanted to ask you before implement some 2D math helpers to do this with additional "meta"-CGPaths attached to a given node or something.

答:
I know this thread is super old but it's 2017 and I was searching for an answer and ended up finding my own by tinkering with my code. Hopefully this helps someone out! It works with circles and ovals. </p>

```<code>-(void)didBeginContact:(SKPhysicsContact *)contact {

// get the path of the physics body ( contact bodyA )
CGPathRef path = CGPathCreateWithEllipseInRect(CGRectMake(contact.bodyA.node.position.x - contact.bodyA.node.frame.size.width/2, contact.bodyA.node.position.y - contact.bodyA.node.frame.size.height/2, contact.bodyA.node.frame.size.width, contact.bodyA.node.frame.size.height), nil);

// check if that path contains the physics body point of BodyB
if (CGPathContainsPoint(path, NULL, contact.bodyB.node.position, FALSE)) {

    NSLog(@"CONTAINS POINT player body B");

}
</code>```

<p>}`</p>

Title: SKPhysicsBody containment test?

Body:
I know this thread is super old but it's 2017 and I was searching for an answer and ended up finding my own by tinkering with my code. Hopefully this helps someone out! It works with circles and ovals.

-(void)didBeginContact:(SKPhysicsContact *)contact {

// get the path of the physics body ( contact bodyA )
CGPathRef path = CGPathCreateWithEllipseInRect(CGRectMake(contact.bodyA.node.position.x - contact.bodyA.node.frame.size.width/2, contact.bodyA.node.position.y - contact.bodyA.node.frame.size.height/2, contact.bodyA.node.frame.size.width, contact.bodyA.node.frame.size.height), nil);

// check if that path contains the physics body point of BodyB
if (CGPathContainsPoint(path, NULL, contact.bodyB.node.position, FALSE)) {

    NSLog(@"CONTAINS POINT player body B");

}

}`


问:
Making 2 sequential requests with Axios - second request depends on the response of 1st
The following code is not waiting for the else part to return data before resolving.

Where I'm going wrong with this code?

```<code>return request.get(`${<URL1>}`)
.then((res) => {
    if (res1.data[0]) {
        data1 = res.data[0]};
    } else {
        request.get(`${<URL2>`)
            .then((res2) => {
                data1 = res2.data
            });
    }
    return Promise.resolve(data1);
})
</code>```

Thanks in advance.

San

答:
I think you can do something like

```<code>function getUserAccount() {
  return axios.get('/user/12345');
}

function getUserPermissions() {
  return axios.get('/user/12345/permissions');
}

axios.all([getUserAccount(), getUserPermissions()])
  .then(axios.spread(function (acct, perms) {
    // Both requests are now complete
  }));
</code>```

I think it should help. You can read more here

ContentLicense: CC BY-SA 4.0

Body:
The following code is not waiting for the else part to return data before resolving.

Where I'm going wrong with this code?

return request.get(`${<URL1>}`)
.then((res) => {
    if (res1.data[0]) {
        data1 = res.data[0]};
    } else {
        request.get(`${<URL2>`)
            .then((res2) => {
                data1 = res2.data
            });
    }
    return Promise.resolve(data1);
})

Thanks in advance.

San

Body:
I think you can do something like

function getUserAccount() {
  return axios.get('/user/12345');
}

function getUserPermissions() {
  return axios.get('/user/12345/permissions');
}

axios.all([getUserAccount(), getUserPermissions()])
  .then(axios.spread(function (acct, perms) {
    // Both requests are now complete
  }));

I think it should help. You can read more here


问:
Create Pandas dataframe using List
Im trying to place a list that I created from reading in a textfile into a pandas dataframe but its not working for some reason. Below you will find some test data and my functions. The first piece of code does some checking and splitting and the second part appends it to a list called data. Here is some test data

```<code>product/productId: B001E4KFG0
review/userId: A3SGXH7AUHU8GW
review/profileName: delmartian
review/helpfulness: 1/1
review/score: 5.0
review/time: 1303862400
review/summary: Good Quality Dog Food
review/text: I have bought several of the Vitality canned dog food products and have found them all to be of good quality. The product looks more like a stew than a processed meat and it smells better. My Labrador is finicky and she appreciates this product better than  most.

product/productId: B00813GRG4
review/userId: A1D87F6ZCVE5NK
review/profileName: dll pa
review/helpfulness: 0/0
review/score: 1.0
review/time: 1346976000
review/summary: Not as Advertised
review/text: Product arrived labeled as Jumbo Salted Peanuts...the peanuts were actually small sized unsalted. Not sure if this was an error or if the vendor intended to represent the product as "Jumbo".
</code>```

Here is my code:

```<code>import pandas as pd
import numpy as np

def grab_next_entry(food_file):
    record={'id':-1,'helpfulness':'','number rated':'','score':'','review':''}
    line=food_file.readline()

    #food_dataframe=pd.DataFrame(columns=column_names)

    while line:
        if 'product/productId' in line:
            split_product_id=line.split(':')
            record['id']=split_product_id[1]

        if 'review/helpfulness' in line:
            split_helpfulness=line.split(':')
            split_helpfulness=split_helpfulness[1].split('/')
            record['helpfulness']=eval(split_helpfulness[0])
            record['number rated']=eval(split_helpfulness[-1])

        if 'review/score' in line:
            split_score = line.split(':')
            record['score']=eval(split_score[1])

        if 'review/text' in line:
            split_review_text=line.split('review/text:')
            record['review']=split_review_text[1:]

        if line=='\n':
            return record
        line=food_file.readline()
</code>```

The next piece of code is creating the list and trying to put it into a pandas dataframe.

```<code>import os

fileLoc = "/Users/brawdyll/Documents/ds710fall2017assignment11/finefoods_test.txt"
column_names=('Product ID', 'People who voted Helpful','Total votes','Rating','Review')
food_dataframe=[]
data=[]
with open(fileLoc,encoding = "ISO 8859-1") as food_file:
    fs=os.fstat(food_file.fileno()).st_size
    num_read = 0
    while not food_file.tell()==fs:
        data.append(grab_next_entry(food_file))
        num_read+=1

Food_dataframe = pd.DataFrame(data,column_names)

print(Food_dataframe)
</code>```

答:
There's a lot of improvements that could be made in this code, but the reason why your program isn't working is because you're setting the indices to be column_names. Running:

```<code>pd.DataFrame(data)
</code>```

will work just fine, and then setting:

```<code>df.columns = column_names
</code>```

Will give you the results you want.

Title: Create Pandas dataframe using List

Body:
Im trying to place a list that I created from reading in a textfile into a pandas dataframe but its not working for some reason. Below you will find some test data and my functions. The first piece of code does some checking and splitting and the second part appends it to a list called data. Here is some test data

product/productId: B001E4KFG0
review/userId: A3SGXH7AUHU8GW
review/profileName: delmartian
review/helpfulness: 1/1
review/score: 5.0
review/time: 1303862400
review/summary: Good Quality Dog Food
review/text: I have bought several of the Vitality canned dog food products and have found them all to be of good quality. The product looks more like a stew than a processed meat and it smells better. My Labrador is finicky and she appreciates this product better than  most.

product/productId: B00813GRG4
review/userId: A1D87F6ZCVE5NK
review/profileName: dll pa
review/helpfulness: 0/0
review/score: 1.0
review/time: 1346976000
review/summary: Not as Advertised
review/text: Product arrived labeled as Jumbo Salted Peanuts...the peanuts were actually small sized unsalted. Not sure if this was an error or if the vendor intended to represent the product as "Jumbo".

Here is my code:

import pandas as pd
import numpy as np

def grab_next_entry(food_file):
    record={'id':-1,'helpfulness':'','number rated':'','score':'','review':''}
    line=food_file.readline()

    #food_dataframe=pd.DataFrame(columns=column_names)

    while line:
        if 'product/productId' in line:
            split_product_id=line.split(':')
            record['id']=split_product_id[1]

        if 'review/helpfulness' in line:
            split_helpfulness=line.split(':')
            split_helpfulness=split_helpfulness[1].split('/')
            record['helpfulness']=eval(split_helpfulness[0])
            record['number rated']=eval(split_helpfulness[-1])

        if 'review/score' in line:
            split_score = line.split(':')
            record['score']=eval(split_score[1])

        if 'review/text' in line:
            split_review_text=line.split('review/text:')
            record['review']=split_review_text[1:]

        if line=='\n':
            return record
        line=food_file.readline()

The next piece of code is creating the list and trying to put it into a pandas dataframe.

import os

fileLoc = "/Users/brawdyll/Documents/ds710fall2017assignment11/finefoods_test.txt"
column_names=('Product ID', 'People who voted Helpful','Total votes','Rating','Review')
food_dataframe=[]
data=[]
with open(fileLoc,encoding = "ISO 8859-1") as food_file:
    fs=os.fstat(food_file.fileno()).st_size
    num_read = 0
    while not food_file.tell()==fs:
        data.append(grab_next_entry(food_file))
        num_read+=1

Food_dataframe = pd.DataFrame(data,column_names)

print(Food_dataframe)

Body:
There's a lot of improvements that could be made in this code, but the reason why your program isn't working is because you're setting the indices to be column_names. Running:

pd.DataFrame(data)

will work just fine, and then setting:

df.columns = column_names

Will give you the results you want.


问:
How to resolve in No4j and Rails 4 Neo4j::ActiveNode::Labels::RecordNotFound
I'm working on the tests for a Rails 4 app which was migrated recently to Neo4j. My tests are failing and I cannot find a way or good reference to resolve my situation. I stuck completely.
The error I have which I need assistance: Neo4j::ActiveNode::Labels::RecordNotFound: Couldn't find Study with 'uuid'=1
Is related to the next line of code: study_version = StudyVersion.create(study_id: 1, name: "Name", description: "description", protocol_name: "protocol_name", state: StudyVersion.states[:qualified], version: 1, semantic_version: "0.1.0")

I would like to understand how to fix this.

Next myall model_speccode:

```<code>require 'rails_helper'

describe Study do

  include FileHelpers

  def sub_dir
    return "models"
  end

  def create_form(study_version, form_id, form_namespace, identifier, ordinal, label)
    form = Form.create(study_version_id: study_version.id, ordinal: ordinal, form_id: form_id,
                       form_namespace: form_namespace, identifier: identifier, label: label)
    return form
  end

  def new_form(study_version, form_id, form_namespace, identifier, ordinal, label)
    form = Form.new(study_version_id: study_version.id, ordinal: ordinal, form_id: form_id,
                    form_namespace: form_namespace, identifier: identifier, label: label)
    return form
  end

  def create_visit(study_version, short_name, long_name, timing, ordinal)
    visit = Visit.create(study_version_id: study_version.id, ordinal: ordinal, short_name: short_name, long_name: long_name, timing: timing)
    return visit
  end

  def new_visit(study_version, short_name, long_name, timing, ordinal)
    visit = Visit.new(study_version_id: study_version.id, ordinal: ordinal, short_name: short_name, long_name: long_name, timing: timing)
    return visit
  end

  def create_element(study_version, form, visit)
    element = Element.create(study_version_id: study_version.id, form_id: form.id, visit_id: visit.id)
    return element
  end

  def new_element(study_version, form, visit)
    element = Element.new(study_version_id: study_version.id, form_id: form.id, visit_id: visit.id)
    return element
  end

  before :each do
    Form.destroy_all
    Visit.destroy_all
    Element.destroy_all
    StudyVersion.destroy_all
  end

  after :each do
    Form.destroy_all
    Visit.destroy_all
    Element.destroy_all
    StudyVersion.destroy_all
  end

  it "edits a version, no clone" do
    study_version = StudyVersion.create(study_id: 1, name: "Name", description: "description", protocol_name: "protocol_name",
                                        state: StudyVersion.states[:incomplete], version: 1, semantic_version: "0.1.0")
    new_version = study_version.edit_version
    expect(new_version.id).to eq(study_version.id)
  end

  it "edits a version, clone" do
    study_version = StudyVersion.create(study_id: 1, name: "Name", description: "description", protocol_name: "protocol_name",
                                        state: StudyVersion.states[:qualified], version: 1, semantic_version: "0.1.0")
    new_version = study_version.edit_version
    expect(new_version.id).to_not eq(study_version.id)
  end

  it "updates the state" do
    study_version = StudyVersion.create(study_id: 1, name: "Name", description: "description", protocol_name: "protocol_name",
                                        state: StudyVersion.states[:qualified], version: 1, semantic_version: "0.1.0")
    study_version.update_state({ state: :standard })
    expect(study_version.state).to eq("standard")
    expect(study_version.semantic_version).to eq("1.0.0")
  end

  it "allows a study version to be cloned, incomplete state" do
    study_version = StudyVersion.new
    form1 = create_form(study_version, "XXX1", "http://www.example.com/form", "F1", 1, "Label 1")
    form2 = create_form(study_version, "XXX2", "http://www.example.com/form", "F2", 2, "Label 2")
    form3 = create_form(study_version, "XXX2", "http://www.example.com/form", "F3", 3, "Label 3")
    visit1 = create_visit(study_version, "V1", "Visit 1", "Day 0", 1)
    visit2 = create_visit(study_version, "V2", "Visit 2", "Day 7", 2)
    element1 = create_element(study_version, form1, visit1)
    element2 = create_element(study_version, form2, visit1)
    study_version.state = StudyVersion.states[:incomplete]
    study_version.semantic_version = "0.1.0"
    study_version.version = 1
    new_version = study_version.clone
    expect(new_version.version).to eq(2)
    expect(new_version.semantic_version).to eq("0.2.0")
    forms = Form.where(study_version_id: new_version.id)
    visits = Visit.where(study_version_id: new_version.id)
    elements = Element.where(study_version_id: new_version.id)
    expect(forms.count).to eq(3)
    expect(visits.count).to eq(2)
    expect(elements.count).to eq(2)
  end

  it "allows a study version to be cloned, qualified state" do
    study_version = StudyVersion.new
    form1 = create_form(study_version, "XXX1", "http://www.example.com/form", "F1", 1, "Label 1")
    form2 = create_form(study_version, "XXX2", "http://www.example.com/form", "F2", 2, "Label 2")
    form3 = create_form(study_version, "XXX2", "http://www.example.com/form", "F3", 3, "Label 3")
    visit1 = create_visit(study_version, "V1", "Visit 1", "Day 0", 1)
    visit2 = create_visit(study_version, "V2", "Visit 2", "Day 7", 2)
    element1 = create_element(study_version, form1, visit1)
    element2 = create_element(study_version, form2, visit1)
    study_version.state = StudyVersion.states[:qualified]
    study_version.semantic_version = "0.1.0"
    study_version.version = 1
    new_version = study_version.clone
    expect(new_version.version).to eq(2)
    expect(new_version.semantic_version).to eq("0.2.0")
    forms = Form.where(study_version_id: new_version.id)
    visits = Visit.where(study_version_id: new_version.id)
    elements = Element.where(study_version_id: new_version.id)
    expect(forms.count).to eq(3)
    expect(visits.count).to eq(2)
    expect(elements.count).to eq(2)
  end

  it "allows a study version to be cloned, standard state" do
    study_version = StudyVersion.new
    form1 = create_form(study_version, "XXX1", "http://www.example.com/form", "F1", 1, "Label 1")
    form2 = create_form(study_version, "XXX2", "http://www.example.com/form", "F2", 2, "Label 2")
    form3 = create_form(study_version, "XXX2", "http://www.example.com/form", "F3", 3, "Label 3")
    visit1 = create_visit(study_version, "V1", "Visit 1", "Day 0", 1)
    visit2 = create_visit(study_version, "V2", "Visit 2", "Day 7", 2)
    element1 = create_element(study_version, form1, visit1)
    element2 = create_element(study_version, form2, visit1)
    study_version.state = StudyVersion.states[:standard]
    study_version.semantic_version = "1.0.0"
    study_version.version = 1
    new_version = study_version.clone
    expect(new_version.version).to eq(2)
    expect(new_version.semantic_version).to eq("1.1.0")
    forms = Form.where(study_version_id: new_version.id)
    visits = Visit.where(study_version_id: new_version.id)
    elements = Element.where(study_version_id: new_version.id)
    expect(forms.count).to eq(3)
    expect(visits.count).to eq(2)
    expect(elements.count).to eq(2)
  end

  it "allows the soa to be generated" do
    study_version = StudyVersion.new
    form1 = create_form(study_version, "XXX1", "http://www.example.com/form", "F1", 1, "Label 1")
    form2 = create_form(study_version, "XXX2", "http://www.example.com/form", "F2", 2, "Label 2")
    form3 = create_form(study_version, "XXX2", "http://www.example.com/form", "F3", 3, "Label 3")
    visit1 = create_visit(study_version, "V1", "Visit 1", "Day 0", 1)
    visit2 = create_visit(study_version, "V2", "Visit 2", "Day 7", 2)
    element1 = create_element(study_version, form1, visit1)
    element2 = create_element(study_version, form2, visit1)
    element3 = create_element(study_version, form3, visit2)
    result = study_version.soa
    #write_text_file(result, sub_dir, "study_version_soa_1.htm")
    expected = read_text_file(sub_dir, "study_version_soa_1.htm")
    expected = expected.gsub("___FORM1___", "#{form1.id}")
    expected = expected.gsub("___FORM2___", "#{form2.id}")
    expected = expected.gsub("___FORM3___", "#{form3.id}")
    expected = expected.gsub("___VISIT1___", "#{visit1.id}")
    expected = expected.gsub("___VISIT2___", "#{visit2.id}")
    expected = expected.gsub("___ELEMENT1___", "#{element1.id}")
    expected = expected.gsub("___ELEMENT2___", "#{element2.id}")
    expected = expected.gsub("___ELEMENT3___", "#{element3.id}")
    expected = Nokogiri::HTML(expected)
    result = Nokogiri::HTML(result)
    expected_table = expected.xpath('//table')
    result_table = result.xpath('//table')
    expect(result_table.search('tr').count).to eq(expected_table.search('tr').count)
    expect(result_table.search('td').count).to eq(expected_table.search('td').count)
    # expect(result).to eq(expected)
  end

  it "allows a hash to be generated" do
    study = Study.create(identifier: "XXX", label: "label for")
    study_version = StudyVersion.new
    study_version.semantic_version = "0.1.0"
    study_version.version = 1
    study_version.state = "standard"
    study_version.description = "Description"
    study_version.name = "Name"
    study_version.protocol_name = "Protcol Name"
    study_version.study_id = study.id
    study_version.save
    form1 = create_form(study_version, "XXX1", "http://www.example.com/form", "F1", 1, "Label 1")
    form2 = create_form(study_version, "XXX2", "http://www.example.com/form", "F2", 2, "Label 2")
    form3 = create_form(study_version, "XXX2", "http://www.example.com/form", "F3", 3, "Label 3")
    result = study_version.to_hash
    #write_yaml_file(result, sub_dir, "study_version_hash_1.yaml")
    expected = read_yaml_file(sub_dir, "study_version_hash_1.yaml")
    expected[:id] = study_version.id # Fix the study id as can be predicted
    expected[:children][0][:id] = form1.id # Fix the form ids as they are dynamic
    expected[:children][1][:id] = form2.id
    expected[:children][2][:id] = form3.id
    expect(result).to eq(expected)
  end

  it "allows a full hash to be generated" do
    study = Study.create(identifier: "XXX", label: "label for")
    study_version = StudyVersion.new
    study_version.semantic_version = "0.1.0"
    study_version.version = 1
    study_version.state = "standard"
    study_version.description = "Description"
    study_version.name = "Name"
    study_version.protocol_name = "Protcol Name"
    study_version.study_id = study.id
    study_version.save
    form1 = create_form(study_version, "XXX1", "http://www.example.com/form", "F1", 1, "Label 1")
    form2 = create_form(study_version, "XXX2", "http://www.example.com/form", "F2", 2, "Label 2")
    form_json_1 = read_yaml_file(sub_dir, "form_json_1.yaml")
    form_json_2 = read_yaml_file(sub_dir, "form_json_2.yaml")
    expect(Mdr).to receive(:form_to_hash).with("XXX1", "http://www.example.com/form").and_return(form_json_1)
    expect(Mdr).to receive(:form_to_hash).with("XXX2", "http://www.example.com/form").and_return(form_json_2)
    result = study_version.to_full_hash
    #write_yaml_file(result, sub_dir, "study_version_hash_2.yaml")
    expected = read_yaml_file(sub_dir, "study_version_hash_2.yaml")
    expected[:id] = study_version.id # Fix the study id as can be predicted
    expect(result).to eq(expected)
  end

  it "next clone version" do
    study_version = StudyVersion.new
    study_version.semantic_version = "0.1.0"
    study_version.version = 1
    study_version.next_clone_version
    expect(study_version.version).to eq(2)
    expect(study_version.semantic_version).to eq("0.2.0")
  end

  it "next state version, qualified" do
    study_version = StudyVersion.new
    study_version.semantic_version = "0.10.0"
    study_version.version = 10
    study_version.state = StudyVersion.states[:qualified]
    study_version.next_state_version
    expect(study_version.version).to eq(10)
    expect(study_version.semantic_version).to eq("0.11.0")
  end

  it "next state version, standard" do
    study_version = StudyVersion.new
    study_version.semantic_version = "0.10.0"
    study_version.version = 10
    study_version.state = StudyVersion.states[:standard]
    study_version.next_state_version
    expect(study_version.version).to eq(10)
    expect(study_version.semantic_version).to eq("1.0.0")
  end

end
</code>```

答:
The uuid is automatic genereated strings which come from neo4j.
And above you found the uuid with number 1, but uuid is not a number, it's a string like b73905f-d72a-4446-85bc-b6bd10cd0ecf.
So the solution is that, you have to find element by correct uuid, or make a exception process.</p>

Body:
I'm working on the tests for a Rails 4 app which was migrated recently to Neo4j. My tests are failing and I cannot find a way or good reference to resolve my situation. I stuck completely.
The error I have which I need assistance: Neo4j::ActiveNode::Labels::RecordNotFound: Couldn't find Study with 'uuid'=1
Is related to the next line of code: study_version = StudyVersion.create(study_id: 1, name: "Name", description: "description", protocol_name: "protocol_name", state: StudyVersion.states[:qualified], version: 1, semantic_version: "0.1.0")

I would like to understand how to fix this.

Next myall model_speccode:

require 'rails_helper'

describe Study do

  include FileHelpers

  def sub_dir
    return "models"
  end

  def create_form(study_version, form_id, form_namespace, identifier, ordinal, label)
    form = Form.create(study_version_id: study_version.id, ordinal: ordinal, form_id: form_id,
                       form_namespace: form_namespace, identifier: identifier, label: label)
    return form
  end

  def new_form(study_version, form_id, form_namespace, identifier, ordinal, label)
    form = Form.new(study_version_id: study_version.id, ordinal: ordinal, form_id: form_id,
                    form_namespace: form_namespace, identifier: identifier, label: label)
    return form
  end

  def create_visit(study_version, short_name, long_name, timing, ordinal)
    visit = Visit.create(study_version_id: study_version.id, ordinal: ordinal, short_name: short_name, long_name: long_name, timing: timing)
    return visit
  end

  def new_visit(study_version, short_name, long_name, timing, ordinal)
    visit = Visit.new(study_version_id: study_version.id, ordinal: ordinal, short_name: short_name, long_name: long_name, timing: timing)
    return visit
  end

  def create_element(study_version, form, visit)
    element = Element.create(study_version_id: study_version.id, form_id: form.id, visit_id: visit.id)
    return element
  end

  def new_element(study_version, form, visit)
    element = Element.new(study_version_id: study_version.id, form_id: form.id, visit_id: visit.id)
    return element
  end

  before :each do
    Form.destroy_all
    Visit.destroy_all
    Element.destroy_all
    StudyVersion.destroy_all
  end

  after :each do
    Form.destroy_all
    Visit.destroy_all
    Element.destroy_all
    StudyVersion.destroy_all
  end

  it "edits a version, no clone" do
    study_version = StudyVersion.create(study_id: 1, name: "Name", description: "description", protocol_name: "protocol_name",
                                        state: StudyVersion.states[:incomplete], version: 1, semantic_version: "0.1.0")
    new_version = study_version.edit_version
    expect(new_version.id).to eq(study_version.id)
  end

  it "edits a version, clone" do
    study_version = StudyVersion.create(study_id: 1, name: "Name", description: "description", protocol_name: "protocol_name",
                                        state: StudyVersion.states[:qualified], version: 1, semantic_version: "0.1.0")
    new_version = study_version.edit_version
    expect(new_version.id).to_not eq(study_version.id)
  end

  it "updates the state" do
    study_version = StudyVersion.create(study_id: 1, name: "Name", description: "description", protocol_name: "protocol_name",
                                        state: StudyVersion.states[:qualified], version: 1, semantic_version: "0.1.0")
    study_version.update_state({ state: :standard })
    expect(study_version.state).to eq("standard")
    expect(study_version.semantic_version).to eq("1.0.0")
  end

  it "allows a study version to be cloned, incomplete state" do
    study_version = StudyVersion.new
    form1 = create_form(study_version, "XXX1", "http://www.example.com/form", "F1", 1, "Label 1")
    form2 = create_form(study_version, "XXX2", "http://www.example.com/form", "F2", 2, "Label 2")
    form3 = create_form(study_version, "XXX2", "http://www.example.com/form", "F3", 3, "Label 3")
    visit1 = create_visit(study_version, "V1", "Visit 1", "Day 0", 1)
    visit2 = create_visit(study_version, "V2", "Visit 2", "Day 7", 2)
    element1 = create_element(study_version, form1, visit1)
    element2 = create_element(study_version, form2, visit1)
    study_version.state = StudyVersion.states[:incomplete]
    study_version.semantic_version = "0.1.0"
    study_version.version = 1
    new_version = study_version.clone
    expect(new_version.version).to eq(2)
    expect(new_version.semantic_version).to eq("0.2.0")
    forms = Form.where(study_version_id: new_version.id)
    visits = Visit.where(study_version_id: new_version.id)
    elements = Element.where(study_version_id: new_version.id)
    expect(forms.count).to eq(3)
    expect(visits.count).to eq(2)
    expect(elements.count).to eq(2)
  end

  it "allows a study version to be cloned, qualified state" do
    study_version = StudyVersion.new
    form1 = create_form(study_version, "XXX1", "http://www.example.com/form", "F1", 1, "Label 1")
    form2 = create_form(study_version, "XXX2", "http://www.example.com/form", "F2", 2, "Label 2")
    form3 = create_form(study_version, "XXX2", "http://www.example.com/form", "F3", 3, "Label 3")
    visit1 = create_visit(study_version, "V1", "Visit 1", "Day 0", 1)
    visit2 = create_visit(study_version, "V2", "Visit 2", "Day 7", 2)
    element1 = create_element(study_version, form1, visit1)
    element2 = create_element(study_version, form2, visit1)
    study_version.state = StudyVersion.states[:qualified]
    study_version.semantic_version = "0.1.0"
    study_version.version = 1
    new_version = study_version.clone
    expect(new_version.version).to eq(2)
    expect(new_version.semantic_version).to eq("0.2.0")
    forms = Form.where(study_version_id: new_version.id)
    visits = Visit.where(study_version_id: new_version.id)
    elements = Element.where(study_version_id: new_version.id)
    expect(forms.count).to eq(3)
    expect(visits.count).to eq(2)
    expect(elements.count).to eq(2)
  end

  it "allows a study version to be cloned, standard state" do
    study_version = StudyVersion.new
    form1 = create_form(study_version, "XXX1", "http://www.example.com/form", "F1", 1, "Label 1")
    form2 = create_form(study_version, "XXX2", "http://www.example.com/form", "F2", 2, "Label 2")
    form3 = create_form(study_version, "XXX2", "http://www.example.com/form", "F3", 3, "Label 3")
    visit1 = create_visit(study_version, "V1", "Visit 1", "Day 0", 1)
    visit2 = create_visit(study_version, "V2", "Visit 2", "Day 7", 2)
    element1 = create_element(study_version, form1, visit1)
    element2 = create_element(study_version, form2, visit1)
    study_version.state = StudyVersion.states[:standard]
    study_version.semantic_version = "1.0.0"
    study_version.version = 1
    new_version = study_version.clone
    expect(new_version.version).to eq(2)
    expect(new_version.semantic_version).to eq("1.1.0")
    forms = Form.where(study_version_id: new_version.id)
    visits = Visit.where(study_version_id: new_version.id)
    elements = Element.where(study_version_id: new_version.id)
    expect(forms.count).to eq(3)
    expect(visits.count).to eq(2)
    expect(elements.count).to eq(2)
  end

  it "allows the soa to be generated" do
    study_version = StudyVersion.new
    form1 = create_form(study_version, "XXX1", "http://www.example.com/form", "F1", 1, "Label 1")
    form2 = create_form(study_version, "XXX2", "http://www.example.com/form", "F2", 2, "Label 2")
    form3 = create_form(study_version, "XXX2", "http://www.example.com/form", "F3", 3, "Label 3")
    visit1 = create_visit(study_version, "V1", "Visit 1", "Day 0", 1)
    visit2 = create_visit(study_version, "V2", "Visit 2", "Day 7", 2)
    element1 = create_element(study_version, form1, visit1)
    element2 = create_element(study_version, form2, visit1)
    element3 = create_element(study_version, form3, visit2)
    result = study_version.soa
    #write_text_file(result, sub_dir, "study_version_soa_1.htm")
    expected = read_text_file(sub_dir, "study_version_soa_1.htm")
    expected = expected.gsub("___FORM1___", "#{form1.id}")
    expected = expected.gsub("___FORM2___", "#{form2.id}")
    expected = expected.gsub("___FORM3___", "#{form3.id}")
    expected = expected.gsub("___VISIT1___", "#{visit1.id}")
    expected = expected.gsub("___VISIT2___", "#{visit2.id}")
    expected = expected.gsub("___ELEMENT1___", "#{element1.id}")
    expected = expected.gsub("___ELEMENT2___", "#{element2.id}")
    expected = expected.gsub("___ELEMENT3___", "#{element3.id}")
    expected = Nokogiri::HTML(expected)
    result = Nokogiri::HTML(result)
    expected_table = expected.xpath('//table')
    result_table = result.xpath('//table')
    expect(result_table.search('tr').count).to eq(expected_table.search('tr').count)
    expect(result_table.search('td').count).to eq(expected_table.search('td').count)
    # expect(result).to eq(expected)
  end

  it "allows a hash to be generated" do
    study = Study.create(identifier: "XXX", label: "label for")
    study_version = StudyVersion.new
    study_version.semantic_version = "0.1.0"
    study_version.version = 1
    study_version.state = "standard"
    study_version.description = "Description"
    study_version.name = "Name"
    study_version.protocol_name = "Protcol Name"
    study_version.study_id = study.id
    study_version.save
    form1 = create_form(study_version, "XXX1", "http://www.example.com/form", "F1", 1, "Label 1")
    form2 = create_form(study_version, "XXX2", "http://www.example.com/form", "F2", 2, "Label 2")
    form3 = create_form(study_version, "XXX2", "http://www.example.com/form", "F3", 3, "Label 3")
    result = study_version.to_hash
    #write_yaml_file(result, sub_dir, "study_version_hash_1.yaml")
    expected = read_yaml_file(sub_dir, "study_version_hash_1.yaml")
    expected[:id] = study_version.id # Fix the study id as can be predicted
    expected[:children][0][:id] = form1.id # Fix the form ids as they are dynamic
    expected[:children][1][:id] = form2.id
    expected[:children][2][:id] = form3.id
    expect(result).to eq(expected)
  end

  it "allows a full hash to be generated" do
    study = Study.create(identifier: "XXX", label: "label for")
    study_version = StudyVersion.new
    study_version.semantic_version = "0.1.0"
    study_version.version = 1
    study_version.state = "standard"
    study_version.description = "Description"
    study_version.name = "Name"
    study_version.protocol_name = "Protcol Name"
    study_version.study_id = study.id
    study_version.save
    form1 = create_form(study_version, "XXX1", "http://www.example.com/form", "F1", 1, "Label 1")
    form2 = create_form(study_version, "XXX2", "http://www.example.com/form", "F2", 2, "Label 2")
    form_json_1 = read_yaml_file(sub_dir, "form_json_1.yaml")
    form_json_2 = read_yaml_file(sub_dir, "form_json_2.yaml")
    expect(Mdr).to receive(:form_to_hash).with("XXX1", "http://www.example.com/form").and_return(form_json_1)
    expect(Mdr).to receive(:form_to_hash).with("XXX2", "http://www.example.com/form").and_return(form_json_2)
    result = study_version.to_full_hash
    #write_yaml_file(result, sub_dir, "study_version_hash_2.yaml")
    expected = read_yaml_file(sub_dir, "study_version_hash_2.yaml")
    expected[:id] = study_version.id # Fix the study id as can be predicted
    expect(result).to eq(expected)
  end

  it "next clone version" do
    study_version = StudyVersion.new
    study_version.semantic_version = "0.1.0"
    study_version.version = 1
    study_version.next_clone_version
    expect(study_version.version).to eq(2)
    expect(study_version.semantic_version).to eq("0.2.0")
  end

  it "next state version, qualified" do
    study_version = StudyVersion.new
    study_version.semantic_version = "0.10.0"
    study_version.version = 10
    study_version.state = StudyVersion.states[:qualified]
    study_version.next_state_version
    expect(study_version.version).to eq(10)
    expect(study_version.semantic_version).to eq("0.11.0")
  end

  it "next state version, standard" do
    study_version = StudyVersion.new
    study_version.semantic_version = "0.10.0"
    study_version.version = 10
    study_version.state = StudyVersion.states[:standard]
    study_version.next_state_version
    expect(study_version.version).to eq(10)
    expect(study_version.semantic_version).to eq("1.0.0")
  end

end


答:
Assign weightsum and weights to divide space into equal halfs

```<code>LinearLayout.LayoutParams params = new LinearLayout.LayoutParams
                                (LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                        category_layout.setWeightSum(2);
                        params.setMargins(15, 5, 5, 10);
                        category_layout.setLayoutParams(params);

    LinearLayout.LayoutParams titleParams = (LinearLayout.LayoutParams) category_layout.getLayoutParams();
    titleParams.weight = 1;
    category_title.setGravity(Gravity.START);
    category_title.setLayoutParams(titleParams);

    LinearLayout.LayoutParams moreParams = (LinearLayout.LayoutParams) category_layout.getLayoutParams();
    moreParams.weight = 1;
    category_more.setGravity(Gravity.END);
    category_more.setLayoutParams(moreParams);
</code>```

Title: Add 2 TextView into LinearLayout(one align left and one align right)

Body:
Assign weightsum and weights to divide space into equal halfs

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams
                                (LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                        category_layout.setWeightSum(2);
                        params.setMargins(15, 5, 5, 10);
                        category_layout.setLayoutParams(params);

    LinearLayout.LayoutParams titleParams = (LinearLayout.LayoutParams) category_layout.getLayoutParams();
    titleParams.weight = 1;
    category_title.setGravity(Gravity.START);
    category_title.setLayoutParams(titleParams);

    LinearLayout.LayoutParams moreParams = (LinearLayout.LayoutParams) category_layout.getLayoutParams();
    moreParams.weight = 1;
    category_more.setGravity(Gravity.END);
    category_more.setLayoutParams(moreParams);


问:
I am attempting to add two models from separate local apps into one template
I am trying to access Content from content.models and Post from Post.models in the blog.html template. The idea for Content is to be able to edit text on the site through the django admin.

The directory stucture is as follows:

```<code> - src [Folder]
   - content [Folder]
     - migrations [Folder]
     - __init__.py
     - admin.py
     - apps.py
     - models.py
     - tests.py
     - views.py
  - main [Folder]
     - settings [Folder]
         - __init__.py
         - base.py
     - migrations [Folder]
     - __init__.py
     - db.sqlite3
     - models.py
     - urls.py
     - views.py
     - wsgi.py
  - posts [Folder]
     - migrations [Folder]
     - templatetags [Folder]
     - __init__.py
     - admin.py
     - apps.py
     - forms.py
     - models.py
     - tests.py
     - urls.py
     - utils.py
     - views.py
    - templates
     - base.html
     - blogbase.html
</code>```

views.py - main looks is as follows:

```<code>from django.shortcuts import render

from django.http import HttpResponse
from django.views.generic import View
from django.views.generic.base import TemplateView, TemplateResponseMixin, ContextMixin

# from posts.models import Post, Content
# from app.models import *
from posts.models import Post
from content.models import Content

class DashboardTemplateView(TemplateView):
    template_name = "base.html"
    context_object_name = 'name'

    def get_context_data(self, *args, **kwargs):
        context = super(DashboardTemplateView,self).get_context_data(*args, **kwargs)
        context["title"] = "This is about us"
        return context

class MyView(ContextMixin, TemplateResponseMixin, View):
    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
        context = {'content_list' : Content.objects.all(), 'post_list':Post.objects.all()}
        return self.render_to_response(context)
</code>```

my models.py - main is as follows:

```<code>from django.db import models

from post.models import Post
from context.models import Contest
</code>```

my urls.py - main is as follows:

```<code>from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.db import models
from django.views.generic import ListView

from accounts.views import (login_view, register_view, logout_view)
# from views import *

urlpatterns = [

    url(r'^admin/', admin.site.urls),
    url(r'^comments/', include("comments.urls", namespace='comments')),

    url(r'^register/', register_view, name='register'),
    url(r'^login/', login_view, name='login'),
    url(r'^logout/', logout_view, name='logout'),
    url(r'^', include("posts.urls", namespace='posts')),

    # The line below does not work
    # url(r'^', DashboardTemplateView.as_view(template_name=('base.html')), name='name'),

]

if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
</code>```

When I add in the line that doesn't work

```<code>url(r'^', DashboardTemplateView.as_view(template_name=('base.html')), name='name'),
</code>```

to the url patterns I get the following error

File
  "blog/src/main/urls.py",
  line 39, in
      url(r'^', DashboardTemplateView.as_view(template_name=('base.html')),
  name='name'), NameError: name 'DashboardTemplateView' is not defined

I am using django 1.9 and python 2.7

答:
It seems that your urls.py has no access to DashboardTemplateView because you have not imported it. To solve this:

Import this module into your urls.py, by typing:

from posts import views as posts_views

When you are building your url, reference it as posts_views.DashboardTemplateView instead of just DashboardTemplateView

url(r'^', posts_view.DashboardTemplateView.as_view(template_name=('base.html')), name='name'),

Hope this helps.

Body:
I am trying to access Content from content.models and Post from Post.models in the blog.html template. The idea for Content is to be able to edit text on the site through the django admin.

The directory stucture is as follows:

 - src [Folder]
   - content [Folder]
     - migrations [Folder]
     - __init__.py
     - admin.py
     - apps.py
     - models.py
     - tests.py
     - views.py
  - main [Folder]
     - settings [Folder]
         - __init__.py
         - base.py
     - migrations [Folder]
     - __init__.py
     - db.sqlite3
     - models.py
     - urls.py
     - views.py
     - wsgi.py
  - posts [Folder]
     - migrations [Folder]
     - templatetags [Folder]
     - __init__.py
     - admin.py
     - apps.py
     - forms.py
     - models.py
     - tests.py
     - urls.py
     - utils.py
     - views.py
    - templates
     - base.html
     - blogbase.html

views.py - main looks is as follows:

from django.shortcuts import render

from django.http import HttpResponse
from django.views.generic import View
from django.views.generic.base import TemplateView, TemplateResponseMixin, ContextMixin

# from posts.models import Post, Content
# from app.models import *
from posts.models import Post
from content.models import Content

class DashboardTemplateView(TemplateView):
    template_name = "base.html"
    context_object_name = 'name'

    def get_context_data(self, *args, **kwargs):
        context = super(DashboardTemplateView,self).get_context_data(*args, **kwargs)
        context["title"] = "This is about us"
        return context

class MyView(ContextMixin, TemplateResponseMixin, View):
    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
        context = {'content_list' : Content.objects.all(), 'post_list':Post.objects.all()}
        return self.render_to_response(context)

my models.py - main is as follows:

from django.db import models

from post.models import Post
from context.models import Contest

my urls.py - main is as follows:

from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.db import models
from django.views.generic import ListView

from accounts.views import (login_view, register_view, logout_view)
# from views import *

urlpatterns = [

    url(r'^admin/', admin.site.urls),
    url(r'^comments/', include("comments.urls", namespace='comments')),

    url(r'^register/', register_view, name='register'),
    url(r'^login/', login_view, name='login'),
    url(r'^logout/', logout_view, name='logout'),
    url(r'^', include("posts.urls", namespace='posts')),

    # The line below does not work
    # url(r'^', DashboardTemplateView.as_view(template_name=('base.html')), name='name'),

]

if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

When I add in the line that doesn't work

url(r'^', DashboardTemplateView.as_view(template_name=('base.html')), name='name'),

to the url patterns I get the following error

File
  "blog/src/main/urls.py",
  line 39, in
      url(r'^', DashboardTemplateView.as_view(template_name=('base.html')),
  name='name'), NameError: name 'DashboardTemplateView' is not defined

I am using django 1.9 and python 2.7


问:
Python Selenium, Scraping dynamic drop down
I am using Selenium and python for web scraping and the page that i am using for testing this link

But the problem is i am not able to handle the dynamic content of the drop down, here is the problem arises

While selecting the state, the city is loaded based on the state, Some Php and js are going in the back end as far as i know.

So, i searched the web and came with a solution to wait for the sometime please use this link as reference.

The following is a part of my code

```<code>from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support.ui import WebDriverWait

from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

chrome_path = r"E:\chromedriver.exe"

driver = webdriver.Chrome(chrome_path)

driver.get("http://www.blooddonors.in")
select = Select(driver.find_element_by_xpath('/html/body/table[3]/tbody/tr/td[2]/table[1]/tbody/tr/td/form/table/tbody/tr[2]/td[1]/select'))

select.select_by_visible_text('Tamil Nadu')
driver.implicitly_wait(60)
drop = Select(driver.find_element_by_xpath('//*[@id="div_city"]/select'))
select.select_by_visible_text('Coimbotore')
</code>```

I am using a windows sys and i tried using CMD. It doesn't need a wait function it works fine without it.

The error that i am facing is:

```<code>raise NoSuchElementException("Could not locate element with visible text: %s" % text)
selenium.common.exceptions.NoSuchElementException: Message: Could not locate element with visible text: Coimbotore
</code>```

But their it is actually their.

If someone can help me resolve the issue it would be great and i can move on to the next.

Thanks

答:
Selenium provides a select class which can be used to grab elements from drop-down menu.</p>

```<code>select = Select(driver.find_element_by_id('city'))
select.select_by_value('430') #search by value, coimbotore is 430
</code>```

Body:
I am using Selenium and python for web scraping and the page that i am using for testing this link

But the problem is i am not able to handle the dynamic content of the drop down, here is the problem arises

While selecting the state, the city is loaded based on the state, Some Php and js are going in the back end as far as i know.

So, i searched the web and came with a solution to wait for the sometime please use this link as reference.

The following is a part of my code

from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support.ui import WebDriverWait

from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

chrome_path = r"E:\chromedriver.exe"

driver = webdriver.Chrome(chrome_path)

driver.get("http://www.blooddonors.in")
select = Select(driver.find_element_by_xpath('/html/body/table[3]/tbody/tr/td[2]/table[1]/tbody/tr/td/form/table/tbody/tr[2]/td[1]/select'))

select.select_by_visible_text('Tamil Nadu')
driver.implicitly_wait(60)
drop = Select(driver.find_element_by_xpath('//*[@id="div_city"]/select'))
select.select_by_visible_text('Coimbotore')

I am using a windows sys and i tried using CMD. It doesn't need a wait function it works fine without it.

The error that i am facing is:

raise NoSuchElementException("Could not locate element with visible text: %s" % text)
selenium.common.exceptions.NoSuchElementException: Message: Could not locate element with visible text: Coimbotore

But their it is actually their.

If someone can help me resolve the issue it would be great and i can move on to the next.

Thanks

Body:
Selenium provides a select class which can be used to grab elements from drop-down menu.

select = Select(driver.find_element_by_id('city'))
select.select_by_value('430') #search by value, coimbotore is 430


问:
How to migrate user and organization in chef-server to newly created chef server?
I am using standalone chef-server now. I got a issue to change the server, so I followed the process stated in here: https://www.ameir.net/blog/archives/326-migrating-from-one-chef-server-to-another.html

The problem is there is no way to use existed user and organization in new  chef server. The workaround I found is to make new user and add existed key to the user. I think it's not a proper way to do what I want, and even more organization is not available for this way.

I think when chef-server create new user and organization, if it has some way to add existed key by parameter, that's enough.

Is there any way to achieve my purpose?

答: You can use chef-server-ctl backup to generate a backup and then restore it to the new server.