问:
Why can you set multiple accessModes on a persistent volume?
For example in the following example:

```<code>apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: exmaple-pvc
spec:
  accessModes:
    - ReadOnlyMany
    - ReadWriteMany
  storageClassName: standard
  volumeMode: Filesystem
  resources:
    requests:
      storage: 1Gi
</code>```

Why is this allowed? What is the actual behavior of the volume in this case? Read only? Read and write?

答:
To be able to fully understand why a certain structure is used in a specific field of yaml definition, first we need to understand the purpose of this particular field. We need to ask what it is for, what is its function in this particular kubernetes api-resource.

I struggled a bit finding the proper explanation of accessModes in PersistentVolumeClaim and I must admit that what I found in official kubernetes docs did not safisfy me:

A PersistentVolume can be mounted on a host in any way supported by
the resource provider. As shown in the table below, providers will
have different capabilities and each PV’s access modes are set to the
specific modes supported by that particular volume. For example, NFS
can support multiple read/write clients, but a specific NFS PV might
be exported on the server as read-only. Each PV gets its own set of
access modes describing that specific PV’s capabilities.

Fortunately this time I managed to find really great explanation of this topic in OpenShift documentation. We can read there:

Claims are matched to volumes with similar access modes. The only two
matching criteria are access modes and size. A claim’s access modes
represent a request. Therefore, you might be granted more, but never
less. For example, if a claim requests RWO, but the only volume
available is an NFS PV (RWO+ROX+RWX), the claim would then match NFS
because it supports RWO.

Direct matches are always attempted first. The volume’s modes must
match or contain more modes than you requested. The size must be
greater than or equal to what is expected. If two types of volumes,
such as NFS and iSCSI, have the same set of access modes, either of
them can match a claim with those modes. There is no ordering between
types of volumes and no way to choose one type over another.

All volumes with the same modes are grouped, and then sorted by size,
smallest to largest. The binder gets the group with matching modes and
iterates over each, in size order, until one size matches.

And now probably the most important part:

A volume’s  AccessModes  are descriptors of the volume’s
capabilities. They are not enforced constraints. The storage provider
is responsible for runtime errors resulting from invalid use of the
resource.

I emphasized this part as AccessModes can be very easily misunderstood. Let's look at the example:

```<code>apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: exmaple-pvc-2
spec:
  accessModes:
  - ReadOnlyMany
  storageClassName: standard
  volumeMode: Filesystem
  resources:
    requests:
      storage: 1Gi
</code>```

The fact that we specified in our PersistentVolumeClaim definition only ReadOnlyMany access mode doesn't mean it cannot be used in other accessModes supported by our storage provider. It's important to understand that we cannot put here any constraint on how the requested storage can be used by our Pods. If our storage provider, hidden behind our standard storage class, supports also ReadWriteOnce, it will be also available for use.

Answering your particular question...

Why is this allowed? What is the actual behavior of the volume in this
case? Read only? Read and write?

It doesn't define behavior of the volume at all. The volume will behave according to its capabilities (we don't define them, they are imposed in advance, being part of the storage specification). In other words we will be able to use it in our Pods in all possible ways, in which it is allowed to be used.

Let's say our standard storage provisioner, which in case of GKE happens to be Google Compute Engine Persistent Disk:

```<code>$ kubectl get storageclass
NAME                 PROVISIONER            AGE
standard (default)   kubernetes.io/gce-pd   10d
</code>```

currently supports two AccessModes:

ReadWriteOnce

ReadOnlyMany

So we can use all of them, no matter what we specified in our claim e.g. this way:

```<code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-app
  labels:
    app: my-app
spec:
  replicas: 1
  selector:
    matchLabels:
      app: debian
  template:
    metadata:
      labels:
        app: debian
    spec:
      containers:
      - name: debian
        image: debian
        command: ['sh', '-c', 'sleep 3600']
        volumeMounts:
         - mountPath: "/mnt"
           name: my-volume
           readOnly: true
      volumes:
      - name: my-volume
        persistentVolumeClaim:
          claimName: example-pvc-2
      initContainers:
      - name: init-myservice
        image: busybox
        command: ['sh', '-c', 'echo "Content of my file" > /mnt/my_file']
        volumeMounts:
         - mountPath: "/mnt"
           name: my-volume
</code>```

In the above example both capabilities are used. First our volume is mounted in rw mode by the init container which saves to it some file and after that it is mounted to the main container as read-only file system. We are still able to do it even though we specified in our PersistentVolumeClaim only one access mode:

```<code>spec:
  accessModes:
  - ReadOnlyMany
</code>```

Going back to the question you asked in the title:

Why can you set multiple accessModes on a persistent volume?

the answer is: You cannot set them at all as they are already set by the storage provider, you can only request this way what storage you want, what requirements it must meet and one of these requirements are access modes it supports.

Basically by typing:

```<code>spec:
  accessModes:
    - ReadOnlyMany
    - ReadWriteOnce
</code>```

in our PersistentVolulmeClaim definition we say:

"Hey! Storage provider! Give me a volume that supports this set of accessModes. I don't care if it supports any others, like ReadWriteMany, as I don't need them. Give me something that meets my requirements!"

I believe that further explanation why an array is used here is not needed.

Body:
For example in the following example:

apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: exmaple-pvc
spec:
  accessModes:
    - ReadOnlyMany
    - ReadWriteMany
  storageClassName: standard
  volumeMode: Filesystem
  resources:
    requests:
      storage: 1Gi

Why is this allowed? What is the actual behavior of the volume in this case? Read only? Read and write?

Body:
To be able to fully understand why a certain structure is used in a specific field of yaml definition, first we need to understand the purpose of this particular field. We need to ask what it is for, what is its function in this particular kubernetes api-resource.

I struggled a bit finding the proper explanation of accessModes in PersistentVolumeClaim and I must admit that what I found in official kubernetes docs did not safisfy me:

A PersistentVolume can be mounted on a host in any way supported by
the resource provider. As shown in the table below, providers will
have different capabilities and each PV’s access modes are set to the
specific modes supported by that particular volume. For example, NFS
can support multiple read/write clients, but a specific NFS PV might
be exported on the server as read-only. Each PV gets its own set of
access modes describing that specific PV’s capabilities.

Fortunately this time I managed to find really great explanation of this topic in OpenShift documentation. We can read there:

Claims are matched to volumes with similar access modes. The only two
matching criteria are access modes and size. A claim’s access modes
represent a request. Therefore, you might be granted more, but never
less. For example, if a claim requests RWO, but the only volume
available is an NFS PV (RWO+ROX+RWX), the claim would then match NFS
because it supports RWO.

Direct matches are always attempted first. The volume’s modes must
match or contain more modes than you requested. The size must be
greater than or equal to what is expected. If two types of volumes,
such as NFS and iSCSI, have the same set of access modes, either of
them can match a claim with those modes. There is no ordering between
types of volumes and no way to choose one type over another.

All volumes with the same modes are grouped, and then sorted by size,
smallest to largest. The binder gets the group with matching modes and
iterates over each, in size order, until one size matches.

And now probably the most important part:

A volume’s  AccessModes  are descriptors of the volume’s
capabilities. They are not enforced constraints. The storage provider
is responsible for runtime errors resulting from invalid use of the
resource.

I emphasized this part as AccessModes can be very easily misunderstood. Let's look at the example:

apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: exmaple-pvc-2
spec:
  accessModes:
  - ReadOnlyMany
  storageClassName: standard
  volumeMode: Filesystem
  resources:
    requests:
      storage: 1Gi

The fact that we specified in our PersistentVolumeClaim definition only ReadOnlyMany access mode doesn't mean it cannot be used in other accessModes supported by our storage provider. It's important to understand that we cannot put here any constraint on how the requested storage can be used by our Pods. If our storage provider, hidden behind our standard storage class, supports also ReadWriteOnce, it will be also available for use.

Answering your particular question...

Why is this allowed? What is the actual behavior of the volume in this
case? Read only? Read and write?

It doesn't define behavior of the volume at all. The volume will behave according to its capabilities (we don't define them, they are imposed in advance, being part of the storage specification). In other words we will be able to use it in our Pods in all possible ways, in which it is allowed to be used.

Let's say our standard storage provisioner, which in case of GKE happens to be Google Compute Engine Persistent Disk:

$ kubectl get storageclass
NAME                 PROVISIONER            AGE
standard (default)   kubernetes.io/gce-pd   10d

currently supports two AccessModes:

ReadWriteOnce

ReadOnlyMany

So we can use all of them, no matter what we specified in our claim e.g. this way:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-app
  labels:
    app: my-app
spec:
  replicas: 1
  selector:
    matchLabels:
      app: debian
  template:
    metadata:
      labels:
        app: debian
    spec:
      containers:
      - name: debian
        image: debian
        command: ['sh', '-c', 'sleep 3600']
        volumeMounts:
         - mountPath: "/mnt"
           name: my-volume
           readOnly: true
      volumes:
      - name: my-volume
        persistentVolumeClaim:
          claimName: example-pvc-2
      initContainers:
      - name: init-myservice
        image: busybox
        command: ['sh', '-c', 'echo "Content of my file" > /mnt/my_file']
        volumeMounts:
         - mountPath: "/mnt"
           name: my-volume

In the above example both capabilities are used. First our volume is mounted in rw mode by the init container which saves to it some file and after that it is mounted to the main container as read-only file system. We are still able to do it even though we specified in our PersistentVolumeClaim only one access mode:

spec:
  accessModes:
  - ReadOnlyMany

Going back to the question you asked in the title:

Why can you set multiple accessModes on a persistent volume?

the answer is: You cannot set them at all as they are already set by the storage provider, you can only request this way what storage you want, what requirements it must meet and one of these requirements are access modes it supports.

Basically by typing:

spec:
  accessModes:
    - ReadOnlyMany
    - ReadWriteOnce

in our PersistentVolulmeClaim definition we say:

"Hey! Storage provider! Give me a volume that supports this set of accessModes. I don't care if it supports any others, like ReadWriteMany, as I don't need them. Give me something that meets my requirements!"

I believe that further explanation why an array is used here is not needed.


来源: stackexchange

问:
Count rows with same value while keeping columns
Lets say i have the following sql table:

```<code>id  item_count  texture_count
30  82          205
30  133         406
35  253         658
30  552         1004
35  234         475
35  119         288
30  104         115
36  594         1422
</code>```

How can i modify my select query to return my data with an additional column telling me the number of occurrences for each ID, while keeping the original columns collected? Which would result in this:

```<code>id  item_count  texture_count   id_count
30  82          205             4
30  133         406             4
35  253         658             3
30  552         1004            4
35  234         475             3
35  119         288             3
30  104         115             4
36  594         1422            1
</code>```

