问:
Delete list-rows where an element contains a string
I have a list where the columns all have the same length,

```<code>ll<-list("a"=c(1:5),
         "b"=c(1:5)*10,
         "c"="one","two","three","four","five")
</code>```

and I would like to remove all rows where ll$c=="one". With dataframes I can use ll[- grep("one", ll$c),], but that doesn't work for lists.

Is there a way to generalize the method to work for lists as well?

答:
If all elements of you list are of the same length, maybe you should be using a data.frame. However, Assuming that you want to remove elements within each list element that correspond to the position where ll$c == "one", you could use the following lapply.

```<code>lapply(ll, "[", ll$c != "one")
$a
[1] 2 3 4 5

$b
[1] 20 30 40 50

$c
[1] "two"   "three" "four"  "five"
</code>```

The second argument indicates the subsetting or extraction function, see ?"[" and the third argument is used to feed the subsetting function with a vector of logicals the same length as ll$c (and the rest of the list elements).

If there are many list elements, it would be more efficient to calculate the logical vector once initially and then refer to it repeatedly.

```<code>keepers <- ll$c != "one"
lapply(ll, "[", keepers)
</code>```

data

```<code>ll <-
structure(list(a = 1:5, b = c(10, 20, 30, 40, 50), c = c("one",
"two", "three", "four", "five")), .Names = c("a", "b", "c"))
</code>```

Body:
I have a list where the columns all have the same length,

ll<-list("a"=c(1:5),
         "b"=c(1:5)*10,
         "c"="one","two","three","four","five")

and I would like to remove all rows where ll$c=="one". With dataframes I can use ll[- grep("one", ll$c),], but that doesn't work for lists.

Is there a way to generalize the method to work for lists as well?

Body:
If all elements of you list are of the same length, maybe you should be using a data.frame. However, Assuming that you want to remove elements within each list element that correspond to the position where ll$c == "one", you could use the following lapply.

lapply(ll, "[", ll$c != "one")
$a
[1] 2 3 4 5

$b
[1] 20 30 40 50

$c
[1] "two"   "three" "four"  "five"

The second argument indicates the subsetting or extraction function, see ?"[" and the third argument is used to feed the subsetting function with a vector of logicals the same length as ll$c (and the rest of the list elements).

If there are many list elements, it would be more efficient to calculate the logical vector once initially and then refer to it repeatedly.

keepers <- ll$c != "one"
lapply(ll, "[", keepers)

data

ll <-
structure(list(a = 1:5, b = c(10, 20, 30, 40, 50), c = c("one",
"two", "three", "four", "five")), .Names = c("a", "b", "c"))


来源: stackexchange

问:
How to make a Swift Class Singleton instance thread safe?
I have a singleton class as so:

```<code>class Database {
   static let instance:Database = Database()
   private var db: Connection?

   private init(){
      do {
        db = try Connection("\(path)/SalesPresenterDatabase.sqlite3")
        }catch{print(error)}
   }
}
</code>```

Now I access this class using Database.instance.xxxxxx to perform a function within the class. However when I access the instance from another thread it throws bizarre results as if its trying to create another instance. Should I be referencing the instance in the same thread?

To clarify the bizarre results show database I/o errors because of two instances trying to access the db at once

Update

please see this question for more info on the database code: Using transactions to insert is throwing errors Sqlite.swift

答:
In Swift 3.0 add a private init to prevent others from using the default () initializer.</p>

```<code>class ClassName {
  static let sharedInstance = ClassName()
  private init() {} //This prevents others from using the default '()' initializer for this class.
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a singleton class as so:

class Database {
   static let instance:Database = Database()
   private var db: Connection?

   private init(){
      do {
        db = try Connection("\(path)/SalesPresenterDatabase.sqlite3")
        }catch{print(error)}
   }
}

Now I access this class using Database.instance.xxxxxx to perform a function within the class. However when I access the instance from another thread it throws bizarre results as if its trying to create another instance. Should I be referencing the instance in the same thread?

To clarify the bizarre results show database I/o errors because of two instances trying to access the db at once

Update

please see this question for more info on the database code: Using transactions to insert is throwing errors Sqlite.swift

Body:
In Swift 3.0 add a private init to prevent others from using the default () initializer.

class ClassName {
  static let sharedInstance = ClassName()
  private init() {} //This prevents others from using the default '()' initializer for this class.
}


问:
How to get different data in ng-repeat ? - AngularJS
I'm using AngularJS and I have created an web app.

I don't know how to get values from one specific link.

I have an admin page where I have all users and I get them using ng-repeat

```<code><div ng-repeat="user in allusers">
</code>```

But I have created routes for example user level and I have added them to http://mylink.com/user_level/john@doe.com -- (that's example so I will get user level via user email)

答:
The recommended approach would be to have the service that retrieves the users, send the user's level in the user object itself.

But, if this is not an option and you have to make separate service calls to get the user's level, this is how you would do this.

```<code>  function getUserLevels(users) {
    for(var i=0; i<users.length; i++) {
      getUserLevelForUser(users[i]);
    }
  }

  function getUserLevelForUser(user) {
    $http.get(BASE_URL + '/' + user.email)
      .then(function (response) {
          user.userLevel = response.data.userLevel;
        });
  }

  getUserLevels($scope.users);
</code>```

Since I do not have access to your API, I've created a plunker app that invokes the Open Movie Database API. In this demo, instead of the user's level, I will be fetching a movie's director. Also, instead of using the user's email in the url, I will be using the movie name.

See working plunker here

Body:
I'm using AngularJS and I have created an web app.

I don't know how to get values from one specific link.

I have an admin page where I have all users and I get them using ng-repeat

But I have created routes for example user level and I have added them to http://mylink.com/user_level/john@doe.com -- (that's example so I will get user level via user email)

Body:
The recommended approach would be to have the service that retrieves the users, send the user's level in the user object itself.

But, if this is not an option and you have to make separate service calls to get the user's level, this is how you would do this.

  function getUserLevels(users) {
    for(var i=0; i<users.length; i++) {
      getUserLevelForUser(users[i]);
    }
  }

  function getUserLevelForUser(user) {
    $http.get(BASE_URL + '/' + user.email)
      .then(function (response) {
          user.userLevel = response.data.userLevel;
        });
  }

  getUserLevels($scope.users);

Since I do not have access to your API, I've created a plunker app that invokes the Open Movie Database API. In this demo, instead of the user's level, I will be fetching a movie's director. Also, instead of using the user's email in the url, I will be using the movie name.

See working plunker here


问:
Issuse: Scipy Fitting Normal Data
I currently have some experiemental data imported and plotted which is normally distributed.

I then tried using Scipy to fit a normal distrubtion to the data:

```<code>from scipy.stats import norm

def normal_fit(data, offset):
    x = numpy.linspace(0, len(data), len(data))
    params = norm.fit(data - offset)
    normal = norm.pdf(x, params[0], params[1])

    return normal, params
</code>```

However it calculates a mean and standard deviation (4504, 2961) that is incorrect - plotted in red below.

How can I fit the data properly?

Edit: Data is offset to zero as suggested by ev-br, this produces parameters that still don't make much sense (954, 2961)

答: You need to subtract the zero level first.</p>

Title: Issuse: Scipy Fitting Normal Data

Body:
I currently have some experiemental data imported and plotted which is normally distributed.

I then tried using Scipy to fit a normal distrubtion to the data:

from scipy.stats import norm

def normal_fit(data, offset):
    x = numpy.linspace(0, len(data), len(data))
    params = norm.fit(data - offset)
    normal = norm.pdf(x, params[0], params[1])

    return normal, params

However it calculates a mean and standard deviation (4504, 2961) that is incorrect - plotted in red below.

How can I fit the data properly?

Edit: Data is offset to zero as suggested by ev-br, this produces parameters that still don't make much sense (954, 2961)


问:
ipad/iphone scrolling div - scroll bars to appear
I have a single page app which has scrolling DIVs as part of the UI on our iPhone/iPad app.

In HTML how do I get the div to show a scroll bar to visually indicated to the user that the area can scroll?

Ian

答: Mobile safari specifically disables scroll bars on overflowing scrollable divs. There is no easy way to enable this without building your own scrollable div visual indicator. </p>

ContentLicense: CC BY-SA 2.5


问:
Reduced size of dictionary elements when two lists combined into a dictionary
I have 2 lists that I combined their elements into a dictionary. Both lists have size of 20, and the created dictionary is almost always 13-15. The code is:

```<code>nodes = []
for x in range(1,21):
    nodes.append(str(random.randint(1,20)))
print(nodes)
</code>```

Output:

```<code>['3', '6', '10', '12', '12', '10', '11', '17', '6', '19', '20', '19', '7', '16', '9', '13', '15', '9', '12', '5']
</code>```

The rest of the code:

```<code>lines=[]

fp = open("work.txt") # open file on read mode
lines = fp.read().split("\n") # create a list containing all lines
fp.close() # close file
print(lines)
</code>```

Output:

```<code>['5', '1', '7', '1', '1', '3', '12', '1', '1', '8', '7', '5', '12', '5', '5', '3', '7', '7', '13', '1', '']
</code>```

To make a dictionary:

```<code>dictionary = dict(zip(nodes,lines))
print(dictionary)

