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 |
|---|---|---|---|---|---|---|---|---|---|
Turning a Python list of objects into a list of one-to-many objects | 37,604,978 | <p>Say we have a list of book objects, each with a title and an author ID:</p>
<pre><code>books = [
{ 'title': 'book1', 'author_id': 'author1' },
{ 'title': 'book2', 'author_id': 'author2' },
{ 'title': 'book3', 'author_id': 'author1' }
]
</code></pre>
<p>How would we efficiently go about transforming thi... | 0 | 2016-06-03T02:23:35Z | 37,605,120 | <p>You could use <a href="https://docs.python.org/2/library/collections.html#collections.defaultdict" rel="nofollow"><code>defaultdict</code></a> to generate a dictionary where keys are author names and values are list of books by each author. Once you have that it's easy to convert to a list:</p>
<pre><code>from coll... | 3 | 2016-06-03T02:40:24Z | [
"python",
"list",
"dictionary",
"one-to-many"
] |
Turning a Python list of objects into a list of one-to-many objects | 37,604,978 | <p>Say we have a list of book objects, each with a title and an author ID:</p>
<pre><code>books = [
{ 'title': 'book1', 'author_id': 'author1' },
{ 'title': 'book2', 'author_id': 'author2' },
{ 'title': 'book3', 'author_id': 'author1' }
]
</code></pre>
<p>How would we efficiently go about transforming thi... | 0 | 2016-06-03T02:23:35Z | 37,605,129 | <p>Using <a href="https://docs.python.org/2/library/itertools.html#itertools.groupby" rel="nofollow"><code>itertools.groupby</code></a>, you can do:</p>
<pre><code>key = lambda d: d['author_id']
authors = [
{'author_id': k, 'books': [{'title': d['title']} for d in g]}
for k, g in groupby(sorted(books, key=key... | 4 | 2016-06-03T02:41:04Z | [
"python",
"list",
"dictionary",
"one-to-many"
] |
Turning a Python list of objects into a list of one-to-many objects | 37,604,978 | <p>Say we have a list of book objects, each with a title and an author ID:</p>
<pre><code>books = [
{ 'title': 'book1', 'author_id': 'author1' },
{ 'title': 'book2', 'author_id': 'author2' },
{ 'title': 'book3', 'author_id': 'author1' }
]
</code></pre>
<p>How would we efficiently go about transforming thi... | 0 | 2016-06-03T02:23:35Z | 37,605,135 | <p>This works for me, just collecting authors in a dict and finally return the constructed list:</p>
<pre><code>def trans(books):
authors = {}
for bk in books:
if bk['author_id'] not in authors:
authors[bk['author_id']] = [{'title': bk['title']}]
else:
authors[bk['author... | 1 | 2016-06-03T02:41:22Z | [
"python",
"list",
"dictionary",
"one-to-many"
] |
Turning a Python list of objects into a list of one-to-many objects | 37,604,978 | <p>Say we have a list of book objects, each with a title and an author ID:</p>
<pre><code>books = [
{ 'title': 'book1', 'author_id': 'author1' },
{ 'title': 'book2', 'author_id': 'author2' },
{ 'title': 'book3', 'author_id': 'author1' }
]
</code></pre>
<p>How would we efficiently go about transforming thi... | 0 | 2016-06-03T02:23:35Z | 37,605,350 | <p>This works for me. Without multiple loops using a map</p>
<pre><code>authors_map = {}
authors = []
for index, book in enumerate(books):
if book['author_id'] in authors_map:
authors[authors_map[book['author_id']]][
'books'].append({'title': book['title']})
else:
authors_map[book['... | 0 | 2016-06-03T03:11:51Z | [
"python",
"list",
"dictionary",
"one-to-many"
] |
How come my ork fight stops and doesn't go to the move() command :/ | 37,605,035 | <p>At some parts of my code its just stop and doesn't go back to the move(). I want it to add the score and i did that with score = score + 100 BUT it just disrupts the code ;-;. Its a bit messy and i'm sorry about that but please help I have NO clue why it does this. Fyi I'm using this code on pythonroom if that helps... | 1 | 2016-06-03T02:30:53Z | 37,605,288 | <p>You're trying to assign to global variable <code>score</code> within function <code>end</code> like this:</p>
<pre><code>val = 5
def func():
val += 5
</code></pre>
<p>It won't work and will result to <code>UnboundLocalError</code>. In order to fix the issue just use keyword <a href="https://docs.python.org/2/... | 1 | 2016-06-03T03:02:37Z | [
"python",
"random"
] |
Cleaning Wikipedia content with python | 37,605,045 | <p>Hi I have made use of a python library to collect the data of a topic. For example I chose the topic of New york and I have retreived the content with the following code:</p>
<pre><code>import wikipedia
f2 = open('newyork', 'w')
ny = wikipedia.page("New York")
f2.write(ny.content.encode('utf8')+"\n")
</code></pre>... | 0 | 2016-06-03T02:32:09Z | 37,605,217 | <p>For <strong>problem 2</strong> you could do something like this</p>
<pre><code>contents = re.sub('=+\s*.+\s*=+', '', contents)
</code></pre>
<p>Just remember to <code>import re</code>, the regular expressions module.</p>
<p>The method being used is <code>re.sub(pattern, repl, string)</code>. <code>pattern</code> ... | 1 | 2016-06-03T02:53:44Z | [
"python",
"python-2.7",
"wikipedia"
] |
Cleaning Wikipedia content with python | 37,605,045 | <p>Hi I have made use of a python library to collect the data of a topic. For example I chose the topic of New york and I have retreived the content with the following code:</p>
<pre><code>import wikipedia
f2 = open('newyork', 'w')
ny = wikipedia.page("New York")
f2.write(ny.content.encode('utf8')+"\n")
</code></pre>... | 0 | 2016-06-03T02:32:09Z | 37,605,277 | <p>I'll assume that Reference/Further Reading are not the last sections in all pages. If those topics are the last sections replace the highlighted code below with a <code>break</code> command.</p>
<pre><code>import re
def parse(raw_content):
section_title_re = re.compile("^=+\s+.*\s+=+$")
content = []
sk... | 2 | 2016-06-03T03:01:33Z | [
"python",
"python-2.7",
"wikipedia"
] |
Graph a cloud of points with plot_trisurf | 37,605,090 | <p>I'm new to python and have the following problem, I hope you can help me.
My program plots 3D cloud of points using <code>plot_trisurf</code>, and I get the next figure:</p>
<p><a href="http://i.stack.imgur.com/d49KP.png" rel="nofollow"><img src="http://i.stack.imgur.com/d49KP.png" alt="enter image description here... | 0 | 2016-06-03T02:37:04Z | 37,605,382 | <p>Try to plot with such command:</p>
<p><code>ax.plot_trisurf(xs, ys, zs, triangles=triangles, color=(255,0,0,0))</code></p>
<p>Last digit in <code>color</code> set transparency.</p>
| 0 | 2016-06-03T03:16:22Z | [
"python",
"matplotlib",
"mplot3d"
] |
Graph a cloud of points with plot_trisurf | 37,605,090 | <p>I'm new to python and have the following problem, I hope you can help me.
My program plots 3D cloud of points using <code>plot_trisurf</code>, and I get the next figure:</p>
<p><a href="http://i.stack.imgur.com/d49KP.png" rel="nofollow"><img src="http://i.stack.imgur.com/d49KP.png" alt="enter image description here... | 0 | 2016-06-03T02:37:04Z | 37,609,278 | <p>Try setting <code>shade=False</code>as argument in the plot. This should hopefully leave all faces with the same color.</p>
| 0 | 2016-06-03T08:12:07Z | [
"python",
"matplotlib",
"mplot3d"
] |
How to create a linearspace of timestamps in python? | 37,605,271 | <p>Is there any way to create a series of equally spaced date-time objects, given the start/stop epochs and the desired number of intervening elements?</p>
<pre><code>t0 = dateutil.parser.parse("23-FEB-2015 23:09:19.445506")
tf = dateutil.parser.parse("24-FEB-2015 01:09:22.404973")
n = 10**4
series = pandas.period_ran... | 3 | 2016-06-03T03:01:08Z | 37,606,498 | <p>A workaround* is to use numpy's <a href="http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.linspace.html" rel="nofollow"><code>linspace</code></a>:</p>
<pre><code>In [11]: np.linspace(pd.Timestamp("23-FEB-2015 23:09:19.445506").value, pd.Timestamp("24-FEB-2015 01:09:22.404973").value, 50, dtype=np.in... | 2 | 2016-06-03T05:23:00Z | [
"python",
"datetime",
"numpy",
"pandas"
] |
How to determine if my Python Requests call to API returns no data | 37,605,278 | <p>I have a query to an job board API using Python Requests. It then writes to a table, that is included in a web page. Sometimes the request will return no data(if there are no open jobs). If so, I want to write a string to the included file instead of the table. What is the best way to identify a response of no data?... | 0 | 2016-06-03T03:01:41Z | 37,605,377 | <p>You have a couple of options depending on what the response actually is. I assume, case 3 applies best:</p>
<pre><code># 1. Test if response body contains sth.
if response.text:
# ...
# 2. Handle error if deserialization fails (because of no text)
try:
responses=response.json()
# ...
except ValueError:... | 1 | 2016-06-03T03:15:50Z | [
"python",
"json"
] |
Keep change to different hash md5 | 37,605,367 | <pre><code>import ftplib
import hashlib
import httplib
import pytz
import datetime
localtime = datetime.datetime.now(pytz.timezone('Asia/Singapore')).isoformat()
cam = "hi5"
lscam = localtime + cam
ftp = ftplib.FTP('localhost','username','password')
ftp.cwd('Server')
m=hashlib.md5()
file = open('Desktop/frame00000.png... | -1 | 2016-06-03T03:14:26Z | 37,605,478 | <p>Your <code>lscam</code> variable is the concatenation of <code>datetime.datetime.now()</code> in isoformat, and <code>cam</code>.</p>
<p>Since <code>now()</code> obviously returns different values every time you run the script, the md5 is different everytime.</p>
<p>However, if you compute the hash twice, with the... | 1 | 2016-06-03T03:29:25Z | [
"python",
"python-2.7",
"hash",
"md5",
"ftplib"
] |
Python diff two lists what's the time complexity? | 37,605,438 | <p>I've been asked this in a technical interview which I would like to know if my answer is totally wrong or not. </p>
<p>The interviewer asked me to diff two lists. Here's the example</p>
<pre><code>[1, 2, 3, 4], [1, 2, 3] => [4]
[1, 2, 2, 2], [1, 2] => [2, 2]
[1, 2, 2, 2], [1, 2, 3, 3] => [2, 2]
def diff... | 2 | 2016-06-03T03:23:44Z | 37,605,616 | <p>I think it is <code>O(m+n)</code> which is maybe what you meant by <code>2o(n) / o(2n)</code>. You have to iterate both lists. A shorter version might clarify that even though it is probably not optimal:</p>
<pre><code>from collections import Counter
def diff_two_list(list1, list2):
c1, c2 = Counter(list1), Co... | 0 | 2016-06-03T03:51:58Z | [
"python"
] |
Python diff two lists what's the time complexity? | 37,605,438 | <p>I've been asked this in a technical interview which I would like to know if my answer is totally wrong or not. </p>
<p>The interviewer asked me to diff two lists. Here's the example</p>
<pre><code>[1, 2, 3, 4], [1, 2, 3] => [4]
[1, 2, 2, 2], [1, 2] => [2, 2]
[1, 2, 2, 2], [1, 2, 3, 3] => [2, 2]
def diff... | 2 | 2016-06-03T03:23:44Z | 37,605,843 | <p>This answer only focuses on the algorithm when the lists are sorted.</p>
<p>At every given moment in the program you are looking at a value from each list <code>a</code> and <code>b</code>. When <code>a</code> is less then <code>b</code> you know that <code>a</code> cannot be equal to any further values in <code>... | 0 | 2016-06-03T04:17:57Z | [
"python"
] |
Python diff two lists what's the time complexity? | 37,605,438 | <p>I've been asked this in a technical interview which I would like to know if my answer is totally wrong or not. </p>
<p>The interviewer asked me to diff two lists. Here's the example</p>
<pre><code>[1, 2, 3, 4], [1, 2, 3] => [4]
[1, 2, 2, 2], [1, 2] => [2, 2]
[1, 2, 2, 2], [1, 2, 3, 3] => [2, 2]
def diff... | 2 | 2016-06-03T03:23:44Z | 37,605,956 | <p>Assuming sorted list you can iterate over each list once which is <code>O(n)</code>:</p>
<pre><code>def diff_list(a, b):
i, j = iter(b), iter(a)
try:
m, n = next(i), next(j)
while True:
if m == n:
m, n = next(i), next(j)
continue
... | 0 | 2016-06-03T04:29:48Z | [
"python"
] |
Python diff two lists what's the time complexity? | 37,605,438 | <p>I've been asked this in a technical interview which I would like to know if my answer is totally wrong or not. </p>
<p>The interviewer asked me to diff two lists. Here's the example</p>
<pre><code>[1, 2, 3, 4], [1, 2, 3] => [4]
[1, 2, 2, 2], [1, 2] => [2, 2]
[1, 2, 2, 2], [1, 2, 3, 3] => [2, 2]
def diff... | 2 | 2016-06-03T03:23:44Z | 37,606,222 | <p>When you are interviewing for a job the interviewer is looking for many things about the candidate. Some examples:</p>
<ul>
<li>Does the candidate ask the right questions about the problem?</li>
<li>Is the candidate experienced in a skill that I value?</li>
<li>Can the candidate think through a problem and come up ... | 4 | 2016-06-03T04:55:19Z | [
"python"
] |
Unicode to string | 37,605,457 | <p>A function is returning sets of unicode values which I must convert to list of strings. How to go about this? For example, the function returns:</p>
<pre><code>for items in someFunction():
print items, type(items)
>> 2016-06-03, 2016-06-02,2016-06-01 <type 'unicode'>
</code></pre>
<p>but then, I w... | -1 | 2016-06-03T03:26:22Z | 37,605,484 | <p>Convert your string into list using slpit() method of class string, Try the following code.</p>
<pre><code>for items in someFunction():
print items.split(','), type(items.split(','))
</code></pre>
| 0 | 2016-06-03T03:30:04Z | [
"python"
] |
Unicode to string | 37,605,457 | <p>A function is returning sets of unicode values which I must convert to list of strings. How to go about this? For example, the function returns:</p>
<pre><code>for items in someFunction():
print items, type(items)
>> 2016-06-03, 2016-06-02,2016-06-01 <type 'unicode'>
</code></pre>
<p>but then, I w... | -1 | 2016-06-03T03:26:22Z | 37,605,506 | <p>someFunction() is returning a long unicode as the first element, split it with ',' then strip it and do a list comprehention. Try the following.</p>
<pre><code>a = someFunction()
b = [str(i).strip() for i in a[0].split(',')]
print b, type(b)
['2016-06-03', '2016-06-06', '2016-06-05', '2016-06-04'] , <type 'list'... | 0 | 2016-06-03T03:33:56Z | [
"python"
] |
Unicode to string | 37,605,457 | <p>A function is returning sets of unicode values which I must convert to list of strings. How to go about this? For example, the function returns:</p>
<pre><code>for items in someFunction():
print items, type(items)
>> 2016-06-03, 2016-06-02,2016-06-01 <type 'unicode'>
</code></pre>
<p>but then, I w... | -1 | 2016-06-03T03:26:22Z | 37,606,519 | <p>Try to encode each value in the list to a string:</p>
<pre><code> item.encode('UTF8')
</code></pre>
<p>Then you can append to a new list and print it out.</p>
| 0 | 2016-06-03T05:24:10Z | [
"python"
] |
Python script to clean .csv file based on array values | 37,605,531 | <p>I am new to Python, so please forgive me. I have pieced this together through things i've found online, however, it's still not working exactly as it should. </p>
<p>I'm wanting a python script that will look in a given spreadsheet (list.csv), parse it for any "key_words", then export a file of only the rows that D... | 0 | 2016-06-03T03:37:57Z | 37,606,049 | <p>Well code looks fine and worked for me, so there is no problem with it per se.</p>
<p>If you only want to check in the first row you have to split the line by ",":</p>
<pre><code>key_words = ['Dog', 'Cat', 'Bird', 'Cow', ]
with open('list.csv') as oldfile, open('cleaned.csv', 'w') as cleaned, open("matched.csv", ... | 1 | 2016-06-03T04:39:09Z | [
"python",
"shell",
"csv",
"pandas",
"export-to-csv"
] |
Python script to clean .csv file based on array values | 37,605,531 | <p>I am new to Python, so please forgive me. I have pieced this together through things i've found online, however, it's still not working exactly as it should. </p>
<p>I'm wanting a python script that will look in a given spreadsheet (list.csv), parse it for any "key_words", then export a file of only the rows that D... | 0 | 2016-06-03T03:37:57Z | 37,609,633 | <p>Here is a pure <code>pandas</code> method:</p>
<pre><code>In [51]:
key_words = [ 'Dog', 'Cat', 'Bird', 'Cow']
t="""Dog,Walks,Land,4legs
Fish,Swims,Water,fins
Kangaroo,Hops,Land,2legs
Cow,Walks,Land,4legs
Bird,Flies,Air,2legs"""
df = pd.read_csv(io.StringIO(t), header=None)
df
Out[51]:
0 1 2 ... | 0 | 2016-06-03T08:33:07Z | [
"python",
"shell",
"csv",
"pandas",
"export-to-csv"
] |
PyImport_ImportModule, possible to load module from memory? | 37,605,612 | <p>I embedded python in my C++ program.</p>
<p>I use PyImport_ImportModule to load my module written in a .py file.
But how can I load it from memory? Let's say my .py file is encrypted, so I need to first decrypt it and feed the code to python to execute. </p>
<p>Moreover, it'd be nice if I could bypass/intercept or... | 0 | 2016-06-03T03:51:46Z | 37,607,766 | <p>The following example shows how to define a module from a C string:</p>
<pre><code>#include <stdio.h>
#include <Python.h>
int main(int argc, char *argv[])
{
Py_Initialize();
PyRun_SimpleString("print('hello from python')");
// fake module
char *source = "__version__ = '2.0'";
char *... | 1 | 2016-06-03T06:51:01Z | [
"python",
"c++",
"cpython",
"python-embedding"
] |
how to implement localize_callback in flask login | 37,605,686 | <p>I see the offical doc an it does not have any detail inplementation the callback.</p>
<p><a href="http://flask-login.readthedocs.io/en/latest/" rel="nofollow">http://flask-login.readthedocs.io/en/latest/</a></p>
<blockquote>
<p>By default, the LoginManager uses flash to display messages when a
user is required... | 0 | 2016-06-03T04:00:10Z | 37,609,002 | <p>I adjust the code a little bit.and it works though not eligant</p>
<pre><code>def localize_callback(*args, **kwargs):
return 'local string'
login_manager.localize_callback = localize_callback
</code></pre>
| 0 | 2016-06-03T07:57:07Z | [
"python",
"flask",
"flask-login"
] |
Tokenize a paragraph into sentence and then into words in NLTK | 37,605,710 | <p>I am trying to input an entire paragraph into my word processor to be split into sentences first and then into words. </p>
<p>I tried the following code but it does not work,</p>
<pre><code> #text is the paragraph input
sent_text = sent_tokenize(text)
tokenized_text = word_tokenize(sent_text.split)
... | 0 | 2016-06-03T04:03:42Z | 37,605,851 | <p>You probably intended to loop over <code>sent_text</code>:</p>
<pre><code>import nltk
sent_text = nltk.sent_tokenize(text) # this gives us a list of sentences
# now loop over each sentence and tokenize it separately
for sentence in sent_text:
tokenized_text = nltk.word_tokenize(sentence)
tagged = nltk.pos_... | 1 | 2016-06-03T04:18:39Z | [
"python",
"nltk"
] |
How to write the list to file? | 37,605,752 | <p>I am unable to write the result of the following code to a file </p>
<pre><code>import boto3
ACCESS_KEY= "XXX"
SECRET_KEY= "XXX"
regions = ['us-east-1','us-west-1','us-west-2','eu-west-1','sa-east-1','ap-southeast-1','ap-southeast-2','ap-northeast-1']
for region in regions:
client = boto3.client('ec2',aws_access_... | 0 | 2016-06-03T04:09:19Z | 37,605,813 | <pre><code>for eip_dict in addresses_dict['Addresses']:
with open('/root/temps', 'w') as f:
if 'PrivateIpAddress' in eip_dict:
print eip_dict['PublicIp']
f.write(eip_dict['PublicIp'])
</code></pre>
<p>You are re-opening the file for writing at each iteration of the loop. Perhaps the last it... | 1 | 2016-06-03T04:15:14Z | [
"python"
] |
How to write the list to file? | 37,605,752 | <p>I am unable to write the result of the following code to a file </p>
<pre><code>import boto3
ACCESS_KEY= "XXX"
SECRET_KEY= "XXX"
regions = ['us-east-1','us-west-1','us-west-2','eu-west-1','sa-east-1','ap-southeast-1','ap-southeast-2','ap-northeast-1']
for region in regions:
client = boto3.client('ec2',aws_access_... | 0 | 2016-06-03T04:09:19Z | 37,605,844 | <p>open file in append mode </p>
<pre><code> with open('/root/temps', 'a') as f:
</code></pre>
<p>or
declare the file outside the loop</p>
| 1 | 2016-06-03T04:18:06Z | [
"python"
] |
How to use the xpath to parse the director part from the html with python 3 | 37,605,814 | <p>I intend to extract the the director's name(such as tom) from the following html (this just a part example of my html, the whole html, please access <a href="http://movie.walkerplus.com/list/2015/12/" rel="nofollow">http://movie.walkerplus.com/list/2015/12/</a>) with python 3 xpath.
please give your hand to help m... | -1 | 2016-06-03T04:15:21Z | 37,606,418 | <p>Read the link provided by alecxe. You are having that issue.</p>
<ol>
<li>You have spaces in your raw string that do not occur in the
sample html </li>
<li>Quotes are special characters and need to be escaped
or replaced by '.' </li>
<li>You need to set the re.M flag for multiline
strings '.' by default does not ... | 1 | 2016-06-03T05:16:17Z | [
"python",
"html",
"regex",
"parse.com"
] |
How to use the xpath to parse the director part from the html with python 3 | 37,605,814 | <p>I intend to extract the the director's name(such as tom) from the following html (this just a part example of my html, the whole html, please access <a href="http://movie.walkerplus.com/list/2015/12/" rel="nofollow">http://movie.walkerplus.com/list/2015/12/</a>) with python 3 xpath.
please give your hand to help m... | -1 | 2016-06-03T04:15:21Z | 37,610,657 | <p>Definitively use <code>lxml</code> for this instead. Like this:</p>
<pre><code>from lxml import etree
f = StringIO(your_html_text)
tree = etree.parse(f)
what_you_are_looking_for = tree.xpath('//*[contains(concat(' ', @class, ' '), ' movies')]')
</code></pre>
<p>This is a very robust way of getting the data you wan... | 2 | 2016-06-03T09:25:45Z | [
"python",
"html",
"regex",
"parse.com"
] |
Why does only one member variable reset? | 37,605,849 | <p>I've noticed something I'm confused about when creating member variables of a class, then setting their value in a class method. Essentially, in my program whenever I change both member variables in this function, they both change like they're supposed to. However, when I create any other instance of that class with... | 0 | 2016-06-03T04:18:29Z | 37,605,994 | <p>This is because you have assigned <code>board</code> to the class <code>Game</code>, rather than individual instances via the <code>__init__</code> method of the class, resulting in every instances of <code>Game</code> sharing the same <code>Game.board</code> attribute. To ensure every instance have its own indepen... | 1 | 2016-06-03T04:33:37Z | [
"python"
] |
New to Python, can't find bug | 37,605,910 | <p>I am new to Python (3rd day) and I was just trying to creat a basic Rock, Paper, Scissors. I am seeing a bug that I can't locate in the code and was hoping somebody could help. Here is the output below with the code following:</p>
<pre><code>Welcome to Rock, Paper, Scissors!
Player 1 name?b
Player 2 name?s
3
2
1
GO... | 1 | 2016-06-03T04:23:58Z | 37,606,240 | <p>Your bug is primarily a small logic error. While loops with a true condition are generally a bad practice. The crux is that you can rewrite <code>rematchinvalid()</code> like this and still be logically equivalent to what you wanted to achieve.</p>
<pre><code>def rematchinvalid():
global rematch
while remat... | 0 | 2016-06-03T04:57:29Z | [
"python",
"debugging"
] |
New to Python, can't find bug | 37,605,910 | <p>I am new to Python (3rd day) and I was just trying to creat a basic Rock, Paper, Scissors. I am seeing a bug that I can't locate in the code and was hoping somebody could help. Here is the output below with the code following:</p>
<pre><code>Welcome to Rock, Paper, Scissors!
Player 1 name?b
Player 2 name?s
3
2
1
GO... | 1 | 2016-06-03T04:23:58Z | 37,606,342 | <p>Take a look at your function <code>winner</code>:</p>
<pre><code>def winner():
global rematch
if P1 == P2:
print("Draw! Get Ready!.")
start()
RPS()
if P1 == rock and P2 == scissors:
print(name1," win.")
if P1 == rock and P2 == paper:
print(name2," win.... | 1 | 2016-06-03T05:09:20Z | [
"python",
"debugging"
] |
New to Python, can't find bug | 37,605,910 | <p>I am new to Python (3rd day) and I was just trying to creat a basic Rock, Paper, Scissors. I am seeing a bug that I can't locate in the code and was hoping somebody could help. Here is the output below with the code following:</p>
<pre><code>Welcome to Rock, Paper, Scissors!
Player 1 name?b
Player 2 name?s
3
2
1
GO... | 1 | 2016-06-03T04:23:58Z | 37,627,434 | <blockquote>
<p>if you have any recommendations on how to clean up the code, that would be appreciated</p>
</blockquote>
<pre><code>codes = {'rock':0, 'paper':1, 'scissors':2}
...
def winner():
outcome = (codes[P1]-codes[P2])%3
if outcome == 0:
# it's a draw
elif outcome == 1:
# player 1 ... | 0 | 2016-06-04T07:07:02Z | [
"python",
"debugging"
] |
Constantly updating global variable only printing first value | 37,605,970 | <p>I'm trying to display the temperature from a temperature sensor on a 7 segment display. Both are connected to my Raspberry Pi. I need to store the current temperature in a variable, and of course that is always changing.</p>
<p>My problem is that the variable only prints what the temperature is at the point when th... | 2 | 2016-06-03T04:31:00Z | 37,606,017 | <p>You are only reading the temperature once and displaying the same value over and over in your <code>while</code> loop. You should periodically re-read the temperature inside the loop:</p>
<pre><code>while True:
read_temp()
print(temp_f)
time.sleep(1)
</code></pre>
<p>A larger <code>sleep</code> value m... | 2 | 2016-06-03T04:35:51Z | [
"python",
"variables",
"raspberry-pi",
"global-variables"
] |
Constantly updating global variable only printing first value | 37,605,970 | <p>I'm trying to display the temperature from a temperature sensor on a 7 segment display. Both are connected to my Raspberry Pi. I need to store the current temperature in a variable, and of course that is always changing.</p>
<p>My problem is that the variable only prints what the temperature is at the point when th... | 2 | 2016-06-03T04:31:00Z | 37,606,023 | <p>You're only calling <code>read_temp()</code> once, and printing the same value on each iteration. Change your loop to this:</p>
<pre><code>while True:
read_temp()
print(temp_f)
time.sleep(1)
</code></pre>
<p>However, global variable usage like this tends to lead to maintainability problems down the roa... | 1 | 2016-06-03T04:36:28Z | [
"python",
"variables",
"raspberry-pi",
"global-variables"
] |
Is there way to get function called column location not only file and line information for Python? | 37,606,094 | <p>I'm implementing logging function in a static period, and getting id to identify where the function is called is necessary for this.
Currently the id is computed with serialization of 'inspect.stack()[1][1:]' by 'pickle' and I have created below python script for testing this feature.
I'm currently using 'inspect' m... | 0 | 2016-06-03T04:43:46Z | 37,609,675 | <p>You can add <code>time()</code> to distinguish functions called within one line.</p>
<pre><code>import inspect
import hashlib
import pickle
from time import time
def loginfo_throttle():
frame = inspect.stack()[1][0]
print('>'*30)
t = time()
print(hashlib.md5(pickle.dumps((t, inspect.stack()[1][... | 0 | 2016-06-03T08:35:33Z | [
"python",
"logging",
"inspect"
] |
Is there way to get function called column location not only file and line information for Python? | 37,606,094 | <p>I'm implementing logging function in a static period, and getting id to identify where the function is called is necessary for this.
Currently the id is computed with serialization of 'inspect.stack()[1][1:]' by 'pickle' and I have created below python script for testing this feature.
I'm currently using 'inspect' m... | 0 | 2016-06-03T04:43:46Z | 37,614,347 | <p>I found the solution, by getting column in source code as below, seeing this post. <a href="http://stackoverflow.com/questions/23044872/how-to-find-column-number-in-python-code">How to find column number in Python code</a></p>
<pre><code>import inspect
import pickle
import time
class LoggingThrottle(object):
... | 0 | 2016-06-03T12:24:24Z | [
"python",
"logging",
"inspect"
] |
What is the time complexity of Python List Reverse? | 37,606,159 | <p>I have seen this page <a href="https://wiki.python.org/moin/TimeComplexity" rel="nofollow">https://wiki.python.org/moin/TimeComplexity</a> but I don't see the reverse function in there for lists. What is the time time complexity of list reverse?</p>
<p>My experiments with time it indicate that it is O(n) for lar... | 1 | 2016-06-03T04:50:03Z | 37,606,324 | <p>Yes, you are right, it is O(n) where n - length of list.
Look here for more information: <a href="https://www.ics.uci.edu/~pattis/ICS-33/lectures/complexitypython.txt" rel="nofollow">https://www.ics.uci.edu/~pattis/ICS-33/lectures/complexitypython.txt</a></p>
| 1 | 2016-06-03T05:06:24Z | [
"python",
"list",
"time-complexity"
] |
Can I understanding [Passing value in Python] this way? | 37,606,219 | <p>everybody, recently I 've read some articles about [passing value in Python].</p>
<p>here's the link:
<a href="http://stackoverflow.com/questions/986006/how-do-i-pass-a-variable-by-reference">How do I pass a variable by reference?</a></p>
<p>However, I'm confusing if I can understand it this way?</p>
<p><img src... | 2 | 2016-06-03T04:55:07Z | 37,606,606 | <p>You got it correct. In Python, parameters are passed by what's called <strong>reference value</strong>, which means a copy or value of the reference (or pointer if you come from a C background) is passed to the method. Think of these references/pointers as integers containing indices to locations in memory.</p>
<p>... | 2 | 2016-06-03T05:30:54Z | [
"python",
"parameter-passing"
] |
Can I understanding [Passing value in Python] this way? | 37,606,219 | <p>everybody, recently I 've read some articles about [passing value in Python].</p>
<p>here's the link:
<a href="http://stackoverflow.com/questions/986006/how-do-i-pass-a-variable-by-reference">How do I pass a variable by reference?</a></p>
<p>However, I'm confusing if I can understand it this way?</p>
<p><img src... | 2 | 2016-06-03T04:55:07Z | 37,608,754 | <p>I think the concept you are missing is "variable scope". Variables created inside a function/method are in a different scope as variables outside the function/method. They are different <strong>even if they have the same name</strong>. You create a variable called <code>the_list</code> that references an object then... | 0 | 2016-06-03T07:44:57Z | [
"python",
"parameter-passing"
] |
How to create a package and modules in python? | 37,606,279 | <p>I am new to python so I trying python packages and modules,but I had a error in my project don't know what was wrong in this.,</p>
<p><strong>Menu.InitUI</strong><br/></p>
<p><strong>TypeError: InitUI() missing 1 required positional argument:'self'</strong></p>
<p>I had a three files<br/>
<strong>1)__init__.py</s... | 1 | 2016-06-03T05:01:34Z | 37,606,834 | <p>The short answer is that <code>def InitUI(self):</code> and <code>def OnQuit(self, e):</code> are ment to belong to a class, and it appears you don't have them in a class. <code>self</code> refers to the current instance of the class a function belongs to.</p>
| 1 | 2016-06-03T05:51:53Z | [
"python",
"python-3.x",
"wxpython",
"python-module",
"python-packaging"
] |
How to create a package and modules in python? | 37,606,279 | <p>I am new to python so I trying python packages and modules,but I had a error in my project don't know what was wrong in this.,</p>
<p><strong>Menu.InitUI</strong><br/></p>
<p><strong>TypeError: InitUI() missing 1 required positional argument:'self'</strong></p>
<p>I had a three files<br/>
<strong>1)__init__.py</s... | 1 | 2016-06-03T05:01:34Z | 37,606,985 | <p>if the def InitUI() method is not of any "Menu" class then you dont need any self parameter in that. No need to do Menu.InitUI() since you have imported the InitUI() method. So simply call it like InitUI(). As you have declared the function as InitUI(self) but calling as Menu.InitUI() thats why the problem is comin... | 1 | 2016-06-03T06:03:36Z | [
"python",
"python-3.x",
"wxpython",
"python-module",
"python-packaging"
] |
applying a freeze transformation command to several duplicates | 37,606,329 | <p>I try to apply a freeze transformation command as well as deleting the history of my duplicates of a geo sphere in maya. Unfortunately it just gets applied to the first object. Here is my forloop:</p>
<pre><code>for items in rigSelection:
cmds.listRelatives(shapes=True)
cleanDuplicate = cmds.duplicate(r... | 1 | 2016-06-03T05:07:10Z | 37,614,799 | <p>Your duplicates are under cleanDuplicate/conDuplicate. You should loop throught them and use command in for loop like this :</p>
<pre><code>items = cleanDuplicate + conDuplicate # where cleanDuplicate/conDuplicate are []
for cleaner in items:
cmds.delete(cleaner, constructionHistory=True)
cmds.makeIdentity... | 1 | 2016-06-03T12:47:06Z | [
"python",
"duplicates",
"maya"
] |
This is a pong game its for my final project but i cant seem to know why the background image doesnt show up | 37,606,492 | <h1> starting all modules and window</h1>
<p>import pygame, sys, time, random
from pygame.locals import *</p>
<pre><code>pygame.init()
bg = pygame.image.load("./soccerfield.png")
mainClock = pygame.time.Clock()
WINDOWWIDTH = 800
WINDOWHEIGHT = 600
SIZESIDES = 20
MIDDLESIZE = 10
FPS = 30
PADDLESPEED = 10
#Rect... | -2 | 2016-06-03T05:22:37Z | 37,606,741 | <p>I don't see you blitting the background image anywhere in your code. Does ammending your draw function like this help? :</p>
<pre><code>def drawGame(Paddle1, scoreP1, Paddle2, scoreP2, Ball):
windowSurface.fill(BLACK)
windowSurface.blit(bg,(0,0)) #added bg image to draw function
Paddle1.draw()
Paddl... | 1 | 2016-06-03T05:44:03Z | [
"python",
"background",
"pygame",
"pong"
] |
How to create a keyframe with Python API for 3D Studio Max | 37,606,543 | <p>Currrently I'm creating keyframes with autokey, like this:</p>
<pre><code>MaxPlus.Animation.SetAnimateButtonState(True) # autokey on
MaxPlus.Animation.SetTime(time) # Set time slider to chosen time of keframe
obj.Position = MaxPlus.Point3(x, y, z) # Set position
MaxPlus.Animation.SetAnimateB... | 1 | 2016-06-03T05:26:08Z | 37,646,531 | <p>With max 2016, there's hardly a better way than what you're doing. Sure, you can assign a new visibility controller:</p>
<pre><code>node.SetVisibilityController(MaxPlus.Factory.CreateDefaultFloatController())
</code></pre>
<p>Or you can modify any existing one:</p>
<pre><code>node.GetSubAnim(0).AddNewKey(time, pa... | 0 | 2016-06-05T20:40:23Z | [
"python",
"python-2.7",
"3dsmax"
] |
Numpy Summing All At Once Gives NaN, But Summing Separately Does Not | 37,606,547 | <p>I have some data - all of it are non-negative. Numpy says its sum is nan, but I don't believe it is. Here is my explanation:</p>
<p>First, I read in the training data:</p>
<pre><code>dataframe = pandas.read_csv( "buggy.csv" )
training = dataframe.ix[:,dataframe.columns != "Survived"].values.astype( np.float32 )
</... | 0 | 2016-06-03T05:26:27Z | 37,606,679 | <p>You are skipping row 61, that's the problematic one. <code>training[0:61][:].sum()</code> excludes row 61.</p>
<pre><code>training[61]
Out[10]: array([ 61., 1., 1., 38., 0., 0., 80., nan], dtype=float32)
</code></pre>
<p>The last column is missing, it has only 7 values. </p>
| 4 | 2016-06-03T05:37:44Z | [
"python",
"numpy",
"pandas"
] |
KeyError while trying to read from Python dataframe | 37,606,625 | <p>Hi I am new to Python and I am trying to read from a csv file using the following code</p>
<pre><code>dataFrame = pd.read_csv(path, header=None)
X = dataFrame.loc[:,1:93]
y = dataFrame.loc[:,94]
print(X)
print(y)
</code></pre>
<p>But I get the following error </p>
<blockquote>
<p>KeyError: 'the label [94] is n... | 0 | 2016-06-03T05:33:06Z | 37,671,141 | <p>My problem has been solved.. Actually my columns in csv were getting read as a single column with /t appended. So I used delimiter specification as follows
<code>dataFrame = pd.read_csv(temp_file,sep=', ', delimiter='\t')</code>
the code works now.</p>
| 0 | 2016-06-07T05:26:45Z | [
"python",
"dataframe"
] |
Enumerate function in lua/torch | 37,606,658 | <p>In python, we use <code>for i, _ in enumerate(wx):</code> where <code>wx</code> is a row matrix or table.
How can we use this in lua/torch. Any enumerate function?</p>
| 1 | 2016-06-03T05:35:59Z | 37,606,794 | <p>In Lua, you have <a href="https://devdocs.io/lua~5.3/index#pdf-pairs" rel="nofollow"><code>pairs</code></a> and <a href="https://devdocs.io/lua~5.3/index#pdf-ipairs" rel="nofollow"><code>ipairs</code></a>:</p>
<blockquote>
<pre><code>pairs (t)
</code></pre>
<p>If <code>t</code> has a metamethod <code>__pairs</... | 1 | 2016-06-03T05:47:38Z | [
"python",
"lua",
"torch"
] |
Python nested loop working with data file | 37,606,687 | <p>I've got a file with data and I want to search for the maximum reading per each hour.</p>
<pre><code>def maximum():
source = open ( 'dataV.csv', 'r' )
result = open ( 'dataV-max.csv', 'w' )
line = source.readline()
max_num = '0'
while line != '' :
for time in range(0, 24):
line = source.readline()
... | 1 | 2016-06-03T05:38:42Z | 37,607,807 | <p>Hero you go:</p>
<pre><code>import sys
def fileParser(sourcefileName, destinationfileName):
fd = open(sourcefileName)
lines = fd.readlines()
hourMaxDict = dict()
for line in lines[1:]:
hour = line.split(" ")[1].split(":")[0]
maxRead = float(line.split(",")[-1].rstrip())
... | 0 | 2016-06-03T06:53:35Z | [
"python"
] |
Python nested loop working with data file | 37,606,687 | <p>I've got a file with data and I want to search for the maximum reading per each hour.</p>
<pre><code>def maximum():
source = open ( 'dataV.csv', 'r' )
result = open ( 'dataV-max.csv', 'w' )
line = source.readline()
max_num = '0'
while line != '' :
for time in range(0, 24):
line = source.readline()
... | 1 | 2016-06-03T05:38:42Z | 37,609,591 | <p>Given the input:</p>
<pre><code>'time PST', saturn03.820.A.AlgaeWatch [microg/l]
'2014-04-25 00:04:48',3.35
'2014-04-25 00:04:54',3.225
'2014-04-25 00:05:00',3.15
'2014-04-25 00:07:48',3.4
'2014-04-25 00:07:54',3.4
'2014-04-25 00:08:00',3.375
'2014-04-25 00:10:48',3.45
'2014-04-25 00:10:54',3.325
'2014-04-25 00:11:... | 0 | 2016-06-03T08:30:51Z | [
"python"
] |
How to calculate the number of recursive call? | 37,606,707 | <p>As ex. I write fibonancci code by recursion -</p>
<pre><code>def fib(n):
x = 0
if n == 0 or n == 1:
return 1
else:
print('computing : ', n) # this show the recursive call.
x = x +1
print('recursive call no total : ',x) # this show the how many number of recursive call.
... | 1 | 2016-06-03T05:40:37Z | 37,606,857 | <p>few ways of doing this</p>
<p>we can use counter as you tried with slight changes:</p>
<pre><code>def fib(n):
if n == 0 or n == 1:
return 1
else:
print('computing : ', n) # this show the recursive call.
fib.x = fib.x + 1
# this show the how many number of recursive call.
... | 2 | 2016-06-03T05:53:14Z | [
"python",
"python-3.x",
"recursion"
] |
How to calculate the number of recursive call? | 37,606,707 | <p>As ex. I write fibonancci code by recursion -</p>
<pre><code>def fib(n):
x = 0
if n == 0 or n == 1:
return 1
else:
print('computing : ', n) # this show the recursive call.
x = x +1
print('recursive call no total : ',x) # this show the how many number of recursive call.
... | 1 | 2016-06-03T05:40:37Z | 37,607,543 | <p>Using a global variable , i tried to solve the ans . Code's may like below-</p>
<pre><code>def fib(n):
global numcalls
numcalls += 1 #this will increment with every fib() call
if n ==0 or n ==1:
return 1
else:
return fib(n-1) + fib(n-2)
print('numcalls =', numcalls)
</code></pre>... | 0 | 2016-06-03T06:39:20Z | [
"python",
"python-3.x",
"recursion"
] |
use python pandas convert csv to html | 37,606,757 | <p>I have a csv file and need to convert to html format. I know python pandas can do it with DataFormat.to_html(), but could not figure out what value to put in the (). I have:
pd.DataFrame.to_html(class=myfile.csv) but got issue with it.</p>
<p>Anyone has idea?</p>
| 1 | 2016-06-03T05:45:24Z | 37,606,812 | <p>You need to put there dataframe:</p>
<pre><code>df = pd.read_csv("myfile.csv")
df.to_html('your_file.html')
</code></pre>
| 2 | 2016-06-03T05:50:10Z | [
"python",
"html",
"csv",
"pandas"
] |
use python pandas convert csv to html | 37,606,757 | <p>I have a csv file and need to convert to html format. I know python pandas can do it with DataFormat.to_html(), but could not figure out what value to put in the (). I have:
pd.DataFrame.to_html(class=myfile.csv) but got issue with it.</p>
<p>Anyone has idea?</p>
| 1 | 2016-06-03T05:45:24Z | 37,606,886 | <p>You can put path where you want to save file including file name.
Example:
DF.to_html ("C:/desktop/test.html")</p>
| 0 | 2016-06-03T05:55:42Z | [
"python",
"html",
"csv",
"pandas"
] |
How to log in to a website while scraping with python 3.5 | 37,606,766 | <p>I am trying to scrape the data from the website <code>www.vestiairecollective.com</code> While scraping I have access to only few of its main pages. For example my script cannot scrape the data for the url <code>http://www.vestiairecollective.com/women-bags/handbags/#_=catalog&id_brand%5B%5D=50&material%5B%5... | 0 | 2016-06-03T05:45:40Z | 37,607,748 | <p>You've got an error in <code>request.Sessions()</code> which should be <code>request.Session()</code>.</p>
<p>My <a href="http://stackoverflow.com/a/37118451/1150303">answer</a> to a similar question will provide some sample code for persistant login with python <code>requests</code> (Python 3).</p>
<p>Shortly sum... | 0 | 2016-06-03T06:50:12Z | [
"python",
"python-3.x",
"web-scraping",
"robobrowser"
] |
How to build Python project including dependencies? | 37,606,773 | <p>I have a few projects, all containing <em><code>setup.py</code></em> and <em><code>requirements.txt</code></em>. Is it possible to package a whole project in one single file including all requirements compiled and ready to install?</p>
<p>What I have tried:</p>
<pre><code>python setup.py bdist_wheel
</code></pre>
... | 1 | 2016-06-03T05:46:00Z | 37,609,201 | <p>You probably want to take a look at tools like <a href="http://cx-freeze.sourceforge.net/" rel="nofollow">cx_freeze</a> or <a href="http://www.pyinstaller.org/" rel="nofollow">PyInstaller</a> if you absolutely want one single file containing everything. Pip itself cannot do what you want.</p>
| 0 | 2016-06-03T08:08:08Z | [
"python",
"pip",
"wheel"
] |
Search a textfile using elements from a dictionary or other data structure in python | 37,606,799 | <p>I'm trying to read in a text file and using a dictionary to see if certain words or other characters appear in the text file. If so how many?</p>
<p>Here is my code so far:</p>
<pre><code>d = {}
d["keyword"] = ["he","him","his"]
print d
keywords = 0
print ("Opening the file")
with open('textFile.txt','r') ... | 0 | 2016-06-03T05:48:11Z | 37,607,049 | <p>1.If we do not use the Dict.then then we can use..</p>
<pre><code> d= ["he","him","his"]
print d
keywords = 0
print ("Opening the file")
with open('textFile.txt','r') as foo:
for line in foo:
elements = line.split()
print elements
for i in range(len(d)):
fo... | 0 | 2016-06-03T06:08:20Z | [
"python",
"dictionary"
] |
Search a textfile using elements from a dictionary or other data structure in python | 37,606,799 | <p>I'm trying to read in a text file and using a dictionary to see if certain words or other characters appear in the text file. If so how many?</p>
<p>Here is my code so far:</p>
<pre><code>d = {}
d["keyword"] = ["he","him","his"]
print d
keywords = 0
print ("Opening the file")
with open('textFile.txt','r') ... | 0 | 2016-06-03T05:48:11Z | 37,607,244 | <p>Try the following code: </p>
<pre><code>for line in foo:
elements = list(line.split())
for element in elements:
if element in d["keyword"]:
keywords +=1
print keywords
</code></pre>
| 0 | 2016-06-03T06:21:41Z | [
"python",
"dictionary"
] |
Search a textfile using elements from a dictionary or other data structure in python | 37,606,799 | <p>I'm trying to read in a text file and using a dictionary to see if certain words or other characters appear in the text file. If so how many?</p>
<p>Here is my code so far:</p>
<pre><code>d = {}
d["keyword"] = ["he","him","his"]
print d
keywords = 0
print ("Opening the file")
with open('textFile.txt','r') ... | 0 | 2016-06-03T05:48:11Z | 37,607,313 | <p>Every time you run <code>for d["keyword"] in elements</code>, you will change the content of <code>d["keyword"]</code> to the current word in <code>elements</code>.</p>
<p>I think it should be:</p>
<pre><code>for line in foo:
elements = line.split()
for elem in elements:
if elem in d["keyword"]:
... | 1 | 2016-06-03T06:26:29Z | [
"python",
"dictionary"
] |
in celery rabbitmq exchange type topic is not working properly | 37,606,835 | <p>I have two python projects. Both are enabled with celery. What i am trying to do here is from project A i am sending task using send_task() method. The task which is i am sending is in project B. So the project B's worker is up and its showing the task. Till this condition everything is working fine. But when i make... | 0 | 2016-06-03T05:51:53Z | 37,661,007 | <p>Both workers are consuming tasks from same queue. </p>
<p>When you have started worker A, it hasn't recognised any tasks (as seen from log).</p>
<pre><code>[tasks]
</code></pre>
<p>Worker B has recognised only 1 task.</p>
<pre><code>[tasks]
. mplogin.sync.register
</code></pre>
<p>You have to make sure both w... | 0 | 2016-06-06T15:16:25Z | [
"python",
"rabbitmq",
"celery",
"amqp"
] |
How to choose Django config setting in virtualenv just once | 37,606,842 | <p>I was reading some materials to better organize my code in Django and I started reading this: <a href="http://www.revsys.com/blog/2014/nov/21/recommended-django-project-layout/" rel="nofollow">http://www.revsys.com/blog/2014/nov/21/recommended-django-project-layout/</a> ... Thought it was a good idea to have differe... | 0 | 2016-06-03T05:52:17Z | 37,608,779 | <p>If you are not using virtualenvwrapper, you can put it in <code>$VIRTUAL_ENV/bin/activate</code> script. like</p>
<p><code>export DJANGO_SETTINGS_MODULE='foo.settings.development'</code></p>
<p>In the same script you can see a deactivate function, there you can unset the environment variable, which will be called ... | 1 | 2016-06-03T07:46:09Z | [
"python",
"django",
"virtualenv"
] |
Duplicates inside list being combined rather than omitted. Conditional error | 37,606,877 | <p>What you see here is a simple sitemap generator. The problem is that whenever there is a duplicate of a link, instead of not doing anything, it seems to combine the duplicate with the next url. For example, it will say <a href="http://www.apple.comhttp://www.apple.com/sitemap" rel="nofollow">http://www.apple.comhttp... | 0 | 2016-06-03T05:55:15Z | 37,607,064 | <p>You don't reset <code>toturl</code> if there is a duplicate. Allways initial variables, when they are first used, not when you're done with them.</p>
<pre><code>from time import sleep
from urllib.request import urlopen
allurl = ["http://www.apple.com"]
url = "http://www.apple.com"
prinst = True
print("Urllib loade... | 0 | 2016-06-03T06:09:44Z | [
"python",
"url",
"conditional",
"ignore"
] |
How to remove a context manager from an ExitStack | 37,606,904 | <p>I have a long-running process called an Updater, that has updates (to an ETL system) submitted to it. The updates have resource requirements that are managed by adding a context manager to the Updater's ExitStack. Some updates will include new configuration, which means that effected resources must be released from ... | 1 | 2016-06-03T05:56:56Z | 37,607,078 | <p><code>contextlib.ExitStack</code> only supports exiting all context managers at once. You can't pop context managers individually. If you want to do this, you should keep track of your context managers with something other than an ExitStack.</p>
| 1 | 2016-06-03T06:10:47Z | [
"python",
"stack",
"with-statement",
"manager"
] |
How to remove a context manager from an ExitStack | 37,606,904 | <p>I have a long-running process called an Updater, that has updates (to an ETL system) submitted to it. The updates have resource requirements that are managed by adding a context manager to the Updater's ExitStack. Some updates will include new configuration, which means that effected resources must be released from ... | 1 | 2016-06-03T05:56:56Z | 37,607,405 | <p>You have to extend <code>ExitStack</code> with your own <code>pop</code>-method:</p>
<pre><code>from contextlib import ExitStack
from collections import deque
class ExitStackWithPop(ExitStack):
def pop(self, cm):
callbacks = self._exit_callbacks
self._exit_callbacks = deque()
found = No... | 2 | 2016-06-03T06:31:03Z | [
"python",
"stack",
"with-statement",
"manager"
] |
object has no attribute 'replace' trying to read a file.txt | 37,606,964 | <p>Before you say it's duplicated... I've read at least 15 other answers and couldn't make it...</p>
<p>I started getting this error while trying to replace an specific line.
Now it tells me it has no replace attribute... which it had at some point</p>
<p>I just need to add +1 to an specific line everytime a determin... | -4 | 2016-06-03T06:02:19Z | 37,607,158 | <p>Obviously a <code>_io.TextIOWrapper</code> i.e. a file object will not have a replace method which is a string function. I think you're trying to make replacements in the entire file. Here is a quick fix. </p>
<pre><code>file_data = ''.join(lines)
# Now apply your replacements here
file_data = file_data.replace(st... | 1 | 2016-06-03T06:15:06Z | [
"python",
"python-3.x"
] |
object has no attribute 'replace' trying to read a file.txt | 37,606,964 | <p>Before you say it's duplicated... I've read at least 15 other answers and couldn't make it...</p>
<p>I started getting this error while trying to replace an specific line.
Now it tells me it has no replace attribute... which it had at some point</p>
<p>I just need to add +1 to an specific line everytime a determin... | -4 | 2016-06-03T06:02:19Z | 37,607,161 | <p>The problem is that you are trying to call <code>replace</code> method on a <code>file</code> object, whereas this is a <code>string</code> method.</p>
<p>Indeed :</p>
<pre><code>>>> f = open('test.txt', 'r+')
>>> ... | 1 | 2016-06-03T06:15:15Z | [
"python",
"python-3.x"
] |
object has no attribute 'replace' trying to read a file.txt | 37,606,964 | <p>Before you say it's duplicated... I've read at least 15 other answers and couldn't make it...</p>
<p>I started getting this error while trying to replace an specific line.
Now it tells me it has no replace attribute... which it had at some point</p>
<p>I just need to add +1 to an specific line everytime a determin... | -4 | 2016-06-03T06:02:19Z | 37,607,489 | <p>What you are trying to do is not practical - in any language. </p>
<p>First, as others have said, there is no <code>replace()</code> method on a file object.</p>
<p>More importantly you don't seem to understand how text files work. You say: "<em>I saw some answers when they create a new file everytime</em>". D... | 3 | 2016-06-03T06:36:12Z | [
"python",
"python-3.x"
] |
Boxplot needs to use multiple groupby in Pandas | 37,607,112 | <p>I am using pandas, Jupyter notebooks and python.
I have a following dataset as a dataframe</p>
<pre><code>Cars,Country,Type
1564,Australia,Stolen
200,Australia,Stolen
579,Australia,Stolen
156,Japan,Lost
900,Africa,Burnt
2000,USA,Stolen
1000,Indonesia,Stolen
900,Australia,Lost
798,Australia,Lost
128,Australia,Lost
2... | 0 | 2016-06-03T06:13:22Z | 37,609,054 | <p>You can select only the rows corresponding to <code>"Australia"</code> from the column <code>"Country"</code> and group it by the column <code>"Type"</code> as shown:</p>
<pre><code>from StringIO import StringIO
import pandas as pd
text_string = StringIO(
"""
Cars,Country,Type,Score
1564,Australia,Stolen,1
200,Aus... | 2 | 2016-06-03T08:00:36Z | [
"python",
"pandas",
"boxplot",
"jupyter"
] |
cx oracle python interface error : unable to acquire oracle environment handle | 37,607,223 | <p>I have big problem with my program written in Python 2.7.11.</p>
<p>When program is executed from PyCharm IDE everything is OK. Then I use pyinstaller to maxe .exe for windows. Running the .exe file couses only one error: </p>
<p>cx_Oracle.InterfaceError: Unable to acquire Oracle environment handle.</p>
<p>This p... | 0 | 2016-06-03T06:19:58Z | 37,667,501 | <p>In order for cx_Oracle to work, an Oracle client is required. The easiest way is to install the Oracle instant client which can be found here:</p>
<p><a href="http://www.oracle.com/technetwork/database/features/instant-client/index.html" rel="nofollow">http://www.oracle.com/technetwork/database/features/instant-cli... | 1 | 2016-06-06T21:58:46Z | [
"python",
"oracle",
"pyinstaller",
"cx-oracle"
] |
Fixing the order of x labels in pandas plot | 37,607,228 | <p>I have the following graph, now I want to have a fixed order of the labels going from smaller to bigger, however pandas rearanges them to get a nice looking graph. I want it fixed so that it is easier to compare many graphs side by side.</p>
<p><a href="http://i.stack.imgur.com/vHPRn.png" rel="nofollow"><img src="h... | -1 | 2016-06-03T06:20:41Z | 37,607,965 | <p>You can pass <code>sort=False</code> to <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.value_counts.html#pandas-series-value-counts" rel="nofollow"><code>value_counts()</code></a>:</p>
<p><code>plot = sample_cut.value_counts(normalize=True, sort=False).plot()</code></p>
<p>This disabl... | 2 | 2016-06-03T07:02:40Z | [
"python",
"pandas",
"plot"
] |
Django : RunTimeWarning : DateTimeField received a naive datetime while time zone support is active | 37,607,411 | <p>I am trying to test a cart creation based on <a href="https://github.com/bmentges/django-cart/blob/master/cart/tests.py" rel="nofollow">django cart</a></p>
<p>But I have this error when I am trying to create the cart :</p>
<blockquote>
<p>RunTimeWarning : DateTimeField received a naive datetime while time zone s... | 1 | 2016-06-03T06:31:32Z | 37,607,525 | <p>The following line creates a naive (non-timezone aware) datetime:</p>
<pre><code>creationDate = datetime.datetime.now()
</code></pre>
<p>Try changing that line to:</p>
<pre><code>creationDate = timezone.now()
</code></pre>
<p>Don't forget to import <code>timezone</code> at the beginning of your code:</p>
<pre><... | 3 | 2016-06-03T06:38:29Z | [
"python",
"django"
] |
CSV Reader not getting the right value from array | 37,607,569 | <p>Below is a class I am making to calculate checkbook transactions. My issue lies in the <code>elif</code> statements where I check if <code>row[0] == "starting"</code> or <code>"ending"</code>. In the csv file which I will also copy and paste, it clearly states in <code>row[0]</code> that those words are there, but m... | 0 | 2016-06-03T06:41:13Z | 37,607,627 | <p>Convert to an <code>int</code> first:</p>
<pre><code>self.startAmt += int(row[1])
</code></pre>
| 0 | 2016-06-03T06:44:08Z | [
"python",
"oop",
"csv"
] |
CSV Reader not getting the right value from array | 37,607,569 | <p>Below is a class I am making to calculate checkbook transactions. My issue lies in the <code>elif</code> statements where I check if <code>row[0] == "starting"</code> or <code>"ending"</code>. In the csv file which I will also copy and paste, it clearly states in <code>row[0]</code> that those words are there, but m... | 0 | 2016-06-03T06:41:13Z | 37,608,257 | <p>You have to keep in mind that all values read from the file are strings and not numbers. If you want to do calculations, you'll have to convert the values intelligently.</p>
<p>You can also simplify your logic a bit; at the same time improve your code by limiting what is in the try/except block. A large statement b... | 0 | 2016-06-03T07:19:17Z | [
"python",
"oop",
"csv"
] |
CSV Reader not getting the right value from array | 37,607,569 | <p>Below is a class I am making to calculate checkbook transactions. My issue lies in the <code>elif</code> statements where I check if <code>row[0] == "starting"</code> or <code>"ending"</code>. In the csv file which I will also copy and paste, it clearly states in <code>row[0]</code> that those words are there, but m... | 0 | 2016-06-03T06:41:13Z | 37,609,344 | <p>class file:
<code>import csv
class Checkbook(object):
def __init__(self, filename):
self.name =filename
self.debitList = []
self.creditList = []
self.startAmt = 0
self.endAmt = 0.0
def Parse(self):
with open(self.name) as csvFile:
readCSV = csv.read... | 0 | 2016-06-03T08:16:21Z | [
"python",
"oop",
"csv"
] |
I want to plot a rectangle with given 4 coordinates in a text file in gnuplot. The rectangle may be at an angle to x axis | 37,607,583 | <p>How do I read the data from the file and plot the rectangle?
The given text file has the following format up to 50 rows:
x1 y1 x2 y2 x3 y3 x4 y4</p>
<p>where (x1,y1), (x2,y2), (x3,y3) and (x4,y4) are the four vertices of the rectangle. The rectangles have random orientation. How do I plot the series of rect... | 2 | 2016-06-03T06:42:03Z | 37,608,709 | <p>Here's the Python code to do so as we discussed. </p>
<p>Your input file is of format: </p>
<pre><code>__ __ x1 y1 x2 y2 x3 y3 x4 y4
</code></pre>
<p>The code.</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
data = np.loadtxt('car.txt')
data = [i[2:] for i in data]
for d in data:
Xs = ... | 1 | 2016-06-03T07:42:28Z | [
"python",
"random",
"plot",
"gnuplot",
"rectangles"
] |
I want to plot a rectangle with given 4 coordinates in a text file in gnuplot. The rectangle may be at an angle to x axis | 37,607,583 | <p>How do I read the data from the file and plot the rectangle?
The given text file has the following format up to 50 rows:
x1 y1 x2 y2 x3 y3 x4 y4</p>
<p>where (x1,y1), (x2,y2), (x3,y3) and (x4,y4) are the four vertices of the rectangle. The rectangles have random orientation. How do I plot the series of rect... | 2 | 2016-06-03T06:42:03Z | 37,640,020 | <p>My <code>Gnuplot</code> solution (not just for rectangles, but any kind of polygons):</p>
<pre><code>plot 'rectal.dat' u 1:2:($3-$1):($4-$2) with vectors nohead lc 1 title 'Rectangle', \
'' u 3:4:($5-$3):($6-$4) with vectors nohead lc 1 notitle, \
'' u 5:6:($7-$5):($8-$6) with vectors nohead lc 1 notitle, \
'' u ... | 1 | 2016-06-05T08:44:18Z | [
"python",
"random",
"plot",
"gnuplot",
"rectangles"
] |
Identify the non-zero element in a list which is close to given number in Python | 37,607,592 | <p>I have list like this:</p>
<pre><code>lst = [1, 5, 0, 0, 4, 0]
</code></pre>
<p>EDIT:
I would like find the location of the first number in list that is not equal to zero and it is <strong>closest</strong> given number.</p>
<pre><code>a = 3 # (given number)
</code></pre>
<p>It should return 4 as index and value... | 3 | 2016-06-03T06:42:41Z | 37,607,759 | <p>If I understood you correctly, just filter out the zeros after enumerating:</p>
<pre><code>In [1]: lst = [1, 5, 0, 0, 4, 0]
In [2]: a = 3
In [3]: min(filter(lambda x: x[1] != 0, enumerate(lst)),
key=lambda x: abs(x[1] - a))
Out[3]: (4, 4)
</code></pre>
<p>Your own example does return <code>(4, 4)</co... | 5 | 2016-06-03T06:50:44Z | [
"python"
] |
Identify the non-zero element in a list which is close to given number in Python | 37,607,592 | <p>I have list like this:</p>
<pre><code>lst = [1, 5, 0, 0, 4, 0]
</code></pre>
<p>EDIT:
I would like find the location of the first number in list that is not equal to zero and it is <strong>closest</strong> given number.</p>
<pre><code>a = 3 # (given number)
</code></pre>
<p>It should return 4 as index and value... | 3 | 2016-06-03T06:42:41Z | 37,608,040 | <p>Your answer is pretty close. You just need to replace zero with infinity.</p>
<pre><code>min(enumerate(lst), key=lambda x: abs(a - (x[1] if x[1] else float("inf"))))
</code></pre>
<p>Edit: flipped <code>a</code> and <code>x[1]</code></p>
| 2 | 2016-06-03T07:06:48Z | [
"python"
] |
How to install Airflow slave/client without the master/server? | 37,607,723 | <p>I've installed airflow onto my server as per the documentations instructions <a href="https://pythonhosted.org/airflow/start.html" rel="nofollow">here</a>. </p>
<p>The installation looks to contain both the master (server) and slave (client).</p>
<p>How to install the slave/client component of Airflow on another c... | 3 | 2016-06-03T06:49:05Z | 37,799,237 | <p>I am not sure what you are referring as client. In my environment Airflow WebServer , Scheduler and worker (CeleryExecutor) are all installed in same server and those components are started as part of init scripts.</p>
| 0 | 2016-06-13T21:13:53Z | [
"python",
"workflow",
"batch-processing",
"job-scheduling",
"airflow"
] |
cumsum() over several columns | 37,607,822 | <p>I want to create the following dataframe:</p>
<pre><code>Index A B C
a 0 0 0
b 1 10 0
c -1 0 -10
d 1 20 0
e 0 0 0
f -1 0 -20
g 0 0 0
h ... | 2 | 2016-06-03T06:54:10Z | 37,608,043 | <p>Try:</p>
<pre><code>df.C = (df.B.replace(0, np.nan).ffill().shift() * (df.A == -1) * -1).fillna(0)
</code></pre>
<hr>
<p>confirmed jezrael's suggestion:</p>
<pre><code>df.C = (df.B.replace(0, np.nan).ffill() * (df.A == -1) * -1).fillna(0)
</code></pre>
<p>works just as well. Since we are forward filling, the s... | 2 | 2016-06-03T07:07:01Z | [
"python",
"pandas",
"dataframe",
"cumsum"
] |
cumsum() over several columns | 37,607,822 | <p>I want to create the following dataframe:</p>
<pre><code>Index A B C
a 0 0 0
b 1 10 0
c -1 0 -10
d 1 20 0
e 0 0 0
f -1 0 -20
g 0 0 0
h ... | 2 | 2016-06-03T06:54:10Z | 37,608,625 | <p>It's easy to do in <code>numpy</code>, but I have yet to find a way to find a way to do it directly in <code>pandas</code>, because apparently <code>pandas</code> somehow ignores the fancy indexing:</p>
<pre><code>def generate_C(df, inplace=False):
import numpy
if not inplace:
df = df.copy()
A... | 2 | 2016-06-03T07:37:15Z | [
"python",
"pandas",
"dataframe",
"cumsum"
] |
cumsum() over several columns | 37,607,822 | <p>I want to create the following dataframe:</p>
<pre><code>Index A B C
a 0 0 0
b 1 10 0
c -1 0 -10
d 1 20 0
e 0 0 0
f -1 0 -20
g 0 0 0
h ... | 2 | 2016-06-03T06:54:10Z | 37,609,060 | <p>You can use:</p>
<pre><code>df.loc[df.A==-1, 'C'] = (-df.loc[df.A==1, 'B']).values
df.C.fillna(0, inplace=True)
print (df)
A B C
Index
a 0 0 0.0
b 1 10 0.0
c -1 0 -10.0
d 1 20 0.0
e 0 0 0.0
f -1 0 -20.0
</code></pre>
| 3 | 2016-06-03T08:00:47Z | [
"python",
"pandas",
"dataframe",
"cumsum"
] |
Import config from sphinx subfolder | 37,608,030 | <p>I've created a sphinx project in a subfolder ("docs") inside my project root. When I run the make file autodoc it cannot find the config file and raises errors.</p>
<p>Is there a way to resolve this?</p>
<p><a href="https://www.syshell.net/extra_upload/37608030/project_structure.txt" rel="nofollow">project struct... | 0 | 2016-06-03T07:06:08Z | 37,618,211 | <p>I have to your folder structure diagram looks very messy. </p>
<p>Well, so from what I can see, there are two possible reasons.</p>
<h3>1. System PATH</h3>
<p>You didn't put the directory of <code>myreplicator.py</code> into the <code>sys.path</code> so that the <code>sphinx.autodoc.py</code> cannot locate your m... | 0 | 2016-06-03T15:27:16Z | [
"python",
"python-sphinx"
] |
Automatic instantiate in luigi? | 37,608,121 | <p>In <code>luigi.Task.run</code>, we need to serialize objects into files/database/etc.:</p>
<pre><code>MyTask(luigi.Task):
param = luigi.Parameter()
def requires(self):
AnotherTask(self.param)
def output(self):
luigi.LocalTarget('out_{}'.format(self.param))
def run(self):
with... | 0 | 2016-06-03T07:11:50Z | 37,633,134 | <p>Self answer: </p>
<pre><code>def getinstances(struct):
if isinstance(struct, luigi.Task):
return struct.instantiate()
elif isinstance(struct, dict):
return {k: getinstances(v) for k, v in six.iteritems(struct)}
else:
# Remaining case: assume r is iterable...
try:
... | 0 | 2016-06-04T17:32:57Z | [
"python",
"luigi"
] |
Is there a time complexity difference between these two methods of list traversal? | 37,608,160 | <p>Is there a difference in time complexity? Or are they the same? Im having trouble telling (python 3.5)</p>
<pre><code>list_of_dict = [{'name':'alan', 'age':5}, {'name':'alice', 'age':6}]
# first method
names = []
ages = []
for i in range(len(list_of_dict)):
names.append(list_of_dict[i]['name'])
ages.appen... | 3 | 2016-06-03T07:13:48Z | 37,608,244 | <p>In terms of asymptotic time complexity, they are the same.</p>
<p>Both methods require constant dictionary access (which is constant time on average), for each element in the list, so <code>O(n)</code> for both.</p>
<p>If you care about constants though, it will be hard to tell, and might vary between different in... | 5 | 2016-06-03T07:18:26Z | [
"python",
"algorithm",
"time-complexity"
] |
Is there a time complexity difference between these two methods of list traversal? | 37,608,160 | <p>Is there a difference in time complexity? Or are they the same? Im having trouble telling (python 3.5)</p>
<pre><code>list_of_dict = [{'name':'alan', 'age':5}, {'name':'alice', 'age':6}]
# first method
names = []
ages = []
for i in range(len(list_of_dict)):
names.append(list_of_dict[i]['name'])
ages.appen... | 3 | 2016-06-03T07:13:48Z | 37,608,292 | <p>beside theoretical complexity, you can time them if you want or use <code>ipython</code> to do it using <code>%timeit</code></p>
<p>first method: <code>10 loops, best of 3: 58.2 ms per loop</code></p>
<p>second method: <code>10 loops, best of 3: 56.3 ms per loop</code></p>
<p>they are quite close, to be checked w... | 2 | 2016-06-03T07:21:17Z | [
"python",
"algorithm",
"time-complexity"
] |
What is the difference between the following two statements? | 37,608,192 | <pre><code>x = func(*(xa,) + args)
y = func(*((xc,) + args))
</code></pre>
<p>where args is an array and function definition is:</p>
<pre><code>def func(lamb, data):
# statements
</code></pre>
<p>I learnt about <code>*args</code>, but I couldn't find the exact difference between these lines.</p>
| 2 | 2016-06-03T07:15:27Z | 37,608,421 | <p>The only difference is the extra set of brackets and one uses <code>xa</code> while the other uses <code>xc</code>, but even that doesn't make much of a difference <a href="https://docs.python.org/3/library/dis.html#dis.dis" rel="nofollow">to the byte code</a>, take a look:</p>
<pre><code># python 2 needs to use di... | 5 | 2016-06-03T07:27:39Z | [
"python"
] |
Read file created with C++ builder in python | 37,608,267 | <p>There is function creating file with data in C++ Builder:</p>
<pre><code>int HandleFile;
if (!FileExists(fnm))
{HandleFile = FileCreate(fnm);FileClose(HandleFile);}
HandleFile = FileOpen(fnm,fmOpenWrite);
if(! HandleFile) {return 0;}
AnsiString str = IntToStr(num)+"#" +IntToStr( GetLastError() )+": "+ AnsiLastErr... | 0 | 2016-06-03T07:19:43Z | 37,608,874 | <pre><code>FileWrite(HandleFile, &str, sizeof(str));
</code></pre>
<p>isn't correct.</p>
<p><a href="http://docwiki.embarcadero.com/Libraries/Berlin/en/System.SysUtils.FileWrite" rel="nofollow"><code>FileWrite</code></a> expects a pointer to a raw buffer and writes <code>x</code> bytes of the buffer to the file g... | 2 | 2016-06-03T07:51:07Z | [
"python",
"c++",
"file-io",
"c++builder",
"readfile"
] |
Python: AttributeError: 'module' object has no attribute 'WD_BREAK' | 37,608,315 | <p>Here is my code: </p>
<pre><code>import docx
doc = docx.Document()
doc.add_paragraph('This is on first page!')
doc.paragraphs[0].runs[0].add_break(docx.text.WD_BREAK.PAGE)
doc.add_paragraph('This is on the second page!')
doc.save('twoPage.docx')
</code></pre>
<p>The error is:</p>
<pre><code>AttributeError: 'modu... | 0 | 2016-06-03T07:22:04Z | 37,608,388 | <p><a href="http://python-docx.readthedocs.io/en/latest/api/text.html?highlight=WD_BREAK.PAGE#docx.text.run.Run.add_break" rel="nofollow">Breaks</a> are included in <code>docx.enum.text</code>. You should change</p>
<pre><code>docx.text.WD_BREAK.PAGE
</code></pre>
<p>to</p>
<pre><code>docx.enum.text.WD_BREAK.PAGE
</... | 0 | 2016-06-03T07:25:37Z | [
"python",
"docx",
"attributeerror"
] |
list comprehension fails but why? | 37,608,375 | <p>Who can explain to me why this list comprehension fails:</p>
<pre><code>provider1 = {'id': 1, 'name': 'Een'}
provider2 = {'id': 2, 'name': 'Twee'}
provider3 = {'id': 3, 'name': 'Drie'}
provider4 = {'id': 4, 'name': 'Vier'}
provider5 = {'id': 5, 'name': 'Vijf'}
provider6 = {'id': 6, 'name': 'Zes'}
provider7 = {'id':... | 1 | 2016-06-03T07:25:03Z | 37,608,432 | <p>That's because <code>next</code> function raises <code>StopIteration</code> when there's no next item. In particular this occures when the underlying iterator is empty which is your case for <code>id == 0</code>.</p>
| 3 | 2016-06-03T07:27:59Z | [
"python"
] |
list comprehension fails but why? | 37,608,375 | <p>Who can explain to me why this list comprehension fails:</p>
<pre><code>provider1 = {'id': 1, 'name': 'Een'}
provider2 = {'id': 2, 'name': 'Twee'}
provider3 = {'id': 3, 'name': 'Drie'}
provider4 = {'id': 4, 'name': 'Vier'}
provider5 = {'id': 5, 'name': 'Vijf'}
provider6 = {'id': 6, 'name': 'Zes'}
provider7 = {'id':... | 1 | 2016-06-03T07:25:03Z | 37,608,463 | <p>The dictionary does not have a value for key <code>0</code>. It finds value as <code>None</code> and it cannot determine the next value for iteration.
Replace your code with valid ranges, your code will work</p>
<pre><code>for x in range(1, 8):
print( testfunc(x))
</code></pre>
<p><strong>OR</strong> </p>
<p... | 2 | 2016-06-03T07:29:10Z | [
"python"
] |
list comprehension fails but why? | 37,608,375 | <p>Who can explain to me why this list comprehension fails:</p>
<pre><code>provider1 = {'id': 1, 'name': 'Een'}
provider2 = {'id': 2, 'name': 'Twee'}
provider3 = {'id': 3, 'name': 'Drie'}
provider4 = {'id': 4, 'name': 'Vier'}
provider5 = {'id': 5, 'name': 'Vijf'}
provider6 = {'id': 6, 'name': 'Zes'}
provider7 = {'id':... | 1 | 2016-06-03T07:25:03Z | 37,608,484 | <p>Yes, because your generator is empty. None of your data matches</p>
<pre><code>if int(provider['id']) == 0
</code></pre>
<p>Calling <code>next</code> on an empty generator throws the <code>StopIteration</code>.</p>
| 0 | 2016-06-03T07:30:02Z | [
"python"
] |
ERROR occur with write_once using python in raspberry PI | 37,608,642 | <pre><code>import os
import select
write_once(os.path.join('/sys/class/gpio', 'export'), '22')
# Pin to work with
pin_base = '/sys/class/gpio/gpio22/'
def write_once(path, value):
with open(path, 'w') as f:
f.write(value)
f = open(os.path.join(pin_base, 'value'), 'r')
write_once(os.path.join(pin_ba... | -2 | 2016-06-03T07:38:44Z | 37,608,712 | <p>You are trying to use the function <code>write_once</code> <em>before</em> declaring it. You must move the following line to the end of your script:</p>
<pre><code>write_once(os.path.join('/sys/class/gpio', 'export'), '22')
</code></pre>
| 1 | 2016-06-03T07:42:35Z | [
"python",
"python-2.7",
"raspberry-pi3"
] |
Installing Link Grammar Python binding on OSX: "Could not link test program to Python" | 37,608,643 | <p>I am trying to install the Link Grammar Python binding on OSX 10.10.3 Yosemite. I run the following command directly from the unpacked downloaded directory (link-grammar-5.3.7):</p>
<pre><code>./configure --enable-python-bindings
</code></pre>
<p>but I get this error: </p>
<pre><code> Could not link test program... | 0 | 2016-06-03T07:38:54Z | 37,908,921 | <p>In LDFLAGS, you have to use the location of the <strong>libpython</strong> library.
The location of the include files, if needed, can be specified with:</p>
<pre><code>CPPFLAGS="-I/path/of/include-directory"
</code></pre>
<p>You may find some hints about what to do next, in issue <a href="https://github.com/openco... | 0 | 2016-06-19T15:36:54Z | [
"python",
"osx",
"python-2.7",
"binding"
] |
Send mail and save message in file using Python | 37,608,735 | <p>I want to send email using Python and simultaneously want to write mail-message in a file as well.For sending mail I can do easily with smtplib but for saving part need your help.</p>
<p>My need is I am creating a webtool for my company where need to send a mail and have to send an update in every an hour so I have... | 0 | 2016-06-03T07:44:08Z | 37,608,896 | <p>Well, all you need to do is:</p>
<pre><code>file = open('myfile', 'w')
file.write(msg)
file.close()
</code></pre>
| 0 | 2016-06-03T07:51:55Z | [
"python",
"file",
"email",
"save",
"smtplib"
] |
Perform a screenshot upon an Exception | 37,608,768 | <p>Hey is there a way to capture a screenshot upon a an Exception, any Exception. My 'failed' solution which is placed in the <code>BaseTestCase</code>, <code>unittest.TestCase</code> subclass:</p>
<pre><code>class BaseTestCase(unittest.TestCase):
@classmethod
def setUpClass(cls):
"""some code"""
@property
def failu... | 2 | 2016-06-03T07:45:32Z | 37,609,045 | <p>It's better to save log from your exception into the file than taking a screenshot. For practice check this code:</p>
<pre><code>>>> s = [1, 2]
>>> try:
... s[3]
... except IndexError as e:
... print(e)
...
list index out of range
</code></pre>
<p>As you can see, it's possible to catch (and pri... | 0 | 2016-06-03T08:00:01Z | [
"python",
"selenium",
"testing"
] |
Perform a screenshot upon an Exception | 37,608,768 | <p>Hey is there a way to capture a screenshot upon a an Exception, any Exception. My 'failed' solution which is placed in the <code>BaseTestCase</code>, <code>unittest.TestCase</code> subclass:</p>
<pre><code>class BaseTestCase(unittest.TestCase):
@classmethod
def setUpClass(cls):
"""some code"""
@property
def failu... | 2 | 2016-06-03T07:45:32Z | 37,609,167 | <p>You're looking for a <a href="https://docs.python.org/3/tutorial/errors.html#handling-exceptions" rel="nofollow">try/except statement</a>:</p>
<pre><code>try:
# your code (which may raise an Exception) goes here
except:
# this code only runs if the code in the try block raised an exception
driver.save_s... | 0 | 2016-06-03T08:06:10Z | [
"python",
"selenium",
"testing"
] |
Perform a screenshot upon an Exception | 37,608,768 | <p>Hey is there a way to capture a screenshot upon a an Exception, any Exception. My 'failed' solution which is placed in the <code>BaseTestCase</code>, <code>unittest.TestCase</code> subclass:</p>
<pre><code>class BaseTestCase(unittest.TestCase):
@classmethod
def setUpClass(cls):
"""some code"""
@property
def failu... | 2 | 2016-06-03T07:45:32Z | 37,609,592 | <p>You can use decorators to catch if your test case functions raise an exception.</p>
<p>To do this you would first need to create a decorator function that returns the function that you want your test cases to be wrapped in like the example below.</p>
<pre><code>def screenshot(func):
def screenshot_exception(*a... | 1 | 2016-06-03T08:31:03Z | [
"python",
"selenium",
"testing"
] |
Perform a screenshot upon an Exception | 37,608,768 | <p>Hey is there a way to capture a screenshot upon a an Exception, any Exception. My 'failed' solution which is placed in the <code>BaseTestCase</code>, <code>unittest.TestCase</code> subclass:</p>
<pre><code>class BaseTestCase(unittest.TestCase):
@classmethod
def setUpClass(cls):
"""some code"""
@property
def failu... | 2 | 2016-06-03T07:45:32Z | 37,615,611 | <p>To take a screenshot when an error or failure occurs, check if there is an exception currently being handled in the <code>tearDown</code> method:</p>
<pre><code>import unittest, sys, exceptions
from selenium import webdriver
class TestCaseBase(unittest.TestCase):
def setUp(self):
self.driver = webdri... | 2 | 2016-06-03T13:23:50Z | [
"python",
"selenium",
"testing"
] |
Non blocking serial readline when using PyGame | 37,608,799 | <p>I'm working on a heart rate monitor written in PyGame using an Arduino as an input, the idea being that the game allows you to try and control your heart rate through relaxation exercises regardless of what's on screen.</p>
<p>I want to be able to run things like video/mouse/keybord button capture etc. in the game ... | 0 | 2016-06-03T07:47:03Z | 37,663,065 | <p>I know very little about Python but I would test to see if there are any characters waiting to be read and just read that number instead of using readline. I think you want to use in_waiting and read(<em>size</em>).</p>
<p>Readline will block until a carriage return is received.</p>
<p>So, I think something like:<... | 0 | 2016-06-06T17:02:48Z | [
"python",
"linux",
"arduino",
"pygame",
"pyserial"
] |
Non blocking serial readline when using PyGame | 37,608,799 | <p>I'm working on a heart rate monitor written in PyGame using an Arduino as an input, the idea being that the game allows you to try and control your heart rate through relaxation exercises regardless of what's on screen.</p>
<p>I want to be able to run things like video/mouse/keybord button capture etc. in the game ... | 0 | 2016-06-03T07:47:03Z | 37,665,593 | <p>I fixed it! :)</p>
<pre><code>#!/usr/bin/env python
import pygame
from threading import Thread
import serial
import json
from pygame.color import Color
from pygame.locals import *
CURHR = 0
ser = serial.Serial('/dev/pts/3', 9600, timeout=0)
def worker():
global CURHR
while True:
msg = ser.readline()
... | 0 | 2016-06-06T19:41:02Z | [
"python",
"linux",
"arduino",
"pygame",
"pyserial"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.