Query is this:

```<code>SELECT
    CAST ((2 * FLOOR(idvalue / 2)) AS INT) as id, -- im creating an id based on this operation, currently id value is a float
    item_count,
    texture_count
FROM
    db
</code>```

答:
You can use window functions, if your database supports them. What you ask for is as simple as a window count:

```<code>select
    t.*,
    count(*) over(partition by id) id_count
from mytable
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Lets say i have the following sql table:

id  item_count  texture_count
30  82          205
30  133         406
35  253         658
30  552         1004
35  234         475
35  119         288
30  104         115
36  594         1422

How can i modify my select query to return my data with an additional column telling me the number of occurrences for each ID, while keeping the original columns collected? Which would result in this:

id  item_count  texture_count   id_count
30  82          205             4
30  133         406             4
35  253         658             3
30  552         1004            4
35  234         475             3
35  119         288             3
30  104         115             4
36  594         1422            1

Query is this:

SELECT
    CAST ((2 * FLOOR(idvalue / 2)) AS INT) as id, -- im creating an id based on this operation, currently id value is a float
    item_count,
    texture_count
FROM
    db

Body:
You can use window functions, if your database supports them. What you ask for is as simple as a window count:

select
    t.*,
    count(*) over(partition by id) id_count
from mytable


问:
Python Data science beginner function question
I'm prepping for a Data science bootcamp and know nothing about coding. Im stuck on this lab im doing right now.

so I have this list:

```<code>travel_destinations = ['argentina', 'mexico', 'italy', 'finland', 'canada', 'croatia']
</code>```

I need to write a function called number_of_destinations that returns the number of destinations in the list travel_destinations.

Here's my code:

```<code>def number_of_destinations(travel_destinations):
    x = len(travel_destinations)
    print (x)
</code>```

Which returns:

```<code><function __main__.number_of_destinations(travel_destinations)>
</code>```

Ive tried so many different approaches and python just keeps spitting out "yes this is a function" basically. Can anyone help me figure out what im doing wrong here?

答:
Your function doesn't return anything because you're missing a return statement. The print function outputs to the terminal but does not return, so you need to swap that out.</p>

```<code>def number_of_destinations(travel_destinations):
    x = len(travel_destinations)
    return x
</code>```

Body:
I'm prepping for a Data science bootcamp and know nothing about coding. Im stuck on this lab im doing right now.

so I have this list:

travel_destinations = ['argentina', 'mexico', 'italy', 'finland', 'canada', 'croatia']

I need to write a function called number_of_destinations that returns the number of destinations in the list travel_destinations.

Here's my code:

def number_of_destinations(travel_destinations):
    x = len(travel_destinations)
    print (x)

Which returns:

<function __main__.number_of_destinations(travel_destinations)>

Ive tried so many different approaches and python just keeps spitting out "yes this is a function" basically. Can anyone help me figure out what im doing wrong here?

Body:
Your function doesn't return anything because you're missing a return statement. The print function outputs to the terminal but does not return, so you need to swap that out.

def number_of_destinations(travel_destinations):
    x = len(travel_destinations)
    return x


问:
Parsing of a huge xml file with `pythons etree.iterparse()` does not work right. Is there a logic error in the code?
I want to parse a huge file xml-file. The records in this huge file do look for example like this. And in general the file looks like this

```<code><?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE dblp SYSTEM "dblp.dtd">
<dblp>
    record_1
    ...
    record_n
</dblp>
</code>```

I wrote some code, that shall get me a selection of recordings from this file.

If I let the code run (takes nearly 50 Minutes including storage in the MySQL-Database) I notice, that there is a record, which seams to have nearly a million authors. This must be wrong. I even checked up on it by looking into the file make sure, that the file has no errors in it. The paper has only 5 or 6 authors, so all is fine wirh dblp.xml. So I assume a logic error in my code. But I can't figure out where this could be. Perhaps someone can tell me, where the error is?

The code stops in the line if len(auth) > 2000.

```<code>import sys
import MySQLdb
from lxml import etree

elements = ['article', 'inproceedings', 'proceedings', 'book', 'incollection']
tags = ["author", "title", "booktitle", "year", "journal"]

def fast_iter(context, cursor):
    mydict = {} # represents a paper with all its tags.
    auth = [] # a list of authors who have written the paper "together".
    counter = 0 # counts the papers

    for event, elem in context:
        if elem.tag in elements and event == "start":
            mydict["element"] = elem.tag
            mydict["mdate"] = elem.get("mdate")
            mydict["key"] = elem.get("key")

        elif elem.tag == "title" and elem.text != None:
            mydict["title"] = elem.text
        elif elem.tag == "booktitle" and elem.text != None:
            mydict["booktitle"] = elem.text
        elif elem.tag == "year" and elem.text != None:
            mydict["year"] = elem.text
        elif elem.tag == "journal" and elem.text != None:
            mydict["journal"] = elem.text
        elif elem.tag == "author" and elem.text != None:
            auth.append(elem.text)
        elif event == "end" and elem.tag in elements:
            counter += 1
            print counter
            #populate_database(mydict, auth, cursor)
            mydict.clear()
            auth = []
            if mydict or auth:
                sys.exit("Program aborted because auth or mydict was not deleted properly!")
        if len(auth) > 200: # There are up to ~150 authors per paper.
            sys.exit("auth: It seams there is a paper which has too many authors.!")
        if len(mydict) > 50: # A paper can have much metadata.
            sys.exit("mydict: It seams there is a paper which has too many tags.")

        elem.clear()
        while elem.getprevious() is not None:
            del elem.getparent()[0]
    del context

def main():
        cursor = connectToDatabase()
        cursor.execute("""SET NAMES utf8""")

        context = etree.iterparse(PATH_TO_XML, dtd_validation=True, events=("start", "end"))
        fast_iter(context, cursor)

        cursor.close()

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

EDIT:

I was totally misguided, when I wrote this function. I made a huge mistake by overlooking, that while trying to skip some unwanted recordings the get messed up with some wanted recordings. And at a certain point in the file, where I skiped nearly a million records in a row, the following wanted record got blown up.

With the help of John and Paul I managed to rewrite my code. It is parsing right now, and seams to do it well. I'll report back, if some unexpected errors remained unsolved. Elsewise thank you all for your help! I really appreciated it!

```<code>def fast_iter2(context, cursor):
    elements = set([
        'article', 'inproceedings', 'proceedings', 'book', 'incollection',
        'phdthesis', "mastersthesis", "www"
        ])
    childElements = set(["title", "booktitle", "year", "journal", "ee"])

    paper = {} # represents a paper with all its tags.
    authors = []   # a list of authors who have written the paper "together".
    paperCounter = 0
    for event, element in context:
        tag = element.tag
        if tag in childElements:
            if element.text:
                paper[tag] = element.text
                # print tag, paper[tag]
        elif tag == "author":
            if element.text:
                authors.append(element.text)
                # print "AUTHOR:", authors[-1]
        elif tag in elements:
            paper["element"] = tag
            paper["mdate"] = element.get("mdate")
            paper["dblpkey"] = element.get("key")
            # print tag, element.get("mdate"), element.get("key"), event
            if paper["element"] in ['phdthesis', "mastersthesis", "www"]:
                pass
            else:
                populate_database(paper, authors, cursor)
            paperCounter += 1
            print paperCounter
            paper = {}
            authors = []
            # if paperCounter == 100:
            #     break
            element.clear()
            while element.getprevious() is not None:
                del element.getparent()[0]
    del context
</code>```

答:
Please eliminate one source of confusion: You haven't actually said that the code that you showed does actually trip over on one of your "count of things > 2000" tests. If not, then the problem lies in the database update code (that you haven't showed us).

If it does so trip over:

(1) Reduce the limits from 2000 to reasonable values (about 20 for auth and exactly 7 for mydict)

(2) When the trip happens, print repr(mydict); print; print repr(auth) and analyse the contents in comparison with your file.

Aside: with iterparse(), elem.text is NOT guaranteed to have been parsed when the "start" event happens. To save some running time, you should access elem.text only when the "end" event happens. In fact, there seems to be no reason why you want "start" events at all. Also you define a list tags but never use it. The start of your function could be written much more concisely:

```<code>def fast_iter(context, cursor):
    mydict = {} # represents a paper with all its tags.
    auth = [] # a list of authors who have written the paper "together".
    counter = 0 # counts the papers
    tagset1 = set(['article', 'inproceedings', 'proceedings', 'book', 'incollection'])
    tagset2 = set(["title", "booktitle", "year", "journal"])
    for event, elem in context:
        tag = elem.tag
        if tag in tagset2:
            if elem.text:
                mydict[tag] = elem.text
        elif tag == "author":
            if elem.text:
                auth.append(elem.text)
        elif tag in tagset1:
            counter += 1
            print counter
            mydict["element"] = tag
            mydict["mdate"] = elem.get("mdate")
            mydict["dblpkey"] = elem.get("key")
            #populate_database(mydict, auth, cursor)
            mydict.clear() # Why not just do mydict = {} ??
            auth = []
            # etc etc
</code>```

Don't forget to fix the call to iterparse() to remove the events arg.

Also I'm reasonably certain that the elem.clear() should be done only when event is "end" and needs to be done only when tag in tagset1. Read the relevant docs carefully. Doing the cleanup in a "start" event could very well be damaging your tree.

ContentLicense: CC BY-SA 3.0

Body:
I want to parse a huge file xml-file. The records in this huge file do look for example like this. And in general the file looks like this

<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE dblp SYSTEM "dblp.dtd">
<dblp>
    record_1
    ...
    record_n
</dblp>

I wrote some code, that shall get me a selection of recordings from this file.

If I let the code run (takes nearly 50 Minutes including storage in the MySQL-Database) I notice, that there is a record, which seams to have nearly a million authors. This must be wrong. I even checked up on it by looking into the file make sure, that the file has no errors in it. The paper has only 5 or 6 authors, so all is fine wirh dblp.xml. So I assume a logic error in my code. But I can't figure out where this could be. Perhaps someone can tell me, where the error is?

The code stops in the line if len(auth) > 2000.

import sys
import MySQLdb
from lxml import etree

elements = ['article', 'inproceedings', 'proceedings', 'book', 'incollection']
tags = ["author", "title", "booktitle", "year", "journal"]