{'3': '1', '6': '5', '10': '12', '12': '13', '10': '12', '11': '7', '17': '7', '6': '5', '19': '3', '20': '1', '19': '1', '17': '3', '16': '5', '9': '7'}
</code>```

As you see, the size is got smaller to 14 when zipped. Do you know what is the reason and how can I fix it?

NOTE: I have to keep all the keys. The duplicates in the lists are on purpose.
NOTE2: The output should have the format above, the pairs of two numbers. (1,3) or (1:3) but not (1:3,4).

Body:
I have 2 lists that I combined their elements into a dictionary. Both lists have size of 20, and the created dictionary is almost always 13-15. The code is:

nodes = []
for x in range(1,21):
    nodes.append(str(random.randint(1,20)))
print(nodes)

Output:

['3', '6', '10', '12', '12', '10', '11', '17', '6', '19', '20', '19', '7', '16', '9', '13', '15', '9', '12', '5']

The rest of the code:

lines=[]

fp = open("work.txt") # open file on read mode
lines = fp.read().split("\n") # create a list containing all lines
fp.close() # close file
print(lines)

Output:

['5', '1', '7', '1', '1', '3', '12', '1', '1', '8', '7', '5', '12', '5', '5', '3', '7', '7', '13', '1', '']

To make a dictionary:

dictionary = dict(zip(nodes,lines))
print(dictionary)

{'3': '1', '6': '5', '10': '12', '12': '13', '10': '12', '11': '7', '17': '7', '6': '5', '19': '3', '20': '1', '19': '1', '17': '3', '16': '5', '9': '7'}

As you see, the size is got smaller to 14 when zipped. Do you know what is the reason and how can I fix it?

NOTE: I have to keep all the keys. The duplicates in the lists are on purpose.
NOTE2: The output should have the format above, the pairs of two numbers. (1,3) or (1:3) but not (1:3,4).

Body:
Because you can't have duplicate key names in a dictionary

>>> nodes = ['3', '6', '10', '12', '12', '10', '11', '17', '6', '19', '20', '19', '7', '16', '9', '13', '15', '9', '12', '5']

>>> lines = ['5', '1', '7', '1', '1', '3', '12', '1', '1', '8', '7', '5', '12', '5', '5', '3', '7', '7', '13', '1', '']

>>> dictionary = dict(zip(nodes,lines))

>>> len(dictionary.keys())
14

There are only 14 unique elemens in nodes, which are your dictionary keys

>>> len(set(nodes))
14


答:
Your "key" list has duplicate items. Dictionaries require unique keys, previously entered keys are overwritten.

You can group items in a list as follows

```<code>result = {}
for key, item in zip(x, y):
    if key in result:
        result[key].append(item)
    else:
        result[key] = [item]
</code>```

Title: Reduced size of dictionary elements when two lists combined into a dictionary

Body:
Your "key" list has duplicate items. Dictionaries require unique keys, previously entered keys are overwritten.

You can group items in a list as follows

result = {}
for key, item in zip(x, y):
    if key in result:
        result[key].append(item)
    else:
        result[key] = [item]


问:
CSS-Grid columns do not align properly
Basically, I often run into this kind of issue, that the columns of my grid do not align as intended. (Bootstrap, Materializecss, and others) Everytime the same issue, sometimes I get it fixed, other times I struggle for hours trying to get it work.

That's really annyoing and I really wan't to know why this issue happens and how to solve it in future projects!

The problems is the following:

I have a layout example (jsfiddle), which I want to sovle. It's using Materializecss with some sections.

```<code>  Large View (with thumbnails right)           Mobile View
+----------------------+-------------+       +----------------------+
| Section 1            | Section 2   |       | Section 1            |
|                      |             |       |                      |
+----------------------+-------------+       +----------------------+
| Image Slider Section | Thumbnails  |       | Section 2            |
|                      | # # # # # # |       |                      |
|                      | # # # # # # |       +----------------------+
|                      | # # # # # # |       | Image Slider Section |
+----------------------+-------------+       |                      |
| Section 3            | Section 4   |       |                      |
|                      |             |       |                      |
|                      +-------------+       +----------------------+
|                      | Section 5   |       | Thumbnails           |
|                      |             |       |  # # # # # # # # # # |
+----------------------+-------------+       |  # # # # # # # # # # |
| Section 6                          |       +----------------------+
|                                    |       | Section 3            |
+----------------------+-------------+       |                      |
                                             |                      |
  Large View (with thumbnails bottom)        |                      |
+----------------------+-------------+       |                      |
| Section 1            | Section 2   |       |                      |
|                      |             |       +----------------------+
+----------------------+-------------+       | Section 4            |
| Image Slider Section | Section 4   |       |                      |
|                      |             |       +----------------------+
|                      +-------------+       | Section 5            |
|                      | Section 5   |       |                      |
+----------------------+             |       +----------------------+
| Thumbnails           |-------------+       | Section 6            |
| # # # # # # # # # # #|                     |                      |
+----------------------+                     +----------------------+
| Section 3            |
|                      |
|                      |
|                      |
|                      |
|                      |
+----------------------+-------------+
| Section 6                          |
|                                    |
+----------------------+-------------+

Both large views are valuable options.
</code>```

I've been told that I should structure and order my cols with mobile-first in mind. That's the HTML:

```<code><article>
  <div class="container">
    <div class="row">
      <section class="col s12 m8">
        <h5 class="teal-text">Share Buttons Section</h5>
      </section>

      <!--<section class="col s12 m4">-->
      <!--<h5 class="teal-text">Nothing (Just a Placeholder)</h5>-->
      <!--</section>-->

      <section class="col s12 m8">
        <h5 class="teal-text">Section 1</h5>
      </section>

      <section class="col s12 m4">
        <h5 class="teal-text">Section 2</h5>
      </section>

      <section class="col s12 m8">
        <h5 class="teal-text">Pushpin Nav</h5>
      </section>

      <section class="col s12 m8">
        <h5 class="teal-text">Slider Section</h5>
        <div class="col s2 amber" style="margin: 3px; width: 100%; height: 480px"></div>
      </section>

      <section class="col s12 m8">
        <h5 class="teal-text">Slider Thumbnails</h5>
        <div class="row">
          <div class="col s2 blue" style="margin: 3px; width: 48px; height: 48px"></div>
          <!--...-->
        </div>
      </section>

      <section class="col s12 m8">
        <h5 class="teal-text">Section 3</h5>
      </section>

      <section class="col s12 m4">
        <h5>Section 4</h5>
      </section>

      <section class="col s12 m4">
        <h5>Section 5</h5>
      </section>

      <section class="col s12">
        <h5>Section 6</h5>
      </section>
    </div>
  </div>
</article>
</code>```

This leaves some gaps in between the sections in the large view if the content of a section is bigger than the other remaining for this row.
Ok cool, so I came across push / pull, which I thought would reorder the columns, and fix the problem if I just push and pull them into the right order. But that causes just to "re-order" the offset in the horizontal space. Gaps still there.

What am I missing, to get the content stick together?

I really appreciate a detailed answer providing some examples, so I understand this kind of issue.

Link to my jsfiddle example:
https://jsfiddle.net/jkdzgafr/

答:
Space is because of float:left for the section. Try placing the Section 2 with float:right which will solve your problem.

About float: it is taken out of the normal flow of the document
  (though still remaining part of it). It is shifted to the left, or
  right until it touches the edge of its containing box, or another
  floated element.

The next float element is placed when the previous row left floated element height completes.

Title: CSS-Grid columns do not align properly

Body:
Basically, I often run into this kind of issue, that the columns of my grid do not align as intended. (Bootstrap, Materializecss, and others) Everytime the same issue, sometimes I get it fixed, other times I struggle for hours trying to get it work.

That's really annyoing and I really wan't to know why this issue happens and how to solve it in future projects!

The problems is the following:

I have a layout example (jsfiddle), which I want to sovle. It's using Materializecss with some sections.

  Large View (with thumbnails right)           Mobile View
+----------------------+-------------+       +----------------------+
| Section 1            | Section 2   |       | Section 1            |
|                      |             |       |                      |
+----------------------+-------------+       +----------------------+
| Image Slider Section | Thumbnails  |       | Section 2            |
|                      | # # # # # # |       |                      |
|                      | # # # # # # |       +----------------------+
|                      | # # # # # # |       | Image Slider Section |
+----------------------+-------------+       |                      |
| Section 3            | Section 4   |       |                      |
|                      |             |       |                      |
|                      +-------------+       +----------------------+
|                      | Section 5   |       | Thumbnails           |
|                      |             |       |  # # # # # # # # # # |
+----------------------+-------------+       |  # # # # # # # # # # |
| Section 6                          |       +----------------------+
|                                    |       | Section 3            |
+----------------------+-------------+       |                      |
                                             |                      |
  Large View (with thumbnails bottom)        |                      |
+----------------------+-------------+       |                      |
| Section 1            | Section 2   |       |                      |
|                      |             |       +----------------------+
+----------------------+-------------+       | Section 4            |
| Image Slider Section | Section 4   |       |                      |
|                      |             |       +----------------------+
|                      +-------------+       | Section 5            |
|                      | Section 5   |       |                      |
+----------------------+             |       +----------------------+
| Thumbnails           |-------------+       | Section 6            |
| # # # # # # # # # # #|                     |                      |
+----------------------+                     +----------------------+
| Section 3            |
|                      |
|                      |
|                      |
|                      |
|                      |
+----------------------+-------------+
| Section 6                          |
|                                    |
+----------------------+-------------+

Both large views are valuable options.

I've been told that I should structure and order my cols with mobile-first in mind. That's the HTML:

Share Buttons Section

Section 1

Section 2

Pushpin Nav

Slider Section

Slider Thumbnails

Section 3

Section 4

Section 5

Section 6

This leaves some gaps in between the sections in the large view if the content of a section is bigger than the other remaining for this row.
Ok cool, so I came across push / pull, which I thought would reorder the columns, and fix the problem if I just push and pull them into the right order. But that causes just to "re-order" the offset in the horizontal space. Gaps still there.

What am I missing, to get the content stick together?

I really appreciate a detailed answer providing some examples, so I understand this kind of issue.

Link to my jsfiddle example:
https://jsfiddle.net/jkdzgafr/


问:
Rundeck behind and SSL Proxy
I am currently trying to set up an environment with Rundeck running behind and nginx reverse ssl proxy. I found different tutorials online for this scenario but none of those worked for me. I am working in an linux environment where both rundeck and nginx run on. My nginx configuration file for rundeck loooks like this:

```<code>server {
        access_log   /var/log/nginx/rundeck.access.log  main;

        listen 443;
        listen       [::]:443;
        ssl    on;
        ssl_certificate    /etc/nginx/conf.d/cert.crt;
        ssl_certificate_key    /etc/nginx/conf.d/key.rsa;

        location / {
          proxy_pass http://localhost:4440/;
          proxy_set_header        Host            $host;
          proxy_set_header        X-Real-IP       $remote_addr;
          proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
          proxy_set_header X-Ssl on;
}

        error_page 404 /404.html;
            location = /40x.html {
        }

        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }
    }
