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 |
|---|---|---|---|---|---|
63,867,203 | I wrote some code in python to see how many times one number can be divided by a number, until it gets a value of one.
```
counter_var = 1
quotient = num1/num2
if quotient<1:
print('1 time')
else:
while quotient >= 1:
quotient = num1/num2
counter_var = counter_var + 1
print(counter_var)
... | 2020/09/13 | [
"https://Stackoverflow.com/questions/63867203",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14108602/"
] | you are not changing the value of quotient in the while loop. it remains constant.
instead of **quotient = num1/num2** it should be **quotient /= num2** if I understand your problem correctly. | Let us breakdown your code with an examples:
section 1: all good code
========================
```
counter_var = 1
quotient = num1/num2
if quotient<1:
print('1 time')
else:
```
section 2: problem code
=======================
```
while quotient >= 1:
quotient = num1/num2
counter_var = coun... |
63,867,203 | I wrote some code in python to see how many times one number can be divided by a number, until it gets a value of one.
```
counter_var = 1
quotient = num1/num2
if quotient<1:
print('1 time')
else:
while quotient >= 1:
quotient = num1/num2
counter_var = counter_var + 1
print(counter_var)
... | 2020/09/13 | [
"https://Stackoverflow.com/questions/63867203",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14108602/"
] | you are not changing the value of quotient in the while loop. it remains constant.
instead of **quotient = num1/num2** it should be **quotient /= num2** if I understand your problem correctly. | you write a infinite loop ! for example if you take 1 as input of num1 and 1 also an input of num2 ! so quotient here take 1 !! so you stuck in infinite loop ! i don't understand your program i mean what you wanna do ! you have to show me the problem first |
63,867,203 | I wrote some code in python to see how many times one number can be divided by a number, until it gets a value of one.
```
counter_var = 1
quotient = num1/num2
if quotient<1:
print('1 time')
else:
while quotient >= 1:
quotient = num1/num2
counter_var = counter_var + 1
print(counter_var)
... | 2020/09/13 | [
"https://Stackoverflow.com/questions/63867203",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14108602/"
] | you are not changing the value of quotient in the while loop. it remains constant.
instead of **quotient = num1/num2** it should be **quotient /= num2** if I understand your problem correctly. | The value of quotient is not changing so the loop is going on forever. For example if quotient is 3, num1 is 18 and num2 is 6. The program will go into the else statement and then continue on to the while statement. It divides 18 by 6 and sets the value of quotient to 3 and increments counter\_var by one. Than it goes ... |
3,300,716 | I'm attempting to use mysql after only having worked with sqlite in the past.
I've installed `XAMPP` on Linux (ubuntu) and have `mysql` up and running fine (seems like that with phpMyadmin at least). However, I'm having trouble getting the MySQLdb (the python lib) working {installed this using apt}.
to be exact:
```p... | 2010/07/21 | [
"https://Stackoverflow.com/questions/3300716",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/264875/"
] | For the record (and thanks to a pointer from Igancio), I found that the below works (terrible I didn't think of this before):
```
db=MySQLdb.connect(
user="root"
,passwd=""
,db="my_db"
,unix_socket="/opt/lampp/var/mysql/mysql.sock")
``` | It means that you didn't start the MySQL server, or it's configured to not use a domain socket. |
3,300,716 | I'm attempting to use mysql after only having worked with sqlite in the past.
I've installed `XAMPP` on Linux (ubuntu) and have `mysql` up and running fine (seems like that with phpMyadmin at least). However, I'm having trouble getting the MySQLdb (the python lib) working {installed this using apt}.
to be exact:
```p... | 2010/07/21 | [
"https://Stackoverflow.com/questions/3300716",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/264875/"
] | It means that you didn't start the MySQL server, or it's configured to not use a domain socket. | Have the same issue using and look for your SQL configuration file my.cnf.
```
# The following options will be passed to all MySQL clients
[client]
#password = your_password
port = 3306
socket = /Applications/XAMPP/xamppfiles/var/mysql/mysql.sock
```
and use socket as parameter:
```
mysql://read:read@... |
3,300,716 | I'm attempting to use mysql after only having worked with sqlite in the past.
I've installed `XAMPP` on Linux (ubuntu) and have `mysql` up and running fine (seems like that with phpMyadmin at least). However, I'm having trouble getting the MySQLdb (the python lib) working {installed this using apt}.
to be exact:
```p... | 2010/07/21 | [
"https://Stackoverflow.com/questions/3300716",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/264875/"
] | For the record (and thanks to a pointer from Igancio), I found that the below works (terrible I didn't think of this before):
```
db=MySQLdb.connect(
user="root"
,passwd=""
,db="my_db"
,unix_socket="/opt/lampp/var/mysql/mysql.sock")
``` | Have the same issue using and look for your SQL configuration file my.cnf.
```
# The following options will be passed to all MySQL clients
[client]
#password = your_password
port = 3306
socket = /Applications/XAMPP/xamppfiles/var/mysql/mysql.sock
```
and use socket as parameter:
```
mysql://read:read@... |
53,798,252 | I'm fairly new to python and attempting to add lines 1-10 of a csv into a JSON file, however, I only seem to be getting the 10th line of the CSV. I can't seem to figure out what is incorrect about my argument. Any help appcreated!
```
import csv, json, itertools
csvFilePath = "example.csv"
jsonFilePath = "example.jso... | 2018/12/15 | [
"https://Stackoverflow.com/questions/53798252",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10796111/"
] | At `data = csvRow`, the `data` variable keeps getting overwritten, so at the end only the last line you read will be inside `data`. Try something like this:
```
import csv, json, itertools
csvFilePath = "example.csv"
jsonFilePath = "example.json"
# Read the CSV and add data to a dictionary
data = {}
with open(csvFil... | Assuming that the input CSV is
```
1,2,3,4,5
a,b,c,d,e
```
We have the following code:
```
import json
import csv
inpf = open("test.csv", "r")
csv_reader = csv.reader(inpf)
# here you slice the columns with [2:4] for example
lines = [row[2:4] for row in csv_reader]
inpf.close()
lines_json = json.dumps(lines)
out... |
53,798,252 | I'm fairly new to python and attempting to add lines 1-10 of a csv into a JSON file, however, I only seem to be getting the 10th line of the CSV. I can't seem to figure out what is incorrect about my argument. Any help appcreated!
```
import csv, json, itertools
csvFilePath = "example.csv"
jsonFilePath = "example.jso... | 2018/12/15 | [
"https://Stackoverflow.com/questions/53798252",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10796111/"
] | At `data = csvRow`, the `data` variable keeps getting overwritten, so at the end only the last line you read will be inside `data`. Try something like this:
```
import csv, json, itertools
csvFilePath = "example.csv"
jsonFilePath = "example.json"
# Read the CSV and add data to a dictionary
data = {}
with open(csvFil... | You are overwriting your `data` dictionary in your loop through the file.
```
CSV_FILE_PATH = "example.csv"
with open(CSV_FILE_PATH) as myfile:
# You might set a key for each index as you loop:
data = {i: next(myfile) for i in range(10)}
print(data)
``` |
43,732,642 | I need the status of the task like if it is running or upforretry or failed within the same dag. So i tried to get it using the below code, though i got no output...
```
Auto = PythonOperator(
task_id='test_sleep',
python_callable=execute_on_emr,
op_kwargs={'cmd':'python /home/hadoop/test/testsleep.py'},
... | 2017/05/02 | [
"https://Stackoverflow.com/questions/43732642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6714806/"
] | Okay, I think I know what you're doing and I don't really agree with it, but I'll start with an answer.
A straightforward, but hackish, way would be to query the task\_instance table. I'm in postgres, but the structure should be the same. Start by grabbing the task\_ids and state of the task you're interested in with ... | You can use the command line Interface for this:
```
airflow task_state [-h] [-sd SUBDIR] dag_id task_id execution_date
```
For more on this you can refer official airflow documentation:
<http://airflow.incubator.apache.org/cli.html> |
43,732,642 | I need the status of the task like if it is running or upforretry or failed within the same dag. So i tried to get it using the below code, though i got no output...
```
Auto = PythonOperator(
task_id='test_sleep',
python_callable=execute_on_emr,
op_kwargs={'cmd':'python /home/hadoop/test/testsleep.py'},
... | 2017/05/02 | [
"https://Stackoverflow.com/questions/43732642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6714806/"
] | Take a look at the code responsible for the command line interface operation suggested by Priyank.
<https://github.com/apache/incubator-airflow/blob/2318cea74d4f71fba353eaca9bb3c4fd3cdb06c0/airflow/bin/cli.py#L581>
```
def task_state(args):
dag = get_dag(args)
task = dag.get_task(task_id=args.task_id)
ti ... | You can use the command line Interface for this:
```
airflow task_state [-h] [-sd SUBDIR] dag_id task_id execution_date
```
For more on this you can refer official airflow documentation:
<http://airflow.incubator.apache.org/cli.html> |
43,732,642 | I need the status of the task like if it is running or upforretry or failed within the same dag. So i tried to get it using the below code, though i got no output...
```
Auto = PythonOperator(
task_id='test_sleep',
python_callable=execute_on_emr,
op_kwargs={'cmd':'python /home/hadoop/test/testsleep.py'},
... | 2017/05/02 | [
"https://Stackoverflow.com/questions/43732642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6714806/"
] | I am doing something similar. I need to check for one task if the previous 10 runs of another task were successful.
taky2 sent me on the right path. It is actually fairly easy:
```
from airflow.models import TaskInstance
ti = TaskInstance(*your_task*, execution_date)
state = ti.current_state()
```
As I want to check... | You can use the command line Interface for this:
```
airflow task_state [-h] [-sd SUBDIR] dag_id task_id execution_date
```
For more on this you can refer official airflow documentation:
<http://airflow.incubator.apache.org/cli.html> |
43,732,642 | I need the status of the task like if it is running or upforretry or failed within the same dag. So i tried to get it using the below code, though i got no output...
```
Auto = PythonOperator(
task_id='test_sleep',
python_callable=execute_on_emr,
op_kwargs={'cmd':'python /home/hadoop/test/testsleep.py'},
... | 2017/05/02 | [
"https://Stackoverflow.com/questions/43732642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6714806/"
] | I am doing something similar. I need to check for one task if the previous 10 runs of another task were successful.
taky2 sent me on the right path. It is actually fairly easy:
```
from airflow.models import TaskInstance
ti = TaskInstance(*your_task*, execution_date)
state = ti.current_state()
```
As I want to check... | Okay, I think I know what you're doing and I don't really agree with it, but I'll start with an answer.
A straightforward, but hackish, way would be to query the task\_instance table. I'm in postgres, but the structure should be the same. Start by grabbing the task\_ids and state of the task you're interested in with ... |
43,732,642 | I need the status of the task like if it is running or upforretry or failed within the same dag. So i tried to get it using the below code, though i got no output...
```
Auto = PythonOperator(
task_id='test_sleep',
python_callable=execute_on_emr,
op_kwargs={'cmd':'python /home/hadoop/test/testsleep.py'},
... | 2017/05/02 | [
"https://Stackoverflow.com/questions/43732642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6714806/"
] | I am doing something similar. I need to check for one task if the previous 10 runs of another task were successful.
taky2 sent me on the right path. It is actually fairly easy:
```
from airflow.models import TaskInstance
ti = TaskInstance(*your_task*, execution_date)
state = ti.current_state()
```
As I want to check... | Take a look at the code responsible for the command line interface operation suggested by Priyank.
<https://github.com/apache/incubator-airflow/blob/2318cea74d4f71fba353eaca9bb3c4fd3cdb06c0/airflow/bin/cli.py#L581>
```
def task_state(args):
dag = get_dag(args)
task = dag.get_task(task_id=args.task_id)
ti ... |
12,125,362 | In a [previous question](https://stackoverflow.com/questions/12124275/splitting-a-string-by-capital-letters-python), it was suggested that, in order to divide a string and store it, I should use a list, like so:
```
[a for a in re.split(r'([A-Z][a-z]*)', 'MgSO4') if a]
['Mg', u'S', u'O', u'4']
```
What I'd like to a... | 2012/08/25 | [
"https://Stackoverflow.com/questions/12125362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1423819/"
] | If your goal is to be able to add up the molecular weights of the atoms comprising a molecule, I suggest doing your regular expressions a bit differently. Instead of having the numbers mixed in with the element symbols in your split list, attach them to the preceding element instead (and attach a 1 if there was no numb... | After running
```
>>> import re
>>> elements = [a for a in re.split(r'([A-Z][a-z]*)', 'MgSO4') if a]
```
you can access the splitted parts using indices
```
>>> print elements[0]
'Mg'
>>> print elements[-1] # print the last element
'4'
``` |
12,125,362 | In a [previous question](https://stackoverflow.com/questions/12124275/splitting-a-string-by-capital-letters-python), it was suggested that, in order to divide a string and store it, I should use a list, like so:
```
[a for a in re.split(r'([A-Z][a-z]*)', 'MgSO4') if a]
['Mg', u'S', u'O', u'4']
```
What I'd like to a... | 2012/08/25 | [
"https://Stackoverflow.com/questions/12125362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1423819/"
] | If your goal is to be able to add up the molecular weights of the atoms comprising a molecule, I suggest doing your regular expressions a bit differently. Instead of having the numbers mixed in with the element symbols in your split list, attach them to the preceding element instead (and attach a 1 if there was no numb... | This is just a guess, but it may be that you're not realizing that the `re.split` code can be applied to any string, including the string you read from `raw_input`. Is this what you're asking for?
```
formula = raw_input("Enter formula: ")
elements = [a for a in re.split(r'([A-Z][a-z]*)', formula) if a]
weight_sum =... |
34,794,417 | I am trying to make kivy work with SDL2 on centos 7 but when I run my main.py I get the following messages:
```
[INFO ] [Logger ] Record log in /home/etienne/.kivy/logs/kivy_16-01-14_51.txt
[INFO ] [Kivy ] v1.9.1
[INFO ] [Python ] v2.7.5 (default, Nov 20 2015, 02:00:19)
[GCC 4.8.5 20150623 (Red... | 2016/01/14 | [
"https://Stackoverflow.com/questions/34794417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5269531/"
] | Actually `sprintf` didn't work for me, so if you don't mind a common dependency:
```
#reproducible example -- this happens with zip codes sometimes
X <- data.frame(A = c('10002','8540','BIRD'), stringsAsFactors=FALSE)
# X$A <- sprintf('%05s',X$A) didn't work for me
# Note in ?sprintf: 0: For numbers, pad to the field... | Try something like this (assuming data frame name and column name are right):
```
element_of_X$a <- with(element_of_X , ifelse(nchar(a) == 4, paste('0', a, sep = ''), a)
``` |
34,794,417 | I am trying to make kivy work with SDL2 on centos 7 but when I run my main.py I get the following messages:
```
[INFO ] [Logger ] Record log in /home/etienne/.kivy/logs/kivy_16-01-14_51.txt
[INFO ] [Kivy ] v1.9.1
[INFO ] [Python ] v2.7.5 (default, Nov 20 2015, 02:00:19)
[GCC 4.8.5 20150623 (Red... | 2016/01/14 | [
"https://Stackoverflow.com/questions/34794417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5269531/"
] | This should do the trick:
```
X$A <- ifelse(nchar(X$A) < 5, paste("0", X$A, sep=""), X$A)
``` | Try something like this (assuming data frame name and column name are right):
```
element_of_X$a <- with(element_of_X , ifelse(nchar(a) == 4, paste('0', a, sep = ''), a)
``` |
34,794,417 | I am trying to make kivy work with SDL2 on centos 7 but when I run my main.py I get the following messages:
```
[INFO ] [Logger ] Record log in /home/etienne/.kivy/logs/kivy_16-01-14_51.txt
[INFO ] [Kivy ] v1.9.1
[INFO ] [Python ] v2.7.5 (default, Nov 20 2015, 02:00:19)
[GCC 4.8.5 20150623 (Red... | 2016/01/14 | [
"https://Stackoverflow.com/questions/34794417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5269531/"
] | If you use `dplyr` and `stringr` you could do the following
```
library(dplyr)
library(stringr)
## Assuming "element_of_X" has element 'A'
element_of_X <-
element_of_X %>%
mutate(A = str_pad(A, 5, side = 'left', pad = '0'))
```
**Edit**
Or perhaps more simply, as suggested in the comments:
```
element_of_... | Try something like this (assuming data frame name and column name are right):
```
element_of_X$a <- with(element_of_X , ifelse(nchar(a) == 4, paste('0', a, sep = ''), a)
``` |
34,794,417 | I am trying to make kivy work with SDL2 on centos 7 but when I run my main.py I get the following messages:
```
[INFO ] [Logger ] Record log in /home/etienne/.kivy/logs/kivy_16-01-14_51.txt
[INFO ] [Kivy ] v1.9.1
[INFO ] [Python ] v2.7.5 (default, Nov 20 2015, 02:00:19)
[GCC 4.8.5 20150623 (Red... | 2016/01/14 | [
"https://Stackoverflow.com/questions/34794417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5269531/"
] | Try something like this (assuming data frame name and column name are right):
```
element_of_X$a <- with(element_of_X , ifelse(nchar(a) == 4, paste('0', a, sep = ''), a)
``` | ```
library(stringr)
x$A=str_pad(x$A, 5, pad = "0")
``` |
34,794,417 | I am trying to make kivy work with SDL2 on centos 7 but when I run my main.py I get the following messages:
```
[INFO ] [Logger ] Record log in /home/etienne/.kivy/logs/kivy_16-01-14_51.txt
[INFO ] [Kivy ] v1.9.1
[INFO ] [Python ] v2.7.5 (default, Nov 20 2015, 02:00:19)
[GCC 4.8.5 20150623 (Red... | 2016/01/14 | [
"https://Stackoverflow.com/questions/34794417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5269531/"
] | Actually `sprintf` didn't work for me, so if you don't mind a common dependency:
```
#reproducible example -- this happens with zip codes sometimes
X <- data.frame(A = c('10002','8540','BIRD'), stringsAsFactors=FALSE)
# X$A <- sprintf('%05s',X$A) didn't work for me
# Note in ?sprintf: 0: For numbers, pad to the field... | This should do the trick:
```
X$A <- ifelse(nchar(X$A) < 5, paste("0", X$A, sep=""), X$A)
``` |
34,794,417 | I am trying to make kivy work with SDL2 on centos 7 but when I run my main.py I get the following messages:
```
[INFO ] [Logger ] Record log in /home/etienne/.kivy/logs/kivy_16-01-14_51.txt
[INFO ] [Kivy ] v1.9.1
[INFO ] [Python ] v2.7.5 (default, Nov 20 2015, 02:00:19)
[GCC 4.8.5 20150623 (Red... | 2016/01/14 | [
"https://Stackoverflow.com/questions/34794417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5269531/"
] | Actually `sprintf` didn't work for me, so if you don't mind a common dependency:
```
#reproducible example -- this happens with zip codes sometimes
X <- data.frame(A = c('10002','8540','BIRD'), stringsAsFactors=FALSE)
# X$A <- sprintf('%05s',X$A) didn't work for me
# Note in ?sprintf: 0: For numbers, pad to the field... | ```
library(stringr)
x$A=str_pad(x$A, 5, pad = "0")
``` |
34,794,417 | I am trying to make kivy work with SDL2 on centos 7 but when I run my main.py I get the following messages:
```
[INFO ] [Logger ] Record log in /home/etienne/.kivy/logs/kivy_16-01-14_51.txt
[INFO ] [Kivy ] v1.9.1
[INFO ] [Python ] v2.7.5 (default, Nov 20 2015, 02:00:19)
[GCC 4.8.5 20150623 (Red... | 2016/01/14 | [
"https://Stackoverflow.com/questions/34794417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5269531/"
] | If you use `dplyr` and `stringr` you could do the following
```
library(dplyr)
library(stringr)
## Assuming "element_of_X" has element 'A'
element_of_X <-
element_of_X %>%
mutate(A = str_pad(A, 5, side = 'left', pad = '0'))
```
**Edit**
Or perhaps more simply, as suggested in the comments:
```
element_of_... | This should do the trick:
```
X$A <- ifelse(nchar(X$A) < 5, paste("0", X$A, sep=""), X$A)
``` |
34,794,417 | I am trying to make kivy work with SDL2 on centos 7 but when I run my main.py I get the following messages:
```
[INFO ] [Logger ] Record log in /home/etienne/.kivy/logs/kivy_16-01-14_51.txt
[INFO ] [Kivy ] v1.9.1
[INFO ] [Python ] v2.7.5 (default, Nov 20 2015, 02:00:19)
[GCC 4.8.5 20150623 (Red... | 2016/01/14 | [
"https://Stackoverflow.com/questions/34794417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5269531/"
] | This should do the trick:
```
X$A <- ifelse(nchar(X$A) < 5, paste("0", X$A, sep=""), X$A)
``` | ```
library(stringr)
x$A=str_pad(x$A, 5, pad = "0")
``` |
34,794,417 | I am trying to make kivy work with SDL2 on centos 7 but when I run my main.py I get the following messages:
```
[INFO ] [Logger ] Record log in /home/etienne/.kivy/logs/kivy_16-01-14_51.txt
[INFO ] [Kivy ] v1.9.1
[INFO ] [Python ] v2.7.5 (default, Nov 20 2015, 02:00:19)
[GCC 4.8.5 20150623 (Red... | 2016/01/14 | [
"https://Stackoverflow.com/questions/34794417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5269531/"
] | If you use `dplyr` and `stringr` you could do the following
```
library(dplyr)
library(stringr)
## Assuming "element_of_X" has element 'A'
element_of_X <-
element_of_X %>%
mutate(A = str_pad(A, 5, side = 'left', pad = '0'))
```
**Edit**
Or perhaps more simply, as suggested in the comments:
```
element_of_... | ```
library(stringr)
x$A=str_pad(x$A, 5, pad = "0")
``` |
46,050,045 | I would like to run a bigquery query from python only if it is below a certain cost estimation.
Is there a way to programmatically check the estimated cost of a query before executing it, just like the Web UI (see attached image)?
[](https://i.stack.i... | 2017/09/05 | [
"https://Stackoverflow.com/questions/46050045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1134753/"
] | Yes, you can use the `dryRun` flag. This will return `totalBytesProcessed` i.e. the amount of data that will be processed if the query is executed.
<https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.dryRun>
[](https://i.stac... | >
> I would like to run a bigquery query from python only if it is below a certain cost estimation
>
>
>
First, please note - BigQuery UI in fact uses DryRun which only estimates `Total Bytes Processed` leaving another important factor `Billing Tier` unknown.
Use of DryRun of course useful and can help in cert... |
59,077,162 | I am using Python 3.8 and Pip 3.8
I cannot seem to install certain modules using pip. For example, when attempting to install the keras module:
```
(venv) C:\Users\Spencer Pruitt\PycharmProjects\MNIST Analyzer>pip install keras
Collecting keras
Using cached https://files.pythonhosted.org/packages/ad/fd/6bfe87920d7f... | 2019/11/27 | [
"https://Stackoverflow.com/questions/59077162",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12447974/"
] | Please use version <3.7 of python for numpy installation. Or see module/package required which version of python. So, just upgrade and degrade the python version to work with packages. | See [this thread](https://github.com/numpy/numpy/issues/11451) re: spaces in path causing issues with installing numpy. Any possibility of moving your virtual environment/project to something like "C:\Temp\MNIST\_Analyzer"?
[This thread](https://stackoverflow.com/questions/15472430/using-virtualenv-with-spaces-in-a-p... |
28,664,632 | This is my project set up:
```
my_project
./my_project
./__init__.py
./foo
./__init__.py
./bar.py
./tests
./__init__.py
./test_bar.py
```
Inside `test_bar.py` I have the following import statement:
`from foo import bar`
However wh... | 2015/02/22 | [
"https://Stackoverflow.com/questions/28664632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2680879/"
] | ```
import sys
sys.path.append('/path/to/my_project/')
```
Now you can import
```
from foo import bar
``` | You can use relative imports:
```
from ..foo import bar
```
<https://docs.python.org/2/whatsnew/2.5.html#pep-328-absolute-and-relative-imports>
but i think too that using absolute paths by [installing](https://docs.python.org/2/distutils/setupscript.html) your project in venv is better way. |
28,664,632 | This is my project set up:
```
my_project
./my_project
./__init__.py
./foo
./__init__.py
./bar.py
./tests
./__init__.py
./test_bar.py
```
Inside `test_bar.py` I have the following import statement:
`from foo import bar`
However wh... | 2015/02/22 | [
"https://Stackoverflow.com/questions/28664632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2680879/"
] | Think about what is on your `PYTHONPATH`. The toplevel package for your project is `my_project`, so that must be the start of any import for something in your project.
```
from my_project.foo import bar
```
You could also use a relative import, although this isn't as clear, and would break if you ever changed the re... | You can use relative imports:
```
from ..foo import bar
```
<https://docs.python.org/2/whatsnew/2.5.html#pep-328-absolute-and-relative-imports>
but i think too that using absolute paths by [installing](https://docs.python.org/2/distutils/setupscript.html) your project in venv is better way. |
28,664,632 | This is my project set up:
```
my_project
./my_project
./__init__.py
./foo
./__init__.py
./bar.py
./tests
./__init__.py
./test_bar.py
```
Inside `test_bar.py` I have the following import statement:
`from foo import bar`
However wh... | 2015/02/22 | [
"https://Stackoverflow.com/questions/28664632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2680879/"
] | Think about what is on your `PYTHONPATH`. The toplevel package for your project is `my_project`, so that must be the start of any import for something in your project.
```
from my_project.foo import bar
```
You could also use a relative import, although this isn't as clear, and would break if you ever changed the re... | ```
import sys
sys.path.append('/path/to/my_project/')
```
Now you can import
```
from foo import bar
``` |
62,126,379 | Very sorry in advance for the long paste.
The code is straight from the text. It may be due to class `Scene`, that seems to have the instruction to: subclass it and implement enter(). But I don't know what that means.
```py
from sys import exit
from random import randint
from textwrap import dedent
class Scene(obj... | 2020/06/01 | [
"https://Stackoverflow.com/questions/62126379",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9808986/"
] | The `enter` method for the `Death` Scene doesn't return anything. In Python, all functions without an explicit return statement return `None`, which explains the error you're getting.
```
class Death(Scene):
quips = [
"You died. You kinda suck at this.",
"Your Mom would be proud...if she were sma... | As the error says,
```
next_scene_name = current_scene.enter() AttributeError: 'Nonetype' object has no attribute 'enter'
```
That means that your `current_scene` variable is equal to `None` when you call `current_scene.enter()` in the `play` method. You need to make sure the variable `current_scene` is properly in... |
16,178,519 | I wrote a metaclass that I'm using for logging purposes in my python project. It makes every class automatically log all activity. The only issue is that I don't want to go into every file and have to add in:
```
__metaclass__ = myMeta
```
Is there a way to set the metaclass in the top level folder so that all the f... | 2013/04/23 | [
"https://Stackoverflow.com/questions/16178519",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1226565/"
] | No, you can only specify the metaclass per class or per module. You cannot set it for the whole package.
In Python 3.1 and onwards, you *can* intercept the `builtins.__build_class__` hook and insert a metaclass programatically, see [Overriding the default type() metaclass before Python runs](https://stackoverflow.com/... | Here's a simple technique. Just *subclass* the *class* itself with `__metaclass__` attribute in the subclass. This process can be automated.
util.py
```
class A(object):
def __init__(self, first, second):
self.first = first
self.second = second
def __str__(self):
return '{} {}'.format... |
20,428,784 | Is it possible to write every line, I receive from this script, into a mysql table ? I want to have 2 columns: The ip-adress I need for the command (ipAdresse) and a part of the output of the command itself (I want to split some content of the output).. I do not want to ask for any code but I just want to know whether ... | 2013/12/06 | [
"https://Stackoverflow.com/questions/20428784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2968265/"
] | Instead of using `respond_to?`
why don't you do:
```
def date_or_time?(obj)
obj.kind_of?(Date) || obj.kind_of?(Time)
end
[19] pry(main)> a = Date.new
=> #<Date: -4712-01-01 ((0j,0s,0n),+0s,2299161j)>
[20] pry(main)> date_or_time? a
=> true
[21] pry(main)> b = DateTime.new
=> #<DateTime: -4712-01-01T00:00:00+00:00 ... | Alternatively you could still use `respond_to?` with `:iso8601`. I believe only 'date-y' types will respond to that (Date, Time, DateTime). |
11,174,532 | I connect to a mysql database using pymysql and after executing a request I got the following string: `\xd0\xbc\xd0\xb0\xd1\x80\xd0\xba\xd0\xb0`.
This should be 5 characters in utf8, but when I do `print s.encode('utf-8')` I get this: `╨╝╨░╤А╨║╨░`. The string looks like byte representation of unicode characters, whic... | 2012/06/24 | [
"https://Stackoverflow.com/questions/11174532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1477552/"
] | You want to `decode` (not `encode`) to get a unicode string from a byte string.
```
>>> s = '\xd0\xbc\xd0\xb0\xd1\x80\xd0\xba\xd0\xb0'
>>> us = s.decode('utf-8')
>>> print us
марка
```
Note that you may not be able to `print` it because it contains characters outside ASCII. But you should be able to see its value in... | Mark is right: you need to decode the string. Byte strings become Unicode strings by decoding them, encoding goes the other way. This and many other details are at [Pragmatic Unicode, or, How Do I Stop The Pain?](http://bit.ly/unipain). |
9,425,556 | I'm trying to use the app wapiti to make some security test in a web project running in localhost, but i have some problems with the syntax of Python. I follow the instructions that they give in wapiti project site and write this:
```
C:\Python27\python C:\Wapiti\wapiti.py http://server.com/base/url/
```
but i get t... | 2012/02/24 | [
"https://Stackoverflow.com/questions/9425556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1229915/"
] | MapKit does not expose a means of performing driving directions. So, it's not as simple as asking the map to display a course from location A to location B. You have two options:
1) Integrate with Google's API to get the driving directions, and overlay your own lines onto the MapKit map.
or
2) Simply direct your use... | Actually there is no api supported by iPhone sdk to draw route on map. There a repo on github which is using google maps api to draw route on map by using map overlay. It has some limitation but you can take help from this repo - <https://github.com/kishikawakatsumi/MapKit-Route-Directions> |
32,788,322 | I want to add a column in a `DataFrame` with some arbitrary value (that is the same for each row). I get an error when I use `withColumn` as follows:
```
dt.withColumn('new_column', 10).head(5)
```
```none
---------------------------------------------------------------------------
AttributeError ... | 2015/09/25 | [
"https://Stackoverflow.com/questions/32788322",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1245418/"
] | **Spark 2.2+**
Spark 2.2 introduces `typedLit` to support `Seq`, `Map`, and `Tuples` ([SPARK-19254](https://issues.apache.org/jira/browse/SPARK-19254)) and following calls should be supported (Scala):
```scala
import org.apache.spark.sql.functions.typedLit
df.withColumn("some_array", typedLit(Seq(1, 2, 3)))
df.withC... | In spark 2.2 there are two ways to add constant value in a column in DataFrame:
1) Using `lit`
2) Using `typedLit`.
The difference between the two is that `typedLit` can also handle parameterized scala types e.g. List, Seq, and Map
**Sample DataFrame:**
```
val df = spark.createDataFrame(Seq((0,"a"),(1,"b"),(2,... |
32,788,322 | I want to add a column in a `DataFrame` with some arbitrary value (that is the same for each row). I get an error when I use `withColumn` as follows:
```
dt.withColumn('new_column', 10).head(5)
```
```none
---------------------------------------------------------------------------
AttributeError ... | 2015/09/25 | [
"https://Stackoverflow.com/questions/32788322",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1245418/"
] | **Spark 2.2+**
Spark 2.2 introduces `typedLit` to support `Seq`, `Map`, and `Tuples` ([SPARK-19254](https://issues.apache.org/jira/browse/SPARK-19254)) and following calls should be supported (Scala):
```scala
import org.apache.spark.sql.functions.typedLit
df.withColumn("some_array", typedLit(Seq(1, 2, 3)))
df.withC... | As the other answers have described, `lit` and `typedLit` are how to add constant columns to DataFrames. `lit` is an important Spark function that you will use frequently, but not for adding constant columns to DataFrames.
You'll commonly be using `lit` to create `org.apache.spark.sql.Column` objects because that's th... |
32,788,322 | I want to add a column in a `DataFrame` with some arbitrary value (that is the same for each row). I get an error when I use `withColumn` as follows:
```
dt.withColumn('new_column', 10).head(5)
```
```none
---------------------------------------------------------------------------
AttributeError ... | 2015/09/25 | [
"https://Stackoverflow.com/questions/32788322",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1245418/"
] | In spark 2.2 there are two ways to add constant value in a column in DataFrame:
1) Using `lit`
2) Using `typedLit`.
The difference between the two is that `typedLit` can also handle parameterized scala types e.g. List, Seq, and Map
**Sample DataFrame:**
```
val df = spark.createDataFrame(Seq((0,"a"),(1,"b"),(2,... | As the other answers have described, `lit` and `typedLit` are how to add constant columns to DataFrames. `lit` is an important Spark function that you will use frequently, but not for adding constant columns to DataFrames.
You'll commonly be using `lit` to create `org.apache.spark.sql.Column` objects because that's th... |
36,791,792 | I am using django-cors-headers to overcome cors issues in python django. But I am getting.
>
> 'Access-Control-Allow-Origin' header contains multiple values '\*, \*', but only one is allowed. while trying to access using angularjs from <http://localhost:8000>
>
>
>
here is my settings for CORS that I am using.
... | 2016/04/22 | [
"https://Stackoverflow.com/questions/36791792",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1433639/"
] | You need to do
```
MIDDLEWARE_CLASSES = (
...
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
...
)
CORS_ORIGIN_ALLOW_ALL = True #for testing.
```
Look `CorsMiddleware` is on top of `CommonMiddleware`.
Hope this helps. | ```
CORS_ORIGIN_ALLOW_ALL = False
```
change allow all to false |
30,930,052 | (I'm using Python 3.4 for this, on Windows)
So, I have this code I whipped out to better show my troubles:
```
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
os.startfile('C:\\téxt.txt')
```
On IDLE it works as it should (it just opens that file I specified), but on Console (double-click) it keeps saying ... | 2015/06/19 | [
"https://Stackoverflow.com/questions/30930052",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5026708/"
] | try this.
Select tableview and go to Attribute Inspector.
In separator just set the table view separator color to clear color. | Try this.
Select tableview and go to Attribute Inspector.
Find the property Separator and make it Default to None.
And also set the color to Clear Color.
I hope it will work for you...good luck !! :) |
30,930,052 | (I'm using Python 3.4 for this, on Windows)
So, I have this code I whipped out to better show my troubles:
```
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
os.startfile('C:\\téxt.txt')
```
On IDLE it works as it should (it just opens that file I specified), but on Console (double-click) it keeps saying ... | 2015/06/19 | [
"https://Stackoverflow.com/questions/30930052",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5026708/"
] | You just need to set the "selection" property of UITableViewCell to "none" and add the following code to your controller. see screenshot its working.

Code:
```
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)inde... | Try this.
Select tableview and go to Attribute Inspector.
Find the property Separator and make it Default to None.
And also set the color to Clear Color.
I hope it will work for you...good luck !! :) |
11,697,096 | I am trying to send a message through GCM (Google Cloud Messaging). I have registered through Google APIs, I can send a regID to my website (which is a Google App Engine Backend) from multiple Android test phones.
However, I can't send anything to GCM from Google App Engine. Here is what I am trying to use.
```
re... | 2012/07/28 | [
"https://Stackoverflow.com/questions/11697096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1256336/"
] | What are data2 and data3 used for ? The data you are posting was not proper json so you need to use json.dumps(data).Code should be like this :
```
json_data = {"collapse_key" : "Food-Promo", "data" : {
"Category" : "FOOD",
"Type": "VEG",
}, "registration_ids": [regId],
}
ur... | Try using [python-gcm](https://github.com/geeknam/python-gcm). It can handle errors as well. |
11,697,096 | I am trying to send a message through GCM (Google Cloud Messaging). I have registered through Google APIs, I can send a regID to my website (which is a Google App Engine Backend) from multiple Android test phones.
However, I can't send anything to GCM from Google App Engine. Here is what I am trying to use.
```
re... | 2012/07/28 | [
"https://Stackoverflow.com/questions/11697096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1256336/"
] | What are data2 and data3 used for ? The data you are posting was not proper json so you need to use json.dumps(data).Code should be like this :
```
json_data = {"collapse_key" : "Food-Promo", "data" : {
"Category" : "FOOD",
"Type": "VEG",
}, "registration_ids": [regId],
}
ur... | Here is how I ended up solving it, but the above works as well.
```
def sendGCM(self, regid, email, entry_id, date_modified, kind):
url = 'https://android.googleapis.com/gcm/send'
apiKey = _MY_API_KEY
myKey = "key=" + apiKey
json_data = { "registration_id": regid, "data" : {
"entry_id" : entr... |
11,697,096 | I am trying to send a message through GCM (Google Cloud Messaging). I have registered through Google APIs, I can send a regID to my website (which is a Google App Engine Backend) from multiple Android test phones.
However, I can't send anything to GCM from Google App Engine. Here is what I am trying to use.
```
re... | 2012/07/28 | [
"https://Stackoverflow.com/questions/11697096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1256336/"
] | Try using [python-gcm](https://github.com/geeknam/python-gcm). It can handle errors as well. | Here is how I ended up solving it, but the above works as well.
```
def sendGCM(self, regid, email, entry_id, date_modified, kind):
url = 'https://android.googleapis.com/gcm/send'
apiKey = _MY_API_KEY
myKey = "key=" + apiKey
json_data = { "registration_id": regid, "data" : {
"entry_id" : entr... |
67,828,477 | Iterable objects are those that implement `__iter__` function, which returns an iterator object, i.e. and object providing the functions `__iter__` and `__next__` and behaving correctly. Usually the size of the iterable object is not known beforehand, and iterable object is not expected to know how long the iteration w... | 2021/06/03 | [
"https://Stackoverflow.com/questions/67828477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6087087/"
] | It sounds like you're asking about something like `__length_hint__`. Excerpts from [PEP 424 – A method for exposing a length hint](https://peps.python.org/pep-0424/):
>
> CPython currently defines a `__length_hint__` method on several types, such as various iterators. This method is then used by various other functio... | If I now understand your question, you're still trying to combine two concepts that don't combine in quite this way. `generator` is a subclass of `iterator`; it's a process. `len` applies to data objects -- in particular, to the *iterable* object, as opposed to the *iterator* that traverses the object.
Therefore, a ge... |
4,364,087 | Can this be somehow overcome? Can a child process create a subprocess?
The problem is, I have a ready application which needs to call a Python script. This script on its own works perfectly, but it needs to call existing shell scripts.
Schematically the problem is in the following code:
### parent.py
```
import sub... | 2010/12/06 | [
"https://Stackoverflow.com/questions/4364087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/457921/"
] | >
> There should be nothing stopping you from using subprocess in both child.py and parent.py
>
>
>
I am able to run it perfectly fine. :)
**Issue Debugging**:
>
> You are using `python` and `/usr/sfw/bin/python`.
>
>
>
1. Is bare python pointing to the same python?
2. Can you check by typing 'which pytho... | Using `subprocess.call` is not the proper way to do it. In my view, `subprocess.Popen` would be better.
parent.py:
```
1 import subprocess
2
3 process = subprocess.Popen(['python', './child.py', 'arg1', 'arg2'],\
4 stdin=subprocess.PIPE, stdout=subprocess.PIPE,\
5 stderr=subprocess.PIPE)
6 process.w... |
4,364,087 | Can this be somehow overcome? Can a child process create a subprocess?
The problem is, I have a ready application which needs to call a Python script. This script on its own works perfectly, but it needs to call existing shell scripts.
Schematically the problem is in the following code:
### parent.py
```
import sub... | 2010/12/06 | [
"https://Stackoverflow.com/questions/4364087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/457921/"
] | >
> There should be nothing stopping you from using subprocess in both child.py and parent.py
>
>
>
I am able to run it perfectly fine. :)
**Issue Debugging**:
>
> You are using `python` and `/usr/sfw/bin/python`.
>
>
>
1. Is bare python pointing to the same python?
2. Can you check by typing 'which pytho... | You can try to add your python directory to sys.path in chield.py
```
import sys
sys.path.append('../')
```
Yes, it's bad way, but it can help you. |
38,909,543 | I am trying to convert a string to hex character by character, but I cant figure it out in Python3.
In older python versions, what I have below works:
```
test = "This is a test"
for c in range(0, len(test) ):
print( "0x%s"%string_value[i].encode("hex") )
```
But with python3 I am getting the following error:
... | 2016/08/12 | [
"https://Stackoverflow.com/questions/38909543",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1902666/"
] | In python 3x Use [`binascii`](https://docs.python.org/3.1/library/binascii.html) instead of hex:
```
>>> import binascii
>>> binascii.hexlify(b'< character / string>')
``` | How about:
```
>>> test = "This is a test"
>>> for c in range(0, len(test) ):
... print( "0x%x"%ord(test[c]))
...
0x54
0x68
0x69
0x73
0x20
0x69
0x73
0x20
0x61
0x20
0x74
0x65
0x73
0x74
``` |
38,909,543 | I am trying to convert a string to hex character by character, but I cant figure it out in Python3.
In older python versions, what I have below works:
```
test = "This is a test"
for c in range(0, len(test) ):
print( "0x%s"%string_value[i].encode("hex") )
```
But with python3 I am getting the following error:
... | 2016/08/12 | [
"https://Stackoverflow.com/questions/38909543",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1902666/"
] | In python 3x Use [`binascii`](https://docs.python.org/3.1/library/binascii.html) instead of hex:
```
>>> import binascii
>>> binascii.hexlify(b'< character / string>')
``` | To print:
```
for c in test:
print(hex(ord(c)))
```
To convert:
```
output = ''.join(hex(ord(c)) for c in test)
```
or without the '0x' in output:
```
output = ''.join(hex(ord(c))[2:] for c in test)
``` |
38,909,543 | I am trying to convert a string to hex character by character, but I cant figure it out in Python3.
In older python versions, what I have below works:
```
test = "This is a test"
for c in range(0, len(test) ):
print( "0x%s"%string_value[i].encode("hex") )
```
But with python3 I am getting the following error:
... | 2016/08/12 | [
"https://Stackoverflow.com/questions/38909543",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1902666/"
] | To print:
```
for c in test:
print(hex(ord(c)))
```
To convert:
```
output = ''.join(hex(ord(c)) for c in test)
```
or without the '0x' in output:
```
output = ''.join(hex(ord(c))[2:] for c in test)
``` | How about:
```
>>> test = "This is a test"
>>> for c in range(0, len(test) ):
... print( "0x%x"%ord(test[c]))
...
0x54
0x68
0x69
0x73
0x20
0x69
0x73
0x20
0x61
0x20
0x74
0x65
0x73
0x74
``` |
14,307,518 | I am only an hour into learning how [cron](http://en.wikipedia.org/wiki/Cron) jobs work, and this is what I have done so far. I’m using `crontab -e` to add my cron command, which is:
`0/1 * * * * /usr/bin/python /home/my_username/hello.py > /home/my_username/log.txt`
`crontab -l` confirms that my command is there.
H... | 2013/01/13 | [
"https://Stackoverflow.com/questions/14307518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1972942/"
] | Experiment shows that the `0/1` seems to be the problem.
`0/1` *should* be equivalent to `*`. If you replace `0/1` with `*`, it should work.
Here's my experimental crontab:
```
0/1 * * * * echo 0/1 >> cron0.log
* * * * * echo star >> cron1.log
```
This creates `cron1.log` but not `cron0.log`.
I'll look into th... | `0/1` seems to be formatted wrong for your version of cron.
I found this on [wikipedia](http://en.wikipedia.org/wiki/Cron#cite_ref-8):
>
> Some versions of cron may not accept a value preceding "/" if it is not a range,
> such as "0". An alternative would be replacing the zero with an asterisk.
>
>
>
So Keith ... |
60,963,452 | I am loading in a very large image (60,000 x 80,000 pixels) and am exceeding the max pixels I can load:
```none
cv2.error: OpenCV(4.2.0) /Users/travis/build/skvark/opencv-python/opencv/modules/imgcodecs/src/loadsave.cpp:75:
error: (-215:Assertion failed) pixels <= CV_IO_MAX_IMAGE_PIXELS in function 'validateInput... | 2020/04/01 | [
"https://Stackoverflow.com/questions/60963452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10537728/"
] | You have to modify the openCV source files and then compile it your own.
EDIT: You can also modify environment variables
```
export CV_IO_MAX_IMAGE_PIXELS=1099511627776
``` | For my problem I should have specified it was a .tif file (NOTE most large images will be in this file format anyway). In which case a very easy way to load it in to a numpy array (so it can then work with OpenCV) is with the package tifffile.
```
pip install tifffile as tifi
```
This will install it in your python ... |
60,963,452 | I am loading in a very large image (60,000 x 80,000 pixels) and am exceeding the max pixels I can load:
```none
cv2.error: OpenCV(4.2.0) /Users/travis/build/skvark/opencv-python/opencv/modules/imgcodecs/src/loadsave.cpp:75:
error: (-215:Assertion failed) pixels <= CV_IO_MAX_IMAGE_PIXELS in function 'validateInput... | 2020/04/01 | [
"https://Stackoverflow.com/questions/60963452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10537728/"
] | You have to modify the openCV source files and then compile it your own.
EDIT: You can also modify environment variables
```
export CV_IO_MAX_IMAGE_PIXELS=1099511627776
``` | Adding the following to your program should fix the issue in python opencv.
```
import os
os.environ["OPENCV_IO_MAX_IMAGE_PIXELS"] = str(pow(2,40))
import cv2
``` |
40,012,264 | I am new to python. I am trying to print sum of all duplicates nos and products of non-duplicates nos from the python list. for examples
list = [2,2,4,4,5,7,8,9,9]. what i want is sum= 2+2+4+4+9+9 and product=5\*7\*8. | 2016/10/13 | [
"https://Stackoverflow.com/questions/40012264",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4024000/"
] | You should not create a new `User` object when writing the parcel. You are operating on the current object instance.
I guess you can perform all the logic for object creation and reading the parcel in the `createFromParcel()` method but I have seen the pattern below more often where you pass the parcel into a construc... | For really **Boolean** (not **boolean**) I would go with:
```
@Override
public void writeToParcel(Parcel out, int flags) {
if (open_now == null) {
out.writeInt(-1);
} else {
out.writeInt(open_now ? 1 : 0);
}
```
and
```
private MyClass(Parcel in) {
switch ... |
41,065,879 | I am having trouble executing this python command and it keeps flagging this specific line. I've read the other posts about EOL, but I can't seem to find an issue with the types of quotes used.
```
logfile = "/Volumes/AC_SMN/03_DIGITAL_12/MD5_CHECKSUM_REPORTS/Text_Files” + id + ".txt"
SyntaxError: EOL while scanning ... | 2016/12/09 | [
"https://Stackoverflow.com/questions/41065879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7273874/"
] | The quote character after Text\_Files is incorrect. You could try this:
```
logfile = "/Volumes/AC_SMN/03_DIGITAL_12/MD5_CHECKSUM_REPORTS/Text_Files" + id + ".txt"
```
However, I would recommend using the string formatting syntax instead:
```
logfile = "/Volumes/AC_SMN/03_DIGITAL_12/MD5_CHECKSUM_REPORTS/Text_Files{... | you have used wrong quote at the end of `Text_Files” + id +`
```
logfile = "/Volumes/AC_SMN/03_DIGITAL_12/MD5_CHECKSUM_REPORTS/Text_Files” + id + ".txt"
```
instead use this (double quotes at the end of the string)
```
logfile = "/Volumes/AC_SMN/03_DIGITAL_12/MD5_CHECKSUM_REPORTS/Text_Files" + id + ".txt"
``` |
2,366,056 | I'm learning python with 'Dive Into Python 3' and It's very hard to remember everything, without writing something, but there are no exercises in this book. So I ask here, where can i find them to remember everything better. | 2010/03/02 | [
"https://Stackoverflow.com/questions/2366056",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/271388/"
] | I used [ProjectEuler.net](http://projecteuler.net/) when learning Python. It also helped sharpen my math skills. | Find a good Code Kata website: Here's a list I compiled.
<http://slott-softwarearchitect.blogspot.com/2009/08/code-kata-resources.html>
I've also collected lots of exercises: <http://homepage.mac.com/s_lott/books/python.html> This book, however, covers only Python 2.6, so it may be more confusing than helpful. |
2,366,056 | I'm learning python with 'Dive Into Python 3' and It's very hard to remember everything, without writing something, but there are no exercises in this book. So I ask here, where can i find them to remember everything better. | 2010/03/02 | [
"https://Stackoverflow.com/questions/2366056",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/271388/"
] | Consider using [*How to Think Like a Computer Scientist*](http://openbookproject.net/thinkcs/python/english2e/index.html) instead of *Dive Into Python* to learn Python. The former has exercises in every chapter, is targeted for a more appropriate version of Python (Python 3 does not have the library support to make it ... | Find a good Code Kata website: Here's a list I compiled.
<http://slott-softwarearchitect.blogspot.com/2009/08/code-kata-resources.html>
I've also collected lots of exercises: <http://homepage.mac.com/s_lott/books/python.html> This book, however, covers only Python 2.6, so it may be more confusing than helpful. |
57,901,183 | I am using python to parse CSV file but I face an issue how to extract "Davies" element from second row.
CSV looks like this
```
"_submissionusersID","_submissionresponseID","username","firstname","lastname","userid","phone","emailaddress","load_date"
"b838b35d-ca18-4c7c-874a-828298ae3345","e9cde2ff-33a7-477e-b3b9-1... | 2019/09/12 | [
"https://Stackoverflow.com/questions/57901183",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4655668/"
] | In the end I sort of solved this by repeatedly subscribing and unsubscribing from the ZMQ socket.
```
# This is run every time the subscriber receive function is called
socket.setsockopt(zmq.SUBSCRIBE, '')
md = socket.recv_json()
msg = socket.recv()
socket.setsockopt(zmq.UNSUBSCRIBE, '')
```
Essentially, I made it ... | Are you looking for `zmq.CONFLATE` option ("Last Message Only")?
Something like this in subscriber side:
```
context = zmq.Context()
socket = context.socket(zmq.SUB)
socket.setsockopt(zmq.SUBSCRIBE, '')
socket.setsockopt(zmq.CONFLATE, 1) # last msg only.
socket.connect("tcp://localhost:%s" % port) # must be placed... |
18,046,817 | I have been trying to add sub-directories to an "items" list and have settled on accomplishing this with the below code.
```
root, dirs, files = iter(os.walk(PATH_TO_DIRECTORY)).next()
items = [{
'label': directory, 'path': plugin.url_for('test')
} for count, directory in enumerate(dirs)]
```
The above works, b... | 2013/08/04 | [
"https://Stackoverflow.com/questions/18046817",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1743833/"
] | I have no idea what plugin.url\_for() does, but you should be able to speed it a bit doit it this way:
```
plugin_url_for = plugin.url_for
_, dirs, _ = iter(os.walk(PATH_TO_DIRECTORY)).next()
items = [{
'label': directory, 'path': plugin_url_for('test')
} for directory in dirs]
```
I dropped root, files variabl... | ```
dirlist = []
for root, dirs, files in os.walk(PATH_TO_DIRECTORY):
dirlist += dirs
```
Should do the trick!
For your revised question, I think what you really need is probably the output of:
```
Dirdict = {}
for (root, dirs, files) in os.walk (START):
Dirdict [root] = dirs
```
You might wish or need so... |
28,147,183 | I was reading about builder.connect\_signals which maps handlers of glade files with methods in your python file. Apparently works, except for the Main Window, which is not destroying when you close it. If you run it from terminal is still running and have to Ctrl-C to completely close the application.
Here is my pyth... | 2015/01/26 | [
"https://Stackoverflow.com/questions/28147183",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/598070/"
] | On closing window your window destroying but main loop of program don't stop, you must connect **destroy** event to the method/function that quit from this loop that ran from last line of code.
Make some change in below lines of codes:
```
#if (window):
# window.connect("destroy", gtk.main_quit)
```
change to:
... | You can use `GtkApplication` and `GtkApplicationWindow` to manage it for you. When Application has no more open windows, it will automatically terminate.
```
#!/usr/bin/env python
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
from gi.repository import Gio
class Mixer(Gtk.Application):
d... |
69,398,944 | I have this easy code to connect to download some data using `GRPC`
```
creds = grpc.ssl_channel_credentials()
channel = grpc.secure_channel(f'{HOST}:{PORT}', credentials=creds)
stub = liveops_pb2_grpc.LiveOpsStub(channel=channel)
request = project_pb2.ListProjectsRequest(organization=ORGANIZATION)
projects = stub.Lis... | 2021/09/30 | [
"https://Stackoverflow.com/questions/69398944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5556466/"
] | You can do that with the method [String#[]](https://ruby-doc.org/core-2.7.0/String.html#method-i-5B-5D) with an argument that is a regular expression.
```
r = /.*?\.(?:rb|com|net|br)(?!\.br)/
'giovanna.macedo@lojas100.com.br-215000695716b.ct.domain.com.br'[r]
#=> "giovanna.macedo@lojas100.com.br"
'alvaro-neves@stoc... | This should work for your scenario:
```rb
expr = /^(.+\.(?:br|com|net))-[^']+(')$/
str = "email = 'giovanna.macedo@lojas100.com.br-215000695716b.ct.domain.com.br'"
str.gsub(expr, '\1\2')
``` |
69,398,944 | I have this easy code to connect to download some data using `GRPC`
```
creds = grpc.ssl_channel_credentials()
channel = grpc.secure_channel(f'{HOST}:{PORT}', credentials=creds)
stub = liveops_pb2_grpc.LiveOpsStub(channel=channel)
request = project_pb2.ListProjectsRequest(organization=ORGANIZATION)
projects = stub.Lis... | 2021/09/30 | [
"https://Stackoverflow.com/questions/69398944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5556466/"
] | You can do that with the method [String#[]](https://ruby-doc.org/core-2.7.0/String.html#method-i-5B-5D) with an argument that is a regular expression.
```
r = /.*?\.(?:rb|com|net|br)(?!\.br)/
'giovanna.macedo@lojas100.com.br-215000695716b.ct.domain.com.br'[r]
#=> "giovanna.macedo@lojas100.com.br"
'alvaro-neves@stoc... | Use the String#delete\_suffix Method
------------------------------------
This was tested with Ruby 3.0.2. Your mileage may vary with other versions that don't support [String#delete\_suffix](https://ruby-doc.org/core-3.0.2/String.html#method-i-delete_suffix) or its [related bang method](https://ruby-doc.org/core-3.0.... |
69,398,944 | I have this easy code to connect to download some data using `GRPC`
```
creds = grpc.ssl_channel_credentials()
channel = grpc.secure_channel(f'{HOST}:{PORT}', credentials=creds)
stub = liveops_pb2_grpc.LiveOpsStub(channel=channel)
request = project_pb2.ListProjectsRequest(organization=ORGANIZATION)
projects = stub.Lis... | 2021/09/30 | [
"https://Stackoverflow.com/questions/69398944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5556466/"
] | You can do that with the method [String#[]](https://ruby-doc.org/core-2.7.0/String.html#method-i-5B-5D) with an argument that is a regular expression.
```
r = /.*?\.(?:rb|com|net|br)(?!\.br)/
'giovanna.macedo@lojas100.com.br-215000695716b.ct.domain.com.br'[r]
#=> "giovanna.macedo@lojas100.com.br"
'alvaro-neves@stoc... | I would just use the `chomp(string)` method like so:
```
mask = "-215000695716b.ct.domain.com.br"
email1.chomp(mask)
#=> "giovanna.macedo@lojas100.com.br"
email2.chomp(mask)
#=> "alvaro-neves@stockshop.com"
email3.chomp(mask)
#=> "filiallojas123@filiallojas.net"
``` |
50,598,438 | I am tracing a python script like this:
```
python -m trace --ignore-dir=$HOME/lib64:$HOME/lib:/usr -t bin/myscript.py
```
Some lines look like this:
```
--- modulename: __init__, funcname: getEffectiveLevel
__init__.py(1325): logger = self
__init__.py(1326): while logger:
__init__.py(1327): ... | 2018/05/30 | [
"https://Stackoverflow.com/questions/50598438",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/633961/"
] | if the purpose is finding the full path, then check [hunter](https://python-hunter.readthedocs.io/en/latest/readme.html#id1) project, it even has support for [query-style](https://python-hunter.readthedocs.io/en/latest/cookbook.html) tracing.
```
# a modified example from docs
# do check the documentation it is easy t... | Unfortunately there is no flag/command-line option to enable that. So the immediate (and probably correct) answer is: **No**.
If you're okay with messing with the built-in libraries you can easily make it possible by changing the line that reads:
```
print (" --- modulename: %s, funcname: %s"
% (modulename, c... |
50,598,438 | I am tracing a python script like this:
```
python -m trace --ignore-dir=$HOME/lib64:$HOME/lib:/usr -t bin/myscript.py
```
Some lines look like this:
```
--- modulename: __init__, funcname: getEffectiveLevel
__init__.py(1325): logger = self
__init__.py(1326): while logger:
__init__.py(1327): ... | 2018/05/30 | [
"https://Stackoverflow.com/questions/50598438",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/633961/"
] | if the purpose is finding the full path, then check [hunter](https://python-hunter.readthedocs.io/en/latest/readme.html#id1) project, it even has support for [query-style](https://python-hunter.readthedocs.io/en/latest/cookbook.html) tracing.
```
# a modified example from docs
# do check the documentation it is easy t... | You can create a `trace2.py` file with below content
```
from trace import Trace, main
original_globaltrace_lt = Trace.globaltrace_lt
def patch_Trace_globaltrace_lt(self, frame, why, arg):
value = original_globaltrace_lt(self, frame, why, arg)
if value:
filename = frame.f_globals.get('__file__', "")
... |
69,271,213 | There are several ways in python to generate a greyscale image from an RGB version. One of those is just to read an image as greyscale using OpenCV.
```
im = cv2.imread(img, 0)
```
While `0` equals `cv2.IMREAD_GRAYSCALE`
There are many different algorithms to handle this operation [well explained here.](https://www... | 2021/09/21 | [
"https://Stackoverflow.com/questions/69271213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5152497/"
] | I think basically @Dan Mašek already answered the question in the comment section.
I will try to summarize the findings for jpg files as an answer and I am glad about any improvements.
CMYK to Grayscale
-----------------
If you want to convert your jpg file from CMYK we have to look into [grfmt\_jpeg.cpp](https://... | in OpenCV [documentation](https://github.com/opencv/opencv/blob/master/modules/imgcodecs/include/opencv2/imgcodecs.hpp) you can find:
```
IMREAD_GRAYSCALE = 0, //!< If set, always convert image to the single channel grayscale image (codec internal conversion).
```
Also
>
> When using IMREAD\_GRAYSCALE, the codec'... |
30,196,585 | I've been struggling for hours on a problem that is making me insane. I installed Python 2.7 with Cygwin and added Scipy, Numpy, Matplotlib (1.4.3) and Ipython. When I decided to run `ipython --pylab` I get the following error:
```
/usr/lib/python2.7/site-packages/matplotlib/transforms.py in <module>()
37 import nump... | 2015/05/12 | [
"https://Stackoverflow.com/questions/30196585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4892337/"
] | For others having this problem, in my case, the solution was simple. The problem was caused by having the wrong matplot library installed on your computer; creating an error in finding the correct matplotlib path. In my case, I had installed matplotlib on a different version of python. Simply update matplotlib on your ... | I doubt that most of you brought here by Google have the problem I had, but just in case:
I got the above "ImportError: No module named \_path" (on Fedora 17) because I was trying to make use of matplotlib by just setting sys.path to point to where I had built the latest version (1.5.1 at the time). Don't do that.
On... |
30,196,585 | I've been struggling for hours on a problem that is making me insane. I installed Python 2.7 with Cygwin and added Scipy, Numpy, Matplotlib (1.4.3) and Ipython. When I decided to run `ipython --pylab` I get the following error:
```
/usr/lib/python2.7/site-packages/matplotlib/transforms.py in <module>()
37 import nump... | 2015/05/12 | [
"https://Stackoverflow.com/questions/30196585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4892337/"
] | For others having this problem, in my case, the solution was simple. The problem was caused by having the wrong matplot library installed on your computer; creating an error in finding the correct matplotlib path. In my case, I had installed matplotlib on a different version of python. Simply update matplotlib on your ... | The package matplotlib requires multiple dependencies (see them [here](https://matplotlib.org/users/installing.html)). For me, the missing dependencies included pyparsing and kiwisolver, but your results my vary. Before you do any of these other things (reinstalling python or the library, etc...), make sure you have in... |
46,368,931 | Here is my main.py:
```
#!/usr/bin/env python3
from kivy.app import App
from kivy.lang import Builder
from kivy.metrics import dp
from kivy.properties import ObjectProperty
from kivy.uix.image import Image
from kivy.uix.widget import Widget
from kivy.uix.boxlayout import BoxLayout
from kivymd.bottomsheet import MDList... | 2017/09/22 | [
"https://Stackoverflow.com/questions/46368931",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4085793/"
] | This works for me Try not to change MDRaisedButton size\_hint to 1 it raised this clock error , my suggestion is not to change any kivymd button size\_hint it is by default None rather you can change size in dp | This bug still persists in `MDRaisedButton` of KivyMD. A simple workaround to solve it is using `size_hint` instead of `size_hint_x`.
For example in your case, replace
```
MDRaisedButton:
size_hint_x: 1
```
by
```
MDRaisedButton:
size_hint: 1., None
``` |
14,206,637 | I am really new to the use of Python and the associated packages that can be installed.
As a biologist I am looking for a lot of new packages that would help me model species systems, ecological change etc.. and after a lot of "Google-ing" I came across scikit-learn.
However, I am having trouble installing it. And I wi... | 2013/01/08 | [
"https://Stackoverflow.com/questions/14206637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1956404/"
] | scikit-learn does not support Python 3 yet. For now you need Python 2.7.
Proper support for Python 3 is expected for the 0.14 release scheduled for Q2-2013. | I am no expert, but in my understanding the print statement in Python 3.\* is now a function, called like: print(). So, a quick solution in this case is to change
```
print "I: Seeding RNGs with %r" % _random_seed
```
to
```
print("I: Seeding RNGs with %r" % _random_seed)
``` |
9,331,000 | I'm trying to remove large blocks of text from a file using python. Each block of text begins with
/translation="SOMETEXT"
Ending with the second quote.
Can anyone give me some advice on how to accomplish this?
Thank you | 2012/02/17 | [
"https://Stackoverflow.com/questions/9331000",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1216584/"
] | You can use re.sub like this:
```
import re
re.sub("/translation=\".*?\" ", "", s)
``` | If performance doesn't matter, you could do something like this. Regular expressions would probably be faster, but this is simpler.
```
def remtxt(s,startstr,endstr):
while startstr in s:
startpos=s.index(startstr)
try:
endpos=s.index(endstr,startpos+len(... |
71,155,282 | Below is the html tag. I want to return the value in span as an integer in python selenium.
Can you help me out?
```html
<span class="pendingCount">
<img src="/static/media/sandPot.a436d753.svg" alt="sandPot">
<span>2</span>
</span>
``` | 2022/02/17 | [
"https://Stackoverflow.com/questions/71155282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14902563/"
] | You could use the dates for the x-axis, the 'constant' column for the y-axis,
and the Cluster id for the coloring.
You can create a custom legend using a list of colored rectangles.
```py
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
import pandas as pd
import numpy as np
N = 100
df = pd.... | You could just plot a normal bar graph, with 1 bar corresponding to 1 day. If you make the width also 1, it will look as if the patches are contiguous.
[](https://i.stack.imgur.com/jtFlV.png)
```
import numpy as np
import matplotlib.pyplot as plt
fr... |
48,655,638 | I think what I am trying to do is pretty much like [github issue in zeep repo](https://github.com/mvantellingen/python-zeep/issues/412) --- but sadly there is no response to this issue yet. I researched suds and installed and tried -- did not even get sending parameter to work and thought zeep seems better maintained?
... | 2018/02/07 | [
"https://Stackoverflow.com/questions/48655638",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2379736/"
] | You can use a Plugin for editing the xml as a plain string. I used this plugin for keeping the characters '<' and '>' in a CDATA element.
```
from xml import etree
from zeep import Plugin
class my_plugin(Plugin):
def egress(self, envelope, http_headers, operation, binding_options):
xml_string = etree.Ele... | On Python 3.9, @David Ortiz answer didn't work for me, maybe something has changed. The `etree_to_string` was failing to convert the XML to string.
What worked for me, instead of a plugin, I created a custom transport, that replaced the stripped tags with the correct characters, just like David's code, before the post... |
56,316,244 | I have some strange behavior on python 3.7 with a nested list comprehension that involves a generator.
**This works:**
```
i = range(20)
n = [1, 2, 3]
result = [min(x + y for x in i) for y in n]
```
It does **not work** if `i` is a generator:
```
i = (p for p in range(20))
n = [1, 2, 3]
result = [min(x + y for x ... | 2019/05/26 | [
"https://Stackoverflow.com/questions/56316244",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/51627/"
] | In both of your last examples, you try to iterate on the generator again after it got exhausted.
In your last example, `list(i)` is evaluated again for each value of `y`, so `i` will be exhausted after the first run.
You have to make a list of the values it yields once before, as in:
```
i = (p for p in range(20))
... | The generator is emptied after the first for loop for both `for x in i` or `for x in list(i)`, instead you need to convert the generator to a list, (which essentially iterates over the generator and empties it) beforehand and use that list
Note that this essentially defeats the purpose of a generator, since now this ... |
56,316,244 | I have some strange behavior on python 3.7 with a nested list comprehension that involves a generator.
**This works:**
```
i = range(20)
n = [1, 2, 3]
result = [min(x + y for x in i) for y in n]
```
It does **not work** if `i` is a generator:
```
i = (p for p in range(20))
n = [1, 2, 3]
result = [min(x + y for x ... | 2019/05/26 | [
"https://Stackoverflow.com/questions/56316244",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/51627/"
] | In `i = range(20)` the `range(20)` is a promise to generate a generator.
While `i = (p for p in range(20))` is already a generator.
Now write your list expression as:
```
for y in [1, 2, 3]:
print(min(x + y for x in i))
## 1
## ...
## ValueError: min() arg is an empty sequence
```
You get a `1` printed, but (t... | The generator is emptied after the first for loop for both `for x in i` or `for x in list(i)`, instead you need to convert the generator to a list, (which essentially iterates over the generator and empties it) beforehand and use that list
Note that this essentially defeats the purpose of a generator, since now this ... |
56,316,244 | I have some strange behavior on python 3.7 with a nested list comprehension that involves a generator.
**This works:**
```
i = range(20)
n = [1, 2, 3]
result = [min(x + y for x in i) for y in n]
```
It does **not work** if `i` is a generator:
```
i = (p for p in range(20))
n = [1, 2, 3]
result = [min(x + y for x ... | 2019/05/26 | [
"https://Stackoverflow.com/questions/56316244",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/51627/"
] | In `i = range(20)` the `range(20)` is a promise to generate a generator.
While `i = (p for p in range(20))` is already a generator.
Now write your list expression as:
```
for y in [1, 2, 3]:
print(min(x + y for x in i))
## 1
## ...
## ValueError: min() arg is an empty sequence
```
You get a `1` printed, but (t... | In both of your last examples, you try to iterate on the generator again after it got exhausted.
In your last example, `list(i)` is evaluated again for each value of `y`, so `i` will be exhausted after the first run.
You have to make a list of the values it yields once before, as in:
```
i = (p for p in range(20))
... |
70,969,920 | I am looping over a list of dictionaries and I have to drop/ignore either one or more keys of the each dictionary in the list and write it to a MongoDB. What is the efficient pythonic way of doing this ?
**Example:**
```
employees = [
{'name': "Tom", 'age': 10, 'salary': 10000, 'floor': 10},
{'name': "Mark", 'age': ... | 2022/02/03 | [
"https://Stackoverflow.com/questions/70969920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14066217/"
] | In the context you ask about you can think that closure is a function that references to some variables that are defined in its outer scope (for other cases see the answer by @phipsgabler). Here is a minimal example:
```
julia> function est_mean(x)
function fun(m)
return m - mean(x)
... | I'm going to complement Bogumił's answer by showing you what he has deliberately left out: a closure does not have to be a function in the strict sense. In fact, you could write them on your own, if nested functions were disallowed in Julia:
```
struct LikelihoodClosure
X
y
end
(l::LikelihoodClosure)(β) = -lo... |
21,811,851 | This question has been troubling me for some days now and I've tried asking in many places for advice, but it seems that nobody can answer it clearly or even provide a reference to an answer.
I've also tried searching for tutorials, but I just cannot find any type of tutorial that explains how you would use a reusable... | 2014/02/16 | [
"https://Stackoverflow.com/questions/21811851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1663535/"
] | TL;DR:
------
Nope & it depends...
Some (Very) Common Reusable Apps
--------------------------------
* [django.contrib.admin](https://docs.djangoproject.com/en/dev/ref/contrib/admin/)
* [django.contrib.auth](https://docs.djangoproject.com/en/dev/ref/contrib/auth/)
* [django.contrib.staticfiles](https://docs.djangopr... | I'm not sure why you think you need a main app for the "frontend" stuff. The point of a reusable app is that it takes care of everything, you just add (usually) a single URL to include the urls.py of the app, plus your own templates and styling as required.
And you certainly don't need to wrap the app's views in your ... |
48,642,572 | I'm trying to port a custom class from Python 2 to Python 3. I can't find the right syntax to port the iterator for the class. Here is a MVCE of the real class and my attempts to solve this so far:
Working Python 2 code:
```
class Temp:
def __init__(self):
self.d = dict()
def __iter__(self):
r... | 2018/02/06 | [
"https://Stackoverflow.com/questions/48642572",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4490400/"
] | As the error message suggests, your `__iter__` function does not return an iterator, which you can easily fix using the built-in `iter` function
```
class Temp:
def __init__(self):
self.d = {}
def __iter__(self):
return iter(self.d.items())
```
This will make your class iterable.
Alternativel... | I don't know what works in Python 2. But on Python 3 iterators can be most easily created using something called a [generator](https://www.pythoncentral.io/python-generators-and-yield-keyword/). I am providing the name and the link so that you can research further.
```
class Temp:
def __init__(self):
self.... |
21,179,140 | Okay, so in a terminal, after importing and making the necessary objects--I typed:
```
for links in soup.find_all('a'):
print(links.get('href'))
```
which gave me all the links on a wikipedia page (roughly 250). No problems.
However, in a program I am coding, I only receive about 60 links (and this is scraping... | 2014/01/17 | [
"https://Stackoverflow.com/questions/21179140",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3204909/"
] | This is not my answer. I got it from [here](http://fryandata.wordpress.com/2014/06/17/24/), which has helped me before.
```
from bs4 import BeautifulSoup
import csv
# Create .csv file with headers
f=csv.writer(open("nyccMeetings.csv","w"))
f.writerow(["Name", "Date", "Time", "Location", "Topic"])... | I have encountered many problems in my web scraping projects; however, BeautifulSoup was never the culprit.
I highly suspect you are having the same problem I had scraping Wikipedia. Wikipedia did not like my user-agent and was returning a page other than what I requested. Try adding a user-agent in your code e.g.
`M... |
13,925,355 | I wanted to run the command:
`repo init -u https://android.googlesource.com/platform/manifest -b android-4.1.1_r6`
and got the following output:
`Traceback (most recent call last):
File "/home/anu/bin/repo", line 91, in <module>
import readline
ImportError: No module named readline`
So to fix the above, I tried t... | 2012/12/18 | [
"https://Stackoverflow.com/questions/13925355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1649409/"
] | ```
sudo apt-get install libncurses5-dev
```
And then rerun you command | If you are running an 64 bit OS, you might have to install the i386 versions of the libraries. A lot (all?) of the Android host commands are 32-bit only. |
13,925,355 | I wanted to run the command:
`repo init -u https://android.googlesource.com/platform/manifest -b android-4.1.1_r6`
and got the following output:
`Traceback (most recent call last):
File "/home/anu/bin/repo", line 91, in <module>
import readline
ImportError: No module named readline`
So to fix the above, I tried t... | 2012/12/18 | [
"https://Stackoverflow.com/questions/13925355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1649409/"
] | ```
sudo apt-get install libncurses5-dev
```
And then rerun you command | I fixed above issue by installing python 2.7 .Guess the repo works fine with previous version of python and not the current version 2.7.3. |
43,748,464 | I have a large number of files with $Log expanded-keyword text at the end that needs to be deleted. I am looking to modify an existing python 2.7 script to do this but cannot get the regex working correctly.
The text to strip from the end of a file looks like this:
```
/*
one or more lines of ..
.. possible text
$Log... | 2017/05/02 | [
"https://Stackoverflow.com/questions/43748464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/947860/"
] | You can use:
```
result = re.sub(r"/\*\s+\*+\s+\$Log.*?\*/", "", subject, 0, re.DOTALL)
```
---
[](https://i.stack.imgur.com/YTKkn.jpg)
---
[Regex Demo](https://regex101.com/r/6AgeQe/4)
[Python Demo](https://ideone.com/QJmjUy) | It is a bit unclear what you are expecting as output. My understanding is that you are trying to extract the comment. I'm assuming that the comment appears on the 3rd line and you have to just extract the third line using regex. Regex Expression used:
```
(\$Log:.*[\r\n]*.*[\r\n])(.*)
```
After using the regex for m... |
43,748,464 | I have a large number of files with $Log expanded-keyword text at the end that needs to be deleted. I am looking to modify an existing python 2.7 script to do this but cannot get the regex working correctly.
The text to strip from the end of a file looks like this:
```
/*
one or more lines of ..
.. possible text
$Log... | 2017/05/02 | [
"https://Stackoverflow.com/questions/43748464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/947860/"
] | You can use:
```
result = re.sub(r"/\*\s+\*+\s+\$Log.*?\*/", "", subject, 0, re.DOTALL)
```
---
[](https://i.stack.imgur.com/YTKkn.jpg)
---
[Regex Demo](https://regex101.com/r/6AgeQe/4)
[Python Demo](https://ideone.com/QJmjUy) | ```
content = re.sub(re.compile(r'\/\*\n\**\n\$Log(?:.|[\n])*\*\/', re.DOTALL), '', content)
```
[Regex Explanation](https://i.stack.imgur.com/jyZyT.png) |
62,791,323 | I have recently upgraded my python/opencv for a project to python 3.7 + opencv 4.3.0 and now I have an issue with opencvs imshow. I am running Ubuntu 18.04 and am using conda venvs.
I tried to rerun this piece of code multiple times and half the time it correctly displays the white image, and half the time it displays... | 2020/07/08 | [
"https://Stackoverflow.com/questions/62791323",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13890473/"
] | ```
django_find_project = True
```
Add this to your `pytest.ini`.
**EDIT:**
It looks like you have spelled `DJANGO_SETTINGS_MODULE` wrong in your `pytest.ini`. Please fix it. | Pytest has an order of precedence when choosing which settings.py to be used in tests and the settings in the pytest.ini is only used as last resort.
Pytest first looks at the `--ds` setting when running your tests, if that is not set it then used the environment variable `DJANGO_SETTINGS_MODULE`, if this also not set... |
62,791,323 | I have recently upgraded my python/opencv for a project to python 3.7 + opencv 4.3.0 and now I have an issue with opencvs imshow. I am running Ubuntu 18.04 and am using conda venvs.
I tried to rerun this piece of code multiple times and half the time it correctly displays the white image, and half the time it displays... | 2020/07/08 | [
"https://Stackoverflow.com/questions/62791323",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13890473/"
] | ```
django_find_project = True
```
Add this to your `pytest.ini`.
**EDIT:**
It looks like you have spelled `DJANGO_SETTINGS_MODULE` wrong in your `pytest.ini`. Please fix it. | You have this issue because **pytest-django** is not installed in addition to your django project.
Do
`pip install pytest-django`
Excute `pytest` again |
62,791,323 | I have recently upgraded my python/opencv for a project to python 3.7 + opencv 4.3.0 and now I have an issue with opencvs imshow. I am running Ubuntu 18.04 and am using conda venvs.
I tried to rerun this piece of code multiple times and half the time it correctly displays the white image, and half the time it displays... | 2020/07/08 | [
"https://Stackoverflow.com/questions/62791323",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13890473/"
] | You have this issue because **pytest-django** is not installed in addition to your django project.
Do
`pip install pytest-django`
Excute `pytest` again | Pytest has an order of precedence when choosing which settings.py to be used in tests and the settings in the pytest.ini is only used as last resort.
Pytest first looks at the `--ds` setting when running your tests, if that is not set it then used the environment variable `DJANGO_SETTINGS_MODULE`, if this also not set... |
48,986,755 | I have a list which contains zeros and non-zero values. I want to find the range of zeros and non-zero values in terms of tuple inside the list. I am looking for package free solution with pythonic way. E.g.
```
a = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 11, 12,
12, 12, 13, 13, 17, 17, ... | 2018/02/26 | [
"https://Stackoverflow.com/questions/48986755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7819943/"
] | You could `enumerate()` to get the indexes, `itertools.groupby()` to group falsy (`0`) and truthy values together, and extract the start and end indexes with `operator.itemgetter(0, -1)`:
```
from operator import truth, itemgetter
from itertools import groupby
[itemgetter(0,-1)([i for i,v in g]) for _, g in groupby(e... | ```
import numpy as np
unique, counts = np.unique(a, return_counts=True)
idx = tuple(zip(unique, counts))
```
I think this will work for you. |
48,986,755 | I have a list which contains zeros and non-zero values. I want to find the range of zeros and non-zero values in terms of tuple inside the list. I am looking for package free solution with pythonic way. E.g.
```
a = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 11, 12,
12, 12, 13, 13, 17, 17, ... | 2018/02/26 | [
"https://Stackoverflow.com/questions/48986755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7819943/"
] | This is an answer without an external library:
```
pointer = 0
is_zero = True
result = []
def finder(p, is_z):
while (a[p] == 0) is is_z:
p += 1
if p == len(a):
return p
return p
while pointer < len(a):
tmp = finder(pointer, is_zero)
result.append((pointer, tmp - 1))
p... | ```
import numpy as np
unique, counts = np.unique(a, return_counts=True)
idx = tuple(zip(unique, counts))
```
I think this will work for you. |
48,986,755 | I have a list which contains zeros and non-zero values. I want to find the range of zeros and non-zero values in terms of tuple inside the list. I am looking for package free solution with pythonic way. E.g.
```
a = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 11, 12,
12, 12, 13, 13, 17, 17, ... | 2018/02/26 | [
"https://Stackoverflow.com/questions/48986755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7819943/"
] | Here my suggestion without external packages, short, readable and easily understandable:
```
# Compute list "b" by replacing any non-zero value of "a" with 1
b = list(map(int,[i != 0 for i in a]))
#Compute ranges of 0 and ranges of 1
idx = [] # result list of tuples
ind = 0 # index of first element of each rang... | ```
import numpy as np
unique, counts = np.unique(a, return_counts=True)
idx = tuple(zip(unique, counts))
```
I think this will work for you. |
48,986,755 | I have a list which contains zeros and non-zero values. I want to find the range of zeros and non-zero values in terms of tuple inside the list. I am looking for package free solution with pythonic way. E.g.
```
a = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 11, 12,
12, 12, 13, 13, 17, 17, ... | 2018/02/26 | [
"https://Stackoverflow.com/questions/48986755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7819943/"
] | No imports needed (so no need to search the library docs to work out how those imports work :-) and with comments.
```
# results is the output list, each entry is a list of startindex,stopindex
results = []
# each time round the logical value is remembered in previouslvalue
previouslvalue = None
for i,value in enumera... | ```
import numpy as np
unique, counts = np.unique(a, return_counts=True)
idx = tuple(zip(unique, counts))
```
I think this will work for you. |
48,986,755 | I have a list which contains zeros and non-zero values. I want to find the range of zeros and non-zero values in terms of tuple inside the list. I am looking for package free solution with pythonic way. E.g.
```
a = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 11, 12,
12, 12, 13, 13, 17, 17, ... | 2018/02/26 | [
"https://Stackoverflow.com/questions/48986755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7819943/"
] | You could `enumerate()` to get the indexes, `itertools.groupby()` to group falsy (`0`) and truthy values together, and extract the start and end indexes with `operator.itemgetter(0, -1)`:
```
from operator import truth, itemgetter
from itertools import groupby
[itemgetter(0,-1)([i for i,v in g]) for _, g in groupby(e... | This is an answer without an external library:
```
pointer = 0
is_zero = True
result = []
def finder(p, is_z):
while (a[p] == 0) is is_z:
p += 1
if p == len(a):
return p
return p
while pointer < len(a):
tmp = finder(pointer, is_zero)
result.append((pointer, tmp - 1))
p... |
48,986,755 | I have a list which contains zeros and non-zero values. I want to find the range of zeros and non-zero values in terms of tuple inside the list. I am looking for package free solution with pythonic way. E.g.
```
a = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 11, 12,
12, 12, 13, 13, 17, 17, ... | 2018/02/26 | [
"https://Stackoverflow.com/questions/48986755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7819943/"
] | Here my suggestion without external packages, short, readable and easily understandable:
```
# Compute list "b" by replacing any non-zero value of "a" with 1
b = list(map(int,[i != 0 for i in a]))
#Compute ranges of 0 and ranges of 1
idx = [] # result list of tuples
ind = 0 # index of first element of each rang... | You could `enumerate()` to get the indexes, `itertools.groupby()` to group falsy (`0`) and truthy values together, and extract the start and end indexes with `operator.itemgetter(0, -1)`:
```
from operator import truth, itemgetter
from itertools import groupby
[itemgetter(0,-1)([i for i,v in g]) for _, g in groupby(e... |
48,986,755 | I have a list which contains zeros and non-zero values. I want to find the range of zeros and non-zero values in terms of tuple inside the list. I am looking for package free solution with pythonic way. E.g.
```
a = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 11, 12,
12, 12, 13, 13, 17, 17, ... | 2018/02/26 | [
"https://Stackoverflow.com/questions/48986755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7819943/"
] | You could `enumerate()` to get the indexes, `itertools.groupby()` to group falsy (`0`) and truthy values together, and extract the start and end indexes with `operator.itemgetter(0, -1)`:
```
from operator import truth, itemgetter
from itertools import groupby
[itemgetter(0,-1)([i for i,v in g]) for _, g in groupby(e... | No imports needed (so no need to search the library docs to work out how those imports work :-) and with comments.
```
# results is the output list, each entry is a list of startindex,stopindex
results = []
# each time round the logical value is remembered in previouslvalue
previouslvalue = None
for i,value in enumera... |
48,986,755 | I have a list which contains zeros and non-zero values. I want to find the range of zeros and non-zero values in terms of tuple inside the list. I am looking for package free solution with pythonic way. E.g.
```
a = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 11, 12,
12, 12, 13, 13, 17, 17, ... | 2018/02/26 | [
"https://Stackoverflow.com/questions/48986755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7819943/"
] | Here my suggestion without external packages, short, readable and easily understandable:
```
# Compute list "b" by replacing any non-zero value of "a" with 1
b = list(map(int,[i != 0 for i in a]))
#Compute ranges of 0 and ranges of 1
idx = [] # result list of tuples
ind = 0 # index of first element of each rang... | This is an answer without an external library:
```
pointer = 0
is_zero = True
result = []
def finder(p, is_z):
while (a[p] == 0) is is_z:
p += 1
if p == len(a):
return p
return p
while pointer < len(a):
tmp = finder(pointer, is_zero)
result.append((pointer, tmp - 1))
p... |
48,986,755 | I have a list which contains zeros and non-zero values. I want to find the range of zeros and non-zero values in terms of tuple inside the list. I am looking for package free solution with pythonic way. E.g.
```
a = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 11, 12,
12, 12, 13, 13, 17, 17, ... | 2018/02/26 | [
"https://Stackoverflow.com/questions/48986755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7819943/"
] | Here my suggestion without external packages, short, readable and easily understandable:
```
# Compute list "b" by replacing any non-zero value of "a" with 1
b = list(map(int,[i != 0 for i in a]))
#Compute ranges of 0 and ranges of 1
idx = [] # result list of tuples
ind = 0 # index of first element of each rang... | No imports needed (so no need to search the library docs to work out how those imports work :-) and with comments.
```
# results is the output list, each entry is a list of startindex,stopindex
results = []
# each time round the logical value is remembered in previouslvalue
previouslvalue = None
for i,value in enumera... |
72,404,096 | Trying to run examples or telegram bots from official site - <https://github.com/python-telegram-bot/python-telegram-bot/tree/master/examples>
Installed :
```
pip install python-telegram-bot
```
and when i run the example, i got error back that version is not compatible.
```
if __version_info__ < (20, 0, 0, "alpha"... | 2022/05/27 | [
"https://Stackoverflow.com/questions/72404096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14333315/"
] | Assuming you have only one non-NaN per row, you can `stack`:
```py
df.stack().droplevel(1).to_frame(name='Fruits')
```
Output:
```
Fruits
0 Apple
1 Pear
2 Orange
3 Mango
4 banana
```
#### Handling rows with only NaNs:
```py
df.stack().droplevel(1).to_frame(name='Fruits').reindex(df.index)
```
Outpu... | I think this should give the desired output -
`df['Fruit1'].fillna(df['Fruit2'])` |
72,404,096 | Trying to run examples or telegram bots from official site - <https://github.com/python-telegram-bot/python-telegram-bot/tree/master/examples>
Installed :
```
pip install python-telegram-bot
```
and when i run the example, i got error back that version is not compatible.
```
if __version_info__ < (20, 0, 0, "alpha"... | 2022/05/27 | [
"https://Stackoverflow.com/questions/72404096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14333315/"
] | I would use [`bfill()`](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.bfill.html):
```
df = pd.DataFrame({
'fruit_1': [None, 'Pear', None, None],
'fruit_2': ['Apple', None, None, None],
'fruit_3': [None, None, 'Orange', None]})
df.bfill(axis=1).iloc[:,0].rename('fruits') # returns
```
... | I think this should give the desired output -
`df['Fruit1'].fillna(df['Fruit2'])` |
72,404,096 | Trying to run examples or telegram bots from official site - <https://github.com/python-telegram-bot/python-telegram-bot/tree/master/examples>
Installed :
```
pip install python-telegram-bot
```
and when i run the example, i got error back that version is not compatible.
```
if __version_info__ < (20, 0, 0, "alpha"... | 2022/05/27 | [
"https://Stackoverflow.com/questions/72404096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14333315/"
] | Assuming you have only one non-NaN per row, you can `stack`:
```py
df.stack().droplevel(1).to_frame(name='Fruits')
```
Output:
```
Fruits
0 Apple
1 Pear
2 Orange
3 Mango
4 banana
```
#### Handling rows with only NaNs:
```py
df.stack().droplevel(1).to_frame(name='Fruits').reindex(df.index)
```
Outpu... | We can use `combine_first` here:
```py
df["Fruits"] = df["Fruit1"].combine_first(df["Fruit2"])
```
We can also use `np.where`:
```py
df["Fruits"] = np.where(df["Fruit1"].isnull(), df["Fruit2"], df["Fruit1"])
``` |
72,404,096 | Trying to run examples or telegram bots from official site - <https://github.com/python-telegram-bot/python-telegram-bot/tree/master/examples>
Installed :
```
pip install python-telegram-bot
```
and when i run the example, i got error back that version is not compatible.
```
if __version_info__ < (20, 0, 0, "alpha"... | 2022/05/27 | [
"https://Stackoverflow.com/questions/72404096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14333315/"
] | I would use [`bfill()`](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.bfill.html):
```
df = pd.DataFrame({
'fruit_1': [None, 'Pear', None, None],
'fruit_2': ['Apple', None, None, None],
'fruit_3': [None, None, 'Orange', None]})
df.bfill(axis=1).iloc[:,0].rename('fruits') # returns
```
... | We can use `combine_first` here:
```py
df["Fruits"] = df["Fruit1"].combine_first(df["Fruit2"])
```
We can also use `np.where`:
```py
df["Fruits"] = np.where(df["Fruit1"].isnull(), df["Fruit2"], df["Fruit1"])
``` |
72,404,096 | Trying to run examples or telegram bots from official site - <https://github.com/python-telegram-bot/python-telegram-bot/tree/master/examples>
Installed :
```
pip install python-telegram-bot
```
and when i run the example, i got error back that version is not compatible.
```
if __version_info__ < (20, 0, 0, "alpha"... | 2022/05/27 | [
"https://Stackoverflow.com/questions/72404096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14333315/"
] | I would use [`bfill()`](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.bfill.html):
```
df = pd.DataFrame({
'fruit_1': [None, 'Pear', None, None],
'fruit_2': ['Apple', None, None, None],
'fruit_3': [None, None, 'Orange', None]})
df.bfill(axis=1).iloc[:,0].rename('fruits') # returns
```
... | Assuming you have only one non-NaN per row, you can `stack`:
```py
df.stack().droplevel(1).to_frame(name='Fruits')
```
Output:
```
Fruits
0 Apple
1 Pear
2 Orange
3 Mango
4 banana
```
#### Handling rows with only NaNs:
```py
df.stack().droplevel(1).to_frame(name='Fruits').reindex(df.index)
```
Outpu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.