def fast_iter(context, cursor):
    mydict = {} # represents a paper with all its tags.
    auth = [] # a list of authors who have written the paper "together".
    counter = 0 # counts the papers

    for event, elem in context:
        if elem.tag in elements and event == "start":
            mydict["element"] = elem.tag
            mydict["mdate"] = elem.get("mdate")
            mydict["key"] = elem.get("key")

        elif elem.tag == "title" and elem.text != None:
            mydict["title"] = elem.text
        elif elem.tag == "booktitle" and elem.text != None:
            mydict["booktitle"] = elem.text
        elif elem.tag == "year" and elem.text != None:
            mydict["year"] = elem.text
        elif elem.tag == "journal" and elem.text != None:
            mydict["journal"] = elem.text
        elif elem.tag == "author" and elem.text != None:
            auth.append(elem.text)
        elif event == "end" and elem.tag in elements:
            counter += 1
            print counter
            #populate_database(mydict, auth, cursor)
            mydict.clear()
            auth = []
            if mydict or auth:
                sys.exit("Program aborted because auth or mydict was not deleted properly!")
        if len(auth) > 200: # There are up to ~150 authors per paper.
            sys.exit("auth: It seams there is a paper which has too many authors.!")
        if len(mydict) > 50: # A paper can have much metadata.
            sys.exit("mydict: It seams there is a paper which has too many tags.")

        elem.clear()
        while elem.getprevious() is not None:
            del elem.getparent()[0]
    del context

def main():
        cursor = connectToDatabase()
        cursor.execute("""SET NAMES utf8""")

        context = etree.iterparse(PATH_TO_XML, dtd_validation=True, events=("start", "end"))
        fast_iter(context, cursor)

        cursor.close()

if __name__ == '__main__':
    main()

EDIT:

I was totally misguided, when I wrote this function. I made a huge mistake by overlooking, that while trying to skip some unwanted recordings the get messed up with some wanted recordings. And at a certain point in the file, where I skiped nearly a million records in a row, the following wanted record got blown up.

With the help of John and Paul I managed to rewrite my code. It is parsing right now, and seams to do it well. I'll report back, if some unexpected errors remained unsolved. Elsewise thank you all for your help! I really appreciated it!

def fast_iter2(context, cursor):
    elements = set([
        'article', 'inproceedings', 'proceedings', 'book', 'incollection',
        'phdthesis', "mastersthesis", "www"
        ])
    childElements = set(["title", "booktitle", "year", "journal", "ee"])

    paper = {} # represents a paper with all its tags.
    authors = []   # a list of authors who have written the paper "together".
    paperCounter = 0
    for event, element in context:
        tag = element.tag
        if tag in childElements:
            if element.text:
                paper[tag] = element.text
                # print tag, paper[tag]
        elif tag == "author":
            if element.text:
                authors.append(element.text)
                # print "AUTHOR:", authors[-1]
        elif tag in elements:
            paper["element"] = tag
            paper["mdate"] = element.get("mdate")
            paper["dblpkey"] = element.get("key")
            # print tag, element.get("mdate"), element.get("key"), event
            if paper["element"] in ['phdthesis', "mastersthesis", "www"]:
                pass
            else:
                populate_database(paper, authors, cursor)
            paperCounter += 1
            print paperCounter
            paper = {}
            authors = []
            # if paperCounter == 100:
            #     break
            element.clear()
            while element.getprevious() is not None:
                del element.getparent()[0]
    del context

Body:
Please eliminate one source of confusion: You haven't actually said that the code that you showed does actually trip over on one of your "count of things > 2000" tests. If not, then the problem lies in the database update code (that you haven't showed us).

If it does so trip over:

(1) Reduce the limits from 2000 to reasonable values (about 20 for auth and exactly 7 for mydict)

(2) When the trip happens, print repr(mydict); print; print repr(auth) and analyse the contents in comparison with your file.

Aside: with iterparse(), elem.text is NOT guaranteed to have been parsed when the "start" event happens. To save some running time, you should access elem.text only when the "end" event happens. In fact, there seems to be no reason why you want "start" events at all. Also you define a list tags but never use it. The start of your function could be written much more concisely:

def fast_iter(context, cursor):
    mydict = {} # represents a paper with all its tags.
    auth = [] # a list of authors who have written the paper "together".
    counter = 0 # counts the papers
    tagset1 = set(['article', 'inproceedings', 'proceedings', 'book', 'incollection'])
    tagset2 = set(["title", "booktitle", "year", "journal"])
    for event, elem in context:
        tag = elem.tag
        if tag in tagset2:
            if elem.text:
                mydict[tag] = elem.text
        elif tag == "author":
            if elem.text:
                auth.append(elem.text)
        elif tag in tagset1:
            counter += 1
            print counter
            mydict["element"] = tag
            mydict["mdate"] = elem.get("mdate")
            mydict["dblpkey"] = elem.get("key")
            #populate_database(mydict, auth, cursor)
            mydict.clear() # Why not just do mydict = {} ??
            auth = []
            # etc etc

Don't forget to fix the call to iterparse() to remove the events arg.

Also I'm reasonably certain that the elem.clear() should be done only when event is "end" and needs to be done only when tag in tagset1. Read the relevant docs carefully. Doing the cleanup in a "start" event could very well be damaging your tree.


答:
It sounds like you aren't passing data to the function. </p>

```<code>def number_of_destinations(destinations):
    x = len(travel_destinations)
    print (x)
    return x

travel_destinations = ['argentina', 'mexico', 'italy', 'finland', 'canada', 'croatia']
destinations_length = number_of_destinations(travel_destinations)
</code>```

Title: Python Data science beginner function question

Body:
It sounds like you aren't passing data to the function.

def number_of_destinations(destinations):
    x = len(travel_destinations)
    print (x)
    return x

travel_destinations = ['argentina', 'mexico', 'italy', 'finland', 'canada', 'croatia']
destinations_length = number_of_destinations(travel_destinations)


问:
why radio button is not marking checked on true condition in angular?
I have an anuglar7 app in which i have a dropdown list with radio buttton with each item. But radio button is not checked on successful condition. Here is what i have in my component.html

```<code><ul class="status-table-ul" (click)="$event.stopPropagation()">
<li class="status-table-li" [ngClass]="[selectedIndex === i ? 'selected' : '' , filterOpt.label === 'All' ? 'all' : '']" *ngFor="let filterOpt of referralFilterOptions;let i = index" (click)="onFilterSelect(i,filterOpt.label)">
    <label class="container">{{filterOpt.label}}
        <input type="radio" [(ngModel)]="selectedFilterOption" name="radio" [value]="filterOpt.label" [checked]="i === selectedIndex">
        <span class="checkmark"></span>
    </label>
 </li>
</ul>
</code>```

And in my component.ts i have like this

```<code>selectedIndex : number = 0;

onFilterSelect(index : number,opt : string){
    this.selectedIndex = index;
    this.refLinkArr = opt === 'All' ? this.masterRefLinkArr : this.masterRefLinkArr.filter(item => item.link_status === opt)
    $("ul.status-table-ul").removeClass("show-menu");
</code>```

Problem is that on component load first element's radio should be checked. But it's not checked on page load.
    }

答:
Remove this :

```<code>[(ngModel)]="selectedFilterOption"
</code>```

When you use [(ngModel)]="selectedFilterOption"  and [checked]="i === selectedIndex" at the same time then the checked state depends on the [(ngModel)]

if the value of selectedFilterOption is 1 it will check it but 0 means false.

Body:
I have an anuglar7 app in which i have a dropdown list with radio buttton with each item. But radio button is not checked on successful condition. Here is what i have in my component.html

    {{filterOpt.label}}
        <input type="radio" [(ngModel)]="selectedFilterOption" name="radio" [value]="filterOpt.label" [checked]="i === selectedIndex">

And in my component.ts i have like this

selectedIndex : number = 0;

onFilterSelect(index : number,opt : string){
    this.selectedIndex = index;
    this.refLinkArr = opt === 'All' ? this.masterRefLinkArr : this.masterRefLinkArr.filter(item => item.link_status === opt)
    $("ul.status-table-ul").removeClass("show-menu");

Problem is that on component load first element's radio should be checked. But it's not checked on page load.
    }

Body:
Remove this :

[(ngModel)]="selectedFilterOption"

When you use [(ngModel)]="selectedFilterOption"  and [checked]="i === selectedIndex" at the same time then the checked state depends on the [(ngModel)]

if the value of selectedFilterOption is 1 it will check it but 0 means false.


问:
Faulty If, Else Statement
I always get the the Error: unexpected 'else' in "     else" in my If, Else Statement. </p>

<p>Pls help I've been sitting with this Error since two days and need to finish my paper till tomorrow. </p>

```<code>Isflorida <- function(data) {
  data <- filter(data,is.na(State)== FALSE)
  data$Isflorida <- vector(mode = "logical", length = nrow(data))
  for (i in 1:nrow(data)) {
    if (data[i,]$State == "Florida") {
      data[i,]$Isflorida <- TRUE }
    else {data[i,]$Isflorida <- FALSE}}data}
</code>```

答:
Do not add data right after }, if really want to, add a semi-colon.

```<code>Isflorida <- function(data) {
  data <- filter(data,is.na(State)== FALSE)
  data$Isflorida <- vector(mode = "logical", length = nrow(data))
  for (i in 1:nrow(data)) {
    if (data[i,]$State == "Florida") {
      data[i,]$Isflorida <- TRUE }
    else {data[i,]$Isflorida <- FALSE}}; data}
</code>```

I would think that most R users will use more lines, like so:

```<code>Isflorida <- function(data) {
  data <- filter(data,is.na(State)== FALSE)
  data$Isflorida <- vector(mode = "logical", length = nrow(data))
  for (i in 1:nrow(data)) {
    if (data[i,]$State == "Florida") {
      data[i,]$Isflorida <- TRUE
    } else {data[i,]$Isflorida <- FALSE}
  }
  data
}
</code>```

Title: Faulty If, Else Statement

Body:
I always get the the Error: unexpected 'else' in "     else" in my If, Else Statement.

Pls help I've been sitting with this Error since two days and need to finish my paper till tomorrow.

Isflorida <- function(data) {
  data <- filter(data,is.na(State)== FALSE)
  data$Isflorida <- vector(mode = "logical", length = nrow(data))
  for (i in 1:nrow(data)) {
    if (data[i,]$State == "Florida") {
      data[i,]$Isflorida <- TRUE }
    else {data[i,]$Isflorida <- FALSE}}data}

Body:
Do not add data right after }, if really want to, add a semi-colon.

Isflorida <- function(data) {
  data <- filter(data,is.na(State)== FALSE)
  data$Isflorida <- vector(mode = "logical", length = nrow(data))
  for (i in 1:nrow(data)) {
    if (data[i,]$State == "Florida") {
      data[i,]$Isflorida <- TRUE }
    else {data[i,]$Isflorida <- FALSE}}; data}

I would think that most R users will use more lines, like so:

Isflorida <- function(data) {
  data <- filter(data,is.na(State)== FALSE)
  data$Isflorida <- vector(mode = "logical", length = nrow(data))
  for (i in 1:nrow(data)) {
    if (data[i,]$State == "Florida") {
      data[i,]$Isflorida <- TRUE
    } else {data[i,]$Isflorida <- FALSE}
  }
  data
}