</code>```

Furthermore I configured those parameters in rundeck:
framework.server.url = https://localhost:4440 and grails.serverURL=https://lde71d6p.de.top.com:443
I tried different combinations with https or only http, without port and with port. None of them works properly.

With the current configuration I get the following error situation.
If i try to call http://hostname.top.com -> Connection Error (seems fine because port 80 isn't handled by nginx)
https://hostname.top.com -> gets a 302 and is redirected to http://hostname.top.com/user/login;jsessionid=xxxxxxx and than gets an connection error.
https://hostname.top.com/user/login gets me straight to the login interface of rundeck. All fine.

Can anyone help me please to resolve the error situations I mentioned first?

Kind Regards,

Max

答:
To run Rundeck behind SSL proxy, you need the following three setting:

https://github.com/rundeck/rundeck/wiki/FAQ#can-i-do-ssl-offloading

Set up RunDeck as http

in profile file, add option -Drundeck.jetty.connector.forwarded=true to RDECK_JVM

Set framework.rundeck.url and grails.serverURL to use https

In your case, profile setting does not seem to have been done yet.

The profile is in /etc/rundeck/profile. (it may depend on the distribution)

Add options -Drundeck.jetty.connector.forwarded=true to RDECK_JVM as follows:

```<code>RDECK_JVM="-Djava.security.auth.login.config=$JAAS_CONF \
       -Dloginmodule.name=$LOGIN_MODULE \
       -Drdeck.config=$RDECK_CONFIG \
       -Drundeck.server.configDir=$RDECK_SERVER_CONFIG \
       -Dserver.datastore.path=$RDECK_SERVER_DATA/rundeck \
       -Drundeck.server.serverDir=$RDECK_INSTALL \
       -Drdeck.projects=$RDECK_PROJECTS \
       -Drdeck.runlogs=$RUNDECK_LOGDIR \
       -Drundeck.config.location=$RDECK_CONFIG/rundeck-config.properties \
       -Djava.io.tmpdir=$RUNDECK_TEMPDIR \
       -Drundeck.server.workDir=$RUNDECK_WORKDIR \
       -Dserver.http.port=$RDECK_HTTP_PORT \
       -Drundeck.jetty.connector.forwarded=true"
</code>```

Title: Rundeck behind and SSL Proxy

Body:
I am currently trying to set up an environment with Rundeck running behind and nginx reverse ssl proxy. I found different tutorials online for this scenario but none of those worked for me. I am working in an linux environment where both rundeck and nginx run on. My nginx configuration file for rundeck loooks like this:

server {
        access_log   /var/log/nginx/rundeck.access.log  main;

        listen 443;
        listen       [::]:443;
        ssl    on;
        ssl_certificate    /etc/nginx/conf.d/cert.crt;
        ssl_certificate_key    /etc/nginx/conf.d/key.rsa;

        location / {
          proxy_pass http://localhost:4440/;
          proxy_set_header        Host            $host;
          proxy_set_header        X-Real-IP       $remote_addr;
          proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
          proxy_set_header X-Ssl on;
}

        error_page 404 /404.html;
            location = /40x.html {
        }

        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }
    }

Furthermore I configured those parameters in rundeck:
framework.server.url = https://localhost:4440 and grails.serverURL=https://lde71d6p.de.top.com:443
I tried different combinations with https or only http, without port and with port. None of them works properly.

With the current configuration I get the following error situation.
If i try to call http://hostname.top.com -> Connection Error (seems fine because port 80 isn't handled by nginx)
https://hostname.top.com -> gets a 302 and is redirected to http://hostname.top.com/user/login;jsessionid=xxxxxxx and than gets an connection error.
https://hostname.top.com/user/login gets me straight to the login interface of rundeck. All fine.

Can anyone help me please to resolve the error situations I mentioned first?

Kind Regards,

Max

Body:
To run Rundeck behind SSL proxy, you need the following three setting:

https://github.com/rundeck/rundeck/wiki/FAQ#can-i-do-ssl-offloading

Set up RunDeck as http

in profile file, add option -Drundeck.jetty.connector.forwarded=true to RDECK_JVM

Set framework.rundeck.url and grails.serverURL to use https

In your case, profile setting does not seem to have been done yet.

The profile is in /etc/rundeck/profile. (it may depend on the distribution)

Add options -Drundeck.jetty.connector.forwarded=true to RDECK_JVM as follows:

RDECK_JVM="-Djava.security.auth.login.config=$JAAS_CONF \
       -Dloginmodule.name=$LOGIN_MODULE \
       -Drdeck.config=$RDECK_CONFIG \
       -Drundeck.server.configDir=$RDECK_SERVER_CONFIG \
       -Dserver.datastore.path=$RDECK_SERVER_DATA/rundeck \
       -Drundeck.server.serverDir=$RDECK_INSTALL \
       -Drdeck.projects=$RDECK_PROJECTS \
       -Drdeck.runlogs=$RUNDECK_LOGDIR \
       -Drundeck.config.location=$RDECK_CONFIG/rundeck-config.properties \
       -Djava.io.tmpdir=$RUNDECK_TEMPDIR \
       -Drundeck.server.workDir=$RUNDECK_WORKDIR \
       -Dserver.http.port=$RDECK_HTTP_PORT \
       -Drundeck.jetty.connector.forwarded=true"


问:
IF THEN loop not setting Value correctly
I have an If...Then loop nested inside of a For loop that is supposed to assign values from an SQL recordset to VBA values so they can be assigned to excel cells.  I have verified that the recordset has values, and that what I am trying to do can be done without the For and If..Then loops.  However, the values seem to be empty whenever the loop runs through.

Here is my block of code:

```<code>Dim counter as Integer
Dim fieldName1, fieldName2, etc. As String
Dim fieldName() As Variant

fieldName = Array("fieldName1", "fieldName2", "etc.")
counter = 0

For I = 0 To UBound(fieldName())
        If Not IsNull(recordSet.Fields(counter)) Then
            fieldName(I) = recordSet.Fields(counter).Value
            counter = counter + 1
        Else : fieldName(I) = ""
            counter = counter + 1
        End If
Next I
</code>```

After this executes, which it does successfully without any errors, and I try to assign a value to a cell, it is a blank string.

This will result in an empty string:

```<code>Range("C8").Select
    With Range("C8")
        Range("C8").Value = fieldName1
    End With
</code>```

Yet this will successfully enter a value into a cell:

```<code>Range("C8").Select
    With Range("C8")
        Range("C8").Value = recordSet.Fields(4).Value
    End With
</code>```

答:
From Siddharth:

I have declared fieldName1, fieldName2 etc. as String. The array is to iterate through those value names so each will get set to a value pulled from the recordset.

You cant declare variables in a loop :)

Body:
I have an If...Then loop nested inside of a For loop that is supposed to assign values from an SQL recordset to VBA values so they can be assigned to excel cells.  I have verified that the recordset has values, and that what I am trying to do can be done without the For and If..Then loops.  However, the values seem to be empty whenever the loop runs through.

Here is my block of code:

Dim counter as Integer
Dim fieldName1, fieldName2, etc. As String
Dim fieldName() As Variant

fieldName = Array("fieldName1", "fieldName2", "etc.")
counter = 0

For I = 0 To UBound(fieldName())
        If Not IsNull(recordSet.Fields(counter)) Then
            fieldName(I) = recordSet.Fields(counter).Value
            counter = counter + 1
        Else : fieldName(I) = ""
            counter = counter + 1
        End If
Next I

After this executes, which it does successfully without any errors, and I try to assign a value to a cell, it is a blank string.

This will result in an empty string:

Range("C8").Select
    With Range("C8")
        Range("C8").Value = fieldName1
    End With

Yet this will successfully enter a value into a cell:

Range("C8").Select
    With Range("C8")
        Range("C8").Value = recordSet.Fields(4).Value
    End With


问:
JSON Deserialize to generic type
I am writing tests for my controllers (ASP.NET Core), and am receiving back some JSON.  I would now like to deserialize it into the correct object so that I can do some assertions against the returned data.  There are no exceptions thrown during deserialization, but my Data variable is null.

Here is the code used for the deserialization:

```<code>var output = JsonConvert.DeserializeObject(responseString,
                typeof(CrudOperationResult<IEnumerable<ApiResource>>));
</code>```

This is the CrudOperationResult class:

```<code>public class CrudOperationResult<T>
{
    private CrudOperationResult()
    { }

    private CrudOperationResult(CrudResult result, string errorMessage, T data)
    {
        Result = result;
        ErrorMessage = errorMessage;
        Data = data;
    }

    [JsonIgnore]
    public CrudResult Result { get; private set; }

    public bool IsError
    {
        get
        {
            return Result == CrudResult.Error;
        }
    }

    public string ErrorMessage { get; private set; }

    public T Data { get; private set; }
}
</code>```

And here is the JSON data returned:

```<code>{
    "isError": false,
    "errorMessage": null,
    "data": [{
        "id": 1,
        "enabled": true,
        "name": "apiResource1",
        "displayName": "My API",
        "description": null,
        "secrets": null,
        "scopes": [{
            "id": 1,
            "name": "apiResource1",
            "displayName": "My API",
            "description": null,
            "required": false,
            "emphasize": false,
            "showInDiscoveryDocument": true,
            "userClaims": null
        }],
        "userClaims": [{
            "id": 1,
            "type": "role"
        },
        {
            "id": 2,
            "type": "user"
        }]
    }]
}
</code>```

答:
Issue 1: To deserialize JSON, you need a public constructor with no arguments.

Issue 2: You can't deserialize an interface type (IEnumerable).

Try:

```<code>var output = JsonConvert.DeserializeObject(responseString,
            typeof(CrudOperationResult<List<ApiResource>>));
