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 |
|---|---|---|---|---|---|---|---|---|---|
Copy an itertools cycle object | 37,466,115 | <p>I want to make a shallow copy of an <code>itertools.cycle</code> object, but I don't know how because it has no builtin copy method. I want to achieve something like the following, where I create a copy of the cycle, iterate through it a few times, then copy the original again, and iterate a few more times <em>start... | 2 | 2016-05-26T16:14:30Z | 37,466,789 | <p>You could create a custom class to do what you want:</p>
<pre><code>import itertools
class CopyCycle:
def __init__(self, iterable):
self.iterable = iterable
self._cycle = itertools.cycle(self.iterable)
def cycle(self):
return self
def __iter__(self):
return self
d... | 1 | 2016-05-26T16:49:03Z | [
"python",
"itertools"
] |
Copy an itertools cycle object | 37,466,115 | <p>I want to make a shallow copy of an <code>itertools.cycle</code> object, but I don't know how because it has no builtin copy method. I want to achieve something like the following, where I create a copy of the cycle, iterate through it a few times, then copy the original again, and iterate a few more times <em>start... | 2 | 2016-05-26T16:14:30Z | 37,467,082 | <p>It may require some refactoring, but a factory would work well here.</p>
<pre><code>from itertools import cycle
cycle_factory = lambda: cycle('1234')
c1 = cycle_factory()
print next(c1) # 1
c2 = cycle_factory()
print next(c2) # 1
</code></pre>
<p>Otherwise, I'm not sure you're going to be able to satisfy the cr... | 2 | 2016-05-26T17:05:20Z | [
"python",
"itertools"
] |
Avoiding for loop in a pandas data frame when working on selected rows | 37,466,159 | <p>I have a <code>pandas</code> data frame, <code>df</code>, that has second-to-second data (Longitude, Latitude, etc.) for each driver. The data frame consists of several trips. There is a feature called <code>Event_Type</code> that can be used to determine the start and end of trips:</p>
<pre><code>ignitionOnList = ... | 1 | 2016-05-26T16:16:49Z | 37,466,472 | <p>I suspect that any performance issues may actually be due to the way you are growing <code>dfTrips</code>. I have found that it is orders of magnitude faster to create many small, even single-row (or single-column), dataframes and then join them all using <code>pd.concat</code>, then to try and grow one df row-by-ro... | 1 | 2016-05-26T16:32:37Z | [
"python",
"loops",
"pandas",
"apply"
] |
Avoiding for loop in a pandas data frame when working on selected rows | 37,466,159 | <p>I have a <code>pandas</code> data frame, <code>df</code>, that has second-to-second data (Longitude, Latitude, etc.) for each driver. The data frame consists of several trips. There is a feature called <code>Event_Type</code> that can be used to determine the start and end of trips:</p>
<pre><code>ignitionOnList = ... | 1 | 2016-05-26T16:16:49Z | 37,468,055 | <p>I am not sure it will save time, but you can (kind of) avoid the loop by using <code>groupby</code>. First you would define a new column, say <code>trip_number</code>, to index each unique trip (this will probably still involve looping over tripNumbers). Then group by <code>trip_number</code>.</p>
<p>You could use ... | 1 | 2016-05-26T18:02:39Z | [
"python",
"loops",
"pandas",
"apply"
] |
MongoEngine delete document | 37,466,212 | <p>I have the following MongoEngine document</p>
<pre><code>{
'_id': 'some_id',
'data': 'some_data'
}
</code></pre>
<p>How can I <code>delete</code> this document using MongoEngine?</p>
<p><strong>What I've tried:</strong></p>
<pre><code>import my_collection
obj = my_collection.MyCol.objects.get(_id='some_... | 3 | 2016-05-26T16:19:17Z | 37,466,496 | <p>From what I understand and according to the <a href="http://docs.mongoengine.org/guide/document-instances.html#deleting-documents" rel="nofollow">note in the docs</a>:</p>
<blockquote>
<p>Note that this will only work if the document exists in the database and has a valid id</p>
</blockquote>
<p><code>obj.delete... | 2 | 2016-05-26T16:33:49Z | [
"python",
"mongoengine"
] |
MongoEngine delete document | 37,466,212 | <p>I have the following MongoEngine document</p>
<pre><code>{
'_id': 'some_id',
'data': 'some_data'
}
</code></pre>
<p>How can I <code>delete</code> this document using MongoEngine?</p>
<p><strong>What I've tried:</strong></p>
<pre><code>import my_collection
obj = my_collection.MyCol.objects.get(_id='some_... | 3 | 2016-05-26T16:19:17Z | 40,062,558 | <p>If your document overrides <code>_id</code>, you must indicate that it's still the primary key. Change your document class definition from:</p>
<pre><code>class MyCol(Document):
_id = db.StringField()
...
</code></pre>
<p>To specify the primary key:</p>
<pre><code>class MyCol(Document):
_id = db.Strin... | 1 | 2016-10-15T18:13:37Z | [
"python",
"mongoengine"
] |
Python - Functional inheritance - changing keyword arguments | 37,466,312 | <p>Is it possible to have a function defined with certain keyword arguments, and then to make a reference to the same function, but using different keyword argument values.</p>
<p>e.g. I have the following</p>
<pre><code>def f_beta(x,a=2.7,b=3.05):
"""The un-normalised beta distribution function."""
return ma... | 1 | 2016-05-26T16:24:35Z | 37,466,362 | <p>Use <a href="https://docs.python.org/2/library/functools.html#functools.partial" rel="nofollow">functools.partial</a>:</p>
<pre><code>Python 2.7.6 (default, Jun 22 2015, 17:58:13)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from functools import partial... | 4 | 2016-05-26T16:27:16Z | [
"python",
"function",
"inheritance",
"keyword-argument"
] |
Assigning a topic to each document in a corpus (LDA) | 37,466,345 | <p>I am trying to compute the probability of a document to belong to each topic found by the LDA model. I have succeded in producing the LDA but now I am stuck. My code goes as following:</p>
<pre><code>## Libraries to download
from nltk.tokenize import RegexpTokenizer
from nltk.corpus import stopwords
from nltk.stem.... | 0 | 2016-05-26T16:26:23Z | 37,469,364 | <p>As I hope you've read elsewhere, the threshold is an application-specific setting, depending on how broad you want your classification model. The 1/k (for k clusters) rationale is empirical: it works as a starting point (i.e. it yields recognizably useful results) for most classification tasks.</p>
<p>The gut-leve... | 1 | 2016-05-26T19:20:40Z | [
"python",
"pandas",
"lda"
] |
Pandas merging data from specific column | 37,466,364 | <p>I am trying to merge data to create a new dataframe. I have two dataframes and am trying to print KEYS Value to the third dataframe if it equals any of the numbers in the following columns</p>
<pre><code>df2
0 1 2 3 4 \
KEYS ... | 0 | 2016-05-26T16:27:27Z | 37,467,325 | <h3>Setup</h3>
<pre><code>import pandas as pd
from StringIO import StringIO
text2 = """KEYS 0 1 2 3 4
FIT-3982 2024.0016 0101.0007 None None None
FIT-3980 1140.0107 None None None None
FIT-3979 1907.00... | 1 | 2016-05-26T17:19:33Z | [
"python",
"csv",
"pandas"
] |
Pandas merging data from specific column | 37,466,364 | <p>I am trying to merge data to create a new dataframe. I have two dataframes and am trying to print KEYS Value to the third dataframe if it equals any of the numbers in the following columns</p>
<pre><code>df2
0 1 2 3 4 \
KEYS ... | 0 | 2016-05-26T16:27:27Z | 37,467,762 | <p>You can <code>stack</code> <code>df2</code>, do some quick formatting, and then use <code>merge</code>:</p>
<pre><code>df2 = df2.stack().reset_index(level=0).rename(columns={0: 'TC_NUM'})
result = df1.merge(df2, how='left', on=['TC_NUM'])'
</code></pre>
<p>The resulting output:</p>
<pre><code> ... | 3 | 2016-05-26T17:45:33Z | [
"python",
"csv",
"pandas"
] |
How do I open up the web.py server to the web? | 37,466,424 | <p>I would like people on the web to be able to enter something into the address bar of their browser and use the web.py app I have written. I have it working properly when I type localhost:8080/app but I want other people to be able to use it, with my home computer acting as the server. I know this must be an obvious ... | 1 | 2016-05-26T16:30:04Z | 37,466,527 | <p>First you need to find your external IP google("what is my IP")</p>
<p><a href="http://i.stack.imgur.com/9dscP.png" rel="nofollow"><img src="http://i.stack.imgur.com/9dscP.png" alt="enter image description here"></a></p>
<p>Second you need to set up a port forward on your router to redirect traffic from an externa... | 0 | 2016-05-26T16:35:25Z | [
"python",
"web.py"
] |
How do I open up the web.py server to the web? | 37,466,424 | <p>I would like people on the web to be able to enter something into the address bar of their browser and use the web.py app I have written. I have it working properly when I type localhost:8080/app but I want other people to be able to use it, with my home computer acting as the server. I know this must be an obvious ... | 1 | 2016-05-26T16:30:04Z | 37,466,654 | <p>First you need to set up port forwarding on your router: Configure it so port 80 of your router forwards to port 8080 of your computer. (You can find your computers internal IP-address in your operating systems network config) You might also need to set your computer to use a static IP-address and disable DHCP.</p>
... | 0 | 2016-05-26T16:41:30Z | [
"python",
"web.py"
] |
Move namepaces in soap enevlope to payload level in python | 37,466,490 | <p>I am using suds-jurko (0.6) with python 2.7</p>
<p>Current soap request generated</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><?xml version="1.0" encoding="UTF-8"?>
<SOAP... | 0 | 2016-05-26T16:33:31Z | 37,468,598 | <p>I found workaround to move namspaces. Not sure if its the best way but its working.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code> def marshalled(self, context):
context.envelope... | 0 | 2016-05-26T18:34:52Z | [
"python",
"soap",
"suds"
] |
Rotation/translation of vtk 3D image with interpolation (python) | 37,466,581 | <p>I have 2 matrix:</p>
<pre><code>#for example
rotation = matrix([[ 0.61782155, 0.78631834, 0. ],
[ 0.78631834, -0.61782155, 0. ],
[ 0. , 0. , -1. ]])
translation = matrix([[-0.33657291],
[ 1.04497454],
[ 0. ]])
vtkinputpath... | 0 | 2016-05-26T16:37:56Z | 37,469,151 | <p>I'm not sure there is specific Python documentation, but this can be useful to understand how RotateWXYZ works: <a href="http://www.vtk.org/doc/nightly/html/classvtkTransform.html#a9a6bcc6b824fb0a9ee3a9048aa6b262c" rel="nofollow">http://www.vtk.org/doc/nightly/html/classvtkTransform.html#a9a6bcc6b824fb0a9ee3a9048aa6... | 1 | 2016-05-26T19:07:43Z | [
"python",
"image-processing",
"interpolation",
"vtk",
"image-rotation"
] |
How to merge two data frames based on different column names | 37,466,614 | <pre><code>import pandas as pd
left = pd.DataFrame({'A': ['A1', 'A1', 'A2', 'A3'],
'B': ['B0', 'B1', 'B2', 'B3'],
'C': ['K0', 'K1', 'K0', 'K1']})
right = pd.DataFrame({'AA': ['A1', 'A3'],
'BB': ['B0', 'B3'],
'CC': ['K0', 'K1'],
... | 1 | 2016-05-26T16:39:40Z | 37,467,197 | <p>It looks like you want to <a href="http://pandas.pydata.org/pandas-docs/stable/merging.html" rel="nofollow">merge</a>.</p>
<p>However at the moment the columns names don't match up (A is AA in <code>right</code>).<br>
So first let's normalize them:</p>
<pre><code>In [11]: right.columns = right.columns.map(lambda x... | 1 | 2016-05-26T17:11:57Z | [
"python",
"pandas"
] |
How to merge two data frames based on different column names | 37,466,614 | <pre><code>import pandas as pd
left = pd.DataFrame({'A': ['A1', 'A1', 'A2', 'A3'],
'B': ['B0', 'B1', 'B2', 'B3'],
'C': ['K0', 'K1', 'K0', 'K1']})
right = pd.DataFrame({'AA': ['A1', 'A3'],
'BB': ['B0', 'B3'],
'CC': ['K0', 'K1'],
... | 1 | 2016-05-26T16:39:40Z | 37,467,438 | <p>Use pandas <code>merge</code> method with <code>left_on</code> and <code>right_on</code> parameters.</p>
<pre><code>left.merge(right, how='left',
left_on=['A', 'B', 'C'],
right_on=['AA', 'BB', 'CC'])[['A', 'B', 'C', 'DD']]
</code></pre>
<p>gets you:</p>
<pre><code> A B C DD
0 A1 B0 ... | 1 | 2016-05-26T17:25:45Z | [
"python",
"pandas"
] |
Using python dictionary in for loop | 37,466,616 | <p>I am developing a project using django.
I am using python dictionary to display data in for loop. I have set a dynamic key as per my requirement in dictionary using following code.</p>
<pre><code>abc = {}
for user in users
abc[user] = "some dynamic data"
context = {
'contributors ': abc
}
ret... | 0 | 2016-05-26T16:39:44Z | 37,466,674 | <p>To iterate a dict in django template you need to use <code>items</code>:</p>
<pre><code>{% for contributor, dynamic_data in contributors.items %}
{{ user }} {{ dynamic_data }}
{% endfor %}
</code></pre>
| 4 | 2016-05-26T16:42:40Z | [
"python",
"django",
"dictionary"
] |
How to plot binary colored histogram in Python? | 37,466,650 | <p>I'm working on a binary classification project with several quantitative variables. I'd like to plot a histogram like below in the exploratory analysis phase. However, after researching on-line for two days, I still could find a solution in Python. </p>
<p>In R, I know how to that with the one-line code: <code>ggpl... | -2 | 2016-05-26T16:41:25Z | 37,467,052 | <p>To get an overlaid bargraph like that in seaborn it is slightly more involved than the one line code from R.</p>
<p>You actually need to create two plots, one for the 'background' and one for the 'foreground' </p>
<pre><code>stacked_bar_data["total"] = stacked_bar_data.Series1 + stacked_bar_data.Series2 # Creates ... | -2 | 2016-05-26T17:04:10Z | [
"python",
"matplotlib",
"seaborn"
] |
Get MAC using scapy and an IP | 37,466,842 | <p>I'm sending an ARP request using this line and what I basically want is to get the MAC from what's returned:</p>
<pre><code>result = sr(ARP(op=ARP.who_has, psrc='X.X.X.X', pdst='Y.Y.Y.Y'))
</code></pre>
<p>how would I retrieve the mac from result[0]?</p>
| 0 | 2016-05-26T16:52:20Z | 37,485,545 | <p>You can print the target hardware address like this:</p>
<pre><code>print result[0][ARP].hwsrc
</code></pre>
| 2 | 2016-05-27T14:06:32Z | [
"python",
"linux",
"get",
"scapy",
"arp"
] |
Using DataFrame.apply with a lambda function to assign returned tuple/list to multiple columns | 37,467,001 | <p>I have a function which takes a single input and returns a list of two values</p>
<pre><code>def my_func(x):
return [x+1, x+2]
</code></pre>
<p>Say I have a simple dataframe</p>
<pre><code>df = pd.DataFrame({'x':[1,2,3,4,5]})
</code></pre>
<p>I'd like to apply my_func to each value of column 'x' and then sav... | 3 | 2016-05-26T17:01:35Z | 37,467,140 | <p>I don't think you need to do an apply here:</p>
<pre><code>In [11]: df["y"], df["z"] = my_func(df.x)
In [12]: df
Out[12]:
x y z
0 1 2 3
1 2 3 4
2 3 4 5
3 4 5 6
4 5 6 7
</code></pre>
| 3 | 2016-05-26T17:08:18Z | [
"python",
"pandas"
] |
TypeError: expected a character buffer object When execute a translate function | 37,467,043 | <p>It's for removing punctuation of a <code>str</code>.</p>
<pre><code>tbl = dict.fromkeys(i for i in xrange(sys.maxunicode)
if unicodedata.category(unichr(i)).startswith('P'))
def remove_punctuation(text):
return text.translate(tbl)
remove_punctuation(',')
</code></pre>
<p>But it shows the... | -1 | 2016-05-26T17:03:45Z | 37,467,260 | <p><code>text.translate()</code> is expecting a string. Make sure you convert <code>tbl</code> to a string first.</p>
<pre><code>def remove_punctuation(text):
return text.translate(str(tbl))
</code></pre>
<p>UPDATE:</p>
<p>Or, as <a href="http://stackoverflow.com/users/279627/sven-marnach">Sven Marnach</a> ment... | -1 | 2016-05-26T17:15:27Z | [
"python",
"unicode"
] |
Can't run migrations when setting up a project with cookiecutter-django | 37,467,088 | <p>I have been trying to set up a new django project locally with cookiecutter-django. I have followed the docs but I keep getting into errors when trying to run <code>python manage.py migrate</code>. </p>
<p>Error Traceback.</p>
<pre><code>Traceback (most recent call last):
File "manage.py", line 10, in <module&g... | 2 | 2016-05-26T17:05:33Z | 37,468,834 | <p>Cookiecutter uses the slug of the project name as the name for the development db you are to use. You are expected to create the database yourself.</p>
<p>from your stacktrace here is the line giving you the problem from your settings.py file:</p>
<pre><code>File "/home/ubuntu/lasbrisas_project/django_condominios/... | 1 | 2016-05-26T18:48:34Z | [
"python",
"django",
"cookiecutter-django"
] |
Python Pandas - combining 2 lines from data frame - with condition | 37,467,146 | <p>I have a Pandas data frame that looks like that:</p>
<pre><code>A B C Stime Etime
1220627 a 10.0 18:00:00 18:09:59
1220627 a 12.0 18:15:00 18:26:59
1220683 b 3.0 18:36:00 18:38:59
1220683 a 3.0 18:36:00 18:38:59
1220732 a 59.0 18:00:00 18:58:59
1220760 A 16.0 18:24:00 18:39:59
1220... | 1 | 2016-05-26T17:08:48Z | 37,467,692 | <p>If we add one second to <code>Etime</code> then we can find rows to be joined by grouping by <code>['A', 'B']</code> and then for each group comparing shifted <code>Etime</code>s with the next <code>Stime</code>:</p>
<pre><code>df['Etime'] += pd.Timedelta(seconds=1)
df = df.sort_values(by=['A', 'B', 'Stime'])
df['k... | 3 | 2016-05-26T17:41:13Z | [
"python",
"datetime",
"pandas"
] |
Python Pandas - combining 2 lines from data frame - with condition | 37,467,146 | <p>I have a Pandas data frame that looks like that:</p>
<pre><code>A B C Stime Etime
1220627 a 10.0 18:00:00 18:09:59
1220627 a 12.0 18:15:00 18:26:59
1220683 b 3.0 18:36:00 18:38:59
1220683 a 3.0 18:36:00 18:38:59
1220732 a 59.0 18:00:00 18:58:59
1220760 A 16.0 18:24:00 18:39:59
1220... | 1 | 2016-05-26T17:08:48Z | 37,468,396 | <p>what about this approach?</p>
<pre><code>In [68]: df.groupby(['A','B', df.Stime - df['Etime'].shift() <= pd.Timedelta('1S')], as_index=False)['C'].sum()
Out[68]:
A B C
0 1220627 a 22.0
1 1220683 a 3.0
2 1220683 b 3.0
3 1220732 a 59.0
4 1220760 A 35.0
5 1220760 a 35.0
6 1220760 ... | 1 | 2016-05-26T18:22:12Z | [
"python",
"datetime",
"pandas"
] |
Python Pandas - combining 2 lines from data frame - with condition | 37,467,146 | <p>I have a Pandas data frame that looks like that:</p>
<pre><code>A B C Stime Etime
1220627 a 10.0 18:00:00 18:09:59
1220627 a 12.0 18:15:00 18:26:59
1220683 b 3.0 18:36:00 18:38:59
1220683 a 3.0 18:36:00 18:38:59
1220732 a 59.0 18:00:00 18:58:59
1220760 A 16.0 18:24:00 18:39:59
1220... | 1 | 2016-05-26T17:08:48Z | 37,514,169 | <p>Ok I think have a solution, but it is very crude and I'm sure someone can improve upon it.</p>
<p>assuming <code>df =</code> the data you have provided above:</p>
<pre><code>df['Stime'] = pd.to_datetime(df['Stime'], format='%H:%M:%S') # needs to be converted to datetime
df['Etime'] = pd.to_datetime(df['Etime'], fo... | 0 | 2016-05-29T19:41:37Z | [
"python",
"datetime",
"pandas"
] |
Python - How do I use user input as an array name? | 37,467,207 | <p>I'm making a game where someone can select a square via notation and then perform an action on that square. Think chess, i.e. perform action on a2 or a3.</p>
<p>I need a2, for example, to be an array. How can I take a user's input and make it the name of the array?</p>
<p>I can basically make it work with:</p>
<p... | 0 | 2016-05-26T17:12:23Z | 37,467,276 | <p>Use a dictionary:</p>
<pre><code>h = {}
if user_input == "a2":
h["a2"] = ["value 1"]
elif user_input == "a3":
h["a3"] = ["value 1"]
</code></pre>
<p>Now, the good thing is that you can factorize your code:</p>
<pre><code>h = {}
h[user_input] = ["value 1"]
</code></pre>
| 0 | 2016-05-26T17:16:47Z | [
"python",
"arrays",
"list"
] |
Python - How do I use user input as an array name? | 37,467,207 | <p>I'm making a game where someone can select a square via notation and then perform an action on that square. Think chess, i.e. perform action on a2 or a3.</p>
<p>I need a2, for example, to be an array. How can I take a user's input and make it the name of the array?</p>
<p>I can basically make it work with:</p>
<p... | 0 | 2016-05-26T17:12:23Z | 37,467,357 | <p>Using a <code>dict</code>, you'll be able to set keys at runtime:</p>
<pre><code>board = dict()
square = user_input
board[square] = ["value 1"]
</code></pre>
<p>This will free you of the need to handle all squares one by one in the code, which is I think your question was about.</p>
| 0 | 2016-05-26T17:21:31Z | [
"python",
"arrays",
"list"
] |
Decouple module error running Django 1.8 project using Django 1.9 | 37,467,213 | <p>Currently, I am using latest version of Django 1.9.
I have a project that is written in Django 1.8</p>
<p>When I tried to runserver, I encountered the following error </p>
<p><a href="http://i.stack.imgur.com/CrWcW.png" rel="nofollow">enter image description here</a></p>
<p>What should I do as I do not want to do... | 0 | 2016-05-26T17:12:32Z | 37,467,278 | <p>It is not because you use Django 1.9 that you get that error, it is because that module is not install at the moment. Run <code>pip install python-decouple</code> to install the module.</p>
| 1 | 2016-05-26T17:16:59Z | [
"python",
"django"
] |
How can I find out which alternate regular expression matched my string | 37,467,287 | <p>If I have a regular expression which has a <code>|</code> operator separating two possible patterns. Is it possible to find which pattern was the one that matched my string? </p>
<p>For example, if I have the pattern <code>([cC]at|[dD]og)</code> and I find a match in the string <code>clifford is a dog</code>. Can I... | 0 | 2016-05-26T17:17:27Z | 37,467,490 | <p>You can use two different groups and check its index, like this:</p>
<pre><code>([cC]at)|([dD]og)
</code></pre>
<p><img src="https://www.debuggex.com/i/9sP5TVC4dQ8ggOU2.png" alt="Regular expression visualization"></p>
<p><strong><a href="https://regex101.com/r/mJ2yD2/1" rel="nofollow">Regex demo</a></strong></p>
... | 1 | 2016-05-26T17:28:47Z | [
"python",
"regex"
] |
converting string to int: Python | 37,467,328 | <p>I have a Series Dataobject which have dtype as object.
It contains int in str format as well as many strings. I want to convert only int to int type and del rest.</p>
<p>Example:</p>
<pre><code>'1','3','sd34','4','r5'
</code></pre>
<p>Result:</p>
<pre><code>[1, 3, 4]
</code></pre>
| -1 | 2016-05-26T17:19:44Z | 37,467,359 | <p>Here's a simple one-liner.</p>
<pre><code>output = [int(s) for s in data_list if s.isdecimal()]
</code></pre>
<p>You may also use a generator expression in case the dataset is large. This will be much more memory efficient for a single iteration over the data.</p>
<pre><code>output_gen = (int(s) for s in data_lis... | 5 | 2016-05-26T17:21:39Z | [
"python"
] |
converting string to int: Python | 37,467,328 | <p>I have a Series Dataobject which have dtype as object.
It contains int in str format as well as many strings. I want to convert only int to int type and del rest.</p>
<p>Example:</p>
<pre><code>'1','3','sd34','4','r5'
</code></pre>
<p>Result:</p>
<pre><code>[1, 3, 4]
</code></pre>
| -1 | 2016-05-26T17:19:44Z | 37,467,369 | <pre><code>data = ['1','3','sd34','4','r5']
result = []
for d in data:
try:
result.append(int(d))
except:
pass
</code></pre>
| -1 | 2016-05-26T17:22:08Z | [
"python"
] |
dict(list(tuple)) vs {list(tuple)}? | 37,467,339 | <p>Why does <code>dict(list(tuple))</code> work but not <code>{list(tuple)}</code>
E.g.</p>
<pre><code>>>> dict([('b', 456), ('a', 123)])
{'a': 123, 'b': 456}
>>> {[('b', 456), ('a', 123)]}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type... | 0 | 2016-05-26T17:20:09Z | 37,467,424 | <p><code>{}</code> can be used for both sets and dictionaries. For example, <code>{8: 2}</code> is a dictionary, but <code>{1, 2, 3, 4}</code> is a set. Since you gave no key, Python assumes that you want a set. A set depends on having hashable items, so it complains when you give it a list.</p>
<p>If you want to u... | 7 | 2016-05-26T17:25:02Z | [
"python",
"list",
"dictionary",
"initialization",
"tuples"
] |
dict(list(tuple)) vs {list(tuple)}? | 37,467,339 | <p>Why does <code>dict(list(tuple))</code> work but not <code>{list(tuple)}</code>
E.g.</p>
<pre><code>>>> dict([('b', 456), ('a', 123)])
{'a': 123, 'b': 456}
>>> {[('b', 456), ('a', 123)]}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type... | 0 | 2016-05-26T17:20:09Z | 37,467,502 | <p>Just like with <code>["asdf"]</code> and <code>list("asdf")</code> or <code>str(thing)</code> and <code>"thing"</code>, calling the dict constructor on a thing does something completely different from surrounding it with braces.</p>
<p>When you construct a dict with braces, you're supposed to write out key-value pa... | 3 | 2016-05-26T17:29:45Z | [
"python",
"list",
"dictionary",
"initialization",
"tuples"
] |
dict(list(tuple)) vs {list(tuple)}? | 37,467,339 | <p>Why does <code>dict(list(tuple))</code> work but not <code>{list(tuple)}</code>
E.g.</p>
<pre><code>>>> dict([('b', 456), ('a', 123)])
{'a': 123, 'b': 456}
>>> {[('b', 456), ('a', 123)]}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type... | 0 | 2016-05-26T17:20:09Z | 37,467,601 | <p><code>dict</code> is a class and when you use <code>dict(list(tuple))</code> it instantiate the class using constructor.</p>
<p>Looking at the documentation for <a href="https://docs.python.org/2/library/stdtypes.html#dict" rel="nofollow"><code>dict</code></a>:</p>
<blockquote>
<p>Dictionaries can be created by ... | 1 | 2016-05-26T17:35:25Z | [
"python",
"list",
"dictionary",
"initialization",
"tuples"
] |
dict(list(tuple)) vs {list(tuple)}? | 37,467,339 | <p>Why does <code>dict(list(tuple))</code> work but not <code>{list(tuple)}</code>
E.g.</p>
<pre><code>>>> dict([('b', 456), ('a', 123)])
{'a': 123, 'b': 456}
>>> {[('b', 456), ('a', 123)]}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type... | 0 | 2016-05-26T17:20:09Z | 37,467,712 | <p><code>dict(list(tuple))</code> create a new dict use the <code>dict()</code> constructor. And here is what he does </p>
<pre><code>def __init__(self, seq=None, **kwargs): # known special case of dict.__init__
"""
dict() -> new empty dictionary
dict(mapping) -> new dictionary initialize... | 0 | 2016-05-26T17:42:14Z | [
"python",
"list",
"dictionary",
"initialization",
"tuples"
] |
How do I switch been text and binary write mode in Python 3? | 37,467,358 | <p>I recently switched to Python 3. In my code I had a numpy save as text command </p>
<pre><code>f_handle = open('results.log','a')
f_handle.write('Some text')
numpy.savetxt(f_handle, X, delimiter=',', fmt='%.4f')
</code></pre>
<p>In Python 3 this causes an error for the numpy command, the flag needs to be 'ab', t... | 2 | 2016-05-26T17:21:36Z | 37,467,627 | <p>You can just encode text before write:</p>
<pre><code>with open('results.log','ab') as f_handle:
f_handle.write('Some text...'.encode('utf-8'))
</code></pre>
| 2 | 2016-05-26T17:36:51Z | [
"python",
"python-3.x",
"numpy",
"io"
] |
How do I switch been text and binary write mode in Python 3? | 37,467,358 | <p>I recently switched to Python 3. In my code I had a numpy save as text command </p>
<pre><code>f_handle = open('results.log','a')
f_handle.write('Some text')
numpy.savetxt(f_handle, X, delimiter=',', fmt='%.4f')
</code></pre>
<p>In Python 3 this causes an error for the numpy command, the flag needs to be 'ab', t... | 2 | 2016-05-26T17:21:36Z | 37,470,157 | <p>You can create a binary string with the <code>b</code> flag.</p>
<pre><code>In [101]: with open('test.txt','wb') as f:
.....: f.write(b'some binary string text\n')
</code></pre>
<p>I use that when creating test strings from <code>genfromtxt</code> (which also insists on working with byte files.</p>
<pre><c... | 1 | 2016-05-26T20:14:32Z | [
"python",
"python-3.x",
"numpy",
"io"
] |
Getting an Trueerror message | 37,467,382 | <p>I am getting the error "TypeError: range() integer end argument expected, got list." Not sure what to do about it. Thanks for the help!</p>
<pre><code>if iput == 1:
numresistors = [input("Number of resistors?")]
if numresistors == [2]:
r1 = raw_input("Enter first resistor:")
r2 = raw_input("... | -1 | 2016-05-26T17:22:57Z | 37,467,472 | <p><code>numresistors</code> is being stored as a list containing a single value</p>
<pre><code> numresistors = [input("Number of resistors?")]
</code></pre>
<p>The error you are getting is saying that the <code>range</code> function doesn't know what to do with a list. You could either call <code>range</code> with t... | 1 | 2016-05-26T17:27:52Z | [
"python",
"python-2.7"
] |
What is the correct way to customize standard features in Pinax? | 37,467,473 | <p>I want to make a somewhat cross-cutting change to <a href="https://github.com/Stackato-Apps/pinax-social" rel="nofollow">Pinax social</a>'s behavior that at least touches representation of the user and access to forums, groups, and possibly other features.</p>
<p>AFAICT most of the things I would like to now change... | 0 | 2016-05-26T17:27:52Z | 37,668,039 | <p><strong>Short answer:</strong> The best option is a good software engineer's last choice: directly customize the code. The functionality needs to run through the middle of certain apps; I'm not quite saying that there <em>is</em> no way to build the kind of site I had in mind just by stacking Lego-like apps on top o... | 0 | 2016-06-06T22:55:09Z | [
"python",
"django",
"pinax"
] |
Getting scipy's rv_discrete to work with floating point values? | 37,467,486 | <p>I'm trying to define my own discrete distribution. The code I have works for integer values but not for decimal values. For example, this works:</p>
<pre><code>>>> from scipy.stats import rv_discrete
>>> probabilities = [0.2, 0.5, 0.3]
>>> values = [1, 2, 3]
>>> distrib = rv_disc... | 0 | 2016-05-26T17:28:29Z | 37,467,897 | <p>Per <a href="http://docs.scipy.org/doc/scipy-0.17.0/reference/generated/scipy.stats.rv_discrete.html" rel="nofollow"><code>stats.rv_discrete</code>'s doc string</a>:</p>
<blockquote>
<p>values : tuple of two array_like, optional
<code>(xk, pk)</code> where <code>xk</code> are <strong>integers</strong> w... | 2 | 2016-05-26T17:53:28Z | [
"python",
"numpy",
"scipy"
] |
Python find index of all array elements in another array | 37,467,515 | <p>I am trying to do the following: </p>
<pre><code>import numpy as np
A = np.array([1,5,2,7,1])
B = np.sort(A)
print B
>>> [1,1,2,5,7]
</code></pre>
<p>I want to find the location of all elements in B as in original array A. i.e. I want to create an array C such that</p>
<pre><code>print C
>>[0,4,2,1... | 2 | 2016-05-26T17:30:49Z | 37,467,583 | <pre><code>import numpy as np
A = np.array([1,5,2,7,1])
print np.argsort(A) #prints [0 4 2 1 3]
</code></pre>
| 9 | 2016-05-26T17:34:31Z | [
"python",
"numpy"
] |
Python find index of all array elements in another array | 37,467,515 | <p>I am trying to do the following: </p>
<pre><code>import numpy as np
A = np.array([1,5,2,7,1])
B = np.sort(A)
print B
>>> [1,1,2,5,7]
</code></pre>
<p>I want to find the location of all elements in B as in original array A. i.e. I want to create an array C such that</p>
<pre><code>print C
>>[0,4,2,1... | 2 | 2016-05-26T17:30:49Z | 37,468,460 | <p>If you don't want to imporr numpy for any reason you can also use this code:</p>
<pre><code>a = [1,5,2,7,1]
b = zip(a, range(len(a)))
tmp = sorted(b, key=lambda x: x[0])
c = map( lambda x: x[1], tmp)
print c
</code></pre>
<blockquote>
<p>[0, 4, 2, 1, 3]</p>
</blockquote>
| 3 | 2016-05-26T18:25:43Z | [
"python",
"numpy"
] |
Python find index of all array elements in another array | 37,467,515 | <p>I am trying to do the following: </p>
<pre><code>import numpy as np
A = np.array([1,5,2,7,1])
B = np.sort(A)
print B
>>> [1,1,2,5,7]
</code></pre>
<p>I want to find the location of all elements in B as in original array A. i.e. I want to create an array C such that</p>
<pre><code>print C
>>[0,4,2,1... | 2 | 2016-05-26T17:30:49Z | 37,468,825 | <p><a href="https://repl.it/CVbI" rel="nofollow">https://repl.it/CVbI</a></p>
<pre><code>A = [1,5,2,7,1]
for i,e in sorted(enumerate(A), key=lambda x: x[1]):
print(i, e)
B = [x for x,_ in sorted(enumerate(A), key=lambda x: x[1])]
A = sorted(A)
print(A)
print(B)
</code></pre>
| 1 | 2016-05-26T18:47:55Z | [
"python",
"numpy"
] |
Keras model to Theano function | 37,467,538 | <p>I am trying to convert a trained model (code given below) to a theano function. But I am getting the following error: <code>AttributeError: 'Dense' object has no attribute 'output'</code>. </p>
<p>The code for my model: </p>
<pre><code>model = Sequential()
model.add(Convolution2D(32, 3, 3, border_mode='same',
... | 2 | 2016-05-26T17:32:23Z | 37,472,741 | <p>Try <code>model.layers[-1].get_output(train=False)</code>. The <a href="http://keras.io/getting-started/faq/#how-can-i-visualize-the-output-of-an-intermediate-layer" rel="nofollow">original Keras tutorial</a> may be outdated.</p>
| 1 | 2016-05-26T23:46:44Z | [
"python",
"deep-learning",
"keras"
] |
Renaming multiple files in a directory using Python | 37,467,561 | <p>I'm trying to rename multiple files in a directory using this Python script:</p>
<pre><code>import os
path = '/Users/myName/Desktop/directory'
files = os.listdir(path)
i = 1
for file in files:
os.rename(file, str(i)+'.jpg')
i = i+1
</code></pre>
<p>When I run this script, I get the following error:</p>
<... | 0 | 2016-05-26T17:33:22Z | 37,467,669 | <p>You are not giving the whole path while renaming, do it like this:</p>
<pre><code>import os
path = '/Users/myName/Desktop/directory'
files = os.listdir(path)
i = 1
for file in files:
os.rename(os.path.join(path, file), os.path.join(path, str(i)+'.jpg'))
i = i+1
</code></pre>
<p><strong>Edit</strong>: Than... | 3 | 2016-05-26T17:40:35Z | [
"python",
"directory",
"rename"
] |
Something like __pycache__ for Python 2.x? | 37,467,733 | <p>I would like to avoid cluttering up my working directory with Python bytecode <code>*.pyc</code> files. Python 3.2+ <a href="https://docs.python.org/dev/whatsnew/3.2.html#pep-3147-pyc-repository-directories" rel="nofollow">uses a subdirectory</a> called <code>__pycache__</code> for this purpose.</p>
<p>Since many o... | 2 | 2016-05-26T17:43:20Z | 37,467,792 | <p>You can try the <code>-B</code> option of Python:</p>
<pre><code>-B : don't write .py[co] files on import; also PYTHONDONTWRITEBYTECODE=x
</code></pre>
<p>So, you can run <code>python -B test.py</code> or set <code>PYTHONDONTWRITEBYTECODE</code> appropriately.</p>
| 0 | 2016-05-26T17:46:59Z | [
"python",
"python-2.7",
"bytecode"
] |
Python JSON Iteration into a POST request | 37,467,810 | <p>I have a JSON file that is formatted something like</p>
<pre><code>{
"unknown1":
[
{"text": "random text again",
"time": "Thu May 15 19:21:59 +0000 2016"},
"text": "akmfkdlm safsa fasffalmfa",
"time": "Thu May 21 09:53:51 +0000 2016"}
]
"unknown2":
[
"text":... | 0 | 2016-05-26T17:48:02Z | 37,468,109 | <p>Assuming you have a valid json. You first need to traverse the list corresponding to "unknown" keys, now this list again contains dictionaries
with <code>text</code> <code>time</code> keys.</p>
<pre><code>for unknown_key in data:
for obj in data[unknown_key]:
body = { "text": obj['text'] , "mime_type":... | 1 | 2016-05-26T18:05:27Z | [
"python",
"json",
"rest",
"http-post",
"httprequest"
] |
Python JSON Iteration into a POST request | 37,467,810 | <p>I have a JSON file that is formatted something like</p>
<pre><code>{
"unknown1":
[
{"text": "random text again",
"time": "Thu May 15 19:21:59 +0000 2016"},
"text": "akmfkdlm safsa fasffalmfa",
"time": "Thu May 21 09:53:51 +0000 2016"}
]
"unknown2":
[
"text":... | 0 | 2016-05-26T17:48:02Z | 37,477,661 | <p>About the part 1 of your question:</p>
<pre><code>for thing in data:
for text, time in data.iteritems():
</code></pre>
<p>With this loop you won't get the <code>text</code>. Your update with:</p>
<pre><code>for thing in data:
for text in data[thing]:
print text['text']
</code></pre>
<p>is correct... | 1 | 2016-05-27T07:42:35Z | [
"python",
"json",
"rest",
"http-post",
"httprequest"
] |
Python: Directional Navigation in 2d Array | 37,467,812 | <p><strong>TLDR: I want to navigate all directions in a 2D array starting at the center</strong></p>
<p>I am trying to do a particular navigation in a 2D Python array. Say I have this 2D array (A1):</p>
<p><a href="http://i.stack.imgur.com/JNVLx.png" rel="nofollow"><img src="http://i.stack.imgur.com/JNVLx.png" alt="e... | 0 | 2016-05-26T17:48:19Z | 37,485,783 | <p>It looks like you are trying to do <a href="http://setosa.io/ev/image-kernels/" rel="nofollow">kernel convolution</a>, yes?</p>
<p>Where are midRow, midColumn, and average defined in your example?</p>
<p>Why do you have to start in the center of A2? Summation and multiplication are both commutative operations, so... | 0 | 2016-05-27T14:17:40Z | [
"python",
"arrays"
] |
I cannot append my data to a list | 37,467,850 | <p>I am trying to append the total area to the attribute table and it runs through without any error message. I am not sure what I'm doing wrong:</p>
<pre><code>import os
import arcpy
import math
folderpath = 'C:\Users\Michaelf\Desktop\GEOG M173'
arcpy.env.workspace = folderpath
arcpy.env.overwriteOutput = True
input_... | -2 | 2016-05-26T17:50:41Z | 37,489,046 | <p>Firstly: You've got a data type issue when you're adding that list of fields.</p>
<p>This code simply adds a field named <code>totarea</code>, and doesn't do anything with the data in the <code>fields</code> list.</p>
<pre><code>for field in fields:
arcpy.AddField_management(equal_shape, "totarea")
</code></pr... | 0 | 2016-05-27T17:14:08Z | [
"python",
"arcpy",
"cursors"
] |
environment settings in my django app are set to debug false but in production it acts as if its true | 37,467,911 | <p>I have local and production settings for my django app that import from base like so</p>
<pre><code>from .base import *
try:
from .local import *
except:
pass
try:
from .production import *
except:
pass
</code></pre>
<p>and in my base I have</p>
<pre><code>import os
import dj_database_url
from .... | 0 | 2016-05-26T17:54:20Z | 37,468,018 | <p>Look at the order of the settings file:</p>
<ul>
<li>first it imports from base: DEBUG is False</li>
<li>then it imports from local: DEBUG is True </li>
<li>then it imports from production: at this point, DEBUG is True, so your <code>if not settings.DEBUG:</code> block is never entered, and DEBUG is not set to Fals... | 1 | 2016-05-26T18:00:34Z | [
"python",
"django",
"development-environment",
"production-environment"
] |
environment settings in my django app are set to debug false but in production it acts as if its true | 37,467,911 | <p>I have local and production settings for my django app that import from base like so</p>
<pre><code>from .base import *
try:
from .local import *
except:
pass
try:
from .production import *
except:
pass
</code></pre>
<p>and in my base I have</p>
<pre><code>import os
import dj_database_url
from .... | 0 | 2016-05-26T17:54:20Z | 37,487,389 | <p>ultimately this is what worked for me</p>
<pre><code>from .base import *
if os.getenv('_system_name') == 'OSX':
from .local import *
else:
from .production import *
</code></pre>
<p>I don't understand why tutorials make this so complicated. I ran printenv to look at the variables I was creating and try t... | 0 | 2016-05-27T15:35:28Z | [
"python",
"django",
"development-environment",
"production-environment"
] |
ArgumentParser.add_mutually_exclusive_group | 37,467,983 | <p>I came across this method in Python:</p>
<pre><code>ArgumentParser.add_mutually_exclusive_group
</code></pre>
<p>In the description, it mentioned:</p>
<pre><code>Create a mutually exclusive group.
</code></pre>
<p>What does a <code>mutually exclusive group</code> mean in this context? Is there a simple example t... | -1 | 2016-05-26T17:58:15Z | 37,468,047 | <p>The <a href="https://docs.python.org/2/library/argparse.html" rel="nofollow">documentation</a> has an explanation (emphasis mine):</p>
<blockquote>
<p>Create a mutually exclusive group. <code>argparse</code> will make sure that <strong>only one</strong> of the arguments in the mutually exclusive group was present... | 0 | 2016-05-26T18:02:15Z | [
"python"
] |
Why is creating a masked numpy array so slow with mask=None or mask=0 | 37,468,069 | <p>Today I profiled a function and I found a (at least to me) weird bottleneck: Creating a masked array with <code>mask=None</code> or <code>mask=0</code> to initialize a mask with all zeros but the same shape as the <code>data</code> is very slow:</p>
<pre><code>>>> import numpy as np
>>> data = np.... | 5 | 2016-05-26T18:03:15Z | 37,468,389 | <p><code>mask=False</code> is special-cased in the <a href="https://github.com/numpy/numpy/blob/v1.11.0/numpy/ma/core.py#L2776" rel="nofollow">NumPy 1.11.0 source code</a>:</p>
<pre><code>if mask is True and mdtype == MaskType:
mask = np.ones(_data.shape, dtype=mdtype)
elif mask is False and mdtype == MaskType:
... | 4 | 2016-05-26T18:21:45Z | [
"python",
"performance",
"numpy"
] |
Why is creating a masked numpy array so slow with mask=None or mask=0 | 37,468,069 | <p>Today I profiled a function and I found a (at least to me) weird bottleneck: Creating a masked array with <code>mask=None</code> or <code>mask=0</code> to initialize a mask with all zeros but the same shape as the <code>data</code> is very slow:</p>
<pre><code>>>> import numpy as np
>>> data = np.... | 5 | 2016-05-26T18:03:15Z | 37,468,507 | <p>I believe @user2357112 has the explanation. I profiled both cases, here are the results:</p>
<pre><code>In [14]: q.run('q.np.ma.array(q.data, mask=None, copy=False)')
49 function calls in 0.161 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
... | 1 | 2016-05-26T18:28:46Z | [
"python",
"performance",
"numpy"
] |
Python Backtracking (queens checkboard) | 37,468,085 | <p>Ok so finally after hours and hours of struggling with my head I finally understood how backtracking works. Though I still think there are secrets left to be understood. Anyways, I'm trying to create the 4-queens problem on the checkboard. Practically I'm giving myself a blank checkboard (it's 4x4 actually) and I ne... | -5 | 2016-05-26T18:04:21Z | 37,468,383 | <p>The first problem I see is the initial nested loops in this routine:</p>
<pre><code>def findNextCell(grid,i,j):
for index in range(i,4):
for jindex in range(j,4):
return index, jindex
for index in range(0,4):
for jindex in range(0,4):
if grid[index][jindex] == 0:
... | 1 | 2016-05-26T18:21:18Z | [
"python"
] |
What happens when you compare lists of different sizes? | 37,468,245 | <p>In Python, I have the two lists of different sizes:</p>
<pre><code>x = [[0,5,10],[0,10,5]]
y = [100,500,900]
</code></pre>
<p>What is the comparison happening at each step when I run:</p>
<pre><code>print x>y
</code></pre>
<p>e.g. How does it compare say the first element: [0,5,10] vs 100?</p>
| 0 | 2016-05-26T18:13:34Z | 37,468,328 | <p>Those comparisons won't work. <code>list</code> and <code>int</code> can't be compared. So it won't work</p>
| 0 | 2016-05-26T18:18:21Z | [
"python",
"list",
"comparison"
] |
What happens when you compare lists of different sizes? | 37,468,245 | <p>In Python, I have the two lists of different sizes:</p>
<pre><code>x = [[0,5,10],[0,10,5]]
y = [100,500,900]
</code></pre>
<p>What is the comparison happening at each step when I run:</p>
<pre><code>print x>y
</code></pre>
<p>e.g. How does it compare say the first element: [0,5,10] vs 100?</p>
| 0 | 2016-05-26T18:13:34Z | 37,468,335 | <p>In Python 3, you can't compare those two lists because their elements are not of comparable types.</p>
<p>In Python 2, lists are always greater than integers, period, so your <code>x</code> is always greater than your <code>y</code> regardless of what elements are in <code>x</code>'s sublists.</p>
| 4 | 2016-05-26T18:18:49Z | [
"python",
"list",
"comparison"
] |
What happens when you compare lists of different sizes? | 37,468,245 | <p>In Python, I have the two lists of different sizes:</p>
<pre><code>x = [[0,5,10],[0,10,5]]
y = [100,500,900]
</code></pre>
<p>What is the comparison happening at each step when I run:</p>
<pre><code>print x>y
</code></pre>
<p>e.g. How does it compare say the first element: [0,5,10] vs 100?</p>
| 0 | 2016-05-26T18:13:34Z | 37,468,461 | <p>The real problem is how to compare <code>[0,5,10]</code> vs <code>100</code>, i.e, a list vs an integer.</p>
<p>The answer depends on the Python version. In Python 3.x, the two types can't be compared. In Python 2.x, lists are always greater than integers because the type names <code>list</code> is greater than <co... | 1 | 2016-05-26T18:25:45Z | [
"python",
"list",
"comparison"
] |
What happens when you compare lists of different sizes? | 37,468,245 | <p>In Python, I have the two lists of different sizes:</p>
<pre><code>x = [[0,5,10],[0,10,5]]
y = [100,500,900]
</code></pre>
<p>What is the comparison happening at each step when I run:</p>
<pre><code>print x>y
</code></pre>
<p>e.g. How does it compare say the first element: [0,5,10] vs 100?</p>
| 0 | 2016-05-26T18:13:34Z | 37,468,475 | <p>Just to expand on the other answers, the documentation is pretty good on this stuff. From <a href="https://docs.python.org/2.7/tutorial/datastructures.html" rel="nofollow">the 2.7 documentation</a>:</p>
<blockquote>
<p>Sequence objects may be compared to other objects with the same sequence type. The comparison ... | 0 | 2016-05-26T18:26:24Z | [
"python",
"list",
"comparison"
] |
What happens when you compare lists of different sizes? | 37,468,245 | <p>In Python, I have the two lists of different sizes:</p>
<pre><code>x = [[0,5,10],[0,10,5]]
y = [100,500,900]
</code></pre>
<p>What is the comparison happening at each step when I run:</p>
<pre><code>print x>y
</code></pre>
<p>e.g. How does it compare say the first element: [0,5,10] vs 100?</p>
| 0 | 2016-05-26T18:13:34Z | 37,468,499 | <p>Essentially <code>x == y</code> uses the magic <code>__eq__</code> method on objects to compare them. Different objects will behave differently, and you can even define your own custom equalities, but in general comparing objects of different types will always evaluate to <code>False</code> (<a href="https://docs.py... | 0 | 2016-05-26T18:28:03Z | [
"python",
"list",
"comparison"
] |
How to re-zip Docx file contents after modification | 37,468,281 | <p>I will try to keep this short and simple. </p>
<p>I made a program that is able to modify text within the Docx document.xml file. I achieved this through xml parsing and it works great. Right now my program is outputting a new document.xml file that is exactly identical to the original one minus the altered text. ... | 0 | 2016-05-26T18:16:05Z | 38,440,903 | <p>If I'm using the original document, Word also says it would be corrupt. </p>
<p>As far as I see there are three references pointing nowhere.
If you comment out the three <code>w:headerReference</code> elements (right at the bottom as children of the <code>w:sectPr</code> element), I can open it without Word compla... | 0 | 2016-07-18T15:43:17Z | [
"python",
"xml",
"zip",
"docx",
"corrupt"
] |
Mapping on HTML escaping function in python | 37,468,340 | <p>I have the following function in Python:</p>
<pre><code>def escape_html(s):
for(i, o) in (("&", "&amp;"),
(">", "&gt;"),
(">", "&gt;"),
(">", "&gt;")):
s = s.replace(i,o)
return s
print escape_html('"hello, & = &... | -1 | 2016-05-26T18:19:13Z | 37,470,000 | <p>First, you need to understand tuple unpacking. We're iterating over a tuple of tuples, so each iteration yields one of the inner tuples. Each of those tuples has two elements, so they can be conveniently unpacked and assigned to two variables in one statement with some fancy syntax:</p>
<pre><code>for pair in (("&a... | 0 | 2016-05-26T20:03:18Z | [
"python",
"escaping",
"mapping"
] |
Tips for properly using large broadcast variables? | 37,468,405 | <p>I'm using a broadcast variable about 100 MB pickled in size, which I'm approximating with:</p>
<pre><code>>>> data = list(range(int(10*1e6)))
>>> import cPickle as pickle
>>> len(pickle.dumps(data))
98888896
</code></pre>
<p>Running on a cluster with 3 c3.2xlarge executors, and a m3.larg... | 2 | 2016-05-26T18:22:48Z | 37,489,738 | <p>Well, the devil is in the detail. To understand the reason why this may happen we'll have to take a closer look at the PySpark serializers. First lets create <code>SparkContext</code> with default settings:</p>
<pre><code>from pyspark import SparkContext
sc = SparkContext("local", "foo")
</code></pre>
<p>and chec... | 3 | 2016-05-27T18:00:56Z | [
"python",
"apache-spark",
"pyspark",
"pickle",
"rdd"
] |
Iterating over a dictionary for tuples as keys | 37,468,485 | <p>Given a dictionary like the one below there are lists which I need to convert to keys for another dictionary. </p>
<pre><code>{'timer': 100,
'blocks': [[[5, 1], {'image': 'red.gif', 'points': 10, 'delete': True}],
[[5, 2], {'image': 'red.gif', 'points': 10, 'bonus': 50, 'delete': True}],
[[... | -1 | 2016-05-26T18:26:53Z | 37,468,768 | <p>If I am right, you are looking for itervalues() and iterkeys() methods of dictionary.</p>
<p>Examples:</p>
<pre><code>for value in dictionary.itervalues():
# do stuff with value
for key in dictionary.iterkeys():
# do stuff with key
</code></pre>
<p>Edit: if you want to find tuples, use type() functio... | -1 | 2016-05-26T18:44:44Z | [
"python",
"json",
"dictionary",
"key",
"tuples"
] |
Am I using the modulo operator incorrectly? | 37,468,616 | <p>If my understanding is correct, 5 % 5 should equal 0. However when i run this code:</p>
<pre><code>endless = 0
while endless == 0:
n = int(input("Provide a number here: "))
count = 0
sum = 0
while count < n:
if 1+count % 3 == 0 | 1+count % 5 == 0:
sum += 1 + count
cou... | -1 | 2016-05-26T18:35:53Z | 37,468,674 | <p>Dont use bitwise OR, and use paranthesis (<a href="https://docs.python.org/2/reference/expressions.html#operator-precedence" rel="nofollow">operator precedence</a>)!</p>
<p>Try:</p>
<pre><code>(1+count) % 3 == 0 or (1+count) % 5 == 0:
^ ^ ^^ ^ ^
</code></pre>
| 3 | 2016-05-26T18:39:05Z | [
"python",
"syntax",
"operators",
"modulo"
] |
Am I using the modulo operator incorrectly? | 37,468,616 | <p>If my understanding is correct, 5 % 5 should equal 0. However when i run this code:</p>
<pre><code>endless = 0
while endless == 0:
n = int(input("Provide a number here: "))
count = 0
sum = 0
while count < n:
if 1+count % 3 == 0 | 1+count % 5 == 0:
sum += 1 + count
cou... | -1 | 2016-05-26T18:35:53Z | 37,468,687 | <p>The operator priority of <code>%</code> is the same as <code>/</code> and higher than <code>+</code>, that means:</p>
<pre><code>1+count % 3 == 1 + (count % 3)
</code></pre>
<p>which can never be <code>0</code> since modulo returns a value between 0 and 2.</p>
| 1 | 2016-05-26T18:40:04Z | [
"python",
"syntax",
"operators",
"modulo"
] |
ValueObject pattern in django models | 37,468,681 | <p>Currently I want to use the Value Object Pattern in my django project. I have a class <code>Price</code> like this:</p>
<pre><code>class Price(object):
def __init__(self, value, currency):
self.value = value
self.currency = currency
</code></pre>
<p>And now I want to use this class in a normal mo... | 0 | 2016-05-26T18:39:19Z | 37,468,791 | <p>I think you'd better define <code>value</code> and <code>currency</code> as fields for the model, then you could have method of the model to give you the price:</p>
<pre><code>class MyModel(Model):
CURRENCIES = Choices( ... | 1 | 2016-05-26T18:46:15Z | [
"python",
"django",
"design-patterns",
"django-models",
"value-objects"
] |
Can **0.5 return a negative number? | 37,468,746 | <p>To find the distance, I was using **0.5 to square root. Will this ever return a negative number?</p>
<pre><code>def distance(x1, y1, x2, y2):
return ((x1-x2)**2 + (y1-y2)**2)**0.5
</code></pre>
| 1 | 2016-05-26T18:43:33Z | 37,469,264 | <p>Yes, the function can return negative numbers. This requires sufficiently broken input arguments.</p>
<pre><code>class Whack(int):
def __pow__(self, other, modulo=None):
if other == 0.5:
return -42
return Whack()
def __sub__(self, other):
return Whack()
__add__ = __s... | 5 | 2016-05-26T19:14:54Z | [
"python",
"python-2.7"
] |
Double summation of matrix elements in Python | 37,468,787 | <p>Based on the simplified example below </p>
<p><a href="http://i.stack.imgur.com/IZ35E.png" rel="nofollow"><img src="http://i.stack.imgur.com/IZ35E.png" alt="enter image description here"></a></p>
<p>I would like in my code</p>
<pre><code>from sympy import*
import numpy as np
init_printing()
x, y = symbols('x, y'... | 2 | 2016-05-26T18:45:42Z | 37,470,802 | <p>You've imported both SymPy and NumPy, so you have a choice of tools here. And for the job of adding together a bunch of numeric matrices, numpy is the right tool. Here is how the summation happens in numpy:</p>
<pre><code>sum([sum([np.array([[x,1], [1,y]]) for y in yr]) for x, yr in zip(X,Y)])
</code></pre>
<p>Her... | 3 | 2016-05-26T20:54:16Z | [
"python",
"python-2.7",
"python-3.x",
"matrix",
"sympy"
] |
Python, opposite of conditional array | 37,468,869 | <p>I have two <code>numpy</code> arrays, let's say <code>A</code> and <code>B</code></p>
<pre><code>In [3]: import numpy as np
In [4]: A = np.array([0.10,0.20,0.30,0.40,0.50])
In [5]: B = np.array([0.15,0.23,0.33,0.41,0.57])
</code></pre>
<p>I apply a condition like this:</p>
<pre><code>In [6]: condition_array = A... | 1 | 2016-05-26T18:50:17Z | 37,468,968 | <p>You can use the <code>~</code> operator to invert the array ...</p>
<pre><code>A[~((B>0.2)*(B<0.5))]
</code></pre>
<p>Note that your use of <code>*</code> seems like it's meant to do a logical "and". Many people would prefer that you use the binary "and" operator (<code>&</code>) instead -- Personally, ... | 3 | 2016-05-26T18:56:09Z | [
"python",
"arrays",
"numpy",
"conditional"
] |
Python, opposite of conditional array | 37,468,869 | <p>I have two <code>numpy</code> arrays, let's say <code>A</code> and <code>B</code></p>
<pre><code>In [3]: import numpy as np
In [4]: A = np.array([0.10,0.20,0.30,0.40,0.50])
In [5]: B = np.array([0.15,0.23,0.33,0.41,0.57])
</code></pre>
<p>I apply a condition like this:</p>
<pre><code>In [6]: condition_array = A... | 1 | 2016-05-26T18:50:17Z | 37,469,069 | <p>By <a href="https://en.wikipedia.org/wiki/De_Morgan%27s_laws" rel="nofollow">De Morgan's Law</a></p>
<pre><code>A[np.logical_or(~(B > 0.2), ~(B < 0.5)]
</code></pre>
<p>Or</p>
<pre><code>A[np.logical_or(B <= 0.2, B >= 0.5)]
</code></pre>
| 2 | 2016-05-26T19:02:26Z | [
"python",
"arrays",
"numpy",
"conditional"
] |
Comparing class attribute to variable | 37,468,905 | <p>So, I am writing a Django application, and there is this little nasty bug. I have the following code:</p>
<pre><code>def appendProduct(self, productID):
for product in Product.objects.all():
if product.product_id == productID:
currentProduct = product
</code></pre>
<p>Somehow that <code>if... | 0 | 2016-05-26T18:52:17Z | 37,468,956 | <p>You should use <code>Product.objects.get(product_id=productID)</code> instead of looping through the objects.</p>
| 0 | 2016-05-26T18:55:02Z | [
"python",
"django",
"python-3.x"
] |
SQLAlchemy: Why does appending to this many-to-one relationship fail? | 37,468,987 | <p>I have two classes, a <code>Parent</code> and <code>Child</code>. A parent can have multiple children. In my program, I append children to parents as needed. This consistently succeeds for the first child but fails for the second. Here are my relationships</p>
<pre><code>class Parent(db.Model):
__tablename__ =... | 0 | 2016-05-26T18:57:29Z | 37,469,748 | <p>The error is due to usage of <code>session.merge</code>. Instead if you use <code>session.add</code>, it should work properly, as <code>session.add</code> performs a <code>insert-or-update</code> operation, which I believe is what you intend here.</p>
<p>This <a href="http://stackoverflow.com/questions/1849567/can-... | 2 | 2016-05-26T19:47:19Z | [
"python",
"sqlalchemy"
] |
Maximum recursion depth exceeded, save method, Django | 37,469,127 | <p>When attempting to generate QR codes using QR-code 5.3 using Python3.4. I'm confronted with several issues: </p>
<p>At first I used io.StringIO and I got a <em>string argument expected, got 'bytes'</em> error message. So I then changed io.StringIO to io.BytesIO. Then I got another error which was <em>'_io.BytesIO' ... | 0 | 2016-05-26T19:06:10Z | 37,469,746 | <p><code>self.qrcode.save</code> means that the whole model object needs to be saved, so it leads to a call to <code>save</code> which calls <code>generate_qrcode</code> which calls <code>self.qrcode.save</code>... (by the way you should be able to see this in the traceback) so your problem has nothing to do with <code... | 1 | 2016-05-26T19:47:12Z | [
"python",
"django"
] |
Running Linux Commands from Python on Windows Computer | 37,469,185 | <p>I am trying to learn how to run command line commands from Python. I am able to do this with DOS:</p>
<pre><code>import subprocess
subprocess.call("dir",shell=True)
</code></pre>
<p>This is fine, but I need to be able to do this for linux commands because my company uses linux servers. I am using Mobaxterm to run ... | 0 | 2016-05-26T19:09:30Z | 37,664,886 | <p>I was able to resolve this issue by opening an <a href="http://www.bu.edu/tech/support/research/system-usage/getting-started/get-started-file-transfer/" rel="nofollow">SFTP Session</a> within Mobaxterm, transferring the python file to the server, then running the file directly on the server (python was already insta... | 0 | 2016-06-06T18:55:34Z | [
"python",
"linux",
"shell"
] |
Python - Search for Keyword and Print line above | 37,469,212 | <p>So basically I download and clean up a webpage as best as I can using BeautifulSoup and save it temporarily as a text file that holds data like this:</p>
<pre><code> 2123:0335
WASHINGTON
13
NATIONAL
A85121
THINGLING
123:4567
VIRGINIA
12
NATIONAL
A85232
SOMETHIHNG
</code></pre>
<p>My goal is to search for... | 0 | 2016-05-26T19:11:27Z | 37,469,296 | <p>Try this -</p>
<pre><code>with open('textfile.txt', 'r') as f:
content = f.readlines()
content = [line.strip('\n') for line in content if line.strip('\n')]
if 'VIRGINIA' in content:
print(content[content.index('VIRGINIA') - 1])
</code></pre>
| 0 | 2016-05-26T19:16:59Z | [
"python"
] |
Python - Search for Keyword and Print line above | 37,469,212 | <p>So basically I download and clean up a webpage as best as I can using BeautifulSoup and save it temporarily as a text file that holds data like this:</p>
<pre><code> 2123:0335
WASHINGTON
13
NATIONAL
A85121
THINGLING
123:4567
VIRGINIA
12
NATIONAL
A85232
SOMETHIHNG
</code></pre>
<p>My goal is to search for... | 0 | 2016-05-26T19:11:27Z | 37,469,319 | <pre><code>with open("textfile.txt", "r") as f:
searchInLines = f.readlines()
for i, line in enumerate(searchInLines):
if "VIRGINIA" in line:
print searchInLines[i-3]
</code></pre>
<p>Variable name <code>searchInlines</code> turned into <code>searchInLines</code>.</p>
<p>Arrays referenced ... | 1 | 2016-05-26T19:18:21Z | [
"python"
] |
Apply series of transformations to pandas DataFrame object | 37,469,265 | <p>I am relatively new to Python programming. I have a pandas DataFrame object say obj1. I need to apply a series of transformation to records stored in obj1['key']. Suppose obj1['key'] has 300 entries and I need to apply func1 then func2 then func3 on each of the 300 entries and store the final result in obj1['key']. ... | 0 | 2016-05-26T19:15:03Z | 37,469,457 | <p>Yes, you could use the default method <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html?highlight=apply#pandas.DataFrame.apply" rel="nofollow">DataFrame.apply()</a></p>
<pre><code>df = df.apply(f1).apply(f2).apply(fn)
</code></pre>
| 2 | 2016-05-26T19:27:14Z | [
"python",
"pandas",
"dataframe"
] |
Apply series of transformations to pandas DataFrame object | 37,469,265 | <p>I am relatively new to Python programming. I have a pandas DataFrame object say obj1. I need to apply a series of transformation to records stored in obj1['key']. Suppose obj1['key'] has 300 entries and I need to apply func1 then func2 then func3 on each of the 300 entries and store the final result in obj1['key']. ... | 0 | 2016-05-26T19:15:03Z | 37,469,839 | <p>define a function</p>
<pre><code>def recursivator(x, fs):
return recursivator(fs[-1](x), fs[:-1]) if len(fs) > 0 else x
</code></pre>
<p><code>x</code> is the thing being operated on, <code>fs</code> is a list of functions.</p>
<pre><code>df = df.applymap(lambda x: recursivator(x, fs))
</code></pre>
| 0 | 2016-05-26T19:53:08Z | [
"python",
"pandas",
"dataframe"
] |
Django file-browser and error 404 | 37,469,309 | <p>I'm using django admin site (v1.9.6) and recently installed file-browser for managing images and documents. I followed installation steps and file-browser is shown in admin interface but I cant upload images and documents. When trying to access them 404 errors shows up (also thumbnails are not shown in file-browser ... | 0 | 2016-05-26T19:17:46Z | 37,471,916 | <p>You are not putting url for displaying image.
In setting.py-</p>
<pre><code>MEDIA_ROOT = os.path.join(BASE_DIR, "media/")
MEDIA_URL = '/media/'
In URLs.py--
Url(r'^media/(?^<path>.*)$','django.views.static.serve',{'document_root':
settings.MEDIA_ROOT,}),
</code></pre>
<p>I think it can help you</p>
| 0 | 2016-05-26T22:13:49Z | [
"python",
"django"
] |
Django file-browser and error 404 | 37,469,309 | <p>I'm using django admin site (v1.9.6) and recently installed file-browser for managing images and documents. I followed installation steps and file-browser is shown in admin interface but I cant upload images and documents. When trying to access them 404 errors shows up (also thumbnails are not shown in file-browser ... | 0 | 2016-05-26T19:17:46Z | 37,488,950 | <p>Ok, here is the solution:</p>
<p><a href="https://docs.djangoproject.com/en/1.9/howto/static-files/#serving-static-files-during-development" rel="nofollow">https://docs.djangoproject.com/en/1.9/howto/static-files/#serving-static-files-during-development</a></p>
<p>The issue was that I was testing django-filebrowse... | 0 | 2016-05-27T17:07:00Z | [
"python",
"django"
] |
Django file-browser and error 404 | 37,469,309 | <p>I'm using django admin site (v1.9.6) and recently installed file-browser for managing images and documents. I followed installation steps and file-browser is shown in admin interface but I cant upload images and documents. When trying to access them 404 errors shows up (also thumbnails are not shown in file-browser ... | 0 | 2016-05-26T19:17:46Z | 37,489,357 | <p>You can do:</p>
<pre><code>from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
#your urls
]
if settings.DEBUG: # will be 'True' in development
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL... | 0 | 2016-05-27T17:35:30Z | [
"python",
"django"
] |
How can I shade an area under a curve between two lines in matplotlib / pandas? | 37,469,382 | <p>I'm trying to recreate this chart, more or less, using matplotlib: </p>
<p><a href="http://i.stack.imgur.com/s0jch.png" rel="nofollow"><img src="http://i.stack.imgur.com/s0jch.png" alt="enter image description here"></a></p>
<p>Except in mine the center is 100 and the standard deviation is 16 (like IQ). This is wh... | 2 | 2016-05-26T19:21:38Z | 37,469,587 | <p>You can use <code>plt.fill_between</code>:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
plt.style.use('ggplot')
mean = 100
std = 16
x = np.linspace(mean - 5 * std, mean + 5 * std, 1000)
iq = stats.norm(mean, std)
plt.plot(x, iq.pdf(x), 'r-', lw=3)
colors = ['c', 'r... | 5 | 2016-05-26T19:36:05Z | [
"python",
"matplotlib"
] |
Importing modules from a sibling directory for use with py.test | 37,469,473 | <p>I am having problems importing anything into my testing files that I intend to run with py.test.</p>
<p>I have a project structure as follows:</p>
<pre><code>/ProjectName
|
|-- /Title
| |-- file1.py
| |-- file2.py
| |-- file3.py
| |-- __init__.py
|
|-- /test
| |-- test_file1.py
</code></pre>
<p>I h... | 1 | 2016-05-26T19:28:34Z | 37,469,619 | <p>No you don't need to add anything to <code>__init__.py</code>. This file tells python to treat the parent directory as module which can be imported as <a href="https://docs.python.org/2/tutorial/modules.html#packages" rel="nofollow">described here</a>.
Just add it to your Title directory and import it like</p>
<pre... | 1 | 2016-05-26T19:38:24Z | [
"python",
"python-3.x",
"python-import",
"importerror",
"py.test"
] |
iPython: Using Pandas to count words, how do I count the least occuring? | 37,469,511 | <p>Using iPython3. I was able to figure out how to count the most occurring words in a column</p>
<pre><code>import pandas as pd
dft = pd.read_csv('NYC.txt')
dft_counts = complaints['Provider'].value_counts()
dft_counts[:10]
</code></pre>
<p>How can I code this to count the least occurring word?</p>
| 2 | 2016-05-26T19:30:24Z | 37,469,560 | <p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.iat.html" rel="nofollow"><code>iat</code></a> with <code>-1</code> what return last value, because last value is smallest - <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.value_counts.html" ... | 1 | 2016-05-26T19:34:14Z | [
"python",
"python-3.x",
"pandas",
"ipython",
"anaconda"
] |
iPython: Using Pandas to count words, how do I count the least occuring? | 37,469,511 | <p>Using iPython3. I was able to figure out how to count the most occurring words in a column</p>
<pre><code>import pandas as pd
dft = pd.read_csv('NYC.txt')
dft_counts = complaints['Provider'].value_counts()
dft_counts[:10]
</code></pre>
<p>How can I code this to count the least occurring word?</p>
| 2 | 2016-05-26T19:30:24Z | 37,469,575 | <p><strong>UPDATE:</strong></p>
<pre><code>counts = complaints['Provider'].value_counts()
counts[counts == 1]
</code></pre>
<p>show "counts" less or equal than 3:</p>
<pre><code>counts[counts <= 3]
</code></pre>
<p><strong>OLD answer:</strong></p>
<p>you can do it this way:</p>
<pre><code>complaints['Provider'... | 3 | 2016-05-26T19:35:09Z | [
"python",
"python-3.x",
"pandas",
"ipython",
"anaconda"
] |
iPython: Using Pandas to count words, how do I count the least occuring? | 37,469,511 | <p>Using iPython3. I was able to figure out how to count the most occurring words in a column</p>
<pre><code>import pandas as pd
dft = pd.read_csv('NYC.txt')
dft_counts = complaints['Provider'].value_counts()
dft_counts[:10]
</code></pre>
<p>How can I code this to count the least occurring word?</p>
| 2 | 2016-05-26T19:30:24Z | 37,470,765 | <p>Just sort the Series:</p>
<pre><code>dft_counts = complaints['Provider'].value_counts()
dft_counts.sort_values(["Provider"], ascending=[True])
</code></pre>
| 0 | 2016-05-26T20:52:25Z | [
"python",
"python-3.x",
"pandas",
"ipython",
"anaconda"
] |
Understanding Closures For Decorators | 37,469,600 | <p>I'm trying to write a decorator that takes a few arguments, and can decorate arbitrary functions. After reading a few code examples, and stepping through the debugger I've figured out <em>how</em> to write it. But I don't fully understand <em>why</em> it works.</p>
<pre><code>def bar(arg1):
def inner_bar(f):
... | 3 | 2016-05-26T19:36:59Z | 37,469,648 | <blockquote>
<p>What is Python doing when I use @bar that makes the different variables available in the different methods of my decorator?</p>
</blockquote>
<p>Note that you're not just using <code>@bar</code>, you're using <code>@bar(4)</code>. It works like this:</p>
<ul>
<li><code>bar(4)</code> returns a funct... | 3 | 2016-05-26T19:40:55Z | [
"python"
] |
gaierror: [Errno 11004] getaddrinfo failed | 37,469,680 | <p>I hope to access the text file from the following url:</p>
<p><a href="http://www.pythonlearn.com/code/intro-short.txt" rel="nofollow">http://www.pythonlearn.com/code/intro-short.txt</a></p>
<p>My code is </p>
<pre><code>import socket
socket.getaddrinfo('127.0.0.1', 8080)
mysock = socket.socket(socket.AF_INET, s... | 1 | 2016-05-26T19:42:21Z | 37,470,987 | <p>In <code>mysock.connect(('http://www.pythonlearn.com', 80))</code>, the first element in the tuple should be just the host name (or address), without 'http://'. </p>
<p>So <code>mysock.connect(('www.pythonlearn.com', 80))</code> should work.</p>
<p>Incidentally, <code>socket.getaddrinfo('127.0.0.1', 8080)</code> ... | 0 | 2016-05-26T21:04:33Z | [
"python",
"sockets"
] |
Python index in nested for loop | 37,469,712 | <p>I can put it in another example:</p>
<pre><code>q=[[100,101,103,104],[201,202,204],[301,302,304],[401,402,403]]
for index, item in enumerate(q):
for i,t in enumerate(q[index]):
if q[index][i+1]-q[index][i]==2:
print index, i, q[index][i]
</code></pre>
<p>which returns</p>
<pre><code>... | -1 | 2016-05-26T19:44:35Z | 37,470,100 | <p>To iterate through list of list you may use this code:</p>
<pre><code>p=[['a','b','c','d'],
['a','c','e','d'],
['a','b','z','x']]
for i,item in enumerate(p):
for j,x in enumerate(item):
print i,j,x
</code></pre>
<p>Output:</p>
<pre><code>0 0 a
0 1 b
0 2 c
0 3 d
1 0 a
1 1 c
1 2 e
1 3 d
2 0 a
2 1... | 1 | 2016-05-26T20:10:23Z | [
"python"
] |
Python index in nested for loop | 37,469,712 | <p>I can put it in another example:</p>
<pre><code>q=[[100,101,103,104],[201,202,204],[301,302,304],[401,402,403]]
for index, item in enumerate(q):
for i,t in enumerate(q[index]):
if q[index][i+1]-q[index][i]==2:
print index, i, q[index][i]
</code></pre>
<p>which returns</p>
<pre><code>... | -1 | 2016-05-26T19:44:35Z | 37,470,582 | <pre><code>for index,item in enumerate(p):
print 'top', index #The index is at this level
for x in range(len(item)):
print 'loop' ,index # Not this level where you print it.
</code></pre>
| 1 | 2016-05-26T20:40:55Z | [
"python"
] |
Generating Point Sets for Reciprocal Function | 37,469,784 | <p>everyone.</p>
<p>I am writing a function that generates the points to graph a reciprocal function. Here is the code :</p>
<pre><code>def genRecp(xValrange=3, shiftHoriz=0, shiftVert=0, vertStrech=1, horizStrech=1):
#setup variables for processing
xrangeP = xValrange
xrangeN = xrangeP - xrangeP * 2
... | 0 | 2016-05-26T19:49:27Z | 37,469,993 | <p>Your default parameter values are all integers, and the line that calculates <code>curY</code> uses integer division <code>/</code>. That rounds your calculated values to an integer.</p>
<p>Do something to make your values non-integers, namely floating-point, force your values to float by wrapping the numerator and... | 0 | 2016-05-26T20:02:42Z | [
"python"
] |
How to convert list object to Pandas Dataframe with defined format? | 37,469,787 | <p>How to convert list object to Pandas Dataframe with defined format?</p>
<p>Printed list has this output (Jupyter):</p>
<pre><code>(u'variable', price threshold
0 13.5 100.0
1 10.0 NaN)
(u'standard', price threshold
0 12.5 300.0
1 11.0 NaN)
(u'fixed', price threshold
0 ... | 0 | 2016-05-26T19:49:40Z | 37,470,052 | <p>After you clearified what is in you list, you could do something like this:</p>
<pre><code>df = pd.DataFrame()
for key, df2 in row_list:
df2['index'] = key
df = df.append(df2, ignore_index=True)
</code></pre>
| 0 | 2016-05-26T20:06:41Z | [
"python",
"list",
"pandas",
"dataframe"
] |
How to get the first column of a list without transforming it in a dataframe in Python? | 37,469,790 | <p>I have a list <code>A</code> that is like a <code>2D</code> array, so </p>
<pre><code>A[0]= ('Tom', 89.0196078431373, 'Jim', None)
</code></pre>
<p>I want to get each column separately. This is what I am doing:</p>
<pre><code>L = list()
df1 = pd.DataFrame(A)
L.append(A.ix[:,2], A.ix[:,1], A.ix[:,3])
</code></pre>... | 0 | 2016-05-26T19:49:57Z | 37,469,971 | <p>If you have a <code>2D</code> array you can store the column <code>i</code> into a list like this:</p>
<pre><code>l = [row[i] for row in A]
</code></pre>
| 1 | 2016-05-26T20:01:28Z | [
"python",
"list"
] |
Pandas Groupby back to DataFrame | 37,469,792 | <p>I have a dataframe:</p>
<pre><code>df = pd.DataFrame({'Section': [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 6],
'Unit': np.arange(0,15)/100.0,
'Entries': [11, 22, 23, 1, 4, 8,
99, 112, 235, 22, 126,
442, 45, 56, 10]... | 2 | 2016-05-26T19:50:11Z | 37,469,833 | <p>is that what you want?</p>
<pre><code>In [93]: df['diff'] = df.groupby('Section')['Entries'].diff().fillna(0)
In [94]: df
Out[94]:
Section Unit Entries Exits diff
0 1 0.00 11 97 0.0
1 1 0.01 22 89 11.0
2 1 0.02 23 98 1.0
3 2 0.03 ... | 2 | 2016-05-26T19:52:47Z | [
"python",
"pandas",
"dataframe",
"group-by"
] |
Where can i find flickering functions for stimuli on psychopy? and how do i use it? | 37,469,796 | <p>currently i am building a stimuli in Psychopy for my thesis in my Uni, the 4 stimuli needs to flicker at 8.57 Hz,10 Hz ,12Hz and 15 Hz using the monitor refresh rate, my question is, can psychopy do that? and also what functions do i use for flickering at psychopy? what i have done so far is creating the shapes tha... | 1 | 2016-05-26T19:50:24Z | 37,470,543 | <p>PsychoPy doesn't appear to have a built-in function for flickering. Its creator, Jon Pierce, <a href="https://groups.google.com/forum/#!topic/psychopy-users/lLgPdmHwsgk" rel="nofollow">recommends</a> implementing flickering by:</p>
<ul>
<li>Looping over frames (using the variable <code>frameN</code>)</li>
<li>Usin... | 1 | 2016-05-26T20:38:22Z | [
"python",
"matlab",
"psychopy",
"psychtoolbox"
] |
Where can i find flickering functions for stimuli on psychopy? and how do i use it? | 37,469,796 | <p>currently i am building a stimuli in Psychopy for my thesis in my Uni, the 4 stimuli needs to flicker at 8.57 Hz,10 Hz ,12Hz and 15 Hz using the monitor refresh rate, my question is, can psychopy do that? and also what functions do i use for flickering at psychopy? what i have done so far is creating the shapes tha... | 1 | 2016-05-26T19:50:24Z | 37,472,296 |
<p>@A_S00 posted a good conceptual answer. Just to be very specific, assuming that you use a 60 Hz monitor:</p>
<ol>
<li>8.57 Hz corresponds to 60/8.57 = 7 frames on and 7 frames off.</li>
<li>10 Hz --> 6 frames</li>
<li>12 Hz --> 5 frames</li>
<li>15 Hz --> 4 frames</li>
</ol>
<p>... here assuming that the frequen... | 1 | 2016-05-26T22:51:05Z | [
"python",
"matlab",
"psychopy",
"psychtoolbox"
] |
Using reduce, map or other function to avoid for loops in python | 37,469,920 | <p>I have a program working for calculating the distance and then apply the k-means algorithm. I tested on a small list and it's working fine and fast, however, my original list is very big (>5000), so it's taking forever and I ended it up terminating the running. Can I use outer() or any other parallel function and ap... | 0 | 2016-05-26T19:58:18Z | 37,472,350 | <pre><code>import numpy as np
strings = ['cosine cos', 'cosine', 'cosine???????', 'l1', 'l2', 'manhattan']
k=len(strings)
data = np.zeros((k,k))
for i,string1 in enumerate(strings):
for j,string2 in enumerate(strings):
data[i][j] = 1-Levenshtein.ratio(string1, string2)
print data
</code></pre>
<p>No ... | 0 | 2016-05-26T22:58:23Z | [
"python",
"functional-programming",
"outer-join",
"levenshtein-distance"
] |
Setting xlim for Pandas DataFrame plot | 37,469,998 | <p>I'm plotting a stacked bar plot from a <code>Pandas DataFrame</code>. The index dates are in <code>datetime</code> format and plot just fine. The issue I'm having is trying to set <code>xlim</code> values.</p>
<pre><code>day_counts = {'a': count_a,
'b': count_b,
'c': count_c,
... | 0 | 2016-05-26T20:03:08Z | 37,471,635 | <p>Per <a href="http://stackoverflow.com/a/31500017/4893407">http://stackoverflow.com/a/31500017/4893407</a> the following should work:</p>
<p><code>ax.set_xlim(pd.Timestamp('2015-09-01'), pd.Timestamp('2016-01-01'))</code></p>
<p>Are you sure the index of your df is a DatetimeIndex? Does it have duplicates? Is it so... | 0 | 2016-05-26T21:51:47Z | [
"python",
"pandas"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.