问:
How to re-use a C++ closure concurrently with variable arguments -- similar to JavaScript?
JavaScript creates a closure with the scope where it was created. For example:

```<code>function startGreeter( name, iterations, delay ) {
    function greeter() {
        console.log("greetings, "+name+"! i="+iterations);
        if( --iterations )
            setTimeout( greeter, delay );
    }
    setTimeout( greeter, delay );
}

startGreeter("Alex",3,1000);
startGreeter("Beth",2,1500);
</code>```

JavaScript creates two distinct closure instances for the greeter() function; one for Alex and one for Beth. Of course, we could create dozens or hundreds of such instances; from an array of data, for example.

I would like to accomplish the same in C++; specifically, to be able to create N distinct simultaneous closure instances of a function.

```<code>void startGreeterTask( AsyncManager& asyncManager, std::string name, int iterations, longtime msDelay )
{
    TaskFunction greetingTask = [&]()
    {
        std::cout << "greetings, task " << name << "! iterations = " << iterations << std::endl;
        if( --iterations )
        {
            asyncManager.setTimeout( greetingTask, msDelay );
        }
    };
    asyncManager.setTimeout( greetingTask, msDelay );
}

int main( int argc, char* argv[] )
{
    AsyncManager asyncManager;
    startGreeterTask( asyncManager, "Alex", 3, 1000 );
    startGreeterTask( asyncManager, "Beth", 2, 1500 );
    asyncManager.execute();
}
</code>```

The AsyncManager provides the setTimeout() functionality and it works if I create multiple closures in the scope of main(). But in startGreetingTask(), the closure function greetingTask() does not work the same as the greeter() function in JavaScript. As I understand it, greetingTask() and all the referenced parameters fall out of scope when startGreeterTask() finishes executing, so the stack memory is freed. Calling startGreeterTask() a second time creates a confliting usage of stack memory, and a seg fault ensures.

How can startGreeterTask() be made to work like the startGreeter() function?

答:
Thanks to Igor Tandetnik for pointing me in the right direction. I'm posting a complete answer here for others to find.

The solution was (a) use copy capture by default, (b) use reference capture for the class instance that I do not want copied, (c) add the mutable keyword to allow the captured variables to be modified, and (d) avoid the closure function reference to itself. Now, instead of calling itself, the closure calls the function in which the closure is defined. This form of self-reference, through a layer of indirection, loses a little bit of the flexibility and expression of the JavaScript idiom, but it is fully functional and solves the problem quite nicely.

That said, if someone else solves this particular closure self-reference problem, I would like to see the solution.

```<code>void greetTask( AsyncManager& asyncManager, std::string name, int iterations, longtime msDelay )
{
    TaskFunction greetingClosure = [=,&asyncManager]() mutable
    {
        std::cout << "greetings, task " << name << "! iterations = " << iterations << std::endl;
        if( --iterations )
        {
            greetTask( asyncManager, name, iterations, msDelay );
        }
    };

    asyncManager.setTimeout( greetingClosure, msDelay );
}
</code>```

Body:
JavaScript creates a closure with the scope where it was created. For example:

function startGreeter( name, iterations, delay ) {
    function greeter() {
        console.log("greetings, "+name+"! i="+iterations);
        if( --iterations )
            setTimeout( greeter, delay );
    }
    setTimeout( greeter, delay );
}

startGreeter("Alex",3,1000);
startGreeter("Beth",2,1500);

JavaScript creates two distinct closure instances for the greeter() function; one for Alex and one for Beth. Of course, we could create dozens or hundreds of such instances; from an array of data, for example.

I would like to accomplish the same in C++; specifically, to be able to create N distinct simultaneous closure instances of a function.

void startGreeterTask( AsyncManager& asyncManager, std::string name, int iterations, longtime msDelay )
{
    TaskFunction greetingTask = [&]()
    {
        std::cout << "greetings, task " << name << "! iterations = " << iterations << std::endl;
        if( --iterations )
        {
            asyncManager.setTimeout( greetingTask, msDelay );
        }
    };
    asyncManager.setTimeout( greetingTask, msDelay );
}

int main( int argc, char* argv[] )
{
    AsyncManager asyncManager;
    startGreeterTask( asyncManager, "Alex", 3, 1000 );
    startGreeterTask( asyncManager, "Beth", 2, 1500 );
    asyncManager.execute();
}

The AsyncManager provides the setTimeout() functionality and it works if I create multiple closures in the scope of main(). But in startGreetingTask(), the closure function greetingTask() does not work the same as the greeter() function in JavaScript. As I understand it, greetingTask() and all the referenced parameters fall out of scope when startGreeterTask() finishes executing, so the stack memory is freed. Calling startGreeterTask() a second time creates a confliting usage of stack memory, and a seg fault ensures.

How can startGreeterTask() be made to work like the startGreeter() function?

Body:
Thanks to Igor Tandetnik for pointing me in the right direction. I'm posting a complete answer here for others to find.

The solution was (a) use copy capture by default, (b) use reference capture for the class instance that I do not want copied, (c) add the mutable keyword to allow the captured variables to be modified, and (d) avoid the closure function reference to itself. Now, instead of calling itself, the closure calls the function in which the closure is defined. This form of self-reference, through a layer of indirection, loses a little bit of the flexibility and expression of the JavaScript idiom, but it is fully functional and solves the problem quite nicely.

That said, if someone else solves this particular closure self-reference problem, I would like to see the solution.

void greetTask( AsyncManager& asyncManager, std::string name, int iterations, longtime msDelay )
{
    TaskFunction greetingClosure = [=,&asyncManager]() mutable
    {
        std::cout << "greetings, task " << name << "! iterations = " << iterations << std::endl;
        if( --iterations )
        {
            greetTask( asyncManager, name, iterations, msDelay );
        }
    };

    asyncManager.setTimeout( greetingClosure, msDelay );
}


问:
An unhandled exception occurred: Job name "..getProjectMetadata" does not exist
When I start to run my Application, I get this error:

```<code>**[error] Error: Job name "..getProjectMetadata" does not exist.**
     at Observable._subscribe (/Users/vasil/KSS/kssfrontend/node_modules/@angular-devkit/core/src/experimental/jobs/simple-scheduler.js:350:23)
     at Observable._trySubscribe (/Users/vasil/KSS/kssfrontend/node_modules/@angular-devkit/core/node_modules/rxjs/internal/Observable.js:44:25)
     at Observable.subscribe (/Users/vasil/KSS/kssfrontend/node_modules/@angular-devkit/core/node_modules/rxjs/internal/Observable.js:30:22)
     at /Users/vasil/KSS/kssfrontend/node_modules/@angular-devkit/core/node_modules/rxjs/internal/util/subscribeTo.js:22:31
     at Object.subscribeToResult (/Users/vasil/KSS/kssfrontend/node_modules/@angular-devkit/core/node_modules/rxjs/internal/util/subscribeToResult.js:10:45)
     at SwitchMapSubscriber._innerSub (/Users/vasil/KSS/kssfrontend/node_modules/@angular-devkit/core/node_modules/rxjs/internal/operators/switchMap.js:65:54)
     at SwitchMapSubscriber._next (/Users/vasil/KSS/kssfrontend/node_modules/@angular-devkit/core/node_modules/rxjs/internal/operators/switchMap.js:55:14)
     at SwitchMapSubscriber.Subscriber.next (/Users/vasil/KSS/kssfrontend/node_modules/@angular-devkit/core/node_modules/rxjs/internal/Subscriber.js:66:18)
     at SwitchMapSubscriber.notifyNext (/Users/vasil/KSS/kssfrontend/node_modules/@angular-devkit/core/node_modules/rxjs/internal/operators/switchMap.js:86:26)
     at InnerSubscriber._next (/Users/vasil/KSS/kssfrontend/node_modules/@angular-devkit/core/node_modules/rxjs/internal/InnerSubscriber.js:28:21)
     at InnerSubscriber.Subscriber.next (/Users/vasil/KSS/kssfrontend/node_modules/@angular-devkit/core/node_modules/rxjs/internal/Subscriber.js:66:18)
     at /Users/vasil/KSS/kssfrontend/node_modules/@angular-devkit/core/node_modules/rxjs/internal/util/subscribeTo.js:17:28
     at Object.subscribeToResult (/Users/vasil/KSS/kssfrontend/node_modules/@angular-devkit/core/node_modules/rxjs/internal/util/subscribeToResult.js:10:45)
     at SwitchMapSubscriber._innerSub (/Users/vasil/KSS/kssfrontend/node_modules/@angular-devkit/core/node_modules/rxjs/internal/operators/switchMap.js:65:54)
     at SwitchMapSubscriber._next (/Users/vasil/KSS/kssfrontend/node_modules/@angular-devkit/core/node_modules/rxjs/internal/operators/switchMap.js:55:14)
     at SwitchMapSubscriber.Subscriber.next (/Users/vasil/KSS/kssfrontend/node_modules/@angular-devkit/core/node_modules/rxjs/internal/Subscriber.js:66:18)
</code>```

I have these versions:
Angular CLI: 8.3.19,
Node: 12.14.0.

Any Idea what causes this problem?

答:
I was installing ngx-quill and faced the same issue.
please make sure to check the supported versions.

For example - If you are using Angular 8, make sure you are installing the supported version. In case of ngx-quill, it will be
npm install ngx-quill@5.2.0

Body:
When I start to run my Application, I get this error:

**[error] Error: Job name "..getProjectMetadata" does not exist.**
     at Observable._subscribe (/Users/vasil/KSS/kssfrontend/node_modules/@angular-devkit/core/src/experimental/jobs/simple-scheduler.js:350:23)
     at Observable._trySubscribe (/Users/vasil/KSS/kssfrontend/node_modules/@angular-devkit/core/node_modules/rxjs/internal/Observable.js:44:25)
     at Observable.subscribe (/Users/vasil/KSS/kssfrontend/node_modules/@angular-devkit/core/node_modules/rxjs/internal/Observable.js:30:22)
     at /Users/vasil/KSS/kssfrontend/node_modules/@angular-devkit/core/node_modules/rxjs/internal/util/subscribeTo.js:22:31
     at Object.subscribeToResult (/Users/vasil/KSS/kssfrontend/node_modules/@angular-devkit/core/node_modules/rxjs/internal/util/subscribeToResult.js:10:45)
     at SwitchMapSubscriber._innerSub (/Users/vasil/KSS/kssfrontend/node_modules/@angular-devkit/core/node_modules/rxjs/internal/operators/switchMap.js:65:54)
     at SwitchMapSubscriber._next (/Users/vasil/KSS/kssfrontend/node_modules/@angular-devkit/core/node_modules/rxjs/internal/operators/switchMap.js:55:14)
     at SwitchMapSubscriber.Subscriber.next (/Users/vasil/KSS/kssfrontend/node_modules/@angular-devkit/core/node_modules/rxjs/internal/Subscriber.js:66:18)
     at SwitchMapSubscriber.notifyNext (/Users/vasil/KSS/kssfrontend/node_modules/@angular-devkit/core/node_modules/rxjs/internal/operators/switchMap.js:86:26)
     at InnerSubscriber._next (/Users/vasil/KSS/kssfrontend/node_modules/@angular-devkit/core/node_modules/rxjs/internal/InnerSubscriber.js:28:21)
     at InnerSubscriber.Subscriber.next (/Users/vasil/KSS/kssfrontend/node_modules/@angular-devkit/core/node_modules/rxjs/internal/Subscriber.js:66:18)
     at /Users/vasil/KSS/kssfrontend/node_modules/@angular-devkit/core/node_modules/rxjs/internal/util/subscribeTo.js:17:28
     at Object.subscribeToResult (/Users/vasil/KSS/kssfrontend/node_modules/@angular-devkit/core/node_modules/rxjs/internal/util/subscribeToResult.js:10:45)
     at SwitchMapSubscriber._innerSub (/Users/vasil/KSS/kssfrontend/node_modules/@angular-devkit/core/node_modules/rxjs/internal/operators/switchMap.js:65:54)
     at SwitchMapSubscriber._next (/Users/vasil/KSS/kssfrontend/node_modules/@angular-devkit/core/node_modules/rxjs/internal/operators/switchMap.js:55:14)
     at SwitchMapSubscriber.Subscriber.next (/Users/vasil/KSS/kssfrontend/node_modules/@angular-devkit/core/node_modules/rxjs/internal/Subscriber.js:66:18)

I have these versions:
Angular CLI: 8.3.19,
Node: 12.14.0.

Any Idea what causes this problem?


问:
What are the best options for source control integrated with visual studio (2017), small team, multiple projects?
What are your thoughts, suggestions, and recommendations for source control for the following environment?