</code>```

Title: JSON Deserialize to generic type

Body:
I am writing tests for my controllers (ASP.NET Core), and am receiving back some JSON.  I would now like to deserialize it into the correct object so that I can do some assertions against the returned data.  There are no exceptions thrown during deserialization, but my Data variable is null.

Here is the code used for the deserialization:

var output = JsonConvert.DeserializeObject(responseString,
                typeof(CrudOperationResult<IEnumerable<ApiResource>>));

This is the CrudOperationResult class:

public class CrudOperationResult<T>
{
    private CrudOperationResult()
    { }

    private CrudOperationResult(CrudResult result, string errorMessage, T data)
    {
        Result = result;
        ErrorMessage = errorMessage;
        Data = data;
    }

    [JsonIgnore]
    public CrudResult Result { get; private set; }

    public bool IsError
    {
        get
        {
            return Result == CrudResult.Error;
        }
    }

    public string ErrorMessage { get; private set; }

    public T Data { get; private set; }
}

And here is the JSON data returned:

{
    "isError": false,
    "errorMessage": null,
    "data": [{
        "id": 1,
        "enabled": true,
        "name": "apiResource1",
        "displayName": "My API",
        "description": null,
        "secrets": null,
        "scopes": [{
            "id": 1,
            "name": "apiResource1",
            "displayName": "My API",
            "description": null,
            "required": false,
            "emphasize": false,
            "showInDiscoveryDocument": true,
            "userClaims": null
        }],
        "userClaims": [{
            "id": 1,
            "type": "role"
        },
        {
            "id": 2,
            "type": "user"
        }]
    }]
}

Body:
Issue 1: To deserialize JSON, you need a public constructor with no arguments.

Issue 2: You can't deserialize an interface type (IEnumerable).

Try:

var output = JsonConvert.DeserializeObject(responseString,
            typeof(CrudOperationResult<List<ApiResource>>));


问:
Angular 2/4 problems to send a POST
I am using the Angular 2/4 framework and I'm trying to understand how to use this new framework, but when I try to send a new information with POST, PUT, etc I can't figure how to send, I tried many ways... ironically I can obtain the information with GET... but I'm still newbie with this framework, I want to understand how to send to my github with Github API, but I am very confused with the POST part, I am using the Github API to post an "issue" in my repository but I'm still stagnant do it ... so I would be very Grateful if anyone can clarify that point to send a "issue" to understand how it works in Angular 2/4 since I understand that it has to be sent in format "JSON" to work but I do not understand how or what is the way to do ...

I'm using the github github api: https://developer.github.com/v3/issues/#create-an-issue

My code:

git.service.ts

```<code>import { Injectable } from '@angular/core';
import {Http, Headers, Response} from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/Rx';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class GitService {

  private username: string;
  private reponame: string;
  private client_id = '+++++++++++++++++++++++';
  private client_secret = '++++++++++++++++++++++++++++';

  constructor(private http: Http) {
    console.log('Github Service Ready...');
    this.username = 'anubis';
  }

  getGithubUser() {
    return this.http.get('http://api.github.com/users/' + this.username
      + '?client_id=' + this.client_id
      + '&client_secret=' + this.client_secret )
      .map( res => res.json());
  }

  getGithubRepository() {
    return this.http.get('http://api.github.com/users/' + this.username
      + '/repos'
      + '?client_id=' + this.client_id
      + '&client_secret=' + this.client_secret )
      .map( res => res.json());
  }

  // to search another user and show his/her repositories
  SearchAgain(usernamenew: string) {
    this.username = usernamenew;
  }

  // I HAVE PROBLEMS IN THIS PART
  addIssue(forms) {
    this.reponame = 'AngularMontoyaTest';
    const headers = new Headers({'Content-Type': 'application/json'});

    return this.http.post('http://api.github.com/repos/ ' + this.username + ' / '
        + this.reponame + ' /issues?' + forms
      + '?client_id=' + this.client_id
      + '&client_secret=' + this.client_secret,
      {headers: headers}).map(res => res.json());
  }

}
</code>```

issuegithub.component.ts

```<code>import { Component, OnInit } from '@angular/core';
import { GitService } from '../../Services/git.service';
import { ActivatedRoute, Params, Router } from '@angular/router';

@Component({
  selector: 'app-issue',
  templateUrl: './issue.component.html'
})
export class IssueComponent implements OnInit {

  user: any;
  repo: any[];
  username: string;

  constructor(private service: GithubService,
              private route: ActivatedRoute,
              private router: Router) { }

  ngOnInit() {
    this.user = false;

    this.route.params
      .subscribe(
        (params: Params) => {
          // this.id = +params['id'];
          // this.editMode = params['id'] != null;
          // this.initForm();
        }
      );
  }

  OnSearchUser() {
    // get user information
    this.service.getGithubUser().subscribe(userGit => {
      console.log(userGit);
      this.user = userGit;
    });

    // get user repositories
    this.service.getGithubRepository().subscribe(userRepo => {
      console.log(userRepo);
      this.repo = userRepo;
    });

    this.service.SearchAgain(this.username);
  }

  addIssue( title: string,
            body: string,
            assignee: string,
            milestone: number,
            labels: string) {

    var newIssueAdd = {
      // title: title,
      // body: body,
      // assignee: assignee,
      // milestone: milestone,
      // labels: labels
      title: 'test1',
      body: 'ksjdlkafjslkdf',
      assignee: 'sdljflksjadflñdks',
      milestone: 1,
      labels: 'testlbl'
    };

    console.log(newIssueAdd);

    this.service.addIssue(newIssueAdd).subscribe(
        (response) => console.log(response),
        (error) => console.log(error)
      );
   }
}
</code>```

issue.component.html I'm only using a simple button to send the "issue" without any forms, I tried to make the post worked but I can't...

```<code><div class="row">
  <div class="col-md-12">
    <form class="well-lg">
      <div class="form-group">
        <input type="text" class="form-control" placeholder="Search Username..."
               [(ngModel)]="username" name="username" (keyup)="OnSearchUser()">
      </div>
    </form>
  </div>
</div>

<div *ngIf="user">
  <div class="panel panel-default">
    <div class="panel-heading">
      <h3 class="panel-title">{{user.name}}</h3>
    </div>
    <div class="panel-body">
      <div class="row">
        <div class="col-md-4">
          <img src="{{user.avatar_url}}" alt="" class="img-thumbnail">
          <a href="{{user.html_url}}" target="_blank" class="btn btn-default btn-block">View Profile</a>
        </div>
        <div class="col-md-8">
          <div class="stats">
            <span class="label label-default">{{user.public_repos}} Public Repositories</span>
            <span class="label label-primary">{{user.public_gists}} Public Github Gists</span>
            <span class="label label-success">{{user.followers}} Followers</span>
            <span class="label label-info">{{user.following}} Following</span>
          </div>
          <br>
          <ul class="list-group">
            <li class="list-group item"><strong>Username: </strong>{{user.login}}</li>
            <li class="list-group item"><strong>Location: </strong>{{user.location}}</li>
            <li class="list-group item"><strong>Email: </strong>{{user.email}}</li>
            <li class="list-group item"><strong>Blog: </strong>{{user.blog}}</li>
            <li class="list-group item"><strong>Member Since: </strong>{{user.created_at}}</li>
          </ul>
        </div>
      </div>
    </div>

    <div class="panel panel-default">
      <div class="panel-heading">
        <h3 class="panel-title">User Repositories</h3>
      </div>
      <div class="panel-body">
        <div *ngFor="let re of repo">
          <div class="row">
            <div class="col-md-9">
              <h4><a target="_blank" href="{{re.html_url}}">{{re.name}}</a></h4>
              <button class="btn btn-primary" (click)="addIssue()">Create Issue</button>
              <p>{{re.description}}</p>
            </div>
            <div class="col-md-3">
              <span class="label label-default">{{re.watchers}} Watchers</span>
              <span class="label label-default">{{re.forks}} Forks</span>
            </div>
          </div>
          <hr>
        </div>
      </div>
    </div>
  </div>
</div>
</code>```

答:
It looks like you have two question marks in your post command. I am not sure, but I believe that is invalid for a query string... Should it either be a slash or else an ampersand?

(slash)

```<code>return this.http.post('http://api.github.com/repos/ ' + this.username + ' / '
    + this.reponame + ' /issues/' + forms
  + '?client_id=' + this.client_id
  + '&client_secret=' + this.client_secret,
  {headers: headers}).map(res => res.json());
</code>```

Title: Angular 2/4 problems to send a POST

Body:
I am using the Angular 2/4 framework and I'm trying to understand how to use this new framework, but when I try to send a new information with POST, PUT, etc I can't figure how to send, I tried many ways... ironically I can obtain the information with GET... but I'm still newbie with this framework, I want to understand how to send to my github with Github API, but I am very confused with the POST part, I am using the Github API to post an "issue" in my repository but I'm still stagnant do it ... so I would be very Grateful if anyone can clarify that point to send a "issue" to understand how it works in Angular 2/4 since I understand that it has to be sent in format "JSON" to work but I do not understand how or what is the way to do ...

I'm using the github github api: https://developer.github.com/v3/issues/#create-an-issue

My code:

git.service.ts

import { Injectable } from '@angular/core';
import {Http, Headers, Response} from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/Rx';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class GitService {

  private username: string;
  private reponame: string;
  private client_id = '+++++++++++++++++++++++';
  private client_secret = '++++++++++++++++++++++++++++';

  constructor(private http: Http) {
    console.log('Github Service Ready...');
    this.username = 'anubis';
  }

  getGithubUser() {
    return this.http.get('http://api.github.com/users/' + this.username
      + '?client_id=' + this.client_id
      + '&client_secret=' + this.client_secret )
      .map( res => res.json());
  }

  getGithubRepository() {
    return this.http.get('http://api.github.com/users/' + this.username
      + '/repos'
      + '?client_id=' + this.client_id
      + '&client_secret=' + this.client_secret )
      .map( res => res.json());
  }

  // to search another user and show his/her repositories
  SearchAgain(usernamenew: string) {
    this.username = usernamenew;
  }

  // I HAVE PROBLEMS IN THIS PART
  addIssue(forms) {
    this.reponame = 'AngularMontoyaTest';
    const headers = new Headers({'Content-Type': 'application/json'});

    return this.http.post('http://api.github.com/repos/ ' + this.username + ' / '
        + this.reponame + ' /issues?' + forms
      + '?client_id=' + this.client_id
      + '&client_secret=' + this.client_secret,
      {headers: headers}).map(res => res.json());
  }

}

issuegithub.component.ts

import { Component, OnInit } from '@angular/core';
import { GitService } from '../../Services/git.service';
import { ActivatedRoute, Params, Router } from '@angular/router';

@Component({
  selector: 'app-issue',
  templateUrl: './issue.component.html'
})
export class IssueComponent implements OnInit {

  user: any;
  repo: any[];
  username: string;

  constructor(private service: GithubService,
              private route: ActivatedRoute,
              private router: Router) { }

  ngOnInit() {
    this.user = false;

    this.route.params
      .subscribe(
        (params: Params) => {
          // this.id = +params['id'];
          // this.editMode = params['id'] != null;
          // this.initForm();
        }
      );
  }

  OnSearchUser() {
    // get user information
    this.service.getGithubUser().subscribe(userGit => {
      console.log(userGit);
      this.user = userGit;
    });

    // get user repositories
    this.service.getGithubRepository().subscribe(userRepo => {
      console.log(userRepo);
      this.repo = userRepo;
    });

    this.service.SearchAgain(this.username);
  }

  addIssue( title: string,
            body: string,
            assignee: string,
            milestone: number,
            labels: string) {

    var newIssueAdd = {
      // title: title,
      // body: body,
      // assignee: assignee,
      // milestone: milestone,
      // labels: labels
      title: 'test1',
      body: 'ksjdlkafjslkdf',
      assignee: 'sdljflksjadflñdks',
      milestone: 1,
      labels: 'testlbl'
    };

    console.log(newIssueAdd);

    this.service.addIssue(newIssueAdd).subscribe(
        (response) => console.log(response),
        (error) => console.log(error)
      );
   }
}

issue.component.html I'm only using a simple button to send the "issue" without any forms, I tried to make the post worked but I can't...

    <form class="well-lg">

        <input type="text" class="form-control" placeholder="Search Username..."
               [(ngModel)]="username" name="username" (keyup)="OnSearchUser()">

    </form>

{{user.name}}

          View Profile

            {{user.public_repos}} Public Repositories
            {{user.public_gists}} Public Github Gists
            {{user.followers}} Followers
            {{user.following}} Following

Username: {{user.login}}

Location: {{user.location}}

Email: {{user.email}}

Blog: {{user.blog}}

Member Since: {{user.created_at}}

User Repositories

{{re.name}}

              <button class="btn btn-primary" (click)="addIssue()">Create Issue</button>

{{re.description}}

              {{re.watchers}} Watchers
              {{re.forks}} Forks

Body:
It looks like you have two question marks in your post command. I am not sure, but I believe that is invalid for a query string... Should it either be a slash or else an ampersand?

(slash)

return this.http.post('http://api.github.com/repos/ ' + this.username + ' / '
    + this.reponame + ' /issues/' + forms
  + '?client_id=' + this.client_id
  + '&client_secret=' + this.client_secret,
  {headers: headers}).map(res => res.json());


问:
ImportError: No module named diversely.settings.dev
I've just completed a django tutorial, and after creating a settings folder and reconfiguring my database in my base.py, my website isn't loading, and I'm getting an ImportError. Any thoughts?

Here's the traceback:

```<code>Traceback (most recent call last):
  File "/Users/m.zayas/Desktop/env1/bin/django-admin", line 11, in <module>
    sys.exit(execute_from_command_line())
  File "/Users/m.zayas/Desktop/env1/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line
    utility.execute()
  File "/Users/m.zayas/Desktop/env1/lib/python2.7/site-packages/django/core/management/__init__.py", line 316, in execute
    settings.INSTALLED_APPS
  File "/Users/m.zayas/Desktop/env1/lib/python2.7/site-packages/django/conf/__init__.py", line 53, in __getattr__
    self._setup(name)
  File "/Users/m.zayas/Desktop/env1/lib/python2.7/site-packages/django/conf/__init__.py", line 41, in _setup
    self._wrapped = Settings(settings_module)
  File "/Users/m.zayas/Desktop/env1/lib/python2.7/site-packages/django/conf/__init__.py", line 97, in __init__
    mod = importlib.import_module(self.SETTINGS_MODULE)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
