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 |
|---|---|---|---|---|---|---|---|---|---|
List of integers in dictionary python | 38,939,356 | <p>i am learning python currently with the Python Crash Course text. I am at the part about having lists in dictionaries specifically the try it yourself. The text explains how to access values that are in list form in python when they are strings but not integers. I have gotten my code to work so far but it prints the... | 0 | 2016-08-14T05:11:40Z | 38,939,380 | <p>This will fix your current code:</p>
<pre><code>for numbers in number:
print(numbers)
</code></pre>
<p>But it's kind of a backward way to name the variables. How about this instead?</p>
<pre><code>for name, numbers in favorite_numbers.items():
print(
"Hey, "
+ name.title() +
" your favorite ... | 1 | 2016-08-14T05:16:42Z | [
"python",
"list",
"dictionary"
] |
List of integers in dictionary python | 38,939,356 | <p>i am learning python currently with the Python Crash Course text. I am at the part about having lists in dictionaries specifically the try it yourself. The text explains how to access values that are in list form in python when they are strings but not integers. I have gotten my code to work so far but it prints the... | 0 | 2016-08-14T05:11:40Z | 38,939,385 | <p>You are confused because you have similarly-named variables. In your case, this line:</p>
<pre><code>for name, number in favorite_numbers.items():
</code></pre>
<p>binds <code>number</code> to successive values in the dictionary. In this example, they are specifically lists containing strings.</p>
<p>This line:</... | 0 | 2016-08-14T05:17:28Z | [
"python",
"list",
"dictionary"
] |
List of integers in dictionary python | 38,939,356 | <p>i am learning python currently with the Python Crash Course text. I am at the part about having lists in dictionaries specifically the try it yourself. The text explains how to access values that are in list form in python when they are strings but not integers. I have gotten my code to work so far but it prints the... | 0 | 2016-08-14T05:11:40Z | 38,939,407 | <p>I think your naming confused you a little. Look at your use of <code>number</code> and <code>numbers</code>. Fixed version below. Also check out `print( "foo", end = "" ) to have multiple print statements that don't terminate in a new line, if you want to clean up the appearance of the output a little.</p>
<pre>... | 2 | 2016-08-14T05:21:31Z | [
"python",
"list",
"dictionary"
] |
Python+kivy+SQLite: How to use them together | 38,939,416 | <p>I am new to python, kivy and sqlite. But I have to do this difficult task. :-( Any kind of help will be highly appreciated. Thanks in advance! </p>
<p>The task is: to display the data from a <code>.db</code> file on the <code>kivy</code> screen on android. </p>
<p>I made the database file from <a href="http://zetc... | 0 | 2016-08-14T05:23:41Z | 38,943,364 | <p>The easiest way would be writing a custom <code>init</code> method for the box layout:</p>
<pre><code>from kivy.uix.boxlayout import BoxLayout
from kivy.clock import mainthread
class MyBoxLayout(BoxLayout):
def init(self, **kwargs):
super().__init__(**kwargs)
@mainthread # execute within nex... | 1 | 2016-08-14T14:50:12Z | [
"python",
"sqlite",
"kivy"
] |
Parsing all the text inside a tag using lxml in python | 38,939,418 | <p>I am trying to parse an HTML file which kind of is as shown below</p>
<pre><code><ol>
<li>
<div class="c1">
<span class="s1">hi</span>
" hello "
<span class="s2">world!</span>
</div>
</li>
<li>
<div class="c2">
... | 0 | 2016-08-14T05:23:57Z | 38,939,595 | <pre><code>$ cat a.py
from lxml import etree
xml = """<ol>
<li>
<div class="c1">
<span class="s1">hi</span>
" hello "
<span class="s2">world!</span>
</div>
</li>
<li>
<div class="c2">
<span class="s3">abc&... | 1 | 2016-08-14T05:56:44Z | [
"python",
"html",
"parsing",
"lxml"
] |
Parsing all the text inside a tag using lxml in python | 38,939,418 | <p>I am trying to parse an HTML file which kind of is as shown below</p>
<pre><code><ol>
<li>
<div class="c1">
<span class="s1">hi</span>
" hello "
<span class="s2">world!</span>
</div>
</li>
<li>
<div class="c2">
... | 0 | 2016-08-14T05:23:57Z | 38,941,322 | <p>You can get each li and use <a href="https://msdn.microsoft.com/en-us/library/ms256063(v=vs.110).aspx" rel="nofollow">normalize-space</a>:</p>
<pre><code>from lxml import html
h = """<ol>
<li>
<div class="c1">
<span class="s1">hi</span>
" hello "
<span class=... | 1 | 2016-08-14T10:28:07Z | [
"python",
"html",
"parsing",
"lxml"
] |
Trying to replicate Python's struct.unpack ">L" in JavaScript with TypedArrays | 38,939,519 | <p>I am trying to reproduce the following Python code in JavaScript.</p>
<pre><code>import struct
val = struct.unpack(">L", "MACS")[0]
</code></pre>
<p><code>val</code> is now <code>1296122707</code> (the same as <code>0x4d414353</code>). Trying the same with <code>htk1</code> gives <code>1752460081</code>, the sa... | 0 | 2016-08-14T05:44:13Z | 38,939,620 | <p>Here's a function that does this (returning undefined if the string is the wrong length):</p>
<pre><code>function stringToUnsignedInt(string) {
if (string.length !== 4) {
return undefined;
}
return (string.charCodeAt(0) << 24) +
(string.charCodeAt(1) << 16) +
(string.charCod... | 2 | 2016-08-14T06:02:14Z | [
"javascript",
"python"
] |
Convert string from Latin-1 to UTF-8 and back to Latin-1 | 38,939,565 | <p>A system (not under my control) sends a <code>latin-1</code> encoded string (such as Ãland) which I can convert to <code>utf-8</code> but not back to <code>latin-1</code>. </p>
<p>Consider this code:</p>
<pre><code>text = '\xc3\x96land' # This is what the external system sends
iso = text.encode(encoding='latin-1'... | -2 | 2016-08-14T05:52:37Z | 38,939,655 | <p>if your external system sends it to you then you should first decode it rather than encoding it since it is sent as encoded.</p>
<p>you don't have to encode the encoded!!</p>
<p><code>hey=u"Ãland".encode('latin-1')
print hey
</code></p>
<p>gives output like this <code>?land</code></p>
<p><code>print hey.decode(... | 0 | 2016-08-14T06:07:38Z | [
"python"
] |
Convert string from Latin-1 to UTF-8 and back to Latin-1 | 38,939,565 | <p>A system (not under my control) sends a <code>latin-1</code> encoded string (such as Ãland) which I can convert to <code>utf-8</code> but not back to <code>latin-1</code>. </p>
<p>Consider this code:</p>
<pre><code>text = '\xc3\x96land' # This is what the external system sends
iso = text.encode(encoding='latin-1'... | -2 | 2016-08-14T05:52:37Z | 38,940,040 | <p>Turns out the external system send the data in utf-8 already.
Converting the string forth and back works like this now: </p>
<pre><code>#!/usr/bin/env python3.4
# -*- coding: utf-8 -*-
text = '\xc3\x96land'
encoded = text.encode(encoding='raw_unicode_escape')
print(encoded)
utf8 = encoded.decode('utf-8')
print(utf... | 0 | 2016-08-14T07:20:33Z | [
"python"
] |
Calculate and store the total score for each student and calculate the average score for the whole class. | 38,939,586 | <p>This is what I have done so far. Need help in finding the total score and average score. </p>
<pre><code>name = ''
results = []
result = 0
question =1
while question <= 30:
name = input("Enter student number "+str(question)+"'s name\n")
result = input("Enter student number " + str(question) + "'s resul... | -1 | 2016-08-14T05:55:47Z | 38,939,631 | <p>(I'm assuming you are using Python 3)</p>
<p>You have a few issues.</p>
<pre><code>result = int(result) #takes the var and makes it into int
typeChecker = type(result) #checks the var type
while typeChecker != int:
.
.
</code></pre>
<p>This <code>while</code> is useless. The type of <code>result</code>... | 1 | 2016-08-14T06:03:20Z | [
"python"
] |
change key in python dict and print only the key value with value | 38,939,598 | <p>I am trying to manipulate a dict as:</p>
<pre><code>op = {'File:Directory': '/var/tmp/Mkbib/Trial2', 'PDF:Title': 'Antiferromagnetic-ferromagnetic transition in FeRh', 'PDF:Author': 'V. L. Moruzzi and P. M. Marcus', 'File:FileSize': '636 kB', 'File:FileInodeChangeDate': '2016:08:13 19:45:15+02:00'}
fields = ["auth... | 1 | 2016-08-14T05:57:50Z | 38,939,677 | <p>You can use dictionary comprehension here.</p>
<pre><code>op = {
'File:Directory': '/var/tmp/Mkbib/Trial2',
'PDF:Title': 'Antiferromagnetic-ferromagnetic transition in FeRh',
'PDF:Author': 'V. L. Moruzzi and P. M. Marcus',
'File:FileSize': '636 kB',
'File:FileInodeChangeDate': '2016:08:13 19:45:... | 3 | 2016-08-14T06:11:53Z | [
"python",
"python-3.x",
"dictionary"
] |
What is the simplest python code to plot a simple graph (simpler than matlab) | 38,939,691 | <p>If I want to draw a y=x^2 graph from 0 to 9 in matlab, I can do </p>
<pre><code>a = [0:1:10]
b = a.^2
plot(a,b)
</code></pre>
<p>Using python, I can do the same like below </p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
a=[x for x in xrange(10)]
b=np.square(a)
plt.plot(a,b)
plt.show()
</code><... | -4 | 2016-08-14T06:15:30Z | 38,939,734 | <p>This is a bit simpler</p>
<pre><code>import matplotlib.pyplot as plt
X = range(10)
plt.plot(X, [x*x for x in X])
plt.show()
</code></pre>
<p>but remember that Python is a general purpose language, so it's not surprising it requires a bit more than a specific charting/math tool.</p>
<p>The main clutter is however... | 0 | 2016-08-14T06:24:40Z | [
"python",
"matlab",
"matplotlib",
"plot"
] |
Can someone explain how this leetcode solution works with negative numbers? | 38,939,781 | <p>This is a solution for <a href="https://leetcode.com/problems/sum-of-two-integers/" rel="nofollow">leetcode problem 371</a>,<code>Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.</code></p>
<p>Why we need <code>MOD</code> and <code>MAX_INT</code> and what is this part ... | 1 | 2016-08-14T06:33:53Z | 38,940,568 | <p>The reason for <code>MOD</code>, <code>MAX_INT</code> and <code>~(a & MAX_INT) ^ MAX_INT</code> is to simulate 32-bit integers. This is needed because in Python integers are not bounded.</p>
<p>After doing a calculation, <code>& MOD</code> is used to only keep the 32-bit least significant bits of the result... | 1 | 2016-08-14T08:45:13Z | [
"python",
"bit-manipulation"
] |
Can someone explain how this leetcode solution works with negative numbers? | 38,939,781 | <p>This is a solution for <a href="https://leetcode.com/problems/sum-of-two-integers/" rel="nofollow">leetcode problem 371</a>,<code>Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.</code></p>
<p>Why we need <code>MOD</code> and <code>MAX_INT</code> and what is this part ... | 1 | 2016-08-14T06:33:53Z | 38,941,567 | <p>I'm not surprised you're having a hard time trying to understand that code, definitely it works alright but I'd recommend you to start from scratch. First be sure you master bit operators, <a href="https://en.wikipedia.org/wiki/Signed_number_representations" rel="nofollow">integer representation</a> of numbers and <... | -1 | 2016-08-14T11:03:43Z | [
"python",
"bit-manipulation"
] |
Regex Search in Multiple PyMongo Document Fields | 38,939,836 | <h2>The Goal</h2>
<p>Search the corpus of Enron emails to find emails to and from Ken Lay, securities fraudster extraordinaire.</p>
<h2>The Data</h2>
<p>One such email document, of 500k+ emails named <code>workdocs</code>, are structured like below:</p>
<p>One such document:</p>
<pre><code> {'headers': {'To': 'eri... | 0 | 2016-08-14T06:42:55Z | 38,944,459 | <p>To only search those four fields, you can use:</p>
<pre><code>(?:to|from|x-b?cc)'\s*:\s*'K[A-Z0-9._%+-]*Lay@[A-Z0-9._%+-]+\.[A-Z]{2,4}
</code></pre>
<p>That version removes the capture group around his first name, which is unnecessary for the match to happen. (It would be faster to extract after the regex is finis... | 1 | 2016-08-14T16:55:00Z | [
"python",
"regex",
"mongodb",
"pymongo"
] |
KeyError: 'PYTHONPATH', how can I fix PYTHONPATH? (Python 3.5.2) | 38,939,936 | <p>I have seen this post asked before in stackoverflow but it was 4 years ago (<a href="http://stackoverflow.com/questions/9320305/how-to-fix-the-python-path">How to fix the python path</a>) so I am not sure wether this is the right solution because I am using a newer version of python (3.5.2). This is what I see in a ... | 0 | 2016-08-14T06:59:59Z | 38,939,957 | <p>There is no PYTHONPATH variable in your OS Environemental variables. Hence the error.</p>
<p>It is not created by Python installation (atleast in windows). You have to create one variable.</p>
<p>To check if there is one such environmental variable, type below command:</p>
<pre><code>SET PYTHONPATH
</code></pre>
... | 0 | 2016-08-14T07:04:36Z | [
"python",
"python-3.x"
] |
KeyError: 'PYTHONPATH', how can I fix PYTHONPATH? (Python 3.5.2) | 38,939,936 | <p>I have seen this post asked before in stackoverflow but it was 4 years ago (<a href="http://stackoverflow.com/questions/9320305/how-to-fix-the-python-path">How to fix the python path</a>) so I am not sure wether this is the right solution because I am using a newer version of python (3.5.2). This is what I see in a ... | 0 | 2016-08-14T06:59:59Z | 38,939,975 | <p>You may want to check <a href="https://docs.python.org/3.5/library/sys.html?highlight=sys#sys.path" rel="nofollow">sys.path</a> </p>
<blockquote>
<p>A list of strings that specifies the search path for modules. Initialized from the environment variable <strong>PYTHONPATH</strong>, plus an installation-dependent d... | 0 | 2016-08-14T07:07:53Z | [
"python",
"python-3.x"
] |
"if not item in list" not functioning properly in Python? | 38,940,026 | <p>I have a simple program that checks the user's 'passcode' that either allows them access or denies them access.</p>
<p>If the user types in the correct passcode, the print statement "Login successful! Passcode used:", passcode" is printed, however, if the passcode is wrong, it simply asks for their passcode again <... | 0 | 2016-08-14T07:18:09Z | 38,940,054 | <p>You're over complicating things. Instead of iterating over the list yourself, you could just check if the <code>passcode</code> is there:</p>
<pre><code>LoginCorrect = False
lst = ['1234', '2345', '3456', '4567', '5678', '6789']
while LoginCorrect:
passcode = input("Please enter your passcode: ")
if passcod... | 4 | 2016-08-14T07:23:13Z | [
"python",
"python-3.x"
] |
"if not item in list" not functioning properly in Python? | 38,940,026 | <p>I have a simple program that checks the user's 'passcode' that either allows them access or denies them access.</p>
<p>If the user types in the correct passcode, the print statement "Login successful! Passcode used:", passcode" is printed, however, if the passcode is wrong, it simply asks for their passcode again <... | 0 | 2016-08-14T07:18:09Z | 38,940,110 | <p>I hope that this is just an excersise and not a production code to perform login, because it is <strong>super not secured</strong>.</p>
<p>Here is a working version of your snippet:</p>
<pre><code>lst = ['1234', '2345', '3456', '4567', '5678', '6789']
LoginCorrect = False
while not LoginCorrect:
passcode = inp... | 0 | 2016-08-14T07:31:45Z | [
"python",
"python-3.x"
] |
"if not item in list" not functioning properly in Python? | 38,940,026 | <p>I have a simple program that checks the user's 'passcode' that either allows them access or denies them access.</p>
<p>If the user types in the correct passcode, the print statement "Login successful! Passcode used:", passcode" is printed, however, if the passcode is wrong, it simply asks for their passcode again <... | 0 | 2016-08-14T07:18:09Z | 38,940,201 | <p>To answer your specific question: <code>not item in lst</code> works fine, but
<code>not item in lst == False</code> is evaluated differently than you probably expect.
Python converts chains of logical tests like <code>(a == b == c)</code> or <code>(a in b in c)</code>
to <code>(a == b) and (b == c)</code> or <code... | 1 | 2016-08-14T07:46:00Z | [
"python",
"python-3.x"
] |
"if not item in list" not functioning properly in Python? | 38,940,026 | <p>I have a simple program that checks the user's 'passcode' that either allows them access or denies them access.</p>
<p>If the user types in the correct passcode, the print statement "Login successful! Passcode used:", passcode" is printed, however, if the passcode is wrong, it simply asks for their passcode again <... | 0 | 2016-08-14T07:18:09Z | 38,940,574 | <p>How about a <code>while</code> statement with <code>continue</code> and <code>break</code>?</p>
<pre><code>lst = ['1234', '2345', '3456', '4567', '5678', '6789']
while True:
passcode = input('Please enter your passcode: ')
if passcode not in lst:
continue
else:
print("Login successful! P... | 0 | 2016-08-14T08:45:43Z | [
"python",
"python-3.x"
] |
"if not item in list" not functioning properly in Python? | 38,940,026 | <p>I have a simple program that checks the user's 'passcode' that either allows them access or denies them access.</p>
<p>If the user types in the correct passcode, the print statement "Login successful! Passcode used:", passcode" is printed, however, if the passcode is wrong, it simply asks for their passcode again <... | 0 | 2016-08-14T07:18:09Z | 38,940,664 | <p>The logic of your code is somewhat unclear. I <em>think</em> you meant to do something like this:</p>
<pre><code>LoginCorrect = 0
lst = ['1234', '2345', '3456', '4567', '5678', '6789']
while LoginCorrect == 0:
passcode = input("Please enter your passcode: ")
for item in lst:
if item == passcode:
... | 1 | 2016-08-14T09:00:25Z | [
"python",
"python-3.x"
] |
Selenium in Python using Chrome, How to select element for clicking of Personal Info. options and then click on Personal Details | 38,940,084 | <p>There is drop menu in a frame, in code it starts with <code><div tag id=masterdiv, div class=submenu and onclick="SwitchMenu('sub1')"></code>,
I have to click first on <code>Personal Info</code>., and then select <code>Personal Details</code>
I tried </p>
<pre><code>driver.find_element_by_xpath("//a[contains(... | 0 | 2016-08-14T07:28:18Z | 39,044,004 | <p>Actually your provided locator looks incorrect that's why are unable to find element, you should try using <code>WebDriverWait</code> to wait until element present as below :-</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support impor... | 0 | 2016-08-19T16:40:12Z | [
"python",
"google-chrome",
"selenium-webdriver"
] |
User Permissions from django admin | 38,940,101 | <p>I have the model Profile related with model User by OneToOne:</p>
<pre><code>class Profile(models.Model):
user = models.OneToOneField(User)
...
</code></pre>
<p>Also i have the model Books related with model Profile by ForeignKey:</p>
<pre><code>class Books(models.Model):
profile = models.ForeignKey(Profi... | 0 | 2016-08-14T07:30:14Z | 38,982,795 | <p>Just create a new admin user</p>
<pre><code>python manage.py createsuperuser
</code></pre>
<p>then go into django admin and:</p>
<ul>
<li>deselect super user</li>
<li>desleect all permissions you don't want to give them</li>
</ul>
<p>then save the admin user</p>
| 0 | 2016-08-16T19:15:28Z | [
"python",
"django",
"django-models",
"django-admin",
"django-admin-filters"
] |
AWS Lambda support for python 3.4 and cronjobs | 38,940,140 | <p>I´ve created a set up using python 3.4 code (as I need the library pyrebase) as well as using Cronjobs. </p>
<p>AWS Lambda would do the job perfect if it wasn´t for the lack of Python 3-support. </p>
<p>Any ideas of other AWS computer services supporting Python and Cronjobs? (or other cloud computing services th... | 0 | 2016-08-14T07:36:52Z | 38,983,206 | <p>The environment that Lambda runs your scripts in has Python 3 available to it, so it is possible to run Python 3 code via Lambda, but it takes a bit of work (I've not done it myself). Here's a similar question: <a href="http://stackoverflow.com/questions/36143563/using-python-3-with-aws-lamba">using Python 3 with A... | 1 | 2016-08-16T19:43:14Z | [
"python",
"amazon-web-services",
"cron",
"aws-lambda"
] |
How do I create dataframes from the groups that have been arranged by groupby? | 38,940,209 | <p>I have separated my data set by months, there are a total of 8 groups for 8 different months, I want to create two separate dataframes which one will include the data that is found on months:5,6,7,8 and the other dataframe will include the months:4,9,10,11. How can I tell groupby to create these two separate dataset... | 1 | 2016-08-14T07:47:25Z | 38,940,384 | <p>Try:</p>
<pre><code>df1 = df[df.month.isin([5, 6, 7, 8])]
df2 = df[df.month.isin([4, 9, 10, 11])]
</code></pre>
| 1 | 2016-08-14T08:13:00Z | [
"python",
"datetime",
"pandas",
"group-by"
] |
How can I detect collision between two objects only once in pygame? | 38,940,220 | <p>In my game, I have a population of fish (10). Each fish has a line of sight (an arc object in front of them). There are sharks, which are predators (they are moving around the room randomly). Each fish is assigned an intelligence number at the beginning. When a shark enters in a fish' line of sight, I want the fish ... | 0 | 2016-08-14T07:49:22Z | 38,940,418 | <p>You can store the last shark that the fish "saw" and compare that in each iteration of the update loop.</p>
<ul>
<li>If the fish sees the same shark again, don't recalculate.</li>
<li>If the fish sees another shark, recalculate and remember that shark.</li>
<li>If it sees no sharks, reset its "memory".</li>
</ul>
... | 2 | 2016-08-14T08:18:46Z | [
"python",
"pygame",
"sprite",
"collision",
"detection"
] |
How can I detect collision between two objects only once in pygame? | 38,940,220 | <p>In my game, I have a population of fish (10). Each fish has a line of sight (an arc object in front of them). There are sharks, which are predators (they are moving around the room randomly). Each fish is assigned an intelligence number at the beginning. When a shark enters in a fish' line of sight, I want the fish ... | 0 | 2016-08-14T07:49:22Z | 38,941,172 | <p>You need to track when the shark was seen, or which shark was seen. Basically update the collision detector one tenth (or 12th or 100th) as often as you update position.</p>
<p>Or, once a fish fails to see a shark, it's doomed, so you can add that list to a list of sharks it's seen and failed to avoid (in case it... | 1 | 2016-08-14T10:09:19Z | [
"python",
"pygame",
"sprite",
"collision",
"detection"
] |
how to scrapy from a table with multi td nested tags | 38,940,281 | <p>I have scrapy the data from this page (<a href="http://www.itjuzi.com/company/934" rel="nofollow">http://www.itjuzi.com/company/934</a>), but what I want to get is a list with children td tags,and a list with parent td tags.</p>
<p>the code is below:</p>
<pre><code>response.xpath("//table[@class='list-round-v2']//... | 0 | 2016-08-14T07:57:27Z | 38,942,195 | <p>This will do the job</p>
<pre><code>textlist=[]
for row in response.xpath("//table[contains(@class,'list-round-v2')]//tr"):
textlist.append(row.xpath("td[4]//text()[parent::a|parent::span]").extract())
</code></pre>
| 1 | 2016-08-14T12:19:55Z | [
"python",
"xpath",
"scrapy"
] |
Python how to output characters as raw text | 38,940,331 | <p>Whenever I try to get the unicode number from a string that has "\xff" in it I get an error.</p>
<pre><code>test = ord(str(tmp1))
TypeError: ord() expected a character, but string of length 4 found
</code></pre>
<p>How can I avoid this?</p>
<p>Edit - The output of <code>print(repr(tmp1))</code> is <code>'\\xff'</... | 0 | 2016-08-14T08:04:45Z | 38,940,455 | <p>you have to encode your text</p>
<pre><code>test = ord(tmp1.encode('utf-16'))
</code></pre>
<p>this way you can avoid this error.</p>
| 0 | 2016-08-14T08:25:33Z | [
"python",
"python-3.x"
] |
How do I use multiple images with the same sprite on pygame? | 38,940,383 | <p>Im learning how to use pygame and I'm trying to use multiple images with the same sprite. I want the sprites image to change when i press a button on my keyboard. Whenever i press the right arrow key and attempt to change the sprites image I get the error: </p>
<pre><code>Traceback (most recent call last):
File "... | 0 | 2016-08-14T08:12:36Z | 38,943,807 | <p>Don't forget the parentheses after <code>self.rect=self.image.get_rect</code> in your <code>look</code> method. Without parenthesis <code>self.rect</code> is assigned to the function instead of the returned rectangle. Since this rectangle is used to draw the image it will cause this position error.</p>
| 0 | 2016-08-14T15:40:40Z | [
"python",
"pygame",
"sprite"
] |
Processing a list whilst using threading | 38,940,385 | <p>My code has a loop which checks a list and if there are items in the list it will process them and remove them from the list. The items are continuously inserted into the list by another thread.</p>
<p>Here is the code: </p>
<pre><code>while True:
for item in list:
Process(item)
Remove(item)
</... | 0 | 2016-08-14T08:13:00Z | 38,940,450 | <p>It seems that the <a href="https://docs.python.org/3.5/library/queue.html?highlight=queue#module-queue" rel="nofollow">queue</a> module will be useful for you. It implements multi-producer, multi-consumer queues and allows synchronize between threads without busy waiting.</p>
<p>see also <a href="http://www.napuzba... | 1 | 2016-08-14T08:24:42Z | [
"python",
"multithreading",
"loops",
"signals",
"cpu"
] |
tkMessageBox Crashes Python Application Upon Running (Resolved) | 38,940,423 | <p>Here is the code</p>
<pre><code>import Tkinter
import tkMessageBox
def created():
tkMessageBox.showinfo('File Created!', 'Letter.html Created on Desktop')
class simpleapp_tk(Tkinter.Tk):
def __init__(self,parent):
Tkinter.Tk.__init__(self,parent)
self.parent = parent
self.initializ... | 0 | 2016-08-14T08:19:21Z | 38,941,330 | <p>py2exe is windows version of py2app.</p>
<p>first of all to build we need a setup file like this:</p>
<p><strong>[setup.py]</strong></p>
<pre><code>from distutils.core import setup
import py2exe #in your case import py2app
setup(console=['myFile.py'])
</code></pre>
<p>on running this file us... | 0 | 2016-08-14T10:29:04Z | [
"python",
"osx",
"python-2.7",
"tkinter",
"tkmessagebox"
] |
Killing child processes, and getting child processes pid without psutil or subprocess | 38,940,429 | <p>I'm encountering a lot of problems with this, I want to kill all my child processes without destroying my own process OR kill all the processes of some group OR get all the child processes PID... and all of this WITHOUT using either <code>subprocess</code> or <code>psutil</code> library in python anyone has any idea... | 0 | 2016-08-14T08:20:43Z | 38,940,705 | <p>If you really cannot access those libraries, you can use <code>os</code> if push comes to shove.<br>
For example:</p>
<pre><code>my_pid = os.popen('ps --no-headers -C name_of_process').read(5)
if my_pid != "":
my_pid = int(my_pid)
os.kill(my_pid, signal.SIGTERM)
</code></pre>
<p>'name_of_process' would be ... | 0 | 2016-08-14T09:05:36Z | [
"python",
"linux",
"process",
"pid"
] |
Filter ForeignKey in django admin panel | 38,940,438 | <p>I'll start from showing how my model look:</p>
<pre><code>from django.db import models
class Project(models.Model):
#.....
pu = models.ForeignKey('Person', default='', related_name='pu')
se = models.ForeignKey('Person', default='', related_name='se')
class Person(models.Model):
first_name = models... | 0 | 2016-08-14T08:22:40Z | 38,982,948 | <p>django admin work arounds are usually possible, with a bit of hacking.</p>
<p>Try creating a myapp/admin.py file</p>
<pre><code>from django.contrib import admin
from .models import Project, Person
class ProjectAdmin(admin.ModelAdmin):
...
filter_horizontal = ('pu', 'se')
def get_form(self, request, ... | 0 | 2016-08-16T19:25:41Z | [
"python",
"django"
] |
Filter ForeignKey in django admin panel | 38,940,438 | <p>I'll start from showing how my model look:</p>
<pre><code>from django.db import models
class Project(models.Model):
#.....
pu = models.ForeignKey('Person', default='', related_name='pu')
se = models.ForeignKey('Person', default='', related_name='se')
class Person(models.Model):
first_name = models... | 0 | 2016-08-14T08:22:40Z | 39,062,517 | <p>I've changed my model.
I won't use Person and Department, I've switched to django's User and Group.</p>
<p>To filter it as I needed i used <code>limit_choices_to</code>.</p>
<pre><code>pu = models.ForeignKey("auth.User", related_name='pu', limit_choices_to={'groups__name': "Purchasing"})
se = models.ForeignKey("au... | 0 | 2016-08-21T08:56:03Z | [
"python",
"django"
] |
TemplateSyntaxError in Django at /admin/login (default requires 2 arguments, 1 provided) | 38,940,457 | <p>I looked thoroughly into my files and I could not find one error. Staring and reading my files for 45 minutes was a pain. I now need someone's help, I can't do this</p>
<p>this is the path of the app: </p>
<pre><code>website
music
project1 #this is the main folder that includes settings... | -1 | 2016-08-14T08:25:44Z | 38,941,084 | <p>Your login template has a syntax error as you did not escape the apostrophe (<code>'</code>) in your string literal. Change the following</p>
<pre><code>{{ site_header|default:('Kweli's webby') }}
</code></pre>
<p>to</p>
<pre><code>{{ site_header|default:_("Kweli's webby") }}
</code></pre>
<p>Also note the under... | 1 | 2016-08-14T09:56:20Z | [
"python",
"django",
"get",
"admin"
] |
Add our own mapping of magic methods | 38,940,497 | <p>Recently I was reading about magic methods in Python, which make the code a lot easier to read. Can we define our own mappings? If so, is there any pointer for this and how complicated it would be?</p>
<p>For example, <code>+</code> is always mapped to <code>__add__</code>. Could I define a mapping for <code>?</cod... | 0 | 2016-08-14T08:32:22Z | 38,940,516 | <p>You seem to be asking if you can create your own syntax in Python, adding new symbols that are implemented via magic methods. The answer is no. The only operators available are the ones that already exist (<code>+</code>, <code>*</code>, etc.), and each has its corresponding magic methods. You can't add new ones.... | 0 | 2016-08-14T08:34:13Z | [
"python",
"magic-methods"
] |
Converting a list of datetime objects to a list of number of days since a certain date | 38,940,665 | <p>I have a large list of dates that are datetime objects like for example</p>
<pre><code>[datetime.datetime(2016,8,14),datetime.datetime(2016,8,13),datetime.datetime(2016,8,12),....etc.]
</code></pre>
<p>Instead of datetime objects of the date what I want instead is a list of numerical integer values since the date ... | 2 | 2016-08-14T09:00:35Z | 38,940,696 | <p><code>timedelta</code> objects have <code>days</code> attribute, so you can simply append that as an <code>int</code>:</p>
<pre><code>numericalDates.append(a.days)
</code></pre>
<p>will result with <code>numericalDates</code> being <code>[42594, 42593, 42592]</code>.</p>
<p>Note that you can also simplify your co... | 3 | 2016-08-14T09:04:28Z | [
"python",
"datetime",
"python-datetime"
] |
How can I get column name and type from an existing table in SQLAlchemy? | 38,940,682 | <p>Suppose I have the table <code>users</code> and I want to know what the column names are and what the types are for each column.</p>
<p>I connect like this; </p>
<pre><code>connectstring = ('mssql+pyodbc:///?odbc_connect=DRIVER%3D%7BSQL'
'+Server%7D%3B+server%3D.....')
engine = sqlalchemy.cre... | 0 | 2016-08-14T09:02:48Z | 38,940,923 | <p>You could call the column names from the Information Schema:</p>
<p>SELECT *
FROM information_schema.columns
WHERE TABLE_NAME = 'users'</p>
<p>Then sort the result as an array, and loop through them.</p>
| 0 | 2016-08-14T09:35:26Z | [
"python",
"sql",
"sql-server-2008",
"orm",
"sqlalchemy"
] |
How can I get column name and type from an existing table in SQLAlchemy? | 38,940,682 | <p>Suppose I have the table <code>users</code> and I want to know what the column names are and what the types are for each column.</p>
<p>I connect like this; </p>
<pre><code>connectstring = ('mssql+pyodbc:///?odbc_connect=DRIVER%3D%7BSQL'
'+Server%7D%3B+server%3D.....')
engine = sqlalchemy.cre... | 0 | 2016-08-14T09:02:48Z | 38,940,927 | <p>columns have <code>name</code> and <code>type</code> attributes</p>
<pre><code>for c in columns:
print c.name, c.type
</code></pre>
| 0 | 2016-08-14T09:35:56Z | [
"python",
"sql",
"sql-server-2008",
"orm",
"sqlalchemy"
] |
Some questions about switches in python | 38,940,826 | <p>This is my first Question here at StackOverflow, so please be patient with me if some info isn't present or I missed something important, but anyways i'll do my best :)</p>
<p>Recently I started to code in Python2.7, so I'm not very good at it. While playing with PyGtk, PyGObject, Glade, etc I found something parti... | 2 | 2016-08-14T09:22:56Z | 39,694,877 | <p>You want to hook up the switch like this:</p>
<p><code>switchie.connect("""activate""", Hi)</code></p>
<p>This will only get called <strong>once</strong> for every time it is clicked. What you were doing is hooking up to the signal after it changed, so it was constantly changing, and never catching up. You will al... | 0 | 2016-09-26T04:45:08Z | [
"python",
"python-2.7",
"pygtk",
"glade",
"pygobject"
] |
How to acquire video feed in python using a wireless webcam setup on my android device? | 38,940,874 | <p>Alright, so my basic aim is to do some video processing. But I want to do so in real time using the feed from a camera. I've downloaded this app on my android phone called <a href="https://play.google.com/store/apps/details?id=com.pas.webcam&hl=en" rel="nofollow">IP webcam</a>. Using this app I can create a wire... | 0 | 2016-08-14T09:29:20Z | 38,978,973 | <p>Without an error code, or some other debugging information, there is too little information to give a definitive answer, but here is something that worked for me when I had a similar problem.</p>
<p>I am using an AXIS IP webcam and to view the stream, I go to <code>http://192.168.206.241/view/viewer_index.shtml?id=... | 0 | 2016-08-16T15:32:45Z | [
"python",
"python-2.7",
"opencv",
"webcam",
"video-capture"
] |
Average of multiple dataframes with the same columns and indices | 38,940,946 | <p>I have a few dataframes. Each of them has the same columns and the same indices. For each index I want to average the values in each column (if these would be matrices, I would just sum them up and divide by the number of matrices).</p>
<p>Here is the example.</p>
<pre><code>v1 = pd.DataFrame([['ind1', 1, 2, 3], [... | 3 | 2016-08-14T09:37:55Z | 38,940,997 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html#cython-optimized-aggregation-functions" rel="nofollow"><code>groupby.mean</code></a> on the <code>index</code> level after concatenating the dataframes:</p>
<pre><code>pd.concat([v1, v2, v3]).groupby(level=0).mean()
c1 ... | 3 | 2016-08-14T09:45:24Z | [
"python",
"pandas"
] |
"ImportError: No module named urls" while following Django Tutorial | 38,940,996 | <p>I am following the official django tutorial <a href="https://docs.djangoproject.com/en/1.10/intro/tutorial04/" rel="nofollow">https://docs.djangoproject.com/en/1.10/intro/tutorial04/</a></p>
<p>I am using Django 1.9.8 and I am now getting the following error in <code>/polls/views.py</code>:</p>
<pre><code>File "C:... | 3 | 2016-08-14T09:44:59Z | 38,941,050 | <p>That tutorial requires Django 1.10 while you seem to be using an older version. In this case, you should import <code>reverse</code> as follows:</p>
<pre><code>from django.core.urlresolvers import reverse
</code></pre>
<p>To upgrade your Django version, use the following command (in your command line, <em>not</em>... | 5 | 2016-08-14T09:52:06Z | [
"python",
"django"
] |
Python urllib unicode exception in 302 redirection | 38,941,075 | <p>The situation is:
I'm scraping one website, the urls for the pages follow the pattern:</p>
<pre><code>http://www.pageadress/somestuff/ID-HERE/
</code></pre>
<p>Nothing unusual.
I have a lot of id's that i need to scrape and most of them work correctly.
However, the page behaves in portal-like way. In browser, when... | 1 | 2016-08-14T09:54:48Z | 38,942,785 | <p>So, i've found out solution to my specific problem.
I've just gathered the remaining part of the 'url' from their api, and after some minor transformations i can access the page without any redirections.
That, of course, doesn't mean that i solved the general problem- it might come back later in the future, so i've ... | 0 | 2016-08-14T13:38:22Z | [
"python",
"python-3.4",
"urllib",
"http-status-code-302"
] |
parsing part of the table for data using BeautifulSoup | 38,941,097 | <p>I have a self-project to scrape data online using BeautifulSoup and Python, and I think historical stocks data would be a good one for me to practice. I looked at the source code <a href="https://uk.finance.yahoo.com/q/hp?s=AAPL" rel="nofollow">here</a> to analyze how I can use BeautifulSoup's select() or findall()... | 0 | 2016-08-14T09:57:55Z | 38,946,771 | <p>You can select the all the rows from the nested table inside the <em>yfnc_datamodoutline1</em> table and index the first two:</p>
<pre><code>soup = BeautifulSoup(html)
table_rows = soup.select("table.yfnc_datamodoutline1 table tr + tr")
row1, row2 = table_rows[0:2]
print(row1)
print(row2)
</code></pre>
<p>Which... | 0 | 2016-08-14T21:26:36Z | [
"python",
"html",
"beautifulsoup"
] |
Django 1.9. template inheritance. Block doesn't display | 38,941,118 | <p>I have 2 html pages in my Django templates. I am trying to insert cats.html in index.html as a block, but nothing happens. No errors, no display. I already looked in django documentation and in the youtube. Just can't understand where is problem</p>
<p>index.html:</p>
<pre><code> {% load static %}
<!DOCTY... | 2 | 2016-08-14T10:01:53Z | 38,941,193 | <p>You are confusing the block name with template name. You are <em>not</em> inserting <code>cats.html</code> into <code>index.html</code> as you expect, but you are extending <code>index.html</code> in your <code>cats.html</code>. You should use your child template (<code>cats.html</code>) in your view, ie change the ... | 1 | 2016-08-14T10:12:48Z | [
"python",
"html",
"django",
"templates",
"inheritance"
] |
Django 1.9. template inheritance. Block doesn't display | 38,941,118 | <p>I have 2 html pages in my Django templates. I am trying to insert cats.html in index.html as a block, but nothing happens. No errors, no display. I already looked in django documentation and in the youtube. Just can't understand where is problem</p>
<p>index.html:</p>
<pre><code> {% load static %}
<!DOCTY... | 2 | 2016-08-14T10:01:53Z | 38,941,260 | <p>actually the problem is you use index.html as a base template
and then inherit in your cats.html
so you have to render cat.html to get the desired result <a href="http://tutorial.djangogirls.org/en/template_extending/" rel="nofollow">THIS IS HELPFUL FOR YOU</a></p>
<pre><code>return render(request, 'cats.html', c... | -1 | 2016-08-14T10:20:54Z | [
"python",
"html",
"django",
"templates",
"inheritance"
] |
PySide Custom widget doesn't auto fit in QTableWidget | 38,941,180 | <p>I am trying to create a custom widget <code>RangeSpinBox</code>. The widget doesn't auto fit in a <code>QTableWidget</code> like in the image attached below.</p>
<p><a href="http://i.stack.imgur.com/W4FP8.png" rel="nofollow"><img src="http://i.stack.imgur.com/W4FP8.png" alt="enter image description here"></a></p>
... | 2 | 2016-08-14T10:10:35Z | 38,947,429 | <p>You need to remove the default margins on the layout, and also change the size-policy on the spin-boxes to expand in both directions:</p>
<pre><code> main_layout = QtGui.QHBoxLayout()
main_layout.setContentsMargins(0, 0, 0, 0)
size_policy = QtGui.QSizePolicy(
QtGui.QSizePolicy.Mi... | 1 | 2016-08-14T23:11:25Z | [
"python",
"qt",
"pyqt4",
"pyside",
"pyqt5"
] |
AttributeError at /circular/1/detail/ 'CircularDetail' object has no attribute 'pk' in Django | 38,941,276 | <pre><code>class CircularDetail(DeleteView):
model = Circular
template_name = 'genre/circular_detail.html'
def get_context_data(self, **kwargs):
ctx = super(CircularDetail, self).get_context_data(**kwargs)
ctx['c'] = Circular.objects.get(pk=self.pk)
ctx['sittings'] = Sitting.objects... | 1 | 2016-08-14T10:22:35Z | 38,941,424 | <p>URL parameters are passed via kwargs, so you can access it this way </p>
<pre><code>self.kwargs.get("pk")
</code></pre>
<p>so change</p>
<pre><code>ctx['c'] = Circular.objects.get(pk=self.pk)
</code></pre>
<p>to</p>
<pre><code>ctx['c'] = Circular.objects.get(pk=self.kwargs.get("pk"))
</code></pre>
| 0 | 2016-08-14T10:42:46Z | [
"python",
"django"
] |
AttributeError at /circular/1/detail/ 'CircularDetail' object has no attribute 'pk' in Django | 38,941,276 | <pre><code>class CircularDetail(DeleteView):
model = Circular
template_name = 'genre/circular_detail.html'
def get_context_data(self, **kwargs):
ctx = super(CircularDetail, self).get_context_data(**kwargs)
ctx['c'] = Circular.objects.get(pk=self.pk)
ctx['sittings'] = Sitting.objects... | 1 | 2016-08-14T10:22:35Z | 38,941,723 | <p>First of all, fix your base class to <code>DetailView</code> (instead of <code>DeleteView</code>)</p>
<p><code>DetailView</code> inherited from <code>django.views.generic.detail.SingleObjectMixin</code> (<a href="https://docs.djangoproject.com/en/1.10/ref/class-based-views/mixins-single-object/#django.views.generic... | 0 | 2016-08-14T11:23:16Z | [
"python",
"django"
] |
Strange error in Python (IndexError) | 38,941,303 | <p>Sorry if this is a dumb question but I am having a few issues with my code.</p>
<p>I have a Python script that scrapes Reddit and sets the top picture as my desktop background.</p>
<p>I want it to only download if the picture is big enough, but I am getting a strange error.</p>
<pre><code>>>> m = '1080x6... | 1 | 2016-08-14T10:26:03Z | 38,941,324 | <p><code>Ã</code> != <code>x</code>. Split returns one-element list, and you are trying to retrieve second element from it.</p>
<pre><code>'1080x608'.rsplit('x', 1) # ['1080', '608']
'1280Ã721'.rsplit('x', 1) # ['1280\xc3\x97721']
</code></pre>
<p>In second case <em>there is no</em> second element in list - it co... | 0 | 2016-08-14T10:28:11Z | [
"python"
] |
Strange error in Python (IndexError) | 38,941,303 | <p>Sorry if this is a dumb question but I am having a few issues with my code.</p>
<p>I have a Python script that scrapes Reddit and sets the top picture as my desktop background.</p>
<p>I want it to only download if the picture is big enough, but I am getting a strange error.</p>
<pre><code>>>> m = '1080x6... | 1 | 2016-08-14T10:26:03Z | 38,941,349 | <p>In your second example <code>Ã</code> is not the same as <code>x</code>, it is instead a multiplication sign. If you are getting these stings from somewhere and then parsing them, you should first do</p>
<pre><code>m = m.replace('Ã', 'x')
</code></pre>
| 0 | 2016-08-14T10:31:32Z | [
"python"
] |
Django deletes previous entry when submiting new one | 38,941,396 | <p>Title is pretty self-explanatory the thing is when I try to submit a new entry django deletes the previous one. I think that the problem is in the delete function because when I disable it I can sumbit as many entries as I want. Here are my files:</p>
<p><strong>Form.py</strong></p>
<pre><code>class FinancesForm(f... | 0 | 2016-08-14T10:39:01Z | 38,941,901 | <p>You have not closed your first form</p>
<pre><code> <td>
<form action="{% url "fdelete" %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="hidden" name="entry" value="{{ entry.pk }}"/>
<input class="btn btn-primary" type="submit" valu... | 0 | 2016-08-14T11:45:49Z | [
"python",
"django"
] |
Porting a function and an array from C to Python | 38,941,441 | <p>I'm trying to port this to python:</p>
<pre><code>uint8 formatHwInfo[0x40*4] =
{
// todo: Convert to struct
// each entry is 4 bytes
0x00,0x00,0x00,0x01,0x08,0x03,0x00,0x01,0x08,0x01,0x00,0x01,0x00,0x00,0x00,0x01,
0x00,0x00,0x00,0x01,0x10,0x07,0x00,0x00,0x10,0x03,0x00,0x01,0x10,0x03,0x00,0x01,
... | 0 | 2016-08-14T10:44:43Z | 38,941,482 | <p>Convert the array to a byte string:</p>
<pre><code>formatHwInfo = b"\x00\x00\x00\x01\x08\x03\x00\x01\x08\x01\x00\x01\x00\x00\x00\x01" \
b"\x00\x00\x00\x01\x10\x07\x00\x00\x10\x03\x00\x01\x10\x03\x00\x01" \
b"\x10\x0B\x00\x01\x10\x01\x00\x01\x10\x03\x00\x01\x10\x03\x00\x01" \
b"\x10\x03\x00\x01\x20\x03\x... | 1 | 2016-08-14T10:51:19Z | [
"python",
"c",
"arrays"
] |
pocketsphinx python example | 38,941,443 | <p>I use the raspberry pi with pocketsphinx python and I found an example <a href="https://pypi.python.org/pypi/pocketsphinx#basic-usage" rel="nofollow">here</a>. From that script I use the same path as described in the script. When I try to run this script it give me an error:</p>
<pre><code>ERROR: "acmod.c", line 83... | -1 | 2016-08-14T10:44:51Z | 38,942,371 | <p>Better use absolute path, for ex: if your 'deps' dir present under '/home/pi' then your code will looks like below:</p>
<pre><code>MODELDIR = '/home/pi/deps/pocketsphinx/model'
DATADIR = '/home/pi/deps/pocketsphinx/test/data'
# Create a decoder with certain model
config = ps.Decoder.default_config()
config.set_str... | 1 | 2016-08-14T12:43:20Z | [
"python",
"pocketsphinx"
] |
Django Invalid block tag: 'static' means what exactly? | 38,941,491 | <p>(I'm using Django 1.3 - Python 2.7)</p>
<p>Been through all the related questions without any resolution.</p>
<p>The syntax error is in line 5, not line one:</p>
<pre><code>{% load static %}
<html>
<head>
<link rel="stylesheet" href="{% static 'css/home.css' %}">
</code></pre>
<p>... | 1 | 2016-08-14T10:52:36Z | 38,941,613 | <p>In Django 1.3 there's no static tag, and you must use it like this:</p>
<pre><code>{% load static %}
<img src="{% get_static_prefix %}images/hi.jpg" />
</code></pre>
<p>or add static to TEMPLATE_CONTEXT_PROCESSORS and use STATIC_URL directly from template:</p>
<pre><code># settings.py
TEMPLATE_CONTEXT_PROC... | 3 | 2016-08-14T11:09:53Z | [
"python",
"django"
] |
Pandas Time Series: How to plot only times of day (no dates) against other values? | 38,941,557 | <p>As I am preparing to do some regressions on a rather big dataset I would like to visualize the data at first.</p>
<p>The data we are talking about is data about the New York subway (hourly entries, rain, weather and such) for May, 2011.</p>
<p>When creating the dataframe I converted hours and time to pandas dateti... | 1 | 2016-08-14T11:01:58Z | 38,941,711 | <p>IIUC you can do it this way:</p>
<pre><code>In [9]: weather_turnstile.plot.line(x=weather_turnstile.Date_Time.dt.time, y='ENTRIESn_hourly', marker='o', alpha=0.3)
Out[9]: <matplotlib.axes._subplots.AxesSubplot at 0xc2a63c8>
</code></pre>
<p><a href="http://i.stack.imgur.com/xFOkI.png" rel="nofollow"><img src... | 2 | 2016-08-14T11:21:34Z | [
"python",
"pandas",
"matplotlib",
"time-series"
] |
How does List Comprehension exactly work in Python? | 38,941,643 | <p>I am going trough the docs of Python 3.X, I have doubt about List Comprehension speed of execution and how it exactly work. </p>
<p>Let's take the following example: </p>
<p><strong>Listing 1</strong></p>
<pre><code>...
L = range(0,10)
L = [x ** 2 for x in L]
...
</code></pre>
<p>Now in my knowledge this return ... | 2 | 2016-08-14T11:13:40Z | 38,941,718 | <p>The answer is actually in your question.</p>
<p>When you run any built in python function you are running something that has been written in C and compiled into machine code.</p>
<p>When you write your own version of it, that code must be converted into CPython objects which are handled by the interpreter.</p>
<p... | 2 | 2016-08-14T11:22:44Z | [
"python"
] |
How does List Comprehension exactly work in Python? | 38,941,643 | <p>I am going trough the docs of Python 3.X, I have doubt about List Comprehension speed of execution and how it exactly work. </p>
<p>Let's take the following example: </p>
<p><strong>Listing 1</strong></p>
<pre><code>...
L = range(0,10)
L = [x ** 2 for x in L]
...
</code></pre>
<p>Now in my knowledge this return ... | 2 | 2016-08-14T11:13:40Z | 38,941,897 | <p>Look at the actual bytecode that is produced. I've put the two fragments of code into fuctions called f1 and f2. </p>
<p>The comprehension does this:</p>
<pre><code> 3 15 LOAD_CONST 3 (<code object <listcomp> at 0x7fbf6c1b59c0, file "<stdin>", line 3>)
18 LOAD... | 2 | 2016-08-14T11:45:32Z | [
"python"
] |
Have problems with SQLite in Python | 38,941,645 | <p>I want to add into my SQLite table a list of values. To be more accurate, I want to add it in Stock column. But I have some problems when running my app. Here is my database before app running.</p>
<p><a href="http://i.stack.imgur.com/qt9o4.png" rel="nofollow"><img src="http://i.stack.imgur.com/qt9o4.png" alt="ente... | 0 | 2016-08-14T11:13:49Z | 38,941,825 | <p>If you want to change the values of rows, just let the database do it for you internally:</p>
<pre><code>def count(ui):
if ui.comboBox.currentText() == '50ÐÐ 4':
condition = "Pumps = '50ÐÐ 4' OR Pumps = '50ÐÐ 4/6'"
elif ui.comboBox.currentText() == '50ÐÐ 6.3':
condition = "Pumps = '50ÐÐ... | 1 | 2016-08-14T11:36:23Z | [
"python",
"sqlite",
"pyqt"
] |
Slicing every nth range within a list with a for and a while loop | 38,941,659 | <p>So I have a short list called <strong>someList</strong> with some numbers in it. What I want to do is output every 3 elements of the list while iterating over it every 3rd slice range.</p>
<p>So if I have </p>
<pre><code>someList = [1,2,3,4,5,6,7,8,9,10]
</code></pre>
<p>The output of my <strong>someList</strong>... | 1 | 2016-08-14T11:15:24Z | 38,941,745 | <p>You have nested loops, but you only need one loop.</p>
<pre><code>someList = [1,2,3,4,5,6,7,8,9,10]
lookupRange = 3
temp = []
for index in range(len(someList) - lookupRange + 1):
temp.append(someList[index:index+lookupRange])
</code></pre>
| 4 | 2016-08-14T11:25:27Z | [
"python",
"iteration",
"slice"
] |
Slicing every nth range within a list with a for and a while loop | 38,941,659 | <p>So I have a short list called <strong>someList</strong> with some numbers in it. What I want to do is output every 3 elements of the list while iterating over it every 3rd slice range.</p>
<p>So if I have </p>
<pre><code>someList = [1,2,3,4,5,6,7,8,9,10]
</code></pre>
<p>The output of my <strong>someList</strong>... | 1 | 2016-08-14T11:15:24Z | 38,941,779 | <p>Using list comprehension:</p>
<pre><code>>>> someList = [1,2,3,4,5,6,7,8,9,10]
>>> chunk = 3
>>> [someList[i : i + chunk] for i in range(len(someList) - chunk + 1)]
[[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7], [6, 7, 8], [7, 8, 9], [8, 9, 10]]
</code></pre>
| 1 | 2016-08-14T11:29:42Z | [
"python",
"iteration",
"slice"
] |
Slicing every nth range within a list with a for and a while loop | 38,941,659 | <p>So I have a short list called <strong>someList</strong> with some numbers in it. What I want to do is output every 3 elements of the list while iterating over it every 3rd slice range.</p>
<p>So if I have </p>
<pre><code>someList = [1,2,3,4,5,6,7,8,9,10]
</code></pre>
<p>The output of my <strong>someList</strong>... | 1 | 2016-08-14T11:15:24Z | 38,942,423 | <p>Here's a pure Python one-liner; Numpy isn't required.</p>
<pre><code>someList = [1,2,3,4,5,6,7,8,9,10]
lookupRange = 3
temp = list(zip(*(someList[i:] for i in range(lookupRange))))
print(temp)
</code></pre>
<p><strong>output</strong></p>
<pre><code>[(1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6), (5, 6, 7), (6, 7, 8)... | 2 | 2016-08-14T12:51:04Z | [
"python",
"iteration",
"slice"
] |
How to sort dataframe by a row? | 38,941,735 | <p>I have a dataframe:</p>
<pre><code>import pandas as pd
df = pd.DataFrame(data={'x':[7,1,9], 'y':[4,5,6],'z':[1,8,3]}, index=['a', 'b', 'c'])
</code></pre>
<p>It shows:</p>
<p><a href="http://i.stack.imgur.com/mJEps.png" rel="nofollow"><img src="http://i.stack.imgur.com/mJEps.png" alt="enter image description her... | 0 | 2016-08-14T11:24:28Z | 38,941,764 | <pre><code>In [7]: df.iloc[:, np.argsort(df.loc['a'])]
Out[7]:
z y x
a 1 4 7
b 8 5 1
c 3 6 9
</code></pre>
<hr>
<p><code>np.argsort</code> returns the indices one would use to sort the <code>a</code> row, <code>df.loc['a']</code>:</p>
<pre><code>In [6]: np.argsort(df.loc['a'])
Out[6]:
x 2
y 1
z... | 3 | 2016-08-14T11:27:23Z | [
"python",
"pandas",
"dataframe"
] |
How to sort dataframe by a row? | 38,941,735 | <p>I have a dataframe:</p>
<pre><code>import pandas as pd
df = pd.DataFrame(data={'x':[7,1,9], 'y':[4,5,6],'z':[1,8,3]}, index=['a', 'b', 'c'])
</code></pre>
<p>It shows:</p>
<p><a href="http://i.stack.imgur.com/mJEps.png" rel="nofollow"><img src="http://i.stack.imgur.com/mJEps.png" alt="enter image description her... | 0 | 2016-08-14T11:24:28Z | 38,941,774 | <p>You can use <code>axis=1</code> when calling <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort.html" rel="nofollow"><code>sort</code></a>:</p>
<pre><code>df.sort(axis=1, ascending=False)
>> z y x
a 1 4 7
b 8 5 1
c 3 6 9
</code></pre>
<... | 1 | 2016-08-14T11:29:18Z | [
"python",
"pandas",
"dataframe"
] |
How to sort dataframe by a row? | 38,941,735 | <p>I have a dataframe:</p>
<pre><code>import pandas as pd
df = pd.DataFrame(data={'x':[7,1,9], 'y':[4,5,6],'z':[1,8,3]}, index=['a', 'b', 'c'])
</code></pre>
<p>It shows:</p>
<p><a href="http://i.stack.imgur.com/mJEps.png" rel="nofollow"><img src="http://i.stack.imgur.com/mJEps.png" alt="enter image description her... | 0 | 2016-08-14T11:24:28Z | 38,941,800 | <p>You can use <code>reindex_axis</code> method:</p>
<pre><code>>>> df.reindex_axis(sorted(df.columns, key=lambda x: df[x]['a']), axis=1)
z y x
a 1 4 7
b 8 5 1
c 3 6 9
</code></pre>
| 2 | 2016-08-14T11:32:58Z | [
"python",
"pandas",
"dataframe"
] |
How to sort dataframe by a row? | 38,941,735 | <p>I have a dataframe:</p>
<pre><code>import pandas as pd
df = pd.DataFrame(data={'x':[7,1,9], 'y':[4,5,6],'z':[1,8,3]}, index=['a', 'b', 'c'])
</code></pre>
<p>It shows:</p>
<p><a href="http://i.stack.imgur.com/mJEps.png" rel="nofollow"><img src="http://i.stack.imgur.com/mJEps.png" alt="enter image description her... | 0 | 2016-08-14T11:24:28Z | 39,429,537 | <p>In v0.19 you can sort by rows:</p>
<pre><code>pd.__version__
Out: '0.19.0rc1'
df.sort_values(by='a', axis=1)
Out:
z y x
a 1 4 7
b 8 5 1
c 3 6 9
</code></pre>
| 1 | 2016-09-10T18:58:22Z | [
"python",
"pandas",
"dataframe"
] |
Windows: How to run a shell script out of a simple CGI python server | 38,941,743 | <p>I have made a python Srver using http.server </p>
<pre><code>python -m http.server --cgi 8000
</code></pre>
<p>Server is running and i am able to run a python script on it. I am trying to <strong>run shell file</strong> with similar content.
I think i am not bale to make the shell file executable. Lookign for soem... | 0 | 2016-08-14T11:25:10Z | 38,967,838 | <p>In windows there are no bash-scripts. You only have .bat-Files with very limited syntax. If you try to run your script as <code>filename.sh</code> windows tries to find a program associated with the extension <code>.sh</code> and fails. You should rename your file to <code>filename.bat</code>.</p>
| 0 | 2016-08-16T06:19:44Z | [
"python",
"shell",
"cgi"
] |
Why is my Python3 pip package not working eventhough it shows on PyPi? | 38,941,840 | <p>Here is a little library that I'm trying to make available on PyPi for others to use.</p>
<p><a href="https://github.com/rojavacrypto/python-libbitcoin" rel="nofollow">https://github.com/rojavacrypto/python-libbitcoin</a></p>
<p>I use this command to upload the package:</p>
<pre><code>$ python setup.py sdist bdis... | 0 | 2016-08-14T11:39:09Z | 38,941,876 | <p>The name of your package in PyPI is "python-libbitcoin":</p>
<pre><code>pip3 install python-libbitcoin
</code></pre>
<p>and here you go:</p>
<pre><code>Downloading/unpacking python-libbitcoin
http://pypi.python.org/simple/python-libbitcoin/ uses an insecure transport scheme (http). Consider using https if pypi.... | 1 | 2016-08-14T11:43:21Z | [
"python",
"python-3.x",
"pip",
"bitcoin"
] |
AttributeError: 'module' object has no attribute 'maketrans' - PyCharm | 38,941,915 | <p>I've got this strange problem on my PC with Python 2.7 + PyCharm 2016.2 + Windows 10 (64).</p>
<p>While running script:</p>
<pre><code>import urllib
from BeautifulSoup import *
url = raw_input('Enter -')
if (len(url) < 1):
url = "http://python-data.dr-chuck.net/comments_292106.html"
html = urllib.urlopen(u... | 1 | 2016-08-14T11:47:18Z | 38,943,367 | <p>I think this is happening behind the scenes. In order to carry out your commands, Python has to do some work and it is not finding the files it needs. That might explain why it may work in Idle and on your PC but not in others like Wing IDE.</p>
| -1 | 2016-08-14T14:50:26Z | [
"python",
"python-2.7",
"base64",
"pycharm",
"urllib"
] |
Why is this SyntaxError? (Python, dictionary comprehension with inline if) | 38,942,073 | <p>In a dictionary, I want to make sure that a specific key has a specific encoding.</p>
<pre><code>test_dictionary = { k:v.encode('latin-1') if k=="test_key" else k:v for k,v in test_dictionary.items() }
</code></pre>
<p>I get <code>SyntaxError</code>. I expected this to be allowed though.</p>
| 0 | 2016-08-14T12:06:40Z | 38,942,103 | <p>Try this instead:</p>
<pre><code>test_dictionary = { k:v.encode('latin-1') if k=="test_key" else v for k,v in test_dictionary.items() }
</code></pre>
<p>The second <code>:</code> has been removed so the inline <code>if</code> either encodes <code>v</code>, or leaves it as it is depending on the condition.</p>
<p>... | 3 | 2016-08-14T12:10:18Z | [
"python"
] |
Conditional raplacement with index shift in Pandas | 38,942,382 | <p>having following column in dataframe:</p>
<pre><code>0
0
0
0
0
5
</code></pre>
<p>I would like to check for values greater than a threshold. If found, set to zero and move up by the difference value-threshold, setting threshold on the new position. Let's say threshold=3, then the resulting column has to be:</p>
<... | -1 | 2016-08-14T12:44:33Z | 38,942,726 | <p>For this DataFrame:</p>
<pre>df
Out:
A
0 0
1 0
2 0
3 0
4 0
5 5
6 0
7 0
8 0
9 0
10 6
11 0
12 0</pre>
<pre><code>threshold = 3
above_threshold = df['A'] > threshold
df.loc[df[above_threshold].index - (df.loc[above_threshold, 'A'] - 3).values, 'A'] = 3
df.loc[above_threshold, 'A'] = 0
<... | 0 | 2016-08-14T13:31:08Z | [
"python",
"pandas",
"dataframe"
] |
Parsing strange xml feeds | 38,942,386 | <p>May not be strange, but I have never used xml, or PHP, which is two of the things I am using for an upcoming project.</p>
<p>Anyway, I am parsing <a href="http://www.huffingtonpost.com/feeds/verticals/good-news/index.xml" rel="nofollow">this</a> XML feed. Each <code><item></code> contains an <code><enclosu... | 0 | 2016-08-14T12:45:09Z | 38,943,413 | <p>Looking at the <a href="http://pythonhosted.org/feedparser/reference-entry-enclosures.html" rel="nofollow">feedparse docs</a> try using the <em>entries[i].enclosures[j].href</em> reference which returns the URL of the linked file:</p>
<pre><code>feed = feedparser.parse("http://www.huffingtonpost.com/feeds/verticals... | 0 | 2016-08-14T14:55:35Z | [
"python",
"xml"
] |
How to read and filter a raw audio file with python? | 38,942,404 | <p>I got a <code>.raw</code> file from recording, it was written by the write method from the Java class <code>AudioOutputStream</code> (I wrote bytes).</p>
<p>I want to filter this audio file with a Python filter. <a href="http://scipy.github.io/old-wiki/pages/Cookbook/ButterworthBandpass" rel="nofollow">Here</a> it ... | -1 | 2016-08-14T12:48:28Z | 38,982,799 | <p>I found two useful java classes: <code>DataInputStream</code> and <code>DataOutputStream</code> to write floats for my Python script to use.</p>
<p>First I read float values from the <code>.raw</code> file with the <code>readFloat</code> method which reads 4 bytes as a float. </p>
<pre><code>FileInputStream is = n... | 0 | 2016-08-16T19:15:38Z | [
"java",
"python",
"audio"
] |
Value Object Django | 38,942,445 | <p>Good morning, first sorry my English because I'm using Google Translate.</p>
<p>I'm starting now with Python and Django and me a question arose in the creation of my models. I would like to create something like:</p>
<p>Person (models.Model)</p>
<ul>
<li>Name</li>
<li>...</li>
<li>Address</li>
</ul>
<p>Address(m... | 0 | 2016-08-14T12:53:21Z | 38,942,731 | <p>You want something like:</p>
<pre><code>class Person(models.Model):
LastName = models.CharField(max_length=30)
FirstName = models.CharField(max_length=30)
...
address = models.ManyToManyField(Address)
</code></pre>
<p>In this many, one person could have multiple addresses, and each address could ha... | 1 | 2016-08-14T13:31:37Z | [
"python",
"django",
"django-models"
] |
Extracting plain text from HTML using Python | 38,942,474 | <p>I'm trying to extract plain text from a website using python. My code is something like this (a slightly modified version of what I found here):</p>
<pre><code>import requests
import urllib
from bs4 import BeautifulSoup
url = "http://www.thelatinlibrary.com/vergil/aen1.shtml"
r = requests.get(url)
k = r.content
fil... | 1 | 2016-08-14T12:58:09Z | 38,942,666 | <p>The "error" is a warning, and is of no consequence. Quieten it with <code>soup = BeautifulSoup(k, 'html.parser')</code> </p>
<p>There seems to be a typo <code>script.exctract()</code> The word <code>extract</code> is spelt incorrectly.</p>
<p>The actual error seems to be that the content is a bytestring, but you a... | 2 | 2016-08-14T13:21:41Z | [
"python",
"beautifulsoup"
] |
Extracting plain text from HTML using Python | 38,942,474 | <p>I'm trying to extract plain text from a website using python. My code is something like this (a slightly modified version of what I found here):</p>
<pre><code>import requests
import urllib
from bs4 import BeautifulSoup
url = "http://www.thelatinlibrary.com/vergil/aen1.shtml"
r = requests.get(url)
k = r.content
fil... | 1 | 2016-08-14T12:58:09Z | 38,982,654 | <p>There was a â on the code which resulted in an error , 'â' being non utf-8 . Changing the encoding before passing text on to BeautifulSoup fixed the issue .</p>
<p>Another error was due to soup.get_text . Missing out () implied I was referencing the method , not the output . </p>
| 0 | 2016-08-16T19:06:17Z | [
"python",
"beautifulsoup"
] |
python3 login website tumblr.com | 38,942,476 | <p>How can I log in tumblr using requests in python3?
Here is my code but it dosn't work well and go back to the login page.
I used request.post to post a log-in form data, and failed.</p>
<pre><code>import requests
from bs4 import BeautifulSoup
start_url = 'https://www.tumblr.com'
# set a session for request
s = re... | 0 | 2016-08-14T12:58:23Z | 38,944,030 | <p>You're nearly to target.</p>
<p>Firstly, you have to make a request to tumblr login page (<a href="https://tumblr.com/login" rel="nofollow">https://tumblr.com/login</a>). (You did)</p>
<p>Then, you have to parse html page and get <code>form_key</code> value. This value is used to make a real login.</p>
<p>Finally... | 2 | 2016-08-14T16:04:56Z | [
"python",
"python-3.x",
"web-crawler"
] |
Error from Python job scheduling module each time I stop server | 38,942,506 | <p>My models.py file in my Django project contains the code based on the <a href="https://github.com/dbader/schedule" rel="nofollow">following tutorial</a>:</p>
<pre><code>import schedule
import time
def job():
print("I'm working...")
schedule.every(3).seconds.do(job)
while True:
schedule.run_pending()
... | 0 | 2016-08-14T13:03:03Z | 38,942,659 | <p>There does not seem to be any problem.</p>
<p>The Traceback you posted reports a KeyboardInterrupt which is commonly used to force-quit an application and thus completely normal.</p>
<p>The server also seems to have started.
Have you tried visiting <a href="http://127.0.0.1:8000/" rel="nofollow">http://127.0.0.1:8... | 1 | 2016-08-14T13:21:11Z | [
"python",
"django"
] |
Why does this not update my table in sqlalchemy? | 38,942,545 | <p>I have the following code: </p>
<pre><code>engine = sqlalchemy.create_engine(connectstring, echo=_echo).connect()
md = sqlalchemy.MetaData(engine)
table = sqlalchemy.Table('table_name', md, autoload=True, autoload_with=engine)
_Session = sessionmaker(bind=engine)
session = _Session()
for row in reader:
table.i... | 0 | 2016-08-14T13:08:18Z | 38,942,929 | <p>the insertion was never executed. </p>
<pre><code>table.insert({'key': 'value'}).execute()
</code></pre>
<p>fixes this problem. </p>
| 1 | 2016-08-14T13:56:25Z | [
"python",
"sql",
"sql-server-2008",
"orm",
"sqlalchemy"
] |
TypeError: 'NoneType' object is not iterable error in matoplotlib animation | 38,942,549 | <p>I've been trying to code an animation using matplolibs FuncAnimation to create a model like the picture below where each frame a circle changes color from white to grey and vice versa. The picture:</p>
<p><a href="http://i.stack.imgur.com/WSAQd.png" rel="nofollow">The model</a></p>
<p>Below is the code. Consider h... | 0 | 2016-08-14T13:08:41Z | 38,942,896 | <p>The <a href="http://matplotlib.org/api/animation_api.html#matplotlib.animation.FuncAnimation" rel="nofollow">documentation of <code>FuncAnimation</code></a> says that the <code>update</code> function should return the changed artists:</p>
<pre><code>If blit=True, func and init_func should return an iterable of draw... | 0 | 2016-08-14T13:52:27Z | [
"python",
"matplotlib"
] |
Python Iterate over NoneType | 38,942,625 | <p>I have the following code and am attempting to iterate over the results of each line and check if a calculated value in the 'untrained' dictionary is greater than 50%. However, some of the lines are NoneType and I am getting error: TypeError: 'NoneType' oject is not subscriptable. Is there a way I can ovoid this and... | 0 | 2016-08-14T13:16:40Z | 38,942,653 | <p>Skip over None values</p>
<pre><code>if untrained is None:
continue
</code></pre>
| 4 | 2016-08-14T13:20:21Z | [
"python",
"dictionary",
"nonetype"
] |
Python Iterate over NoneType | 38,942,625 | <p>I have the following code and am attempting to iterate over the results of each line and check if a calculated value in the 'untrained' dictionary is greater than 50%. However, some of the lines are NoneType and I am getting error: TypeError: 'NoneType' oject is not subscriptable. Is there a way I can ovoid this and... | 0 | 2016-08-14T13:16:40Z | 38,942,914 | <p>You can not just skip the lines where <code>untrained</code> is <code>None</code> or you will skip the <code>trained</code> values, too. Instead, you should add an additional guard directly to the <code>if</code> condition checking whether the percentage is > 50:</p>
<pre><code>if untrained is not None and untraine... | 1 | 2016-08-14T13:54:38Z | [
"python",
"dictionary",
"nonetype"
] |
Understanding recursive odd/even functions | 38,942,725 | <p>I'm currently studying python from <a href="http://www.sololearn.com/Play/Python" rel="nofollow">http://www.sololearn.com/Play/Python</a> and I'm having trouble understanding why this code works.</p>
<pre><code>def is_even(x):
if x == 0:
return True
else:
return is_odd(x-1)
def is_odd(x):
... | 1 | 2016-08-14T13:31:05Z | 38,942,781 | <p>It's based on an inductive definition of evenness:</p>
<ul>
<li>Zero is even</li>
<li>If some number "n" is even, then "n+1" is not even</li>
<li>If some number "n" is not even, then "n+1" is even</li>
</ul>
<p>"odd" is obviously "not even". </p>
<p>The code takes this definition, and checks it backwards - using ... | 1 | 2016-08-14T13:38:00Z | [
"python",
"python-3.x",
"recursion"
] |
Understanding recursive odd/even functions | 38,942,725 | <p>I'm currently studying python from <a href="http://www.sololearn.com/Play/Python" rel="nofollow">http://www.sololearn.com/Play/Python</a> and I'm having trouble understanding why this code works.</p>
<pre><code>def is_even(x):
if x == 0:
return True
else:
return is_odd(x-1)
def is_odd(x):
... | 1 | 2016-08-14T13:31:05Z | 38,942,864 | <p>That recursive function is really a bad way to teach recursion, you should apply recursion only when it's useful. In fact, test those functions with negative numbers and you'll get <code>RuntimeError: maximum recursion depth exceeded</code> errors.</p>
<p>To check parity numbers you'd better use <code>%</code> oper... | 0 | 2016-08-14T13:48:40Z | [
"python",
"python-3.x",
"recursion"
] |
Understanding recursive odd/even functions | 38,942,725 | <p>I'm currently studying python from <a href="http://www.sololearn.com/Play/Python" rel="nofollow">http://www.sololearn.com/Play/Python</a> and I'm having trouble understanding why this code works.</p>
<pre><code>def is_even(x):
if x == 0:
return True
else:
return is_odd(x-1)
def is_odd(x):
... | 1 | 2016-08-14T13:31:05Z | 38,942,897 | <p>A little hint:</p>
<pre><code>0 -> True
1 -> not True
2 -> not not True
3 -> not not not True
...
</code></pre>
<p>and so on.</p>
| 0 | 2016-08-14T13:52:33Z | [
"python",
"python-3.x",
"recursion"
] |
Understanding recursive odd/even functions | 38,942,725 | <p>I'm currently studying python from <a href="http://www.sololearn.com/Play/Python" rel="nofollow">http://www.sololearn.com/Play/Python</a> and I'm having trouble understanding why this code works.</p>
<pre><code>def is_even(x):
if x == 0:
return True
else:
return is_odd(x-1)
def is_odd(x):
... | 1 | 2016-08-14T13:31:05Z | 38,942,979 | <p><code>is_even'</code>s base case resolves to <code>True</code>. Since <code>is_odd(x)</code> returns <code>not is_even(x)</code>, the value <code>True</code> will be a part of the expression returned by <code>is_odd</code>. The question is how many times will that <code>True</code> value be <em>negated</em>. By trac... | 1 | 2016-08-14T14:01:47Z | [
"python",
"python-3.x",
"recursion"
] |
Python Pandas Dataframe Append Rows | 38,942,790 | <p>I'm trying to append the data frame values as rows but its appending them as columns. I have 32 files that i would like to take the second column from (called dataset_code) and append it. But its creating 32 rows and 101 columns. I would like 1 column and 3232 rows.</p>
<pre><code>import pandas as pd
import os
... | 1 | 2016-08-14T13:39:15Z | 38,942,937 | <p><code>df["dataset_code"]</code> is a <code>Series</code>, not a <code>DataFrame</code>. Since you want to append one DataFrame to another, you need to change the Series object to a DataFrame object.</p>
<pre><code>>>> type(df)
<class 'pandas.core.frame.DataFrame'>
>>> type(df['dataset_code']... | 3 | 2016-08-14T13:57:22Z | [
"python",
"python-2.7",
"pandas",
"dataframe"
] |
Python Pandas Dataframe Append Rows | 38,942,790 | <p>I'm trying to append the data frame values as rows but its appending them as columns. I have 32 files that i would like to take the second column from (called dataset_code) and append it. But its creating 32 rows and 101 columns. I would like 1 column and 3232 rows.</p>
<pre><code>import pandas as pd
import os
... | 1 | 2016-08-14T13:39:15Z | 38,943,318 | <p>Alternatively, you can create a dataframe with double square brackets:</p>
<pre><code>df = df[["dataset_code"]]
</code></pre>
| 2 | 2016-08-14T14:44:25Z | [
"python",
"python-2.7",
"pandas",
"dataframe"
] |
Python Pandas Dataframe Append Rows | 38,942,790 | <p>I'm trying to append the data frame values as rows but its appending them as columns. I have 32 files that i would like to take the second column from (called dataset_code) and append it. But its creating 32 rows and 101 columns. I would like 1 column and 3232 rows.</p>
<pre><code>import pandas as pd
import os
... | 1 | 2016-08-14T13:39:15Z | 38,943,704 | <p>You already have two perfectly good answers, but let me make a couple of recommendations.</p>
<ol>
<li>If you only want the <code>dataset_code</code> column, tell <code>pd.read_csv</code> directly (<code>usecols=['dataset_code']</code>) instead of loading the whole file into memory only to subset the dataframe imme... | 4 | 2016-08-14T15:29:51Z | [
"python",
"python-2.7",
"pandas",
"dataframe"
] |
TypeError: slice indices must be integers in Python 3 | 38,942,865 | <p>I'm new to Python, thus the question,</p>
<p>I'm trying to slice an array and find the sub array of the longest length that is less than a particular value. This is my code,</p>
<pre><code>def main():
a = [1, 2, 3]
print(maxLength(a, 3))
def maxLength(a, k):
max = 0
currTotal = 0
for i in en... | 0 | 2016-08-14T13:49:05Z | 38,942,900 | <p>When you use <a href="https://docs.python.org/2/library/functions.html#enumerate" rel="nofollow"><code>enumerate</code></a>, it gives you a sequence of tuples.</p>
<pre><code>for i,x in enumerate(mylist):
# i is the index
# x is the item at that index
</code></pre>
<p>You are assigning that tuple to one va... | 5 | 2016-08-14T13:52:57Z | [
"python"
] |
TypeError: slice indices must be integers in Python 3 | 38,942,865 | <p>I'm new to Python, thus the question,</p>
<p>I'm trying to slice an array and find the sub array of the longest length that is less than a particular value. This is my code,</p>
<pre><code>def main():
a = [1, 2, 3]
print(maxLength(a, 3))
def maxLength(a, k):
max = 0
currTotal = 0
for i in en... | 0 | 2016-08-14T13:49:05Z | 38,942,917 | <p><code>enumerate</code> returns an <code>object</code>. Thats why it is giving you that error.</p>
<p>if you want to traverse the array, try <code>range(len(a))</code> instead.</p>
<pre><code>for i in range(len(a)):
for j in range(len(a)):
temp = a[i:i+j:1]
currTotal += a[j]
... | 0 | 2016-08-14T13:55:12Z | [
"python"
] |
Python and multithreading sys.excepthook is missing | 38,942,867 | <p>So I have many files to download from a server. Over 1000... So I thought I'd write a script that would do this for me that is multithreaded so that I don't have to wait for ages for it to finish. The problem is that it spits out a bunch of errors. I have searched for this but couldn't really find anything that seem... | 0 | 2016-08-14T13:49:15Z | 38,944,010 | <p>So I actually managed to make it work after some more googling and reading.</p>
<p>current code:</p>
<pre><code>mycount = 0
mylistLoc = []
for index in range(len(mylist)):
mylistLoc.append(index)
def download(mycount):
global mylistLoc
url = "http://myserver.com/content/zips/" + mylist[mycount]
try:
myfil... | 0 | 2016-08-14T16:03:10Z | [
"python",
"multithreading"
] |
Filtering rows containing a string pattern from a Pandas dataframe index | 38,943,008 | <p>I need to filter rows containing a string pattern from a Pandas dataframe index.</p>
<p>I found the following example: <a href="http://stackoverflow.com/questions/27975069/how-to-filter-rows-containing-a-string-pattern-from-a-pandas-dataframe">How to filter rows containing a string pattern from a Pandas dataframe</... | 0 | 2016-08-14T14:06:24Z | 38,943,411 | <p>You should ensure that your index is a string. The example below produces an error.</p>
<pre><code># Test data
df = DataFrame([1,2,3,4], index=['foo', 'foo1', 'foo2', 1], columns=['value'])
df[df.index.str.contains('foo')]
</code></pre>
<p>Converting the index to <code>str</code> permits to obtain the expected res... | 0 | 2016-08-14T14:55:27Z | [
"python",
"pandas"
] |
Difference between Python 2 and 3 for shuffle with a given seed | 38,943,038 | <p>I am writing a program compatible with both Python 2.7 and 3.5. Some parts of it rely on stochastic process. My unit tests use an arbitrary seed, which leads to the same results across executions and languages... except for the code using <code>random.shuffle</code>.</p>
<p>Example in Python 2.7:</p>
<pre><code>In... | 3 | 2016-08-14T14:09:41Z | 38,943,222 | <p>In Python 3.2 the random module was refactored a little to make the output uniform across architectures (given the same seed), see <a href="http://bugs.python.org/issue7889" rel="nofollow">issue #7889</a>. The <code>shuffle()</code> method was switched to using <code>Random._randbelow()</code>.</p>
<p>However, the ... | 9 | 2016-08-14T14:31:20Z | [
"python",
"python-2.7",
"python-3.x",
"shuffle",
"random-seed"
] |
Difference between Python 2 and 3 for shuffle with a given seed | 38,943,038 | <p>I am writing a program compatible with both Python 2.7 and 3.5. Some parts of it rely on stochastic process. My unit tests use an arbitrary seed, which leads to the same results across executions and languages... except for the code using <code>random.shuffle</code>.</p>
<p>Example in Python 2.7:</p>
<pre><code>In... | 3 | 2016-08-14T14:09:41Z | 38,944,272 | <p>Elaborating on Martijn Pieters excellent answer and comments, and on this <a href="http://stackoverflow.com/questions/30585108/disable-hash-randomization-from-within-python-program?noredirect=1&lq=1">discussion</a>, I finally found a workaround, which arguably doesn't answer my very question, but at the same tim... | 1 | 2016-08-14T16:34:19Z | [
"python",
"python-2.7",
"python-3.x",
"shuffle",
"random-seed"
] |
Efficiency issues with finding correlations between lists inside lists | 38,943,055 | <p>If I have two small lists and I want to find the correlation between each list inside <strong>list1</strong> with each list inside <strong>list2</strong>, I can do this</p>
<pre><code>from scipy.stats import pearsonr
list1 = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
list2 = [[10,20,30],[40,50,60],[77,78,79],[80,78,56]]... | 1 | 2016-08-14T14:10:47Z | 38,945,568 | <p>Doing the same calculation, but collecting the values in a 4x4 array:</p>
<pre><code>In [1791]: res=np.zeros((4,4))
In [1792]: for i in range(4):
...: for j in range(4):
...: res[i,j]=stats.pearsonr(list1[i],list2[j])[0]
...:
In [1793]: res
Out[1793]:
array([[ 1. , 1.... | 0 | 2016-08-14T18:54:25Z | [
"python",
"scipy",
"correlation"
] |
Efficiency issues with finding correlations between lists inside lists | 38,943,055 | <p>If I have two small lists and I want to find the correlation between each list inside <strong>list1</strong> with each list inside <strong>list2</strong>, I can do this</p>
<pre><code>from scipy.stats import pearsonr
list1 = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
list2 = [[10,20,30],[40,50,60],[77,78,79],[80,78,56]]... | 1 | 2016-08-14T14:10:47Z | 38,946,645 | <p>The scipy module <a href="http://docs.scipy.org/doc/scipy/reference/spatial.distance.html" rel="nofollow"><code>scipy.spatial.distance</code></a> includes a distance function known as <a href="https://en.wikipedia.org/wiki/Pearson_product-moment_correlation_coefficient#Pearson.E2.80.99s_distance" rel="nofollow">Pear... | 2 | 2016-08-14T21:07:50Z | [
"python",
"scipy",
"correlation"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.