MUST have Visual Studio integration!
Major Languages used: Visual Basic, SQL, C#
Possible other languages: Python, ASP MVC, others
Team size: small (currently 2 and probably won't change in the near future)
Organization: Not for profit, 500 employees, small IT department

答:
Now that Git took the world of Version control tools by storm, you should have a really good reason to not choose it.

And there is not a lot of reasons.

Learn to use it, that will surely be a knowledge that you will use elsewhere. Especially now that a lot of libraries, tools and frameworks are developed in open source on git forges (GitHub, Bitbuckets,...)


问:
Make geopandas DataFrame plot on top a raster plot fit correctly
I am trying to plot the Pumps.shp data on top of the OSMap.tif file from this website on the same figure.

I tried using rasterio.plot() and geopandas.plot() methods, with matplotlibs subplots.

The problem is that the plots don't match, the raster file gets plotted in the range(0,1000) for both axis and the shp gets plotted in the actual coordinates range(around 50000 on the x axis and around).

The crs are equal in both objects and the coordinates are in the same range. Why is this? What am I doing wrong?

Here is my code

```<code>   import rasterio as rast
   import rasterio.plot as rsplot
   import geopandas as gpd
   src=rast.open("OSMap.tif")
   data=gpd.read_file("Pumps.shp")
   fig,ax=plt.subplots()
   rsplot.show(src,ax=ax)
   data.plot(ax=ax)
   plt.show()
</code>```

This is the result of calling src.bounds:

BoundingBox(left=528765.0, bottom=180466.0, right=529934.0, top=181519.0)

This is the result of data.bounds

(528765.0, 180466.0, 529934.0, 181519.0)

This is crs of both:

CRS({'lon_0': -2, 'y_0': -100000, 'k': 0.9996012717, 'lat_0': 49, 'proj': 'tmerc', 'wktext': True, 'datum': 'OSGB36', 'no_defs': True, 'x_0': 400000, 'units': 'm'})

答: Use matplotlib imshow instead of rasterio show. Pass the bounds of raster as "extent" parameter of imshow.</p>

Body:
I am trying to plot the Pumps.shp data on top of the OSMap.tif file from this website on the same figure.

I tried using rasterio.plot() and geopandas.plot() methods, with matplotlibs subplots.

The problem is that the plots don't match, the raster file gets plotted in the range(0,1000) for both axis and the shp gets plotted in the actual coordinates range(around 50000 on the x axis and around).

The crs are equal in both objects and the coordinates are in the same range. Why is this? What am I doing wrong?

Here is my code

   import rasterio as rast
   import rasterio.plot as rsplot
   import geopandas as gpd
   src=rast.open("OSMap.tif")
   data=gpd.read_file("Pumps.shp")
   fig,ax=plt.subplots()
   rsplot.show(src,ax=ax)
   data.plot(ax=ax)
   plt.show()

This is the result of calling src.bounds:

BoundingBox(left=528765.0, bottom=180466.0, right=529934.0, top=181519.0)

This is the result of data.bounds

(528765.0, 180466.0, 529934.0, 181519.0)

This is crs of both:

CRS({'lon_0': -2, 'y_0': -100000, 'k': 0.9996012717, 'lat_0': 49, 'proj': 'tmerc', 'wktext': True, 'datum': 'OSGB36', 'no_defs': True, 'x_0': 400000, 'units': 'm'})


问:
Generating random integers in TensorFlow
I would like to generate random integers in TensorFlow but I don't which command I should use. In particular, I would like to generate from a uniform random variable which takes values in {1, 2, 3, 4}. I have tried to look among the distributions included in tensorflow_probability but I didn't find it.

Thanks in advance for your help.

答:
For simple integers from uniform distribution you could use tf.random.uniform.

In order to get the specified range and integers you should specify the minval, maxval and dtype parameters. So in your case:

For Tensorflow 2.0 and above:

print(tf.random.uniform(shape=(), minval=1, maxval=5, dtype=tf.int32)
```
<p>For Tensorflow 1.15 and below:</p>
<pre class="lang-py prettyprint-override"><code>with tf.Session() as sess:
    random_int = tf.random.uniform(shape=(), minval=1, maxval=5, dtype=tf.int32)
    print(sess.run(random_int))
</code>```

Note that the actual maximum value will be maxval-1.

Body:
For simple integers from uniform distribution you could use tf.random.uniform.

In order to get the specified range and integers you should specify the minval, maxval and dtype parameters. So in your case:

For Tensorflow 2.0 and above:

print(tf.random.uniform(shape=(), minval=1, maxval=5, dtype=tf.int32)

For Tensorflow 1.15 and below:

with tf.Session() as sess:
    random_int = tf.random.uniform(shape=(), minval=1, maxval=5, dtype=tf.int32)
    print(sess.run(random_int))

Note that the actual maximum value will be maxval-1.


问:
ASP.NET MVC 5 Core Identity CompanyID foreign key on dbo.AspNetUsers table
I've got an MVC 5 app that uses Core Identity on a SQL server database. On the user registration view, I want to add a foreign key dropdown for the Company that the user is assigned to. It is a required field and a user can only be assigned to one company.

AspNetUsers

Company Table

```<code>public class ApplicationUser : IdentityUser
{
    ....
    public int? CompanyID { get; set; }

  //  [ForeignKey("CompanyId")]
  //  public virtual Company UserCompany { get; set; }
}
</code>```

I have added the CompanyID to the RegisterViewModel under the AccountViewModels.cs

```<code>public class RegisterViewModel
{
    ....

    [Required]
    [Display(Name = "Company")]
    public int CompanyID { get; set; }
</code>```

Then I have added the following to the AccountController:

```<code>    using System;
    using System.Globalization;
    using System.Linq;
    using System.Security.Claims;
    using System.Threading.Tasks;
    using System.Web;
    using System.Web.Mvc;
    using Microsoft.AspNet.Identity;
    using Microsoft.AspNet.Identity.Owin;
    using Microsoft.Owin.Security;
    using EMS.Models;

    namespace EMS.Controllers
    {
       // [Authorize]
        public class AccountController : Controller
        {
    private ApplicationSignInManager _signInManager;
    private ApplicationUserManager _userManager;
    private ApplicationDbContext context;
    **private EMSEntities db = new EMSEntities();**

    public AccountController()
    {
        context = new ApplicationDbContext();
    }

    //
    // GET: /Account/Register
    [AllowAnonymous]
    public ActionResult Register()
    {
        **ViewBag.Company = new SelectList(db.Companies.ToList(), "ID", "CompanyName");**
        ViewBag.Name = new SelectList(context.Roles.ToList(), "Name", "Name");
        return View();
    }

    //
    // POST: /Account/Register
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegisterViewModel model, ApplicationUser applicationUser)
    {
        if (ModelState.IsValid)
        {
            **ViewBag.Company = new SelectList(db.Companies.ToList(), "ID", "CompanyName", model.CompanyID);**
            var user = new ApplicationUser { UserName = model.Email, Email = model.Email, **CompanyID = model.CompanyID** };
            var result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);

                // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771
                // Send an email with this link
                // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");
                await this.UserManager.AddToRoleAsync(user.Id, model.Name);
                return RedirectToAction("Index", "Home");
            }
            AddErrors(result);
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

    // New Methods

        [AllowAnonymous]
        [HttpGet]
        public ActionResult RegisterRole()
    {
        ViewBag.Name = new SelectList(context.Roles.ToList(), "Name", "Name");
        ViewBag.UserName = new SelectList(context.Users.ToList(), "UserName", "UserName");
        return View();
    }
</code>```

And then finally I have added the dropdown to the Register view:

```<code><div class="form-group">
    @Html.Label("Company", new { @class = "col-md-2 control-label" })
    <div class="col-md-10">
        @Html.DropDownList("CompanyID", null, htmlAttributes: new { @class = "form-control" })
    </div>
</div>
</code>```

When running the app and trying to register a new user, I get the following error:

Register user issue

When trying to login, I get the same error on a different line:

Server Error in '/' Application. The model backing the
  'ApplicationDbContext' context has changed since the database was
  created. Consider using Code First Migrations to update the database
  (http://go.microsoft.com/fwlink/?LinkId=238269).

What is the problem?

答:
Try in Package Manager Console:

```<code>Enable-Migrations -ContextTypeName 'Applicationname.Data.ApplicationDbContext'
add-migration 'migrationsname'
update-database
</code>```

It simply just needs to update the database. This is because Code First created a database before enabling migrations so you will need an initail migration.

Body:
I've got an MVC 5 app that uses Core Identity on a SQL server database. On the user registration view, I want to add a foreign key dropdown for the Company that the user is assigned to. It is a required field and a user can only be assigned to one company.

AspNetUsers

Company Table

public class ApplicationUser : IdentityUser
{
    ....
    public int? CompanyID { get; set; }

  //  [ForeignKey("CompanyId")]
  //  public virtual Company UserCompany { get; set; }
}

I have added the CompanyID to the RegisterViewModel under the AccountViewModels.cs

public class RegisterViewModel
{
    ....

    [Required]
    [Display(Name = "Company")]
    public int CompanyID { get; set; }

Then I have added the following to the AccountController:

    using System;
    using System.Globalization;
    using System.Linq;
    using System.Security.Claims;
    using System.Threading.Tasks;
    using System.Web;
    using System.Web.Mvc;
    using Microsoft.AspNet.Identity;
    using Microsoft.AspNet.Identity.Owin;
    using Microsoft.Owin.Security;
    using EMS.Models;

    namespace EMS.Controllers
    {
       // [Authorize]
        public class AccountController : Controller
        {
    private ApplicationSignInManager _signInManager;
    private ApplicationUserManager _userManager;
    private ApplicationDbContext context;
    **private EMSEntities db = new EMSEntities();**

    public AccountController()
    {
        context = new ApplicationDbContext();
    }

    //
    // GET: /Account/Register
    [AllowAnonymous]
    public ActionResult Register()
    {
        **ViewBag.Company = new SelectList(db.Companies.ToList(), "ID", "CompanyName");**
        ViewBag.Name = new SelectList(context.Roles.ToList(), "Name", "Name");
        return View();
    }

    //
    // POST: /Account/Register
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegisterViewModel model, ApplicationUser applicationUser)
    {
        if (ModelState.IsValid)
        {
            **ViewBag.Company = new SelectList(db.Companies.ToList(), "ID", "CompanyName", model.CompanyID);**
            var user = new ApplicationUser { UserName = model.Email, Email = model.Email, **CompanyID = model.CompanyID** };
            var result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);

                // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771
                // Send an email with this link
                // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking here");
                await this.UserManager.AddToRoleAsync(user.Id, model.Name);
                return RedirectToAction("Index", "Home");
            }
            AddErrors(result);
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

    // New Methods

        [AllowAnonymous]
        [HttpGet]
        public ActionResult RegisterRole()
    {
        ViewBag.Name = new SelectList(context.Roles.ToList(), "Name", "Name");
        ViewBag.UserName = new SelectList(context.Users.ToList(), "UserName", "UserName");
        return View();
    }

And then finally I have added the dropdown to the Register view:

    @Html.Label("Company", new { @class = "col-md-2 control-label" })

        @Html.DropDownList("CompanyID", null, htmlAttributes: new { @class = "form-control" })

When running the app and trying to register a new user, I get the following error:

Register user issue

When trying to login, I get the same error on a different line:

Server Error in '/' Application. The model backing the
  'ApplicationDbContext' context has changed since the database was
  created. Consider using Code First Migrations to update the database
  (http://go.microsoft.com/fwlink/?LinkId=238269).

What is the problem?

Body:
Try in Package Manager Console:

Enable-Migrations -ContextTypeName 'Applicationname.Data.ApplicationDbContext'
add-migration 'migrationsname'
update-database

It simply just needs to update the database. This is because Code First created a database before enabling migrations so you will need an initail migration.


问:
Set the size of the boxes for Ipython wigets
I'm woring on a simple interface where I have a text box and an interactive plot.
The idea of the text box in to used for some logs.

I'm able to get the plot and update the text from the same function, but my issue is that the text box is to large, I need to change its width.

Below is my current code and a screenshot of the result:

```<code>from IPython.display import display
from ipywidgets import Button, Layout, Textarea, HBox, VBox
import numpy as np
from ipywidgets import interact, interactive, fixed, interact_manual
import plotly.graph_objects as go

def f(x):

    x = np.arange(x)
    t1.value = "".join([str(c) for c in x.tolist()] )
    fig = go.Figure(data=go.Scatter(x=x, y=x**2))
    fig.show()

x = np.linspace(10,100,1)

interactive_plot = interactive(f, x=(1, 20))
l = Layout(flex='0 1 auto', height='400px', min_height='40px', width='10')
t1 = Textarea(value='TA: height=40px', layout=l)
</code>```

答:
The layout attribute exposes CSS properties like height, width, border, margin of the ipywidgets. This allows one to control how the ipywidgets are laid out. It is possible to control the width and height of the textbox by tweaking the values in the Layout snippet below as required. The parameters accept values in pixels(px) or percentage of available space(%) or even 'auto' to allow these values to be set automatically. You can find an example in the docs. I've set the height as 30px and width as 'auto' to automatically set a width:

```<code>l = Layout(flex='0 1 auto', height='30px', min_height='40px', width='auto')
</code>```

Output:

Body:
I'm woring on a simple interface where I have a text box and an interactive plot.
The idea of the text box in to used for some logs.

I'm able to get the plot and update the text from the same function, but my issue is that the text box is to large, I need to change its width.

Below is my current code and a screenshot of the result:

from IPython.display import display
from ipywidgets import Button, Layout, Textarea, HBox, VBox
import numpy as np
from ipywidgets import interact, interactive, fixed, interact_manual
import plotly.graph_objects as go

def f(x):

    x = np.arange(x)
    t1.value = "".join([str(c) for c in x.tolist()] )
    fig = go.Figure(data=go.Scatter(x=x, y=x**2))
    fig.show()

x = np.linspace(10,100,1)

interactive_plot = interactive(f, x=(1, 20))
l = Layout(flex='0 1 auto', height='400px', min_height='40px', width='10')
t1 = Textarea(value='TA: height=40px', layout=l)

Body:
The layout attribute exposes CSS properties like height, width, border, margin of the ipywidgets. This allows one to control how the ipywidgets are laid out. It is possible to control the width and height of the textbox by tweaking the values in the Layout snippet below as required. The parameters accept values in pixels(px) or percentage of available space(%) or even 'auto' to allow these values to be set automatically. You can find an example in the docs. I've set the height as 30px and width as 'auto' to automatically set a width:

l = Layout(flex='0 1 auto', height='30px', min_height='40px', width='auto')

Output:


问:
HTML/CSS Button Hover shifting everything else away?
If I hover over my buttons they shift(?) other elements.

as you can see I already tried to compensate the +4 pixels from the border by subtracting them from the height and the width but the problem remains.

I don't want this. I want it to change appearance without any shifting.

Here a video to visualize my problem

Thank you in advance :)

Here the CSS and HTML

HTML:

```<code><body>
  <nav>
    <img class="logo" src="images/logo-bookmark.svg" alt="Logo nav">
    <div class="navElements">
      <a href="#" class="nav-links">Features</a>
      <a href="#" class="nav-links">Pricing</a>
      <a href="#" class="nav-links">Contact</a>
      <a href="#" class="nav-logo-btn">Login</a>
    </div>
  </nav>

  <section class="header">
    <div class="header-left">
      <h1 class="header-heading">A Simple Bookmark Manager</h1>
      <p class="header-text"> A clean and simple interface to organize your favourite websites. Open a new
        browser tab and see your sites load instantly. Try it for free.</p>
      <a href="#" class="btn-1">Get it on Chrome</a>
      <a href="#" class="btn-2">Get it on Firefox</a>
    </div>
    <img class="header-img" src="images\illustration-hero.svg" alt="Hero image">
</code>```

Login Button:

```<code>.nav-logo-btn {
  text-decoration: none;
  color: white;
  background-color: var(--SoftRed);
  padding: 10px 32px;
  border-radius: 5px;
  text-transform: uppercase;
  font-weight: 500;
  font-family: "Rubik";
  font-size: 12px;
  letter-spacing: 2px;
}

.nav-logo-btn:hover {
  color: var(--SoftRed);
  background-color: white;
  border: solid 2px;
  padding: 8px 30px;
  transition: all 0.3s;
}
</code>```

Chrome/Firefox Buttons:

```<code>.btn-1, .btn-2 {
  display: inline-block;
  text-decoration: none;
  border-radius: 5px;
  text-align: center;
  line-height: 48px;
  height: 48px;
  width: 165px;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.2s;
  position: relative;
}

.btn-1:hover, .btn-2:hover {
  background-color: white;
  border: solid 2px;
  height: 44px;
  width: 161px;
}

.btn-1 {
  background-color: var(--SoftBlue);
  color: white;

}

.btn-2 {
  background-color: #f7f7f7;
  color: #606068;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.1);
  left: 50px;
}

.btn-1:hover {
  color: var(--SoftBlue);
}

.btn-2:hover {
  color: #606068;
}

</code>```

答: You should add backface-visibility: hidden; on your header class and it will work

Body:
If I hover over my buttons they shift(?) other elements.

as you can see I already tried to compensate the +4 pixels from the border by subtracting them from the height and the width but the problem remains.

I don't want this. I want it to change appearance without any shifting.

Here a video to visualize my problem

Thank you in advance :)

Here the CSS and HTML

HTML:

      Features
      Pricing
      Contact
      Login

A Simple Bookmark Manager

 A clean and simple interface to organize your favourite websites. Open a new
        browser tab and see your sites load instantly. Try it for free.

      Get it on Chrome
      Get it on Firefox

Login Button:

.nav-logo-btn {
  text-decoration: none;
  color: white;
  background-color: var(--SoftRed);
  padding: 10px 32px;
  border-radius: 5px;
  text-transform: uppercase;
  font-weight: 500;
  font-family: "Rubik";
  font-size: 12px;
  letter-spacing: 2px;
}

.nav-logo-btn:hover {
  color: var(--SoftRed);
  background-color: white;
  border: solid 2px;
  padding: 8px 30px;
  transition: all 0.3s;
}

Chrome/Firefox Buttons:

.btn-1, .btn-2 {
  display: inline-block;
  text-decoration: none;
  border-radius: 5px;
  text-align: center;
  line-height: 48px;
  height: 48px;
  width: 165px;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.2s;
  position: relative;
}

.btn-1:hover, .btn-2:hover {
  background-color: white;
  border: solid 2px;
  height: 44px;
  width: 161px;
}

.btn-1 {
  background-color: var(--SoftBlue);
  color: white;

}

.btn-2 {
  background-color: #f7f7f7;
  color: #606068;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.1);
  left: 50px;
}

.btn-1:hover {
  color: var(--SoftBlue);
}

.btn-2:hover {
  color: #606068;
}


问:
c++ SIGTERM not returning after caught
I am trying to catch SIGTERM in my program, this is the problem.

My program starts and sets ups the listener for the signal SIGTERM. The program then enters a loop which continuously checks a socket file descriptor using select so that it is non blocking.When I send the program TERM through kill the program acknowledges that it receives the signal but that's it no return back to the loop I describe earlier.

The signal handler sets a public variable inside the class so the loop knows to exit. I should mention that in gdb this works but outside of gdb it does not.

Thanks in advance.

```<code>class A
{
    public:
        bool volatile stop;

    void loop();
    {
        while(!stop)
            {
                //check socket
            }
    }
};

A *aptr;

void sigterm_handler(int i)
{
    aptr->stop = true;
}

int main()
{
    A a;
    aptr = &a;
    struct sigaction sa;
    sa.sa_handler = &sigterm_handler;
    sigaction(SIGTERM, &sa, NULL);
    a.stop = false;
    a.loop();
}
</code>```

EDIT: sorry did not finish the code off properly.

答:
You need to make stop "volatile" otherwise the compiler won't actually check it in the loop as it thinks it can't change.</p>

```<code>bool volatile stop;
</code>```

Title: c++ SIGTERM not returning after caught

Body:
I am trying to catch SIGTERM in my program, this is the problem.

My program starts and sets ups the listener for the signal SIGTERM. The program then enters a loop which continuously checks a socket file descriptor using select so that it is non blocking.When I send the program TERM through kill the program acknowledges that it receives the signal but that's it no return back to the loop I describe earlier.

The signal handler sets a public variable inside the class so the loop knows to exit. I should mention that in gdb this works but outside of gdb it does not.

Thanks in advance.

class A
{
    public:
        bool volatile stop;

    void loop();
    {
        while(!stop)
            {
                //check socket
            }
    }
};

A *aptr;

void sigterm_handler(int i)
{
    aptr->stop = true;
}

int main()
{
    A a;
    aptr = &a;
    struct sigaction sa;
    sa.sa_handler = &sigterm_handler;
    sigaction(SIGTERM, &sa, NULL);
    a.stop = false;
    a.loop();
}

EDIT: sorry did not finish the code off properly.

Body:
You need to make stop "volatile" otherwise the compiler won't actually check it in the loop as it thinks it can't change.

bool volatile stop;


问:
node printer.node is not a valid win32 application
I have developed a node API for my angular application, My node application uses node-printer package for printing pdf files generated by node, when i tried to run my application using nodemon i am getting an error

node printer.node is not a valid win32 application

The same application is working on the other machine without any error. both the machines are of X64 bit architecture.

also i have also tried to install node js 32 bit then too i am getting same error.

答:
This worked for me, installing printer as such:</p>

```<code>npm install printer --build-from-source
</code>```

Body:
This worked for me, installing printer as such:

npm install printer --build-from-source


问:
Django Channels: Exception inside application: No handler for message type app_consumer.notification_message
I'm trying to send a notification to the user using websockets, on a particular event.
I have the following model receiver which triggers a websocket method:

@receiver(pre_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, update_fields=None, **kwargs):
    if update_fields:
        if 'pan_number_verified' in update_fields and instance.pan_number_verified is True:
            notification = Notification.objects.create(message='Your PAN Number has been verified...Head on to '
                                                               'creating a campaign right away.', user=instance)
            channel_layer = get_channel_layer()
            async_to_sync(channel_layer.group_send)("notification_%s" % instance.id, {
                "type": "app_consumer.notification_message",
                "message": str(notification.id)
            })
```

<p>Here is my app consumer:</p>

<pre class="lang-py prettyprint-override"><code>class AppConsumer(WebsocketConsumer):
    def connect(self):
        self.room_name = self.scope['url_route']['kwargs']['user_id']
        self.room_group_name = 'notification_%s' % self.room_name
        async_to_sync(self.channel_layer.group_add)(
            self.room_group_name,
            self.channel_name
        )
        self.accept()

    def disconnect(self, close_code):
        async_to_sync(self.channel_layer.group_discard)(
            self.room_group_name,
            self.channel_name
        )

    def receive(self, text_data):
        text_data_json = json.loads(text_data)
        message = text_data_json['message']

        async_to_sync(self.channel_layer.group_send)(
            self.room_group_name,
            {
                'type': 'app_consumer.notification_message',
                'message': message
            }
        )

    def notification_message(self, event):
        message = event['message']

        self.send(text_data=json.dumps({
            'message': message
        }))
</code>```

But I get the following error message:

Exception inside application: No handler for message type app_consumer.notification_message

File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/channels/consumer.py", line 59, in call
      [receive, self.channel_receive], self.dispatch

File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/channels/utils.py", line 51, in await_many_dispatch
      await dispatch(result)

File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/asgiref/sync.py", line 244, in call
      return await asyncio.wait_for(future, timeout=None)

File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/asyncio/tasks.py", line 414, in wait_for
      return await fut

File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/concurrent/futures/thread.py", line 57, in run
      result = self.fn(*self.args, **self.kwargs)

File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/channels/db.py", line 14, in thread_handler
      return super().thread_handler(loop, *args, **kwargs)

File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/asgiref/sync.py", line 277, in thread_handler
      return func(*args, **kwargs)

File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/channels/consumer.py", line 107, in dispatch
      raise ValueError("No handler for message type %s" % message["type"])

No handler for message type app_consumer.notification_message

答:
You issue here is the name of your notification_message handler method.

Channels expects it to be named app_consumer_notification_message.

Channels replaces the . in message types with _ when looking for a message handling method.

(the prefix in the message type is not used for routing just the group name)

Body:
I'm trying to send a notification to the user using websockets, on a particular event.
I have the following model receiver which triggers a websocket method:

@receiver(pre_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, update_fields=None, **kwargs):
    if update_fields:
        if 'pan_number_verified' in update_fields and instance.pan_number_verified is True:
            notification = Notification.objects.create(message='Your PAN Number has been verified...Head on to '
                                                               'creating a campaign right away.', user=instance)
            channel_layer = get_channel_layer()
            async_to_sync(channel_layer.group_send)("notification_%s" % instance.id, {
                "type": "app_consumer.notification_message",
                "message": str(notification.id)
            })

Here is my app consumer:

class AppConsumer(WebsocketConsumer):
    def connect(self):
        self.room_name = self.scope['url_route']['kwargs']['user_id']
        self.room_group_name = 'notification_%s' % self.room_name
        async_to_sync(self.channel_layer.group_add)(
            self.room_group_name,
            self.channel_name
        )
        self.accept()

    def disconnect(self, close_code):
        async_to_sync(self.channel_layer.group_discard)(
            self.room_group_name,
            self.channel_name
        )

    def receive(self, text_data):
        text_data_json = json.loads(text_data)
        message = text_data_json['message']

        async_to_sync(self.channel_layer.group_send)(
            self.room_group_name,
            {
                'type': 'app_consumer.notification_message',
                'message': message
            }
        )

    def notification_message(self, event):
        message = event['message']

        self.send(text_data=json.dumps({
            'message': message
        }))

But I get the following error message:

Exception inside application: No handler for message type app_consumer.notification_message

File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/channels/consumer.py", line 59, in call
      [receive, self.channel_receive], self.dispatch

File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/channels/utils.py", line 51, in await_many_dispatch
      await dispatch(result)

File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/asgiref/sync.py", line 244, in call
      return await asyncio.wait_for(future, timeout=None)

File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/asyncio/tasks.py", line 414, in wait_for
      return await fut

File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/concurrent/futures/thread.py", line 57, in run
      result = self.fn(*self.args, **self.kwargs)

File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/channels/db.py", line 14, in thread_handler
      return super().thread_handler(loop, *args, **kwargs)

File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/asgiref/sync.py", line 277, in thread_handler
      return func(*args, **kwargs)

File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/channels/consumer.py", line 107, in dispatch
      raise ValueError("No handler for message type %s" % message["type"])

No handler for message type app_consumer.notification_message


问:
copy and paste special with VBA in excel
I wrote this code and it keeps giving me an error that the size of the copy area and the paste area are not the same.
but if I just use the copy-paste method, it works perfectly. could you pls help me out.</p>

```<code>Sub copy()
eRow = Sheet5.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
Sheet4.Range("a4", "d23").copy
Sheet5.Cells(eRow, 1).PasteSpecial (xlPasteValues)
End Sub
</code>```

答:
Move values one by one with a value transfer. As implied in the name, a value transfer does not carry over formats.

This just copies the 2 individual cells A4 & D23

```<code>Sub copy_me()

Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("Sheet1")
Dim lr As Long

lr = ws.Range("A" & ws.Rows.Count).End(xlUp).Offset(1).Row

ws.Range("A" & lr).Value = ws.Range("A4").Value
ws.Range("D" & lr).Value = ws.Range("D23").Value

End Sub
</code>```

If you meant to grab the entire range A4:D23 then

```<code>ws.Range("A4:D23").Copy
ws.Range("A" & lr).PasteSpecial xlPasteValues
</code>```

OR

```<code>ws.Range("A" & lr).Resize(20, 4).Value = ws.Range("A4:D23").Value
</code>```

Body:
I wrote this code and it keeps giving me an error that the size of the copy area and the paste area are not the same.
but if I just use the copy-paste method, it works perfectly. could you pls help me out.

Sub copy()
eRow = Sheet5.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
Sheet4.Range("a4", "d23").copy
Sheet5.Cells(eRow, 1).PasteSpecial (xlPasteValues)
End Sub

Body:
Move values one by one with a value transfer. As implied in the name, a value transfer does not carry over formats.

This just copies the 2 individual cells A4 & D23

Sub copy_me()

Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("Sheet1")
Dim lr As Long

lr = ws.Range("A" & ws.Rows.Count).End(xlUp).Offset(1).Row

ws.Range("A" & lr).Value = ws.Range("A4").Value
ws.Range("D" & lr).Value = ws.Range("D23").Value

End Sub

If you meant to grab the entire range A4:D23 then

ws.Range("A4:D23").Copy
ws.Range("A" & lr).PasteSpecial xlPasteValues

OR

ws.Range("A" & lr).Resize(20, 4).Value = ws.Range("A4:D23").Value


问:
How would i leave out the name jones but display people with the same deptno
```<code>SQL> select empno, ename, deptno
  2  from empcopy
  3  where deptno =
  4      (select deptno
  5       from empcopy
  6       where ename like 'JONES');

 EMPNO ENAME          DEPTNO
------ ---------- ----------
  7369 SMITH              20
  7566 JONES              20
  7788 SCOTT              20
  7876 ADAMS              20
  7902 FORD               20
</code>```

答:
You can do it this way:</p>

```<code>select
empno, ename, deptno
from empcopy
where DEPTNO in (select DEPTNO  from empcopy where ename ='JONES')
and ename <>'JONES'
</code>```

Body:
You can do it this way:

select
empno, ename, deptno
from empcopy
where DEPTNO in (select DEPTNO  from empcopy where ename ='JONES')
and ename <>'JONES'


问:
KeePass URL override for opening Cisco AnyConnect VPN connection
I'm using KeePass 2 for storing my passwords. I have to use several different VPN clients for connecting to our customers. I'm looking for URL override to allow automatic connection to given VPN server.  </p>

答:
I’m finally succeeded with this definition:

```<code>cmd://cmd /c "START /wait taskkill /F /IM vpnui.exe && "{ENV_PROGRAMFILES_X86}\Cisco\Cisco AnyConnect Secure Mobility Client\vpncli.exe" disconnect && (echo connect {URL:RMVSCM}&&echo {USERNAME}&&echo {PASSWORD})>c:\Windows\Temp\vpn.txt && "{ENV_PROGRAMFILES_X86}\Cisco\Cisco AnyConnect Secure Mobility Client\vpncli.exe" -s < c:\Windows\Temp\vpn.txt && del c:\Windows\Temp\vpn.txt && "{ENV_PROGRAMFILES_X86}\Cisco\Cisco AnyConnect Secure Mobility Client\vpnui.exe" "
</code>```

It basically creates a temporary file with vpn address, login and password and pass this file to vpncli. However vpnui must be closed first and I prefer to start it afterwards (to be able to comfortably close connection, when I don’t need it anymore).

Hope it helps someone :-)

Body:
I’m finally succeeded with this definition:

cmd://cmd /c "START /wait taskkill /F /IM vpnui.exe && "{ENV_PROGRAMFILES_X86}\Cisco\Cisco AnyConnect Secure Mobility Client\vpncli.exe" disconnect && (echo connect {URL:RMVSCM}&&echo {USERNAME}&&echo {PASSWORD})>c:\Windows\Temp\vpn.txt && "{ENV_PROGRAMFILES_X86}\Cisco\Cisco AnyConnect Secure Mobility Client\vpncli.exe" -s < c:\Windows\Temp\vpn.txt && del c:\Windows\Temp\vpn.txt && "{ENV_PROGRAMFILES_X86}\Cisco\Cisco AnyConnect Secure Mobility Client\vpnui.exe" "

It basically creates a temporary file with vpn address, login and password and pass this file to vpncli. However vpnui must be closed first and I prefer to start it afterwards (to be able to comfortably close connection, when I don’t need it anymore).

Hope it helps someone :-)


问:
Variables within app.config/web.config
Is it is possible to do something like the following in the app.config or web.config files?

```<code><appSettings>
 <add key="MyBaseDir" value="C:\MyBase" />
 <add key="Dir1" value="[MyBaseDir]\Dir1"/>
 <add key="Dir2" value="[MyBaseDir]\Dir2"/>
</appSettings>
</code>```

I then want to access Dir2 in my code by simply saying:

```<code> ConfigurationManager.AppSettings["Dir2"]
</code>```

This will help me when I install my application in different servers and locations wherein I will only have to change ONE entry in my entire app.config.
(I know I can manage all the concatenation in code, but I prefer it this way).

答: For rolling out products where we need to configure a lot of items with similar values, we use small console apps that read the XML and update based on the parameters passed in.  These are then called by the installer after it has asked the user for the required information.</p>

OwnerDisplayName: DeeStackOverflow

ContentLicense: CC BY-SA 2.5

Title: Variables within app.config/web.config

Body:
Is it is possible to do something like the following in the app.config or web.config files?

<appSettings>
 <add key="MyBaseDir" value="C:\MyBase" />
 <add key="Dir1" value="[MyBaseDir]\Dir1"/>
 <add key="Dir2" value="[MyBaseDir]\Dir2"/>
</appSettings>

I then want to access Dir2 in my code by simply saying:

 ConfigurationManager.AppSettings["Dir2"]

This will help me when I install my application in different servers and locations wherein I will only have to change ONE entry in my entire app.config.
(I know I can manage all the concatenation in code, but I prefer it this way).

LastEditorDisplayName: LFSR Consulting

OwnerDisplayName: ck


问:
escaping special character in groovy
I want to run my command in background.And I am trying this in jenkins pipeline
This is my command

sh "./node_modules/.bin/selenium-standalone start  \&"

But when I run this command & gets single quote because of which the command fails.
OUTPUT :  ./node_modules/.bin/selenium-standalone start '&'

Can anyone suggest how I should escape the & in groovy so I just get & without single quote.

答:
This won't work that easily, first because & is a command for job control in the interactive shell, and also because of how process trees work in Linux.

To make a long story short, if you need to start a command in background, you should use daemonize:

```<code>sh label: "starting selenium in the background",
    script: "/usr/local/bin/daemonize ./node_modules/.bin/selenium-standalone start"
</code>```

Title: escaping special character in groovy

Body:
This won't work that easily, first because & is a command for job control in the interactive shell, and also because of how process trees work in Linux.

To make a long story short, if you need to start a command in background, you should use daemonize:

sh label: "starting selenium in the background",
    script: "/usr/local/bin/daemonize ./node_modules/.bin/selenium-standalone start"


问:
Is there a way to create,edit, or list rubrics?
Is there a way to create,edit, or list rubrics?

I see in the documentation I can create coursework, but one of the key pieces of coursework is the rubric.

答: Rubrics have not been added to the CourseWork API however there is an issue in the Google Issue Tracker here.</p>


问:
Sending data through serial using jQuery slider
This is my first question on stack overflow so I'd like to say hello to everyone. My question today is as follows...

I am trying to use a jQuery UI slider to send values over TCP/IP to Arduino's serial port.

I have the communication part pretty much done (TCP and serial). The problem is that whenever the user moves the slider, every value along the way is sent one after another very rapidly. I'd like to delay the slider so that it sends those values with a 100ms delay between every step.

I've tried to use 'setInterval' and 'clearInterval' with no success.  Here is the code:

```<code>$(document).ready(function() {

    $( "#mySlider" ).slider({
        range: "min",
        min: 0,
        max: 180,
        value: 90,
        slide: function( event, ui ) {

        delayPan(ui.value);

        }
});

$( "#total" ).val( $( "#mySlider" ).slider( "value" ) );

});

var timeOut;

function delayPan(vals) {

    $( "#total" ).val("$" +  vals );

    //the part below sends values to another PHP file in order to then send it using TCP/IP

    timeOut = setInterval(function()
    {

        $.get("insert_commands.php", {command: 39, parameter: 0, value: vals, number: 0},
        function(command,parameter,value,number){}, "json");

    }, 100);

    clearInterval(timeOut);

}
</code>```

And for more clarity, here is the slider's HTML on my index.php website:

```<code><label for="total">ANGLE:</label>
<input type="text" id="total" style="border:0; color:#fa4b2a; font-weight:bold;">
</p>
<div id="mySlider"></div>
</code>```

I am not sure how to go about solving this- I am pretty new to javascript/jQuery. I could just delay the reception on Arduino or TCP socket but there are other buttons on the main website with different delays set so I need to do it in jQuery if possible.

I'd appreciate any advice.

Thank you
Rob

答:
you have two solutions to this

1 don't call delay function from slider just make the interval always sending the current value of the slider every 100ms, also  remove the  clearInterval(timeOut);

2  make timeDelta to limit the Generating of the Get Requests

like this
https://codepen.io/vkv88/pen/PoqGzJE?editors=1000

Body:
This is my first question on stack overflow so I'd like to say hello to everyone. My question today is as follows...

I am trying to use a jQuery UI slider to send values over TCP/IP to Arduino's serial port.

I have the communication part pretty much done (TCP and serial). The problem is that whenever the user moves the slider, every value along the way is sent one after another very rapidly. I'd like to delay the slider so that it sends those values with a 100ms delay between every step.

I've tried to use 'setInterval' and 'clearInterval' with no success.  Here is the code:

$(document).ready(function() {

    $( "#mySlider" ).slider({
        range: "min",
        min: 0,
        max: 180,
        value: 90,
        slide: function( event, ui ) {

        delayPan(ui.value);

        }
});

$( "#total" ).val( $( "#mySlider" ).slider( "value" ) );

});

var timeOut;

function delayPan(vals) {

    $( "#total" ).val("$" +  vals );

    //the part below sends values to another PHP file in order to then send it using TCP/IP

    timeOut = setInterval(function()
    {

        $.get("insert_commands.php", {command: 39, parameter: 0, value: vals, number: 0},
        function(command,parameter,value,number){}, "json");

    }, 100);

    clearInterval(timeOut);

}

And for more clarity, here is the slider's HTML on my index.php website:

ANGLE:
<input type="text" id="total" style="border:0; color:#fa4b2a; font-weight:bold;">

I am not sure how to go about solving this- I am pretty new to javascript/jQuery. I could just delay the reception on Arduino or TCP socket but there are other buttons on the main website with different delays set so I need to do it in jQuery if possible.

I'd appreciate any advice.

Thank you
Rob


问:
Number of rows with specified number of null columns
How to get information how many rows in a table have particular number of nulls in it?

I want to get something like this:

```<code>Number of nulls | Number of rows
        0       |      10
        1       |       4
        2       |      11
</code>```

Motivation:

I need this for data mining purposes. If for example I have an observation that has in almost all columns null value then I need to get rid of this observation, but there can be also a situation where many observations have small value of nulls which is acceptable.

答:
With just SQL, you'll have to resort to unpleasant code, something like:

```<code>SELECT CASE WHEN column1 IS NULL THEN 1 ELSE 0 END
       + CASE WHEN column2 IS NULL THEN 1 ELSE 0 END
       + ... AS num_nulls,
       COUNT(*) as num_rows
FROM table
GROUP BY num_nulls;
</code>```

Also note that not all SQL dialects support referencing a calculated column by alas in the GROUP BY clause, so you might end up with a much uglier query. Needless to say, you'll also have to make a different query for each table. You could of course generate the query using some INFORMATION_SCHEMA voodoo...

Body:
How to get information how many rows in a table have particular number of nulls in it?

I want to get something like this:

Number of nulls | Number of rows
        0       |      10
        1       |       4
        2       |      11

Motivation:

I need this for data mining purposes. If for example I have an observation that has in almost all columns null value then I need to get rid of this observation, but there can be also a situation where many observations have small value of nulls which is acceptable.

Body:
With just SQL, you'll have to resort to unpleasant code, something like:

SELECT CASE WHEN column1 IS NULL THEN 1 ELSE 0 END
       + CASE WHEN column2 IS NULL THEN 1 ELSE 0 END
       + ... AS num_nulls,
       COUNT(*) as num_rows
FROM table
GROUP BY num_nulls;

Also note that not all SQL dialects support referencing a calculated column by alas in the GROUP BY clause, so you might end up with a much uglier query. Needless to say, you'll also have to make a different query for each table. You could of course generate the query using some INFORMATION_SCHEMA voodoo...