ImportError: No module named diversely.settings.dev
</code>```

Here is my base.py:

```<code>import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '_h0tyj2^#5x2jh$9!&p0589-zop-0aiwok)x(sf+u-jjhw9l*o'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'accounts',
    'home',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'diversely.middleware.LoginRequiredMiddleware'
]

ROOT_URLCONF = 'diversely.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'accounts/templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'diversely.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Password validation
# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/1.10/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/

STATIC_URL = '/static/'

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'diversely/media')

LOGIN_REDIRECT_URL = '/home/'

LOGIN_URL = '/account/login'

LOGIN_EXEMPT_URLS = (
    r'^account/logout/$',
    r'^account/register/$',
    r'^account/reset-password/$',
    r'^account/reset-password/done/$',
    r'^account/reset-password/$',
    r'^account/reset-password/confirm/(?P<uidb64>[0-9A-Za-z]+)-(?P<token>.+)/$',
    r'^account/reset-password/complete/$',

)

EMAIL_HOST = 'localhost'
EMAIL_PORT = 1025
</code>```

my wsgi:

```<code>"""
WSGI config for diversely project.

It exposes the WSGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "diversely.settings.prod")

application = get_wsgi_application()
</code>```

dev.py:

```<code>from diversely.settings.base import *

# Override base.py settings here

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

try:
    from diversely.settings.local import *
except:
    pass
</code>```

prod.py:

```<code>from diversely.settings.base import *

# Override base.py settings here
DEBUG = False
ALLOWED_HOSTS = ['*']
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

try:
    from diversely.settings.local import *
except:
    pass
</code>```

folder structure:
here's my folder structure:

```<code>diversely
  Ldiversely
    L settings.py
      L __init__.py
      L base.py
      L dev.py
      L local.py
      L production.py
</code>```

答:
Your folder structure should be like this,

```<code>- diversely
  --- __init__.py
  --- settings
      ---- __init__.py
      ---- base.py
      ---- dev.py
      ---- production.py
      ---- local.py
</code>```

Each directory must contain an __init__.py file. If not Django raises "No module found" error.

Note: If your folder's name is "settings.py", then change it to "settings".

Body:
I've just completed a django tutorial, and after creating a settings folder and reconfiguring my database in my base.py, my website isn't loading, and I'm getting an ImportError. Any thoughts?

Here's the traceback:

Traceback (most recent call last):
  File "/Users/m.zayas/Desktop/env1/bin/django-admin", line 11, in <module>
    sys.exit(execute_from_command_line())
  File "/Users/m.zayas/Desktop/env1/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line
    utility.execute()
  File "/Users/m.zayas/Desktop/env1/lib/python2.7/site-packages/django/core/management/__init__.py", line 316, in execute
    settings.INSTALLED_APPS
  File "/Users/m.zayas/Desktop/env1/lib/python2.7/site-packages/django/conf/__init__.py", line 53, in __getattr__
    self._setup(name)
  File "/Users/m.zayas/Desktop/env1/lib/python2.7/site-packages/django/conf/__init__.py", line 41, in _setup
    self._wrapped = Settings(settings_module)
  File "/Users/m.zayas/Desktop/env1/lib/python2.7/site-packages/django/conf/__init__.py", line 97, in __init__
    mod = importlib.import_module(self.SETTINGS_MODULE)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
ImportError: No module named diversely.settings.dev

Here is my base.py:

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '_h0tyj2^#5x2jh$9!&p0589-zop-0aiwok)x(sf+u-jjhw9l*o'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'accounts',
    'home',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'diversely.middleware.LoginRequiredMiddleware'
]

ROOT_URLCONF = 'diversely.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'accounts/templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'diversely.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Password validation
# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/1.10/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/

STATIC_URL = '/static/'

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'diversely/media')

LOGIN_REDIRECT_URL = '/home/'

LOGIN_URL = '/account/login'

LOGIN_EXEMPT_URLS = (
    r'^account/logout/$',
    r'^account/register/$',
    r'^account/reset-password/$',
    r'^account/reset-password/done/$',
    r'^account/reset-password/$',
    r'^account/reset-password/confirm/(?P<uidb64>[0-9A-Za-z]+)-(?P<token>.+)/$',
    r'^account/reset-password/complete/$',

)

EMAIL_HOST = 'localhost'
EMAIL_PORT = 1025

my wsgi:

"""
WSGI config for diversely project.

It exposes the WSGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "diversely.settings.prod")

application = get_wsgi_application()

dev.py:

from diversely.settings.base import *

# Override base.py settings here

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

try:
    from diversely.settings.local import *
except:
    pass

prod.py:

from diversely.settings.base import *

# Override base.py settings here
DEBUG = False
ALLOWED_HOSTS = ['*']
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

try:
    from diversely.settings.local import *
except:
    pass

folder structure:
here's my folder structure:

diversely
  Ldiversely
    L settings.py
      L __init__.py
      L base.py
      L dev.py
      L local.py
      L production.py

Body:
Your folder structure should be like this,

- diversely
  --- __init__.py
  --- settings
      ---- __init__.py
      ---- base.py
      ---- dev.py
      ---- production.py
      ---- local.py

Each directory must contain an __init__.py file. If not Django raises "No module found" error.

Note: If your folder's name is "settings.py", then change it to "settings".


问:
How to use scipy.optimize minimize_scalar when objective function has multiple arguments?
I have a function of multiple arguments. I want to optimize it with respect to a single variable while holding others constant. For that I want to use minimize_scalar from spicy.optimize. I read the documentation, but I am still confused how to tell minimize_scalar that I want to minimize with respect to variable:w1. Below is a minimal working code.</p>

```<code>import numpy as np
from scipy.optimize import minimize_scalar

def error(w0,w1,x,y_actual):
    y_pred = w0+w1*x
    mse = ((y_actual-y_pred)**2).mean()
    return mse

w0=50
x = np.array([1,2,3])
y = np.array([52,54,56])
minimize_scalar(error,args=(w0,x,y),bounds=(-5,5))
</code>```

答:
You can also use a partial function.

```<code>from functools import partial
error_partial = partial(error, w0=w0, x=x, y_actual=y)
minimize_scalar(error_partial, bounds=(-5, 5))
</code>```

In case you are wondering about the performance ... it is the same as with lambdas.

```<code>import time
from functools import partial
import numpy as np
from scipy.optimize import minimize_scalar

def error(w1, w0, x, y_actual):
    y_pred = w0 + w1 * x
    mse = ((y_actual - y_pred) ** 2).mean()
    return mse

w0 = 50
x = np.arange(int(1e5))
y = np.arange(int(1e5)) + 52

error_partial = partial(error, w0=w0, x=x, y_actual=y)

p_time = []
for _ in range(100):
    p_time_ = time.time()
    p = minimize_scalar(error_partial, bounds=(-5, 5))
    p_time_ = time.time() - p_time_
    p_time.append(p_time_  / p.nfev)

l_time = []
for _ in range(100):
    l_time_ = time.time()
    l = minimize_scalar(lambda w1: error(w1, w0, x, y), bounds=(-5, 5))
    l_time_ = time.time() - l_time_
    l_time.append(l_time_ / l.nfev)

print(f'Same performance? {np.median(p_time) == np.median(l_time)}')
# Same performance? True
</code>```

Body:
I have a function of multiple arguments. I want to optimize it with respect to a single variable while holding others constant. For that I want to use minimize_scalar from spicy.optimize. I read the documentation, but I am still confused how to tell minimize_scalar that I want to minimize with respect to variable:w1. Below is a minimal working code.

import numpy as np
from scipy.optimize import minimize_scalar

