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 listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
Is it possible to inverse inheritance using a Python meta class? | 38,405,169 | <p>Out of curiosity, I'm interested whether it's possible to write a meta class that causes methods of parent classes to have preference over methods of sub classes. I'd like to play around with it for a while. It would not be possible to override methods anymore. The base class would have to call the sub method explic... | 1 | 2016-07-15T21:18:12Z | 38,405,722 | <p>If you only care about making lookups on <em>instances</em> go in reverse order (not classes), you don't even need a metaclass. You can just override <code>__getattribute__</code>:</p>
<pre><code>class ReverseLookup:
def __getattribute__(self, attr):
if attr.startswith('__'):
return super()... | 2 | 2016-07-15T22:16:15Z | [
"python",
"python-3.x",
"inheritance",
"metaprogramming",
"metaclass"
] |
Multiple Count and Median Values from a Dataframe | 38,405,192 | <p>I am trying to perform several operations in one program at same time.
I have a data-frame that has <code>Dates</code> of which I have no clue of start and end and I want to find:</p>
<ol>
<li>Total number of days the data-set has </li>
<li>Total number of hours </li>
<li>Median of the Count </li>
<li>Write a sepa... | 2 | 2016-07-15T21:21:24Z | 38,405,222 | <p>IIUC maybe help change:</p>
<pre><code>date_count = df.count(['date'])
all_median = df.median(['count'])
all_hours = df.count(['startTime'])
</code></pre>
<p>to: </p>
<pre><code>date_count = df['date'].count()
all_median = df['count'].median()
all_hours = df['startTime'].count()
print (date_count)
print (all_... | 3 | 2016-07-15T21:23:57Z | [
"python",
"datetime",
"pandas",
"median",
"median-of-medians"
] |
Set PYTHONPATH for cron jobs in shared hosting | 38,405,210 | <p>I had issues running my python script on shared hosting (bluehost), and with the help of other SO threads I was able to set PYTHONPATH and run the script with no issues. </p>
<p>Now I need to run the script via a cron job. The cron jobs in shared hosting environment are just one line which I can call the script, bu... | 0 | 2016-07-15T21:23:22Z | 38,405,344 | <p>Change your cron job to run a shell script. Inside the shell script, set <code>PYTHONPATH</code> and then call the python program.</p>
<p>Change your cron job to this:</p>
<pre><code>/path/to/my_shell_script.sh
</code></pre>
<p>Contents of <code>my_shell_script.sh</code>:</p>
<pre><code>export PYTHONPATH=someth... | 2 | 2016-07-15T21:36:36Z | [
"python",
"cron",
"shared-hosting"
] |
Packaging a Python library with an executable | 38,405,248 | <p>I just finished a module and want to package it. I've read the documentation and this question <a href="http://stackoverflow.com/questions/7156333/packaging-a-python-application">packaging a python application</a> but I am not sure about how to proceed when I don't have a package to import but a script to launch ins... | 1 | 2016-07-15T21:25:35Z | 38,405,462 | <p>Generally, you only distribute python packages as modules when the entire project fits in a single module file. If your project is more complex than that, it's usually best to structure your project as a package with an <code>__init__.py</code> file. Here is what your project would look like converted to a package... | 0 | 2016-07-15T21:48:57Z | [
"python",
"packaging",
"setup.py"
] |
What is the reason i don't get all the elements in the tuple when i print args. Here args[0] prints 2 instead of 1. | 38,405,276 | <pre><code>def __init__(self, *args, **kwargs):
a=[args,kwargs]
print args
print type(args)
print type(kwargs)
print a
__init__(1,2,3,4,5)
</code></pre>
<p>Output -</p>
<pre><code>(2, 3, 4, 5)
<type 'tuple'>
<type 'dict'>
[(2, 3, 4, 5), {}]
</code></pre>
<p>Where do 1 from the tuple a... | 1 | 2016-07-15T21:29:11Z | 38,405,308 | <p>In this case, <code>self</code> would pass as any other argument since <code>__init__</code> is not bound to any class instance. <code>self</code> takes <code>1</code>.</p>
<p>Note that <code>self</code> is only a convention used for naming class instances in the class body and has no special significance when used... | 1 | 2016-07-15T21:32:09Z | [
"python",
"python-2.7"
] |
What is the reason i don't get all the elements in the tuple when i print args. Here args[0] prints 2 instead of 1. | 38,405,276 | <pre><code>def __init__(self, *args, **kwargs):
a=[args,kwargs]
print args
print type(args)
print type(kwargs)
print a
__init__(1,2,3,4,5)
</code></pre>
<p>Output -</p>
<pre><code>(2, 3, 4, 5)
<type 'tuple'>
<type 'dict'>
[(2, 3, 4, 5), {}]
</code></pre>
<p>Where do 1 from the tuple a... | 1 | 2016-07-15T21:29:11Z | 38,405,338 | <p>Other answers are right, but perhaps this will better explain:</p>
<pre><code>def foo(bar, *args):
print('Bar is {bar}'.format(bar=bar))
print('args is {args}'.format(args=args))
foo(1, 2, 3, 4, 5)
# Output:
# Bar is 1
# args is (2, 3, 4, 5)
</code></pre>
<p>The confusing part is that you named your func... | 2 | 2016-07-15T21:35:57Z | [
"python",
"python-2.7"
] |
What is the reason i don't get all the elements in the tuple when i print args. Here args[0] prints 2 instead of 1. | 38,405,276 | <pre><code>def __init__(self, *args, **kwargs):
a=[args,kwargs]
print args
print type(args)
print type(kwargs)
print a
__init__(1,2,3,4,5)
</code></pre>
<p>Output -</p>
<pre><code>(2, 3, 4, 5)
<type 'tuple'>
<type 'dict'>
[(2, 3, 4, 5), {}]
</code></pre>
<p>Where do 1 from the tuple a... | 1 | 2016-07-15T21:29:11Z | 38,405,342 | <p>You could stick your method in a class and get the expected output:</p>
<pre><code>class Example:
def __init__(self, *args, **kwargs):
a=[args,kwargs]
print args
print type(args)
print type(kwargs)
print a
Example(1,2,3,4,5)
</code></pre>
| 1 | 2016-07-15T21:36:20Z | [
"python",
"python-2.7"
] |
Cannot detect any serial ports with Python | 38,405,326 | <p>I am trying to find the correct com port a device is connected to before being able to run the rest of the Python script.</p>
<p>I have tried using this:</p>
<pre><code> import serial.tools.list_ports
ports = list(serial.tools.list_ports.comports())
for p in ports:
print p
</code></pre>
<p>And ... | 0 | 2016-07-15T21:34:59Z | 38,451,942 | <p>Like this :</p>
<pre><code>import serial,os,sys,glob
def serial_ports():
if sys.platform.startswith('win'):
ports = ['COM%s' % (i + 1) for i in range(256)]
print ports
elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):
# this excludes your current termina... | 0 | 2016-07-19T07:22:02Z | [
"python",
"serial-port"
] |
circle plot in bokeh jupyter is not displaying | 38,405,341 | <p>I am trying to make a circle plot in boke 0.12.0 in a jupyter notebook like this:</p>
<pre><code>s5 = figure(toolbar_location="above", x_axis_type = 'datetime')
s5.circle([1467568091,1467568152,1467568213],[1,1,1])
s5.xaxis.formatter = DatetimeTickFormatter(formats = dict(
seconds=["%d %m %Y %H %M %S"],
min... | 1 | 2016-07-15T21:36:08Z | 38,408,003 | <p>If you are going to <em>replace</em> the formats dictionary, you have to take care to make a formats dict that has <em>every possible</em> resolution. In this case, you have left off an entry for <code>"milliseconds"</code>. The following code generates a plot:</p>
<pre><code>s5 = figure(toolbar_location="above", x... | 1 | 2016-07-16T05:14:00Z | [
"python",
"ipython",
"visualization",
"jupyter",
"bokeh"
] |
How to loop through multiple cells in Jupyter / iPython Notebook | 38,405,345 | <p>I've got a Jupyter Notebook with a couple hundred lines of code in it, spread across about 30 cells. If I want to loop through 10 cells in the middle (e.g. using a For Loop), how do you do that? Is it even possible, or do you need to merge all the code in your loop into one cell? </p>
| 1 | 2016-07-15T21:36:37Z | 38,405,533 | <p>The only way I can see to do it would be to join the cells, and then put the entire thing in a for/while loop.</p>
| 0 | 2016-07-15T21:55:27Z | [
"python",
"jupyter-notebook"
] |
DataFrame inplace modification with return value | 38,405,384 | <p>I am reading Wes McKinney's 'python for data analysis' and saw the following code</p>
<pre><code># Always returns a reference to a DataFrame
_ = data.rename(index={'Ohio':'Indiana'}, inplace=True)
</code></pre>
<p>Is there a reason to set the inplace change to <code>_</code>?</p>
| 2 | 2016-07-15T21:40:26Z | 38,405,412 | <p>We use <code>_</code> to represent a value that we don't care about. It's convention. The <code>inplace</code> argument will alter the object that <code>data</code> currently points to along with the <code>rename</code> method returning another reference to it. This statement is a taking the return value from <co... | 2 | 2016-07-15T21:44:10Z | [
"python",
"pandas",
"dataframe",
"in-place"
] |
DataFrame inplace modification with return value | 38,405,384 | <p>I am reading Wes McKinney's 'python for data analysis' and saw the following code</p>
<pre><code># Always returns a reference to a DataFrame
_ = data.rename(index={'Ohio':'Indiana'}, inplace=True)
</code></pre>
<p>Is there a reason to set the inplace change to <code>_</code>?</p>
| 2 | 2016-07-15T21:40:26Z | 38,405,468 | <p><code>_</code> is usually meant to label a variable we don't care about/don't want to use.</p>
<p>This usually makes more sense when you pull out a tuple and don't care about all the values e.g.</p>
<pre><code>a, _ = (1, 2) # pulls out a == 1
</code></pre>
<p>In this case, with a single value, there is no reason... | 2 | 2016-07-15T21:49:24Z | [
"python",
"pandas",
"dataframe",
"in-place"
] |
Python printing lists side by side | 38,405,389 | <p>everyone. I am new to Python and in dire need of some help. I am trying to count the unique values in a few lists and then print the output side by side as columns. I can count them fine using collections. However, I don't know how to print them side by side. Is there any pythonic way to concatenate or display the... | 0 | 2016-07-15T21:41:03Z | 38,405,473 | <p>Im sure you can manually build your own library, but Python seems to have a format method built into the string type that could work well for your purpose. </p>
<p>This <a href="http://stackoverflow.com/questions/27663924/printing-2-evenly-populated-lists-side-by-side-evenly">link</a> of a previous post can help yo... | 0 | 2016-07-15T21:49:54Z | [
"python",
"dictionary",
"multiple-columns"
] |
Python printing lists side by side | 38,405,389 | <p>everyone. I am new to Python and in dire need of some help. I am trying to count the unique values in a few lists and then print the output side by side as columns. I can count them fine using collections. However, I don't know how to print them side by side. Is there any pythonic way to concatenate or display the... | 0 | 2016-07-15T21:41:03Z | 38,405,519 | <p>Taking a dependency on the <a href="https://pypi.python.org/pypi/tabulate" rel="nofollow">tabulate module</a>:</p>
<pre><code>import collections
from itertools import zip_longest
import operator
from tabulate import tabulate
def parsed_list(lst):
width = max(len(item) for item in lst)
return ['{key} {valu... | 2 | 2016-07-15T21:53:58Z | [
"python",
"dictionary",
"multiple-columns"
] |
Python printing lists side by side | 38,405,389 | <p>everyone. I am new to Python and in dire need of some help. I am trying to count the unique values in a few lists and then print the output side by side as columns. I can count them fine using collections. However, I don't know how to print them side by side. Is there any pythonic way to concatenate or display the... | 0 | 2016-07-15T21:41:03Z | 38,405,531 | <pre><code>from collections import Counter
from itertools import zip_longest
a = ['Black Cat', 'Black Dog', 'Black Mouse']
b = ['Bird', 'Bird', 'Parrot']
c = ['Eagle', 'Eagle', 'Eagle', 'Hawk']
def parse(lst):
c = Counter(lst)
r = []
for s, cnt in c.most_common():
r += ['%12s%3i' % (s, cnt)]
re... | 1 | 2016-07-15T21:55:24Z | [
"python",
"dictionary",
"multiple-columns"
] |
Firebase Cloud Messaging (FCM) in Python with pyFCM - Client registration | 38,405,419 | <p>I am trying to build a simple "Hello World" type app that includes push notifications (via FCM) in python using kivy and pyFCM. </p>
<p>i'm having trouble finding a way in python to create a "device registration token" as described here: "<a href="https://firebase.google.com/docs/cloud-messaging/android/client" rel... | 0 | 2016-07-15T21:45:01Z | 38,732,574 | <p>You need to manually obtain a registration token for a client (Android, iOS, web) before you can use pyfcm to send message to the client after obtaining the client's fcm registration token.</p>
| 0 | 2016-08-03T00:37:25Z | [
"android",
"python",
"python-3.x",
"firebase",
"firebase-cloud-messaging"
] |
Django with gunicorn and nginx does not return 404 or 500 | 38,405,430 | <p>If I use <code>get_object_or_404()</code>, Django shows my correct error page but NGINX still returns:</p>
<pre><code>HTTP/1.1 200 OK
Server: nginx
</code></pre>
<p>tl;tr </p>
<p>Every page returns 200 or (if 500) time out. Whats wrong here?</p>
<p>NGINX conf:</p>
<pre><code>location / {
proxy_pass http... | 1 | 2016-07-15T21:46:19Z | 38,405,643 | <p>You should setup the handlers, this can be done this way:</p>
<pre><code>from django.utils.functional import curry
handler404 = curry(page_not_found, template_name='404.html')
handler500 = curry(page_not_found, template_name='500.html')
handler403 = curry(page_not_found, template_name='403.html')
</code></pre>
<p... | 1 | 2016-07-15T22:07:41Z | [
"python",
"django",
"nginx",
"http-status-code-404",
"gunicorn"
] |
Intel Distribution for Python and Spyder IDE | 38,405,454 | <p>I've just installed the new Intel Distribution for Python because I need some performance improvements with my Skull Canyon NUC, but I don't understand how to use all the packages/modules modified by Intel.</p>
<p>I usually use Anaconda Spyder as my main IDE, how can I "tell" to Spyder to not use the Anaconda stand... | 0 | 2016-07-15T21:48:29Z | 38,405,541 | <p>In Spyder menu choose Preferences then click console and click to Advanced settings tab. From there choose the Python interpreter, which came with Intel Distribution.</p>
| 0 | 2016-07-15T21:56:18Z | [
"python",
"performance",
"intel",
"python-multiprocessing",
"intel-mkl"
] |
Intel Distribution for Python and Spyder IDE | 38,405,454 | <p>I've just installed the new Intel Distribution for Python because I need some performance improvements with my Skull Canyon NUC, but I don't understand how to use all the packages/modules modified by Intel.</p>
<p>I usually use Anaconda Spyder as my main IDE, how can I "tell" to Spyder to not use the Anaconda stand... | 0 | 2016-07-15T21:48:29Z | 38,420,252 | <p>Thank you, by the way the performance doesn't seem to be improved if compared with the standard Anaconda Python (2.7) interpreter.</p>
<p>I chosen the python.exe file inside the Intel folder, but there is also a pythonnw.exe file inside the same folder. Did I used the wrong one?</p>
| 0 | 2016-07-17T10:27:37Z | [
"python",
"performance",
"intel",
"python-multiprocessing",
"intel-mkl"
] |
Converting library from Python 2.7 to 3.4 | 38,405,499 | <p>I'm writing an equity calculator for poker hands
using this library <code>Deuces</code> for hand evaluation
<a href="https://github.com/worldveil/deuces" rel="nofollow">https://github.com/worldveil/deuces</a></p>
<p>The library is written for Python 2.7 and it can be
installed with the command</p>
<pre><code>pip i... | 0 | 2016-07-15T21:52:26Z | 38,405,650 | <ul>
<li>Download your library from <a href="https://pypi.python.org/pypi/deuces" rel="nofollow">deuces</a></li>
<li>Apply <strong>2to3</strong> to it</li>
<li>Manually install it <a href="http://stackoverflow.com/questions/4933224/how-to-install-a-python-library-manually">How to install a python library manually</a></... | 0 | 2016-07-15T22:08:33Z | [
"python",
"python-2.7",
"python-3.x",
"pip",
"converter"
] |
How do you manipulate the third argument of the range function to go up a factor of n? | 38,405,553 | <p>Python's for loop accepts three arguments in the range of the for loop. How could I manipulate the third argument to be a factor?</p>
<pre><code>factor_of = 2
li = []
for i in range(first_value, 25000, factor_of):
li.append(i)
</code></pre>
<p>Now I realize this will go up 2 every time, but how would I make it... | 2 | 2016-07-15T21:58:48Z | 38,405,611 | <p>You cannot do such a thing using the built-in <a href="https://docs.python.org/3/library/functions.html#func-range" rel="nofollow"><code>range()</code></a>. However, you can define your own <a href="https://www.python.org/dev/peps/pep-0255/" rel="nofollow">generator</a>, like this:</p>
<pre><code>def range_factor(s... | 5 | 2016-07-15T22:03:48Z | [
"python",
"python-3.x"
] |
How do you manipulate the third argument of the range function to go up a factor of n? | 38,405,553 | <p>Python's for loop accepts three arguments in the range of the for loop. How could I manipulate the third argument to be a factor?</p>
<pre><code>factor_of = 2
li = []
for i in range(first_value, 25000, factor_of):
li.append(i)
</code></pre>
<p>Now I realize this will go up 2 every time, but how would I make it... | 2 | 2016-07-15T21:58:48Z | 38,415,255 | <p>I would use a <code>while</code> loop as suggested by @Delgan. Nevertheless, if you still prefer to employ a <code>for</code> loop, here's the solution I came up with<sup>*</sup>:</p>
<pre><code>from math import log, ceil
def my_func(first, last, factor):
x = log(last/first)/log(factor)
n = int(x + 1 if x ... | 1 | 2016-07-16T20:19:29Z | [
"python",
"python-3.x"
] |
How do you manipulate the third argument of the range function to go up a factor of n? | 38,405,553 | <p>Python's for loop accepts three arguments in the range of the for loop. How could I manipulate the third argument to be a factor?</p>
<pre><code>factor_of = 2
li = []
for i in range(first_value, 25000, factor_of):
li.append(i)
</code></pre>
<p>Now I realize this will go up 2 every time, but how would I make it... | 2 | 2016-07-15T21:58:48Z | 38,434,376 | <pre><code>factor_of = 2
for i in range(1,15):
print( 10 * factor_of**i )
</code></pre>
<p>or:</p>
<pre><code>[ 10*factor_of**i for i in range(1,15) ]
</code></pre>
| 0 | 2016-07-18T10:27:34Z | [
"python",
"python-3.x"
] |
Python2.7: How to create bar graph using index and column information? | 38,405,568 | <p>I have just started learning Python 2.7 for data science and encounter a difficulty which I could not solve after googling... I would appreciate if you could help me how to create a bar graph.</p>
<p>So I have a data frame like this.
<a href="http://i.stack.imgur.com/aHKvR.png" rel="nofollow"><img src="http://i.sta... | 3 | 2016-07-15T22:00:20Z | 38,405,627 | <p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.plot.barh.html" rel="nofollow"><code>DataFrame.plot.barh</code></a>:</p>
<pre><code>import matplotlib.pyplot as plt
df.plot.barh()
#pandas version bellow 0.17.0
#df.plot(kind='barh')
plt.show()
</code></pre>
<p><a hre... | 2 | 2016-07-15T22:06:01Z | [
"python",
"python-2.7",
"pandas",
"data-visualization",
"seaborn"
] |
Iterate python list and sum equal items | 38,405,630 | <p>Considering a endpoint on my backend, that returns the following response:</p>
<pre><code>class Arc_Edges_Data(Resource):
def get(self):
#Connect to databse
conn = connectDB()
cur = conn.cursor()
#Perform query and return JSON data
try:
cur.execute("select json_bu... | 0 | 2016-07-15T22:06:31Z | 38,405,669 | <p>How about this?</p>
<pre><code>import collections
data = [
{
"frequency": 1,
"source": "c",
"target": "c",
},
{
"frequency": 1,
"source": "a",
"target": "b",
},
{
"frequency": 1,
"source": "a",
"target": "b",
},
... | 2 | 2016-07-15T22:10:37Z | [
"python",
"json"
] |
Iterate python list and sum equal items | 38,405,630 | <p>Considering a endpoint on my backend, that returns the following response:</p>
<pre><code>class Arc_Edges_Data(Resource):
def get(self):
#Connect to databse
conn = connectDB()
cur = conn.cursor()
#Perform query and return JSON data
try:
cur.execute("select json_bu... | 0 | 2016-07-15T22:06:31Z | 38,405,696 | <p>You could do this:</p>
<pre><code>r = {}
for d in ArcList:
key = (d['source'], d['target'])
r[key] = r.setdefault(key, 0) + d['frequency']
return [{'source': k[0], 'target': k[1], 'frequency': v} for k, v in r.items()]
</code></pre>
<p>If you want to preserve the original ordering of the items:</p>
<pre><... | 0 | 2016-07-15T22:13:38Z | [
"python",
"json"
] |
What is the best data structure to store objects indexed by date? | 38,405,633 | <p>I have some objects whicha re associated with dates. I would like to be able to get objects for a given date range, as well as for a single date.
What is the best data structure in python to do this?</p>
<p>I believe in some languages this would be achieved using a 'Curve'.</p>
| 3 | 2016-07-15T22:06:38Z | 38,405,691 | <p>A dictionary would work. <code>datetime</code> objects can be used as dictionary keys, and can be compared against one another in ranges.</p>
| 1 | 2016-07-15T22:12:39Z | [
"python",
"python-3.x"
] |
What is the best data structure to store objects indexed by date? | 38,405,633 | <p>I have some objects whicha re associated with dates. I would like to be able to get objects for a given date range, as well as for a single date.
What is the best data structure in python to do this?</p>
<p>I believe in some languages this would be achieved using a 'Curve'.</p>
| 3 | 2016-07-15T22:06:38Z | 38,405,872 | <p>You could use a <a href="http://pandas.pydata.org/" rel="nofollow">pandas</a> <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html" rel="nofollow"><code>DataFrame</code></a>:</p>
<pre><code>import pandas as pd, numpy as np
df = pd.DataFrame(np.random.random((10,1)))
df['date'] = pd.... | 3 | 2016-07-15T22:32:22Z | [
"python",
"python-3.x"
] |
tuple of strings "is" comparison behaves inconsistently | 38,405,660 | <p>I'm confused.</p>
<pre><code>foo = ("empty", 0)
foo[0] is "empty"
</code></pre>
<p>Returns False. This seems to be a problem with keyword strings, as "list" fails as well. "empt" and other strings return true. This only seems to happen with tuples, as if foo is a list the code also returns true</p>
<p>I've tested... | 1 | 2016-07-15T22:09:46Z | 38,405,720 | <pre><code>a is b
</code></pre>
<p>Equals to</p>
<pre><code>id(a) == id(b)
</code></pre>
<p>As mentioned here <a href="http://stackoverflow.com/questions/1504717/why-does-comparing-strings-in-python-using-either-or-is-sometimes-produce">Comparing strings</a>
Also read this
<a href="https://docs.python.org/3/library... | 0 | 2016-07-15T22:16:07Z | [
"python",
"python-3.x"
] |
tuple of strings "is" comparison behaves inconsistently | 38,405,660 | <p>I'm confused.</p>
<pre><code>foo = ("empty", 0)
foo[0] is "empty"
</code></pre>
<p>Returns False. This seems to be a problem with keyword strings, as "list" fails as well. "empt" and other strings return true. This only seems to happen with tuples, as if foo is a list the code also returns true</p>
<p>I've tested... | 1 | 2016-07-15T22:09:46Z | 38,405,835 | <p>As the other answers already mentioned: You are comparing strings by identity and this is likely to fail. Assumptions about the identity of string literals can not be made.</p>
<p>However, you actually found a subtle issue.</p>
<pre><code>>>> t = ("list",); t[0] is "list"
False
>>> t = ("notlist"... | 0 | 2016-07-15T22:28:55Z | [
"python",
"python-3.x"
] |
tuple of strings "is" comparison behaves inconsistently | 38,405,660 | <p>I'm confused.</p>
<pre><code>foo = ("empty", 0)
foo[0] is "empty"
</code></pre>
<p>Returns False. This seems to be a problem with keyword strings, as "list" fails as well. "empt" and other strings return true. This only seems to happen with tuples, as if foo is a list the code also returns true</p>
<p>I've tested... | 1 | 2016-07-15T22:09:46Z | 38,405,930 | <p>Using a literal value with <code>is</code> is almost certainly going to give you an implementation-dependent result. The only literal that Python guarantees to be a singleton is <code>None</code>. Any other literal may or may not resolve to a reference to an existing object. You can't assume that the interpreter wil... | 0 | 2016-07-15T22:38:39Z | [
"python",
"python-3.x"
] |
Slicing in C compared with Python | 38,405,690 | <p>I have been trying to figure out a substring method like Python's splice, e.g. 'hello'[2:4].</p>
<p><strong>OLD</strong>: The pointers <code>new</code> and <code>toret</code> (to return) are the same, but when stored in <code>hello</code>, it has a new address. Is there a way to maintain the address and get the sli... | 1 | 2016-07-15T22:12:23Z | 38,405,735 | <p>Not tested, but something similar as follows should work:</p>
<pre><code>char name[] = "Clayton";
int slice_begin = 0, slice_end = 3;
printf("%.*s", slice_end - slice_begin, name + slice_begin);
</code></pre>
<p><strong>Update</strong> Based on this technique, you can use two variables to represent a substring: a ... | 1 | 2016-07-15T22:18:09Z | [
"python",
"c",
"pointers",
"slice",
"memory-address"
] |
Slicing in C compared with Python | 38,405,690 | <p>I have been trying to figure out a substring method like Python's splice, e.g. 'hello'[2:4].</p>
<p><strong>OLD</strong>: The pointers <code>new</code> and <code>toret</code> (to return) are the same, but when stored in <code>hello</code>, it has a new address. Is there a way to maintain the address and get the sli... | 1 | 2016-07-15T22:12:23Z | 38,405,804 | <p>You can't return a pointer to a buffer that is declared locally within the function. That memory resides on the stack, and the next function call will likely overwrite that memory. You would need to use <code>malloc</code> to create the memory you need if you are going to return it to the calling function, which t... | 4 | 2016-07-15T22:26:30Z | [
"python",
"c",
"pointers",
"slice",
"memory-address"
] |
Slicing in C compared with Python | 38,405,690 | <p>I have been trying to figure out a substring method like Python's splice, e.g. 'hello'[2:4].</p>
<p><strong>OLD</strong>: The pointers <code>new</code> and <code>toret</code> (to return) are the same, but when stored in <code>hello</code>, it has a new address. Is there a way to maintain the address and get the sli... | 1 | 2016-07-15T22:12:23Z | 38,406,202 | <p>Since you want to emulate Python's slice, I'd go with something like:</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
char *slice(char *string, int start, int stop, int step) {
size_t string_length = ceil(fabs((stop - start) / (float) step));
... | 1 | 2016-07-15T23:16:12Z | [
"python",
"c",
"pointers",
"slice",
"memory-address"
] |
Error when theres zero ocurrence of word | 38,405,707 | <p>First of all, sorry for my broken english.</p>
<p>Iâm using this code to count the number of times the words âLeBronâ or âCurryâ appear on tweets. The problem is that if none of the tweets contains the word âLeBronâ or âCurryâ the program crash. Is the words are there, the program run perfectly.</... | 1 | 2016-07-15T22:14:57Z | 38,405,890 | <p>Use exception handling by surrounding the code on line 44 with try/catch:</p>
<pre><code>try:
LeBron = tweets['LeBron'].value_counts()[True]
except IndexError:
LeBron = 0
</code></pre>
| 2 | 2016-07-15T22:34:34Z | [
"python",
"pandas",
"twitter",
"tweepy"
] |
How to apply interp1d to each element of a tensor in Tensorflow | 38,405,731 | <p>Let say, I have a interpolation function.</p>
<pre><code>def mymap():
x = np.arange(256)
y = np.random.rand(x.size)*255.0
return interp1d(x, y)
</code></pre>
<p>This guy maps a number in [0,255] to a number following the profile given by <code>x</code> and <code>y</code> (now <code>y</code> is random, ... | 0 | 2016-07-15T22:17:37Z | 38,412,492 | <p>The function input of <code>tf.map_fn</code> needs to be a function written with Tensorflow ops. For instance, this one will work:</p>
<pre><code>def this_will_work(x):
return tf.square(x)
img = tf.placeholder(tf.float32, [64, 64, 1])
res = tf.map_fn(this_will_work, img)
</code></pre>
<hr>
<p>This one will n... | 1 | 2016-07-16T15:13:23Z | [
"python",
"tensorflow"
] |
pandas equals mysterious behavior | 38,405,775 | <p>I'm writing some unit tests, but it keeps failing when the dataframes are equal in every regard. After some investigating, I found that</p>
<pre><code>a.equals( a[ a.columns ] )
</code></pre>
<p>is false, where a is the dataframe I've manually created. What reason could there be for that?</p>
<p>edit:
I figured o... | 2 | 2016-07-15T22:23:22Z | 38,409,118 | <p>I think you can use <code>pd.util.testing.assert_frame_equal()</code> method:</p>
<pre><code>In [15]: help(pd.util.testing.assert_frame_equal)
Help on function assert_frame_equal in module pandas.util.testing:
assert_frame_equal(left, right, check_dtype=True, check_index_type='equiv', check_column_type='equiv', c... | 1 | 2016-07-16T08:00:31Z | [
"python",
"pandas",
"dataframe"
] |
How do I plot a bar graph from matplotlib/seaborn with an int list as value and a string list as x axis? | 38,405,789 | <p>I have a list of ints <code>arr=[1,2,3,4]</code> and a list of strings <code>list(df)</code> (which returns a list of column headers of the dataframe). I want to plot a bar graph such that the x axis labels are taken from the list of strings and the value for them are taken from the list of ints.</p>
<p>So for eg i... | -1 | 2016-07-15T22:24:36Z | 38,406,092 | <p>It doesn't seem like an intuitive thing to do. I followed the example <a href="http://matplotlib.org/examples/api/barchart_demo.html" rel="nofollow">here</a> to create this code:</p>
<pre><code>import matplotlib.pyplot as plt
vals=[1,2,3,4,5]
inds=range(len(vals))
labels=["A","B","C","D","E"]
fig,ax = plt.subplots... | 0 | 2016-07-15T22:59:17Z | [
"python",
"matplotlib",
"seaborn"
] |
Does Dask support functions with multiple outputs in Custom Graphs? | 38,405,844 | <p>The <a href="http://dask.pydata.org/en/latest/custom-graphs.html#custom-graphs" rel="nofollow">Custom Graphs</a> API of <a href="http://dask.pydata.org" rel="nofollow">Dask</a> seems to support only functions returning one output key/value.</p>
<p>For example, the following dependency could not be easily represente... | 2 | 2016-07-15T22:30:06Z | 38,407,189 | <h3>Short answer</h3>
<p>No, but it shouldn't matter.</p>
<h3>Programming interface</h3>
<p>You are correct that the correct way to manage multiple outputs with Dask is to use getitem. In terms of programming interface, the standard way to do this with dask.delayed is with getitem as you suggest. Here is an exampl... | 1 | 2016-07-16T02:40:17Z | [
"python",
"dask"
] |
PyCharm: Unresolved reference | 38,405,947 | <p>I am using pycharm and got the following red warnings in my <code>from ... import ...</code>. But it didn't ask me to install any requirement. Why is this happening and how do I get rid of the red thing. Thanks!</p>
<p><a href="http://i.stack.imgur.com/JAhDT.png" rel="nofollow"><img src="http://i.stack.imgur.com/JA... | 0 | 2016-07-15T22:41:02Z | 38,406,190 | <p>Does the code run? If not, you will want to install <code>pyspark</code> and add it to your python environment. Otherwise, if the code does run and you simply want to remove the red inspection warning, try adding <code>pyspark</code> to the list of <code>Unresolved references</code> you want it to ignore in File | S... | 0 | 2016-07-15T23:13:38Z | [
"python",
"pycharm"
] |
increasing timer in python | 38,405,949 | <p>I have an infinite for loop that runs like so:</p>
<pre><code>for I in count():
#doing something
savetask = savedata()
if savetask == None:
timerfunction()
def timerfunction():
time.sleep(60)
</code></pre>
<p>My question or rather what I want to achieve is a function that runs like this.... | -1 | 2016-07-15T22:41:10Z | 38,406,399 | <p>you can exponential backoff doing something like this</p>
<pre><code>for i in count():
#doing something
savetask = savedata()
if savetask == None:
timerfunction(i)
def timerfunction(i):
time.sleep(60*2**i)
</code></pre>
<p>minor stylistic point, capitals in python are typically for classe... | 0 | 2016-07-15T23:49:51Z | [
"python",
"timer",
"sleep"
] |
Dumb error in my if/and statement - not seeing it | 38,405,961 | <p>I have a data set with float values:</p>
<pre><code>dog-auto dog-bird dog-cat dog-dog Result
41.9579761457 41.7538647304 36.4196077068 33.4773590373 0
46.0021331807 41.33958925 38.8353268874 32.8458495684 0
42.9462290692 38.6157590853 36.9763410854 35.0397073189... | 0 | 2016-07-15T22:42:30Z | 38,406,084 | <p>Change & to and as indicated by the previous comments. Also, I recommend you break up such long if statements into multiple lines so it's clearer and easier to read.</p>
<pre><code>def is_dog_correct(row):
if (dog_distances[dog_distances['dog-dog']] < dog_distances[dog_distances['dog-cat']]) and
... | 1 | 2016-07-15T22:58:25Z | [
"python",
"if-statement",
"subset"
] |
Dumb error in my if/and statement - not seeing it | 38,405,961 | <p>I have a data set with float values:</p>
<pre><code>dog-auto dog-bird dog-cat dog-dog Result
41.9579761457 41.7538647304 36.4196077068 33.4773590373 0
46.0021331807 41.33958925 38.8353268874 32.8458495684 0
42.9462290692 38.6157590853 36.9763410854 35.0397073189... | 0 | 2016-07-15T22:42:30Z | 38,406,103 | <p>Make your first if statement more clean by finding the <code>min</code> (minimum) of all of the values. This makes sure that 'dog-dog' is less than all of the rest:</p>
<pre><code>def is_dog_correct(row):
if dog_distances[dog_distances['dog-dog']] < min([dog_distances[dog_distances['dog-'+x]] for x in ['cat'... | 0 | 2016-07-15T23:02:04Z | [
"python",
"if-statement",
"subset"
] |
"Self" not defined when trying to use self in instance variable within class | 38,406,056 | <p>Let us say I have code like this</p>
<pre><code>class A:
var1 = self.var0
def __init__(self, var0):
self.var0 = var0
</code></pre>
<p>how might I get self.var0 into var1 without putting var1 inside the init function?</p>
| -2 | 2016-07-15T22:56:03Z | 38,406,107 | <p>Try this instead:</p>
<pre><code>class A:
def __init__(self, var0):
self.var1 = self.var0 = var0
</code></pre>
<p>However, I do not see much point in this and would rather simply initialize it immediately like so:</p>
<pre><code>class A:
def __init__(self, var0):
self.var1 = var0
</code></pre>
<p>I... | 0 | 2016-07-15T23:02:23Z | [
"python"
] |
"Self" not defined when trying to use self in instance variable within class | 38,406,056 | <p>Let us say I have code like this</p>
<pre><code>class A:
var1 = self.var0
def __init__(self, var0):
self.var0 = var0
</code></pre>
<p>how might I get self.var0 into var1 without putting var1 inside the init function?</p>
| -2 | 2016-07-15T22:56:03Z | 38,406,170 | <p>You have two options that I can think of:</p>
<p>1) Include it in the init function if you want an A object to be created with A.var1=var0:</p>
<pre><code>class A:
def __init__(self, var0):
self.var0 = var0
self.var1 = self.var0
</code></pre>
<p>2) If you really don't want var1 inside of the init funct... | 1 | 2016-07-15T23:10:23Z | [
"python"
] |
"Self" not defined when trying to use self in instance variable within class | 38,406,056 | <p>Let us say I have code like this</p>
<pre><code>class A:
var1 = self.var0
def __init__(self, var0):
self.var0 = var0
</code></pre>
<p>how might I get self.var0 into var1 without putting var1 inside the init function?</p>
| -2 | 2016-07-15T22:56:03Z | 38,406,185 | <p>In your code <code>var1 = self.var0</code> is at class-level, not at instance-level, so <code>self</code> doesn't make sense here. To see it, try this:</p>
<pre><code>class C(object):
field1 = 1
def __init__(self):
self.field2 = 2
print(C.field1)
print(C.field2) # should raise an exception
instanc... | 0 | 2016-07-15T23:12:49Z | [
"python"
] |
I have lxml but still I am asked to install it | 38,406,095 | <p>I have lxml because I checked it using </p>
<pre><code>`import pandas as pd `
`pd.show_versions(as_json=False)`
</code></pre>
<p>and I have lxml version 3.6.0 which is in this "installed versions" </p>
<pre><code>INSTALLED VERSIONS
------------------
commit: None
python: 2.7.12.final.0
python-bits: 64
OS: Linux
... | 0 | 2016-07-15T22:59:27Z | 38,412,556 | <p>I see 2 problems that you are reporting: </p>
<ol>
<li>you have an issue with internet access to <code>anaconda.org</code>. Try to ping it to see if it is down, review your connection, and/or see if that service is temporarily down...</li>
<li>I have tested on Anaconda-Python3.5 and Canopy1.7 (Python 2.7) and with ... | 0 | 2016-07-16T15:23:20Z | [
"python",
"http",
"lxml"
] |
writing to csv file whilst keep shape of array | 38,406,150 | <p>I want to write to a cvs file but it ceases to preserve the shape of the array, writing the equivalent of a 1d array. </p>
<pre><code>reader = open('/Users/williamneal/Scratch/Titanic/Employment.csv', 'rt')
csv_file_object = csv.reader(reader)
header = next(csv_file_object)
data=[]
for row in csv_file_object:
... | 0 | 2016-07-15T23:08:06Z | 38,406,473 | <p>Just use numpy for this:</p>
<pre><code>In [10]: arr = np.random.random((16,5))
In [11]: arr
Out[11]:
array([[ 0.11072668, 0.33415019, 0.799157 , 0.19265392, 0.65449757],
[ 0.06553107, 0.84417166, 0.04288959, 0.05092669, 0.6867636 ],
[ 0.91626205, 0.85025192, 0.40024396, 0.56022321, 0.8... | 0 | 2016-07-16T00:03:28Z | [
"python",
"csv",
"numpy"
] |
Python: I have a global declaration which I need to call in different Python programs | 38,406,165 | <p>Now, I would like to use <code>TOPOLOGY</code> in many scripts. Instead of writing that
again and again, I would like to keep those in a function or something so
that I can call them and use them instead of writing again and again in all scripts.</p>
<p>Could you please suggest some better and good solutions?</p>... | 1 | 2016-07-15T23:10:09Z | 38,406,208 | <p>You could place your constants in a module and import it from your script: </p>
<p>module constants: (constants.py)</p>
<pre><code>"""
This module contains the constants
constants.py
"""
# a constants useful in topology
TOPOLOGY = """
[type=switch name="Switch 1"] ops1
[type=host name="Host 1" image="Ubuntu"] h... | 2 | 2016-07-15T23:16:54Z | [
"python"
] |
Python: I have a global declaration which I need to call in different Python programs | 38,406,165 | <p>Now, I would like to use <code>TOPOLOGY</code> in many scripts. Instead of writing that
again and again, I would like to keep those in a function or something so
that I can call them and use them instead of writing again and again in all scripts.</p>
<p>Could you please suggest some better and good solutions?</p>... | 1 | 2016-07-15T23:10:09Z | 38,529,336 | <p>You could also make a class and add the variable as an attribute of the class.</p>
<pre><code>Class Topo:
def __init__(self):
self.Topo = """..."""
def topology_1switch_2host(self):
Topology = self.Topo
</code></pre>
<p>If your list of constants becomes long enough, it might make sense to ... | 0 | 2016-07-22T14:45:34Z | [
"python"
] |
Find all upper, lower and mixed case combinations of a string that contains numeric and special chars | 38,406,249 | <p>I want to write a program that would take a string, let's say "abc", then it would display:</p>
<p><code>abc, Abc, ABc, ABC, AbC, aBc, aBC, AbC</code></p>
<p>After digging for a while I found <a href="http://stackoverflow.com/questions/11144389/find-all-upper-lower-and-mixed-case-combinations-of-a-string">this que... | 0 | 2016-07-15T23:24:44Z | 38,406,288 | <p>Try converting the array into a set:</p>
<pre><code>x = set(map(''.join, itertools.product(*((c.upper(), c.lower()) for c in string))))
</code></pre>
| 0 | 2016-07-15T23:30:28Z | [
"python",
"string"
] |
Find all upper, lower and mixed case combinations of a string that contains numeric and special chars | 38,406,249 | <p>I want to write a program that would take a string, let's say "abc", then it would display:</p>
<p><code>abc, Abc, ABc, ABC, AbC, aBc, aBC, AbC</code></p>
<p>After digging for a while I found <a href="http://stackoverflow.com/questions/11144389/find-all-upper-lower-and-mixed-case-combinations-of-a-string">this que... | 0 | 2016-07-15T23:24:44Z | 38,406,306 | <p>@Caius's answer works, but it's more efficient to remove the duplicate <em>characters</em> up front instead of waiting until you have all the results and then removing the duplicates there.</p>
<p>The difference in my code is just <code>set((c.upper(), c.lower()))</code> instead of just <code>(c.upper(), c.lower())... | 2 | 2016-07-15T23:32:54Z | [
"python",
"string"
] |
Ordinary Least Squares Regression for multiple columns in Pandas Dataframe | 38,406,324 | <p>I'm trying to find a way to iterate code for a linear regression over many many columns, upwards of Z3. Here is a snippet of the dataframe called df1</p>
<pre><code> Time A1 A2 A3 B1 B2 B3
1 1.00 6.64 6.82 6.79 6.70 6.95 7.02
2 2.00 6.70 6.86 6.92 NaN... | 2 | 2016-07-15T23:35:22Z | 38,407,935 | <p>Looping is a decent strategy for a modest number (say, fewer than thousands) of columns. Without seeing your implementation, I can't say what's wrong, but here's my version, which works:</p>
<pre><code>slopes = []
for c in cols:
if c=="Time": break
mask = ~np.isnan(df1[c])
x = np.atleast_2d(df1.Time[ma... | 1 | 2016-07-16T05:03:28Z | [
"python",
"numpy",
"pandas",
"scipy",
"scikit-learn"
] |
Ordinary Least Squares Regression for multiple columns in Pandas Dataframe | 38,406,324 | <p>I'm trying to find a way to iterate code for a linear regression over many many columns, upwards of Z3. Here is a snippet of the dataframe called df1</p>
<pre><code> Time A1 A2 A3 B1 B2 B3
1 1.00 6.64 6.82 6.79 6.70 6.95 7.02
2 2.00 6.70 6.86 6.92 NaN... | 2 | 2016-07-15T23:35:22Z | 38,409,941 | <h3>One liner (or three)</h3>
<pre><code>time = df[['Time']]
pd.DataFrame(np.linalg.pinv(time.T.dot(time)).dot(time.T).dot(df.fillna(0)),
['Slope'], df.columns)
</code></pre>
<p><a href="http://i.stack.imgur.com/tUSg7.png" rel="nofollow"><img src="http://i.stack.imgur.com/tUSg7.png" alt="enter image desc... | 3 | 2016-07-16T09:59:16Z | [
"python",
"numpy",
"pandas",
"scipy",
"scikit-learn"
] |
How to correctly write out a TSV file from a series in Pandas? | 38,406,328 | <p>I have read the manual <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_csv.html" rel="nofollow">here</a> and saw <a href="http://stackoverflow.com/questions/21147058/pandas-to-csv-output-quoting-issue/21147228?noredirect=1#comment64220918_21147228">this</a> answer, but it is not wo... | 2 | 2016-07-15T23:36:24Z | 38,409,332 | <p>The <a href="https://github.com/pydata/pandas/blob/master/pandas/core/series.py#L2553" rel="nofollow">internal pandas implementation of <code>Series.to_csv()</code></a> first converts Series to DataFrame and then calls <code>DataFrame.to_csv()</code> method:</p>
<pre><code>def to_csv(self, path, index=True, sep=","... | 3 | 2016-07-16T08:33:49Z | [
"python",
"pandas",
"dataframe"
] |
python regular expression error | 38,406,330 | <p>I am trying do a pattern search and if match then set a bitarray on the counter value.</p>
<pre><code>runOutput = device[router].execute (cmd)
runOutput = output.split('\n')
print(runOutput)
for this_line,counter in enumerate(runOutput):
print(counter)
... | 0 | 2016-07-15T23:37:24Z | 38,406,373 | <p>You mixed up the arguments for <a href="https://docs.python.org/2/library/functions.html#enumerate" rel="nofollow"><code>enumerate()</code></a> - first goes the index, then the item itself. Replace:</p>
<pre><code>for this_line,counter in enumerate(runOutput):
</code></pre>
<p>with:</p>
<pre><code>for counter, th... | 2 | 2016-07-15T23:44:37Z | [
"python",
"regex"
] |
What is the maximum number of selenium drivers on service like AWS-EC2 or Pythonanywhere | 38,406,408 | <p>Using python-selenium and pyvirtualdisplay, I would like to open about 10 different Firefox browsers simultaneously on a remote server. However, on both AWS and pythonanywhere the firefox driver starts throwing exceptions at around the fifth opened window:</p>
<blockquote>
<p>WebDriverException: Message:The brows... | -1 | 2016-07-15T23:51:27Z | 38,412,220 | <p>On PythonAnywhere, it's fairly likely that you're bumping into one of the limitations that we impose to prevent our users from trampling all over each other.</p>
| 0 | 2016-07-16T14:35:30Z | [
"python",
"selenium",
"amazon-ec2",
"pythonanywhere",
"pyvirtualdisplay"
] |
jQuery get changing the URL parameter itself | 38,406,412 | <p>I am making a get request using jquery to the local server in Flask. Here is the endpoint in Flask</p>
<pre><code>@app.route('/getNews', methods=['GET', 'POST'])
def getNews():
return jsonify(news['news'])
</code></pre>
<p>Here is the call from HTML</p>
<pre><code> $.get({
url:"http://0.0.0.0:9090/ge... | 0 | 2016-07-15T23:52:18Z | 38,406,460 | <p>Your url argument is a string, not in the data object. The second argument is the data you are passing to the endpoint. The third argument is the success handler. And the last argument is the datatype expected back.</p>
<pre><code>$.get( "http://0.0.0.0:9090/getNews", 'd', function( data ) {
console.log(data)... | 1 | 2016-07-16T00:01:20Z | [
"jquery",
"python",
"ajax",
"flask",
"get"
] |
Casting python list to numpy array gives the wrong shape | 38,406,434 | <p>I am reading data from a file, like so:</p>
<pre><code>f = open('some/file/path')
data = f.read().split('\n')
</code></pre>
<p>Which gives me something like <code>data = ['1 a #', '3 e &']</code>
if the original file was </p>
<blockquote>
<p>1 a #</p>
<p>3 e &</p>
</blockquote>
<p>I need it in a f... | 0 | 2016-07-15T23:56:40Z | 38,406,490 | <p>To turn <code>data = ['1 a #', '3 e &']</code> into <code>[['1','a','#'],['3','e','&']]</code> you should do:</p>
<pre><code>>>> data2 = []
>>> for line in data:
data2.append(line.split())
>>> data2
[['1', 'a', '#'], ['3', 'e', '&']]
</code></pre>
| 0 | 2016-07-16T00:05:44Z | [
"python",
"arrays",
"numpy"
] |
Casting python list to numpy array gives the wrong shape | 38,406,434 | <p>I am reading data from a file, like so:</p>
<pre><code>f = open('some/file/path')
data = f.read().split('\n')
</code></pre>
<p>Which gives me something like <code>data = ['1 a #', '3 e &']</code>
if the original file was </p>
<blockquote>
<p>1 a #</p>
<p>3 e &</p>
</blockquote>
<p>I need it in a f... | 0 | 2016-07-15T23:56:40Z | 38,406,500 | <p>split the strings first:</p>
<pre><code>import numpy as np
data = ['1 a #', '3 e &']
np.array([x.split() for x in data]).T
</code></pre>
| 0 | 2016-07-16T00:07:57Z | [
"python",
"arrays",
"numpy"
] |
Casting python list to numpy array gives the wrong shape | 38,406,434 | <p>I am reading data from a file, like so:</p>
<pre><code>f = open('some/file/path')
data = f.read().split('\n')
</code></pre>
<p>Which gives me something like <code>data = ['1 a #', '3 e &']</code>
if the original file was </p>
<blockquote>
<p>1 a #</p>
<p>3 e &</p>
</blockquote>
<p>I need it in a f... | 0 | 2016-07-15T23:56:40Z | 38,406,954 | <p>Your line split looks fine</p>
<pre><code>In [110]: data = ['1 a #', '3 e &']
In [111]: for n in range(len(data)): data[n] = data[n].split()
In [112]: data
Out[112]: [['1', 'a', '#'], ['3', 'e', '&']]
In [113]: A=np.array(data)
In [114]: A
Out[114]:
array([['1', 'a', '#'],
['3', 'e', '&']], ... | 0 | 2016-07-16T01:49:56Z | [
"python",
"arrays",
"numpy"
] |
Casting python list to numpy array gives the wrong shape | 38,406,434 | <p>I am reading data from a file, like so:</p>
<pre><code>f = open('some/file/path')
data = f.read().split('\n')
</code></pre>
<p>Which gives me something like <code>data = ['1 a #', '3 e &']</code>
if the original file was </p>
<blockquote>
<p>1 a #</p>
<p>3 e &</p>
</blockquote>
<p>I need it in a f... | 0 | 2016-07-15T23:56:40Z | 38,421,915 | <p>Reading the file(strip() will remove the '\n'):
<code>
filename="some/file/path"
data=[i.strip().split(' ') for i in open(filename)]
print(data)
</code>
Converting list to numpy array and swap the axis:
<code>
import numpy as np
print(np.asarray(data))
print(np.asarray(data).T)</code></p>
| 0 | 2016-07-17T13:47:05Z | [
"python",
"arrays",
"numpy"
] |
reading multiple text files from different folders python | 38,406,443 | <p>So, I'm trying to look through multiple text files located in different folders:</p>
<pre><code>path1 = 'P:/folder1/best_par.txt'
path2 = 'P:/folder2/best_par.txt'
paths = (path1, path2)
for i in paths:
inputfile = open(i)
text = inputfile.read()
cn2 = re.findall(r'(CN2\.mgt)\s+([-+]?[0-9]+\.[0-9]+)', t... | 0 | 2016-07-15T23:58:54Z | 38,406,463 | <p>You are overwriting your cn2 variable, you should declare it outside of the loop and append to it all the results.</p>
| 1 | 2016-07-16T00:01:39Z | [
"python",
"regex",
"loops",
"text"
] |
reading multiple text files from different folders python | 38,406,443 | <p>So, I'm trying to look through multiple text files located in different folders:</p>
<pre><code>path1 = 'P:/folder1/best_par.txt'
path2 = 'P:/folder2/best_par.txt'
paths = (path1, path2)
for i in paths:
inputfile = open(i)
text = inputfile.read()
cn2 = re.findall(r'(CN2\.mgt)\s+([-+]?[0-9]+\.[0-9]+)', t... | 0 | 2016-07-15T23:58:54Z | 38,406,487 | <pre><code>path1 = 'P:/folder1/best_par.txt'
path2 = 'P:/folder2/best_par.txt'
paths = (path1, path2)
for i in paths:
inputfile = open(i)
text = inputfile.read()
cn2 = re.findall(r'(CN2\.mgt)\s+([-+]?[0-9]+\.[0-9]+)', text)
</code></pre>
<p>When your loop runs for first time path1 best_par is read and cn2 ... | 3 | 2016-07-16T00:05:28Z | [
"python",
"regex",
"loops",
"text"
] |
cannot import name same_origin from authentication.py tastypie django | 38,406,488 | <p>I was wondering if someone could help me figure out why I am getting a "ImportError: cannot import name same_origin"</p>
<p>Here is the full stack trace:</p>
<pre><code>Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/usr/local/lib/p... | 0 | 2016-07-16T00:05:35Z | 38,406,504 | <p>django.utils.http doesn't have a same_origin function (<a href="https://docs.djangoproject.com/en/1.9/ref/utils/" rel="nofollow">https://docs.djangoproject.com/en/1.9/ref/utils/</a>)</p>
<p>Maybe this is what you're looking for? <a href="https://docs.djangoproject.com/en/1.9/ref/clickjacking/" rel="nofollow">https:... | 1 | 2016-07-16T00:09:00Z | [
"python",
"django",
"tastypie"
] |
cannot import name same_origin from authentication.py tastypie django | 38,406,488 | <p>I was wondering if someone could help me figure out why I am getting a "ImportError: cannot import name same_origin"</p>
<p>Here is the full stack trace:</p>
<pre><code>Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/usr/local/lib/p... | 0 | 2016-07-16T00:05:35Z | 38,406,650 | <p>The <code>same_origin</code> method was removed from django as of version 1.9. You can <a href="https://github.com/django/django/commit/b0c56b895fd2694d7f5d4595bdbbc41916607f45#diff-60f461827b74beaf0ea54cb211e5e4dd" rel="nofollow">look at the commit here</a>.</p>
<p>It looks like this was fixed in tastypie <a href=... | 3 | 2016-07-16T00:38:30Z | [
"python",
"django",
"tastypie"
] |
Write json format using pandas Series and DataFrame | 38,406,511 | <p>I'm working with csvfiles. My goal is to write a json format with csvfile information. Especifically, I want to get a similar format as miserables.json</p>
<p>Example:</p>
<pre><code>{"source": "Napoleon", "target": "Myriel", "value": 1},
</code></pre>
<p>According with the information I have the format would be:... | 0 | 2016-07-16T00:10:04Z | 38,417,239 | <p>Consider removing the <code>Series()</code> around the scalar value, country. By doing so and then upsizing the dictionaries of series into a dataframe, you force <code>NaN</code> (later converted to <code>null</code> in json) into the series to match the lengths of other series. You can see this by printing out the... | 1 | 2016-07-17T01:55:51Z | [
"python",
"json",
"python-3.x",
"pandas"
] |
Delete a directory that is not empty on python | 38,406,516 | <p>So, I need to clean a directory that is not empty.
I have created the following function.For testing reasons I tried to remove a JDK installation</p>
<pre><code>def clean_dir(location):
fileList = os.listdir(location)
for fileName in fileList:
fullpath=os.path.join(location, fileName)
if os... | 0 | 2016-07-16T00:11:01Z | 38,406,553 | <p>You're encountering one of the differences between the way Windows and Linux (UNIX really) handle filesystems. I believe adding an additional case to your code will at least help:</p>
<pre><code>...
for fileName in fileList:
fullpath = os.path.join(location, fileName)
## |<-- Handle symlink -->|
i... | 2 | 2016-07-16T00:20:10Z | [
"python",
"delete-file"
] |
Delete a directory that is not empty on python | 38,406,516 | <p>So, I need to clean a directory that is not empty.
I have created the following function.For testing reasons I tried to remove a JDK installation</p>
<pre><code>def clean_dir(location):
fileList = os.listdir(location)
for fileName in fileList:
fullpath=os.path.join(location, fileName)
if os... | 0 | 2016-07-16T00:11:01Z | 38,406,908 | <p>kronenpj thanks, that was the idea. But when you have a symlink it tries to delete is as a normal file and fails. I had to add a new elif and add the unlink option for the symlink</p>
<p><pre>
def clean_dir(location):
fileList = os.listdir(location)</p>
<code>for fileName in fileList:
fullpath=os.path.join... | 0 | 2016-07-16T01:38:37Z | [
"python",
"delete-file"
] |
key event triggers and moving objects on screen | 38,406,529 | <p>So I am making a game with the pygame module in python. The game is <a href="https://en.wikipedia.org/wiki/Breakout_(video_game)" rel="nofollow">Breakout</a>. One of the mechanics of the game is move the player left and right. How am I doing this is when the user presses the left or right arrow key, the player brick... | 0 | 2016-07-16T00:14:04Z | 38,406,565 | <pre><code>import pygame
pygame.init()
#colors
BLACK = ( 0, 0, 0)
WHITE = ( 255, 255, 255)
GREEN = ( 0, 255, 0)
RED = ( 255, 0, 0)
#the Brick
class goodbrick:
def __init__ (self, color):
self.color_scheme=color
##################X, Y L F
self.cordinates= ... | 1 | 2016-07-16T00:22:49Z | [
"python",
"pygame"
] |
mplot3d animation with transparent background | 38,406,617 | <p>I want to generate some gifs with transparent background using matplotlib. I tried different options but I can't get my files with transparent background. With the current setup I get the first frame like that but not the rest. The following is my code</p>
<pre><code>from __future__ import division
from numpy impor... | 8 | 2016-07-16T00:33:42Z | 39,731,822 | <p>I think it's really a bug.
However, if you rather care about the result than the way to get there, the following would do the job. Instead of calling animation, you can save each image separately and then call imageMagick to convert them to an animated gif.
See the code below and mind the arguments to convert.exe.<... | 4 | 2016-09-27T18:25:23Z | [
"python",
"matplotlib",
"animated-gif",
"mplot3d"
] |
If X and Y matches element in NumPy Array | 38,406,638 | <p>How do I check if there is an element in an array where both axes <code>[X, Y]</code> match <code>[drawx, drawy]</code>?</p>
<p>I have a <strong>NumPy array</strong>:</p>
<pre><code>#format: [X, Y]
wallxy = numpy.array([[0,1],[3,2],[4,6]])
</code></pre>
<p>and <strong>two other variables</strong>:</p>
<pre><code... | 3 | 2016-07-16T00:36:26Z | 38,406,927 | <p>numpy doesn't have but list does</p>
<pre><code>[3,2] in wallxy.tolist()
True
</code></pre>
| -1 | 2016-07-16T01:42:08Z | [
"python",
"arrays",
"numpy"
] |
If X and Y matches element in NumPy Array | 38,406,638 | <p>How do I check if there is an element in an array where both axes <code>[X, Y]</code> match <code>[drawx, drawy]</code>?</p>
<p>I have a <strong>NumPy array</strong>:</p>
<pre><code>#format: [X, Y]
wallxy = numpy.array([[0,1],[3,2],[4,6]])
</code></pre>
<p>and <strong>two other variables</strong>:</p>
<pre><code... | 3 | 2016-07-16T00:36:26Z | 38,406,982 | <p><code>==</code> will broadcast the comparison, so </p>
<pre><code>wallxy = numpy.array([[0, 1],[3, 2][4, 6]])
z0 = numpy.array([3,2])
z1 = numpy.array([2,3])
(z0==wallxy).all(1).any() # True
(z1==wallxy).all(1).any() # False
</code></pre>
<p>Which is, I think, what you're looking for.</p>
<p>Printing out the i... | 1 | 2016-07-16T01:55:39Z | [
"python",
"arrays",
"numpy"
] |
Swift URL String Template Equivalent to Python | 38,406,658 | <p>I'm making url requests to a web api. I'd like to make a template URL and then use string format to pass in the parameters. In Python this is very easy. Here's an example:
<a href="http://i.stack.imgur.com/8EkqC.png" rel="nofollow"><img src="http://i.stack.imgur.com/8EkqC.png" alt="Python Url Template Example"></a><... | 0 | 2016-07-16T00:40:45Z | 38,406,773 | <p>You can do this easily in Swift without any special string "magic" by creating a function that takes in a <code>String</code> and an <code>Int</code> then returning a <code>String</code>.</p>
<pre><code>// Create the template function
let urlTemplate: (String, Int) -> String = { (string, number) in
return "h... | 2 | 2016-07-16T01:02:52Z | [
"python",
"ios",
"swift",
"string",
"format"
] |
How do I list all the objects in a folder of a Google Cloud Bucket in Python? | 38,406,661 | <p>In python the way I get my bucket is:</p>
<pre><code>gs_conn = connect_gs(gs_access_key_id='accessid', gs_secret_access_key='secretaccesskey')
gs_conn.get_bucket(bucketname)
</code></pre>
<p>I can list all of the objects in that bucket by:</p>
<pre><code>for obj in gs_conn.get_bucket(bucketname):
print obj.na... | 1 | 2016-07-16T00:41:28Z | 38,406,738 | <p>You can use the <a href="http://boto.cloudhackers.com/en/latest/ref/gs.html#boto.gs.bucket.Bucket.get_all_keys" rel="nofollow">get_all_keys</a> method of the bucket. For example:</p>
<pre><code>bucket = gs_conn.get_bucket(bucketname)
for obj in bucket.get_all_keys(prefix='Animals/Dogs/'):
print obj.name
</code>... | 1 | 2016-07-16T00:56:23Z | [
"python",
"google-cloud-storage"
] |
Compressing a list of integers in Python | 38,406,670 | <p>I have a list of positive (random) integers with the following properties:</p>
<p>Number of elements: 78495</p>
<p>Maximum value of element: 999982</p>
<p>Length of list when converted to a string: 517115 (string looks like "6,79384,238956,...")</p>
<p>Size of list in text file on disk: 520 kb</p>
<p>I am tryin... | 0 | 2016-07-16T00:43:06Z | 38,406,697 | <p>In short, no.</p>
<pre><code>log(2, 999982) ~= 20
</code></pre>
<p>So the largest number would take 20 bits to store. Let's say that on average, each number takes 10 bits to store (evenly distributed between 0 and the max).</p>
<pre><code>~80,000 numbers * 10 bits per number = 800,000 bits = 100,000 bytes
</code>... | 1 | 2016-07-16T00:49:05Z | [
"python",
"list",
"memory",
"compression"
] |
Compressing a list of integers in Python | 38,406,670 | <p>I have a list of positive (random) integers with the following properties:</p>
<p>Number of elements: 78495</p>
<p>Maximum value of element: 999982</p>
<p>Length of list when converted to a string: 517115 (string looks like "6,79384,238956,...")</p>
<p>Size of list in text file on disk: 520 kb</p>
<p>I am tryin... | 0 | 2016-07-16T00:43:06Z | 38,406,722 | <p>The <a href="http://www.byronknoll.com/cmix.html" rel="nofollow">best text compression</a> available offers a (roughly) 12-17% compression ratio (62.4-90 kB) so you're not going to meet your threshold. Your data are random, as well, which generally makes compression algorithms perform worse. </p>
<p>Look at an alte... | 1 | 2016-07-16T00:52:51Z | [
"python",
"list",
"memory",
"compression"
] |
Compressing a list of integers in Python | 38,406,670 | <p>I have a list of positive (random) integers with the following properties:</p>
<p>Number of elements: 78495</p>
<p>Maximum value of element: 999982</p>
<p>Length of list when converted to a string: 517115 (string looks like "6,79384,238956,...")</p>
<p>Size of list in text file on disk: 520 kb</p>
<p>I am tryin... | 0 | 2016-07-16T00:43:06Z | 38,412,604 | <p>Given your definition ...</p>
<p><em>it is a list of smallest-k values for which 10^k = 1 mod p for primes p > 5</em></p>
<p>... am I wrong to believe that your values are of the form <code>(p - 1) / x</code> where x is an integer significantly smaller than p?</p>
<p>For instance, for p < 50, we have:</p>
<pr... | 3 | 2016-07-16T15:28:17Z | [
"python",
"list",
"memory",
"compression"
] |
How to calculate spin from a set of translating images in python | 38,406,682 | <p>I am wondering if this can be done:</p>
<p>I have a set of images that start out looking forward, as they move forward the camera spins horizontally in a 360 direction.
So each image has a slightly different view as it spins around going forward.
The question is; can I accurately calculate the spin that camera is... | 0 | 2016-07-16T00:46:00Z | 38,415,693 | <p>The idea would be to use a few points that you would track across the transformation. And from those points you could find the angle of rotation between each frame.</p>
<p>You might want to have a look at this that explains the maths.
<a href="http://nghiaho.com/?page_id=671" rel="nofollow">http://nghiaho.com/?page... | 1 | 2016-07-16T21:14:27Z | [
"python",
"opencv"
] |
AttributeError: module 'socket' has no attribute 'AF_PACKET' | 38,406,741 | <p>I am working on building a packet sniffing program using Python, however I have hit a speed bump. For some reason I think socket has not imported properly, because I am getting the following message when my program is run: <code>AttributeError: module 'socket' has no attribute 'AF_PACKET'</code></p>
<p>I am using O... | 1 | 2016-07-16T00:57:06Z | 38,406,832 | <p>Actually, AF_PACKET doesn't work on OS X, it works on Linux.</p>
<p><a href="http://stackoverflow.com/questions/7284853/af-packet-equivalent-under-mac-os-x-darwin">AF_PACKET equivalent under Mac OS X (Darwin)</a></p>
| 1 | 2016-07-16T01:16:38Z | [
"python",
"sockets",
"python-3.x"
] |
Python 3.4 Poker Position of Hero | 38,406,789 | <p>I have a poker table with 9 seats represented as a list of players and the button position.
I have to calculate the position of Hero(UTG, Middle Position, Late Position, CO, BB, SB...).
Some seats could be empty, in this case the place is filled with "".</p>
<pre><code>table=["Player_1","Player_2","","","Hero","","... | -1 | 2016-07-16T01:07:03Z | 38,412,880 | <p>I solved with 2 <code>for</code>(cycling first from button to the end, and then cycling from start to button-1):</p>
<pre><code>def position(table,button_position):
temp = [x for x in table if x!=""]
contatore=0
relative_position=0
for i in range(button_position,len(table)):
if(table[i]!=""):
contator... | 0 | 2016-07-16T15:55:53Z | [
"python",
"position",
"poker"
] |
How to set spark driver maxResultSize when in client mode in pyspark? | 38,406,825 | <p>I know when you are in client mode in pyspark, you cannot set configurations in your script, because the JVM gets started as soon as the libraries are loaded. </p>
<p>So, the way to set the configurations is to actually go and edit the shell script that launches it: <code>spark-env.sh</code>...according to this d... | 1 | 2016-07-16T01:15:30Z | 38,407,487 | <p>The configuration file is <code>conf/spark-default.conf</code>. </p>
<p>If <code>conf/spark-default.conf</code> does not exist</p>
<pre><code>cp conf/spark-defaults.conf.template conf/spark-defaults.conf
</code></pre>
<p>Add configuration like </p>
<pre><code>spark.driver.maxResultSize 2g
</code></pre>
<p>Ther... | 1 | 2016-07-16T03:42:44Z | [
"python",
"apache-spark",
"driver",
"pyspark"
] |
Is it possible that if I multiply 2 floats the result will be different then multiplication of 2 decimals? | 38,406,833 | <p>I am calculating a field in my view file </p>
<pre><code>data_dict = { 'quantity_order': float(bom.quantity) * float(quantity)}
</code></pre>
<p>I added float conversion since I was getting a different problem: </p>
<blockquote>
<p>"can't multiply sequence by non-int of type 'Decimal'"</p>
</blockquote>
<p>In ... | 2 | 2016-07-16T01:16:44Z | 38,407,292 | <p>Why do you want to convert it to float? Decimal is good enough for this. The result is still the same even if you don't convert it.</p>
<p>If you really want to convert it for some reason then use this method:</p>
<pre><code>data_dict = { 'quantity_order': float(bom.quantity * quantity)}
</code></pre>
<p>but this... | 0 | 2016-07-16T03:02:55Z | [
"python",
"django"
] |
Is it possible that if I multiply 2 floats the result will be different then multiplication of 2 decimals? | 38,406,833 | <p>I am calculating a field in my view file </p>
<pre><code>data_dict = { 'quantity_order': float(bom.quantity) * float(quantity)}
</code></pre>
<p>I added float conversion since I was getting a different problem: </p>
<blockquote>
<p>"can't multiply sequence by non-int of type 'Decimal'"</p>
</blockquote>
<p>In ... | 2 | 2016-07-16T01:16:44Z | 38,412,394 | <blockquote>
<p>"can't multiply sequence by non-int of type 'Decimal'"</p>
</blockquote>
<p>What this actually means is that one of your operands is a sequence and the other is a Decimal. Ie, one of <code>bom.quantity</code> or <code>quantity</code> is a sequence and not an int, float or decimal. </p>
<pre><code>da... | 1 | 2016-07-16T14:58:47Z | [
"python",
"django"
] |
1A - Theatre Square CodeForces | 38,406,856 | <p>I am trying to answer the 1A-Theatre Square problem on CodeForces.
Its keeps telling me: "Runtime error on test 1" </p>
<p>Here is my code:</p>
<pre><code>n= int(input())
m= int(input())
a= int(input())
n1=1
n2=1
while n>a*n1:
n1=n1+1
break
while m>a*n2:
n2=n2+1
break
print (n1*n2)
</code></p... | 0 | 2016-07-16T01:22:48Z | 38,406,896 | <p>You will get time limit exceed, because the concept you are using has 2 loops that is time complexity of O(n). But the actual solution will have time complexity of O(1) i.e. it will not require any loops.</p>
<p>Hint:-
You will need, just a few if else based solution. </p>
| 0 | 2016-07-16T01:35:14Z | [
"python",
"runtime"
] |
How to mock Django's now function in all application functions | 38,406,892 | <p>I am attempting to mock Django's now() function in order to spoof the time used in my application. I can easily mock the now() function within my test file, but the mock replacement doesn't seem to percolate down recursively into my applications functions. Here is the code I am using:</p>
<pre><code># file - tests.... | 2 | 2016-07-16T01:33:52Z | 38,407,411 | <p>I personally don't like to use mocks for date because of constant pain. Instead I suggest you to give <a href="https://github.com/spulec/freezegun" rel="nofollow">FreezeGun</a> a try. It has all sorts of datetime fiddling utils you need in your tests and wherever.</p>
<p>Example from docs with timezones:</p>
<pre>... | 1 | 2016-07-16T03:25:18Z | [
"python",
"django",
"unit-testing",
"mocking"
] |
Iteratively Capture Value Counts in Single DataFrame | 38,406,897 | <p>I have a pandas dataframe that looks something like this:</p>
<pre><code>id group gender age_grp status
1 1 m over21 active
2 4 m under21 active
3 2 f over21 inactive
</code></pre>
<p>I have over 100 columns and thousands of rows. I am trying to create a single p... | 1 | 2016-07-16T01:35:17Z | 38,408,934 | <p>This should do it:</p>
<pre><code>df.stack().groupby(level=1).value_counts()
id 1 1
2 1
3 1
group 1 1
2 1
4 1
gender m 2
f 1
age_grp over21 2
under21 1
status ... | 2 | 2016-07-16T07:34:29Z | [
"python",
"pandas"
] |
Python- Selecting a row to manipulate from an image created | 38,406,912 | <p>I'm new to python, and I'm working on a code. One part of it is:</p>
<pre><code>a=3
def tictactoe(a):
for x in range(0,a):
print (("- "*a))
z=tictactoe(a)
print(z)
</code></pre>
<p>which prints out:</p>
<pre><code> - - -
- - -
- - -
</code></pre>
<p>I would like to select a row from the im... | 0 | 2016-07-16T01:39:00Z | 38,406,965 | <p>Your question is somewhat confused: there is no data structure in your code, with rows to be "selected". But there could be!</p>
<p>First, create a 3x3 board, as a <code>list</code> of <code>list</code>s:</p>
<pre><code>board = []
for x in xrange(3):
board.append(['-']*3)
</code></pre>
<p><strong>Note</strong... | 1 | 2016-07-16T01:52:11Z | [
"python"
] |
Python- Selecting a row to manipulate from an image created | 38,406,912 | <p>I'm new to python, and I'm working on a code. One part of it is:</p>
<pre><code>a=3
def tictactoe(a):
for x in range(0,a):
print (("- "*a))
z=tictactoe(a)
print(z)
</code></pre>
<p>which prints out:</p>
<pre><code> - - -
- - -
- - -
</code></pre>
<p>I would like to select a row from the im... | 0 | 2016-07-16T01:39:00Z | 38,408,184 | <p>just another approach</p>
<pre><code>def write(board, char, row, column):
"""write char on board, row and column
are indexed with base 1
"""
row -= 1
column = 2*(column - 1)
board[row] = board[row][:column] + char + board[row][column + 1:]
return board
def print_board(board):
for ro... | 0 | 2016-07-16T05:46:52Z | [
"python"
] |
Difference between ffmpeg and avconv for rawvideo image2pipe | 38,406,935 | <p>I'm not sure why, but <code>avconv</code> does not seem to be piping raw video like I would expect.</p>
<p>I'm trying pipe a video from <code>ffmpeg</code> into <code>python</code> (eventually I want to read from <code>x11grab</code>, not a video file). It works just fine on my Macbook using <code>ffmpeg</code>, bu... | 0 | 2016-07-16T01:44:47Z | 38,950,189 | <p>I had this problem because I am running from inside a Docker instance, which is built off of Debian. <code>ffmpeg</code> isn't packaged by default in the version of Debian I'm running.</p>
<p>I managed to fix this problem by just downloading an <code>ffmpeg</code> binary, per @LordNeckbeard's comment above. I've ad... | 1 | 2016-08-15T06:21:01Z | [
"python",
"video",
"ffmpeg",
"avconv"
] |
list of lambdas in python | 38,406,937 | <p>I have seen <a href="http://stackoverflow.com/questions/452610/how-do-i-create-a-list-of-python-lambdas-in-a-list-comprehension-for-loop">this question</a>, but i still cannot get why such simple example does not work:</p>
<pre><code>mylist = ["alice", "bob", "greta"]
funcdict = dict(((y, lambda x: x==str(y)) for y... | 2 | 2016-07-16T01:45:00Z | 38,406,972 | <p>The <code>y</code> in the body of the <code>lambda</code> expression is just a name, unrelated to the <code>y</code> you use to iterate over <code>mylist</code>. As a free variable, a value of <code>y</code> is not found until you actually call the function, at which time it uses whatever value for <code>y</code> is... | 4 | 2016-07-16T01:53:33Z | [
"python",
"list",
"lambda"
] |
list of lambdas in python | 38,406,937 | <p>I have seen <a href="http://stackoverflow.com/questions/452610/how-do-i-create-a-list-of-python-lambdas-in-a-list-comprehension-for-loop">this question</a>, but i still cannot get why such simple example does not work:</p>
<pre><code>mylist = ["alice", "bob", "greta"]
funcdict = dict(((y, lambda x: x==str(y)) for y... | 2 | 2016-07-16T01:45:00Z | 38,406,974 | <pre><code>((y, lambda x: x==str(y)) for y in mylist)
</code></pre>
<p><code>y</code> inside the lambda is not bound at the time of the genration expression defined, but it's bound when it's called; When it's called, iteration is already done, so <code>y</code> references the last item <code>greta</code>.</p>
<p>One ... | 2 | 2016-07-16T01:53:43Z | [
"python",
"list",
"lambda"
] |
Colorkey collision between Rects in Pygame, Python 3 | 38,406,992 | <p>I'm currently working on a game on Pygame, Python 3 and one of the essential parts of the game is the collision of Rects in a bullet-target situation.</p>
<p>This is fairly easy to achieve using the <code>colliderect</code> function but it is necessary for the pixels that are the same color as the colorkey to not b... | 1 | 2016-07-16T01:57:50Z | 38,409,321 | <p>Have a look at the collide_mask function:</p>
<p><a href="http://www.pygame.org/docs/ref/sprite.html#pygame.sprite.collide_mask" rel="nofollow">http://www.pygame.org/docs/ref/sprite.html#pygame.sprite.collide_mask</a></p>
<p>In brief you give each sprite a self.mask attribute (using pygame.mask.from_surface()) - w... | 1 | 2016-07-16T08:31:17Z | [
"python",
"python-3.x",
"pygame",
"pygame-surface",
"color-key"
] |
Colorkey collision between Rects in Pygame, Python 3 | 38,406,992 | <p>I'm currently working on a game on Pygame, Python 3 and one of the essential parts of the game is the collision of Rects in a bullet-target situation.</p>
<p>This is fairly easy to achieve using the <code>colliderect</code> function but it is necessary for the pixels that are the same color as the colorkey to not b... | 1 | 2016-07-16T01:57:50Z | 38,416,818 | <p>I managed to make an algorithm that looks at the corners of each rect:</p>
<pre><code>def rectsCollideSimple (rect1, surf1, rect2, surf2):
collide = False
try:
if surf1.get_at((rect2.left - rect1.left, rect2.top - rect1.top)) != surf1.get_colorkey():
collide = True
except IndexError:... | 0 | 2016-07-17T00:21:40Z | [
"python",
"python-3.x",
"pygame",
"pygame-surface",
"color-key"
] |
Exception Value: invalid type for argument text | 38,407,047 | <p>I'm trying to get a paragraph with <code>reportlab</code> but I can't get it to work.</p>
<p>This code works fine:</p>
<pre><code>p.setFont('Helvetica',8)
labo = str('CANCIÃN').decode('utf-8')
p.setFillColor(HexColor('#ff8100'))
p.drawString(350,736, labo)
</code></pre>
<p>But this code doesn't:</p>
<pre><code>... | 0 | 2016-07-16T02:10:33Z | 38,475,832 | <p>The reason you get this error is that you are mixing up syntax. <code>Paragraph</code> is used in <code>Platypus</code> while <code>drawCentredString</code> is a basic canvas operation.</p>
<p>The syntax for <code>drawCentredString</code> is <code>canvas.drawCentredString(x, y, text)</code> which expects you to fee... | 0 | 2016-07-20T08:12:55Z | [
"python",
"pdf",
"reportlab"
] |
pandas - figuring out how many rows needed to reach a pct | 38,407,056 | <p>i have a pandas series of number, I would like to know how many of these numbers I need to reach 80% of the value of the series (given that the serie is ordered, and taking the biggest number first).</p>
<p>How could I do that ? </p>
| 1 | 2016-07-16T02:12:19Z | 38,407,753 | <p>You can extract that number using <code>cumsum</code></p>
<pre><code>df = pd.Series(list(reversed(range(1,10))))
sum = df.cumsum()
list(sum)
#[9, 17, 24, 30, 35, 39, 42, 44, 45]
list(sum[sum > 0.8 * max(sum)].index)[0]+1
#6
</code></pre>
| 1 | 2016-07-16T04:35:57Z | [
"python",
"pandas"
] |
Rearranging table in Python | 38,407,195 | <p>I got the following list in Python.</p>
<pre><code>v5z 3CD 300
vdz 3CD 100
vqz 3CD 200
vtz 3CD 10
v5z 3C2 22
vdz 3C2 3232
vqz 3C2 338
vtz 3C2 55
v5z 3Cfix 55
vdz 3Cfix 100
vqz 3Cfix 200
vtz 3Cfix 22
</code></pre>
<p>Though I am wondering how to rearrange it and obtain:</p>
<pre><code>vdz 3CD 100
vtz 3CD 10
vqz 3C... | 0 | 2016-07-16T02:40:42Z | 38,407,386 | <p>You can try something like this </p>
<pre><code>from pprint import PrettyPrinter
pprint = PrettyPrinter(4).pprint
lst = [
['v5z', '3CD', 300],
['vdz', '3CD', 100],
['vqz', '3CD', 200],
['vtz', '3CD', 10],
['v5z', '3C2', 22],
['vdz', '3C2', 3232],
['vqz', '3C2', 338],
['vtz', '3C2',... | 0 | 2016-07-16T03:21:27Z | [
"python",
"list",
"sorting"
] |
Scraping with Beautifulsoup - contents different from displayed page | 38,407,203 | <p>I am trying to scrape contents from <a href="http://www.indeed.com/cmp/Microsoft/reviews?fcountry=ALL" rel="nofollow">this page</a>, see code below. I am curious, though, as if I run the code repeatedly, I keep getting a different list of job locations (and thus, reviews), even though the displayed page in my browse... | 1 | 2016-07-16T02:41:44Z | 38,407,742 | <p>In my opinion, it's related with Ajax request in <a href="http://www.indeed.com/cmp/Microsoft/reviews?fcountry=ALL" rel="nofollow">your target url</a>, I could find some XHR type requests when I visit it.</p>
<p>For Ajax related website, <a href="https://developers.google.com/webmasters/ajax-crawling/docs/learn-mor... | 0 | 2016-07-16T04:34:16Z | [
"python",
"beautifulsoup"
] |
How to solve ImportError on import cv2 without uninstalling | 38,407,260 | <p>I've installed OpenCV3 from source and after running <code>import cv2</code> I get the error:</p>
<pre><code>ImportError: dlopen(/Users/Victor/.virtualenvs/cv/lib/python3.5/cv2.so, 2): Symbol not found: _PyCObject_Type
Referenced from: /Users/Victor/.virtualenvs/cv/lib/python3.5/cv2.so
Expected in: flat ... | 0 | 2016-07-16T02:56:27Z | 38,416,867 | <p>The way I solved this was taking the cv2.cpython-35m-darwin.so file from the opencv/build/lib directory and putting it in place of cv2.so in my virtualenv folder</p>
| 0 | 2016-07-17T00:31:18Z | [
"python",
"python-3.x",
"opencv",
"python-3.5"
] |
How to solve ImportError on import cv2 without uninstalling | 38,407,260 | <p>I've installed OpenCV3 from source and after running <code>import cv2</code> I get the error:</p>
<pre><code>ImportError: dlopen(/Users/Victor/.virtualenvs/cv/lib/python3.5/cv2.so, 2): Symbol not found: _PyCObject_Type
Referenced from: /Users/Victor/.virtualenvs/cv/lib/python3.5/cv2.so
Expected in: flat ... | 0 | 2016-07-16T02:56:27Z | 38,422,314 | <p>Try this</p>
<p><code>export PYTHONPATH=/usr/local/Cellar/python3/3.5.1:$PYTHONPATH</code></p>
| 0 | 2016-07-17T14:29:41Z | [
"python",
"python-3.x",
"opencv",
"python-3.5"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.