title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags list |
|---|---|---|---|---|---|---|---|---|---|
No JSON object could be decoded, JvectorMap Converter | 38,929,030 | <p>Scenario is,</p>
<p>Im new to python and trying to generate jvectorMap using <code>Converter.py</code> plugin provided by <code>jVectorMap</code>,</p>
<p>I have installed OSGEO4W (Desktop INSTALL) on Windows 7 64bit. Python 2.7,GDAL 2.1.0 and Shapely is also installed under OSGEO4W.</p>
<p>I download shapefile</p... | 0 | 2016-08-13T03:56:34Z | 38,929,056 | <p>I suspect the issue is that the passed in arguments cannot be converted to JSON by the script due to a missing double quote at the end of your <code>--where</code>. It should probably be:</p>
<pre><code>--where "ISO_3166_2 = 'RU-' and code_hasc!=''"
</code></pre>
<p><strong>EDIT</strong>:</p>
<p>Turns out it's a ... | 0 | 2016-08-13T04:02:55Z | [
"python",
"json",
"windows",
"shapefile",
"jvectormap"
] |
Splitting a dictionary's multiple values from one key | 38,929,119 | <p>I have the dictionary:</p>
<pre><code>dict1 = {'A': {'val1': '5', 'val2': '1'},
'B': {'val1': '10', 'val2': '10'},
'C': {'val1': '15', 'val3': '100'}
</code></pre>
<p>Here, I have one key, with two values. I can obtain the key by using:</p>
<pre><code>letters = dict1.keys()
</code></pre>
<p>which retur... | 0 | 2016-08-13T04:14:44Z | 38,929,182 | <p>If I understand you correctly then:</p>
<pre><code>number1 = [val["val1"] for val in dict1.values()]
</code></pre>
<p>If you prefer, this will accomplish the same thing with lambdas.</p>
<pre><code>number1 = map(lambda value: value["val1"], dict1.values())
</code></pre>
<p>Note how you really need to take the di... | 1 | 2016-08-13T04:26:59Z | [
"python",
"python-2.7",
"dictionary"
] |
modifying argument value within function | 38,929,137 | <p>I am trying to figure out a way to modify the order of a list of tuples within a function without returning the list.</p>
<p>For example:</p>
<pre><code>L = [(2,4),(8,5),(1,3),(9,4)]
def sort_ratios(L):
L = sorted(L, key=lambda x: float(x[0])/float(x[1]))
return L
</code></pre>
<p>Thus, calling sort_ratio... | 0 | 2016-08-13T04:18:10Z | 38,929,170 | <p>Try <code>L.sort(key=lambda x: float(x[0])/float(x[1]))</code> for an in-place sort.</p>
| 4 | 2016-08-13T04:25:28Z | [
"python"
] |
"RuntimeError: working outside of application context" for config module | 38,929,153 | <p>I have a config.py module that I call from my main file, it has a variety of app.configs for jinja2filters and some other plugins I'm using:</p>
<p>excerpt of config.py:</p>
<pre><code>from flask import current_app as app
#imports go here
def function1:
print("hello")
app.config['PROPERTY_1'] = 'configgoes... | 0 | 2016-08-13T04:22:46Z | 38,929,258 | <p>Check out Flask's explanation of <a href="http://flask.pocoo.org/docs/0.10/appcontext/#creating-an-application-context" rel="nofollow">Application Contexts</a>.</p>
<p>In your <code>config.py</code> file, the <code>from flask import current_app as app</code> makes it so that the call to <code>app.config['PROPERTY_1... | 0 | 2016-08-13T04:41:13Z | [
"python",
"flask",
"jinja2"
] |
pandas DataFrame columns named True and False work just fine | 38,929,267 | <p>The sample code:</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.rand(5,2), columns=[True, False])
# All of the following works fine. Just like you would expect
# them to, if the columns had any other (string) name.
# (Because True == True, True == False and False == False are
# v... | 2 | 2016-08-13T04:42:26Z | 38,929,383 | <p>There is no witchcraft. As far as I know, columns can be labeled by any hashable type. Given that booleans are instances of ints, is it really any more strange than: </p>
<pre><code>In [7]: df1 = pd.DataFrame(np.random.rand(5,2), columns=[0, 1])
In [8]: df1
Out[8]:
0 1
0 0.706135 0.307180
1 0... | 2 | 2016-08-13T05:01:04Z | [
"python",
"pandas"
] |
pandas DataFrame columns named True and False work just fine | 38,929,267 | <p>The sample code:</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.rand(5,2), columns=[True, False])
# All of the following works fine. Just like you would expect
# them to, if the columns had any other (string) name.
# (Because True == True, True == False and False == False are
# v... | 2 | 2016-08-13T04:42:26Z | 38,930,045 | <p>There is no witchcraft!</p>
<p>The cool thing about <code>loc</code> is that you can pass boolean masks along side label indexing. The developers decided that if <code>loc</code> sees an array like structure of boolean values... then its going to be a mask.</p>
<pre><code>df[False]
0 0.385615
1 0.212807
2 ... | 1 | 2016-08-13T06:50:19Z | [
"python",
"pandas"
] |
pytesser giving import error | 38,929,372 | <p>I am trying to implement OCR in python. When I run the following code:</p>
<pre><code>from PIL import Image
from pytesser import *
image_file = 'menu.jpg'
im = Image.open(image_file)
text = image_to_string(im)
text = image_file_to_string(image_file)
text = image_file_to_string(image_file, graceful_errors=True)
pri... | 1 | 2016-08-13T04:59:19Z | 38,929,467 | <p>As per the traceback, error is not from <code>pytesser</code> in <code>c:\Python27\Lib\Site-Packages</code>, it is coming from <code>C:\Python27\pytesser.py line 6</code></p>
<p>Can you share the code at C:\Python27\pytesser.py line 6? or debug it by looking at code at <code>C:\Python27\pytesser.py line 6</code></p... | 0 | 2016-08-13T05:15:21Z | [
"python",
"python-2.7"
] |
How to pass a username from a Django login form? | 38,929,433 | <p>This will be an easy question for someone out there. I searched around quite a bit and if there's a thread that addresses this perfectly, please direct me and close this out. I'm building a very simple web form within our organization's website using Django. </p>
<p>In forms.py I've got a class for the login page:<... | 0 | 2016-08-13T05:11:16Z | 38,930,075 | <p>You need to use <code>authenticate</code> method provided by <code>Django</code> in order to get the user. The <code>authenticate</code> method returns a user if it finds one.
<br>
To <code>authenticate</code> a given <code>username</code> and <code>password</code>, use <code>authenticate()</code>. It takes two key... | 0 | 2016-08-13T06:53:31Z | [
"python",
"django",
"django-forms"
] |
How can I insert the Python timestamp time.strftime into a pathname for the filename output? | 38,929,493 | <p>Goal is to put a date-timestamp as the filename for output of photos of a Python script.</p>
<pre><code>timestr=time.strftime("%Y%m%d-%H%M%S")
</code></pre>
<p>gives me exactly what I want for print (timestr) but I cannot figure out how to insert this string for the file name into what I am given by:</p>
<pre><co... | 0 | 2016-08-13T05:19:56Z | 38,929,615 | <p>you are halfway done, now just try to change the file name that you are saving </p>
<pre><code>dir_path='path/to/save/'
timestr=time.strftime("%Y%m%d-%H%M%S")
file_name=timestr + '.jpg' #file name
path=dir_path+file_name #abs path of file
camera.capture(path)
</code></pre>
| 0 | 2016-08-13T05:38:40Z | [
"python"
] |
How can I insert the Python timestamp time.strftime into a pathname for the filename output? | 38,929,493 | <p>Goal is to put a date-timestamp as the filename for output of photos of a Python script.</p>
<pre><code>timestr=time.strftime("%Y%m%d-%H%M%S")
</code></pre>
<p>gives me exactly what I want for print (timestr) but I cannot figure out how to insert this string for the file name into what I am given by:</p>
<pre><co... | 0 | 2016-08-13T05:19:56Z | 38,932,335 | <p>Here's a proper solution:</p>
<pre><code>import time
import os
timestr, file_path = time.strftime("%Y%m%d-%H%M%S"), '/path/to/save/file.jpg'
filename, file_extension = os.path.splitext(file_path)
output = "{0}_{1}{2}".format(filename, timestr, file_extension)
print timestr, filename, output
</code></pre>
<p>outpu... | 0 | 2016-08-13T11:41:28Z | [
"python"
] |
Numpy: Reshape array along a specified axis | 38,929,531 | <p>I have the following array:</p>
<pre><code>x = np.arange(24).reshape((2,3,2,2))
array([[[[ 0, 1],
[ 2, 3]],
[[ 4, 5],
[ 6, 7]],
[[ 8, 9],
[10, 11]]],
[[[12, 13],
[14, 15]],
[[16, 17],
[18, 19]],
[[20, 21],
[22, 23]]]])
</code></pre>
<p>I would like to res... | 1 | 2016-08-13T05:28:56Z | 38,929,595 | <pre><code>x = np.arange(24).reshape((2,3,2,2))
y = np.dstack(zip(x))[0]
print y
</code></pre>
<p>result:</p>
<pre><code>[[[ 0 1]
[ 2 3]
[12 13]
[14 15]]
[[ 4 5]
[ 6 7]
[16 17]
[18 19]]
[[ 8 9]
[10 11]
[20 21]
[22 23]]]
</code></pre>
| 1 | 2016-08-13T05:36:11Z | [
"python",
"arrays",
"numpy"
] |
Numpy: Reshape array along a specified axis | 38,929,531 | <p>I have the following array:</p>
<pre><code>x = np.arange(24).reshape((2,3,2,2))
array([[[[ 0, 1],
[ 2, 3]],
[[ 4, 5],
[ 6, 7]],
[[ 8, 9],
[10, 11]]],
[[[12, 13],
[14, 15]],
[[16, 17],
[18, 19]],
[[20, 21],
[22, 23]]]])
</code></pre>
<p>I would like to res... | 1 | 2016-08-13T05:28:56Z | 38,929,684 | <p>Use <code>transpose</code> and then <code>reshape</code> like so -</p>
<pre><code>shp = x.shape
out = x.transpose(1,0,2,3).reshape(shp[1],-1,shp[-1])
</code></pre>
| 1 | 2016-08-13T05:50:46Z | [
"python",
"arrays",
"numpy"
] |
Get value from variable instead of command line in argparse | 38,929,563 | <p>I am using pynetdicom script to fetch the data from the dcm4chee.
to run the script I need to pass the arguments from the command line.
But I already have that value in some variable or in other object and I need to use from there but I am not getting how can I pass that value to the parser or Is it possible to do ... | 0 | 2016-08-13T05:32:36Z | 38,929,965 | <p>Put everything inside functions and call them wherever you like:</p>
<pre><code>#!/usr/bin/python
"""
For help on usage,
python qrscu.py -h
"""
import os
import argparse
from netdicom.applicationentity import AE
from netdicom.SOPclass import *
from dicom.dataset import Dataset, FileDataset
from dicom.UID import ... | 1 | 2016-08-13T06:37:28Z | [
"python",
"python-2.7",
"arguments",
"argparse"
] |
Get value from variable instead of command line in argparse | 38,929,563 | <p>I am using pynetdicom script to fetch the data from the dcm4chee.
to run the script I need to pass the arguments from the command line.
But I already have that value in some variable or in other object and I need to use from there but I am not getting how can I pass that value to the parser or Is it possible to do ... | 0 | 2016-08-13T05:32:36Z | 38,930,285 | <p>You can incorporate and use the script above in your own code by using the pyhton module <a href="https://docs.python.org/2/library/subprocess.html" rel="nofollow">subprocess</a>. It will let you run the script with arguments that you define depending on your variables or objects.</p>
<p>Example: Let say that you h... | 0 | 2016-08-13T07:20:19Z | [
"python",
"python-2.7",
"arguments",
"argparse"
] |
sending more than1000 requests per second in python | 38,929,590 | <p>I am trying to send requests concurrently to a server and then record the average latency using this code:</p>
<pre><code>import Queue
import time
import threading
import urllib2
data = "{"image_1":"abc/xyz.jpg"}"
headers = {.....}
def get_url(q, url):
num = 1
sum = 0
while num <= 200:
start... | 0 | 2016-08-13T05:35:08Z | 39,109,582 | <p>With qrequests you do not need to implement threading or queues. Grequests handles that all for you. Just do a normal request but use grequests instead like shown in the example.</p>
| 0 | 2016-08-23T19:51:23Z | [
"python",
"python-multithreading",
"grequests"
] |
Python - List of Assignments | 38,929,641 | <p>Is there a way to have</p>
<pre><code>statements = [statement1, statement2, statement3, ...]
</code></pre>
<p>in Python?</p>
<p>I want to be able to do:</p>
<pre><code>run statements[i]
</code></pre>
<p>or:</p>
<p><code>f = statements[j]</code> (where f is a function)</p>
<p>P.S. I want to have a list of assi... | 1 | 2016-08-13T05:44:02Z | 38,929,678 | <p>This is a perfectly fine usage in python as in python function is first class</p>
<p>You can use </p>
<pre><code>def add(a,b):
return a+b
def sub(a,b):
return a-b;
funcs = [add,sub]
for func in funcs:
print func[10,15]
</code></pre>
<p>Or you may use lamdas instead of defining the functions in advanc... | 0 | 2016-08-13T05:49:56Z | [
"python"
] |
Python - List of Assignments | 38,929,641 | <p>Is there a way to have</p>
<pre><code>statements = [statement1, statement2, statement3, ...]
</code></pre>
<p>in Python?</p>
<p>I want to be able to do:</p>
<pre><code>run statements[i]
</code></pre>
<p>or:</p>
<p><code>f = statements[j]</code> (where f is a function)</p>
<p>P.S. I want to have a list of assi... | 1 | 2016-08-13T05:44:02Z | 38,929,680 | <p>This is perfectly fine:</p>
<pre><code>def addbla(item):
return item + ' bla'
items = ['Trump', 'Donald', 'tax declaration']
new_items = [addbla(item) for item in items]
print(new_items)
</code></pre>
<p>It adds a <em>political statement</em> to every item in <code>items</code> :)</p>
| 0 | 2016-08-13T05:50:21Z | [
"python"
] |
Python - List of Assignments | 38,929,641 | <p>Is there a way to have</p>
<pre><code>statements = [statement1, statement2, statement3, ...]
</code></pre>
<p>in Python?</p>
<p>I want to be able to do:</p>
<pre><code>run statements[i]
</code></pre>
<p>or:</p>
<p><code>f = statements[j]</code> (where f is a function)</p>
<p>P.S. I want to have a list of assi... | 1 | 2016-08-13T05:44:02Z | 38,929,682 | <p>If you want to run a block of statements, use a function.</p>
<pre><code>def run_statements():
func()
for i in range(3):
if i > 1:
break
extra_func()
run_statements()
</code></pre>
<p>If you want to choose specific statements from a list, wrap each one in a function:</p>
<pre><... | 0 | 2016-08-13T05:50:35Z | [
"python"
] |
Python - List of Assignments | 38,929,641 | <p>Is there a way to have</p>
<pre><code>statements = [statement1, statement2, statement3, ...]
</code></pre>
<p>in Python?</p>
<p>I want to be able to do:</p>
<pre><code>run statements[i]
</code></pre>
<p>or:</p>
<p><code>f = statements[j]</code> (where f is a function)</p>
<p>P.S. I want to have a list of assi... | 1 | 2016-08-13T05:44:02Z | 38,929,738 | <p>Yes. Functions are <em>first-class-citizens</em> in python: i.e. you could pass them as parameters or even store them in an array. </p>
<p>It is not uncommon to have a list of functions:
You could build a simple registry in python like this:</p>
<pre><code>#!/usr/bin/env python
processing_pipeline = []
def step(... | 4 | 2016-08-13T05:58:27Z | [
"python"
] |
Python - List of Assignments | 38,929,641 | <p>Is there a way to have</p>
<pre><code>statements = [statement1, statement2, statement3, ...]
</code></pre>
<p>in Python?</p>
<p>I want to be able to do:</p>
<pre><code>run statements[i]
</code></pre>
<p>or:</p>
<p><code>f = statements[j]</code> (where f is a function)</p>
<p>P.S. I want to have a list of assi... | 1 | 2016-08-13T05:44:02Z | 38,929,739 | <p>You can do:</p>
<pre><code>funcs = [min, max, sum]
f = funcs[0]
funcs[1](1,2,3) # out 3
funcs[2]([1,2,3]) # out 6
</code></pre>
| 0 | 2016-08-13T05:58:52Z | [
"python"
] |
Python - List of Assignments | 38,929,641 | <p>Is there a way to have</p>
<pre><code>statements = [statement1, statement2, statement3, ...]
</code></pre>
<p>in Python?</p>
<p>I want to be able to do:</p>
<pre><code>run statements[i]
</code></pre>
<p>or:</p>
<p><code>f = statements[j]</code> (where f is a function)</p>
<p>P.S. I want to have a list of assi... | 1 | 2016-08-13T05:44:02Z | 38,930,766 | <blockquote>
<p>I want to be able to do: <code>run statements[i]</code></p>
</blockquote>
<p>well, you can do that by <strong>exec</strong>:</p>
<pre><code>statements = ["result=max(1,2)","print(result)"]
for idx in range(len(statements)):
exec(statements[idx])
print(result)
</code></pre>
<p>Hope it helps!</p>... | 0 | 2016-08-13T08:23:06Z | [
"python"
] |
Python - List of Assignments | 38,929,641 | <p>Is there a way to have</p>
<pre><code>statements = [statement1, statement2, statement3, ...]
</code></pre>
<p>in Python?</p>
<p>I want to be able to do:</p>
<pre><code>run statements[i]
</code></pre>
<p>or:</p>
<p><code>f = statements[j]</code> (where f is a function)</p>
<p>P.S. I want to have a list of assi... | 1 | 2016-08-13T05:44:02Z | 39,116,194 | <p>Since we've had every other way, I thought I'd toss this out:</p>
<pre><code>def a(input):
return pow(input, 3)
def b(input):
return abs(input)
def c(input):
return "I have {0} chickens".format(str(input))
#make an array of functions
foo = [a,b,c]
#make a list comprehension of the list of functions
... | 0 | 2016-08-24T06:46:31Z | [
"python"
] |
django-mongodb-engine can't update an object | 38,929,708 | <p>I am writing a Django-based back end using django-mongodb-engine for an android app and I'm trying to get data from a PUT request to update a record in my database. I'm getting a username and filtering the database for the user object with that name (successfully), but the save function doesn't seem to be saving th... | 0 | 2016-08-13T05:53:57Z | 38,938,428 | <p>Found an answer to this question. I'm not sure why it wasn't working as posted, but there were problems trying to access the object through the list... in other words the following didn't work:</p>
<pre><code>existing_user[0].userName = "Barney"
existing_user[0].save()
</code></pre>
<p>But this did:</p>
<pre><co... | 0 | 2016-08-14T01:31:33Z | [
"python",
"django",
"mongodb"
] |
Pandas: Rolling sum with multiple indexes (i.e. panel data) | 38,929,737 | <p>I have a dataframe with multiple index and would like to create a rolling sum of some data, but for each id in the index.</p>
<p>For instance, let us say I have two indexes (<em>Firm</em> and <em>Year</em>) and I have some data with name <em>zdata</em>. The working example is the following:</p>
<pre><code>import p... | 2 | 2016-08-13T05:58:25Z | 38,929,931 | <p><strong><em>Option 1</em></strong></p>
<pre><code>mydf.unstack(0).rolling(2).sum().stack().swaplevel(0, 1).sort_index()
</code></pre>
<p><a href="http://i.stack.imgur.com/9yYCq.png" rel="nofollow"><img src="http://i.stack.imgur.com/9yYCq.png" alt="enter image description here"></a></p>
<p><strong><em>Option 2</em... | 1 | 2016-08-13T06:32:26Z | [
"python",
"pandas",
"panel",
"multi-index",
"rolling-sum"
] |
Send multiple Web requests | 38,929,778 | <p>Im trying to send API requests at specific rate (Example using QPS value),
I'm using the following code to launch my requests (stored in web_requests list).</p>
<p>If I set QPS=10, delay will be 0.1s or 100 ms. I use time.sleep(0.1) and send a request, but this code is waiting for remote end HTTP response which is ... | 0 | 2016-08-13T06:07:56Z | 38,933,772 | <p>Simply do not "yield" the future returned by "fetch". Then your coroutine will continue looping immediately, and the callback is executed when the fetch completes in the background.</p>
<p>Also, never ever ever call "sleep" in a Tornado application:</p>
<p><a href="http://www.tornadoweb.org/en/stable/faq.html#why-... | 1 | 2016-08-13T14:35:49Z | [
"python",
"multithreading",
"web-services",
"tornado"
] |
sending a function instance over API (django) | 38,929,855 | <p>maybe a stupid question :)
I have two Django apps,
I need one of them to use the functions of the other one without importing them.
as if I am requesting them using API, is there a way I can get an instance of a function and use it, I don't want to do the following:</p>
<pre><code>response = requests.get('HTTP://UR... | 0 | 2016-08-13T06:21:53Z | 38,931,071 | <p>You can use <code>marshal</code> module to serialize function code, add it as a request content and deserialize in the other app.</p>
<pre><code>In [13]: def foo(a, b):
print a + b
....:
In [14]: import marshal
In [15]: a = marshal.dumps(foo.func_code)
In [16]: a
Out[16]:
'c\x02\x00\x00\x00\x02\x00\x00\x00... | 0 | 2016-08-13T09:01:17Z | [
"python",
"function",
"instance",
"django-apps"
] |
Django Error : 'WSGIRequest' object has no attribute 'user' | 38,930,157 | <p><br>
I'm practicing django.<br>
Before I met this error message that is</p>
<blockquote>
<p>'WSGIRequest' object has no attribute 'user'</p>
</blockquote>
<p>, I restart project and it was disappeared.<br>
Today, I met this error message again. I want to fix.<br>
It's OK when I open </p>
<blockquote>
<p>local... | 0 | 2016-08-13T07:02:58Z | 38,930,587 | <p>Change in settings.py <code>MIDDLEWARE</code> to <code>MIDDLEWARE_CLASSES</code>.</p>
| 2 | 2016-08-13T07:59:43Z | [
"python",
"django"
] |
Django Error : 'WSGIRequest' object has no attribute 'user' | 38,930,157 | <p><br>
I'm practicing django.<br>
Before I met this error message that is</p>
<blockquote>
<p>'WSGIRequest' object has no attribute 'user'</p>
</blockquote>
<p>, I restart project and it was disappeared.<br>
Today, I met this error message again. I want to fix.<br>
It's OK when I open </p>
<blockquote>
<p>local... | 0 | 2016-08-13T07:02:58Z | 38,930,620 | <p><code>request.user</code> is added by <a href="https://docs.djangoproject.com/en/1.10/ref/middleware/#django.contrib.auth.middleware.AuthenticationMiddleware" rel="nofollow"><code>AuthenticationMiddleware</code></a>. As you can easily see from the error message, you don't have that loaded.</p>
<p>As noted by @Serge... | 2 | 2016-08-13T08:03:30Z | [
"python",
"django"
] |
Python 2.7, finding length of numpy.ndarray | 38,930,191 | <p>So with my code, I'm analyzing the total number of pixels that are within the threshold of my values. However, it's very slow, and it all comes down to one line of code, basically bottle-necking the entire program. This code is simple, in that it splits the array up into the values so I can count the length, however... | 2 | 2016-08-13T07:07:07Z | 38,930,476 | <blockquote>
<p>I don't want the size of the picture itself, nor how many total
pixels. Just the pixels that are within the threshold.</p>
</blockquote>
<p><code>cv2.inRange</code> already does that, so the <em>set comprehension</em> will not be required:</p>
<blockquote>
<p>After calling <code>cv2.inRange</cod... | 1 | 2016-08-13T07:44:57Z | [
"python",
"arrays",
"python-2.7",
"opencv",
"numpy"
] |
Error: Unexpected eof while parsing? | 38,930,206 | <p>Im writing my first code and can't figure out what this error means and what i should fix, Please help. Error: Unexpected eof while parsing</p>
<pre><code>import math
def circumference(r):
return 2 * math.pi * r
def area(r) :
return math.pi * radius**2 * r
fName = input("Please enter your first name: ")
lName = ... | -1 | 2016-08-13T07:09:14Z | 38,931,148 | <p>You need to close every parenthesis you open. The line of code that is probably causing the error is this:</p>
<pre><code>print("Hello %s %s Your circumference is %s and your area is %s " % (fName, lName, circumference(radius), area(radius))
</code></pre>
<p>You're missing a ")" at the end.</p>
| 0 | 2016-08-13T09:10:31Z | [
"python",
"python-3.x"
] |
Update creates a new entity instead of updating the current one on Google's Datastore | 38,930,291 | <p>Working on an app in python deployed over the google app engine.</p>
<p>Here is the code i used to do the update.</p>
<pre><code>key = ndb.Key('User', uid)
user = key.get()
if not user:
logging.info("Creating new user...")
user = M.User(id=uid)
user.remind = tmp
... | 0 | 2016-08-13T07:21:29Z | 39,000,551 | <p>if you want to update an entity you ought to retrieve this entity by his id, then you can change the old value. For exemple:</p>
<pre><code>entity_to_edit = Entity.get_by_id(this_entit_id)
entity_to_edit.some_attribute = "new_variable"
entity_to_edit.put()
</code></pre>
| 0 | 2016-08-17T15:18:54Z | [
"python",
"google-app-engine",
"app-engine-ndb",
"google-cloud-datastore"
] |
MrJob on Hadoop can't import libraries | 38,930,398 | <p>I am using CDH 5.7.2 and MrJob to submit a MapReduce job</p>
<p>When I try in <strong>localmode, everything works fine</strong>, but when i use <code>-r hadoop</code> It gives me following error:</p>
<pre><code> Task Id : attempt_1471071791922_0005_m_000001_2, Status : FAILED
Error: java.lang.RuntimeException: Pip... | 0 | 2016-08-13T07:35:20Z | 39,011,937 | <p>Found answer by myself.</p>
<p>What I have to do - is to install this library on <strong>all of my nodes</strong> (not just on master)</p>
| 0 | 2016-08-18T07:09:05Z | [
"python",
"hadoop",
"mapreduce",
"cloudera-cdh",
"mrjob"
] |
page not found django.views.static.serve | 38,930,474 | <p>first post so be gentle.</p>
<p>I am trying to display a static image in django. I can upload the image to my media directory but when I try to display it I get a nothing. If I copy the url to the browser I get ...</p>
<p>Page not found (404)
Request Method: GET
Request URL: <a href="http://127.0.0.1:8000/... | 1 | 2016-08-13T07:44:36Z | 38,954,912 | <p>document_root=settings.STATIC_URL should be document_root=settings.STATIC_ROOT and similar for MEDIA_ROOT. You want the filesystem path in there, not the URL. â dhke</p>
| 0 | 2016-08-15T12:16:27Z | [
"python",
"django",
"filefield"
] |
Webpack setup, webpack doesn't resolve(pack into bundle) css files | 38,930,589 | <p>I have problem inserting css inside my react code. Problem is that webpack not resolving css files.
I did everything according to docs, and no luck. Also could be issue that i'm using django 1.9 for this</p>
<p>File structure:</p>
<pre><code>webpack.config.js
static
âââ bundles
â  âââ reqct-25186... | 0 | 2016-08-13T08:00:07Z | 38,930,741 | <p>From the error messages, it looks like you're trying to include <code>./testings.css</code> in the file <code>static/js/envs.jsx</code>, so Webpack is (understandably) trying to find that CSS file in <code>static/js</code>:</p>
<blockquote>
<p>.../<strong>static/js/testings.css</strong> doesn't exist</p>
</blockq... | 0 | 2016-08-13T08:19:40Z | [
"python",
"django",
"reactjs",
"webpack",
"css-loader"
] |
flask and flask_login - organizing code | 38,930,604 | <p>I am currently coding up a simple web application using flask and flask_login, and got stuck due to a code organisation problem.</p>
<pre><code>import flask
import flask_login
app = flask.Flask(__name__)
login_manager = flask_login.LoginManager()
login_manager.init_app(app)
</code></pre>
<p>The above works. The ... | 1 | 2016-08-13T08:01:39Z | 38,930,826 | <p>You can do something like the following, if <code>main.py</code> and <code>my_auth.py</code> reside on same directory:</p>
<p><code>my_auth.py</code>:</p>
<pre><code>import flask_login
login_manager = flask_login.LoginManager()
</code></pre>
<p><code>main.py</code>:</p>
<pre><code>from flask import Flask
from m... | 1 | 2016-08-13T08:31:16Z | [
"python",
"flask",
"flask-login"
] |
Can't see the where "expected an indented block" should be | 38,930,627 | <p>I know it's an indent issue but I can't see the indent problem with this. I've added added and removed indents. move it all over, moved it all back. I've got square eyes on this one :)</p>
<blockquote>
<p>File "", line 7
def <strong>init</strong>(self, start_time, time_limit=60):</p>
</blockquote>
<p>Inden... | 0 | 2016-08-13T08:04:24Z | 38,930,684 | <p>You must be mixing tabs and spaces for indentation.</p>
<p>Check this:
<a href="https://www.python.org/dev/peps/pep-0008/#tabs-or-spaces" rel="nofollow">https://www.python.org/dev/peps/pep-0008/#tabs-or-spaces</a></p>
<blockquote>
<p>A text editor which automatically formats code will guide your code
from gett... | 1 | 2016-08-13T08:12:46Z | [
"python",
"python-2.7"
] |
Interpreting a bytearray as array of longs in Python 2.7 | 38,930,639 | <p>In Python 3 it is possible to interpret the underlying memory as array of bytes or ints or longs via <code>memoryview.cast()</code>:</p>
<pre><code>[] b=bytearray(2*8)
[] b
bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
[] m=memoryview(b).cast('L') #reinterpret as an array of unsigne... | 4 | 2016-08-13T08:06:51Z | 38,930,889 | <p>Not really a reinterpretation since it creates a copy. In that case, you would have to </p>
<ul>
<li>convert <code>bytearray</code> to list of longs</li>
<li>work with the list of longs</li>
<li>convert back to <code>bytearray</code> when you're done</li>
</ul>
<p>(a bit like working with <code>str</code> characte... | 1 | 2016-08-13T08:39:24Z | [
"python",
"python-2.7",
"bytearray"
] |
Interpreting a bytearray as array of longs in Python 2.7 | 38,930,639 | <p>In Python 3 it is possible to interpret the underlying memory as array of bytes or ints or longs via <code>memoryview.cast()</code>:</p>
<pre><code>[] b=bytearray(2*8)
[] b
bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
[] m=memoryview(b).cast('L') #reinterpret as an array of unsigne... | 4 | 2016-08-13T08:06:51Z | 38,938,610 | <p>You can use ctypes and its <a href="https://docs.python.org/2/library/ctypes.html#ctypes._CData.from_buffer" rel="nofollow"><code>from_buffer</code></a> method to create a ctypes array of unsigned longs that shares its memory with the <code>bytearray</code> object.</p>
<p>For example:</p>
<pre><code>import ctypes
... | 1 | 2016-08-14T02:24:07Z | [
"python",
"python-2.7",
"bytearray"
] |
Heroku Web Server Won't Start Locally | 38,930,678 | <p>I am having problems starting heroku web server localy. Here is the error message I am constantlly getting:</p>
<pre><code>PS C:\Users\Dragan\heroku_workspace\python-getting-started> heroku local
[OKAY] Loaded ENV .env File as KEY=VALUE Format
10:01:32 web.1 | Traceback (most recent call last):
10:01:32 web.1... | 1 | 2016-08-13T08:12:15Z | 38,944,880 | <p>You are trying to deploy a Python web application to Heroku using the <a href="http://gunicorn.org/" rel="nofollow">gunicorn</a> web server. This works great on Heroku, but CANNOT WORK on Windows because gunicorn only runs on *nix based operating systems.</p>
<p>What you can do instead of running <code>heroku local... | 1 | 2016-08-14T17:43:12Z | [
"python",
"heroku"
] |
Django simple queryset in form field | 38,930,901 | <p>I couldn't find any solution in previous answers so i'm here asking how to register the result of a form field made by a queryset. Maybe i'm doing wrong something simple here how ever my model are:</p>
<pre><code>@python_2_unicode_compatible
class Choice(models.Model):
choice_text = models.CharField(max_length=... | 0 | 2016-08-13T08:40:22Z | 38,932,232 | <p>Edit Your ContactForm</p>
<pre><code>class ContactForm(ModelForm):
contatto_choice = forms.ModelChoiceField(queryset=Choice.objects.all())
class Meta:
model = Contatto
fields = ['contatto_choice', 'phone_number','email','text']
</code></pre>
<p>and you will not need other form </p>
| 1 | 2016-08-13T11:28:45Z | [
"python",
"django",
"forms"
] |
How to order the files the way it is selecting in pyqt? | 38,930,908 | <p>i have code which can select multiple files and print their names. But i found that they are not in order in which i am selecting them. say for example if i have file name as <strong>file1,file2,file3</strong>and if i first select <strong>file2</strong> then <strong>file3</strong> then <strong>file1</strong> while p... | -1 | 2016-08-13T08:41:22Z | 38,931,140 | <p>I don't think there is a method for that but you can write a function to get the selection and compare it to the previous one and connect that function to the activation of your QFileDialog :</p>
<pre><code>global desktop1
global previous_selection
global filesnames1
QtGui.QFileDialog.currentChanged(get_selection)
... | 0 | 2016-08-13T09:09:24Z | [
"python",
"pyqt"
] |
How to order the files the way it is selecting in pyqt? | 38,930,908 | <p>i have code which can select multiple files and print their names. But i found that they are not in order in which i am selecting them. say for example if i have file name as <strong>file1,file2,file3</strong>and if i first select <strong>file2</strong> then <strong>file3</strong> then <strong>file1</strong> while p... | -1 | 2016-08-13T08:41:22Z | 38,934,440 | <p>By default, the <a href="http://doc.qt.io/qt-4.8/qfiledialog.html#static-public-members" rel="nofollow">static functions</a> (like <code>getOpenFileNames</code>) will open a <em>native</em> file-dialog whenever possible. For native file-dialogs, Qt has no control over the order of the returned files, so there's noth... | 1 | 2016-08-13T15:51:52Z | [
"python",
"pyqt"
] |
How do I make one data frame to keep the same rows as another one? | 38,930,932 | <p>I have one data frame (df) x,</p>
<pre><code> A B
O 2 3
1 4 4
3 2 1
</code></pre>
<p>You may notice that the number 2 row is missing. That is because i have used x.dropna() and therefore the no.2 row is dropped as it is NAN.</p>
<p>Now I have another df y:</p>
<pre><code> C D
O 1 2
1 4 3... | 2 | 2016-08-13T08:44:33Z | 38,930,967 | <p>Use loc:</p>
<pre><code>y.loc[x.index]
Out:
C D
O 1 2
1 4 3
3 1 4
</code></pre>
<p>You can assign it back to y: <code>y = y.loc[x.index]</code></p>
| 1 | 2016-08-13T08:49:17Z | [
"python",
"pandas",
"dataframe"
] |
How do I make one data frame to keep the same rows as another one? | 38,930,932 | <p>I have one data frame (df) x,</p>
<pre><code> A B
O 2 3
1 4 4
3 2 1
</code></pre>
<p>You may notice that the number 2 row is missing. That is because i have used x.dropna() and therefore the no.2 row is dropped as it is NAN.</p>
<p>Now I have another df y:</p>
<pre><code> C D
O 1 2
1 4 3... | 2 | 2016-08-13T08:44:33Z | 38,931,445 | <p>You can also use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.isin.html" rel="nofollow"><code>index.isin</code></a> to check if each index value of <code>y</code> is found in index value of <code>x</code>.</p>
<pre><code>In [3]: y = y[y.index.isin(x.index)]
In [4]: y
Out[4]:
... | 1 | 2016-08-13T09:48:09Z | [
"python",
"pandas",
"dataframe"
] |
Run and log the output of 'ping' in a loop in a Python script | 38,930,950 | <p>i wrote a simple agaent in python that all it dose is just cheacks for the internet connection.
When he finds out that ther is no connection he writes a log file to a text the hour and date and then just exit the program.</p>
<p>I want it to keep testing if there is a connection even if there is not how can i do th... | -1 | 2016-08-13T08:46:59Z | 38,931,004 | <p>Wrap the <code>Main</code> call in an <em>infinite loop</em>?</p>
<pre><code>if __name__ == "__main__":
while True:
Main()
time.sleep(1) # optional, as Main already contains a sleep time
</code></pre>
| 1 | 2016-08-13T08:53:41Z | [
"python",
"while-loop",
"io"
] |
Run and log the output of 'ping' in a loop in a Python script | 38,930,950 | <p>i wrote a simple agaent in python that all it dose is just cheacks for the internet connection.
When he finds out that ther is no connection he writes a log file to a text the hour and date and then just exit the program.</p>
<p>I want it to keep testing if there is a connection even if there is not how can i do th... | -1 | 2016-08-13T08:46:59Z | 38,931,252 | <p>If I understand yous correctly this will do its job:</p>
<pre><code>import os
import time
def Main():
while True:
ping = os.system('ping -n 1 -l 1000 8.8.8.8 ')
if ping:
print 'no connection'
CT =time.strftime("%H:%M:%S %d/%m/%y")
alert=' No Connection'
... | 0 | 2016-08-13T09:25:03Z | [
"python",
"while-loop",
"io"
] |
Run and log the output of 'ping' in a loop in a Python script | 38,930,950 | <p>i wrote a simple agaent in python that all it dose is just cheacks for the internet connection.
When he finds out that ther is no connection he writes a log file to a text the hour and date and then just exit the program.</p>
<p>I want it to keep testing if there is a connection even if there is not how can i do th... | -1 | 2016-08-13T08:46:59Z | 38,931,579 | <p>This code should set you on your way. Just substitute the host with that of your choosing in the call to the <code>LogPing</code> object.</p>
<p>Check out the comments inline and please ask me if you have any questions.</p>
<pre><code>from datetime import datetime
import os
import shlex
import subprocess
from tim... | 1 | 2016-08-13T10:04:35Z | [
"python",
"while-loop",
"io"
] |
Can you get and put into a Queue at the same time? | 38,930,971 | <p>I currently have a program that starts a thread with a FIFO queue. The queue is constantly putting data into the queue, and there is a method to get the items from the queue. The method acquires a lock and releases it once it grabs the items. </p>
<p>My question is, will I face into any problems in the future putti... | 0 | 2016-08-13T08:49:53Z | 38,932,248 | <p>The <code>Queue</code> type has blocking calls to <code>get()</code> and <code>put()</code> by default. So when you make a <code>get()</code> call, it will block the call and wait for an item to be put in the queue. </p>
<p>The <code>put()</code> call will also by default block if the queue is full and wait for a s... | 1 | 2016-08-13T11:30:50Z | [
"python",
"multithreading",
"queue",
"locking"
] |
flask and flask_login - avoid importing flask_login from main code | 38,930,978 | <p>I am currently coding up a simple web application using flask and flask_login. This is <code>main.py</code>:</p>
<pre><code>import flask
import flask_login
app = flask.Flask(__name__)
login_manager = flask_login.LoginManager()
login_manager.init_app(app)
@app.route('/')
@flask_login.login_required
def index():
... | 0 | 2016-08-13T08:50:51Z | 38,931,555 | <p>create a file <code>my_auth.py</code></p>
<pre><code># my_auth.py
import flask_login
login_manager = flask_login.LoginManager()
# create an alias of login_required decorator
login_required = flask_login.login_required
</code></pre>
<p>and in file <code>main.py</code></p>
<pre><code># main.py
import flask
from... | 3 | 2016-08-13T10:02:10Z | [
"python",
"flask",
"flask-login"
] |
flask and flask_login - avoid importing flask_login from main code | 38,930,978 | <p>I am currently coding up a simple web application using flask and flask_login. This is <code>main.py</code>:</p>
<pre><code>import flask
import flask_login
app = flask.Flask(__name__)
login_manager = flask_login.LoginManager()
login_manager.init_app(app)
@app.route('/')
@flask_login.login_required
def index():
... | 0 | 2016-08-13T08:50:51Z | 38,931,700 | <p>I can confirm that Akshay's answer works.</p>
<p>While waiting for an answer, however, I've also found a workaround(?) that does not rely on using the decorator:</p>
<p>In <code>main.py</code>:</p>
<pre><code>@SVS.route("/")
def index():
if not my_auth.is_authenticated():
return flask.redirect(flask.u... | 1 | 2016-08-13T10:19:50Z | [
"python",
"flask",
"flask-login"
] |
OneClassSVM scikit learn | 38,931,023 | <p>I have two data sets, trainig and test. They have labels "1" and "0". I need to evaluate these data sets using "oneClassSVM" Algorithm with "rbf" kernel in scikit learn. I loaded training data set, but I have no idea how to evaluate that with test data set. Below is my code,</p>
<pre><code>from sklearn import svm
i... | 1 | 2016-08-13T08:55:34Z | 38,931,229 | <p>It's as simple as adding the following two lines of code at the end of your script:</p>
<pre><code>estimator.fit(X_train)
y_pred_test = estimator.predict(X_test)
</code></pre>
<p>The first line tells svn which training data to use and the second one makes prediction on the test set (be sure to load both datasets a... | 2 | 2016-08-13T09:21:06Z | [
"python",
"machine-learning",
"scikit-learn",
"svm"
] |
TypeError: string indices must be integer | 38,931,066 | <p>I tried to get data from <code>JSON</code>. But instead data i get <code>TypeError</code>:</p>
<pre><code>'TypeError: string indices must be integers'
</code></pre>
<p>Here ist my code:</p>
<pre><code>api.authenticate(LOGIN, CONN)
profil = api.get_profile("abc")
data = json.dumps(profil, indent=4)
print(data["log... | 0 | 2016-08-13T09:00:31Z | 38,931,241 | <p>There is an extra <code>,</code> in your json file at the end. Delete this:</p>
<pre><code>{
"public_email": "",
"violation_url": null,
"is_blocked": false,
"links_published": 0,
"login": "abc",
"links_added": 1,
"gg": "",
"signup_date": "2014-10-26 21:15:41"
}
</code></pre>
<p>Then <code>l... | -1 | 2016-08-13T09:22:36Z | [
"python",
"json",
"python-3.x"
] |
theano.function - how does it work? | 38,931,112 | <p>I've read the official documenation and read the comments here <a href="https://github.com/Theano/theano/blob/ddfd7d239a1e656cee850cdbc548da63f349c37d/theano/compile/function.py#L74-L324" rel="nofollow">https://github.com/Theano/theano/blob/ddfd7d239a1e656cee850cdbc548da63f349c37d/theano/compile/function.py#L74-L324... | 1 | 2016-08-13T09:06:08Z | 38,931,455 | <p>I'm no expert but here's my take at explaining it:</p>
<p>Yes the 'body' is defined in the code above. But <code>theano</code> doesn't 'interpret' that code directly like the python interpreter would. The code in question is just creating <code>theano</code> objects that will allow <code>theano</code> to compile th... | 1 | 2016-08-13T09:48:49Z | [
"python",
"function",
"theano"
] |
pygame-How to darken screen | 38,931,142 | <p>I want to darken current screen a bit before poping up a new surface. I know there is no function in pygame to do this and that I will have to process the image to darken it. But as long as I know the only way to get current displaying surface in pygame is by saving it to disk as a file which slows down the game. Is... | 1 | 2016-08-13T09:09:37Z | 38,931,184 | <p>You don't need to save anything to a file.
When you read an image to a file, it is a <code>Surface</code> object. You them blit this object to the screen. But these <code>Surface</code> objects have the same methods and properties than the object working as the screen - (which is also a Surface): you can draw primit... | 2 | 2016-08-13T09:15:20Z | [
"python",
"python-3.x",
"pygame"
] |
Avoiding duplicates and assigning value to each singleton in a for loop | 38,931,196 | <p>I am attempting to deal with the duplication and the failure of assigning value to each singleton in a for loop.</p>
<p>First, I create edges from one node to nodes which it connects to:</p>
<pre><code>ti = "D" #node from
lst = ["A", "B", "C"] #nodes to
packaged = [(ti, l) for l in lst] # a list of edges (from -... | 0 | 2016-08-13T09:16:37Z | 38,931,220 | <p>What you need is this:</p>
<pre><code>ti = "D" #node from
lst = ["A", "B", "C"] #nodes to
packaged = [(ti, l) for l in lst] # a list of edges (from - to)
l_lst = len(lst) ## length of lst, *i.e.* degree of ti
weight = 1 / float(l_lst) # edge weight, normalized by length of lst
for pair in packaged:
print... | 3 | 2016-08-13T09:19:54Z | [
"python",
"loops"
] |
Avoiding duplicates and assigning value to each singleton in a for loop | 38,931,196 | <p>I am attempting to deal with the duplication and the failure of assigning value to each singleton in a for loop.</p>
<p>First, I create edges from one node to nodes which it connects to:</p>
<pre><code>ti = "D" #node from
lst = ["A", "B", "C"] #nodes to
packaged = [(ti, l) for l in lst] # a list of edges (from -... | 0 | 2016-08-13T09:16:37Z | 38,931,235 | <p>A simple fix:</p>
<pre><code>for pair in packaged:
print (pair, weight)
</code></pre>
| 3 | 2016-08-13T09:21:51Z | [
"python",
"loops"
] |
OrientDB: How can I create a property unique using SQL? | 38,931,334 | <p>I have a little question for you, I don't know how create a property UNIQUE. I know the SQL command for create a property, but don't know how do this UNIQUE.</p>
<p>And I can't use the app studio of OrientDB (would be most easy for me but...)</p>
<p>This is the command that I know:</p>
<pre><code>"CREATE PROPERTY... | 0 | 2016-08-13T09:34:48Z | 38,931,388 | <p>You can create index on this particular property.</p>
<pre><code>CREATE INDEX user.name UNIQUE
</code></pre>
<p>Take a look here: <a href="http://orientdb.com/docs/2.1/Console-Command-Create-Index.html" rel="nofollow">Console - CREATE INDEX</a></p>
| 2 | 2016-08-13T09:42:48Z | [
"python",
"orientdb"
] |
How to execute one python file with the arguments from another python file without passing arguments on command/terminal line? | 38,931,450 | <p>I have a default code in Python that has the argument parser and have to pass those argument by myself in command line,but i dont want to pass the arguments myself rather execute that file from another python file with the arguments written in that file or i dont want to write those arguments myself on command lines... | -4 | 2016-08-13T09:48:24Z | 38,931,618 | <p>Here is how you do it. You need to slightly modify the above code to form the following</p>
<pre><code>import sys, argparse
def run_function (lista):
parser = argparse.ArgumentParser()
parser.add_argument('-i', type=str, nargs='+', help="Enter the filenames with extention of an Image")
arg=parser.parse... | 0 | 2016-08-13T10:08:28Z | [
"python",
"opencv"
] |
Invalid \escape in json.loads(), python 2.7 | 38,931,535 | <p>I am having a list of jsons in a text file as </p>
<pre><code>[{"key1": "value1", "key2": "value2"},{},{}]
</code></pre>
<p>Now I am trying to read the file and converting it into list of dicts so that I can iterate and use those key-value pairs using code - </p>
<pre><code>with open('./file.txt') as f:
listOf... | 0 | 2016-08-13T09:59:00Z | 38,931,895 | <p>Ok, you'll have to do a little string manipulation to unescape and decode.</p>
<p>It depends on whether your data contains escaped Unicodes or escaped 8bit characterset, like <code>latin1</code> or <code>cp1252</code>. You'll have to experiment to see what works for your data.</p>
<p>If it's escaped Unicode you ca... | 0 | 2016-08-13T10:47:38Z | [
"python",
"json",
"io",
"character-encoding"
] |
How can I increment the value of a variable within dictionary comprehension | 38,931,552 | <pre><code>start = 0
limit = 100
count = 10
total_count = 1000
pages = {}
for i in range(1, count+1):
pages[i] = start
start += limit
print pages
{1: 0, 2: 100, 3: 200, 4: 300, 5: 400, 6: 500, 7: 600, 8: 700, 9: 800, 10: 900}
</code></pre>
<p>How can I achieve the same result using dictionary comprehension? I ... | 0 | 2016-08-13T10:02:09Z | 38,931,612 | <pre><code>start = 0
limit = 100
count = 10
pages2 = {(i + 1): start + i * limit for i in range(count)}
print pages2
</code></pre>
| 1 | 2016-08-13T10:07:48Z | [
"python",
"dictionary-comprehension"
] |
How can I increment the value of a variable within dictionary comprehension | 38,931,552 | <pre><code>start = 0
limit = 100
count = 10
total_count = 1000
pages = {}
for i in range(1, count+1):
pages[i] = start
start += limit
print pages
{1: 0, 2: 100, 3: 200, 4: 300, 5: 400, 6: 500, 7: 600, 8: 700, 9: 800, 10: 900}
</code></pre>
<p>How can I achieve the same result using dictionary comprehension? I ... | 0 | 2016-08-13T10:02:09Z | 38,931,615 | <p>Use mathematics:</p>
<pre><code>pages = {(i+1): 100 * i for i in range(count)}
</code></pre>
<p>Since <code>start</code> starts at zero and keeps adding <code>100</code>, we can use multiplication to find where it should be at each point. If <code>start</code> and <code>limit</code> aren't always going to be what... | 2 | 2016-08-13T10:07:56Z | [
"python",
"dictionary-comprehension"
] |
weird behaviour of globals() and locals() in python | 38,931,598 | <p>I create a simple code.
For example </p>
<pre><code>x = 50
def func(x):
x = 2
print 'Changed local x to', x
func(x)
</code></pre>
<p>Then I type globals() and expect to see the list of global variables
Instead I get a weird output like this below. Why? I use python 2.7, in jupyter. Everything else works... | 0 | 2016-08-13T10:06:17Z | 38,931,692 | <p>What you're seeing is indeed the global variables defined in your interpreter session. There are a few more of them than you expected! That's because the interactive interpreter uses some variables for its own purposes, such as keeping track of past inputs and outputs.</p>
<p>Some of the globals you're seeing (like... | 2 | 2016-08-13T10:18:25Z | [
"python",
"python-2.7",
"ipython",
"jupyter",
"jupyter-notebook"
] |
How to access dictionary-type items in a list (python or maybe javascript) | 38,931,966 | <p>I have some data stored in 'nutrients' JSONField in a django 'Food' model.</p>
<p>some sample datastructure at the bottom.</p>
<p>The data is Food.nutrients, but I don't know how/ best way access a particular item in the nutrients list - which is structured like [{dict type item},{dict type item},...]. </p>
<p>Ea... | 0 | 2016-08-13T10:57:13Z | 38,932,026 | <p>Let's suppose, you have the list of dictionaries in <code>nutrients</code>. Now you can filter the list to find the items matching a particular key with a specific value. For example, to find the dictionary with <code>name</code> having "Manganese, Mn", you can do: </p>
<pre><code>matches = filter(lambda n: n.get('... | 3 | 2016-08-13T11:05:54Z | [
"python",
"json",
"list",
"dictionary"
] |
cannot import name DurationField | 38,931,987 | <p>I am trying to run an application that uses django rest framework.However am getting the import error "cannot import name DurationField".How do i resolve this error ?</p>
<p>Error message
<a href="http://i.stack.imgur.com/EiRl1.png" rel="nofollow">enter image description here</a></p>
<p>Views.py</p>
<pre><code>fr... | 0 | 2016-08-13T10:59:47Z | 38,932,278 | <p>From the screenshot, I can see you're using Django 1.7. </p>
<p>The <code>DurationField</code> that is being imported by DRF was introduced in Django 1.8. </p>
<p>So you have to upgrade your Django to get this version of DRF to work. </p>
| 2 | 2016-08-13T11:34:29Z | [
"python",
"django",
"django-rest-framework"
] |
is there a way to execute a python program using c#? | 38,932,127 | <p>I want to call my python program and get it executed automatically as it gets called, using c#. I have done uptill opening the program but how to run it and the get the output. It is my final year project kindly help me out.Here is my code:</p>
<pre><code>Process p = new Process();
ProcessStartInfo pi = new... | 0 | 2016-08-13T11:18:23Z | 38,944,660 | <p>The following code execute python script that call modules and return result</p>
<pre><code>class Program
{
static void Main(string[] args)
{
RunPython();
Console.ReadKey();
}
static void RunPython()
{
var args = "test.py"; //main python script
ProcessStartInfo... | 0 | 2016-08-14T17:19:06Z | [
"c#",
"python",
"using",
"execute"
] |
mnlogit regression, singular matrix error | 38,932,129 | <p>My regression model using statsmodels in python works with 48,065 lines of data, but while adding new data I have tracked down one line of code that produces a singular matrix error. Answers to similar questions seem to suggest missing data but I have checked and there is nothing visibibly irregular from the error p... | 0 | 2016-08-13T11:18:51Z | 38,933,654 | <p>As far as I can see:</p>
<p>The problem is the variable <code>is_own_goal</code> because all observation where this is 1 also have the dependent variable <code>is_success</code> equal to 1. That means there is no variation in the outcome because <code>is_own_goal</code> already specifies that it is a success. </p>
... | 0 | 2016-08-13T14:22:42Z | [
"python",
"regression",
"statsmodels"
] |
How improve this django view code? | 38,932,266 | <p>What do you think about this code part? How bad it is? It's normal practise to write code like this? How I can improve this code and make it shorter, more readable and ofcourse improver performance?</p>
<p>I think this code isn't very good, especially to understand it and maintain it.</p>
<pre><code>def car_list(r... | 1 | 2016-08-13T11:32:46Z | 38,932,462 | <p>I would start with this small refactoring</p>
<p>from </p>
<pre><code>if request.user.is_authenticated():
favorite = CarFavorite.objects.filter(user=request.user)
else:
favorite = []
favorite_user_cars = []
for fav in favorite:
favorite_user_cars.append(fav.car.id)
</code></pre>
<p>to --></p>
<pre><... | 2 | 2016-08-13T11:56:04Z | [
"python",
"django",
"django-views"
] |
How to pip install for certain version of python | 38,932,377 | <p>I need to install <code>requests</code> for python3</p>
<pre><code>pip install requests
</code></pre>
<p>installs it for python2.7.</p>
<p>How to do this without <code>virtualenv</code> ?</p>
| -4 | 2016-08-13T11:45:57Z | 38,932,589 | <p>Sorry for the rate of -2 in your problem, and I don't think I can understand your question well, either. I will try too help.</p>
<p>Now you have python 2.7 and python3, when your virtualenv is not activate, 'pip' is for python2.x and 'pip3' is for python3.x</p>
<p>there is no necessary to think about Why pip is f... | 0 | 2016-08-13T12:11:06Z | [
"python",
"python-3.x",
"pip",
"virtualenv"
] |
How to pip install for certain version of python | 38,932,377 | <p>I need to install <code>requests</code> for python3</p>
<pre><code>pip install requests
</code></pre>
<p>installs it for python2.7.</p>
<p>How to do this without <code>virtualenv</code> ?</p>
| -4 | 2016-08-13T11:45:57Z | 38,937,196 | <p>I tried <code>pip install lxml</code> and succeed, not sure the situation you encountered.</p>
<p><code>pip</code> command uses the "default" Python version in your system, you HAVE to check the output of <code>pip --version</code> to figure out which version it belongs to.</p>
<p>"<code>pip</code> is for Python2"... | 0 | 2016-08-13T21:33:45Z | [
"python",
"python-3.x",
"pip",
"virtualenv"
] |
How to pip install for certain version of python | 38,932,377 | <p>I need to install <code>requests</code> for python3</p>
<pre><code>pip install requests
</code></pre>
<p>installs it for python2.7.</p>
<p>How to do this without <code>virtualenv</code> ?</p>
| -4 | 2016-08-13T11:45:57Z | 38,943,277 | <p>To resolve conflicting installation sites always follow the following steps:</p>
<ol>
<li><p>To install for python3 use: <code>python3 -m pip install requests</code></p></li>
<li><p>For python2 use: <code>python2 -m pip install [any_module]</code></p></li>
</ol>
<p>This will prevent any conflicts, which I hope is... | 2 | 2016-08-14T14:40:37Z | [
"python",
"python-3.x",
"pip",
"virtualenv"
] |
Using except to mean "and if that doesn't work" | 38,932,530 | <p>I fully get the general principle of not catching all exception, as explained in this question, for instance (<a href="http://stackoverflow.com/questions/21553327/why-is-except-pass-a-bad-programming-practice">Why is "except: pass" a bad programming practice?</a>). Yet I have found myself writing this sequ... | 1 | 2016-08-13T12:03:07Z | 38,932,719 | <p>Maybe it'd be better to put it into a dedicated function ?</p>
<pre><code>def func(source):
try:
return source.geturl()
except Exception:
try:
return pathlib.Path(os.path.abspath(source.name)).as_uri()
except Exception:
pass
</code></pre>
<h2>Notes on swallowing exc... | 1 | 2016-08-13T12:27:18Z | [
"python",
"exception"
] |
Cannot fully utilise all cpu using multiprocessing.pool.ThreadPool Module | 38,932,541 | <p>I have a 32 core machine , using multiprocessing.pool.ThreadPool library to generate ThreadPool of Size 32. I have given the sample snippet in my case 2 D Array is huge. </p>
<pre><code>from multiprocessing.pool import ThreadPool as Pool
import time
def f(x):
return x[1]
if __name__ == '__main__':
pool = ... | 0 | 2016-08-13T12:04:17Z | 38,999,404 | <p>I believe the issue is because you're using <code>multiprocessing.pool.ThreadPool</code> as the <code>Pool</code>, not <code>multiprocessing.Pool</code>. The former creates thread-based dummy Process objects that wrap a Python thread, so using it doesn't create separate processes like the latter does.</p>
<p>Try us... | 0 | 2016-08-17T14:25:49Z | [
"python",
"multithreading",
"threadpool",
"python-multithreading",
"python-multiprocessing"
] |
Multithreading in Scrapy using proxies | 38,932,556 | <p>I want to crawl about 4 million pages using scrapy. I am using <a href="http://stormproxies.com/" rel="nofollow">storm proxies</a>.
Lets say Number of threads allowed on my account is 20.
I want to ask - </p>
<p>Is multithreading means CONCURRENT_REQUESTS_PER_DOMAIN , in scrapy.</p>
<p>or there is an any other way... | 1 | 2016-08-13T12:06:47Z | 38,943,547 | <p>Straight out of the docs:</p>
<blockquote>
<p><code>CONCURRENT_REQUESTS</code>- The maximum number of concurrent (ie.
simultaneous) requests that will be performed by the Scrapy
downloader.</p>
<p><code>CONCURRENT_REQUESTS_PER_DOMAIN</code> - The maximum number of concurrent
(ie. simultaneous) requests... | 1 | 2016-08-14T15:11:36Z | [
"python",
"multithreading",
"web-scraping",
"scrapy"
] |
Unsure how to run Celery under windows for periodic tasks | 38,932,602 | <p>I am having difficulty understanding how to run Celery after setting up some scheduled tasks. </p>
<p>Firstly, my project directory is structured as follows:</p>
<p><a href="http://i.stack.imgur.com/AwGsB.png" rel="nofollow"><img src="http://i.stack.imgur.com/AwGsB.png" alt="enter image description here"></a></p>
... | 0 | 2016-08-13T12:12:06Z | 39,025,232 | <p>You need to run celery beat with the celery settings file, rather than</p>
<pre><code>celery -A blogpodapi.celery beat --loglevel=INFO
</code></pre>
| 1 | 2016-08-18T18:33:22Z | [
"python",
"django",
"windows",
"celery",
"django-celery"
] |
LoginRequiredMixin and get_queryset with django-tables2 | 38,932,651 | <p>I already had a working table built on Django's generic ListView class. But I was missing the ability to sort and I therefore took a look at generating a new table using django-tables2. It was very easy to set up, but I don't know how to implement two important features from my old ListView class; 1) page is only vi... | 0 | 2016-08-13T12:18:09Z | 39,006,148 | <p>For managing permission to view page you can still use <a href="https://docs.djangoproject.com/en/1.10/topics/auth/default/#django.contrib.auth.decorators.login_required" rel="nofollow" title="login_required">login_required</a> decorator for your function-based views.</p>
<pre><code>from django.contrib.auth.decorat... | 1 | 2016-08-17T20:57:15Z | [
"python",
"django",
"python-3.x",
"django-views",
"django-tables2"
] |
send a list of string elements in Django | 38,932,686 | <p>I am new to Django. This is my Tag model</p>
<pre><code>class Tag(models.Model):
name=models.CharField(max_length=255)
post=models.ManyToManyField('Post')
</code></pre>
<p>I send a list of all tags name to a template. I want to use it in a javascript code. The problem is that, the list looks like this in j... | 0 | 2016-08-13T12:22:35Z | 38,932,884 | <p>Can you tell me whether the mistake is when you render the first time the view, or is an ajax call?, I think you are doing ajax call, then can you debug the django process, and write here what are the datas that you recover of your database, please?.</p>
<p>In addition, can you put the json serializer that you are ... | 1 | 2016-08-13T12:47:01Z | [
"javascript",
"python",
"django",
"unicode"
] |
send a list of string elements in Django | 38,932,686 | <p>I am new to Django. This is my Tag model</p>
<pre><code>class Tag(models.Model):
name=models.CharField(max_length=255)
post=models.ManyToManyField('Post')
</code></pre>
<p>I send a list of all tags name to a template. I want to use it in a javascript code. The problem is that, the list looks like this in j... | 0 | 2016-08-13T12:22:35Z | 38,932,941 | <p>Use "|safe"</p>
<p>something like this in your template.</p>
<pre><code>{{ variable_name | safe }}
</code></pre>
| 0 | 2016-08-13T12:55:19Z | [
"javascript",
"python",
"django",
"unicode"
] |
Number of occurence of a name in list | 38,932,703 | <p>Here is my homework:</p>
<blockquote>
<p>Write a function, number of occurrences(string, name) which returns the number of occurrences of name in the string of names string.</p>
<p>For example, number of occurrences('Alojz, Samo, Peter, Alojz, Franci','Alojz') should return 2.</p>
</blockquote>
<p>Here is m... | -2 | 2016-08-13T12:24:56Z | 38,932,728 | <p>you can use collections.Counter</p>
<pre><code>from collections import Counter
l = (word.strip() for word in string.split(','))
c = Counter(l)
return c[name]
</code></pre>
<p>edited</p>
<p>OR</p>
<p>You can use regex:</p>
<pre><code>def count_naem(string, name):
return len(re.findall("{},".format(name), str... | 1 | 2016-08-13T12:29:09Z | [
"python",
"string",
"list",
"split"
] |
Number of occurence of a name in list | 38,932,703 | <p>Here is my homework:</p>
<blockquote>
<p>Write a function, number of occurrences(string, name) which returns the number of occurrences of name in the string of names string.</p>
<p>For example, number of occurrences('Alojz, Samo, Peter, Alojz, Franci','Alojz') should return 2.</p>
</blockquote>
<p>Here is m... | -2 | 2016-08-13T12:24:56Z | 38,932,771 | <p>If you change your input string to <code>('Alojz,Samo,Peter,Alojz,Franci' , 'Alojz')</code> from <code>('Alojz, Samo, Peter, Alojz, Franci' , 'Alojz')</code>, it would work.</p>
<p>You need to remove extra spaces from input string.</p>
<p>OR</p>
<p>Replace white space from string.</p>
<pre><code> def number_o... | 0 | 2016-08-13T12:33:00Z | [
"python",
"string",
"list",
"split"
] |
Number of occurence of a name in list | 38,932,703 | <p>Here is my homework:</p>
<blockquote>
<p>Write a function, number of occurrences(string, name) which returns the number of occurrences of name in the string of names string.</p>
<p>For example, number of occurrences('Alojz, Samo, Peter, Alojz, Franci','Alojz') should return 2.</p>
</blockquote>
<p>Here is m... | -2 | 2016-08-13T12:24:56Z | 38,932,831 | <p>you can just trim out whitespaces after splitting the string.</p>
<p>use <code>strip()</code> to strip <code>whitespaces</code> from both sides. you can have <code>whitespaces</code> in both sides.</p>
<p>this may help you:</p>
<pre><code>def number_of_occurence(string,name):
m = 0
l = string.split(',')
... | 0 | 2016-08-13T12:40:54Z | [
"python",
"string",
"list",
"split"
] |
why do these python code examples all call the constructor twice? | 38,932,722 | <p>I am new to Python, and have been reading some API examples of python scientific libraries. </p>
<p>in one library, scikit-learn, the code examples always call the constructor once without arguments, and then later again with all the arguments.</p>
<p>Here is an example (see the last line, and the third before las... | 2 | 2016-08-13T12:27:32Z | 38,932,860 | <p>What you are reading is a <a href="https://docs.python.org/3.5/library/doctest.html" rel="nofollow">doctest</a>, a test embedded in a documentation string.</p>
<p>Doctests use lines prefixed by <code>>>></code> to indicate runnable examples, while their output is shown unprefixed.</p>
<p>The test runner w... | 3 | 2016-08-13T12:43:55Z | [
"python"
] |
Python: Is there a way to execute an or statement before != | 38,932,775 | <p>I'm trying to run the following code:</p>
<pre><code>while check == False:
op = input('Do you want to add, subtract, multiply or divide?')
if op != ((('add' or 'subtract') or 'multiply') or 'divide'):
print('Please enter a valid operation')
else:
check = True
</code></pre>
<p>However, o... | -1 | 2016-08-13T12:33:20Z | 38,932,808 | <p>You have to make each comparison individually, so <code>op != 'add' and op != 'subtract'...</code>.</p>
| 1 | 2016-08-13T12:37:58Z | [
"python",
"python-3.x",
"operand"
] |
Python: Is there a way to execute an or statement before != | 38,932,775 | <p>I'm trying to run the following code:</p>
<pre><code>while check == False:
op = input('Do you want to add, subtract, multiply or divide?')
if op != ((('add' or 'subtract') or 'multiply') or 'divide'):
print('Please enter a valid operation')
else:
check = True
</code></pre>
<p>However, o... | -1 | 2016-08-13T12:33:20Z | 38,932,816 | <p>You can do it using the <code>not in</code> operator:</p>
<pre><code>if op not in ['add', 'substract', 'multiply', 'divide']:
print('Please enter a valid operation')
</code></pre>
<p><code>in</code> checks for an item in a <em>container</em>, <code>not in</code> just does the opposite.</p>
<hr>
<p>Or additio... | 4 | 2016-08-13T12:39:03Z | [
"python",
"python-3.x",
"operand"
] |
Python: Is there a way to execute an or statement before != | 38,932,775 | <p>I'm trying to run the following code:</p>
<pre><code>while check == False:
op = input('Do you want to add, subtract, multiply or divide?')
if op != ((('add' or 'subtract') or 'multiply') or 'divide'):
print('Please enter a valid operation')
else:
check = True
</code></pre>
<p>However, o... | -1 | 2016-08-13T12:33:20Z | 38,932,840 | <p><code>or</code> operator <em>is</em> executed before <code>!=</code>. What you doing wrong is that you are working with wrong operands:</p>
<pre><code>'add' or 'substract'
>>> 'add'
</code></pre>
<p>This means that in the end it will be:</p>
<pre><code>if 'op' != 'add':
</code></pre>
<p>That is exactly ... | 0 | 2016-08-13T12:41:48Z | [
"python",
"python-3.x",
"operand"
] |
Python: Is there a way to execute an or statement before != | 38,932,775 | <p>I'm trying to run the following code:</p>
<pre><code>while check == False:
op = input('Do you want to add, subtract, multiply or divide?')
if op != ((('add' or 'subtract') or 'multiply') or 'divide'):
print('Please enter a valid operation')
else:
check = True
</code></pre>
<p>However, o... | -1 | 2016-08-13T12:33:20Z | 38,932,850 | <p>You can use <code>in</code> and a list.</p>
<pre><code>while check == False:
op = input('Do you want to add, subtract, multiply or divide?')
if op not in ['add', 'subtract', 'multiply', 'divide']:
print('Please enter a valid operation')
else:
check = True
</code></pre>
| 0 | 2016-08-13T12:43:04Z | [
"python",
"python-3.x",
"operand"
] |
Python: Is there a way to execute an or statement before != | 38,932,775 | <p>I'm trying to run the following code:</p>
<pre><code>while check == False:
op = input('Do you want to add, subtract, multiply or divide?')
if op != ((('add' or 'subtract') or 'multiply') or 'divide'):
print('Please enter a valid operation')
else:
check = True
</code></pre>
<p>However, o... | -1 | 2016-08-13T12:33:20Z | 38,932,867 | <p>If you're keen on an answer similar to your code, this works:</p>
<pre><code>check = False
while check == False:
op = raw_input('add/subtract/multiply/divide ? : ')
if op != 'add' and op != 'subtract' and op != 'multiply' and op != 'divide':
print 'What? Choose wisely.'
else:
print 'Well chosen.'
... | 0 | 2016-08-13T12:44:40Z | [
"python",
"python-3.x",
"operand"
] |
Unable to install pyzmail - "Command "python setup.py egg_info" failed with error code 1" | 38,932,818 | <p>I am trying to install pyzmail for Python 3.4. I am using Visual Studio Community Edition (Windows) but have also tried to install using the command line and get the following dump:</p>
<pre><code> ----- Installing 'pyzmail' -----
Collecting pyzmail
Using cached pyzmail-1.0.3.tar.gz
Collecting distribute (from py... | 0 | 2016-08-13T12:39:31Z | 38,932,976 | <p>I've been able to reproduce your problem, and you're right, using <code>pip install pyzmail</code> wont' be good (pyzmail's installer is buggy) so i've tried this instead:</p>
<pre><code>easy_install pyzmail
</code></pre>
<p>And it succeed, then I could just import pyzmail without any problem.</p>
| 0 | 2016-08-13T12:59:08Z | [
"python",
"visual-studio",
"python-3.x"
] |
Django installation picking up wrong path names for migrate after project was copied | 38,932,939 | <p>I have tried to create a new Django project on my Mac by making a copy of an existing working Django project.</p>
<p>I have tried to remove references to the old project paths from the new project but when doing a migrate or createsuperuser I get an error:</p>
<pre><code>psycopg2.OperationalError: invalid connecti... | 0 | 2016-08-13T12:55:11Z | 38,935,435 | <p>It's still trying to use a postgres database. You should update the <code>DATABASES</code> setting to use django's mysql backend, and you may need to remove all of your migrations as well. After you've removed the migrations and change the <code>DATABASES</code> settings, you should be able to <code>python manage.py... | 0 | 2016-08-13T17:49:08Z | [
"python",
"django",
"postgresql"
] |
remove() pop () and del() function | 38,932,943 | <pre><code>>>> b=[0, 2, 5, 1, 5, 0, 2, 3, 5, 1]
>>> c=[0, 2, 5, 1, 5, 0, 2, 3, 5, 1]
>>> d=[0, 2, 5, 1, 5, 0, 2, 3, 5, 1]
>>> for i in c:
print('i:',i)
del c[c.index(i)]
print(c)
i: 0
[2, 5, 1, 5, 0, 2, 3, 5, 1]
i: 5
[2, 1, 5, 0, 2, 3, 5, 1]
i: 5
[2, 1, 0, 2, 3, 5, 1]
i... | 0 | 2016-08-13T12:56:06Z | 38,933,100 | <p>Whenever you iterate over an object using <code>for</code>, a separate <em>iterator</em> object is created. This object keeps track of which object the <code>for</code> loop's body should use next, and when to stop. When you <code>for</code>-loop over a list, Python creates a list iterator object.</p>
<p>But whenev... | 3 | 2016-08-13T13:15:13Z | [
"python"
] |
Python 2.7 built from Source on AIX5.3 does not execute for libpython2.7.so | 38,933,007 | <p>This is on AIX 5.3.</p>
<p>When i run Python that I built from source, I get the following error (<strong>This is despite the library being present in the path and that path being present in the LD_LIBRARY_PATH variable.</strong>).</p>
<pre><code>a776q /app/appadm/.Mim>python2.7/bin/python
exec(): 0509-036 Cann... | 0 | 2016-08-13T13:03:01Z | 39,337,361 | <p>In the end the issue was that I was setting <strong>LD_LIBRARY_PATH</strong> when i should instead be setting <strong>LIBPATH</strong> on AIX.</p>
| 0 | 2016-09-05T20:34:03Z | [
"python",
"python-2.7",
"aix"
] |
What's the proper way to scrape asynchronously and store my results using django celery and redis and store my? | 38,933,035 | <p>I have been trying to understand what my problem is when I try to scrape using a function I created in my django app. The function goes to a website gathers data and stores it in my database. At first I tried using rq and redis for a while but I kept getting an error message. So someone thought I should try and use ... | 4 | 2016-08-13T13:06:57Z | 39,438,939 | <h3>You need to setup Django</h3>
<p>You seem to be trying to run your task in <strong>Python shell</strong>, it's more likely since your code works when you comment out the <em>Django model</em> part.</p>
<p>So the problem is, when running pure <em>python shell</em>, <strong>Django needs to be setup</strong>, in ord... | 6 | 2016-09-11T17:46:19Z | [
"python",
"django",
"queue",
"rabbitmq",
"django-celery"
] |
how do i properly indent my code on python | 38,933,049 | <p>I use python 3.5.0 and I'm not sure if my code is properly indented and the reason why I don't know is because I am a new to python starting this in secondary and not sure what's entirely correct. <strong>So is there any way to find out how to indent my code properly?</strong> because many people have said its wrong... | -1 | 2016-08-13T13:10:00Z | 38,933,442 | <p>I think you're asking why flow of your program isn't controlled properly which could have to do with indentation, but in this case it doesn't. All of your intends are tabs (which they should be) so there's no problem there. </p>
<p>One suggestion I would have is to put a while loop around the section that asks for ... | 0 | 2016-08-13T13:54:55Z | [
"python",
"pygame"
] |
Group by two columns and count the occurrences of each combination in pandas | 38,933,071 | <p>I have the following data frame:</p>
<pre><code>data = pd.DataFrame({'user_id' : ['a1', 'a1', 'a1', 'a2','a2','a2','a3','a3','a3'], 'product_id' : ['p1','p1','p2','p1','p1','p1','p2','p2','p3']})
product_id user_id
p1 a1
p1 a1
p2 a1
p1 a2
p1 a2
p1 a2
... | 1 | 2016-08-13T13:12:38Z | 38,933,130 | <p>Maybe this is what you want?</p>
<pre><code>>>> data = pd.DataFrame({'user_id' : ['a1', 'a1', 'a1', 'a2','a2','a2','a3','a3','a3'], 'product_id' : ['p1','p1','p2','p1','p1','p1','p2','p2','p3']})
>>> count_series = data.groupby(['user_id', 'product_id']).size()
>>> count_series
user_id p... | 2 | 2016-08-13T13:17:38Z | [
"python",
"pandas",
"dataframe",
"data-analysis"
] |
How to create multiple objects with django transactions? | 38,933,134 | <p>I have to retrieve M objects from a list of Q objects and then maps the M objects to an User. To achieve this, I need to run the code inside a transaction and roll back the DB in the case 1 of M objects are not created:</p>
<pre><code>def polls(request, template_name='polls/polls.html'):
question_list = random.... | 0 | 2016-08-13T13:18:18Z | 38,934,168 | <p>You need to use <a href="https://simpleisbetterthancomplex.com/tutorial/2016/07/28/how-to-create-django-signals.html" rel="nofollow">django signals</a> while doing user registration.
Also you do not need <code>with transaction.atomic():</code> part. You need to use
<a href="https://docs.djangoproject.com/en/1.9/re... | 0 | 2016-08-13T15:20:26Z | [
"python",
"django",
"django-models",
"transactions"
] |
How to create multiple objects with django transactions? | 38,933,134 | <p>I have to retrieve M objects from a list of Q objects and then maps the M objects to an User. To achieve this, I need to run the code inside a transaction and roll back the DB in the case 1 of M objects are not created:</p>
<pre><code>def polls(request, template_name='polls/polls.html'):
question_list = random.... | 0 | 2016-08-13T13:18:18Z | 38,942,389 | <p>First of all, we create a signal, in order to map the related questions to an user when the user is registered. The signal is triggered from post_save() and the call-back function retrieve N random questions and map it to the user. The signal must be connected, to do it, we use the decorator @receiver. We also need ... | 0 | 2016-08-14T12:45:36Z | [
"python",
"django",
"django-models",
"transactions"
] |
Yahtzee, using a dictionary instead of list of attributes | 38,933,138 | <p>So my issue is that currently I have code for my yahtzee (I will not post all of the code, but the important stuff is looking like this (and it works):</p>
<pre><code>from terminaltables import AsciiTable
class Player:
def __init__(self,name):
self.name=name
self.ones=0
self.twos=0
... | -4 | 2016-08-13T13:18:57Z | 38,933,527 | <pre><code>dict_names = ['ones', 'twos', ..., 'totalsum']
self.dict = {name:0 for name in dict_names}
</code></pre>
<p>and to access you'd use <code>player.dict['fours']</code> instead if <code>player.fours</code></p>
| 1 | 2016-08-13T14:06:13Z | [
"python"
] |
spark cannot create LabeledPoint | 38,933,198 | <p>I always get this error:
AnalysisException: u"cannot resolve 'substring(l,1,-1)' due to data type mismatch: argument 1 requires (string or binary) type, however, 'l' is of array type.;"</p>
<p>Quite confused because l[0] is a string, and matches arg 1.
dataframe has only one column named 'value', which is a comma s... | -2 | 2016-08-13T13:25:39Z | 38,933,848 | <p>I think you what to create LabeledPoint in dataframe. So you can:</p>
<p>def parse_points(df):</p>
<pre><code>df1=df.select(split(df.value,',').alias('l'))
df2=df1.map(lambda seq: LabeledPoint(float(seq[0][0]),seq[0][1:])) # since map applies lambda in each tuple
return df2.toDF() #this will convert pipelinedRD... | 0 | 2016-08-13T14:44:17Z | [
"python",
"apache-spark"
] |
Pyspark tuple object has no attribute split | 38,933,253 | <p>I am struggling with a Pyspark assignment. I am required to get a sum of all the viewing numbers per channels. I have 2 sets of files: 1 showing the show and views per show the other showing the shows and what channel they are shown on (can be multiple). </p>
<p>I have performed a join operation on the 2 files and ... | -1 | 2016-08-13T13:32:48Z | 38,933,356 | <p><em>Since this is an assignment, I'll try to explain what's going on rather than just doing the answer. Hopefully that will be more helpful!</em></p>
<p>This actually isn't anything to do with pySpark; it's just a plain Python issue. Like the error is saying, you're trying to split a tuple, when <code>split</code>... | 1 | 2016-08-13T13:45:14Z | [
"python",
"indexing",
"pyspark"
] |
Running old django app in new virtual environment | 38,933,309 | <p>I have a django app i was running in python 2.7 and django 1.7.10.However am trying to transition it to django 1.8. I have created a new virtualenv,installed python2.7 and django 1.8 in it and moved the app there.However when i run the server it still reads django 1.7.10.What could be the problem ?</p>
<p>console
<... | 0 | 2016-08-13T13:38:17Z | 38,933,515 | <p>You do not need to move application for new virtual environment you just need to activate it probably you did not activate new one. Actually also you do not need a new virtual environment for upgrade. Just <code>pip install -U django==1.8</code> it will upgrade your django and then make necessary edits. </p>
| 0 | 2016-08-13T14:04:29Z | [
"python",
"django"
] |
Getting fields of derived class | 38,933,342 | <p>In Python, I can get a classes fields with <code>__dict__</code>. Here I have two questions:</p>
<p>Is there a better way to get fields? Because it only brings fields that has values.
How can I get fields that exist only in class itself, not the base class?</p>
| 0 | 2016-08-13T13:42:35Z | 38,933,395 | <p>Check this:</p>
<pre><code>from types import FunctionType
class A (object):
def test(self):
pass
class B(A):
def test12(self):
pass
print([x for x,y in A.__dict__.items() if type(y) == FunctionType])
print([x for x,y in B.__dict__.items() if type(y) == FunctionType])
</code></pre>
<p>F... | 1 | 2016-08-13T13:49:40Z | [
"python",
"inheritance"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.