def error(w0,w1,x,y_actual):
    y_pred = w0+w1*x
    mse = ((y_actual-y_pred)**2).mean()
    return mse

w0=50
x = np.array([1,2,3])
y = np.array([52,54,56])
minimize_scalar(error,args=(w0,x,y),bounds=(-5,5))

Body:
You can also use a partial function.

from functools import partial
error_partial = partial(error, w0=w0, x=x, y_actual=y)
minimize_scalar(error_partial, bounds=(-5, 5))

In case you are wondering about the performance ... it is the same as with lambdas.

import time
from functools import partial
import numpy as np
from scipy.optimize import minimize_scalar

def error(w1, w0, x, y_actual):
    y_pred = w0 + w1 * x
    mse = ((y_actual - y_pred) ** 2).mean()
    return mse

w0 = 50
x = np.arange(int(1e5))
y = np.arange(int(1e5)) + 52

error_partial = partial(error, w0=w0, x=x, y_actual=y)

p_time = []
for _ in range(100):
    p_time_ = time.time()
    p = minimize_scalar(error_partial, bounds=(-5, 5))
    p_time_ = time.time() - p_time_
    p_time.append(p_time_  / p.nfev)

l_time = []
for _ in range(100):
    l_time_ = time.time()
    l = minimize_scalar(lambda w1: error(w1, w0, x, y), bounds=(-5, 5))
    l_time_ = time.time() - l_time_
    l_time.append(l_time_ / l.nfev)

print(f'Same performance? {np.median(p_time) == np.median(l_time)}')
# Same performance? True


问:
Error when running maildev - logger.info(`Recieved shutdown signal, shutting down now...`)
I get the above error when trying to run the maildev command in the terminal. I had it working before but it won't start since I needed to reboot my machine. I uninstalled and reinstalled but still no luck.

Here is the full error. Thanks in advance for any assistance.

```<code>$ maildev
/usr/local/lib/node_modules/maildev/index.js:92
    logger.info(`Recieved shutdown signal, shutting down now...`)
                ^
SyntaxError: Unexpected token ILLEGAL
    at exports.runInThisContext (vm.js:73:16)
    at Module._compile (module.js:443:25)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at Object.<anonymous> (/usr/local/lib/node_modules/maildev/bin/maildev:7:17)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)
</code>```

答:
The error you're getting is a syntax error, not a shutdown signal. You're running an older version of Node that doesn't support template literals which maildev is using in that logger message. So when it tries to log that line, Node crashes.

Template literals are an ES6 language feature that only newer versions of Node support. They act like strings that use backtick quotes, as opposed to single or double quotes. They allow you to evaluate expressions and variables directly inside the string.

```<code>console.log(`Hello ${name}, the ${job}!`)
</code>```

The solution is to upgrade your version of Node to at least 4.0.0 or greater. If you can't upgrade Node then consider using an older version of maildev that doesn't use ES6 syntax like version 0.11.

Body:
I get the above error when trying to run the maildev command in the terminal. I had it working before but it won't start since I needed to reboot my machine. I uninstalled and reinstalled but still no luck.

Here is the full error. Thanks in advance for any assistance.

$ maildev
/usr/local/lib/node_modules/maildev/index.js:92
    logger.info(`Recieved shutdown signal, shutting down now...`)
                ^
SyntaxError: Unexpected token ILLEGAL
    at exports.runInThisContext (vm.js:73:16)
    at Module._compile (module.js:443:25)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at Object.<anonymous> (/usr/local/lib/node_modules/maildev/bin/maildev:7:17)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)

Body:
The error you're getting is a syntax error, not a shutdown signal. You're running an older version of Node that doesn't support template literals which maildev is using in that logger message. So when it tries to log that line, Node crashes.

Template literals are an ES6 language feature that only newer versions of Node support. They act like strings that use backtick quotes, as opposed to single or double quotes. They allow you to evaluate expressions and variables directly inside the string.

console.log(`Hello ${name}, the ${job}!`)

The solution is to upgrade your version of Node to at least 4.0.0 or greater. If you can't upgrade Node then consider using an older version of maildev that doesn't use ES6 syntax like version 0.11.


问:
asp.net mvc dynamic regular expression variable
i am dynamically validating regular expression in which the regular expression are from database

ok so the thing is happening that \ is replaced by \\ which is not validating the email

i have  Regex RegExp = new Regex("@" + IsMandatoryTextTextAreaFiles.vcr_RegularExpression, RegexOptions.Compiled);

in which  IsMandatoryTextTextAreaFiles.vcr_RegularExpression=\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)* .

So what to do now?

答:
No, the \ are not replaced by \\, my guess is that you are looking at the value in the debugger, where the string is displayed as it would be written as a string literal in the code.

Concatenating the string "@" and some other string doesn't make it a literal string, i.e. "@" + "asdf" is not the same as @"asdf", it's just "@asdf". That means that the @ becomes part of the pattern. Just use the string as it is:

```<code>Regex RegExp = new Regex(IsMandatoryTextTextAreaFiles.vcr_RegularExpression, RegexOptions.Compiled);
</code>```

Note that the regular expression is only verifying that a string contains a valid email, not that it is only a valid email. So for example the string "Here: asdf@asdf.com dear sir" would pass the test.

You can use ^ and $ to specify the beginning and end of the string in the regular expression:

```<code>^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$
</code>```

Body:
No, the \ are not replaced by \\, my guess is that you are looking at the value in the debugger, where the string is displayed as it would be written as a string literal in the code.

Concatenating the string "@" and some other string doesn't make it a literal string, i.e. "@" + "asdf" is not the same as @"asdf", it's just "@asdf". That means that the @ becomes part of the pattern. Just use the string as it is:

Regex RegExp = new Regex(IsMandatoryTextTextAreaFiles.vcr_RegularExpression, RegexOptions.Compiled);

Note that the regular expression is only verifying that a string contains a valid email, not that it is only a valid email. So for example the string "Here: asdf@asdf.com dear sir" would pass the test.

You can use ^ and $ to specify the beginning and end of the string in the regular expression:

^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$


问:
How to change image color in openlayers3?
I am new to openlayers3. I am showing point as a image but I want to change color of image dynamically.Is it possible in openlayers3 or have any other facility like canvas in openlayers3?</p>

```<code>var iconStyle = new ol.style.Style({
    image: new ol.style.Icon(/** @type {olx.style.IconOptions} */ ({
         anchor: [0.5, 46],
         anchorXUnits: 'fraction',
         anchorYUnits: 'pixels',
         src: 'data/icon.png'
    }))
});
</code>```

答:
Taking Icon Colors as starting point where they use a transparent PNG with ol.Color option to have multiple color dots I've tried to change the colors like this without success...

var london = new ol.Feature({
  geometry: new ol.geom.Point(ol.proj.fromLonLat([-0.12755, 51.507222]))
});

london.setStyle(new ol.style.Style({
  image: new ol.style.Icon(/** @type {olx.style.IconOptions} */ ({
    color: '#ff0000',
    crossOrigin: 'anonymous',
    src: 'https://openlayers.org/en/v4.1.1/examples/data/dot.png'
  }))
}));

var vectorSource = new ol.source.Vector({
  features: [london]
});

var vectorLayer = new ol.layer.Vector({
  source: vectorSource
});

var rasterLayer = new ol.layer.Tile({
  source: new ol.source.TileJSON({
    url: 'https://api.tiles.mapbox.com/v3/mapbox.geography-class.json?secure',
    crossOrigin: ''
  })
});

var map = new ol.Map({
  layers: [rasterLayer, vectorLayer],
  target: document.getElementById('map'),
  view: new ol.View({
    center: ol.proj.fromLonLat([2.896372, 44.60240]),
    zoom: 3
  })
});

