qid int64 469 74.7M | question stringlengths 36 37.8k | date stringlengths 10 10 | metadata list | response_j stringlengths 5 31.5k | response_k stringlengths 10 31.6k |
|---|---|---|---|---|---|
405,282 | I am trying to write a life simulation in python with a variety of animals. It is impossible to name each instance of the classes I am going to use because I have no way of knowing how many there will be.
So, my question:
How can I automatically give a name to an object?
I was thinking of creating a "Herd" class whi... | 2009/01/01 | [
"https://Stackoverflow.com/questions/405282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | you could make an 'animal' class with a name attribute.
Or
you could programmically define the class like so:
```
from new import classobj
my_class=classobj('Foo',(object,),{})
```
Found this:
<http://www.gamedev.net/community/forums/topic.asp?topic_id=445037> | Any instance could have a name attribute. So it sounds like you may be asking how to dynamically name a *class*, not an *instance*. If that's the case, you can explicitly set the \_\_name\_\_ attribute of a class, or better yet just create the class with the builtin [type](http://docs.python.org/library/functions.html#... |
405,282 | I am trying to write a life simulation in python with a variety of animals. It is impossible to name each instance of the classes I am going to use because I have no way of knowing how many there will be.
So, my question:
How can I automatically give a name to an object?
I was thinking of creating a "Herd" class whi... | 2009/01/01 | [
"https://Stackoverflow.com/questions/405282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Like this?
```
class Animal( object ):
pass # lots of details omitted
herd= [ Animal() for i in range(10000) ]
```
At this point, herd will have 10,000 distinct instances of the `Animal` class. | If you need a way to refer to them individually, it's relatively common to have the class give each instance a unique identifier on initialization:
```
>>> import itertools
>>> class Animal(object):
... id_iter = itertools.count(1)
... def __init__(self):
... self.id = self.id_iter.next()
...
>>> ... |
405,282 | I am trying to write a life simulation in python with a variety of animals. It is impossible to name each instance of the classes I am going to use because I have no way of knowing how many there will be.
So, my question:
How can I automatically give a name to an object?
I was thinking of creating a "Herd" class whi... | 2009/01/01 | [
"https://Stackoverflow.com/questions/405282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Like this?
```
class Animal( object ):
pass # lots of details omitted
herd= [ Animal() for i in range(10000) ]
```
At this point, herd will have 10,000 distinct instances of the `Animal` class. | Any instance could have a name attribute. So it sounds like you may be asking how to dynamically name a *class*, not an *instance*. If that's the case, you can explicitly set the \_\_name\_\_ attribute of a class, or better yet just create the class with the builtin [type](http://docs.python.org/library/functions.html#... |
405,282 | I am trying to write a life simulation in python with a variety of animals. It is impossible to name each instance of the classes I am going to use because I have no way of knowing how many there will be.
So, my question:
How can I automatically give a name to an object?
I was thinking of creating a "Herd" class whi... | 2009/01/01 | [
"https://Stackoverflow.com/questions/405282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | If you need a way to refer to them individually, it's relatively common to have the class give each instance a unique identifier on initialization:
```
>>> import itertools
>>> class Animal(object):
... id_iter = itertools.count(1)
... def __init__(self):
... self.id = self.id_iter.next()
...
>>> ... | Any instance could have a name attribute. So it sounds like you may be asking how to dynamically name a *class*, not an *instance*. If that's the case, you can explicitly set the \_\_name\_\_ attribute of a class, or better yet just create the class with the builtin [type](http://docs.python.org/library/functions.html#... |
57,814,535 | I figured out this is a popular question, but still I couldn't find a solution for that.
I'm trying to run a simple repo [Here](https://github.com/swathikirans/violence-recognition-pytorch) which uses `PyTorch`. Although I just upgraded my Pytorch to the latest CUDA version from pytorch.org (`1.2.0`), it still throws ... | 2019/09/06 | [
"https://Stackoverflow.com/questions/57814535",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3204706/"
] | try this:
```
conda install pytorch torchvision cudatoolkit=10.2 -c pytorch
``` | Uninstalling the packages and reinstalling it with pip instead solved it for me.
1.`conda remove pytorch torchvision torchaudio cudatoolkit`
2.`pip3 install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu116` |
57,814,535 | I figured out this is a popular question, but still I couldn't find a solution for that.
I'm trying to run a simple repo [Here](https://github.com/swathikirans/violence-recognition-pytorch) which uses `PyTorch`. Although I just upgraded my Pytorch to the latest CUDA version from pytorch.org (`1.2.0`), it still throws ... | 2019/09/06 | [
"https://Stackoverflow.com/questions/57814535",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3204706/"
] | you dont have to install it via anaconda, you could install cuda from their [website](https://developer.nvidia.com/cuda-downloads). after install ends open a new terminal and check your cuda version with:
```
>>> nvcc --version
nvcc: NVIDIA (R) Cuda compiler driver
Copyright (c) 2005-2021 NVIDIA Corporation
Built on T... | First activate your environment. Replace <name> with your environment name.
```
conda activate <name>
```
Then see cuda version in your machine. To see cuda version:
```
nvcc --version
```
Now for CUDA 10.1 use:
```
conda install pytorch==1.4.0 torchvision==0.5.0 cudatoolkit=10.1 -c pytorch
```
For CUDA 10.0 u... |
57,814,535 | I figured out this is a popular question, but still I couldn't find a solution for that.
I'm trying to run a simple repo [Here](https://github.com/swathikirans/violence-recognition-pytorch) which uses `PyTorch`. Although I just upgraded my Pytorch to the latest CUDA version from pytorch.org (`1.2.0`), it still throws ... | 2019/09/06 | [
"https://Stackoverflow.com/questions/57814535",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3204706/"
] | First activate your environment. Replace <name> with your environment name.
```
conda activate <name>
```
Then see cuda version in your machine. To see cuda version:
```
nvcc --version
```
Now for CUDA 10.1 use:
```
conda install pytorch==1.4.0 torchvision==0.5.0 cudatoolkit=10.1 -c pytorch
```
For CUDA 10.0 u... | Uninstalling the packages and reinstalling it with pip instead solved it for me.
1.`conda remove pytorch torchvision torchaudio cudatoolkit`
2.`pip3 install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu116` |
57,814,535 | I figured out this is a popular question, but still I couldn't find a solution for that.
I'm trying to run a simple repo [Here](https://github.com/swathikirans/violence-recognition-pytorch) which uses `PyTorch`. Although I just upgraded my Pytorch to the latest CUDA version from pytorch.org (`1.2.0`), it still throws ... | 2019/09/06 | [
"https://Stackoverflow.com/questions/57814535",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3204706/"
] | First activate your environment. Replace <name> with your environment name.
```
conda activate <name>
```
Then see cuda version in your machine. To see cuda version:
```
nvcc --version
```
Now for CUDA 10.1 use:
```
conda install pytorch==1.4.0 torchvision==0.5.0 cudatoolkit=10.1 -c pytorch
```
For CUDA 10.0 u... | One more thing to note here is if you are installing PyTorch with CUDA support in an anaconda environment, Please make sure that the **Python** version should be **3.7-3.9**.
conda install pytorch torchvision torchaudio cudatoolkit=11.6 -c pytorch -c conda-forge.
I was getting the same "AssertionError: Torch not comp... |
57,814,535 | I figured out this is a popular question, but still I couldn't find a solution for that.
I'm trying to run a simple repo [Here](https://github.com/swathikirans/violence-recognition-pytorch) which uses `PyTorch`. Although I just upgraded my Pytorch to the latest CUDA version from pytorch.org (`1.2.0`), it still throws ... | 2019/09/06 | [
"https://Stackoverflow.com/questions/57814535",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3204706/"
] | How did you install pytorch? It sounds like you installed pytorch without CUDA support. <https://pytorch.org/> has instructions for how to install pytorch with cuda support.
In this case, we have the following command:
`conda install pytorch torchvision cudatoolkit=10.1 -c pytorch`
OR the command with latest cudatoo... | First activate your environment. Replace <name> with your environment name.
```
conda activate <name>
```
Then see cuda version in your machine. To see cuda version:
```
nvcc --version
```
Now for CUDA 10.1 use:
```
conda install pytorch==1.4.0 torchvision==0.5.0 cudatoolkit=10.1 -c pytorch
```
For CUDA 10.0 u... |
57,814,535 | I figured out this is a popular question, but still I couldn't find a solution for that.
I'm trying to run a simple repo [Here](https://github.com/swathikirans/violence-recognition-pytorch) which uses `PyTorch`. Although I just upgraded my Pytorch to the latest CUDA version from pytorch.org (`1.2.0`), it still throws ... | 2019/09/06 | [
"https://Stackoverflow.com/questions/57814535",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3204706/"
] | How did you install pytorch? It sounds like you installed pytorch without CUDA support. <https://pytorch.org/> has instructions for how to install pytorch with cuda support.
In this case, we have the following command:
`conda install pytorch torchvision cudatoolkit=10.1 -c pytorch`
OR the command with latest cudatoo... | try this:
```
conda install pytorch torchvision cudatoolkit=10.2 -c pytorch
``` |
57,814,535 | I figured out this is a popular question, but still I couldn't find a solution for that.
I'm trying to run a simple repo [Here](https://github.com/swathikirans/violence-recognition-pytorch) which uses `PyTorch`. Although I just upgraded my Pytorch to the latest CUDA version from pytorch.org (`1.2.0`), it still throws ... | 2019/09/06 | [
"https://Stackoverflow.com/questions/57814535",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3204706/"
] | you dont have to install it via anaconda, you could install cuda from their [website](https://developer.nvidia.com/cuda-downloads). after install ends open a new terminal and check your cuda version with:
```
>>> nvcc --version
nvcc: NVIDIA (R) Cuda compiler driver
Copyright (c) 2005-2021 NVIDIA Corporation
Built on T... | try this:
```
conda install pytorch torchvision cudatoolkit=10.2 -c pytorch
``` |
57,814,535 | I figured out this is a popular question, but still I couldn't find a solution for that.
I'm trying to run a simple repo [Here](https://github.com/swathikirans/violence-recognition-pytorch) which uses `PyTorch`. Although I just upgraded my Pytorch to the latest CUDA version from pytorch.org (`1.2.0`), it still throws ... | 2019/09/06 | [
"https://Stackoverflow.com/questions/57814535",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3204706/"
] | How did you install pytorch? It sounds like you installed pytorch without CUDA support. <https://pytorch.org/> has instructions for how to install pytorch with cuda support.
In this case, we have the following command:
`conda install pytorch torchvision cudatoolkit=10.1 -c pytorch`
OR the command with latest cudatoo... | Uninstalling the packages and reinstalling it with pip instead solved it for me.
1.`conda remove pytorch torchvision torchaudio cudatoolkit`
2.`pip3 install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu116` |
57,814,535 | I figured out this is a popular question, but still I couldn't find a solution for that.
I'm trying to run a simple repo [Here](https://github.com/swathikirans/violence-recognition-pytorch) which uses `PyTorch`. Although I just upgraded my Pytorch to the latest CUDA version from pytorch.org (`1.2.0`), it still throws ... | 2019/09/06 | [
"https://Stackoverflow.com/questions/57814535",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3204706/"
] | This error is happening because of incorrect device. Make sure to run this snippet before every experiment.
```
device = "cuda" if torch.cuda.is_available() else "cpu"
device
``` | Uninstalling the packages and reinstalling it with pip instead solved it for me.
1.`conda remove pytorch torchvision torchaudio cudatoolkit`
2.`pip3 install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu116` |
57,814,535 | I figured out this is a popular question, but still I couldn't find a solution for that.
I'm trying to run a simple repo [Here](https://github.com/swathikirans/violence-recognition-pytorch) which uses `PyTorch`. Although I just upgraded my Pytorch to the latest CUDA version from pytorch.org (`1.2.0`), it still throws ... | 2019/09/06 | [
"https://Stackoverflow.com/questions/57814535",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3204706/"
] | you dont have to install it via anaconda, you could install cuda from their [website](https://developer.nvidia.com/cuda-downloads). after install ends open a new terminal and check your cuda version with:
```
>>> nvcc --version
nvcc: NVIDIA (R) Cuda compiler driver
Copyright (c) 2005-2021 NVIDIA Corporation
Built on T... | This error is happening because of incorrect device. Make sure to run this snippet before every experiment.
```
device = "cuda" if torch.cuda.is_available() else "cpu"
device
``` |
10,891,670 | I'm using the [runwithfriends](http://apps.facebook.com/runwithfriends) example app to learn canvas programming and GAE. I can upload the sample code to GAE without any errors. Here are my config.py and app.yaml files:
### conf.py:
```
# Facebook Application ID and Secret.
FACEBOOK_APP_ID = ''
FACEBOOK_APP_SECRET = '... | 2012/06/05 | [
"https://Stackoverflow.com/questions/10891670",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/137527/"
] | Read the [documentation for `__del__`](http://docs.python.org/reference/datamodel.html#object.__del__) and [for the garbage collector](http://docs.python.org/library/gc.html#gc.garbage). `__del__` doesn't do what you probably think it does, nor does `del`. `__del__` is not necessarily called when you do a `del`, and ma... | Because the garbage collector has no way of knowing which can safely be deleted first. |
10,891,670 | I'm using the [runwithfriends](http://apps.facebook.com/runwithfriends) example app to learn canvas programming and GAE. I can upload the sample code to GAE without any errors. Here are my config.py and app.yaml files:
### conf.py:
```
# Facebook Application ID and Secret.
FACEBOOK_APP_ID = ''
FACEBOOK_APP_SECRET = '... | 2012/06/05 | [
"https://Stackoverflow.com/questions/10891670",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/137527/"
] | This is not true anymore since python 3.4. See [PEP-442](https://www.python.org/dev/peps/pep-0442/). | Because the garbage collector has no way of knowing which can safely be deleted first. |
10,891,670 | I'm using the [runwithfriends](http://apps.facebook.com/runwithfriends) example app to learn canvas programming and GAE. I can upload the sample code to GAE without any errors. Here are my config.py and app.yaml files:
### conf.py:
```
# Facebook Application ID and Secret.
FACEBOOK_APP_ID = ''
FACEBOOK_APP_SECRET = '... | 2012/06/05 | [
"https://Stackoverflow.com/questions/10891670",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/137527/"
] | Read the [documentation for `__del__`](http://docs.python.org/reference/datamodel.html#object.__del__) and [for the garbage collector](http://docs.python.org/library/gc.html#gc.garbage). `__del__` doesn't do what you probably think it does, nor does `del`. `__del__` is not necessarily called when you do a `del`, and ma... | Read this [link](https://stackoverflow.com/questions/6104535/i-dont-understand-this-python-del-behaviour). I think this will help you.
>
> `del` doesn't call `__del__`
>
>
> `del` in the way you are using removes a local variable. `__del__` is called when the object is destroyed. Python as a language makes no guara... |
10,891,670 | I'm using the [runwithfriends](http://apps.facebook.com/runwithfriends) example app to learn canvas programming and GAE. I can upload the sample code to GAE without any errors. Here are my config.py and app.yaml files:
### conf.py:
```
# Facebook Application ID and Secret.
FACEBOOK_APP_ID = ''
FACEBOOK_APP_SECRET = '... | 2012/06/05 | [
"https://Stackoverflow.com/questions/10891670",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/137527/"
] | This is not true anymore since python 3.4. See [PEP-442](https://www.python.org/dev/peps/pep-0442/). | Read this [link](https://stackoverflow.com/questions/6104535/i-dont-understand-this-python-del-behaviour). I think this will help you.
>
> `del` doesn't call `__del__`
>
>
> `del` in the way you are using removes a local variable. `__del__` is called when the object is destroyed. Python as a language makes no guara... |
53,784,485 | I am using python to collect temperature data but only want to store the last 24 hours of data.
I am currently generating my .csv file with this
```
while True:
tempC = mcp.temperature
tempF = tempC * 9 / 5 + 32
timestamp = datetime.datetime.now().strftime("%y-%m-%d %H:%M ")
f = open("24hr.csv", "a... | 2018/12/14 | [
"https://Stackoverflow.com/questions/53784485",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10792002/"
] | You've done most of the work already. I've got a couple of suggestions.
1. Use `with`. This will mean that if there's an error mid-way through your program and an exception is raised, the file will be closed properly.
2. Parse the timestamp from the file and compare it with the current time.
3. Use `len` to check the ... | Are u using linux ? If u jus need last 144 lines u can try
```
tail -n 144 file.csv
```
U can find tail for windows too, I got one with CMDer.
If u have to use python and u have small file which fit in RAM, load it with readlines() into list, cut it (lst = lst[:144]) and rewrite. If u dont shure how many lines u h... |
53,784,485 | I am using python to collect temperature data but only want to store the last 24 hours of data.
I am currently generating my .csv file with this
```
while True:
tempC = mcp.temperature
tempF = tempC * 9 / 5 + 32
timestamp = datetime.datetime.now().strftime("%y-%m-%d %H:%M ")
f = open("24hr.csv", "a... | 2018/12/14 | [
"https://Stackoverflow.com/questions/53784485",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10792002/"
] | You've done most of the work already. I've got a couple of suggestions.
1. Use `with`. This will mean that if there's an error mid-way through your program and an exception is raised, the file will be closed properly.
2. Parse the timestamp from the file and compare it with the current time.
3. Use `len` to check the ... | Given that 288 lines will not take up much memory, I think is perfectly fine just reading the lines, truncating the file, and putting back the desired lines:
```
# Unless you are working in a system with limited memory
# reading 288 lines isn't much
def remove_old_entries(file_):
file_.seek(0) # Just in case go t... |
53,784,485 | I am using python to collect temperature data but only want to store the last 24 hours of data.
I am currently generating my .csv file with this
```
while True:
tempC = mcp.temperature
tempF = tempC * 9 / 5 + 32
timestamp = datetime.datetime.now().strftime("%y-%m-%d %H:%M ")
f = open("24hr.csv", "a... | 2018/12/14 | [
"https://Stackoverflow.com/questions/53784485",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10792002/"
] | You've done most of the work already. I've got a couple of suggestions.
1. Use `with`. This will mean that if there's an error mid-way through your program and an exception is raised, the file will be closed properly.
2. Parse the timestamp from the file and compare it with the current time.
3. Use `len` to check the ... | If you are on Linux or likes, the right approach is to implement [logrotaion](https://manpages.debian.org/jessie/logrotate/logrotate.8.en.html) |
47,128,570 | I have a set of data that looks like the following:
```
index 902.4 909.4 915.3
n 0.6 0.3 1.4
n.1 0.4 0.3 1.3
n.2 0.3 0.2 1.1
n.3 0.2 0.2 1.3
n.4 0.4 0.3 1.4
DCIS 0.3 1.6
DCIS.1 0.3 1.2
DCIS.2 1.1
DCIS.3 0.2 1.2
DCIS.4 0.2 ... | 2017/11/06 | [
"https://Stackoverflow.com/questions/47128570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8147329/"
] | You can use this:
```
plt.title("Histograms for " + str(df.columns[i]))
``` | Try
```
plt.title("Histograms for {0:.2f}".format(df.columns[i]))
```
The characters inside the curly brackets are from the [Format Specification Mini-Language](https://docs.python.org/3/library/string.html#format-specification-mini-language). This example formats a float with 2 decimal places. If you follow the lin... |
47,128,570 | I have a set of data that looks like the following:
```
index 902.4 909.4 915.3
n 0.6 0.3 1.4
n.1 0.4 0.3 1.3
n.2 0.3 0.2 1.1
n.3 0.2 0.2 1.3
n.4 0.4 0.3 1.4
DCIS 0.3 1.6
DCIS.1 0.3 1.2
DCIS.2 1.1
DCIS.3 0.2 1.2
DCIS.4 0.2 ... | 2017/11/06 | [
"https://Stackoverflow.com/questions/47128570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8147329/"
] | You can use this:
```
plt.title("Histograms for " + str(df.columns[i]))
``` | If you don't want the plots to be attached together, I'd suggest avoiding `subplots()` entirely. Instead, separate each plot with `plt.show()`:
```
cols = ["902.4", "909.4", "915.3"]
data = [{"df":df_n, "color":"k", "label":"N"},
{"df":df_DCIS, "color":"r", "label":"DCIS"},
{"df":df_br1234, "color":"or... |
62,741,775 | With my python script below, I wanted to check if a cron job is defined in my linux (centOS 7.5) server, and if it doesn't exist, I will add one by using python-crontab module.. It was working well until I gave CRONTAB -R to delete existing cron jobs and when I re-execute my python script, it is saying cronjob exists e... | 2020/07/05 | [
"https://Stackoverflow.com/questions/62741775",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11999777/"
] | The problem is that you have initialized a new Cron job before checking if it exists. You assumed that `Cron.find_command()` is only identifying enabled cron jobs. But it also identifies cronjobs that are created, but not enabled yet.
So, you have to check if the cronjob exists before creating a new job. Then, if it d... | Another Solution might be to add the items to an list as the output of the find command is an generator object but by putting the items into an list makes it easier to work on. This is what I did to solve the problem you had
Below here based on everything else already being initialized
```
List_A=[]
basic_iter... |
46,418,897 | I have a list as shown below which contain some dictionaries.
```
dlist=[
{
"a":1,
"b":[1,2]
},
{
"a":3,
"b":[4,5]
},
{
"a":1,
"b":[1,2,3]
}
]
```
I want the result to be as in this form as shown below
```
dlist=[
{
"a":1,
"b":[1,2,3]
},
{
"a":3,
"b":[4,5]
}
]
```
I can so... | 2017/09/26 | [
"https://Stackoverflow.com/questions/46418897",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6858122/"
] | Here is a solution that uses a temporary defaultdict:
```python
from collections import defaultdict
dd = defaultdict(set) # create temporary defaultdict
for d in dlist: dd[d["a"]] |= set(d["b"]) # union set(b) for each a
l = [{"a":k, "b":list(v)} for k,v in dd.items()] # generat... | if My understanding is right
```
uniques, theNewList = set(), []
for d in dlist:
cur = d["a"] # Avoid multiple lookups of the same thing
if cur not in uniques:
theNewList.append(d)
uniques.add(cur)
print(theNewList)
``` |
18,305,026 | I want to monitor a dir , and the dir has sub dirs and in subdir there are somes files with `.md`. (maybe there are some other files, such as \*.swp...)
I only want to monitor the .md files, I have read the doc, and there is only a `ExcludeFilter`, and in the issue : <https://github.com/seb-m/pyinotify/issues/31> says... | 2013/08/19 | [
"https://Stackoverflow.com/questions/18305026",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1276501/"
] | I think you basically have the right idea, but that it could be implemented more easily.
The `ProcessEvent` class in the **pyinotify** module already has a hook you can use to filter the processing of events. It's specified via an optional `pevent` keyword argument given on the call to the constructor and is saved in ... | There's nothing particularly wrong with your solution, but you want your inotify handler to be as fast as possible, so there are a few optimizations you can make.
You should move your match suffixes out of your function, so the compiler only builds them once:
```
EXTS = set([".md", ".markdown"])
```
I made them a s... |
18,305,026 | I want to monitor a dir , and the dir has sub dirs and in subdir there are somes files with `.md`. (maybe there are some other files, such as \*.swp...)
I only want to monitor the .md files, I have read the doc, and there is only a `ExcludeFilter`, and in the issue : <https://github.com/seb-m/pyinotify/issues/31> says... | 2013/08/19 | [
"https://Stackoverflow.com/questions/18305026",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1276501/"
] | I think you basically have the right idea, but that it could be implemented more easily.
The `ProcessEvent` class in the **pyinotify** module already has a hook you can use to filter the processing of events. It's specified via an optional `pevent` keyword argument given on the call to the constructor and is saved in ... | You can use the `__call__` method of `ProcessEvent` to centralize the call to `suffix_filter`:
```
class EventHandler(pyinotify.ProcessEvent):
def __call__(self, event):
if not suffix_filter(event.name):
super(EventHandler, self).__call__(event)
def process_IN_CREATE(self, event):
... |
40,613,590 | I would like to design a function `f(x : float, up : bool)` with these input/output:
```
# 2 decimals part rounded up (up = True)
f(142.452, True) = 142.46
f(142.449, True) = 142.45
# 2 decimals part rounded down (up = False)
f(142.452, False) = 142.45
f(142.449, False) = 142.44
```
Now, I know about Python's `round... | 2016/11/15 | [
"https://Stackoverflow.com/questions/40613590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1974842/"
] | Have you considered a mathematical approach using `floor` and `ceil`?
If you always want to round to 2 digits, then you could premultiply the number to be rounded by 100, then perform the rounding to the nearest integer and then divide again by 100.
```
from math import floor, ceil
def rounder(num, up=True):
dig... | `math.ceil()` rounds up, and `math.floor()` rounds down. So, the following is an example of how to use it:
```
import math
def f(x, b):
if b:
return (math.ceil(100*x) / 100)
else:
return (math.floor(100*x) / 100)
```
This function should do exactly what you want. |
40,613,590 | I would like to design a function `f(x : float, up : bool)` with these input/output:
```
# 2 decimals part rounded up (up = True)
f(142.452, True) = 142.46
f(142.449, True) = 142.45
# 2 decimals part rounded down (up = False)
f(142.452, False) = 142.45
f(142.449, False) = 142.44
```
Now, I know about Python's `round... | 2016/11/15 | [
"https://Stackoverflow.com/questions/40613590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1974842/"
] | Have you considered a mathematical approach using `floor` and `ceil`?
If you always want to round to 2 digits, then you could premultiply the number to be rounded by 100, then perform the rounding to the nearest integer and then divide again by 100.
```
from math import floor, ceil
def rounder(num, up=True):
dig... | You can also perform some mathematical logic if you do not want to use any explicit function as:
```
def f(num, up):
num = num * 100
if up and num != int(num): # if up and "float' value != 'int' value
num += 1
return int(num) / (100.0)
```
Here, the idea is if `up` is `True` and `int` value of n... |
40,613,590 | I would like to design a function `f(x : float, up : bool)` with these input/output:
```
# 2 decimals part rounded up (up = True)
f(142.452, True) = 142.46
f(142.449, True) = 142.45
# 2 decimals part rounded down (up = False)
f(142.452, False) = 142.45
f(142.449, False) = 142.44
```
Now, I know about Python's `round... | 2016/11/15 | [
"https://Stackoverflow.com/questions/40613590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1974842/"
] | You can also perform some mathematical logic if you do not want to use any explicit function as:
```
def f(num, up):
num = num * 100
if up and num != int(num): # if up and "float' value != 'int' value
num += 1
return int(num) / (100.0)
```
Here, the idea is if `up` is `True` and `int` value of n... | `math.ceil()` rounds up, and `math.floor()` rounds down. So, the following is an example of how to use it:
```
import math
def f(x, b):
if b:
return (math.ceil(100*x) / 100)
else:
return (math.floor(100*x) / 100)
```
This function should do exactly what you want. |
5,104,366 | users,
I have a basic question concerning inheritance (in python). I have two classes and one of them is inherited from the other like
```
class p:
def __init__(self,name):
self.pname = name
class c(p):
def __init__(self,name):
self.cname = name
```
Is there any possibility that I ca... | 2011/02/24 | [
"https://Stackoverflow.com/questions/5104366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/632263/"
] | >
> It should work like that that the parent object contains several variables and whenever I access the corresponding variables from a child I actually access the variable form the parent. I.e. if I change it for one child it is changed also for all other childes and the data are only stored once in memory (and not c... | I am lost in all these diverse answers.
But I think that what you need is expressed in the following code:
```
class P:
pvar=1 # <--- class attribute
def __init__(self,name):
self.cname = name
class C(P):
def __init__(self,name):
self.cname = name
c1=C('1')
c2=C('2')... |
5,104,366 | users,
I have a basic question concerning inheritance (in python). I have two classes and one of them is inherited from the other like
```
class p:
def __init__(self,name):
self.pname = name
class c(p):
def __init__(self,name):
self.cname = name
```
Is there any possibility that I ca... | 2011/02/24 | [
"https://Stackoverflow.com/questions/5104366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/632263/"
] | >
> It should work like that that the parent object contains several variables and whenever I access the corresponding variables from a child I actually access the variable form the parent. I.e. if I change it for one child it is changed also for all other childes and the data are only stored once in memory (and not c... | Finally, I found a way to do it.
The key point is to abandon the aim to obtain instances **c** with real **pvar** field, because it is impossible:
Since it is the same **\_*init*\_()** function (the one being in class P) that processes to create the objects **pvar**, it isn't possible to create **pvar** in instances... |
5,104,366 | users,
I have a basic question concerning inheritance (in python). I have two classes and one of them is inherited from the other like
```
class p:
def __init__(self,name):
self.pname = name
class c(p):
def __init__(self,name):
self.cname = name
```
Is there any possibility that I ca... | 2011/02/24 | [
"https://Stackoverflow.com/questions/5104366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/632263/"
] | >
> It should work like that that the parent object contains several variables and whenever I access the corresponding variables from a child I actually access the variable form the parent. I.e. if I change it for one child it is changed also for all other childes and the data are only stored once in memory (and not c... | r6d9, please, when you write an update, you should put the date and hour by the word UPDATE. It begins to be complcated to follow all that
.
.
Concerning this code of you:
```
def replaceinstance(parent,child):
for item in parent.__dict__.items():
child.__dict__.__setitem__(item[0],item[1])
prin... |
5,104,366 | users,
I have a basic question concerning inheritance (in python). I have two classes and one of them is inherited from the other like
```
class p:
def __init__(self,name):
self.pname = name
class c(p):
def __init__(self,name):
self.cname = name
```
Is there any possibility that I ca... | 2011/02/24 | [
"https://Stackoverflow.com/questions/5104366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/632263/"
] | >
> It should work like that that the parent object contains several variables and whenever I access the corresponding variables from a child I actually access the variable form the parent. I.e. if I change it for one child it is changed also for all other childes and the data are only stored once in memory (and not c... | One thing you must know as a base of the understanding of functionning of classes and instances:
>
> A class instance has a namespace
> implemented as a dictionary which is
> the **first place in which attribute
> references are searched**.
>
>
> When an attribute is not found there,
> and the instance’s class ... |
5,104,366 | users,
I have a basic question concerning inheritance (in python). I have two classes and one of them is inherited from the other like
```
class p:
def __init__(self,name):
self.pname = name
class c(p):
def __init__(self,name):
self.cname = name
```
Is there any possibility that I ca... | 2011/02/24 | [
"https://Stackoverflow.com/questions/5104366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/632263/"
] | I think your workaround is doable; You could use properties to make access to `P`'s attributes easier:
```
class P(object):
def __init__(self,name='default',pvar=1):
self.pname = name
self.pvar=pvar
class C(object):
def __init__(self,name,pobject=P()): #<-- The same default `P()` is
... | Finally, I found a way to do it.
The key point is to abandon the aim to obtain instances **c** with real **pvar** field, because it is impossible:
Since it is the same **\_*init*\_()** function (the one being in class P) that processes to create the objects **pvar**, it isn't possible to create **pvar** in instances... |
5,104,366 | users,
I have a basic question concerning inheritance (in python). I have two classes and one of them is inherited from the other like
```
class p:
def __init__(self,name):
self.pname = name
class c(p):
def __init__(self,name):
self.cname = name
```
Is there any possibility that I ca... | 2011/02/24 | [
"https://Stackoverflow.com/questions/5104366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/632263/"
] | >
> It should work like that that the parent object contains several variables and whenever I access the corresponding variables from a child I actually access the variable form the parent. I.e. if I change it for one child it is changed also for all other childes and the data are only stored once in memory (and not c... | I think your workaround is doable; You could use properties to make access to `P`'s attributes easier:
```
class P(object):
def __init__(self,name='default',pvar=1):
self.pname = name
self.pvar=pvar
class C(object):
def __init__(self,name,pobject=P()): #<-- The same default `P()` is
... |
5,104,366 | users,
I have a basic question concerning inheritance (in python). I have two classes and one of them is inherited from the other like
```
class p:
def __init__(self,name):
self.pname = name
class c(p):
def __init__(self,name):
self.cname = name
```
Is there any possibility that I ca... | 2011/02/24 | [
"https://Stackoverflow.com/questions/5104366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/632263/"
] | The other answer is right, your question is more about namespaces and references than about inheritance.
All variables in Python are references, and all object instance is a namespace. So you can do:
```
class C():
def __init__(self, x):
self.x = x
class Shared(object):
def __init__(self, value):
... | Okay, I think you might want to rephrase your question as:
**How can I extend Python's OOP to make inheritance work on the level of objects rather than classes?**
*First off - don't mess with the dicts:*
If you are just copying the entries of the parent dict over to the child-dict, this works for instantiation, but c... |
5,104,366 | users,
I have a basic question concerning inheritance (in python). I have two classes and one of them is inherited from the other like
```
class p:
def __init__(self,name):
self.pname = name
class c(p):
def __init__(self,name):
self.cname = name
```
Is there any possibility that I ca... | 2011/02/24 | [
"https://Stackoverflow.com/questions/5104366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/632263/"
] | I think your workaround is doable; You could use properties to make access to `P`'s attributes easier:
```
class P(object):
def __init__(self,name='default',pvar=1):
self.pname = name
self.pvar=pvar
class C(object):
def __init__(self,name,pobject=P()): #<-- The same default `P()` is
... | One thing you must know as a base of the understanding of functionning of classes and instances:
>
> A class instance has a namespace
> implemented as a dictionary which is
> the **first place in which attribute
> references are searched**.
>
>
> When an attribute is not found there,
> and the instance’s class ... |
5,104,366 | users,
I have a basic question concerning inheritance (in python). I have two classes and one of them is inherited from the other like
```
class p:
def __init__(self,name):
self.pname = name
class c(p):
def __init__(self,name):
self.cname = name
```
Is there any possibility that I ca... | 2011/02/24 | [
"https://Stackoverflow.com/questions/5104366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/632263/"
] | The other answer is right, your question is more about namespaces and references than about inheritance.
All variables in Python are references, and all object instance is a namespace. So you can do:
```
class C():
def __init__(self, x):
self.x = x
class Shared(object):
def __init__(self, value):
... | One thing you must know as a base of the understanding of functionning of classes and instances:
>
> A class instance has a namespace
> implemented as a dictionary which is
> the **first place in which attribute
> references are searched**.
>
>
> When an attribute is not found there,
> and the instance’s class ... |
5,104,366 | users,
I have a basic question concerning inheritance (in python). I have two classes and one of them is inherited from the other like
```
class p:
def __init__(self,name):
self.pname = name
class c(p):
def __init__(self,name):
self.cname = name
```
Is there any possibility that I ca... | 2011/02/24 | [
"https://Stackoverflow.com/questions/5104366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/632263/"
] | The other answer is right, your question is more about namespaces and references than about inheritance.
All variables in Python are references, and all object instance is a namespace. So you can do:
```
class C():
def __init__(self, x):
self.x = x
class Shared(object):
def __init__(self, value):
... | Finally, I found a way to do it.
The key point is to abandon the aim to obtain instances **c** with real **pvar** field, because it is impossible:
Since it is the same **\_*init*\_()** function (the one being in class P) that processes to create the objects **pvar**, it isn't possible to create **pvar** in instances... |
72,509,585 | I have information about places and purchases in a table, and I need to find the name of all the places where, for all the clients who purchased in that place, the total of their purchases is at least 70%.
I've already found the answer on python, I've sum the number of purchases per client, then the purchases per clie... | 2022/06/05 | [
"https://Stackoverflow.com/questions/72509585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9535697/"
] | Schema and insert statements:
```
create table c(client_id int, place_name varchar(50), total_purchase int, detail_purchase int);
insert into c values(1 ,'place1', 10, 7);
insert into c values(1 ,'place2', 10, 3);
insert into c values(2 ,'place1', 5, 4);
insert into c values(2 ,'place3', 5, 1);
```
Query:... | If I understand your question correctly, you could just use a where statement
```
SELECT place_name
FROM purchases
where (detail_purchase/total_purchase) >=0.7
GROUP BY place_name
```
[db fiddle](https://www.db-fiddle.com/f/w4EVh4WrdPJWJBKzqJ8RQb/1) |
72,509,585 | I have information about places and purchases in a table, and I need to find the name of all the places where, for all the clients who purchased in that place, the total of their purchases is at least 70%.
I've already found the answer on python, I've sum the number of purchases per client, then the purchases per clie... | 2022/06/05 | [
"https://Stackoverflow.com/questions/72509585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9535697/"
] | Here is a clean solution based on [group by](https://www.postgresql.org/docs/current/tutorial-agg.html) and [min](https://www.postgresql.org/docs/8.0/functions-aggregate.html) functions
```
select place_name
from c
group by place_name
having min(percent)>=0.7
```
| place\_name |
| --- |
| place1 |
[Fiddle](https://... | If I understand your question correctly, you could just use a where statement
```
SELECT place_name
FROM purchases
where (detail_purchase/total_purchase) >=0.7
GROUP BY place_name
```
[db fiddle](https://www.db-fiddle.com/f/w4EVh4WrdPJWJBKzqJ8RQb/1) |
39,448,135 | I have an application generating a weird config file
```
app_id1 {
key1 = val
key2 = val
...
}
app_id2 {
key1 = val
key2 = val
...
}
...
```
And I am struggling on how to parse this in python. The keys of each app may vary too.
I can't change the application to generate the configuration file in some easily parsable... | 2016/09/12 | [
"https://Stackoverflow.com/questions/39448135",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3821298/"
] | Based on the fact you said it had a button where you can view source, this sounds like a WYSIWIG (What you see is what you get) editor like CKeditor, TinyMCE, Froala, etc. They take standard HTML textarea elements and using Javascript and CSS convert them into more robust editors. They allow you to do simple text forma... | It`s not much information, so I‘ll take a guess:
For `<strong><em>`: The website could eventually use a div with the `contenteditable="true"` attribute ([more info on mdn](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/contenteditable)) as the input method. When you then paste in text from another... |
16,158,221 | I got this error:
```
[Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] mod_wsgi (pid=19481): Exception occurred processing WSGI script '/home/projects/treeio/treeio.wsgi'.
[Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] Traceback (most recent call last):
[Mon Apr 22 23:45:42 2013] [error] [client 192.... | 2013/04/22 | [
"https://Stackoverflow.com/questions/16158221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2309182/"
] | try `GROUP BY` with `GROUP_CONCAT`
<http://www.mysqlperformanceblog.com/2006/09/04/group_concat-useful-group-by-extension/> | You could do this all in your query instead of relying on PHP.
```
Select item, group_concat(category) FROM yourtable GROUP BY Item
``` |
16,158,221 | I got this error:
```
[Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] mod_wsgi (pid=19481): Exception occurred processing WSGI script '/home/projects/treeio/treeio.wsgi'.
[Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] Traceback (most recent call last):
[Mon Apr 22 23:45:42 2013] [error] [client 192.... | 2013/04/22 | [
"https://Stackoverflow.com/questions/16158221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2309182/"
] | try `GROUP BY` with `GROUP_CONCAT`
<http://www.mysqlperformanceblog.com/2006/09/04/group_concat-useful-group-by-extension/> | Create an array of categories for each item:
```
while($results = mysql_fetch_array($raw_results)) {
$items[$results['item']][] = $results['category'];
}
```
Then use that to output your HTML:
```
foreach ($items as $itemName => $categories) {
echo $itemName.'<br>';
echo 'Categories: '.implode(', ',$cat... |
16,158,221 | I got this error:
```
[Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] mod_wsgi (pid=19481): Exception occurred processing WSGI script '/home/projects/treeio/treeio.wsgi'.
[Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] Traceback (most recent call last):
[Mon Apr 22 23:45:42 2013] [error] [client 192.... | 2013/04/22 | [
"https://Stackoverflow.com/questions/16158221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2309182/"
] | try `GROUP BY` with `GROUP_CONCAT`
<http://www.mysqlperformanceblog.com/2006/09/04/group_concat-useful-group-by-extension/> | I would do something like this :
```
select id, item, group_concat(category) from Table1
group by id, item
```
[SQLFiddle](http://sqlfiddle.com/#!2/9e49f/2) |
16,158,221 | I got this error:
```
[Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] mod_wsgi (pid=19481): Exception occurred processing WSGI script '/home/projects/treeio/treeio.wsgi'.
[Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] Traceback (most recent call last):
[Mon Apr 22 23:45:42 2013] [error] [client 192.... | 2013/04/22 | [
"https://Stackoverflow.com/questions/16158221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2309182/"
] | try `GROUP BY` with `GROUP_CONCAT`
<http://www.mysqlperformanceblog.com/2006/09/04/group_concat-useful-group-by-extension/> | If you do not have the ability to change the query that gets the data from the database you can use the PHP helper function `array_unique`. This function removes duplicate values from an array. While it is better to do this in MySQL, its not always possible for the developer to do this easily so this would help. Here i... |
16,158,221 | I got this error:
```
[Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] mod_wsgi (pid=19481): Exception occurred processing WSGI script '/home/projects/treeio/treeio.wsgi'.
[Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] Traceback (most recent call last):
[Mon Apr 22 23:45:42 2013] [error] [client 192.... | 2013/04/22 | [
"https://Stackoverflow.com/questions/16158221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2309182/"
] | You could do this all in your query instead of relying on PHP.
```
Select item, group_concat(category) FROM yourtable GROUP BY Item
``` | Create an array of categories for each item:
```
while($results = mysql_fetch_array($raw_results)) {
$items[$results['item']][] = $results['category'];
}
```
Then use that to output your HTML:
```
foreach ($items as $itemName => $categories) {
echo $itemName.'<br>';
echo 'Categories: '.implode(', ',$cat... |
16,158,221 | I got this error:
```
[Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] mod_wsgi (pid=19481): Exception occurred processing WSGI script '/home/projects/treeio/treeio.wsgi'.
[Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] Traceback (most recent call last):
[Mon Apr 22 23:45:42 2013] [error] [client 192.... | 2013/04/22 | [
"https://Stackoverflow.com/questions/16158221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2309182/"
] | You could do this all in your query instead of relying on PHP.
```
Select item, group_concat(category) FROM yourtable GROUP BY Item
``` | If you do not have the ability to change the query that gets the data from the database you can use the PHP helper function `array_unique`. This function removes duplicate values from an array. While it is better to do this in MySQL, its not always possible for the developer to do this easily so this would help. Here i... |
16,158,221 | I got this error:
```
[Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] mod_wsgi (pid=19481): Exception occurred processing WSGI script '/home/projects/treeio/treeio.wsgi'.
[Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] Traceback (most recent call last):
[Mon Apr 22 23:45:42 2013] [error] [client 192.... | 2013/04/22 | [
"https://Stackoverflow.com/questions/16158221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2309182/"
] | I would do something like this :
```
select id, item, group_concat(category) from Table1
group by id, item
```
[SQLFiddle](http://sqlfiddle.com/#!2/9e49f/2) | Create an array of categories for each item:
```
while($results = mysql_fetch_array($raw_results)) {
$items[$results['item']][] = $results['category'];
}
```
Then use that to output your HTML:
```
foreach ($items as $itemName => $categories) {
echo $itemName.'<br>';
echo 'Categories: '.implode(', ',$cat... |
16,158,221 | I got this error:
```
[Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] mod_wsgi (pid=19481): Exception occurred processing WSGI script '/home/projects/treeio/treeio.wsgi'.
[Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] Traceback (most recent call last):
[Mon Apr 22 23:45:42 2013] [error] [client 192.... | 2013/04/22 | [
"https://Stackoverflow.com/questions/16158221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2309182/"
] | I would do something like this :
```
select id, item, group_concat(category) from Table1
group by id, item
```
[SQLFiddle](http://sqlfiddle.com/#!2/9e49f/2) | If you do not have the ability to change the query that gets the data from the database you can use the PHP helper function `array_unique`. This function removes duplicate values from an array. While it is better to do this in MySQL, its not always possible for the developer to do this easily so this would help. Here i... |
12,482,819 | I have been working with Beaglebone lately and have a question.
I have worked with TI microcontrollers before, setting the registers as I needed to.
From what I understand, the Angstrom distro (the one that comes with the board) let to set the registers of the processor as you want (through the kernel and class folde... | 2012/09/18 | [
"https://Stackoverflow.com/questions/12482819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1420553/"
] | After trying out a few variations this worked:
```
-:System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute
``` | Make sure you add this filter inside **Attribute Filter**:
```
-:System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute
```
 |
41,009,009 | I'm trying to create a function
```
rotate_character(char, rot)
```
that receives a character, "char" (a string with a length of 1), and an integer "rot". The function should return a new string with a length of 1, which is the result of rotating char by rot number of places to the right.
So an input of "A" for cha... | 2016/12/07 | [
"https://Stackoverflow.com/questions/41009009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3546086/"
] | ```
def rotate(letter, rot):
shift = 97 if letter.islower() else 65
return chr((ord(letter) + rot - shift) % 26 + shift)
letter = input('Enter a letter: ')
rot = int(input('Enter a number: '))
print(rotate(letter, rot))
``` | You can use the `string` module and then use the modulo operator to "wrap around" the end of the alphabet:
```
from string import lowercase
def rotate_char(char, rot):
i = lowercase.index(char)
return lowercase[(i + rot) % 25]
``` |
39,606,112 | I'm a beginner trying to write a program that will read in .exe files, .class files, or .pyc files and get the percentage of alphanumeric characters (a-z,A-Z,0-9). Here's what I have right now (I'm just trying to see if I can identify anything at the moment, not looking to count stuff yet):
```
chars_total = 0
chars_a... | 2016/09/21 | [
"https://Stackoverflow.com/questions/39606112",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6856008/"
] | `viewWillLayoutSubviews` is called when view controller's view's bounds changed (usually happens when view loaded, or orientation changed, or if it's a child view controller, and its view was changed by the parent view controller), but before it's subview's bounds or position changes. You can override this method to ma... | You can call the `layoutSubviews()` of UIView when you are changing any constraint value which is inside the UIView and more then one element is effected by the constraint change. When you are performing some task by changing the constraint by taking an outlet of the constraint at runtime you can call this. But this is... |
39,606,112 | I'm a beginner trying to write a program that will read in .exe files, .class files, or .pyc files and get the percentage of alphanumeric characters (a-z,A-Z,0-9). Here's what I have right now (I'm just trying to see if I can identify anything at the moment, not looking to count stuff yet):
```
chars_total = 0
chars_a... | 2016/09/21 | [
"https://Stackoverflow.com/questions/39606112",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6856008/"
] | There is no effective difference. One (`layoutSubviews`) is a message the runtime sends to the view, the other (`viewWillLayoutSubviews`) is a message the runtime sends to the view controller. The message to the view controller tells the view controller that its view is about to receive the view message! That's all. Th... | You can call the `layoutSubviews()` of UIView when you are changing any constraint value which is inside the UIView and more then one element is effected by the constraint change. When you are performing some task by changing the constraint by taking an outlet of the constraint at runtime you can call this. But this is... |
39,606,112 | I'm a beginner trying to write a program that will read in .exe files, .class files, or .pyc files and get the percentage of alphanumeric characters (a-z,A-Z,0-9). Here's what I have right now (I'm just trying to see if I can identify anything at the moment, not looking to count stuff yet):
```
chars_total = 0
chars_a... | 2016/09/21 | [
"https://Stackoverflow.com/questions/39606112",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6856008/"
] | There is no effective difference. One (`layoutSubviews`) is a message the runtime sends to the view, the other (`viewWillLayoutSubviews`) is a message the runtime sends to the view controller. The message to the view controller tells the view controller that its view is about to receive the view message! That's all. Th... | `viewWillLayoutSubviews` is called when view controller's view's bounds changed (usually happens when view loaded, or orientation changed, or if it's a child view controller, and its view was changed by the parent view controller), but before it's subview's bounds or position changes. You can override this method to ma... |
52,072,784 | I am working on a positioning system.
The input I have is a dict which will give us circles of radius d1 from point(x1,y1) and so on.
The output I want is an array(similar to a 2D coordinate system) in which the intersecting area is marked 1 and rest is 0.
I tried this:
```
xsize=3000
ysize=2000
lis={(x1,y1):d1,(x2,y... | 2018/08/29 | [
"https://Stackoverflow.com/questions/52072784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10269207/"
] | As you are already using numpy, try to rewrite your operations in a vectorized fashion, instead of using loops.
```
# choose appropriate dtype for better perf
dtype = np.float32
# take all indices in an array
indices = np.indices((ysize, xsize), dtype=dtype).T
points = np.array(list(lis.keys()), dtype=dtype)
# squar... | Thanks for the answers!
I also found this:
```
pos=np.ones((xsize,ysize))
xx,yy=np.mgrid[:xsize,:ysize]
for element in lis:
circle=(xx-element[0])**2+(yy-element[1])**2
pos=np.logical_and(pos,(circle<(lis[element]**2)))
#pos&circle<(lis[element]**2 doesn't work(I read somewhere it does)
```
I needed thi... |
42,835,809 | are there any tutorials available about `export_savedmodel` ?
I have gone through [this article](https://www.tensorflow.org/versions/master/api_docs/python/contrib.learn/estimators) on tensorflow.org and [unittest code](https://github.com/tensorflow/tensorflow/blob/05d7f793ec5f04cd6b362abfef620a78fefdb35f/tensorflow/p... | 2017/03/16 | [
"https://Stackoverflow.com/questions/42835809",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/456105/"
] | if you are using tensorflow straight from the master branch there's a module tensorflow.python.estimator.export that provides a function for that:
```
from tensorflow.python.estimator.export import export
feature_spec = {'MY_FEATURE': tf.constant(2.0, shape=[1, 1])}
serving_input_fn = export.build_raw_serving_input_re... | You need to have tf.train.Example and tf.train.Feature and pass the input to input receiver function and invoke the model.
You can take a look at this example
<https://github.com/tettusud/tensorflow-examples/tree/master/estimators> |
42,835,809 | are there any tutorials available about `export_savedmodel` ?
I have gone through [this article](https://www.tensorflow.org/versions/master/api_docs/python/contrib.learn/estimators) on tensorflow.org and [unittest code](https://github.com/tensorflow/tensorflow/blob/05d7f793ec5f04cd6b362abfef620a78fefdb35f/tensorflow/p... | 2017/03/16 | [
"https://Stackoverflow.com/questions/42835809",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/456105/"
] | Do it like this:
```
your_feature_spec = {
"some_feature": tf.FixedLenFeature([], dtype=tf.string, default_value=""),
"some_feature": tf.VarLenFeature(dtype=tf.string),
}
def _serving_input_receiver_fn():
serialized_tf_example = tf.placeholder(dtype=tf.string, shape=None,
... | if you are using tensorflow straight from the master branch there's a module tensorflow.python.estimator.export that provides a function for that:
```
from tensorflow.python.estimator.export import export
feature_spec = {'MY_FEATURE': tf.constant(2.0, shape=[1, 1])}
serving_input_fn = export.build_raw_serving_input_re... |
42,835,809 | are there any tutorials available about `export_savedmodel` ?
I have gone through [this article](https://www.tensorflow.org/versions/master/api_docs/python/contrib.learn/estimators) on tensorflow.org and [unittest code](https://github.com/tensorflow/tensorflow/blob/05d7f793ec5f04cd6b362abfef620a78fefdb35f/tensorflow/p... | 2017/03/16 | [
"https://Stackoverflow.com/questions/42835809",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/456105/"
] | You have 2 options:
Export your model to work with JSON dictionaries
------------------------------------------------
In my [mlengine-boilerplate repository](https://github.com/Fematich/mlengine-boilerplate/blob/master/trainer/task.py), I use this to export estimator models to Cloud ML Engine to easily use this with ... | You need to have tf.train.Example and tf.train.Feature and pass the input to input receiver function and invoke the model.
You can take a look at this example
<https://github.com/tettusud/tensorflow-examples/tree/master/estimators> |
42,835,809 | are there any tutorials available about `export_savedmodel` ?
I have gone through [this article](https://www.tensorflow.org/versions/master/api_docs/python/contrib.learn/estimators) on tensorflow.org and [unittest code](https://github.com/tensorflow/tensorflow/blob/05d7f793ec5f04cd6b362abfef620a78fefdb35f/tensorflow/p... | 2017/03/16 | [
"https://Stackoverflow.com/questions/42835809",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/456105/"
] | Do it like this:
```
your_feature_spec = {
"some_feature": tf.FixedLenFeature([], dtype=tf.string, default_value=""),
"some_feature": tf.VarLenFeature(dtype=tf.string),
}
def _serving_input_receiver_fn():
serialized_tf_example = tf.placeholder(dtype=tf.string, shape=None,
... | You have 2 options:
Export your model to work with JSON dictionaries
------------------------------------------------
In my [mlengine-boilerplate repository](https://github.com/Fematich/mlengine-boilerplate/blob/master/trainer/task.py), I use this to export estimator models to Cloud ML Engine to easily use this with ... |
42,835,809 | are there any tutorials available about `export_savedmodel` ?
I have gone through [this article](https://www.tensorflow.org/versions/master/api_docs/python/contrib.learn/estimators) on tensorflow.org and [unittest code](https://github.com/tensorflow/tensorflow/blob/05d7f793ec5f04cd6b362abfef620a78fefdb35f/tensorflow/p... | 2017/03/16 | [
"https://Stackoverflow.com/questions/42835809",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/456105/"
] | Do it like this:
```
your_feature_spec = {
"some_feature": tf.FixedLenFeature([], dtype=tf.string, default_value=""),
"some_feature": tf.VarLenFeature(dtype=tf.string),
}
def _serving_input_receiver_fn():
serialized_tf_example = tf.placeholder(dtype=tf.string, shape=None,
... | You need to have tf.train.Example and tf.train.Feature and pass the input to input receiver function and invoke the model.
You can take a look at this example
<https://github.com/tettusud/tensorflow-examples/tree/master/estimators> |
70,068,198 | I have api like this :

I want to call this api in python, this is my code :
```
def get_province():
headers = {
'Content-type': 'application/json',
'x-api-key': api_key
}
response = requests.get(url, headers=headers)
return response.json()
```
But, i... | 2021/11/22 | [
"https://Stackoverflow.com/questions/70068198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17480369/"
] | **No Need for a LOOP**
Here is a little technique Gordon Linoff demonstrated some time ago.
1. Expand
2. Elimnate
3. Restore
You can substitute any `ODD` combination of characters/strings pairs like `§§` and `||`
**Example**
```
Select replace(replace(replace('my string to split',' ','><'),'<>',''),'><',' ')
`... | use charindex <https://www.w3schools.com/sql/func_sqlserver_charindex.asp> in a looping structure and then use a variable to keep track of the index position. |
14,444,012 | I am writing a bit of `python` code where I had to check if all values in `list2` was present in `list1`, I did that by using `set(list2).difference(list1)` but that function was too slow with many items in the list.
So I was thinking that `list1` could be a dictionary for fast lookup...
So I would like to find a fa... | 2013/01/21 | [
"https://Stackoverflow.com/questions/14444012",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1376883/"
] | A fast way to achieve what you want will be using `all` and a generator comprehension.
```
s_list2 = set(list2)
all_present = all(l in s_list2 for l in list1)
```
This will be advantageous in the case that some elements of list1 are not present in list2.
Some timing. In the case where all values in the first list a... | You can convert the lists to sets and then use the method `issubset()` to check whether one is a subset of another set or not.
```
In [78]: import random
In [79]: lis2=range(100)
In [80]: random.shuffle(lis2)
In [81]: lis1=range(1000)
In [82]: random.shuffle(lis1)
In [83]: s1=set(lis1)
In [84]: all(l in s1 for l... |
14,444,012 | I am writing a bit of `python` code where I had to check if all values in `list2` was present in `list1`, I did that by using `set(list2).difference(list1)` but that function was too slow with many items in the list.
So I was thinking that `list1` could be a dictionary for fast lookup...
So I would like to find a fa... | 2013/01/21 | [
"https://Stackoverflow.com/questions/14444012",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1376883/"
] | A fast way to achieve what you want will be using `all` and a generator comprehension.
```
s_list2 = set(list2)
all_present = all(l in s_list2 for l in list1)
```
This will be advantageous in the case that some elements of list1 are not present in list2.
Some timing. In the case where all values in the first list a... | Sorting both lists and then walking through them together is O(n log n). i.e.:
```
l1.sort()
l2.sort()
j = 0
for i in range(0,len(l1)):
while ((j < len(l2)) and (l1[i] == l2[j])):
j = j+1
if (j == len(l2)):
break
if (l1[i] > l2[j]):
break
if (j == len(l2)): # all of l2 in l1
```
Now in terms of t... |
14,444,012 | I am writing a bit of `python` code where I had to check if all values in `list2` was present in `list1`, I did that by using `set(list2).difference(list1)` but that function was too slow with many items in the list.
So I was thinking that `list1` could be a dictionary for fast lookup...
So I would like to find a fa... | 2013/01/21 | [
"https://Stackoverflow.com/questions/14444012",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1376883/"
] | You can convert the lists to sets and then use the method `issubset()` to check whether one is a subset of another set or not.
```
In [78]: import random
In [79]: lis2=range(100)
In [80]: random.shuffle(lis2)
In [81]: lis1=range(1000)
In [82]: random.shuffle(lis1)
In [83]: s1=set(lis1)
In [84]: all(l in s1 for l... | Sorting both lists and then walking through them together is O(n log n). i.e.:
```
l1.sort()
l2.sort()
j = 0
for i in range(0,len(l1)):
while ((j < len(l2)) and (l1[i] == l2[j])):
j = j+1
if (j == len(l2)):
break
if (l1[i] > l2[j]):
break
if (j == len(l2)): # all of l2 in l1
```
Now in terms of t... |
11,962,123 | I am trying to make a query which I haven't been able to yet. My permanent view function is following:
```
function(doc) {
if('llweb_result' in doc){
for(i in doc.llweb_result){
emit(doc.llweb_result[i].llweb_result, doc);
}
}
}
```
Depending on the key, I filter the result. ... | 2012/08/14 | [
"https://Stackoverflow.com/questions/11962123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1277280/"
] | If you get duplicate pairs in the query results, it means that you have the duplicate `doc.llweb_result[i].llweb_result` values in each document.
You can change the view function to emit only one of these values (as the key). One way to do so would be:
```
function(doc) {
if ('llweb_result' in doc) {
dis... | I don't know anything about `couchdb-python` but CouchDB supports either a single `key` or multiple `keys` in an array. So, take a look in your `couchdb-python` docs for how to supply `keys=[0,1,2]` as a parameter.
Regarding getting just the unique values, take a look [at this section of *CouchDB The Definitive Guide*... |
7,045,371 | I recently learned I could run a server with this command:
```
sudo python -m HTTPSimpleServer
```
**My question: how do I terminate this server when done with it?** | 2011/08/12 | [
"https://Stackoverflow.com/questions/7045371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/873392/"
] | Type Control-C. Simple as that. | You might want to check the HttpServer class in [this servlet module](http://code.google.com/p/verse-quiz/source/browse/trunk/servlet.py) for a modification that allows the server to be quit. If the handler raises a SystemExit exception, the server will break from its serving.
---
```
class HttpServer(socketserver.Th... |
2,706,129 | I'm trying to speed up a python routine by writing it in C++, then using it using ctypes or cython.
I'm brand new to c++. I'm using Microsoft Visual C++ Express as it's free.
I plan to implement an expression tree, and a method to evaluate it in postfix order.
The problem I run into right away is:
```
class Node {
... | 2010/04/24 | [
"https://Stackoverflow.com/questions/2706129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/169415/"
] | No, because the object would be infinitely large (because every `Node` has as members two other `Node` objects, which each have as members two other `Node` objects, which each... well, you get the point).
You can, however, have a pointer to the class type as a member variable:
```
class Node {
char *cargo;
No... | No, but it can have a reference or a pointer to itself:
```
class Node
{
Node *pnode;
Node &rnode;
};
``` |
2,706,129 | I'm trying to speed up a python routine by writing it in C++, then using it using ctypes or cython.
I'm brand new to c++. I'm using Microsoft Visual C++ Express as it's free.
I plan to implement an expression tree, and a method to evaluate it in postfix order.
The problem I run into right away is:
```
class Node {
... | 2010/04/24 | [
"https://Stackoverflow.com/questions/2706129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/169415/"
] | No, because the object would be infinitely large (because every `Node` has as members two other `Node` objects, which each have as members two other `Node` objects, which each... well, you get the point).
You can, however, have a pointer to the class type as a member variable:
```
class Node {
char *cargo;
No... | Just for completeness, note that a class can contain a static instance of itself:
```
class A
{
static A a;
};
```
This is because static members are not actually stored in the class instances, so there is no recursion. |
2,706,129 | I'm trying to speed up a python routine by writing it in C++, then using it using ctypes or cython.
I'm brand new to c++. I'm using Microsoft Visual C++ Express as it's free.
I plan to implement an expression tree, and a method to evaluate it in postfix order.
The problem I run into right away is:
```
class Node {
... | 2010/04/24 | [
"https://Stackoverflow.com/questions/2706129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/169415/"
] | No, because the object would be infinitely large (because every `Node` has as members two other `Node` objects, which each have as members two other `Node` objects, which each... well, you get the point).
You can, however, have a pointer to the class type as a member variable:
```
class Node {
char *cargo;
No... | Use a pointer, *& better initialized*:
```
class Node {
char * cargo = nullptr;
Node * left = nullptr;
Node * right = nullptr;
};
```
**Modern C++**
It is a better practice to use **smart-pointers** (unique\_ptr, shared\_ptr, etc.), instead of memory allocations by 'new':
```
#include <string>
#include... |
2,706,129 | I'm trying to speed up a python routine by writing it in C++, then using it using ctypes or cython.
I'm brand new to c++. I'm using Microsoft Visual C++ Express as it's free.
I plan to implement an expression tree, and a method to evaluate it in postfix order.
The problem I run into right away is:
```
class Node {
... | 2010/04/24 | [
"https://Stackoverflow.com/questions/2706129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/169415/"
] | Just for completeness, note that a class can contain a static instance of itself:
```
class A
{
static A a;
};
```
This is because static members are not actually stored in the class instances, so there is no recursion. | No, but it can have a reference or a pointer to itself:
```
class Node
{
Node *pnode;
Node &rnode;
};
``` |
2,706,129 | I'm trying to speed up a python routine by writing it in C++, then using it using ctypes or cython.
I'm brand new to c++. I'm using Microsoft Visual C++ Express as it's free.
I plan to implement an expression tree, and a method to evaluate it in postfix order.
The problem I run into right away is:
```
class Node {
... | 2010/04/24 | [
"https://Stackoverflow.com/questions/2706129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/169415/"
] | No, but it can have a reference or a pointer to itself:
```
class Node
{
Node *pnode;
Node &rnode;
};
``` | Use a pointer, *& better initialized*:
```
class Node {
char * cargo = nullptr;
Node * left = nullptr;
Node * right = nullptr;
};
```
**Modern C++**
It is a better practice to use **smart-pointers** (unique\_ptr, shared\_ptr, etc.), instead of memory allocations by 'new':
```
#include <string>
#include... |
2,706,129 | I'm trying to speed up a python routine by writing it in C++, then using it using ctypes or cython.
I'm brand new to c++. I'm using Microsoft Visual C++ Express as it's free.
I plan to implement an expression tree, and a method to evaluate it in postfix order.
The problem I run into right away is:
```
class Node {
... | 2010/04/24 | [
"https://Stackoverflow.com/questions/2706129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/169415/"
] | Just for completeness, note that a class can contain a static instance of itself:
```
class A
{
static A a;
};
```
This is because static members are not actually stored in the class instances, so there is no recursion. | Use a pointer, *& better initialized*:
```
class Node {
char * cargo = nullptr;
Node * left = nullptr;
Node * right = nullptr;
};
```
**Modern C++**
It is a better practice to use **smart-pointers** (unique\_ptr, shared\_ptr, etc.), instead of memory allocations by 'new':
```
#include <string>
#include... |
48,490,382 | Gnome desktop has 2 clipboards, the X.org (saves every selection) and the legacy one (CTRL+C). I am writing a simple python script to clear both clipboards, securely preferably, since it may be done after copy-pasting a password.
The code that I have seen over here is this:
```
# empty X.org clipboard
os.system("xcli... | 2018/01/28 | [
"https://Stackoverflow.com/questions/48490382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9213435/"
] | I know three ways to clear the clipboard from Python. First using tkinter:
```
try:
from Tkinter import Tk
except ImportError:
from tkinter import Tk
r = Tk()
r.withdraw()
r.clipboard_clear()
r.destroy()
```
Second with xclip, but I use xclip like this:
```
echo -n | xclip -selection clipboard
```
Does it... | I have figured out:
```
#CLIPBOARD cleaner
subprocess.run(["xsel","-bc"])
#PRIMARY cleaner
subprocess.run(["xsel","-c"])
```
This one cleans both buffers, and leaves no zombie processes at all. Thanks for everyone who suggested some of them. |
48,490,382 | Gnome desktop has 2 clipboards, the X.org (saves every selection) and the legacy one (CTRL+C). I am writing a simple python script to clear both clipboards, securely preferably, since it may be done after copy-pasting a password.
The code that I have seen over here is this:
```
# empty X.org clipboard
os.system("xcli... | 2018/01/28 | [
"https://Stackoverflow.com/questions/48490382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9213435/"
] | Misconceptions
==============
1. GNOME doesn't "have clipboards"; *X11* has [selections and cut buffers](https://en.wikipedia.org/wiki/X_Window_selection). There are more than 2 of them, but mostly we worry about the selections `PRIMARY` and `CLIPBOARD`. Neither of them is "legacy".
2. You can't "securely" clear these... | I have figured out:
```
#CLIPBOARD cleaner
subprocess.run(["xsel","-bc"])
#PRIMARY cleaner
subprocess.run(["xsel","-c"])
```
This one cleans both buffers, and leaves no zombie processes at all. Thanks for everyone who suggested some of them. |
40,942,338 | I'm working on a python AWS Cognito implementation using boto3. `jwt.decode` on the IdToken yields a payload that's in the form of a dictionary, like so:
```py
{
"sub": "a uuid",
"email_verified": True,
"iss": "https://cognito-idp....",
"phone_number_verified": False,
"cognito:username": "19407ea0-... | 2016/12/02 | [
"https://Stackoverflow.com/questions/40942338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/119041/"
] | As I noted in a comment, the bulk of your work can be done by a dict comprehension:
```
lst = get_user() # or something similar, lst is a list of dicts
parsed_res = {k["Name"]:k["Value"] for k in lst}
```
This only differs from your expected output in that it contains `'true'` and `'false'` whereas you want bools in... | A dictionary comprehension, as Andras answered above, is a simple, Pythonic one-liner for your case. Some style guidelines ([such as Google's](https://google.github.io/styleguide/pyguide.html?showone=List_Comprehensions#List_Comprehensions)), however, recommend against them if they introduce complex logic or take up mo... |
67,448,604 | I have a pandas DataFrame containing rows of nodes that I ultimately would like to *connect* and turn into a graph like object. For this, I first thought of converting this DataFrame to something that resembles an adjacency list, to later on easily create a graph from this. I have the following:
A pandas Dataframe:
`... | 2021/05/08 | [
"https://Stackoverflow.com/questions/67448604",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5560529/"
] | One option would be to apply the following function - it's not completely vectorised because Dataframes don't particularly like embedding mutable objects like lists, and I don't think you can apply set operations in a vectorised way. It does cut down the number of comparisons needed though.
```
def f(x):
check = d... | TRY:
```
k=0
def test(x):
global k
k+=1
test_df = df[k:]
return list(test_df[test_df['start'] == x].index)
df['adjancy_matrix'] = df.end.apply(test,1)
```
**OUTPUT:**
```
id start end cases adjancy_matrix
0 0 A B [c1,c2,c44] [1, 6]
1 1 B C [c2,c1,c3] ... |
67,448,604 | I have a pandas DataFrame containing rows of nodes that I ultimately would like to *connect* and turn into a graph like object. For this, I first thought of converting this DataFrame to something that resembles an adjacency list, to later on easily create a graph from this. I have the following:
A pandas Dataframe:
`... | 2021/05/08 | [
"https://Stackoverflow.com/questions/67448604",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5560529/"
] | A self-join option:
```py
df['adjacency_list'] = df.apply(lambda s: df[(df['start'] == s.end) &
(df['id'] != s.id)].index.tolist(), axis=1)
print(df)
```
Output:
```
id start end cases adjacency_list
0 0 A B [c1, c2, c44] [1, 6]
1 1 B ... | TRY:
```
k=0
def test(x):
global k
k+=1
test_df = df[k:]
return list(test_df[test_df['start'] == x].index)
df['adjancy_matrix'] = df.end.apply(test,1)
```
**OUTPUT:**
```
id start end cases adjancy_matrix
0 0 A B [c1,c2,c44] [1, 6]
1 1 B C [c2,c1,c3] ... |
40,041,463 | I installed OpenCV 3.1.0 and CUDA 8.0 in Ubuntu 16.04. When I check "nvcc --version" to check the CUDA version, it is 8.0. But when I try to compile a C++ OpenCV program I get the following error:
```
Could NOT find CUDA: Found unsuitable version "7.5", but required
is exact version "8.0" (found /usr/local/cuda)
``... | 2016/10/14 | [
"https://Stackoverflow.com/questions/40041463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4136920/"
] | I had a similar issue after upgrading from CUDA 8.0 to 9.1. When I compiled my code and got error "found unsuitable version (CUDA 8.0)". In my case, it's the problem of previous cmake files. Just deleted previous files generated by cmake and then it worked fine. | Environment Variables
As part of the CUDA environment, you should add the following in the .bashrc file of your home folder.
```
export CUDA_HOME=/usr/local/cuda-7.5
export LD_LIBRARY_PATH=${CUDA_HOME}/lib64
PATH=${CUDA_HOME}/bin:${PATH}
export PATH
``` |
40,041,463 | I installed OpenCV 3.1.0 and CUDA 8.0 in Ubuntu 16.04. When I check "nvcc --version" to check the CUDA version, it is 8.0. But when I try to compile a C++ OpenCV program I get the following error:
```
Could NOT find CUDA: Found unsuitable version "7.5", but required
is exact version "8.0" (found /usr/local/cuda)
``... | 2016/10/14 | [
"https://Stackoverflow.com/questions/40041463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4136920/"
] | I had a similar issue after upgrading from CUDA 8.0 to 9.1. When I compiled my code and got error "found unsuitable version (CUDA 8.0)". In my case, it's the problem of previous cmake files. Just deleted previous files generated by cmake and then it worked fine. | try this:
```
cd /usr/local
ls -l | grep cuda
```
if you see something like:
```
lrwxrwxrwx 1 root root 9 9 4 10:08 cuda -> cuda-7.5/
drwxr-xr-x 13 root root 4096 1 5 2017 cuda-7.5
drwxr-xr-x 14 root root 4096 7 27 17:24 cuda-8.0
```
then:
```
sudo rm -rf cuda
ln -s cuda-8.0 cuda
``` |
39,656,433 | I need to download incoming attachment without past attachment from mail using Python Script.
For example:If anyone send mail at this time(now) then just download that attachment only into local drive not past attachments.
Please anyone help me to download attachment using python script or java. | 2016/09/23 | [
"https://Stackoverflow.com/questions/39656433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5693776/"
] | ```
import email
import imaplib
import os
class FetchEmail():
connection = None
error = None
mail_server="host_name"
username="outlook_username"
password="password"
self.save_attachment(self,msg,download_folder)
def __init__(self, mail_server, username, password):
self.connection = imaplib.IMAP4_SSL(mail_server)
... | ```
import win32com.client #pip install pypiwin32 to work with windows operating sysytm
import datetime
import os
# To get today's date in 'day-month-year' format(01-12-2017).
dateToday=datetime.datetime.today()
FormatedDate=('{:02d}'.format(dateToday.day)+'-'+'{:02d}'.format(dateToday.month)+'-'+'{:04d}'.format(dateT... |
39,656,433 | I need to download incoming attachment without past attachment from mail using Python Script.
For example:If anyone send mail at this time(now) then just download that attachment only into local drive not past attachments.
Please anyone help me to download attachment using python script or java. | 2016/09/23 | [
"https://Stackoverflow.com/questions/39656433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5693776/"
] | ```
import email
import imaplib
import os
class FetchEmail():
connection = None
error = None
mail_server="host_name"
username="outlook_username"
password="password"
self.save_attachment(self,msg,download_folder)
def __init__(self, mail_server, username, password):
self.connection = imaplib.IMAP4_SSL(mail_server)
... | If you want to download the attachment from the outlook application from a particular sender and with a specific subject. The below code may be helpful.
```
import win32com.client
import os
from datetime import datetime, timedelta
outlook = win32com.client.Dispatch('outlook.application')
mapi = outlook.GetNamespace("M... |
39,656,433 | I need to download incoming attachment without past attachment from mail using Python Script.
For example:If anyone send mail at this time(now) then just download that attachment only into local drive not past attachments.
Please anyone help me to download attachment using python script or java. | 2016/09/23 | [
"https://Stackoverflow.com/questions/39656433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5693776/"
] | The below code helps by downloading the attachments from outlook emails that are
* '*Unread*' (and changes the mail to Read.) or from '*Today's*' date.
* without altering the file name.
Just pass the '*Subject*' argument.
```
import datetime
import os
import win32com.client
path = os.path.expanduser("~/Desktop/Att... | ```
import win32com.client #pip install pypiwin32 to work with windows operating sysytm
import datetime
import os
# To get today's date in 'day-month-year' format(01-12-2017).
dateToday=datetime.datetime.today()
FormatedDate=('{:02d}'.format(dateToday.day)+'-'+'{:02d}'.format(dateToday.month)+'-'+'{:04d}'.format(dateT... |
39,656,433 | I need to download incoming attachment without past attachment from mail using Python Script.
For example:If anyone send mail at this time(now) then just download that attachment only into local drive not past attachments.
Please anyone help me to download attachment using python script or java. | 2016/09/23 | [
"https://Stackoverflow.com/questions/39656433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5693776/"
] | ```
import win32com.client #pip install pypiwin32 to work with windows operating sysytm
import datetime
import os
# To get today's date in 'day-month-year' format(01-12-2017).
dateToday=datetime.datetime.today()
FormatedDate=('{:02d}'.format(dateToday.day)+'-'+'{:02d}'.format(dateToday.month)+'-'+'{:04d}'.format(dateT... | If you want to download the attachment from the outlook application from a particular sender and with a specific subject. The below code may be helpful.
```
import win32com.client
import os
from datetime import datetime, timedelta
outlook = win32com.client.Dispatch('outlook.application')
mapi = outlook.GetNamespace("M... |
39,656,433 | I need to download incoming attachment without past attachment from mail using Python Script.
For example:If anyone send mail at this time(now) then just download that attachment only into local drive not past attachments.
Please anyone help me to download attachment using python script or java. | 2016/09/23 | [
"https://Stackoverflow.com/questions/39656433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5693776/"
] | The below code helps by downloading the attachments from outlook emails that are
* '*Unread*' (and changes the mail to Read.) or from '*Today's*' date.
* without altering the file name.
Just pass the '*Subject*' argument.
```
import datetime
import os
import win32com.client
path = os.path.expanduser("~/Desktop/Att... | If you want to download the attachment from the outlook application from a particular sender and with a specific subject. The below code may be helpful.
```
import win32com.client
import os
from datetime import datetime, timedelta
outlook = win32com.client.Dispatch('outlook.application')
mapi = outlook.GetNamespace("M... |
70,580,711 | How can I change my slurm script below so that each python job gets a unique GPU? The node had 4 GPUs, I would like to run 1 python job per each GPU.
The problem is that all jobs use the first GPU and other GPUs are idle.
```
#!/bin/bash
#SBATCH --qos=maxjobs
#SBATCH -N 1
#SBATCH --exclusive
for i in `seq 0 3`; do
... | 2022/01/04 | [
"https://Stackoverflow.com/questions/70580711",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7242276/"
] | If the solution proposed by @Iagows doesn't work for you, have a look at this:
[flutter\_launcher\_icons-issues](https://github.com/fluttercommunity/flutter_launcher_icons/issues/324#issuecomment-1005736502) | The issue is explained in the readme of the plugin, section "Dependency incompatible". It says
```
Because flutter_launcher_icons >=0.9.0 depends on args 2.0.0 and flutter_native_splash 1.2.0 depends on args ^2.1.1, flutter_launcher_icons >=0.9.0 is incompatible with flutter_native_splash 1.2.0.
And because no version... |
70,580,711 | How can I change my slurm script below so that each python job gets a unique GPU? The node had 4 GPUs, I would like to run 1 python job per each GPU.
The problem is that all jobs use the first GPU and other GPUs are idle.
```
#!/bin/bash
#SBATCH --qos=maxjobs
#SBATCH -N 1
#SBATCH --exclusive
for i in `seq 0 3`; do
... | 2022/01/04 | [
"https://Stackoverflow.com/questions/70580711",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7242276/"
] | Inside file: ~/flutter/.pub-cache/hosted/pub.dartlang.org/flutter\_launcher\_icons-0.9.2/lib/android.dart
Replace Line:
```
final String minSdk = line.replaceAll(RegExp(r'[^\d]'), '');
To this:
final String minSdk = "21"; // line.replaceAll(RegExp(r'[^\d]'), '');
```
Save the file and then run:
```
flutter ... | The issue is explained in the readme of the plugin, section "Dependency incompatible". It says
```
Because flutter_launcher_icons >=0.9.0 depends on args 2.0.0 and flutter_native_splash 1.2.0 depends on args ^2.1.1, flutter_launcher_icons >=0.9.0 is incompatible with flutter_native_splash 1.2.0.
And because no version... |
70,580,711 | How can I change my slurm script below so that each python job gets a unique GPU? The node had 4 GPUs, I would like to run 1 python job per each GPU.
The problem is that all jobs use the first GPU and other GPUs are idle.
```
#!/bin/bash
#SBATCH --qos=maxjobs
#SBATCH -N 1
#SBATCH --exclusive
for i in `seq 0 3`; do
... | 2022/01/04 | [
"https://Stackoverflow.com/questions/70580711",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7242276/"
] | Thanks to this [answer](https://github.com/fluttercommunity/flutter_launcher_icons/issues/324#issuecomment-1057617130), I was able to fix the issue! | The issue is explained in the readme of the plugin, section "Dependency incompatible". It says
```
Because flutter_launcher_icons >=0.9.0 depends on args 2.0.0 and flutter_native_splash 1.2.0 depends on args ^2.1.1, flutter_launcher_icons >=0.9.0 is incompatible with flutter_native_splash 1.2.0.
And because no version... |
70,580,711 | How can I change my slurm script below so that each python job gets a unique GPU? The node had 4 GPUs, I would like to run 1 python job per each GPU.
The problem is that all jobs use the first GPU and other GPUs are idle.
```
#!/bin/bash
#SBATCH --qos=maxjobs
#SBATCH -N 1
#SBATCH --exclusive
for i in `seq 0 3`; do
... | 2022/01/04 | [
"https://Stackoverflow.com/questions/70580711",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7242276/"
] | Thanks to this [answer](https://github.com/fluttercommunity/flutter_launcher_icons/issues/324#issuecomment-1057617130), I was able to fix the issue! | Inside file: ~/flutter/.pub-cache/hosted/pub.dartlang.org/flutter\_launcher\_icons-0.9.2/lib/android.dart
Replace Line:
```
final String minSdk = line.replaceAll(RegExp(r'[^\d]'), '');
To this:
final String minSdk = "21"; // line.replaceAll(RegExp(r'[^\d]'), '');
```
Save the file and then run:
```
flutter ... |
70,580,711 | How can I change my slurm script below so that each python job gets a unique GPU? The node had 4 GPUs, I would like to run 1 python job per each GPU.
The problem is that all jobs use the first GPU and other GPUs are idle.
```
#!/bin/bash
#SBATCH --qos=maxjobs
#SBATCH -N 1
#SBATCH --exclusive
for i in `seq 0 3`; do
... | 2022/01/04 | [
"https://Stackoverflow.com/questions/70580711",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7242276/"
] | I just had the same problem and solved doing this in `android/app/build.gradle`.
Changed:
```
minSdkVersion flutter.minSdkVersion
targetSdkVersion flutter.targetSdkVersion
```
To:
```
minSdkVersion 26
targetSdkVersion 30
```
[Source](https://github.com/fluttercommunity/flutter_launcher_icons/issues/88)
[Edit]
A... | Thanks to this [answer](https://github.com/fluttercommunity/flutter_launcher_icons/issues/324#issuecomment-1057617130), I was able to fix the issue! |
70,580,711 | How can I change my slurm script below so that each python job gets a unique GPU? The node had 4 GPUs, I would like to run 1 python job per each GPU.
The problem is that all jobs use the first GPU and other GPUs are idle.
```
#!/bin/bash
#SBATCH --qos=maxjobs
#SBATCH -N 1
#SBATCH --exclusive
for i in `seq 0 3`; do
... | 2022/01/04 | [
"https://Stackoverflow.com/questions/70580711",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7242276/"
] | I just had the same problem and solved doing this in `android/app/build.gradle`.
Changed:
```
minSdkVersion flutter.minSdkVersion
targetSdkVersion flutter.targetSdkVersion
```
To:
```
minSdkVersion 26
targetSdkVersion 30
```
[Source](https://github.com/fluttercommunity/flutter_launcher_icons/issues/88)
[Edit]
A... | The issue is explained in the readme of the plugin, section "Dependency incompatible". It says
```
Because flutter_launcher_icons >=0.9.0 depends on args 2.0.0 and flutter_native_splash 1.2.0 depends on args ^2.1.1, flutter_launcher_icons >=0.9.0 is incompatible with flutter_native_splash 1.2.0.
And because no version... |
70,580,711 | How can I change my slurm script below so that each python job gets a unique GPU? The node had 4 GPUs, I would like to run 1 python job per each GPU.
The problem is that all jobs use the first GPU and other GPUs are idle.
```
#!/bin/bash
#SBATCH --qos=maxjobs
#SBATCH -N 1
#SBATCH --exclusive
for i in `seq 0 3`; do
... | 2022/01/04 | [
"https://Stackoverflow.com/questions/70580711",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7242276/"
] | Thanks to this [answer](https://github.com/fluttercommunity/flutter_launcher_icons/issues/324#issuecomment-1057617130), I was able to fix the issue! | I just changed the package version in `pubspec.yaml` and that solved the problem for me.
```yaml
dependencies:
flutter_launcher_icons: ^0.10.0
``` |
70,580,711 | How can I change my slurm script below so that each python job gets a unique GPU? The node had 4 GPUs, I would like to run 1 python job per each GPU.
The problem is that all jobs use the first GPU and other GPUs are idle.
```
#!/bin/bash
#SBATCH --qos=maxjobs
#SBATCH -N 1
#SBATCH --exclusive
for i in `seq 0 3`; do
... | 2022/01/04 | [
"https://Stackoverflow.com/questions/70580711",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7242276/"
] | Thanks to this [answer](https://github.com/fluttercommunity/flutter_launcher_icons/issues/324#issuecomment-1057617130), I was able to fix the issue! | If the solution proposed by @Iagows doesn't work for you, have a look at this:
[flutter\_launcher\_icons-issues](https://github.com/fluttercommunity/flutter_launcher_icons/issues/324#issuecomment-1005736502) |
70,580,711 | How can I change my slurm script below so that each python job gets a unique GPU? The node had 4 GPUs, I would like to run 1 python job per each GPU.
The problem is that all jobs use the first GPU and other GPUs are idle.
```
#!/bin/bash
#SBATCH --qos=maxjobs
#SBATCH -N 1
#SBATCH --exclusive
for i in `seq 0 3`; do
... | 2022/01/04 | [
"https://Stackoverflow.com/questions/70580711",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7242276/"
] | I just had the same problem and solved doing this in `android/app/build.gradle`.
Changed:
```
minSdkVersion flutter.minSdkVersion
targetSdkVersion flutter.targetSdkVersion
```
To:
```
minSdkVersion 26
targetSdkVersion 30
```
[Source](https://github.com/fluttercommunity/flutter_launcher_icons/issues/88)
[Edit]
A... | I just changed the package version in `pubspec.yaml` and that solved the problem for me.
```yaml
dependencies:
flutter_launcher_icons: ^0.10.0
``` |
70,580,711 | How can I change my slurm script below so that each python job gets a unique GPU? The node had 4 GPUs, I would like to run 1 python job per each GPU.
The problem is that all jobs use the first GPU and other GPUs are idle.
```
#!/bin/bash
#SBATCH --qos=maxjobs
#SBATCH -N 1
#SBATCH --exclusive
for i in `seq 0 3`; do
... | 2022/01/04 | [
"https://Stackoverflow.com/questions/70580711",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7242276/"
] | I just changed the package version in `pubspec.yaml` and that solved the problem for me.
```yaml
dependencies:
flutter_launcher_icons: ^0.10.0
``` | The issue is explained in the readme of the plugin, section "Dependency incompatible". It says
```
Because flutter_launcher_icons >=0.9.0 depends on args 2.0.0 and flutter_native_splash 1.2.0 depends on args ^2.1.1, flutter_launcher_icons >=0.9.0 is incompatible with flutter_native_splash 1.2.0.
And because no version... |
60,548,289 | I don't know why I am getting this error. Below is the code I am using.
**settings.py**
```
TEMPLATE_DIRS = (os.path.join(os.path.dirname(BASE_DIR), "mysite", "static", "templates"),)
```
**urls.py**
```
from django.urls import path
from django.conf.urls import include, url
from django.contrib.auth import views as... | 2020/03/05 | [
"https://Stackoverflow.com/questions/60548289",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5227269/"
] | The problem comes from the "this" scope.
Either you have to bind the function you're using in the class.
```
constructor( props ){
super( props );
this.resetTimer = this.resetTimer.bind(this);
}
```
A second option is to use arrow functions when you declare your functions in order to maintain the scope of "th... | instead of writing
```
`resetTimer() {
this.setState(initialState);
}`
```
use arrow function
`const resetTimer=()=> {
this.setState(initialState);
}`
this will work |
60,548,289 | I don't know why I am getting this error. Below is the code I am using.
**settings.py**
```
TEMPLATE_DIRS = (os.path.join(os.path.dirname(BASE_DIR), "mysite", "static", "templates"),)
```
**urls.py**
```
from django.urls import path
from django.conf.urls import include, url
from django.contrib.auth import views as... | 2020/03/05 | [
"https://Stackoverflow.com/questions/60548289",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5227269/"
] | instead of writing
```
`resetTimer() {
this.setState(initialState);
}`
```
use arrow function
`const resetTimer=()=> {
this.setState(initialState);
}`
this will work | You have to bind the method call with the event as suggested by other users If you don't bind the method, It will be always be called with the re-render
First approach
Inside constructor
`this.methodName = this.bind.methodName(this);`
Inside render()
```
render(){
return(
<button onClick={this.methodName}></button>... |
60,548,289 | I don't know why I am getting this error. Below is the code I am using.
**settings.py**
```
TEMPLATE_DIRS = (os.path.join(os.path.dirname(BASE_DIR), "mysite", "static", "templates"),)
```
**urls.py**
```
from django.urls import path
from django.conf.urls import include, url
from django.contrib.auth import views as... | 2020/03/05 | [
"https://Stackoverflow.com/questions/60548289",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5227269/"
] | The problem comes from the "this" scope.
Either you have to bind the function you're using in the class.
```
constructor( props ){
super( props );
this.resetTimer = this.resetTimer.bind(this);
}
```
A second option is to use arrow functions when you declare your functions in order to maintain the scope of "th... | **second Solution** - this is because you have not bind the function and calling it in the click event
Please refer [Handling events](https://reactjs.org/docs/handling-events.html)
So add this line inside the constructor
```
this.resetTimer = this.resetTimer.bind();
```
I hope this solves your problem :) |
60,548,289 | I don't know why I am getting this error. Below is the code I am using.
**settings.py**
```
TEMPLATE_DIRS = (os.path.join(os.path.dirname(BASE_DIR), "mysite", "static", "templates"),)
```
**urls.py**
```
from django.urls import path
from django.conf.urls import include, url
from django.contrib.auth import views as... | 2020/03/05 | [
"https://Stackoverflow.com/questions/60548289",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5227269/"
] | The problem comes from the "this" scope.
Either you have to bind the function you're using in the class.
```
constructor( props ){
super( props );
this.resetTimer = this.resetTimer.bind(this);
}
```
A second option is to use arrow functions when you declare your functions in order to maintain the scope of "th... | You have to bind the method call with the event as suggested by other users If you don't bind the method, It will be always be called with the re-render
First approach
Inside constructor
`this.methodName = this.bind.methodName(this);`
Inside render()
```
render(){
return(
<button onClick={this.methodName}></button>... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.