qid int64 46k 74.7M | question stringlengths 54 37.8k | date stringlengths 10 10 | metadata listlengths 3 3 | response_j stringlengths 17 26k | response_k stringlengths 26 26k |
|---|---|---|---|---|---|
4,135,261 | I am having a problem connecting to a device with a Paramiko (version 1.7.6-2) ssh client:
```
$ python
Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import paramiko
>>> ssh = paramiko.SSHClient()
>>> ssh.set_missing_h... | 2010/11/09 | [
"https://Stackoverflow.com/questions/4135261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/197108/"
] | It's really a old and remote issue, but I just got the same error and I think It'll be helpful to list the following info:
1. I'm using paramiko 2.9.1 and python>=3.6, make sure your paramiko>=2.9.0
2. cmd `ssh <hostname>` works fine
3. Code below get error: `AuthenticationException: Authentication failed.`
```
impor... | Make sure that the permissions on the public and private key files (and possibly the containing folder) are set to very restrictive (i.e. chmod 600 id\_rsa). It turns out this is required (by the Operating System?) to use the files as ssh keys. Found this out from my helpful colleague :)
Also make sure that you are usi... |
4,135,261 | I am having a problem connecting to a device with a Paramiko (version 1.7.6-2) ssh client:
```
$ python
Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import paramiko
>>> ssh = paramiko.SSHClient()
>>> ssh.set_missing_h... | 2010/11/09 | [
"https://Stackoverflow.com/questions/4135261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/197108/"
] | As a very late follow-up on this matter, I believe I was running into the same issue as waffleman, in a context of a confined network.
The hint about using `auth_none` on the `Transport` object turned out quite helpful, but I found myself a little puzzled as to how to implement that. Thing is, as of today at least, I ... | There could be different reasons on **server** side (sshd where you're connecting to), so it might be hard to debug on client side.
For example, `tail -f /var/log/secure` :
>
> Oct 9 15:50:26 pc1udatahgw04 sshd[27501]: Authentication refused: bad
> ownership or modes for directory /home/testuser
>
>
>
If you r... |
4,135,261 | I am having a problem connecting to a device with a Paramiko (version 1.7.6-2) ssh client:
```
$ python
Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import paramiko
>>> ssh = paramiko.SSHClient()
>>> ssh.set_missing_h... | 2010/11/09 | [
"https://Stackoverflow.com/questions/4135261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/197108/"
] | The ssh server on the remote device denied your authentication. Make sure you're using the correct key, the public key is present in `authorized_keys`, `.ssh` directory permissions are correct, `authorized_keys` permissions are correct, and the device doesn't have any other access restrictions. It hard to say what's go... | [paramiko's SSHClient](http://www.lag.net/paramiko/docs/paramiko.SSHClient-class.html) has [`load_system_host_keys`](http://www.lag.net/paramiko/docs/paramiko.SSHClient-class.html#load_system_host_keys) method which you could use to load user specific set of keys. As example in the docs explain, it needs to be run befo... |
4,135,261 | I am having a problem connecting to a device with a Paramiko (version 1.7.6-2) ssh client:
```
$ python
Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import paramiko
>>> ssh = paramiko.SSHClient()
>>> ssh.set_missing_h... | 2010/11/09 | [
"https://Stackoverflow.com/questions/4135261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/197108/"
] | Make sure that the permissions on the public and private key files (and possibly the containing folder) are set to very restrictive (i.e. chmod 600 id\_rsa). It turns out this is required (by the Operating System?) to use the files as ssh keys. Found this out from my helpful colleague :)
Also make sure that you are usi... | you may need to check log in server, try to excute `tail -f /var/log/auth.log` then you may find the reason why server refuses your connection.
If server shows like this `userauth_pubkey: unsupported public key algorithm: rsa-sha2-512 [preauth]`, then you can add `transport.server_extensions = {'server-sig-algs': 'ssh-... |
4,135,261 | I am having a problem connecting to a device with a Paramiko (version 1.7.6-2) ssh client:
```
$ python
Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import paramiko
>>> ssh = paramiko.SSHClient()
>>> ssh.set_missing_h... | 2010/11/09 | [
"https://Stackoverflow.com/questions/4135261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/197108/"
] | The ssh server on the remote device denied your authentication. Make sure you're using the correct key, the public key is present in `authorized_keys`, `.ssh` directory permissions are correct, `authorized_keys` permissions are correct, and the device doesn't have any other access restrictions. It hard to say what's go... | venv installation also makes global files
-----------------------------------------
Installing paramiko in a venv installs files both in the venv and in the global environment. Using paramiko in that venv only does not seem to work.
In codium / vscode, be in a folder that has no access to the venv and then use parami... |
4,135,261 | I am having a problem connecting to a device with a Paramiko (version 1.7.6-2) ssh client:
```
$ python
Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import paramiko
>>> ssh = paramiko.SSHClient()
>>> ssh.set_missing_h... | 2010/11/09 | [
"https://Stackoverflow.com/questions/4135261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/197108/"
] | As a very late follow-up on this matter, I believe I was running into the same issue as waffleman, in a context of a confined network.
The hint about using `auth_none` on the `Transport` object turned out quite helpful, but I found myself a little puzzled as to how to implement that. Thing is, as of today at least, I ... | Make sure that the permissions on the public and private key files (and possibly the containing folder) are set to very restrictive (i.e. chmod 600 id\_rsa). It turns out this is required (by the Operating System?) to use the files as ssh keys. Found this out from my helpful colleague :)
Also make sure that you are usi... |
4,135,261 | I am having a problem connecting to a device with a Paramiko (version 1.7.6-2) ssh client:
```
$ python
Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import paramiko
>>> ssh = paramiko.SSHClient()
>>> ssh.set_missing_h... | 2010/11/09 | [
"https://Stackoverflow.com/questions/4135261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/197108/"
] | Make sure that the permissions on the public and private key files (and possibly the containing folder) are set to very restrictive (i.e. chmod 600 id\_rsa). It turns out this is required (by the Operating System?) to use the files as ssh keys. Found this out from my helpful colleague :)
Also make sure that you are usi... | venv installation also makes global files
-----------------------------------------
Installing paramiko in a venv installs files both in the venv and in the global environment. Using paramiko in that venv only does not seem to work.
In codium / vscode, be in a folder that has no access to the venv and then use parami... |
73,353,608 | My script takes `-d`, `--delimiter` as argument:
```
parser.add_argument('-d', '--delimiter')
```
but when I pass it `--` as delimiter, it is empty
```
script.py --delimiter='--'
```
I know `--` is special in argument/parameter parsing, but I am using it in the form `--option='--'` and quoted.
Why does it not w... | 2022/08/14 | [
"https://Stackoverflow.com/questions/73353608",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7287412/"
] | Existing bug report
-------------------
Patches have been suggested, but it hasn't been applied. [Argparse incorrectly handles '--' as argument to option](https://github.com/python/cpython/issues/58572)
Some simple examples:
---------------------
```
In [1]: import argparse
In [2]: p = argparse.ArgumentParser()
In [... | It calls `parse_args` which calls `parse_known_args` which calls `_parse_known_args`.
Then, on line 2078 (or something similar), it does this (inside a while loop going through the string):
```py
start_index = consume_optional(start_index)
```
which calls the `consume_optional` (which makes sense, because this is a... |
73,353,608 | My script takes `-d`, `--delimiter` as argument:
```
parser.add_argument('-d', '--delimiter')
```
but when I pass it `--` as delimiter, it is empty
```
script.py --delimiter='--'
```
I know `--` is special in argument/parameter parsing, but I am using it in the form `--option='--'` and quoted.
Why does it not w... | 2022/08/14 | [
"https://Stackoverflow.com/questions/73353608",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7287412/"
] | This looks like a bug. You should report it.
[This code](https://github.com/python/cpython/blob/3.10/Lib/argparse.py#L2422-L2426) in `argparse.py` is the start of `_get_values`, one of the primary helper functions for parsing values:
```
if action.nargs not in [PARSER, REMAINDER]:
try:
arg_strings.remove(... | Existing bug report
-------------------
Patches have been suggested, but it hasn't been applied. [Argparse incorrectly handles '--' as argument to option](https://github.com/python/cpython/issues/58572)
Some simple examples:
---------------------
```
In [1]: import argparse
In [2]: p = argparse.ArgumentParser()
In [... |
73,353,608 | My script takes `-d`, `--delimiter` as argument:
```
parser.add_argument('-d', '--delimiter')
```
but when I pass it `--` as delimiter, it is empty
```
script.py --delimiter='--'
```
I know `--` is special in argument/parameter parsing, but I am using it in the form `--option='--'` and quoted.
Why does it not w... | 2022/08/14 | [
"https://Stackoverflow.com/questions/73353608",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7287412/"
] | This looks like a bug. You should report it.
[This code](https://github.com/python/cpython/blob/3.10/Lib/argparse.py#L2422-L2426) in `argparse.py` is the start of `_get_values`, one of the primary helper functions for parsing values:
```
if action.nargs not in [PARSER, REMAINDER]:
try:
arg_strings.remove(... | It calls `parse_args` which calls `parse_known_args` which calls `_parse_known_args`.
Then, on line 2078 (or something similar), it does this (inside a while loop going through the string):
```py
start_index = consume_optional(start_index)
```
which calls the `consume_optional` (which makes sense, because this is a... |
18,219,529 | In python, logging to syslog is fairly trivial:
```
syslog.openlog("ident")
syslog.syslog(0, "spilled beer on server")
syslog.closelog()
```
Is there an equivalently simple way in Java? After quite a bit of googling, I've been unable to find an easy to understand method that doesn't require reconfiguring rsyslogd or... | 2013/08/13 | [
"https://Stackoverflow.com/questions/18219529",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/643675/"
] | One way to go direct to the log without udp is with [syslog4j](http://www.syslog4j.org/). I wouldn't necessarily say it's simple, but it doesn't require reconfiguring syslog, at least. | The closest I can think of, would be using [Log4J](https://logging.apache.org/log4j/) and configuring the [SyslogAppender](https://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/net/SyslogAppender.html) so it writes to syslog. Sorry, that's not as easy as in Python! |
18,219,529 | In python, logging to syslog is fairly trivial:
```
syslog.openlog("ident")
syslog.syslog(0, "spilled beer on server")
syslog.closelog()
```
Is there an equivalently simple way in Java? After quite a bit of googling, I've been unable to find an easy to understand method that doesn't require reconfiguring rsyslogd or... | 2013/08/13 | [
"https://Stackoverflow.com/questions/18219529",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/643675/"
] | The closest I can think of, would be using [Log4J](https://logging.apache.org/log4j/) and configuring the [SyslogAppender](https://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/net/SyslogAppender.html) so it writes to syslog. Sorry, that's not as easy as in Python! | This is the simplest client code I could think of:
```
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
// java Syslog localhost "Hello world"
public class Syslog {
public static void main(String[] args) throws Exception {
InetAddress address = InetAddress.getByName(a... |
18,219,529 | In python, logging to syslog is fairly trivial:
```
syslog.openlog("ident")
syslog.syslog(0, "spilled beer on server")
syslog.closelog()
```
Is there an equivalently simple way in Java? After quite a bit of googling, I've been unable to find an easy to understand method that doesn't require reconfiguring rsyslogd or... | 2013/08/13 | [
"https://Stackoverflow.com/questions/18219529",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/643675/"
] | One way to go direct to the log without udp is with [syslog4j](http://www.syslog4j.org/). I wouldn't necessarily say it's simple, but it doesn't require reconfiguring syslog, at least. | This is the simplest client code I could think of:
```
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
// java Syslog localhost "Hello world"
public class Syslog {
public static void main(String[] args) throws Exception {
InetAddress address = InetAddress.getByName(a... |
48,102,393 | I have 1000 files each having one million lines. Each line has the following form:
```
a number,a text
```
I want to remove all of the numbers from the beginning of every line of every file. including the ,
Example:
```
14671823,aboasdyflj -> aboasdyflj
```
What I'm doing is:
```
os.system("sed -i -- 's/^.*,//g... | 2018/01/04 | [
"https://Stackoverflow.com/questions/48102393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5120089/"
] | This is much faster:
```
cut -f2 -d ',' data.txt > tmp.txt && mv tmp.txt data.txt
```
On a file with 11 million rows it took less than one second.
To use this on several files in a directory, use:
```sh
TMP=/pathto/tmpfile
for file in dir/*; do
cut -f2 -d ',' "$file" > $TMP && mv $TMP "$file"
done
```
A thin... | I would use GNU `awk` (to leverage the `-i inplace` editing of file) with `,` as the field separator, *no expensive Regex manipulation*:
```
awk -F, -i inplace '{print $2}' file.txt
```
For example, if the filenames have a common prefix like `file`, you can use shell globbing:
```
awk -F, -i inplace '{print $2}' fi... |
48,102,393 | I have 1000 files each having one million lines. Each line has the following form:
```
a number,a text
```
I want to remove all of the numbers from the beginning of every line of every file. including the ,
Example:
```
14671823,aboasdyflj -> aboasdyflj
```
What I'm doing is:
```
os.system("sed -i -- 's/^.*,//g... | 2018/01/04 | [
"https://Stackoverflow.com/questions/48102393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5120089/"
] | This is much faster:
```
cut -f2 -d ',' data.txt > tmp.txt && mv tmp.txt data.txt
```
On a file with 11 million rows it took less than one second.
To use this on several files in a directory, use:
```sh
TMP=/pathto/tmpfile
for file in dir/*; do
cut -f2 -d ',' "$file" > $TMP && mv $TMP "$file"
done
```
A thin... | You can take advantage of your multicore system, along with the tips of other users on handling a specific file faster.
```
FILES = ['a', 'b', 'c', 'd']
CORES = 4
q = multiprocessing.Queue(len(FILES))
for f in FILES:
q.put(f)
def handler(q, i):
while True:
try:
f = q.get(block=False)
... |
48,102,393 | I have 1000 files each having one million lines. Each line has the following form:
```
a number,a text
```
I want to remove all of the numbers from the beginning of every line of every file. including the ,
Example:
```
14671823,aboasdyflj -> aboasdyflj
```
What I'm doing is:
```
os.system("sed -i -- 's/^.*,//g... | 2018/01/04 | [
"https://Stackoverflow.com/questions/48102393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5120089/"
] | This is much faster:
```
cut -f2 -d ',' data.txt > tmp.txt && mv tmp.txt data.txt
```
On a file with 11 million rows it took less than one second.
To use this on several files in a directory, use:
```sh
TMP=/pathto/tmpfile
for file in dir/*; do
cut -f2 -d ',' "$file" > $TMP && mv $TMP "$file"
done
```
A thin... | that's probably pretty fast & native python. Reduced loops and using `csv.reader` & `csv.writer` which are compiled in most implementations:
```
import csv,os,glob
for f1 in glob.glob("*.txt"):
f2 = f1+".new"
with open(f1) as fr, open(f2,"w",newline="") as fw:
csv.writer(fw).writerows(x[1] for x in csv... |
48,102,393 | I have 1000 files each having one million lines. Each line has the following form:
```
a number,a text
```
I want to remove all of the numbers from the beginning of every line of every file. including the ,
Example:
```
14671823,aboasdyflj -> aboasdyflj
```
What I'm doing is:
```
os.system("sed -i -- 's/^.*,//g... | 2018/01/04 | [
"https://Stackoverflow.com/questions/48102393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5120089/"
] | I would use GNU `awk` (to leverage the `-i inplace` editing of file) with `,` as the field separator, *no expensive Regex manipulation*:
```
awk -F, -i inplace '{print $2}' file.txt
```
For example, if the filenames have a common prefix like `file`, you can use shell globbing:
```
awk -F, -i inplace '{print $2}' fi... | You can take advantage of your multicore system, along with the tips of other users on handling a specific file faster.
```
FILES = ['a', 'b', 'c', 'd']
CORES = 4
q = multiprocessing.Queue(len(FILES))
for f in FILES:
q.put(f)
def handler(q, i):
while True:
try:
f = q.get(block=False)
... |
48,102,393 | I have 1000 files each having one million lines. Each line has the following form:
```
a number,a text
```
I want to remove all of the numbers from the beginning of every line of every file. including the ,
Example:
```
14671823,aboasdyflj -> aboasdyflj
```
What I'm doing is:
```
os.system("sed -i -- 's/^.*,//g... | 2018/01/04 | [
"https://Stackoverflow.com/questions/48102393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5120089/"
] | that's probably pretty fast & native python. Reduced loops and using `csv.reader` & `csv.writer` which are compiled in most implementations:
```
import csv,os,glob
for f1 in glob.glob("*.txt"):
f2 = f1+".new"
with open(f1) as fr, open(f2,"w",newline="") as fw:
csv.writer(fw).writerows(x[1] for x in csv... | You can take advantage of your multicore system, along with the tips of other users on handling a specific file faster.
```
FILES = ['a', 'b', 'c', 'd']
CORES = 4
q = multiprocessing.Queue(len(FILES))
for f in FILES:
q.put(f)
def handler(q, i):
while True:
try:
f = q.get(block=False)
... |
61,380,617 | when I'm trying open a website with urllib library I'm getting the error. I'm not getting why this error occurs? currently I'm using python 3.6 version. Is this problem with version?
```
url = 'https://example.com'
html = urllib.request.urlopen(url).read().decode('utf-8')
text = get_text(html)
data = text.split()
prin... | 2020/04/23 | [
"https://Stackoverflow.com/questions/61380617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13139499/"
] | You should not have duplicate column names in the dataframe, we correct that using `make.unique`.
```
names(df) <- make.unique(names(df))
```
We can then remove empty rows and get data in long format using `pivot_longer`.
```
library(dplyr)
library(tidyr)
df %>%
filter(orig != '' | dest != '') %>%
pivot_longe... | a `data.table` solution. You might need to play around the `year`. As `melt` now in `data.table` cannot handle the `year` in your question correctly. I guess `pivot_longer` from `tidyr` can do this in one shot.
```r
library(data.table)
df <- fread('orig dest cartrip cartrip cartrip cartrip cartrip walking walki... |
15,118,974 | I'm trying to learn ruby, so I'm following an exercise of google dev. I'm trying to parse some links. In the case of successful redirection (considering that I know that it its possible only to get redirected once), I get redirect forbidden. I noticed that I go from a http protocol link to an https protocol link. Any c... | 2013/02/27 | [
"https://Stackoverflow.com/questions/15118974",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1388172/"
] | Ruby's [OpenURI](http://www.ruby-doc.org/stdlib-1.9.3/libdoc/open-uri/rdoc/OpenURI.html) will automatically handle redirects for you, as long as they're not "[meta-refresh](http://en.wikipedia.org/wiki/Meta_refresh)" that occur inside the HTML itself.
For instance, this follows a redirect automatically:
```
irb(main... | Basically the url in code.google that you're trying to open redirects to a https url. You can see that by yourself if you paste `http://code.google.com/edu/languages/google-python-class/images/puzzle/p-bija-baei.jpg` into your browser
Check the following [bug report](http://bugs.ruby-lang.org/issues/859) that explains... |
29,656,173 | I'm a student doing a computer science course and for part of the assessment we have to write a program that will take 10 digits from the user and used them to calculate an 11th number in order to produce an ISBN. The numbers that the user inputs HAVE to be limited to one digit, and an error message should be displayed... | 2015/04/15 | [
"https://Stackoverflow.com/questions/29656173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4678142/"
] | You have to convert the int to a string because int does not have a length property. Also You were checking if the digit was longer than 1 for a twice so I switched the SECOND NUMBER check to b
```
print('Please enter your 10 digit number')
a = raw_input("FIRST NUMBER: ")
if len(a) > 1:
print ("Error. Only 1 digit... | Firstly, I'm assuming you are using 3.x. Secondly, if you are using 2.x, you can't use `len` on numbers.
This is what I would suggest:
```
print('Please enter your 10 digit number')
number = ''
for x in range(1,11):
digit = input('Please enter digit ' + str(x) + ': ')
while len(digit) != 1:
# digit ... |
29,656,173 | I'm a student doing a computer science course and for part of the assessment we have to write a program that will take 10 digits from the user and used them to calculate an 11th number in order to produce an ISBN. The numbers that the user inputs HAVE to be limited to one digit, and an error message should be displayed... | 2015/04/15 | [
"https://Stackoverflow.com/questions/29656173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4678142/"
] | You have to convert the int to a string because int does not have a length property. Also You were checking if the digit was longer than 1 for a twice so I switched the SECOND NUMBER check to b
```
print('Please enter your 10 digit number')
a = raw_input("FIRST NUMBER: ")
if len(a) > 1:
print ("Error. Only 1 digit... | You never stated if you're on Windows or Linux, the code listed below is for Windows (as I'm on a Windows machine right now and can't test the equivalent on Linux).
```
# For windows
import msvcrt
print('Please enter your 10 digit number')
print('First number: ')
a = int(msvcrt.getch())
print(a)
```
The `.getch()` c... |
29,656,173 | I'm a student doing a computer science course and for part of the assessment we have to write a program that will take 10 digits from the user and used them to calculate an 11th number in order to produce an ISBN. The numbers that the user inputs HAVE to be limited to one digit, and an error message should be displayed... | 2015/04/15 | [
"https://Stackoverflow.com/questions/29656173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4678142/"
] | You have to convert the int to a string because int does not have a length property. Also You were checking if the digit was longer than 1 for a twice so I switched the SECOND NUMBER check to b
```
print('Please enter your 10 digit number')
a = raw_input("FIRST NUMBER: ")
if len(a) > 1:
print ("Error. Only 1 digit... | I suggest creating a function to handle of of the prompting, then call it in your code. Here is a simplfied example:
```
def single_num(prompt):
num = ""
while True:
num = raw_input(prompt)
if len(num) == 1:
try:
return int(num)
except ValueError:
... |
29,656,173 | I'm a student doing a computer science course and for part of the assessment we have to write a program that will take 10 digits from the user and used them to calculate an 11th number in order to produce an ISBN. The numbers that the user inputs HAVE to be limited to one digit, and an error message should be displayed... | 2015/04/15 | [
"https://Stackoverflow.com/questions/29656173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4678142/"
] | You have to convert the int to a string because int does not have a length property. Also You were checking if the digit was longer than 1 for a twice so I switched the SECOND NUMBER check to b
```
print('Please enter your 10 digit number')
a = raw_input("FIRST NUMBER: ")
if len(a) > 1:
print ("Error. Only 1 digit... | This is probably *cleanest* to do with a validation wrapper.
```
def validator(testfunc):
def wrap(func):
def wrapped(*args, **kwargs):
result = func(*args, **kwargs)
pass, *failfunc = testfunc(result)
it pass:
return result
elif failfunc:
... |
66,533,544 | ```
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-1-b7eb239f86a7> in <module>
1 # Initialize path to SQLite database
2 path = 'data/classic_rock.db'
----> 3 con = sq3.Connection(path)
... | 2021/03/08 | [
"https://Stackoverflow.com/questions/66533544",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14204983/"
] | It looks like from the traceback that you are attempting to use `sq3` and you either did not `import` the library or did not correctly alias the library in question. Cannot know for sure without your code though. | 'sq3' is not defined
That's why. Somewhere in your code you're expecting a variable called sql3 but it doesn't exist. |
36,467,658 | I installed firewalld on my centos server but as I tried to start it I got this:
```
$ sudo systemctl start firewalld
Job for firewalld.service failed. See 'systemctl status firewalld.service' and 'journalctl -xn' for details.
```
here is the systemctl status:
```
sudo systemctl status firewalld
firewalld.service -... | 2016/04/07 | [
"https://Stackoverflow.com/questions/36467658",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3383936/"
] | This worked for me:
```
systemctl stop firewalld
pkill -f firewalld
systemctl start firewalld
``` | I know that it is an old thread , But I was facing this problem and I just fixed it, Figured it will help someone in the nearby future.
I thought the problem was in my code or that I mis placed the file.
Well , sadly This file is corrupted (perhaps misplaced)
`/usr/lib/python2.7/site-packages/gi/_gi.so` or I think ... |
36,467,658 | I installed firewalld on my centos server but as I tried to start it I got this:
```
$ sudo systemctl start firewalld
Job for firewalld.service failed. See 'systemctl status firewalld.service' and 'journalctl -xn' for details.
```
here is the systemctl status:
```
sudo systemctl status firewalld
firewalld.service -... | 2016/04/07 | [
"https://Stackoverflow.com/questions/36467658",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3383936/"
] | I know that it is an old thread , But I was facing this problem and I just fixed it, Figured it will help someone in the nearby future.
I thought the problem was in my code or that I mis placed the file.
Well , sadly This file is corrupted (perhaps misplaced)
`/usr/lib/python2.7/site-packages/gi/_gi.so` or I think ... | The problem is your package `/usr/lib/python2.7/site-packages/gi/_gi.so`
```
Debian (python2) -> sudo apt install python-gi
Debian (python3) -> sudo apt install python3-gi
```
RedHat based systems -> `yum install gilb2`
Note : for OverWrite and fix you can use:
-> `yum update glib2` |
36,467,658 | I installed firewalld on my centos server but as I tried to start it I got this:
```
$ sudo systemctl start firewalld
Job for firewalld.service failed. See 'systemctl status firewalld.service' and 'journalctl -xn' for details.
```
here is the systemctl status:
```
sudo systemctl status firewalld
firewalld.service -... | 2016/04/07 | [
"https://Stackoverflow.com/questions/36467658",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3383936/"
] | I know that it is an old thread , But I was facing this problem and I just fixed it, Figured it will help someone in the nearby future.
I thought the problem was in my code or that I mis placed the file.
Well , sadly This file is corrupted (perhaps misplaced)
`/usr/lib/python2.7/site-packages/gi/_gi.so` or I think ... | You should try restarting the dbus service:
```
$ sudo systemctl restart dbus
$ sudo systemctl restart firewalld
``` |
36,467,658 | I installed firewalld on my centos server but as I tried to start it I got this:
```
$ sudo systemctl start firewalld
Job for firewalld.service failed. See 'systemctl status firewalld.service' and 'journalctl -xn' for details.
```
here is the systemctl status:
```
sudo systemctl status firewalld
firewalld.service -... | 2016/04/07 | [
"https://Stackoverflow.com/questions/36467658",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3383936/"
] | This worked for me:
```
systemctl stop firewalld
pkill -f firewalld
systemctl start firewalld
``` | The problem is your package `/usr/lib/python2.7/site-packages/gi/_gi.so`
```
Debian (python2) -> sudo apt install python-gi
Debian (python3) -> sudo apt install python3-gi
```
RedHat based systems -> `yum install gilb2`
Note : for OverWrite and fix you can use:
-> `yum update glib2` |
36,467,658 | I installed firewalld on my centos server but as I tried to start it I got this:
```
$ sudo systemctl start firewalld
Job for firewalld.service failed. See 'systemctl status firewalld.service' and 'journalctl -xn' for details.
```
here is the systemctl status:
```
sudo systemctl status firewalld
firewalld.service -... | 2016/04/07 | [
"https://Stackoverflow.com/questions/36467658",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3383936/"
] | This worked for me:
```
systemctl stop firewalld
pkill -f firewalld
systemctl start firewalld
``` | You should try restarting the dbus service:
```
$ sudo systemctl restart dbus
$ sudo systemctl restart firewalld
``` |
38,282,659 | I have two data points `x` and `y`:
```
x = 5 (value corresponding to 95%)
y = 17 (value corresponding to 102.5%)
```
No I would like to calculate the value for `xi` which should correspond to 100%.
```
x = 5 (value corresponding to 95%)
xi = ?? (value corresponding to 100%)
y = 17 (value corresponding to 1... | 2016/07/09 | [
"https://Stackoverflow.com/questions/38282659",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6306448/"
] | is that what you want?
```
In [145]: s = pd.Series([5, np.nan, 17], index=[95, 100, 102.5])
In [146]: s
Out[146]:
95.0 5.0
100.0 NaN
102.5 17.0
dtype: float64
In [147]: s.interpolate(method='index')
Out[147]:
95.0 5.0
100.0 13.0
102.5 17.0
dtype: float64
``` | We can easily plot this on a graph without Python:
[](https://i.stack.imgur.com/PW6fy.png)
This shows us what the answer should be (13).
But how do we calculate this? First, we find the gradient with this:
[](https://i.stack.imgur.com/... |
38,282,659 | I have two data points `x` and `y`:
```
x = 5 (value corresponding to 95%)
y = 17 (value corresponding to 102.5%)
```
No I would like to calculate the value for `xi` which should correspond to 100%.
```
x = 5 (value corresponding to 95%)
xi = ?? (value corresponding to 100%)
y = 17 (value corresponding to 1... | 2016/07/09 | [
"https://Stackoverflow.com/questions/38282659",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6306448/"
] | is that what you want?
```
In [145]: s = pd.Series([5, np.nan, 17], index=[95, 100, 102.5])
In [146]: s
Out[146]:
95.0 5.0
100.0 NaN
102.5 17.0
dtype: float64
In [147]: s.interpolate(method='index')
Out[147]:
95.0 5.0
100.0 13.0
102.5 17.0
dtype: float64
``` | You can use [numpy.interp](https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.interp.html) function to interpolate a value
```
import numpy as np
import matplotlib.pyplot as plt
x = [95, 102.5]
y = [5, 17]
x_new = 100
y_new = np.interp(x_new, x, y)
print(y_new)
# 13.0
plt.plot(x, y, "og-", x_new, y_... |
34,778,397 | I am currently creating a music player in python 3.3 and I have a way of opening the mp3/wav files, namely through using through 'os.startfile()', but, this way of running the files means that if I run more than one, the second cancels the first, and the third cancels the second, and so on and so forth, so I only end u... | 2016/01/13 | [
"https://Stackoverflow.com/questions/34778397",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2966288/"
] | i've managed to do this Using an external module, as after ages of trying to do it without any, i gave up and used [tinytag](https://pypi.python.org/pypi/tinytag/), as it is easy to install and use. | Nothing you can do without external libraries, as far as I know. Try using [pymad](http://spacepants.org/src/pymad/).
Use it like this:
```
import mad
SongFile = mad.MadFile("something.mp3")
SongLength = SongFile.total_time()
``` |
22,490,833 | I have this string:
```
Email: promo@elysianrealestate.com
```
I want to get the email address:
### I tried this
```
Email:.*
```
but I got the whole string, not just the email
help please
### i am using scrapy with python | 2014/03/18 | [
"https://Stackoverflow.com/questions/22490833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2038257/"
] | If your string always finish with the email, you use:
```
r'Email:\s*(.*)'
```
I got the idea from [here](http://doc.scrapy.org/en/0.7/topics/selectors.html#using-selectors-with-regular-expressions) but I can't test it as I don't have a scrapy shell availabl at the moment. | This should capture your emails, it ensures that you only capture correctly formed emails:
```
Email:\s+(\b[A-Za-z0-9(._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}\b)
```
Here's how I tested it:
```
>>> import re
>>> txt = """
I have this string:
Email: promo@elysianrealestate.com foo bar baz
I want to get the email addr... |
22,490,833 | I have this string:
```
Email: promo@elysianrealestate.com
```
I want to get the email address:
### I tried this
```
Email:.*
```
but I got the whole string, not just the email
help please
### i am using scrapy with python | 2014/03/18 | [
"https://Stackoverflow.com/questions/22490833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2038257/"
] | If your string always finish with the email, you use:
```
r'Email:\s*(.*)'
```
I got the idea from [here](http://doc.scrapy.org/en/0.7/topics/selectors.html#using-selectors-with-regular-expressions) but I can't test it as I don't have a scrapy shell availabl at the moment. | You need to create a group to mark the text that you want captured. For this, try wrapping the pattern in parenthesis:
```py
r'Email:\s+(.+)'
``` |
22,490,833 | I have this string:
```
Email: promo@elysianrealestate.com
```
I want to get the email address:
### I tried this
```
Email:.*
```
but I got the whole string, not just the email
help please
### i am using scrapy with python | 2014/03/18 | [
"https://Stackoverflow.com/questions/22490833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2038257/"
] | If your string always finish with the email, you use:
```
r'Email:\s*(.*)'
```
I got the idea from [here](http://doc.scrapy.org/en/0.7/topics/selectors.html#using-selectors-with-regular-expressions) but I can't test it as I don't have a scrapy shell availabl at the moment. | As long as you know the ":" will always separate the "Email" from the actual email address, why not try ( for s = "Email: promo@elysianrealestate.com"):
```
emailAddr = s.split(":")[1].strip()
```
If you need to worry about text after the ".com", just try another split on a " " character and then take the first (0th... |
57,854,020 | **My Problem**
I am trying to create a column in python which is the conditional smoothed moving 14 day average of another column. The condition is that I only want to include positive values from another column in the rolling average.
I am currently using the following code which works exactly how I want it to, but ... | 2019/09/09 | [
"https://Stackoverflow.com/questions/57854020",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12041022/"
] | This should speed up your code:
`df['avg_gain'] = df[df['delta'] > 0]['delta'].rolling(14).mean()`
Does your current code converge to zero? If you can provide the data, then it would be easier for the folk to do some analysis. | I would suggest you add a column which is 0 if the value is < 0 and instead has the same value as the one you want to consider if it is >= 0. Then you take the running average of this new column.
```
df['new_col'] = df.apply(lambda x: x['delta'] if x['delta'] >= 0 else 0)
df['avg_gain'] = df['new_value'].rolling(14).m... |
44,934,948 | I try to get all lattitudes and longtitudes from this json.
Code:
```
import urllib.parse
import requests
raw_json = 'http://live.ksmobile.net/live/getreplayvideos?userid='
print()
userid = 735890904669618176
#userid = input('UserID: ')
url = raw_json + urllib.parse.urlencode({'userid=': userid}) + '&page_size=100... | 2017/07/05 | [
"https://Stackoverflow.com/questions/44934948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8258990/"
] | Your URL construction is incorrect. The URL you have built (as shown in the output of your script) is:
```
http://live.ksmobile.net/live/getreplayvideos?userid=userid%3D=735890904669618176&page_size=1000
```
Where you actually want this:
```
http://live.ksmobile.net/live/getreplayvideos?userid=735890904669618176&pa... | According to your posted json, you have problem in this statement-
`print(coordinates['lat'], coordinates['lnt'])`
Here `coordinates` is a list having only one item which is dictionary. So your statement should be-
`print(coordinates[0]['lat'], coordinates[0]['lnt'])` |
63,301,691 | my code works perfectly in Python 3.8, but when I switch to Python 3.5 in same operating system, with same code and everything else, it starts throwing out "SyntaxError: invalid syntax".
Here is the error, and the part of the code that I think which relates to the error :
```
Traceback (most recent call last):
File... | 2020/08/07 | [
"https://Stackoverflow.com/questions/63301691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10214891/"
] | There are at least two issues here:
1. [Variable annotations](https://docs.python.org/3/whatsnew/3.6.html#whatsnew36-pep526) were new in Python 3.6.
2. The [`dataclasses`](https://docs.python.org/3/library/dataclasses.html?highlight=dataclass#module-dataclasses) module was new in Python 3.7.
Either use Python 3.7 or ... | One new and exciting feature coming in Python 3.7 is the data class. you're not able to use it in python 3.5.
You should use the traditional way and use constructor:
```
class Mapping:
def __init__(self, iterable):
self.items_list = []
self.__update(iterable)
def update(self, iterable):
for item in iterab... |
46,366,398 | I am using Pymodm as a mongoDB odm with python flask. I have looked through code and documentation (<https://github.com/mongodb/pymodm> and <http://pymodm.readthedocs.io/en/latest>) but could not find what I was looking for.
I am looking for an easy way to fetch data from the database without converting it to a pymodm... | 2017/09/22 | [
"https://Stackoverflow.com/questions/46366398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3531894/"
] | It is not obvious from the PyMODM documentation, but here's how to do it:
```
pymodm_obj.to_son().to_dict()
```
Actually, I just re-read your question, and I don't think anything is forcing you to use PyMODM everywhere in your project once you have made the decision to use it. So if you are just looking for the JSON... | Having:
```
from pymodm import MongoModel, fields
import json
class Foo(MongoModel):
name = fields.CharField(required=True)
a=Foo()
```
You can do:
```
jsonFooString=json.dumps(a.to_son().to_dict())
``` |
46,366,398 | I am using Pymodm as a mongoDB odm with python flask. I have looked through code and documentation (<https://github.com/mongodb/pymodm> and <http://pymodm.readthedocs.io/en/latest>) but could not find what I was looking for.
I am looking for an easy way to fetch data from the database without converting it to a pymodm... | 2017/09/22 | [
"https://Stackoverflow.com/questions/46366398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3531894/"
] | It is not obvious from the PyMODM documentation, but here's how to do it:
```
pymodm_obj.to_son().to_dict()
```
Actually, I just re-read your question, and I don't think anything is forcing you to use PyMODM everywhere in your project once you have made the decision to use it. So if you are just looking for the JSON... | If you need to build CRUD api you might also want to check this little package, basically DRF for pymodm
So if you want to create CREATE/UPDATE/DELETE it would look like this
from api.pymodm\_rest import viewsets
```
class ServiceAreaViewSet(viewsets.ModelViewSet):
queryset = ServiceArea.objects
instance_cla... |
46,366,398 | I am using Pymodm as a mongoDB odm with python flask. I have looked through code and documentation (<https://github.com/mongodb/pymodm> and <http://pymodm.readthedocs.io/en/latest>) but could not find what I was looking for.
I am looking for an easy way to fetch data from the database without converting it to a pymodm... | 2017/09/22 | [
"https://Stackoverflow.com/questions/46366398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3531894/"
] | Having:
```
from pymodm import MongoModel, fields
import json
class Foo(MongoModel):
name = fields.CharField(required=True)
a=Foo()
```
You can do:
```
jsonFooString=json.dumps(a.to_son().to_dict())
``` | If you need to build CRUD api you might also want to check this little package, basically DRF for pymodm
So if you want to create CREATE/UPDATE/DELETE it would look like this
from api.pymodm\_rest import viewsets
```
class ServiceAreaViewSet(viewsets.ModelViewSet):
queryset = ServiceArea.objects
instance_cla... |
15,059,082 | This is my code. In the first def function, I made it return column\_choose, and I wanna use column\_choose's value in second def function(get\_data\_list). What can I do? I have tried many times. But IDLE always show:global name 'column\_choose' is not defined.
How to use column\_choose's value in second function?
By... | 2013/02/25 | [
"https://Stackoverflow.com/questions/15059082",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2011210/"
] | Using `float: left` on the elements will cause them to ignore the `nowrap` rule. Since you are already using `display: inline-block`, you don't need to float the elements to have them display side-by-side. Just remove `float: left` | Was because of the float:left;, once i removed that, fine. Spotted it after typing out question sorry. |
70,647,836 | Very new to python. I am trying to iterate over a list of floating points and append elements to a new list based on a condition. Everytime I populate the list I get double the output, for example a list with three floating points gives me an output of six elements in the new list.
```
tempretures = [39.3, 38.2, 38.1]... | 2022/01/10 | [
"https://Stackoverflow.com/questions/70647836",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17887798/"
] | The issue is with the indentation of the line `new_list = new_list + ['N']`. Because it is under-indented, it runs for every instance.
If I can suggest an easier syntax:
```
temperatures = [39.3, 38.2, 38.1]
new_list = []
for temperature in temperatures:
if temperature < 38.3:
new_list.append('L')
el... | Hope it will solve your issue:
```
tempretures = [39.3, 38.2, 38.1]
new_list = []
for temperature in tempretures:
if temperature > 39.2:
new_list.append('H')
elif temperature>=38.3 and temperature<39.2:
new_list.append('N')
else:
new_list.append('L')
print (new_list)
```
sample o... |
70,647,836 | Very new to python. I am trying to iterate over a list of floating points and append elements to a new list based on a condition. Everytime I populate the list I get double the output, for example a list with three floating points gives me an output of six elements in the new list.
```
tempretures = [39.3, 38.2, 38.1]... | 2022/01/10 | [
"https://Stackoverflow.com/questions/70647836",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17887798/"
] | The cause of this is at the `else:` statement at the bottom, you haven't indented the line `new_list = new_list + ['N']` so it is being ran no matter the result.
There are also a few other improvements which I've made and added comments explaining what it's doing
Change your code to this:
```
temperatures = [39.3, 3... | Hope it will solve your issue:
```
tempretures = [39.3, 38.2, 38.1]
new_list = []
for temperature in tempretures:
if temperature > 39.2:
new_list.append('H')
elif temperature>=38.3 and temperature<39.2:
new_list.append('N')
else:
new_list.append('L')
print (new_list)
```
sample o... |
70,647,836 | Very new to python. I am trying to iterate over a list of floating points and append elements to a new list based on a condition. Everytime I populate the list I get double the output, for example a list with three floating points gives me an output of six elements in the new list.
```
tempretures = [39.3, 38.2, 38.1]... | 2022/01/10 | [
"https://Stackoverflow.com/questions/70647836",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17887798/"
] | It looks like you're looking for something like the below list comprehension, which should be a go to when you have a pattern of building a new list based on the values in an existing list.
```
new_list = ['L' if t < 38.3 else 'H' if t > 39.2 else 'N' for t in temperatures]
``` | Hope it will solve your issue:
```
tempretures = [39.3, 38.2, 38.1]
new_list = []
for temperature in tempretures:
if temperature > 39.2:
new_list.append('H')
elif temperature>=38.3 and temperature<39.2:
new_list.append('N')
else:
new_list.append('L')
print (new_list)
```
sample o... |
57,010,692 | i am trying to extract specific data from requested json file
so after passing Authorization and using requests.get i got my request , i think it is called dictionary for python coders and called json for javascript coders
it containt too much information that i dont need and i would like to extract one or two only
fo... | 2019/07/12 | [
"https://Stackoverflow.com/questions/57010692",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9952973/"
] | The `Aphid` library I created is perfect for this.
from command-prompt
```py
py -m pip install Aphid
```
Then its just as easy as loading your json data and searching it with aphid.
```
import json
import Aphid
resp = requests.get(yoururl)
data = json.loads(resp.text)
results = Aphid.findall(data, 'bio')
```
... | After you get your request either:
* you get a simple json file (in which case you import it to python using [json](https://docs.python.org/3/library/json.html)) **or**
* you get an html file from which you can extract the json code (using BeautifulSoup) which in turn you will parse using json library. |
16,956,523 | [Using Python3] I have a csv file that has two columns (an email address and a country code; script is made to actually make it two columns if not the case in the original file - kind of) that I want to split out by the value in the second column and output in separate csv files.
```
eppetj@desrfpkwpwmhdc.com u... | 2013/06/06 | [
"https://Stackoverflow.com/questions/16956523",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2445114/"
] | You can simplify this a lot by using a `defaultdict`:
```
import csv
from collections import defaultdict
emails = defaultdict(list)
with open('email.tsv','r') as f:
reader = csv.reader(f, delimiter='\t')
for row in reader:
if row:
if '@' in row[0]:
emails[row[1].strip()].append(row[0]... | Not a Python answer, but maybe you can use this Bash solution.
```
$ while read email country
do
echo $email >> output-$country.csv
done < in.csv
```
This reads the lines from `in.csv`, splits them into two parts `email` and `country`, and appends (`>>`) the `email` to the file called `output-$country.csv`. |
16,956,523 | [Using Python3] I have a csv file that has two columns (an email address and a country code; script is made to actually make it two columns if not the case in the original file - kind of) that I want to split out by the value in the second column and output in separate csv files.
```
eppetj@desrfpkwpwmhdc.com u... | 2013/06/06 | [
"https://Stackoverflow.com/questions/16956523",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2445114/"
] | The problem with your code is that it keeps opening the same country output file each time it writes an entry into it, thereby overwriting whatever might have already been there.
A simple way to avoid that is to open all the output files at once for writing and store them in a dictionary keyed by the country code. Lik... | Not a Python answer, but maybe you can use this Bash solution.
```
$ while read email country
do
echo $email >> output-$country.csv
done < in.csv
```
This reads the lines from `in.csv`, splits them into two parts `email` and `country`, and appends (`>>`) the `email` to the file called `output-$country.csv`. |
16,956,523 | [Using Python3] I have a csv file that has two columns (an email address and a country code; script is made to actually make it two columns if not the case in the original file - kind of) that I want to split out by the value in the second column and output in separate csv files.
```
eppetj@desrfpkwpwmhdc.com u... | 2013/06/06 | [
"https://Stackoverflow.com/questions/16956523",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2445114/"
] | You can simplify this a lot by using a `defaultdict`:
```
import csv
from collections import defaultdict
emails = defaultdict(list)
with open('email.tsv','r') as f:
reader = csv.reader(f, delimiter='\t')
for row in reader:
if row:
if '@' in row[0]:
emails[row[1].strip()].append(row[0]... | The problem with your code is that it keeps opening the same country output file each time it writes an entry into it, thereby overwriting whatever might have already been there.
A simple way to avoid that is to open all the output files at once for writing and store them in a dictionary keyed by the country code. Lik... |
71,117,916 | I'm looking to use the Kubernetes python client to delete a deployment, but then block and wait until all of the associated pods are deleted as well. A lot of the examples I'm finding recommend using the watch function something like follows.
```
try:
# try to delete if exists
AppsV1Api(api_client).delete_name... | 2022/02/14 | [
"https://Stackoverflow.com/questions/71117916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/226081/"
] | ```css
.card {
display: flex;
flex-direction: column;
flex-wrap: wrap;
justify-content: center;
align-items: center;
height: 400px;
}
.card img {
height: 400px;
max-width:50%;
}
```
```html
<div class = "container">
<div class = "card">
<img src="https://www.unfe.org/wp-content/uploads/2019/0... | You need to `flex`:
```css
.card{
display: flex;
justify-content: center;
gap: 20px;
margin-top: 20px;
}
.img{
width: 40%;
}
img{
width: 100%;
}
.text{
width: 40%;
}
.text p{
font-size: 12px;
}
```
```html
<div class="card">
<div class="img">
<img src="https://s6.uupload.ir/files/magearray-giftcar... |
50,259,795 | I just installed the discord.py rewrite branch, but attempting to use `import discord` or `from discord.ext import commands` simply results in a TypeError.
```
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.6/site-packages/discord/__init__.py", line 20, in <modu... | 2018/05/09 | [
"https://Stackoverflow.com/questions/50259795",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9766666/"
] | Your aiohttp package might be out of date.
Try
```
pip install --upgrade aiohttp
``` | I tried to install discord.py on my python 3.7 and it didn't work.
I had to install python 3.6.6 to make it work, maybe you are using python 3.7, if so you should try rolling back to python 3.6.6 |
66,306,167 | Can you please explain how the below python code is evaluated to be True
```
if 50 == 10 or 30:
print('True')
else:
print('False')
```
Output: True | 2021/02/21 | [
"https://Stackoverflow.com/questions/66306167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7121586/"
] | Replace internals of while- loop with simpler version
```
while leftIndex < left.count && rightIndex < right.count {
if left[leftIndex] <= right[rightIndex] {
mergedArr.append(left[leftIndex])
leftIndex += 1
} else {
mergedArr.append(right[rightIndex])
rightIndex += 1
}
}
... | Consider if the data remains on the `left` or `right` only.
```
public func mergeSort<T: Comparable>(_ array: [T]) -> [T] {
if array.count < 2 {
return array
}
let mid = array.count / 2
let left = [T](array[0..<mid])
let right = [T](array[mid..<array.count])
return merge(left, right)... |
66,306,167 | Can you please explain how the below python code is evaluated to be True
```
if 50 == 10 or 30:
print('True')
else:
print('False')
```
Output: True | 2021/02/21 | [
"https://Stackoverflow.com/questions/66306167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7121586/"
] | It's not working because you forget to add to your ordered array the remaining data in left and right sub-array(s). The merge method should look like the below.
```
func merge<>(_ left: [Int], _ right: [Int]) -> [Int] {
var leftIndex = 0
var rightIndex = 0
var orderedArray = [Int]()
while leftIndex < left.cou... | Consider if the data remains on the `left` or `right` only.
```
public func mergeSort<T: Comparable>(_ array: [T]) -> [T] {
if array.count < 2 {
return array
}
let mid = array.count / 2
let left = [T](array[0..<mid])
let right = [T](array[mid..<array.count])
return merge(left, right)... |
13,907,949 | I'm having an issue and I have no idea why this is happening and how to fix it. I'm working on developing a Videogame with python and pygame and I'm getting this error:
```
File "/home/matt/Smoking-Games/sg-project00/project00/GameModel.py", line 15, in Update
self.imageDef=self.values[2]
TypeError: 'NoneType' o... | 2012/12/17 | [
"https://Stackoverflow.com/questions/13907949",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1908896/"
] | BrenBarn is correct. The error means you tried to do something like `None[5]`. In the backtrace, it says `self.imageDef=self.values[2]`, which means that your `self.values` is `None`.
You should go through all the functions that update `self.values` and make sure you account for all the corner cases. | The function `move.CompleteMove(events)` that you use within your class probably doesn't contain a `return` statement. So nothing is returned to `self.values` (==> None). Use `return` in `move.CompleteMove(events)` to return whatever you want to store in `self.values` and it should work. Hope this helps. |
13,907,949 | I'm having an issue and I have no idea why this is happening and how to fix it. I'm working on developing a Videogame with python and pygame and I'm getting this error:
```
File "/home/matt/Smoking-Games/sg-project00/project00/GameModel.py", line 15, in Update
self.imageDef=self.values[2]
TypeError: 'NoneType' o... | 2012/12/17 | [
"https://Stackoverflow.com/questions/13907949",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1908896/"
] | BrenBarn is correct. The error means you tried to do something like `None[5]`. In the backtrace, it says `self.imageDef=self.values[2]`, which means that your `self.values` is `None`.
You should go through all the functions that update `self.values` and make sure you account for all the corner cases. | `move.CompleteMove()` does not return a value (perhaps it just prints something). Any method that does not return a value returns `None`, and you have assigned `None` to `self.values`.
Here is an example of this:
```
>>> def hello(x):
... print x*2
...
>>> hello('world')
worldworld
>>> y = hello('world')
worldworl... |
13,907,949 | I'm having an issue and I have no idea why this is happening and how to fix it. I'm working on developing a Videogame with python and pygame and I'm getting this error:
```
File "/home/matt/Smoking-Games/sg-project00/project00/GameModel.py", line 15, in Update
self.imageDef=self.values[2]
TypeError: 'NoneType' o... | 2012/12/17 | [
"https://Stackoverflow.com/questions/13907949",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1908896/"
] | `move.CompleteMove()` does not return a value (perhaps it just prints something). Any method that does not return a value returns `None`, and you have assigned `None` to `self.values`.
Here is an example of this:
```
>>> def hello(x):
... print x*2
...
>>> hello('world')
worldworld
>>> y = hello('world')
worldworl... | The function `move.CompleteMove(events)` that you use within your class probably doesn't contain a `return` statement. So nothing is returned to `self.values` (==> None). Use `return` in `move.CompleteMove(events)` to return whatever you want to store in `self.values` and it should work. Hope this helps. |
58,500,923 | I have an array of elements [a\_1, a\_2, ... a\_n] and array ofprobabilities associated with this elements [p\_1, p\_2, ..., p\_n].
I want to choose "k" elements from [a\_1,...a\_n], k << n, according to probabilities [p\_1,p\_2,...,p\_n].
How can I code it in python? Thank you very much, I am not experienced at prog... | 2019/10/22 | [
"https://Stackoverflow.com/questions/58500923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12256362/"
] | use `numpy.random.choice`
example:
```
from numpy.random import choice
sample_space = np.array([a_1, a_2, ... a_n]) # substitute the a_i's
discrete_probability_distribution = np.array([p_1, p_2, ..., p_n]) # substitute the p_i's
# picking N samples
N = 10
for _ in range(N):
print(choice(sample_space, discre... | Perhaps you want something similar to this?
```
import random
data = ['a', 'b', 'c', 'd']
probabilities = [0.5, 0.1, 0.9, 0.2]
for _ in range(10):
print([d for d,p in zip(data,probabilities) if p>random.random()])
```
The above would output something like:
```
['c']
['c']
['a', 'c']
['a', 'c']
['a', 'c']
[]
['a... |
15,305,634 | Today I progressed further into [this Python roguelike tutorial](http://roguebasin.roguelikedevelopment.org/index.php?title=Complete_Roguelike_Tutorial,_using_python%2Blibtcod), and got to the inventory. As of now, I can pick up items and use them. The only problem is, when accessing the inventory, it's only visible fo... | 2013/03/09 | [
"https://Stackoverflow.com/questions/15305634",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2138040/"
] | Your code is messy, there may be multiple issues but I think this line is your problem
```
txView.SetBackgroundResource(Resource.Color.PrimaryColor);
```
As you can see [here](http://developer.android.com/reference/android/view/View.html#setBackgroundResource%28int%29) in the documentation you should only pass a ref... | You need to tell which view to find id in. So instantiate a `view` after get the `factory`.
```
var view = factory.Inflate(Resource.Layout.DialogRegister, null);
```
Because the `titleView` would reference to null, it causes the crash,
Then, you can find the `title` using the `view` you just created. One thing to ... |
15,305,634 | Today I progressed further into [this Python roguelike tutorial](http://roguebasin.roguelikedevelopment.org/index.php?title=Complete_Roguelike_Tutorial,_using_python%2Blibtcod), and got to the inventory. As of now, I can pick up items and use them. The only problem is, when accessing the inventory, it's only visible fo... | 2013/03/09 | [
"https://Stackoverflow.com/questions/15305634",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2138040/"
] | You need to tell which view to find id in. So instantiate a `view` after get the `factory`.
```
var view = factory.Inflate(Resource.Layout.DialogRegister, null);
```
Because the `titleView` would reference to null, it causes the crash,
Then, you can find the `title` using the `view` you just created. One thing to ... | I would just use dialogs. You override the OnCreateDialog method. There you can set a contentview and set a custom title if needed. You can also customize the dialog.Here is some example code, there is a SetTitle method. Here is a brief example more can be found at the link below the code.
This code shows how to wire ... |
15,305,634 | Today I progressed further into [this Python roguelike tutorial](http://roguebasin.roguelikedevelopment.org/index.php?title=Complete_Roguelike_Tutorial,_using_python%2Blibtcod), and got to the inventory. As of now, I can pick up items and use them. The only problem is, when accessing the inventory, it's only visible fo... | 2013/03/09 | [
"https://Stackoverflow.com/questions/15305634",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2138040/"
] | Your code is messy, there may be multiple issues but I think this line is your problem
```
txView.SetBackgroundResource(Resource.Color.PrimaryColor);
```
As you can see [here](http://developer.android.com/reference/android/view/View.html#setBackgroundResource%28int%29) in the documentation you should only pass a ref... | I would just use dialogs. You override the OnCreateDialog method. There you can set a contentview and set a custom title if needed. You can also customize the dialog.Here is some example code, there is a SetTitle method. Here is a brief example more can be found at the link below the code.
This code shows how to wire ... |
56,324,750 | I want to get docker host machine ip address and interface names i.e ifconfig of docker host machine. instead im getting docker container ip address on doing ifconfig in docker container.
It would be great if someone tell me to fetch ip address of docker host machine from a docker container.
i have tried doing ifconf... | 2019/05/27 | [
"https://Stackoverflow.com/questions/56324750",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11361438/"
] | This is an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)
Why? Because the issue is not the amount of data not fitting the index, that's the *symptom*.
Real problem
------------
Real problem is how to stop duplicate email entries.
Attempted solution
------------------
Attempted... | You can chenge the innodb\_large\_prefix in your config file to ON. That will set your index key prefixes up to 3072 bytes as the mysql [doc](https://dev.mysql.com/doc/refman/5.6/en/innodb-restrictions.html) says.
```
[mysqld]
innodb_large_prefix = 1
``` |
63,320,723 | Im a beginner in python and im currently working on a problem on code forces called Lecture Sleep. The question gives you 3 lines of inputs:
```
6 3
1 3 5 2 5 4
1 1 0 1 0 0
```
I'm trying to figure out how to link the second array of numbers `(1 3 5 2 5 4)` to the 3rd array of numbers `(1 1 0 1 0 0)`. So that `1 = 1... | 2020/08/08 | [
"https://Stackoverflow.com/questions/63320723",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14072979/"
] | It might not be the solution for you, but I tell what we do.
1. Prefix the package names, and using namespaces (eg. `company.product.tool`).
2. When we install our packages (including their in-house dependencies), we use a `requirements.txt` file including our PyPI URL. We run everything in container(s) and we install... | Your company could redirect all requests to pypi to a service you control first (perhaps just at your build servers' `hosts` file(s))
This would potentially allow you to
* prefer/override arbitrary packages with local ones
* detect such cases
* cache common/large upstream packages locally
* reject suspect/non-known v... |
63,320,723 | Im a beginner in python and im currently working on a problem on code forces called Lecture Sleep. The question gives you 3 lines of inputs:
```
6 3
1 3 5 2 5 4
1 1 0 1 0 0
```
I'm trying to figure out how to link the second array of numbers `(1 3 5 2 5 4)` to the 3rd array of numbers `(1 1 0 1 0 0)`. So that `1 = 1... | 2020/08/08 | [
"https://Stackoverflow.com/questions/63320723",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14072979/"
] | It might not be the solution for you, but I tell what we do.
1. Prefix the package names, and using namespaces (eg. `company.product.tool`).
2. When we install our packages (including their in-house dependencies), we use a `requirements.txt` file including our PyPI URL. We run everything in container(s) and we install... | We use VCS for this. I see you've explicitly ruled that out, but have you considered using branches to mark your latest stable builds in VCS?
If you aren't interested in the latest version of master or the dev branch, but you are running test/QA against commits, then I would configure your test/QA suite to merge into ... |
63,320,723 | Im a beginner in python and im currently working on a problem on code forces called Lecture Sleep. The question gives you 3 lines of inputs:
```
6 3
1 3 5 2 5 4
1 1 0 1 0 0
```
I'm trying to figure out how to link the second array of numbers `(1 3 5 2 5 4)` to the 3rd array of numbers `(1 1 0 1 0 0)`. So that `1 = 1... | 2020/08/08 | [
"https://Stackoverflow.com/questions/63320723",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14072979/"
] | It might not be the solution for you, but I tell what we do.
1. Prefix the package names, and using namespaces (eg. `company.product.tool`).
2. When we install our packages (including their in-house dependencies), we use a `requirements.txt` file including our PyPI URL. We run everything in container(s) and we install... | You could perhaps get the behavior you are looking for from a `requirements.txt` and two `pip` calls:
```
cat requirements.txt | xargs -n 1 pip install -i <your-s3pipy>
pip install -r requirements.txt
```
The first one tries to install what it can from your local repository and ignores a package if it fails. The sec... |
63,320,723 | Im a beginner in python and im currently working on a problem on code forces called Lecture Sleep. The question gives you 3 lines of inputs:
```
6 3
1 3 5 2 5 4
1 1 0 1 0 0
```
I'm trying to figure out how to link the second array of numbers `(1 3 5 2 5 4)` to the 3rd array of numbers `(1 1 0 1 0 0)`. So that `1 = 1... | 2020/08/08 | [
"https://Stackoverflow.com/questions/63320723",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14072979/"
] | It might not be the solution for you, but I tell what we do.
1. Prefix the package names, and using namespaces (eg. `company.product.tool`).
2. When we install our packages (including their in-house dependencies), we use a `requirements.txt` file including our PyPI URL. We run everything in container(s) and we install... | The comment from @a\_guest on my first answer got me thinking, and the "problem" is that pip doesn't consider where the package originated when it sorts through candidates to satisfy requirements.
So here is a possible way to change this: Monkey-patch pip and introduce a preference over indexes.
```
from __future__ i... |
12,468,022 | I have several threads running in parallel from Python on a cluster system. Each python thread outputs to a directory `mydir`. Each script, before outputting checks if *mydir* exists and if not creates it:
```
if not os.path.isdir(mydir):
os.makedirs(mydir)
```
but this yields the error:
```
os.makedirs(self.lo... | 2012/09/17 | [
"https://Stackoverflow.com/questions/12468022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Any time code can execute between when you check something and when you act on it, you will have a race condition. One way to avoid this (and the usual way in Python) is to just try and then handle the exception
```
while True:
mydir = next_dir_name()
try:
os.makedirs(mydir)
break
except OS... | Catch the exception and, if the errno is 17, ignore it. That's the only thing you can do if there's a race condition between the `isdir` and `makedirs` calls.
However, it could also be possible that a *file* with the same name exists - in that case `os.path.exists` would return `True` but `os.path.isdir` returns false... |
12,468,022 | I have several threads running in parallel from Python on a cluster system. Each python thread outputs to a directory `mydir`. Each script, before outputting checks if *mydir* exists and if not creates it:
```
if not os.path.isdir(mydir):
os.makedirs(mydir)
```
but this yields the error:
```
os.makedirs(self.lo... | 2012/09/17 | [
"https://Stackoverflow.com/questions/12468022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | As of Python `>=3.2`, `os.makedirs()` can take a third optional argument `exist_ok`:
```
os.makedirs(mydir, exist_ok=True)
``` | Catch the exception and, if the errno is 17, ignore it. That's the only thing you can do if there's a race condition between the `isdir` and `makedirs` calls.
However, it could also be possible that a *file* with the same name exists - in that case `os.path.exists` would return `True` but `os.path.isdir` returns false... |
12,468,022 | I have several threads running in parallel from Python on a cluster system. Each python thread outputs to a directory `mydir`. Each script, before outputting checks if *mydir* exists and if not creates it:
```
if not os.path.isdir(mydir):
os.makedirs(mydir)
```
but this yields the error:
```
os.makedirs(self.lo... | 2012/09/17 | [
"https://Stackoverflow.com/questions/12468022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Catch the exception and, if the errno is 17, ignore it. That's the only thing you can do if there's a race condition between the `isdir` and `makedirs` calls.
However, it could also be possible that a *file* with the same name exists - in that case `os.path.exists` would return `True` but `os.path.isdir` returns false... | I had a similar issues and here is what I did
```
try:
if not os.path.exists(os.path.dirname(mydir)):
os.makedirs(os.path.dirname(mydir))
except OSError as err:
print(err)
```
**Description:**
Just checking if the directory already exist throws this error message **[Errno 17] File exists**
because we a... |
12,468,022 | I have several threads running in parallel from Python on a cluster system. Each python thread outputs to a directory `mydir`. Each script, before outputting checks if *mydir* exists and if not creates it:
```
if not os.path.isdir(mydir):
os.makedirs(mydir)
```
but this yields the error:
```
os.makedirs(self.lo... | 2012/09/17 | [
"https://Stackoverflow.com/questions/12468022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Catch the exception and, if the errno is 17, ignore it. That's the only thing you can do if there's a race condition between the `isdir` and `makedirs` calls.
However, it could also be possible that a *file* with the same name exists - in that case `os.path.exists` would return `True` but `os.path.isdir` returns false... | To ignore the dir or file exist error, you can try this:
```
except OSError, e:
if e.errno != 17:
print("Error:", e)
``` |
12,468,022 | I have several threads running in parallel from Python on a cluster system. Each python thread outputs to a directory `mydir`. Each script, before outputting checks if *mydir* exists and if not creates it:
```
if not os.path.isdir(mydir):
os.makedirs(mydir)
```
but this yields the error:
```
os.makedirs(self.lo... | 2012/09/17 | [
"https://Stackoverflow.com/questions/12468022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Any time code can execute between when you check something and when you act on it, you will have a race condition. One way to avoid this (and the usual way in Python) is to just try and then handle the exception
```
while True:
mydir = next_dir_name()
try:
os.makedirs(mydir)
break
except OS... | I had a similar issues and here is what I did
```
try:
if not os.path.exists(os.path.dirname(mydir)):
os.makedirs(os.path.dirname(mydir))
except OSError as err:
print(err)
```
**Description:**
Just checking if the directory already exist throws this error message **[Errno 17] File exists**
because we a... |
12,468,022 | I have several threads running in parallel from Python on a cluster system. Each python thread outputs to a directory `mydir`. Each script, before outputting checks if *mydir* exists and if not creates it:
```
if not os.path.isdir(mydir):
os.makedirs(mydir)
```
but this yields the error:
```
os.makedirs(self.lo... | 2012/09/17 | [
"https://Stackoverflow.com/questions/12468022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Any time code can execute between when you check something and when you act on it, you will have a race condition. One way to avoid this (and the usual way in Python) is to just try and then handle the exception
```
while True:
mydir = next_dir_name()
try:
os.makedirs(mydir)
break
except OS... | To ignore the dir or file exist error, you can try this:
```
except OSError, e:
if e.errno != 17:
print("Error:", e)
``` |
12,468,022 | I have several threads running in parallel from Python on a cluster system. Each python thread outputs to a directory `mydir`. Each script, before outputting checks if *mydir* exists and if not creates it:
```
if not os.path.isdir(mydir):
os.makedirs(mydir)
```
but this yields the error:
```
os.makedirs(self.lo... | 2012/09/17 | [
"https://Stackoverflow.com/questions/12468022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | As of Python `>=3.2`, `os.makedirs()` can take a third optional argument `exist_ok`:
```
os.makedirs(mydir, exist_ok=True)
``` | I had a similar issues and here is what I did
```
try:
if not os.path.exists(os.path.dirname(mydir)):
os.makedirs(os.path.dirname(mydir))
except OSError as err:
print(err)
```
**Description:**
Just checking if the directory already exist throws this error message **[Errno 17] File exists**
because we a... |
12,468,022 | I have several threads running in parallel from Python on a cluster system. Each python thread outputs to a directory `mydir`. Each script, before outputting checks if *mydir* exists and if not creates it:
```
if not os.path.isdir(mydir):
os.makedirs(mydir)
```
but this yields the error:
```
os.makedirs(self.lo... | 2012/09/17 | [
"https://Stackoverflow.com/questions/12468022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | As of Python `>=3.2`, `os.makedirs()` can take a third optional argument `exist_ok`:
```
os.makedirs(mydir, exist_ok=True)
``` | To ignore the dir or file exist error, you can try this:
```
except OSError, e:
if e.errno != 17:
print("Error:", e)
``` |
12,468,022 | I have several threads running in parallel from Python on a cluster system. Each python thread outputs to a directory `mydir`. Each script, before outputting checks if *mydir* exists and if not creates it:
```
if not os.path.isdir(mydir):
os.makedirs(mydir)
```
but this yields the error:
```
os.makedirs(self.lo... | 2012/09/17 | [
"https://Stackoverflow.com/questions/12468022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I had a similar issues and here is what I did
```
try:
if not os.path.exists(os.path.dirname(mydir)):
os.makedirs(os.path.dirname(mydir))
except OSError as err:
print(err)
```
**Description:**
Just checking if the directory already exist throws this error message **[Errno 17] File exists**
because we a... | To ignore the dir or file exist error, you can try this:
```
except OSError, e:
if e.errno != 17:
print("Error:", e)
``` |
63,783,587 | My goal is to install a package to a specific directory on my machine so I can package it up to be used with AWS Lambda.
Here is what I have tried:
`pip install snowflake-connector-python -t .`
`pip install --system --target=C:\Users\path2folder --install-option=--install-scripts=C:\Users\path2folder --upgrade sno... | 2020/09/07 | [
"https://Stackoverflow.com/questions/63783587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12655086/"
] | We encountered the same issue when running `pip install --target ./py_pkg -r requirements.txt --upgrade` with Microsoft store version of Python 3.9.
Adding `--no-user` to the end of it seems solves the issue. Maybe you can try that in your command and let us know if this solution works?
`pip install --target ./py_pkg... | We had the same issue just in a Python course: The error comes up if Python is installed as an app from the Microsoft app store. In our case it was resolved after re-installing Python by downloading and using the installation package directly from the Python website. |
63,783,587 | My goal is to install a package to a specific directory on my machine so I can package it up to be used with AWS Lambda.
Here is what I have tried:
`pip install snowflake-connector-python -t .`
`pip install --system --target=C:\Users\path2folder --install-option=--install-scripts=C:\Users\path2folder --upgrade sno... | 2020/09/07 | [
"https://Stackoverflow.com/questions/63783587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12655086/"
] | We had the same issue just in a Python course: The error comes up if Python is installed as an app from the Microsoft app store. In our case it was resolved after re-installing Python by downloading and using the installation package directly from the Python website. | I got a similar error recently. Adding my solution so that it might help someone facing the error due to the same reason.
I was facing an issue where all my pip installed packages were going to an older python brew installation folder.
As part of debugging, I was trying to install `awscli-local` package to user site-... |
63,783,587 | My goal is to install a package to a specific directory on my machine so I can package it up to be used with AWS Lambda.
Here is what I have tried:
`pip install snowflake-connector-python -t .`
`pip install --system --target=C:\Users\path2folder --install-option=--install-scripts=C:\Users\path2folder --upgrade sno... | 2020/09/07 | [
"https://Stackoverflow.com/questions/63783587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12655086/"
] | We encountered the same issue when running `pip install --target ./py_pkg -r requirements.txt --upgrade` with Microsoft store version of Python 3.9.
Adding `--no-user` to the end of it seems solves the issue. Maybe you can try that in your command and let us know if this solution works?
`pip install --target ./py_pkg... | I got a similar error recently. Adding my solution so that it might help someone facing the error due to the same reason.
I was facing an issue where all my pip installed packages were going to an older python brew installation folder.
As part of debugging, I was trying to install `awscli-local` package to user site-... |
56,578,199 | I am trying to save AWS CLI command into python variable (list). The trick is the following code returns result I want but doesn't save it into variable and return empty list.
```
import os
bashCommand = 'aws s3api list-buckets --query "Buckets[].Name"'
f = [os.system(bashCommand)]
print(f)
```
output:
```
[
"buck... | 2019/06/13 | [
"https://Stackoverflow.com/questions/56578199",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10941134/"
] | If you are using Python and you wish to list buckets, then it would be better to use the AWS SDK for Python, which is `boto3`:
```
import boto3
s3 = boto3.resource('s3')
buckets = [bucket.name for bucket in s3.buckets.all()]
```
See: [S3 — Boto 3 Docs](https://boto3.amazonaws.com/v1/documentation/api/latest/referen... | I use this command to create a Python list of all buckets:
```
bucket_list = eval(subprocess.check_output('aws s3api list-buckets --query "Buckets[].Name"').translate(None, '\r\n '))
``` |
56,578,199 | I am trying to save AWS CLI command into python variable (list). The trick is the following code returns result I want but doesn't save it into variable and return empty list.
```
import os
bashCommand = 'aws s3api list-buckets --query "Buckets[].Name"'
f = [os.system(bashCommand)]
print(f)
```
output:
```
[
"buck... | 2019/06/13 | [
"https://Stackoverflow.com/questions/56578199",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10941134/"
] | If you are using Python and you wish to list buckets, then it would be better to use the AWS SDK for Python, which is `boto3`:
```
import boto3
s3 = boto3.resource('s3')
buckets = [bucket.name for bucket in s3.buckets.all()]
```
See: [S3 — Boto 3 Docs](https://boto3.amazonaws.com/v1/documentation/api/latest/referen... | You really don't need anything fancy , all you have to do is import subprocess and json and use them :)
This was tested using python3.6 and on Linux
```
output = subprocess.run(["aws", "--region=us-west-2", "s3api", "list-buckets", "--query", "Buckets[].Name"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output... |
56,578,199 | I am trying to save AWS CLI command into python variable (list). The trick is the following code returns result I want but doesn't save it into variable and return empty list.
```
import os
bashCommand = 'aws s3api list-buckets --query "Buckets[].Name"'
f = [os.system(bashCommand)]
print(f)
```
output:
```
[
"buck... | 2019/06/13 | [
"https://Stackoverflow.com/questions/56578199",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10941134/"
] | You really don't need anything fancy , all you have to do is import subprocess and json and use them :)
This was tested using python3.6 and on Linux
```
output = subprocess.run(["aws", "--region=us-west-2", "s3api", "list-buckets", "--query", "Buckets[].Name"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output... | I use this command to create a Python list of all buckets:
```
bucket_list = eval(subprocess.check_output('aws s3api list-buckets --query "Buckets[].Name"').translate(None, '\r\n '))
``` |
63,993,912 | python version 3.8.3
```
import telegram #imorted methodts
from telegram.ext import Updater, CommandHandler
import requests
from telegram import ReplyKeyboardMarkup, KeyboardButton
from telegram.ext.messagehandler import MessageHandler
import json
# below is function defined the buttons to be return
def start(bot, u... | 2020/09/21 | [
"https://Stackoverflow.com/questions/63993912",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14315167/"
] | After a great effort, I have found a solution for this.
```
class LinearProgressWithTextWidget extends StatelessWidget {
final Color color;
final double progress;
LinearProgressWithTextWidget({Key key,@required this.color, @required this.progress}) : super(key: key);
@override
Widget build(BuildContext cont... | I added the loading indicator inside of a stack and wrapped the whole widget with a `LayoutBuilder`, which will give you the BoxConstraints of the current widget. You can use that to calculate the position of the percent indicator and place a widget (text) above it.
[. How to install python3-dev locally?
I am using ubuntu 16.04. | 2016/11/28 | [
"https://Stackoverflow.com/questions/40840480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5651936/"
] | You have a widget for this:
```
{{ form_errors(form) }}
``` | Accessing errors from **TWIG**
Displays all errors in template
```
{{ form_errors(form) }}
```
Access error for specific field
```
{{ form_errors(form.username) }}
```
Read More: [How to get error message of each field from form object in symfony2?](https://stackoverflow.com/a/40712685/2689199) |
48,965,221 | I'm having a dataset which as the following
```
customer products Sales
1 a 10
1 a 10
2 b 20
3 c 30
```
How can I reshape and to do that in python and pandas? I've tried with the pivot tools but since I have duplicated CUSTOMER ID ... | 2018/02/24 | [
"https://Stackoverflow.com/questions/48965221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9406236/"
] | You can use [`cumcount`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.cumcount.html) with [`set_index`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html) + [`unstack`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.unstack.ht... | Your question is unclear. In case of duplicate key, we usually aggregate values. Is that what you want ? Try this:
```
df.pivot_table(index='customer', columns='products', values ='Sales', aggfunc='sum')
products customer a b c
0 1 20.0 NaN NaN
1 2 NaN 20.0 NaN
2 3 ... |
48,965,221 | I'm having a dataset which as the following
```
customer products Sales
1 a 10
1 a 10
2 b 20
3 c 30
```
How can I reshape and to do that in python and pandas? I've tried with the pivot tools but since I have duplicated CUSTOMER ID ... | 2018/02/24 | [
"https://Stackoverflow.com/questions/48965221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9406236/"
] | You can use [`cumcount`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.cumcount.html) with [`set_index`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html) + [`unstack`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.unstack.ht... | Another method using [`str.get_dummies`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.get_dummies.html).
```
pd.concat([df, df.products.str.get_dummies().multiply(df["Sales"], axis="index")],
axis=1)
customer products Sales a b c
0 1 a 10 10 0 0
1 1... |
48,965,221 | I'm having a dataset which as the following
```
customer products Sales
1 a 10
1 a 10
2 b 20
3 c 30
```
How can I reshape and to do that in python and pandas? I've tried with the pivot tools but since I have duplicated CUSTOMER ID ... | 2018/02/24 | [
"https://Stackoverflow.com/questions/48965221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9406236/"
] | Another method using [`str.get_dummies`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.get_dummies.html).
```
pd.concat([df, df.products.str.get_dummies().multiply(df["Sales"], axis="index")],
axis=1)
customer products Sales a b c
0 1 a 10 10 0 0
1 1... | Your question is unclear. In case of duplicate key, we usually aggregate values. Is that what you want ? Try this:
```
df.pivot_table(index='customer', columns='products', values ='Sales', aggfunc='sum')
products customer a b c
0 1 20.0 NaN NaN
1 2 NaN 20.0 NaN
2 3 ... |
48,965,221 | I'm having a dataset which as the following
```
customer products Sales
1 a 10
1 a 10
2 b 20
3 c 30
```
How can I reshape and to do that in python and pandas? I've tried with the pivot tools but since I have duplicated CUSTOMER ID ... | 2018/02/24 | [
"https://Stackoverflow.com/questions/48965221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9406236/"
] | Here's fairly straight-forward way assuming you have a unique index, given your input of:
```
customer products Sales
0 1 a 10
1 1 a 10
2 2 b 20
3 3 c 30
```
Pivot it to columnise the products and rejoin to just the customer column on th... | Your question is unclear. In case of duplicate key, we usually aggregate values. Is that what you want ? Try this:
```
df.pivot_table(index='customer', columns='products', values ='Sales', aggfunc='sum')
products customer a b c
0 1 20.0 NaN NaN
1 2 NaN 20.0 NaN
2 3 ... |
48,965,221 | I'm having a dataset which as the following
```
customer products Sales
1 a 10
1 a 10
2 b 20
3 c 30
```
How can I reshape and to do that in python and pandas? I've tried with the pivot tools but since I have duplicated CUSTOMER ID ... | 2018/02/24 | [
"https://Stackoverflow.com/questions/48965221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9406236/"
] | Here's fairly straight-forward way assuming you have a unique index, given your input of:
```
customer products Sales
0 1 a 10
1 1 a 10
2 2 b 20
3 3 c 30
```
Pivot it to columnise the products and rejoin to just the customer column on th... | Another method using [`str.get_dummies`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.get_dummies.html).
```
pd.concat([df, df.products.str.get_dummies().multiply(df["Sales"], axis="index")],
axis=1)
customer products Sales a b c
0 1 a 10 10 0 0
1 1... |
26,409,964 | The [pickle documentation](https://docs.python.org/2/library/pickle.html#what-can-be-pickled-and-unpickled) states that "when class instances are pickled, their class’s data are not pickled along with them. Only the instance data are pickled." Can anyone provide a recipe for including class variables as well as instanc... | 2014/10/16 | [
"https://Stackoverflow.com/questions/26409964",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4147103/"
] | Use `dill` instead of pickle, and code exactly how you probably have done already.
```
>>> class A(object):
... y = 1
... x = 0
... def __call__(self, x):
... self.x = x
... return self.x + self.y
...
>>> b = A()
>>> b.y = 4
>>> b(2)
6
>>> b.z = 5
>>> import dill
>>> _b = dill.dumps(b)
>>> b_ = dill.loa... | You can do this easily using the standard library functions by using `__getstate__` and `__setstate__`:
```
class A(object):
y = 1
x = 0
def __getstate__(self):
ret = self.__dict__.copy()
ret['cls_x'] = A.x
ret['cls_y'] = A.y
return ret
def __setstate__(self, state):
A.x = state.pop('cls_... |
26,409,964 | The [pickle documentation](https://docs.python.org/2/library/pickle.html#what-can-be-pickled-and-unpickled) states that "when class instances are pickled, their class’s data are not pickled along with them. Only the instance data are pickled." Can anyone provide a recipe for including class variables as well as instanc... | 2014/10/16 | [
"https://Stackoverflow.com/questions/26409964",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4147103/"
] | Use `dill` instead of pickle, and code exactly how you probably have done already.
```
>>> class A(object):
... y = 1
... x = 0
... def __call__(self, x):
... self.x = x
... return self.x + self.y
...
>>> b = A()
>>> b.y = 4
>>> b(2)
6
>>> b.z = 5
>>> import dill
>>> _b = dill.dumps(b)
>>> b_ = dill.loa... | Here's a solution using only standard library modules. Simply execute the following code block, and from then on pickle behaves in the desired way. As Mike McKerns was saying, `dill` does something similar under the hood.
Based on relevant discussion found [here](https://bytes.com/topic/python/answers/552476-why-cant-... |
25,384,922 | I've installed some packages during the execution of my script as a user. Those packages were the first user packages, so python didn't add `~/.local/lib/python2.7/site-packages` to the `sys.path` before script run. I want to import those installed packages. But I cannot because they are not in `sys.path`.
How can I r... | 2014/08/19 | [
"https://Stackoverflow.com/questions/25384922",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2108548/"
] | As explained in [What sets up sys.path with Python, and when?](https://stackoverflow.com/questions/4271494/what-sets-up-sys-path-with-python-and-when) `sys.path` is populated with the help of builtin `site.py` module.
So you just need to reload it. You cannot it in one step because you don't have `site` in your namesp... | It might be better to add it directly to your `sys.path` with:
```
import sys
sys.path.append("/your/new/path")
```
Or, if it needs to be found first:
```
import sys
sys.path.insert(1, "/your/new/path")
``` |
18,621,624 | [I'm taking an intro to python class online](http://cscircles.cemc.uwaterloo.ca/8-remix/) and the site is designed to auto-enter input() data into the program that you write to resolve various python logic problems.
[Please see this page to see how the online class's tool uses input entries](http://cscircles.cemc.uwat... | 2013/09/04 | [
"https://Stackoverflow.com/questions/18621624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2609312/"
] | It sounds like you want to call `input` in a loop. Here's one way to do it:
```
lst = []
s = input()
while s != 'END':
lst.append(s)
s = input()
```
There are other options for how to set up the condition on the loop, but I think this is the most straight forward. If the calculation for when to stop looping ... | You can create a list and read each string one by one, and add it to the list:
```
width=int(input())
lis=[]
tmp=''
while tmp!='END':
tmp=input() #receives a string, in python 3.0+
lis.append(tmp)
``` |
18,621,624 | [I'm taking an intro to python class online](http://cscircles.cemc.uwaterloo.ca/8-remix/) and the site is designed to auto-enter input() data into the program that you write to resolve various python logic problems.
[Please see this page to see how the online class's tool uses input entries](http://cscircles.cemc.uwat... | 2013/09/04 | [
"https://Stackoverflow.com/questions/18621624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2609312/"
] | It sounds like you want to call `input` in a loop. Here's one way to do it:
```
lst = []
s = input()
while s != 'END':
lst.append(s)
s = input()
```
There are other options for how to set up the condition on the loop, but I think this is the most straight forward. If the calculation for when to stop looping ... | The `input()` method they provide you will return each line of the user input as it's called. For example, the following function prints each line of the input by calling input throughout a loop
```
for line in range(6):
print(input())
``` |
65,643,645 | I'm pretty new to python and to programming in general. I'm trying to make the game Bounce. The game runs as expected but as soon as I close the window, it shows an error.
This is the code:
```
from tkinter import *
import random
import time
# Creating the window:
window = Tk()
window.title("Bounce")
window.geometry(... | 2021/01/09 | [
"https://Stackoverflow.com/questions/65643645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14915849/"
] | It is caused by close button on top-right corner of window, the only way you have to stop script. After you click close button, window destried, so no widget, like canvas, exist.
You can set a flag to identify if while loop should stop and exit in handler of window close button event.
```py
window.protocol("WM_DELETE... | I had this problem and solved it by restarting my iPython-console (Spyder) |
5,898,555 | I'm playing with the [pyflakes plugin for vim](https://github.com/kevinw/pyflakes-vim) and now when I open a python file I get the error messages in the screenshot [here](http://dl.dropbox.com/u/6114719/Screenshot.png)
Any ideas how to fix this?
Thanks in advance... | 2011/05/05 | [
"https://Stackoverflow.com/questions/5898555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91748/"
] | Could be an issue with the version of Python you're running under vs. what the package you're using is looking for. A quick google for "Module getChildNodes python" got me to the page for [Python compiler package](http://docs.python.org/library/compiler.html) which has one of those nice little "Deprecated" messages on ... | This is a bug in pyflakes and we cannot help you with this here.
Try filing an issue on [their git repository](https://github.com/kevinw/pyflakes-vim/issues). |
5,898,555 | I'm playing with the [pyflakes plugin for vim](https://github.com/kevinw/pyflakes-vim) and now when I open a python file I get the error messages in the screenshot [here](http://dl.dropbox.com/u/6114719/Screenshot.png)
Any ideas how to fix this?
Thanks in advance... | 2011/05/05 | [
"https://Stackoverflow.com/questions/5898555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91748/"
] | <https://github.com/kevinw/pyflakes-vim/issues/27>
>
> You can recommend to users that they clone the pyflakes-vim repo with git clone --recursive or you can suggest after the fact to use git submodule update --init --recursive if pyflakes-vim is saved as a git submodule itself.
>
>
>
Or go to pyflakes-vim and:
... | This is a bug in pyflakes and we cannot help you with this here.
Try filing an issue on [their git repository](https://github.com/kevinw/pyflakes-vim/issues). |
5,898,555 | I'm playing with the [pyflakes plugin for vim](https://github.com/kevinw/pyflakes-vim) and now when I open a python file I get the error messages in the screenshot [here](http://dl.dropbox.com/u/6114719/Screenshot.png)
Any ideas how to fix this?
Thanks in advance... | 2011/05/05 | [
"https://Stackoverflow.com/questions/5898555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91748/"
] | I tried this to solve my problem under the Mac OS X 10.9.5.
```
sudo easy_install pip
pip install pyflakes
```
Then I opened the python scripts again, no issues reported as this:

Enjoy!
Robin
2015.01.30 | This is a bug in pyflakes and we cannot help you with this here.
Try filing an issue on [their git repository](https://github.com/kevinw/pyflakes-vim/issues). |
5,898,555 | I'm playing with the [pyflakes plugin for vim](https://github.com/kevinw/pyflakes-vim) and now when I open a python file I get the error messages in the screenshot [here](http://dl.dropbox.com/u/6114719/Screenshot.png)
Any ideas how to fix this?
Thanks in advance... | 2011/05/05 | [
"https://Stackoverflow.com/questions/5898555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91748/"
] | <https://github.com/kevinw/pyflakes-vim/issues/27>
>
> You can recommend to users that they clone the pyflakes-vim repo with git clone --recursive or you can suggest after the fact to use git submodule update --init --recursive if pyflakes-vim is saved as a git submodule itself.
>
>
>
Or go to pyflakes-vim and:
... | Could be an issue with the version of Python you're running under vs. what the package you're using is looking for. A quick google for "Module getChildNodes python" got me to the page for [Python compiler package](http://docs.python.org/library/compiler.html) which has one of those nice little "Deprecated" messages on ... |
5,898,555 | I'm playing with the [pyflakes plugin for vim](https://github.com/kevinw/pyflakes-vim) and now when I open a python file I get the error messages in the screenshot [here](http://dl.dropbox.com/u/6114719/Screenshot.png)
Any ideas how to fix this?
Thanks in advance... | 2011/05/05 | [
"https://Stackoverflow.com/questions/5898555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91748/"
] | Could be an issue with the version of Python you're running under vs. what the package you're using is looking for. A quick google for "Module getChildNodes python" got me to the page for [Python compiler package](http://docs.python.org/library/compiler.html) which has one of those nice little "Deprecated" messages on ... | I tried this to solve my problem under the Mac OS X 10.9.5.
```
sudo easy_install pip
pip install pyflakes
```
Then I opened the python scripts again, no issues reported as this:

Enjoy!
Robin
2015.01.30 |
5,898,555 | I'm playing with the [pyflakes plugin for vim](https://github.com/kevinw/pyflakes-vim) and now when I open a python file I get the error messages in the screenshot [here](http://dl.dropbox.com/u/6114719/Screenshot.png)
Any ideas how to fix this?
Thanks in advance... | 2011/05/05 | [
"https://Stackoverflow.com/questions/5898555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91748/"
] | <https://github.com/kevinw/pyflakes-vim/issues/27>
>
> You can recommend to users that they clone the pyflakes-vim repo with git clone --recursive or you can suggest after the fact to use git submodule update --init --recursive if pyflakes-vim is saved as a git submodule itself.
>
>
>
Or go to pyflakes-vim and:
... | I tried this to solve my problem under the Mac OS X 10.9.5.
```
sudo easy_install pip
pip install pyflakes
```
Then I opened the python scripts again, no issues reported as this:

Enjoy!
Robin
2015.01.30 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.