map.on('singleclick', function (event) { // Use 'pointermove' to capture mouse movement over the feature
  map.forEachFeatureAtPixel(event.pixel, function (feature, layer) {
    /* Get the current image instance and its color */
    var image = feature.getStyle().getImage();
    console.log(image.getColor());

    /* Color gets stored in image.i, but there's no setter */
    console.log(image.i);

    /* Trying to force the color change: */
    image.i = [0, 255, 0, 1];

    /* Dispatch the changed() event on layer, to force styles reload */
    layer.changed();

    console.log(image.getColor()); // Logs new color, but it doesn't work...

  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL"></script>
<script src="https://openlayers.org/en/v4.1.1/build/ol.js"></script>
<div id="map" class="map"></div></code>```

See how you can retrieve an icon's color like this:

```<code>var image = feature.getStyle().getImage(),
    color = image.getColor(); // returns [R, G, B, alpha]
</code>```

but there's no setColor() method, so there's no way to change the color in runtime...

EDIT: Reviewing again your question and your code, I've noticed you never set a color for your icon, so maybe you don't really want to actually change the color in response to an event but just set a color. If that's what you want, then it's easy:

```<code>var iconStyle = new ol.style.Style({
     image: new ol.style.Icon(/** @type {olx.style.IconOptions} */ ({
         anchor: [0.5, 46],
         anchorXUnits: 'fraction',
         anchorYUnits: 'pixels',
         src: 'data/icon.png',
         color: '#ff0000' // allows HEX as String or RGB(a) as Array
     }))
});
</code>```

See: http://openlayers.org/en/latest/apidoc/ol.style.Icon.html

Body:
I am new to openlayers3. I am showing point as a image but I want to change color of image dynamically.Is it possible in openlayers3 or have any other facility like canvas in openlayers3?

var iconStyle = new ol.style.Style({
    image: new ol.style.Icon(/** @type {olx.style.IconOptions} */ ({
         anchor: [0.5, 46],
         anchorXUnits: 'fraction',
         anchorYUnits: 'pixels',
         src: 'data/icon.png'
    }))
});

Body:
Taking Icon Colors as starting point where they use a transparent PNG with ol.Color option to have multiple color dots I've tried to change the colors like this without success...

var london = new ol.Feature({
  geometry: new ol.geom.Point(ol.proj.fromLonLat([-0.12755, 51.507222]))
});

london.setStyle(new ol.style.Style({
  image: new ol.style.Icon(/** @type {olx.style.IconOptions} */ ({
    color: '#ff0000',
    crossOrigin: 'anonymous',
    src: 'https://openlayers.org/en/v4.1.1/examples/data/dot.png'
  }))
}));

var vectorSource = new ol.source.Vector({
  features: [london]
});

var vectorLayer = new ol.layer.Vector({
  source: vectorSource
});

var rasterLayer = new ol.layer.Tile({
  source: new ol.source.TileJSON({
    url: 'https://api.tiles.mapbox.com/v3/mapbox.geography-class.json?secure',
    crossOrigin: ''
  })
});

var map = new ol.Map({
  layers: [rasterLayer, vectorLayer],
  target: document.getElementById('map'),
  view: new ol.View({
    center: ol.proj.fromLonLat([2.896372, 44.60240]),
    zoom: 3
  })
});

map.on('singleclick', function (event) { // Use 'pointermove' to capture mouse movement over the feature
  map.forEachFeatureAtPixel(event.pixel, function (feature, layer) {
    /* Get the current image instance and its color */
    var image = feature.getStyle().getImage();
    console.log(image.getColor());

    /* Color gets stored in image.i, but there's no setter */
    console.log(image.i);

    /* Trying to force the color change: */
    image.i = [0, 255, 0, 1];

    /* Dispatch the changed() event on layer, to force styles reload */
    layer.changed();

    console.log(image.getColor()); // Logs new color, but it doesn't work...

  });
});

<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL"></script>
<script src="https://openlayers.org/en/v4.1.1/build/ol.js"></script>
<div id="map" class="map"></div>

See how you can retrieve an icon's color like this:

var image = feature.getStyle().getImage(),
    color = image.getColor(); // returns [R, G, B, alpha]

but there's no setColor() method, so there's no way to change the color in runtime...

EDIT: Reviewing again your question and your code, I've noticed you never set a color for your icon, so maybe you don't really want to actually change the color in response to an event but just set a color. If that's what you want, then it's easy:

var iconStyle = new ol.style.Style({
     image: new ol.style.Icon(/** @type {olx.style.IconOptions} */ ({
         anchor: [0.5, 46],
         anchorXUnits: 'fraction',
         anchorYUnits: 'pixels',
         src: 'data/icon.png',
         color: '#ff0000' // allows HEX as String or RGB(a) as Array
     }))
});

See: http://openlayers.org/en/latest/apidoc/ol.style.Icon.html


问:
TypeConverter not working with ExpandoObject and DataGrid
I have a Poco class where one Property is an enumeration type.

In order to make the enumeration property localizable on the UI layer (WPF) I have created a TypeConverter for the enumeration type which looks up the localized enumeration value.
A list of instances of this POCO class is bound to a WPF DataGrid:

```<code>// in the ViewModel:
public Pocos = CollectionViewSource.GetDefaultView( DataLayer.GetPocos() );
</code>```

That worked perfectly well.

Later I refactored the code so that the data layer no longer returns List<Poco> but List<ExpandoObject>:

```<code>public Pocos = CollectionViewSource.GetDefaultView( DataLayer.GetExpandos() );
</code>```

These ExpandoObjects are the result of database query and contain only a subset of the original Poco's properties, depending on the select statement.

Everything works fine, with the exception of the TypeConverter for the enumeration property which is no longer invoked.

The TypeConverter is still exposed, so this works:

```<code>dynamic eo = new ExpandoObject();
eo.EnumProperty = MyEnum.SomeValue;
var converter = TypeConverter.GetConverter( (eo.EnumProperty).GetType() );
var result = converter.ConvertTo( eo.EnumProperty, typeof( string ) );
</code>```

I do not know what is going on inside WPF's DataGrid. I am under the impression that it, for whatever reason, simply invokes ToString() on the enumeration type property instead of invoking the TypeConverter.

Any way to get this working?

Implementation Details:

XAML:

```<code><DataGrid x:Name="PocoGrid" x:FieldModifier="public"
  Grid.Column="0" Grid.Row="0" Grid.ColumnSpan="2"
  ItemsSource="{Binding Pocos}"
  SelectedItem="{Binding SelectedPoco}"
  bh:DataGridColumnsBehavior.BindableColumns="{Binding PocoColumns}"
  IsSynchronizedWithCurrentItem="True" IsReadOnly="True" AutoGenerateColumns="False">
  <DataGrid.InputBindings>
    <MouseBinding MouseAction="LeftDoubleClick" Command="{Binding PocoDoubleClick}" CommandParameter="{Binding Pocos/}"/>
  </DataGrid.InputBindings>
</DataGrid>
</code>```

TYPE CONVERTER:

```<code>public abstract class EnumTypeConverterBase : TypeConverter
{
   public static ILocalizedResourceProvider ResourceProvider { get; set; } = null;
}

public class EnumTypeConverter<T> : EnumTypeConverterBase where T : struct, IConvertible, IComparable
{
   private static string typeParameterName = typeof(T).Name;

   public override bool CanConvertFrom( ITypeDescriptorContext context, Type sourceType )
   {
      if( sourceType == typeof( string ) )
         return true;
      return base.CanConvertFrom( context, sourceType );
   }

   public override object ConvertFrom( ITypeDescriptorContext context, CultureInfo culture, object value )
   {
      throw new NotImplementedException();
   }

   public override object ConvertTo( ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType )
   {
      string val = value.ToString();

      if( ResourceProvider == null )
         return val;
      else
         return ResourceProvider.GetEnum( typeParameterName, val );
   }
}
</code>```

ENUMERATION DEFINITION:

```<code>[TypeConverter( typeof( EnumTypeConverter<MyEnum> ) )]
public enum MyEnum
{
   Unknown = 0,
   SomeValue = 1,
   SomeOtherValue = 2
}
</code>```

答:
Use a value converter. That's a more conventional way to do this anyhow, and it doesn't depend on reflection to get invoked at runtime.

```<code>public class MyEnumLocalizationConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var e = (MyEnum)value;

        var converted = "";

        //  Do whatever the type converter now does

        return converted;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
</code>```

XAML:

```<code><Window.Resources>
    <!-- ... -->

    <local:MyEnumLocalizationConverter x:Key="MyEnumLocalizer" />

    <!-- ... -->
</Window.Resources>

<!-- ... -->

    <DataGridTextColumn
        Binding="{Binding EnumProperty, Converter={StaticResource MyEnumLocalizer}}"
        />
</code>```

If you share some XAML I can show you

Body:
I have a Poco class where one Property is an enumeration type.

In order to make the enumeration property localizable on the UI layer (WPF) I have created a TypeConverter for the enumeration type which looks up the localized enumeration value.
A list of instances of this POCO class is bound to a WPF DataGrid:

// in the ViewModel:
public Pocos = CollectionViewSource.GetDefaultView( DataLayer.GetPocos() );

That worked perfectly well.

Later I refactored the code so that the data layer no longer returns List<Poco> but List<ExpandoObject>:

public Pocos = CollectionViewSource.GetDefaultView( DataLayer.GetExpandos() );

These ExpandoObjects are the result of database query and contain only a subset of the original Poco's properties, depending on the select statement.

Everything works fine, with the exception of the TypeConverter for the enumeration property which is no longer invoked.

The TypeConverter is still exposed, so this works:

dynamic eo = new ExpandoObject();
eo.EnumProperty = MyEnum.SomeValue;
var converter = TypeConverter.GetConverter( (eo.EnumProperty).GetType() );
var result = converter.ConvertTo( eo.EnumProperty, typeof( string ) );

I do not know what is going on inside WPF's DataGrid. I am under the impression that it, for whatever reason, simply invokes ToString() on the enumeration type property instead of invoking the TypeConverter.

Any way to get this working?

Implementation Details:

XAML:

<DataGrid x:Name="PocoGrid" x:FieldModifier="public"
  Grid.Column="0" Grid.Row="0" Grid.ColumnSpan="2"
  ItemsSource="{Binding Pocos}"
  SelectedItem="{Binding SelectedPoco}"
  bh:DataGridColumnsBehavior.BindableColumns="{Binding PocoColumns}"
  IsSynchronizedWithCurrentItem="True" IsReadOnly="True" AutoGenerateColumns="False">
  <DataGrid.InputBindings>
    <MouseBinding MouseAction="LeftDoubleClick" Command="{Binding PocoDoubleClick}" CommandParameter="{Binding Pocos/}"/>
  </DataGrid.InputBindings>
</DataGrid>

TYPE CONVERTER:

public abstract class EnumTypeConverterBase : TypeConverter
{
   public static ILocalizedResourceProvider ResourceProvider { get; set; } = null;
}

public class EnumTypeConverter<T> : EnumTypeConverterBase where T : struct, IConvertible, IComparable
{
   private static string typeParameterName = typeof(T).Name;

   public override bool CanConvertFrom( ITypeDescriptorContext context, Type sourceType )
   {
      if( sourceType == typeof( string ) )
         return true;
      return base.CanConvertFrom( context, sourceType );
   }

   public override object ConvertFrom( ITypeDescriptorContext context, CultureInfo culture, object value )
   {
      throw new NotImplementedException();
   }

   public override object ConvertTo( ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType )
   {
      string val = value.ToString();

      if( ResourceProvider == null )
         return val;
      else
         return ResourceProvider.GetEnum( typeParameterName, val );
   }
}

ENUMERATION DEFINITION:

[TypeConverter( typeof( EnumTypeConverter<MyEnum> ) )]
public enum MyEnum
{
   Unknown = 0,
   SomeValue = 1,
   SomeOtherValue = 2
}

Body:
Use a value converter. That's a more conventional way to do this anyhow, and it doesn't depend on reflection to get invoked at runtime.

public class MyEnumLocalizationConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var e = (MyEnum)value;

        var converted = "";

        //  Do whatever the type converter now does

        return converted;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

XAML:

<Window.Resources>
    <!-- ... -->

    <local:MyEnumLocalizationConverter x:Key="MyEnumLocalizer" />

    <!-- ... -->
</Window.Resources>

<!-- ... -->

    <DataGridTextColumn
        Binding="{Binding EnumProperty, Converter={StaticResource MyEnumLocalizer}}"
        />

If you share some XAML I can show you


问:
ImportError: libcudnn when running a TensorFlow program
I encountered the following error when trying to run a TensorFlow program:</p>

```
ImportError: libcudnn.<i>Version</i>: cannot open shared object file: No such file or director
```

答: I was able to solve problem by changing my cudNN installation from cudNN 6.0 to cudNN 5.1. cudNN 6.0 has the file libcudnn.so.6 while cudNN 5.1 has the file libcudnn.so.5.</p>

Body:
I encountered the following error when trying to run a TensorFlow program:

ImportError: libcudnn.Version: cannot open shared object file: No such file or director


问:
How to place an UIImage at the top centre using storyboard and auotlayout?
What are the constraints need to place an UIImageView at the top centre of the storyboard using auto-layout?
1.Currently i am setting Leading Space
2.Trailing Space
3.Width and height constraints
But the image displaces while coming in the 5s phone. Please help.

答:
You are mostly there. The leading and trailing constraints are the ones causing the issue. Remove both of those and then add the 'Center Horizontally in Container' constraint to UIImageView.

Hopefully that achieves what you are after.


问:
Opencellid request location
I have an csv that contain the information of cell towers. MMC, MNC, LAC, ID.
The python script I wrote read from the csv file
Iterate through rows and extract the information of the cell in a dictionary:

```<code>Cell={"MMC":6050, "MNC":01, "LAN":213, "ID":3657, "TX":230, "RX":960, "LONG":None, "LAT":None}
</code>```

Now, I want to connect to opencellid  to get the location of the cell.
It maybe something like this:

```<code>data={"MMC":6050, "MNC":01, "LAN":213, "ID":3657}
res=requests.post("https://www.opencellid.com/location/search.php", data)
res.json()
</code>```

I don't have a clear idea about this. And I don't know how to deal with the Opencellid API.
I really need help?

答:
Read this: https://unwiredlabs.com/docs/?python#geocoding
You will be able to see a small sample of python code on how to send a request and print a response. You are missing your token as well so make sure to get one and send it in your data field.</p>

Title: Opencellid request location

Body:
I have an csv that contain the information of cell towers. MMC, MNC, LAC, ID.
The python script I wrote read from the csv file
Iterate through rows and extract the information of the cell in a dictionary:

Cell={"MMC":6050, "MNC":01, "LAN":213, "ID":3657, "TX":230, "RX":960, "LONG":None, "LAT":None}

Now, I want to connect to opencellid  to get the location of the cell.
It maybe something like this:

data={"MMC":6050, "MNC":01, "LAN":213, "ID":3657}
res=requests.post("https://www.opencellid.com/location/search.php", data)
res.json()

I don't have a clear idea about this. And I don't know how to deal with the Opencellid API.
I really need help?

ContentLicense: CC BY-SA 4.0


问:
How to turn a string of letters into integer?
Specifically, I'm taking a word that a user inputs, which is equivalent to a number (that the user wouldn't know).

my code:

```<code>animal = raw_input( > )  #and a user inputs cat
dog = 30
cat = 10
frog = 5
print 10 + int(animal) #with the hope that will output 20
</code>```

Not sure how to do it..

答:
Be sure to handle every input value:</p>

```<code>types = {'dog': 30, 'cat': 10, 'frog': 5}

def getInput():
  try:
    return 10 + types[raw_input("Give me an animal: ")]
  except:
    print("BAD! Available animals are: {}".format(", ".join(types.keys())))
    return getInput()

print(getInput())
</code>```

Body:
Specifically, I'm taking a word that a user inputs, which is equivalent to a number (that the user wouldn't know).

my code:

animal = raw_input( > )  #and a user inputs cat
dog = 30
cat = 10
frog = 5
print 10 + int(animal) #with the hope that will output 20

Not sure how to do it..

Body:
Be sure to handle every input value:

types = {'dog': 30, 'cat': 10, 'frog': 5}

def getInput():
  try:
    return 10 + types[raw_input("Give me an animal: ")]
  except:
    print("BAD! Available animals are: {}".format(", ".join(types.keys())))
    return getInput()

print(getInput())


问:
Load Two Dimensional Array from LINQ Query?
I’m using VB.Net and have the following LINQ Query…

```<code>Dim ACFTTail5 = (From tailcounts In db.TailCounts _
                 Where tailcounts.Model = "UH-60A" _
                 Group tailcounts By _
                 tailcounts.Tail, tailcounts.Model _
                 Into g = Group Order By Tail _
                 Select Tail, rdf = CStr(g.Sum(Function(p) _ p.TailCount))).ToArray
</code>```

I’m trying to get a two dimensional array like below..

```<code>    ACFTTail5 (0)(0) “Tail-a”
    ACFTTail5 (0)(1) “RDF-a”
    ACFTTail5 (1)(0) “Tail-b”
    ACFTTail5 (1)(1) “RDF-b”
    ACFTTail5 (2)(0) “Tail-c”
    ACFTTail5 (2)(1) “RDF-c”
</code>```

ETC..

I have tried…

```<code>    Dim ACFTTail5(,) As String

    ACFTTail5 = (From tailcounts In db.TailCounts _
                 Where tailcounts.Model = "UH-60A" _
                 Group tailcounts By _
                 tailcounts.Tail, tailcounts.Model _
                 Into g = Group Order By Tail _
                 Select Tail, rdf = CStr(g.Sum(Function(p) p.TailCount)))
</code>```

But get the following error…

“Unable to cast object of type 'System.Data.Linq.DataQuery1[VB$AnonymousType_42[System.String,System.String]]' to type 'System.String[,]'."

Any suggestions would be greatly appreciated…

Thanks

答:
If you could be less concerned with forcing it into a 2d array, you could just allow the compiler to assign the anonymous IQueryable type and use that for iteration:

```<code>Dim ACFTTail5 = (From tailcounts In db.TailCounts _
             Where tailcounts.Model = "UH-60A" _
             Group tailcounts By _
             tailcounts.Tail, tailcounts.Model _
             Into g = Group Order By Tail _
             Select Tail, rdf = CStr(g.Sum(Function(p) p.TailCount)))
</code>```

You could then just use the For each iterator to cycle through whatever you needed.

Edit:

I haven't tested this little piece by any stretch, but you should be able to use a List

```<code>Dim ACFTTail5 as List(Of String())

ACFTTail5 = new List(Of String())(From tailcounts In db.TailCounts _
             Where tailcounts.Model = "UH-60A" _
             Group tailcounts By _
             tailcounts.Tail, tailcounts.Model _
             Into g = Group Order By Tail _
             Select new String() { Tail, rdf = CStr(g.Sum(Function(p) p.TailCount)) })

Dim ACFTTail5_2d_Array as String(,) = ACFTTail5.ToArray()
</code>```

The key that I'm using here is to select it directly into a new class (in this case a string array), and keep it in a List specifically for string arrays. Then you should be able to send that to a string array of string arrays.

Body:
I’m using VB.Net and have the following LINQ Query…

Dim ACFTTail5 = (From tailcounts In db.TailCounts _
                 Where tailcounts.Model = "UH-60A" _
                 Group tailcounts By _
                 tailcounts.Tail, tailcounts.Model _
                 Into g = Group Order By Tail _
                 Select Tail, rdf = CStr(g.Sum(Function(p) _ p.TailCount))).ToArray

I’m trying to get a two dimensional array like below..

    ACFTTail5 (0)(0) “Tail-a”
    ACFTTail5 (0)(1) “RDF-a”
    ACFTTail5 (1)(0) “Tail-b”
    ACFTTail5 (1)(1) “RDF-b”
    ACFTTail5 (2)(0) “Tail-c”
    ACFTTail5 (2)(1) “RDF-c”

ETC..

I have tried…

    Dim ACFTTail5(,) As String

    ACFTTail5 = (From tailcounts In db.TailCounts _
                 Where tailcounts.Model = "UH-60A" _
                 Group tailcounts By _
                 tailcounts.Tail, tailcounts.Model _
                 Into g = Group Order By Tail _
                 Select Tail, rdf = CStr(g.Sum(Function(p) p.TailCount)))

But get the following error…

“Unable to cast object of type 'System.Data.Linq.DataQuery1[VB$AnonymousType_42[System.String,System.String]]' to type 'System.String[,]'."

Any suggestions would be greatly appreciated…

Thanks

Body:
If you could be less concerned with forcing it into a 2d array, you could just allow the compiler to assign the anonymous IQueryable type and use that for iteration:

Dim ACFTTail5 = (From tailcounts In db.TailCounts _
             Where tailcounts.Model = "UH-60A" _
             Group tailcounts By _
             tailcounts.Tail, tailcounts.Model _
             Into g = Group Order By Tail _
             Select Tail, rdf = CStr(g.Sum(Function(p) p.TailCount)))

You could then just use the For each iterator to cycle through whatever you needed.

Edit:

I haven't tested this little piece by any stretch, but you should be able to use a List

Dim ACFTTail5 as List(Of String())

ACFTTail5 = new List(Of String())(From tailcounts In db.TailCounts _
             Where tailcounts.Model = "UH-60A" _
             Group tailcounts By _
             tailcounts.Tail, tailcounts.Model _
             Into g = Group Order By Tail _
             Select new String() { Tail, rdf = CStr(g.Sum(Function(p) p.TailCount)) })

Dim ACFTTail5_2d_Array as String(,) = ACFTTail5.ToArray()

The key that I'm using here is to select it directly into a new class (in this case a string array), and keep it in a List specifically for string arrays. Then you should be able to send that to a string array of string arrays.


问:
Split a datetime string into date time in C++
Assume that I have an string like this: 20160501124254.000

The string is date and time without delimiter. It must be this: 2016/05/01  12:42:54.

How can I split the first string to the second string and save each date and time in separate variables in C++?

Actually I need a little function for it.

答:
You can try something like</p>

```<code>int year;
int month;
int day;
int hour;
int minute;
int second;
sscanf(buffer, "%4d%2d%2d%2d%2d%2d", &year, &month, &day, &hour, &minute, &second);
</code>```

Body:
You can try something like

int year;
int month;
int day;
int hour;
int minute;
int second;
sscanf(buffer, "%4d%2d%2d%2d%2d%2d", &year, &month, &day, &hour, &minute, &second);


答:
A dictionary is the best idea, has other's have posted. Just don't forget to handle bad input

```<code>animals = dict(dog=30,cat=10,frog=5)
animal = raw_input(">") # and a user inputs cat
if animal in animals:
    print "animal %s id: %d" % (animal,animals[animal])
else:
    print "animal '%s' not found" % (animal,)
</code>```

https://docs.python.org/2/tutorial/datastructures.html#dictionaries

Title: How to turn a string of letters into integer?

Body:
A dictionary is the best idea, has other's have posted. Just don't forget to handle bad input

animals = dict(dog=30,cat=10,frog=5)
animal = raw_input(">") # and a user inputs cat
if animal in animals:
    print "animal %s id: %d" % (animal,animals[animal])
else:
    print "animal '%s' not found" % (animal,)

https://docs.python.org/2/tutorial/datastructures.html#dictionaries