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 |
|---|---|---|---|---|---|---|---|---|---|
How can I scrape data that is locked by a button? | 38,190,635 | <p>I'm trying to fetch some info from a website, without success.</p>
<p>The problem is that the data is shown only after clicking a certain button.</p>
<p><a href="http://i.stack.imgur.com/i45mi.png" rel="nofollow"><img src="http://i.stack.imgur.com/i45mi.png" alt="first_page"></a></p>
<p>The info that I want is lo... | 2 | 2016-07-04T18:41:41Z | 38,191,987 | <p>It is pretty straightforward using a <a href="http://docs.python-requests.org/en/master/user/advanced/#session-objects" rel="nofollow">requests.Session</a> object, you just need to extract the <code>__RequestVerificationToken</code> token from the initial page and a couple of pieces of form data. I used the page o... | 1 | 2016-07-04T20:42:58Z | [
"jquery",
"python",
"html",
"web-scraping",
"beautifulsoup"
] |
Paramiko - NoValidConnectionsError - periodically unable to connect to aws instance | 38,190,697 | <p>Infrequently upon creating an instance in aws and then trying to connect I receive the following error from paramiko:</p>
<pre><code>NoValidConnectionsError: [Errno None] Unable to connect to port 22 on 192.168.1.155, fe80::18f3:2388:9bf3:e2d%4 or fe80::49f2:7e18:c58d:aac5%5
</code></pre>
<p>The code to connect to... | 0 | 2016-07-04T18:48:11Z | 38,225,505 | <p>If you wait to connect until the instance is "running" this error does not occur.</p>
| 0 | 2016-07-06T13:40:42Z | [
"python",
"amazon-web-services",
"paramiko"
] |
One class-based view object for multiple urls depending on parameters | 38,190,758 | <p>I have multiple urls whose mission is almost identical (generate a list page with the corresponding context). So my <code>urlpatterns</code> is something like:</p>
<pre><code>url('^by-country/(?<arg1>\w+)', MyO.as_view(), name='by-country'),
url('^by-period/(?<arg1>\w+)', MyO.as_view(), name='by-period'... | 1 | 2016-07-04T18:54:47Z | 38,190,922 | <p>All url patterns accept a third positional argument, which is a dict of extra parameters to pass to the view that are not derived from the regex itself. So:</p>
<pre><code>url('^by-country/(?<arg1>\w+)', MyO.as_view(), {'category': 'by-country'}, name='by-country'),
</code></pre>
| 1 | 2016-07-04T19:07:10Z | [
"python",
"django"
] |
How can I use lxml to get text between empty elements | 38,190,762 | <p>How can I use lxml to get text between empty elements?</p>
<p>Example: </p>
<pre><code><tagx page="1"/>Target Text<tagx page="2"/>
</code></pre>
| -2 | 2016-07-04T18:55:18Z | 38,206,499 | <p>"Target Text" is the <code>tail</code> of the first <code><tagx></code> element. </p>
<p>Reference: <a href="http://lxml.de/api/lxml.etree._Element-class.html#tail" rel="nofollow">http://lxml.de/api/lxml.etree._Element-class.html#tail</a>.</p>
| 0 | 2016-07-05T14:49:35Z | [
"python",
"lxml"
] |
Custom colormap in matplotlib for 3D surface plot | 38,190,799 | <p>I have a surface plot with a specified colormap. Following is how I get it:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
import math
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import plaque_vessel_models
# Model creation
ptX= []
ptY = []
ptZ = []
ptX1 = []
ptY1 = []
ptZ1... | 0 | 2016-07-04T18:57:49Z | 38,190,996 | <pre><code>m.set_clim(vmin=0.5, vmax=1.0)
</code></pre>
| 1 | 2016-07-04T19:13:26Z | [
"python",
"matplotlib",
"colormap"
] |
Python 3 - Only iterate files that are currently open | 38,190,845 | <p>I have two files open in system. The user gives some input, and then the script chooses which file to close. <strong>I must close one of the files.</strong></p>
<p>However, I have a for loop later on. Since I do not know which one of the files will stay open, and I need to iterate over the rows and columns of one o... | 0 | 2016-07-04T19:01:34Z | 38,191,006 | <p>Only create the csv object after the user chooses:</p>
<pre><code>with open("file1.csv","r") as a, open ("file2.csv","r") as b:
Question=input(Questions[0]).title()
if Question =='something':
r = csv.reader(b)
a.close()
elif Question == 'something_else':
b.close()
r = cs... | 0 | 2016-07-04T19:14:23Z | [
"python",
"python-3.x",
"csv",
"for-loop",
"iterator"
] |
Exe created by Pyinstaller runs on one machine, but gives error on another | 38,190,861 | <p>Host OS: Windows 10, 64-bit</p>
<p>Python: Version 2.7, 32-bit</p>
<p>For <strong>Ethical Hacking</strong>, I am following video, <a href="https://www.youtube.com/watch?v=8BiOPBsXh0g" rel="nofollow">Ethical Hacking Python Keylogger</a></p>
<p>I created the code per the video, </p>
<pre><code>import pyHook, pytho... | 0 | 2016-07-04T19:02:30Z | 38,191,056 | <p>You don't have to install the dll(s) required to run the program. They do however have to be available. This can be achieved by including them in the current working directory of where the .exe file is located. </p>
<p><strong>Additional information:</strong>
The DLLs missing here are part of <em>Microsoft's Visual... | 1 | 2016-07-04T19:18:34Z | [
"python",
"windows",
"dll",
"pyinstaller",
"hacking"
] |
Function averaging values in list of dictionaries | 38,190,890 | <p>I have 3 dictionaries:</p>
<pre><code>zosia = {'imie': 'Zosia', 'zadania': 1, 'quizy': 2, 'testy': 5 },
jas = {'imie': 'Jas', 'zadania': 5, 'quizy': 5, 'testy': 5 },
malgosia = {'imie': 'Malgosia', 'zadania': 3, 'quizy': 3, 'testy': 4 }
</code></pre>
<p>And list that contains them: </p>
<pre><code>studenci = [z... | -3 | 2016-07-04T19:04:29Z | 38,190,975 | <p>Just chain the values and use <code>sum()</code> and <code>len()</code> to average them. Note that you cannot have a comma after the dicts in your question; that wraps them into tuples.</p>
<pre><code>from __future__ import division # only use this if you are in python 2.7
from itertools import chain
zosia = {'imi... | 2 | 2016-07-04T19:11:50Z | [
"python",
"list",
"dictionary"
] |
Function averaging values in list of dictionaries | 38,190,890 | <p>I have 3 dictionaries:</p>
<pre><code>zosia = {'imie': 'Zosia', 'zadania': 1, 'quizy': 2, 'testy': 5 },
jas = {'imie': 'Jas', 'zadania': 5, 'quizy': 5, 'testy': 5 },
malgosia = {'imie': 'Malgosia', 'zadania': 3, 'quizy': 3, 'testy': 4 }
</code></pre>
<p>And list that contains them: </p>
<pre><code>studenci = [z... | -3 | 2016-07-04T19:04:29Z | 38,191,088 | <pre><code>'Returns a list of the "averages" of each dictionary'
def dict_average(*args):
averages = []
for arg in args:
values = arg.values()
s = 0
i = 0
for v in values:
try:
s += v
i += 1
except TypeError:
... | 0 | 2016-07-04T19:21:35Z | [
"python",
"list",
"dictionary"
] |
Genetic Algorithm / AI; basically, am I on the right track? | 38,190,923 | <p>I know Python isn't the best idea to be writing any kind of software of this nature. My reasoning is to use this type of algorithm for a Raspberry Pi 3 in it's decision making (still unsure how that will go), and the libraries and APIs that I'll be using (Adafruit motor HATs, Google services, OpenCV, various sensors... | -1 | 2016-07-04T19:07:13Z | 38,233,890 | <p>I'm working with evolutionary computation right now so I hope my answer will be helpful for you, personally, I work with java, mostly because is one of my main languages, and for the portability, because I tested in linux, windows and mac. In my case I work with permutation encoding, but if you are still learning ho... | 3 | 2016-07-06T21:15:27Z | [
"python",
"artificial-intelligence",
"genetic-algorithm",
"genetic-programming",
"genetic"
] |
Genetic Algorithm / AI; basically, am I on the right track? | 38,190,923 | <p>I know Python isn't the best idea to be writing any kind of software of this nature. My reasoning is to use this type of algorithm for a Raspberry Pi 3 in it's decision making (still unsure how that will go), and the libraries and APIs that I'll be using (Adafruit motor HATs, Google services, OpenCV, various sensors... | -1 | 2016-07-04T19:07:13Z | 38,424,247 | <p>Just to add a bit to Alberto's great answer, you need to watch out for two issues as your solution evolves.</p>
<p>The first one is Over-fitting. This basically means that your solution is complex enough to "learn" all samples, but it is not applicable outside the training set. To avoid this, your need to make ... | 1 | 2016-07-17T17:54:38Z | [
"python",
"artificial-intelligence",
"genetic-algorithm",
"genetic-programming",
"genetic"
] |
Creating simple if statement in Python when pining IP address | 38,191,011 | <p>I'm using: Windows I'm trying to create a simple <code>if</code> statement when pinging ip address</p>
<pre><code>import os
hostname = "192.168.8.8." #example
response = os.system("ping -c 1 " + hostname)
#and then check the response...
if response == 0:
print hostname, 'is down'
else:
print hostname, 'is u... | 1 | 2016-07-04T19:14:35Z | 38,191,141 | <p><em>os.system() returns the process exit value. 0 means success.</em></p>
<p>In your case it is getting executed successfully and hence it is returning 0. All you have to do is get the complete output from the ping command and then do string comparison to find out if that IP is alive.</p>
<p>You need to use <a hre... | 1 | 2016-07-04T19:25:47Z | [
"python",
"ip",
"ping"
] |
Creating simple if statement in Python when pining IP address | 38,191,011 | <p>I'm using: Windows I'm trying to create a simple <code>if</code> statement when pinging ip address</p>
<pre><code>import os
hostname = "192.168.8.8." #example
response = os.system("ping -c 1 " + hostname)
#and then check the response...
if response == 0:
print hostname, 'is down'
else:
print hostname, 'is u... | 1 | 2016-07-04T19:14:35Z | 38,191,159 | <p>Use a variation of my answer <a href="http://stackoverflow.com/questions/35768878/detecting-internet-for-a-specific-interface-over-python/35769171#35769171">here</a> removing the interface argument <code>subprocess.check_call</code>:</p>
<pre><code>from subprocess import check_call, CalledProcessError, PIPE
def is... | 0 | 2016-07-04T19:27:01Z | [
"python",
"ip",
"ping"
] |
Creating simple if statement in Python when pining IP address | 38,191,011 | <p>I'm using: Windows I'm trying to create a simple <code>if</code> statement when pinging ip address</p>
<pre><code>import os
hostname = "192.168.8.8." #example
response = os.system("ping -c 1 " + hostname)
#and then check the response...
if response == 0:
print hostname, 'is down'
else:
print hostname, 'is u... | 1 | 2016-07-04T19:14:35Z | 38,191,237 | <p>You did everything okay, The only issue is that you confused the correct output which is 0 with the wrong output, which is everything above 0.</p>
<pre><code>import os
hostname = "192.168.8.8." #example
response = os.system("ping -c 1 " + hostname)
#and then check the response...
if response == 0:
print hostna... | -1 | 2016-07-04T19:35:07Z | [
"python",
"ip",
"ping"
] |
Float Object is not Callable Error in Python | 38,191,114 | <pre><code>degrees = float()
fahrenheit = float()
celsius = float()
meters = float()#decs.
feet = float()
selection = str()
def main():#main program
print("Here are your choices: \n C = celsius \n M = meters \n E = exit")
selection = input("Enter your selection")
while selection != "e":
if selectio... | 1 | 2016-07-04T19:24:21Z | 38,191,153 | <p>You have a name conflict: <code>degrees</code> and <code>meters</code> were defined as floats and then as functions. The float names are called instead of the functions which are defined at some later point in your module. </p>
<blockquote>
<p><strong>floats</strong> are not callable</p>
</blockquote>
<hr>
<p>Y... | 2 | 2016-07-04T19:26:41Z | [
"python"
] |
getting specific dict property values from multiple lists | 38,191,146 | <p>Say I have a Dict that looks like so...</p>
<pre><code>values = {
'student': [{
'field': 'prefix',
'description': 'First name'
},
{
'field': 'suffix',
'description': 'Last name'
... | 3 | 2016-07-04T19:26:09Z | 38,191,216 | <p>You get the error because the dictionary is one level deeper than your loop, and you can call <code>items()</code> on the dictionary to get the values part:</p>
<pre><code>[v1['field'] for k, v in values.items() for v1 in v]
# ['prefix', 'suffix', 'student_email', 'course_code']
</code></pre>
| 5 | 2016-07-04T19:33:12Z | [
"python",
"python-3.x"
] |
getting specific dict property values from multiple lists | 38,191,146 | <p>Say I have a Dict that looks like so...</p>
<pre><code>values = {
'student': [{
'field': 'prefix',
'description': 'First name'
},
{
'field': 'suffix',
'description': 'Last name'
... | 3 | 2016-07-04T19:26:09Z | 38,191,319 | <p>If you just need to gather those strings in a list but you are not constrained to arrange them in a specific order, this should work:</p>
<pre><code>>>> from itertools import chain
>>> [x['field'] for x in chain(*values.values())]
['course_code', 'prefix', 'suffix', 'student_email']
</code></pre>
... | 2 | 2016-07-04T19:41:13Z | [
"python",
"python-3.x"
] |
getting specific dict property values from multiple lists | 38,191,146 | <p>Say I have a Dict that looks like so...</p>
<pre><code>values = {
'student': [{
'field': 'prefix',
'description': 'First name'
},
{
'field': 'suffix',
'description': 'Last name'
... | 3 | 2016-07-04T19:26:09Z | 38,191,541 | <p>You could also do it completely functionally combining, <a href="https://docs.python.org/3/library/functions.html#map" rel="nofollow">map</a>, <a href="https://docs.python.org/3/library/itertools.html#itertools.chain.from_iterable" rel="nofollow">itertools.chain.from_iterable</a> and <a href="https://docs.python.org... | 1 | 2016-07-04T20:03:03Z | [
"python",
"python-3.x"
] |
Regex Search Expected Strings Or Byte Like Objects | 38,191,161 | <pre><code>import os
import codecs
import argparse
os.chdir('C:\\Users\\Kingsaber\\Desktop\\python_excercises')
a = codecs.open('BeforeKichiku.txt', encoding='utf-8')
p = a.read()
print(p)
import re
#ch = u"I am from ç¾å½ãWe should be friends. æå."
b = re.findall(u"[\u4e00-\u9fff]+", a)
for x in b:
print... | -3 | 2016-07-04T19:27:09Z | 38,196,915 | <p>You are passing in the <em>file object</em>:</p>
<pre><code>a = codecs.open('BeforeKichiku.txt', encoding='utf-8')
# ...
b = re.findall(u"[\u4e00-\u9fff]+", a)
</code></pre>
<p>Note how <code>a</code> is the <code>codecs.open()</code> result, and you pass <code>a</code> into <code>re.findall()</code>. You put th... | 0 | 2016-07-05T06:49:42Z | [
"python",
"regex",
"python-3.5"
] |
Subtract pandas dataframes while leaving some columns intact | 38,191,307 | <p>Suppose I have two dataframes:</p>
<pre><code>data1 = """
idx, stat, val
1, 1, 5
2, 1, 10
3, 2, 15
4, 3, 20
"""
data2 = """
idx, stat, val
2, 1, 8
4, 5, 16
"""
</code></pre>
<p>(sorry - I don't know how to code this easily in pandas - I would read them in from csv in real life).</p>
<p>I would like to subtract th... | 1 | 2016-07-04T19:40:30Z | 38,191,460 | <p>You can use:</p>
<pre><code>df1.set_index(['idx','stat'], inplace=True)
df2.set_index('idx', inplace=True)
print (df1.sub(df2[['val']]))
val
idx stat
1 1 NaN
2 1 2.0
3 2 NaN
4 3 4.0
print (df1.sub(df2[['val']]).reset_index())
idx stat val
0 1 1 NaN
1 2 1 ... | 1 | 2016-07-04T19:54:24Z | [
"python",
"pandas",
"dataframe"
] |
installing lxml via cmd | 38,191,374 | <p>I am trying to install a lxml file but I am getting several errors. Most notable when i enter the command </p>
<blockquote>
<p><strong><em>python lxml.py install</em></strong></p>
</blockquote>
<p>I am returned with two error messages as shown in image <a href="http://i.stack.imgur.com/ztmpf.jpg" rel="nofollow">... | 0 | 2016-07-04T19:46:54Z | 38,192,654 | <p>So the solution to my problem is as follows.</p>
<p>1- I installed mingw installation manager and downloaded the corresponding packages</p>
<p>2- afterwards I ran <strong><em>pythom -m pip install lxml-3.6.0-cp35-cp35m-win32.whl</em></strong> which worked thanks to minGW.</p>
<p>3- I then ran <strong><em>python -... | 1 | 2016-07-04T21:52:33Z | [
"python",
"python-2.7",
"python-3.x",
"pip"
] |
Extract a value from each text file obeying a naming convention - how? | 38,191,376 | <p>I need to extract the last number in the last line of each text file in a directory. Can someone get me started on this in Python? The data is information formatted as follows:</p>
<pre><code># time 'A' 'B'
0.000000E+00 10000 0
1.000000E+05 7742 2263
</code></pre>
<p>where the '#' column is empty in each file.... | 1 | 2016-07-04T19:47:08Z | 38,191,464 | <p>This code should get you started. As far as the directory has only those files for which you need the last number, the naming convention can be ignored. Because, you can rather look up all of the file in that directory.</p>
<pre><code>import glob
last_numbers = []
for filename in glob.glob("/path/to/directory/*"):... | 2 | 2016-07-04T19:54:45Z | [
"python",
"file",
"text",
"extract"
] |
Scrapy contracts with multiple parse methods | 38,191,402 | <p>What's the best approach to write contracts for Scrapy spiders that have more than one method to parse the response?
I saw this <a href="http://stackoverflow.com/questions/27368342/how-to-add-attributes-to-a-request-in-a-scrapy-contract">answer</a> but it didn't sound very clear to me.</p>
<p>My current example: I ... | 2 | 2016-07-04T19:49:05Z | 38,193,550 | <p>Frankly, I don't use Scrapy contracts and I don't really recommend anyone to use them either. They have <a href="https://github.com/scrapy/scrapy/issues/1918" rel="nofollow">many issues</a> and <a href="https://github.com/scrapy/scrapy/issues/1777#issuecomment-184272838" rel="nofollow">someday may be removed from Sc... | 3 | 2016-07-05T00:05:02Z | [
"python",
"unit-testing",
"scrapy",
"web-crawler",
"contracts"
] |
SQL Alchemy : cannot connect using engine.connect() | 38,191,437 | <p>I am using sqlalchemy and pandas to connect to db and create the dataframe from sql table.</p>
<p>This is my code:</p>
<pre><code>port=3306
unix_socket='/var/lib/mysql/mysql.sock'
conn = "mysql://user:pwd@localhost/dbname?port=3306?unix_socket=/var/lib/mysql/mysql.sock"
_engine = create_engine(conn)
print conn
p... | 0 | 2016-07-04T19:52:27Z | 38,198,680 | <p>Your connection string looks wrong. The <a href="http://docs.sqlalchemy.org/en/latest/dialects/mysql.html#module-sqlalchemy.dialects.mysql.mysqldb" rel="nofollow">sqlalchemy documentation</a> states the following string: <code>mysql+mysqldb://<user>:<password>@<host>[:<port>]/<dbname></... | 0 | 2016-07-05T08:31:08Z | [
"python",
"python-2.7",
"sqlalchemy"
] |
Django Social Auth access first_name and last_name | 38,191,566 | <p>I've been trying to get Facebook login to work for my Django application. I have a custom user, except it seems that upon Facebook authentication, Facebook only passes back the user's username, whereas I would like the username, email, first_name, last_name, and profile picture. The other problem I have is that upon... | 0 | 2016-07-04T20:04:56Z | 38,195,103 | <p>Define this setting:</p>
<pre><code>SOCIAL_AUTH_FACEBOOK_EXTRA_DATA = ['first_name', 'last_name']
Then you can access those values with:
social = user.social_auth.get(provider='facebook')
userid = social.uid
first_name = social.extra_data['first_name']
last_name = social.extra_data['last_name']
</code></pre>
| 0 | 2016-07-05T04:17:22Z | [
"python",
"django",
"facebook",
"authentication"
] |
Errors when connecting to nxt brick | 38,191,619 | <p>I'm using nxt-python to connect to my nxt brick from my raspberry pi.</p>
<p>After some struggle with the python 3.2 versions of the bluetooth and usb libraries it requires i've managed to get it to connect via bluetooth and ask for a passkey. After some more struggle i found that i could type <code>bluetooth-agent... | 0 | 2016-07-04T20:10:05Z | 38,194,049 | <p>I've downloaded the v2.2.2 stable instead of cloning the master commit and it runs fine under python2. Too bad it isn't python3 though.</p>
| 0 | 2016-07-05T01:37:36Z | [
"python",
"bluetooth",
"raspberry-pi",
"usb",
"nxt-python"
] |
Get .csv-file with Python from url | 38,191,627 | <p>I'm trying to get a .csv-file from a url with Python. When I use the url in a browser I get the .csv-file downloaded but when I'm using this script I'm only getting html-code.</p>
<pre><code>__file_url__ = "http://myurl.com/?export"
data = urllib2.urlopen(__file_url__)
for line in data:
print(li... | -2 | 2016-07-04T20:10:43Z | 38,220,077 | <p>I am super stupid. It's required to be logged in to download this. And ofcourse, when making the request from Python I was not logged in. So, I needed to use the session from the request lib to first post a login formular and then ask for the file again and wiola - there's my file.</p>
<pre><code>from requests impo... | 0 | 2016-07-06T09:03:15Z | [
"python",
"file",
"csv",
"download"
] |
How to determine most curvature points of a graph in python | 38,191,658 | <p>I have a figure that I get contour lines from a picture of face use by opencv (image below). I need to determine most curvature points of this contour in python (in the image, I need to define the red dots on right of the red line). How can I do it ?</p>
<p><a href="http://i.stack.imgur.com/YSNWw.png" rel="nofollow... | 2 | 2016-07-04T20:14:17Z | 38,199,319 | <p>Just find contour and compute curvature then find maximums: <a href="https://en.wikipedia.org/wiki/Curvature" rel="nofollow">curvature</a></p>
<p>This article also may be useful: <a href="http://www.morethantechnical.com/2012/12/07/resampling-smoothing-and-interest-points-of-curves-via-css-in-opencv-w-code/" rel="n... | 1 | 2016-07-05T09:04:26Z | [
"python",
"opencv",
"image-processing"
] |
Usage of Django-Filter on large tables along with DataTables2 | 38,191,704 | <p>I am using Django-Tables2 with following code to load the data on to data tables.</p>
<pre><code>sales_data = SalesTable(sale.objects.all().order_by('-time'))
RequestConfig(request,paginate={'per_page': 50}).configure(sales_data)
</code></pre>
<p>My Sales table has 1.4 million rows and yet, the above method of Req... | 1 | 2016-07-04T20:18:31Z | 38,206,470 | <p>In CBV, instead of filter, filter.qs has to be passed. In the previous case, entire table is loaded to memory and hence loading time is more and browser crashes happening. </p>
<p>With this modification, both empty filter & filterform query sets are loaded with LIMIT Query.</p>
<p><strong>views.py</strong></p>... | 2 | 2016-07-05T14:48:24Z | [
"python",
"django",
"datatables",
"django-filter",
"django-tables2"
] |
pyplot legend for scatter plot colored by values | 38,191,710 | <p>When I use a variable for coloring a scatter plot, how can I make a legend stating what colors represent? How can I make the legend show a label of <code>0</code> represents empty and <code>1</code> represents full? </p>
<pre><code>import matplotlib.pyplot as plt
X = [1,2,3,1,2,3,4]
Y = [1,1,1,2,2,2,2]
label = [0,1... | 1 | 2016-07-04T20:18:54Z | 38,192,314 | <p>Give this code a try:</p>
<pre><code>import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
X = [1, 2 ,3, 1, 2, 3, 4]
Y = [1, 1, 1, 2, 2, 2, 2]
labels = [0, 1, 1, 0, 0, 1, 1]
key = {0: ('red', 'empty'), 1: ('green', 'full')}
plt.scatter(X, Y, c=[key[index][0] for index in labels], s=50)
patches = [mp... | 2 | 2016-07-04T21:16:59Z | [
"python",
"matplotlib"
] |
Problems with moving character in python game and other issues | 38,191,791 | <p>I am making a pygame game and the player does not always move to the arrow keys I press. Here is the code for moving the player.</p>
<pre><code>def playerstuff(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pyga... | 1 | 2016-07-04T20:25:32Z | 38,197,788 | <p>You're probably throwing away events in your global event queue. You check the event queue twice, once in <code>playerstuff()</code> and once in your global game loop, but the second time you don't deal with keypress events.</p>
<pre><code>def game():
gameDisplay.blit(Town,(0,0))
player1 = Player(w... | 0 | 2016-07-05T07:38:35Z | [
"python",
"pygame"
] |
User Auth in Django | 38,191,835 | <p>I started learning Django last week and I thought the best way is to just build an App. I'm stuck now with the User Auth module with my tests. Maybe someone could help me out:
I want to model employees in the db and also put them in the User Auth model, so I build the model and after a few checks I want to add it t... | 0 | 2016-07-04T20:29:38Z | 38,192,083 | <p>If you want to create a custom user model you should use AbstractBaseUser.</p>
<p><a href="https://docs.djangoproject.com/es/1.9/topics/auth/customizing/#specifying-a-custom-user-model" rel="nofollow">https://docs.djangoproject.com/es/1.9/topics/auth/customizing/#specifying-a-custom-user-model</a></p>
| 1 | 2016-07-04T20:51:32Z | [
"python",
"django",
"authentication",
"user"
] |
Zero pad numpy array | 38,191,855 | <p>What's the more pythonic way to pad an array with zeros at the end?</p>
<pre><code>def pad(A, length):
...
A = np.array([1,2,3,4,5])
pad(A, 8) # expected : [1,2,3,4,5,0,0,0]
</code></pre>
<hr>
<p>In my real use case, in fact I want to pad an array to the closest multiple of 1024. Ex: 1342 => 2048, 3000 ... | 2 | 2016-07-04T20:31:21Z | 38,191,927 | <p>This should work:</p>
<pre><code>def pad(A, length):
arr = np.zeros(length)
arr[:len(A)] = A
return arr
</code></pre>
<p>You <em>might</em> be able to get slightly better performance if you initialize an empty array (<code>np.empty(length)</code>) and then fill in <code>A</code> and the <code>zeros</co... | 1 | 2016-07-04T20:37:12Z | [
"python",
"numpy"
] |
Zero pad numpy array | 38,191,855 | <p>What's the more pythonic way to pad an array with zeros at the end?</p>
<pre><code>def pad(A, length):
...
A = np.array([1,2,3,4,5])
pad(A, 8) # expected : [1,2,3,4,5,0,0,0]
</code></pre>
<hr>
<p>In my real use case, in fact I want to pad an array to the closest multiple of 1024. Ex: 1342 => 2048, 3000 ... | 2 | 2016-07-04T20:31:21Z | 38,191,964 | <p>You could also use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.pad.html" rel="nofollow"><code>numpy.pad</code></a>:</p>
<pre><code>>>> A = np.array([1,2,3,4,5])
>>> npad = 8 - len(A)
>>> np.pad(A, pad_width=npad, mode='constant', constant_values=0)[npad:]
array([1, ... | 1 | 2016-07-04T20:40:56Z | [
"python",
"numpy"
] |
Zero pad numpy array | 38,191,855 | <p>What's the more pythonic way to pad an array with zeros at the end?</p>
<pre><code>def pad(A, length):
...
A = np.array([1,2,3,4,5])
pad(A, 8) # expected : [1,2,3,4,5,0,0,0]
</code></pre>
<hr>
<p>In my real use case, in fact I want to pad an array to the closest multiple of 1024. Ex: 1342 => 2048, 3000 ... | 2 | 2016-07-04T20:31:21Z | 38,191,981 | <p>There's <code>np.pad</code>:</p>
<pre><code>A = np.array([1, 2, 3, 4, 5])
A = np.pad(A, (0, length), mode='constant')
</code></pre>
<p>Regarding your use case, the required number of zeros to pad can be calculated as <code>length = len(A) + 1024 - 1024 % len(A)</code>.</p>
| 0 | 2016-07-04T20:42:36Z | [
"python",
"numpy"
] |
Zero pad numpy array | 38,191,855 | <p>What's the more pythonic way to pad an array with zeros at the end?</p>
<pre><code>def pad(A, length):
...
A = np.array([1,2,3,4,5])
pad(A, 8) # expected : [1,2,3,4,5,0,0,0]
</code></pre>
<hr>
<p>In my real use case, in fact I want to pad an array to the closest multiple of 1024. Ex: 1342 => 2048, 3000 ... | 2 | 2016-07-04T20:31:21Z | 38,192,105 | <p>Use <code>numpy.pad</code>:</p>
<pre><code>B = np.pad(A, (0, 1024 - len(A)%1024), 'constant')
B
# array([1, 2, 3, ..., 0, 0, 0])
len(B)
# 1024
</code></pre>
<p>For a larger <code>A</code>:</p>
<pre><code>A = np.ones(3000)
B = np.pad(A, (0, 1024 - len(A)%1024), 'constant')
B
# array([ 1., 1., 1., ..., 0., 0., ... | 2 | 2016-07-04T20:53:50Z | [
"python",
"numpy"
] |
Is it possible to use the K++ initialization procedure that k-means uses in scikit/sklearn learn? | 38,191,930 | <p>I was reading the documentation for <a href="http://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html" rel="nofollow">k-means</a> and I saw that it uses <a href="https://en.wikipedia.org/wiki/K-means%2B%2B" rel="nofollow">k++</a> as initialization. Is it possible to use its k++ initialization fun... | 1 | 2016-07-04T20:37:29Z | 38,198,644 | <p>It's not implemented in scipy. There's a pull request implementing it, but it stalled.
<a href="https://github.com/scipy/scipy/pull/4119" rel="nofollow">https://github.com/scipy/scipy/pull/4119</a></p>
| 0 | 2016-07-05T08:28:53Z | [
"python",
"numpy",
"machine-learning",
"scipy",
"scikit-learn"
] |
How to scrape datetime ind different format using django-dynamic-scraper | 38,192,025 | <p>I am new in django and perhaps my problem is easy to solve but i cant find any way to resolve it in docs. I want to crape datetime from webside and store it in model as datetime field. In documentation i found something like date preprocesor but it works only for eng(and den?) language. For instance my datetime on p... | 0 | 2016-07-04T20:46:17Z | 38,192,853 | <p>I don't know about django-dynamic-scraper, but <code>DateTimeField</code> in Django supports multiple input formats:</p>
<pre><code>>>> dt_field = DateTimeField(input_formats=['%Y-%m-%d %H:%M:%S', '%Y/%m/%d'])
>>> dt_field.clean("2012-11-12 11:12:23")
datetime.datetime(2012, 11, 12, 11, 12, 23, tz... | 0 | 2016-07-04T22:17:16Z | [
"python",
"django",
"datetime",
"django-dynamic-scraper"
] |
Simplest way to find the difference between two dates in pandas | 38,192,080 | <p>I'm trying to find the difference between two dates in a multi index data frame that is the result of a pivot table operation.</p>
<p>The data frame contains three columns. The first is a <code>measurement</code> the second is the <code>end date</code> and the third is the <code>start date</code>.</p>
<p>I've been... | 1 | 2016-07-04T20:51:23Z | 38,192,236 | <p>You can select <code>Multiindex</code> in columns by <code>tuples</code> and subtract columns:</p>
<pre><code>print (df)
a
meas end start
0 7 2015-04-05 2015-04-01
1 8 2015-04-07 2015-04-02
2 9 2015-04-14 2015-04-04
#if dtypes not datetime
df[('a','end')]... | 0 | 2016-07-04T21:07:48Z | [
"python",
"pandas",
"dataframe",
"time-series",
"multi-index"
] |
Bash if else then in one line with bash version of sys.exit() | 38,192,116 | <p>I am running this bash command:</p>
<pre><code>xe pbd-unplug uuid=$PBDUUID
</code></pre>
<p>If the result exists - i.e. if the variable <code>PBDUUID</code> is not empty then I would like to run another command:</p>
<pre><code>xe sr-forget uuid=$SRUUID
</code></pre>
<p>However, if the variable is blank then I wo... | 0 | 2016-07-04T20:55:40Z | 38,192,175 | <pre><code>if xe pbd-unplug uuid="$PBDUUID"; then xe sr-forget "uuid=$SRUUID"; else echo "Error: No PBD."; exit 1; fi
</code></pre>
<p>More readably, that is:</p>
<pre><code>if xe pbd-unplug uuid="$PBDUUID"; then
xe sr-forget "uuid=$SRUUID"
else
echo "Error: No PBD." >&2
exit 1
fi
</code></pre>
<p>BTW, ... | 2 | 2016-07-04T21:01:01Z | [
"python",
"linux",
"bash"
] |
Getting content of specific cells from table | 38,192,121 | <p>I am trying to parse patent data from, e.g., <a href="http://patft.uspto.gov/netacgi/nph-Parser?Sect1=PTO2&Sect2=HITOFF&p=1&u=%2Fnetahtml%2FPTO%2Fsearch-bool.html&r=1&f=G&l=50&co1=AND&d=PTXT&s1=boston&s2=2005$.PD.&OS=boston%20AND%20ISD/2005&RS=boston%20AND%20ISD/2005" ... | 1 | 2016-07-04T20:56:10Z | 38,201,566 | <p>It is a bit more involved, you really need to use a regex to find the rows you want as there are line breaks in the text so you cannot just specify <code>text="Family ID":</code> etc.., this will get all the links from the site and write the three rows of interest if available, if the row is nto there the csv will h... | 0 | 2016-07-05T10:51:46Z | [
"python",
"parsing",
"beautifulsoup"
] |
How to indent entire strings of text in text file? | 38,192,148 | <p>I have a dictionary:</p>
<pre><code>page_info = {'LISTS':['string 1', 'string 2']}
</code></pre>
<p>I want to print to a text file with the word 'LISTS' being the header and values of key appearing below it and indented one space to the right. </p>
<pre><code>with codecs.open(stats_file, 'a', encoding="utf8") as ... | 0 | 2016-07-04T20:59:06Z | 38,192,183 | <p>Use the <a href="https://docs.python.org/2/library/textwrap.html" rel="nofollow"><code>textwrap</code> module</a> to wrap your lines and add indentation to each line:</p>
<pre><code>wrapper = textwrap.TextWrapper(initial_indent='\t', subsequent_indent='\t')
for tag in page_info['LISTS']:
wrapped = wrapper.fill(... | 2 | 2016-07-04T21:02:10Z | [
"python",
"text-files"
] |
Cannot easy_install IMDbPY | 38,192,172 | <p>I'm trying to install the IMDbPY module to Python using easy_install. However, I've never used Python before and kept getting stuck on using easy_install or pip install. Since I'm using Windows 7, I tried running the following code in command prompt:</p>
<p>easy_install IMDbPY</p>
<p>A flashing cursor then appears... | 0 | 2016-07-04T21:00:46Z | 38,193,742 | <p>I was able to bypass using easy_install by changing the directory to each package's installation folder and running "python setup.py install" in command prompt. </p>
| 0 | 2016-07-05T00:40:09Z | [
"python",
"windows-7",
"easy-install",
"imdbpy"
] |
Easy way to view and save the binary of a file? | 38,192,211 | <p>What is the easiest way to get the underlying binary code(0s and 1s) for a given file? The context for this question is that I want a python function which takes a file name, looks it up and gathers the binary code for that file before either storing it somewhere or returning it. After this I want to do some manipul... | -1 | 2016-07-04T21:05:50Z | 38,192,262 | <p>The underlying code for a file is available form the <code>.read()</code> method of the file object. Use the <code>b</code> mode modifier when you open the file: </p>
<pre><code>with open("input_file.bin", "rb") as input_file:
bits = input_file.read()
</code></pre>
<p>If you want to easily manipulate the bits... | 1 | 2016-07-04T21:10:47Z | [
"python",
"file",
"binary"
] |
Interleaving and searching through Logfiles | 38,192,237 | <p>I have multiple GB of logfiles which I want to search through. Every log has a timestamp, message and additional multiple fields, so each log consists of multiple lines looking like this:</p>
<pre><code>Mon Jan 20 12:00:00 2016 127.0.0.1:12345 Hello World!
Field_1 = foo
Field_2 = bar
... (some more fields)
<empt... | -2 | 2016-07-04T21:07:48Z | 38,192,383 | <p>I would definitely recommend that you would look at <a href="https://docs.python.org/3/library/re.html" rel="nofollow">regular expressions</a>
, they have all the things you need! You could make a script that compiles the regex template and then use <code>re.findall(regex_template, your_log_variable)</code> < Jus... | 0 | 2016-07-04T21:22:50Z | [
"python",
"bash",
"sorting",
"search",
"logging"
] |
Performance: expand binary image (morphological dilation) | 38,192,456 | <p>I wrote a Cython function which expands a binary image (numpy array) by 1 pixel. So I want simply to expand the area where array values are 1.
Here is my naive approach:</p>
<pre><code>def expand_1px (numpy.ndarray[numpy.uint8_t, ndim = 2] A):
cdef int h = A.shape[0]
cdef int w = A.shape[1]
cdef numpy... | 1 | 2016-07-04T21:30:10Z | 38,212,919 | <p>There is a big issue with your function: you are doing more loops that you need.</p>
<pre><code>import cython
@wraparound(false)
def expand_1px(numpy.ndarray[numpy.uint8_t, ndim = 2] A):
cdef int h = A.shape[0]
cdef int w = A.shape[1]
cdef numpy.ndarray[numpy.uint8_t, ndim = 2] RES = numpy.zeros([h, ... | 1 | 2016-07-05T21:19:24Z | [
"python",
"performance",
"numpy",
"optimization",
"cython"
] |
converting a csv file to json + python with specific json format | 38,192,637 | <p>can I convert a csv file into json as follows:<br>
csv = headers in line1 with values below <br>
json = <code>[{"key1":"value1",...},{"key1":"value2",...}...]</code></p>
<p>This is my csv file:</p>
<pre><code>$ cat -v head_data.csv
"Rec Open Date","MSISDN","IMEI","Data Volume (Bytes)","Device Manufacturer","Device... | 1 | 2016-07-04T21:51:05Z | 38,193,687 | <p>If you don't care about key's order, just do:</p>
<pre><code>import csv
import json
json.dumps(list(csv.DictReader(open("file.csv"))))
</code></pre>
<p>Check <a href="https://docs.python.org/2/library/json.html" rel="nofollow">pretty printing</a> section on the manual for more options, or do</p>
<pre><code>json.d... | 2 | 2016-07-05T00:28:52Z | [
"python",
"json",
"csv"
] |
converting a csv file to json + python with specific json format | 38,192,637 | <p>can I convert a csv file into json as follows:<br>
csv = headers in line1 with values below <br>
json = <code>[{"key1":"value1",...},{"key1":"value2",...}...]</code></p>
<p>This is my csv file:</p>
<pre><code>$ cat -v head_data.csv
"Rec Open Date","MSISDN","IMEI","Data Volume (Bytes)","Device Manufacturer","Device... | 1 | 2016-07-04T21:51:05Z | 38,194,687 | <p>If you want to keep the order of the keys, don't use <code>csv.DictReader</code> since it overcomplicates things, just record the header and then <code>zip</code> it with each of the rows:</p>
<pre><code>import csv
from collections import OrderedDict
reader = csv.reader(open("text.csv"))
header = next(reader)
dat... | 1 | 2016-07-05T03:12:43Z | [
"python",
"json",
"csv"
] |
converting a csv file to json + python with specific json format | 38,192,637 | <p>can I convert a csv file into json as follows:<br>
csv = headers in line1 with values below <br>
json = <code>[{"key1":"value1",...},{"key1":"value2",...}...]</code></p>
<p>This is my csv file:</p>
<pre><code>$ cat -v head_data.csv
"Rec Open Date","MSISDN","IMEI","Data Volume (Bytes)","Device Manufacturer","Device... | 1 | 2016-07-04T21:51:05Z | 38,368,800 | <p>An alternative command line solution:</p>
<pre><code>$ pip install pyexcel-cli, pyexcel-text
$ pyexcel transcode --name-columns-by-row 0 --output-file-type json example.csv -
{"example.csv": [{"Data Volume (Bytes)": 63979, "Device Manufacturer": "Samsung SM-G935FD ", "Device Model": "Samsung SM-G935FD", "IMEI": 230... | 0 | 2016-07-14T08:09:10Z | [
"python",
"json",
"csv"
] |
Memory error loading a 1GB .accdb using pypyodbc and pandas | 38,192,651 | <p>I'm trying to do something that maybe is not possible or maybe should be done in a different way...</p>
<p>I have to read a 1 GB Access file and manipulate it in pandas; since <code>cursor.fetchall()</code> failed directly with <code>Memory Error</code>, I tried the function below in order to see when the memory er... | 1 | 2016-07-04T21:52:16Z | 38,193,141 | <p>I would use native pandas method - <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_sql.html" rel="nofollow">read_sql()</a> instead of fetching rows manually in loops:</p>
<pre><code>def msaccess_to_df (abs_path, query):
conn = pypyodbc.connect(
r"Driver={Microsoft Access Drive... | 0 | 2016-07-04T22:55:44Z | [
"python",
"ms-access",
"pandas",
"access",
"pypyodbc"
] |
Get value for only one JSON variable | 38,192,655 | <p>I want to get the value for <a href="https://www.bitstamp.net/api/v2/ticker/btcusd/" rel="nofollow"><code>last</code></a> with Python, using <code>requests</code> and <code>json</code>. I have this:</p>
<pre><code>import requests
import json
res = requests.get('https://www.bitstamp.net/api/v2/ticker/btcusd/')
prin... | -1 | 2016-07-04T21:52:58Z | 38,192,730 | <p><code>res.json()</code> will parse the responses json object, which you need to do, to access any value of it. So to access the value <code>last</code>, you need to do: <code>res.json()['last']</code></p>
| 0 | 2016-07-04T22:02:38Z | [
"python",
"json",
"parsing",
"request"
] |
Trying to convert an mp3 file to a Numpy Array, and ffmpeg just hangs | 38,192,663 | <p>I'm working on a music classification methodology with Scikit-learn, and the first step in that process is converting a music file to a numpy array. </p>
<p>After unsuccessfully trying to call ffmpeg from a python script, I decided to simply pipe the file in directly:</p>
<pre><code>FFMPEG_BIN = "ffmpeg"
cwd = (os... | 0 | 2016-07-04T21:54:11Z | 38,192,996 | <p>I recommend you pymedia or audioread or decoder.py. There are also pyffmpeg and similar modules for doing just that what you want. Take a look at pypi.python.org.</p>
<p>Of course, these will not help you turn the data into numpy array.</p>
<p>Anyway, this is how it is done crudely using piping to ffmpeg:</p>
<pr... | 1 | 2016-07-04T22:35:38Z | [
"python",
"numpy",
"ffmpeg",
"stream",
"scikit-learn"
] |
python text substitution 'str' object is not callable | 38,192,694 | <p>I want to substitute a variable name in an expression. However I get the error that str is not callable
Here is my example</p>
<pre><code>import numpy as np
import pandas as pd
raw_data = {'student_name': ['M1', 'M2', 'M3', 'M4', 'M5', 'M6', 'M7', 'M8', 'M9', 'M10', 'M11', 'M12'],
'vocal_grade': ['R', 'X',... | 0 | 2016-07-04T21:58:21Z | 38,192,736 | <p>The problem is that you passed a string to <code>map</code> which is expecting a dictionary in your case. In order for the map to treat it as a dictionary instead of a string, use <code>eval</code> to evaluate the string and get back the corresponding dictionary:</p>
<pre><code>x = 'vocal'
df[x+'_score'] = df[x+"_g... | -1 | 2016-07-04T22:02:56Z | [
"python",
"string",
"dictionary",
"text",
"substitution"
] |
python text substitution 'str' object is not callable | 38,192,694 | <p>I want to substitute a variable name in an expression. However I get the error that str is not callable
Here is my example</p>
<pre><code>import numpy as np
import pandas as pd
raw_data = {'student_name': ['M1', 'M2', 'M3', 'M4', 'M5', 'M6', 'M7', 'M8', 'M9', 'M10', 'M11', 'M12'],
'vocal_grade': ['R', 'X',... | 0 | 2016-07-04T21:58:21Z | 38,192,839 | <p>You can call <code>dict_sam_vocal</code> using a string like this:</p>
<p><code>df[x+'_score'] = df[x+"_grade"].map(globals()["dict_sam_"+x])</code></p>
| 0 | 2016-07-04T22:15:03Z | [
"python",
"string",
"dictionary",
"text",
"substitution"
] |
Scraping threads that are hundreds of pages deep w/ BeautifulSoup | 38,192,744 | <p>Python and BeautifulSoup newbie here.</p>
<p>I am trying to scrape a forum that has about 500 pages, each of which contains 50 individual threads. Some of these threads contain about 200 pages worth of posts. </p>
<p>I would like to write a program that can scrape the relevant parts of the whole forum in an automa... | 0 | 2016-07-04T22:03:50Z | 38,208,484 | <p>I solved this myself, so I'm posting the answer, just in case someone else might benefit. </p>
<p>So, the problem was that urlopen could not open the URL found in a list within a list.</p>
<p>In my case, each forum page had a maximum of 1 relevant internal link. Rather than asking my getNext_link function to retur... | 0 | 2016-07-05T16:36:21Z | [
"python",
"web-scraping",
"beautifulsoup"
] |
jython setup in Eclipse/PyCharm | 38,192,788 | <p>Using Python 2.7 on Mac, and IDE is PyCharm. Need to use some Java functions inside Python script, and prefer to use import of Python, for example <code>from com.a.b.c import fooFunc</code>, so that I can use <code>fooFunc</code> in Python script as a Python function. The Java functions are defined in <code>goo.jar<... | 1 | 2016-07-04T22:08:35Z | 38,193,480 | <p>Follow up on the comments above, yes if you are using pydev for eclipse, then that's just the plugin that allows for writing python code with eclipse. To install jython, there are a number of guides out there, but it boils down to a two step process:</p>
<ol>
<li><a href="http://search.maven.org/#search%7Cgav%7C1%7... | 1 | 2016-07-04T23:52:02Z | [
"java",
"python",
"osx",
"python-2.7",
"pycharm"
] |
Why are strings favored over defined symbols (constants)? | 38,192,807 | <p>I notice that Python frequently uses strings where you could use some kind of defined symbol, like a constant. For example, to paraphrase a sample of code from <code>argparse</code>:</p>
<pre class="lang-python prettyprint-override"><code>import argparse
parser = argparse.ArgumentParser(description='Process some i... | 0 | 2016-07-04T22:10:44Z | 38,192,890 | <p>many libraries do use "constants" ... including argparse</p>
<p>you could just as easily pass in <code>argparse._StoreConstAction</code></p>
<p>it also provides the following named constants</p>
<pre><code>SUPPRESS = '==SUPPRESS=='
OPTIONAL = '?'
ZERO_OR_MORE = '*'
ONE_OR_MORE = '+'
PARSER = 'A...'
REMAINDER = ... | 1 | 2016-07-04T22:23:00Z | [
"python"
] |
Replace head of a file with the contents of another file | 38,192,867 | <p>I have two files:</p>
<p>File A:</p>
<pre><code>line A_1
line A_2
line A_3
...
line A_n
</code></pre>
<p>File B:</p>
<pre><code>line B_1
line B_2
...
line B_n
line B_n+1
...
line B_m
</code></pre>
<p>I want the first <code>n</code> lines of file A to replace the first <code>n</code> lines of file B (<code>m >... | 0 | 2016-07-04T22:19:32Z | 38,192,951 | <pre><code>with open("newB.txt","wb") as fout:
with open("B.txt") as b:
for lineA,lineB in zip(open("A.txt"),b):
fout.write(lineA)
fout.writelines(b)
</code></pre>
<p>maybe ... I guess...</p>
| 1 | 2016-07-04T22:30:31Z | [
"python"
] |
Replace head of a file with the contents of another file | 38,192,867 | <p>I have two files:</p>
<p>File A:</p>
<pre><code>line A_1
line A_2
line A_3
...
line A_n
</code></pre>
<p>File B:</p>
<pre><code>line B_1
line B_2
...
line B_n
line B_n+1
...
line B_m
</code></pre>
<p>I want the first <code>n</code> lines of file A to replace the first <code>n</code> lines of file B (<code>m >... | 0 | 2016-07-04T22:19:32Z | 38,192,952 | <pre><code>with open(A) as fp_A:
for i, line in enumerate(fp_A):
if i <= n:
print(line)
else:
break
with open(B) as fp_B:
for i, line in enumerate(fp_B):
if i > n:
print(line)
</code></pre>
| 0 | 2016-07-04T22:30:31Z | [
"python"
] |
BFS issue, trying to find "children", my counter in my method seem to be wrong | 38,192,900 | <p>So my code is currently looking like this:</p>
<pre><code>def hamta():
ordlista=[]
fil=open("labb9text.txt")
ordlista=[]
for line in fil.readlines():
ordlista.append(line.strip())
return ordlista
def setlista():
ordlista=hamta()
setlista=set()
for a in ordlista:
if a... | 0 | 2016-07-04T22:24:11Z | 38,193,575 | <p>maybe difflib could help</p>
<pre><code>import difflib
difflib.SequenceMatcher(None, "fan", "fai").ratio()
0.6666666666666666
difflib.SequenceMatcher(None, "fan", "fin").ratio()
0.6666666666666666
</code></pre>
| 1 | 2016-07-05T00:09:34Z | [
"python",
"methods",
"counter",
"bfs"
] |
Create 2D lists in python with variable length indexed vectors | 38,192,915 | <p>I am working on an image processing problem where I have code that looks like this (the code written below just illustrates the type of problem I want to solve):</p>
<pre><code>for i in range(0,10):
for j in range(0,10):
number_length = round(random.random()*10)
a = np.zeros(number_length)
Z[i][j] = a... | 0 | 2016-07-04T22:25:50Z | 38,194,124 | <p>A NumPy array won't work because it requires fixed dimensions. You can use a 2d list (i.e. list of lists), where each element can be an array of arbitrary length. This is analogous to your setup in Matlab, using a 2d cell array of vectors.</p>
<p>Try this:</p>
<pre><code>z = [[np.zeros(np.random.randint(10)+1) for... | 2 | 2016-07-05T01:49:39Z | [
"python",
"arrays",
"matlab",
"list",
"vector"
] |
How can I update a specific value on a custom configuration file? | 38,192,920 | <p>Assuming I have a configuration txt file with this content:</p>
<pre><code>{"Mode":"Classic","Encoding":"UTF-8","Colors":3,"Blue":80,"Red":90,"Green":160,"Shortcuts":[],"protocol":"2.1"}
</code></pre>
<p>How can i change a specific value like <code>"Red":90</code> to <code>"Red":110</code> in the file without chan... | 0 | 2016-07-04T22:26:26Z | 38,193,016 | <p>this looks like json so you could:</p>
<pre><code>import json
obj = json.load(open("/path/to/jsonfile","r"))
obj["Blue"] = 10
json.dump(obj,open("/path/to/mynewfile","w"))
</code></pre>
<p>but be aware that a json dict does not have an order.
So the order of the elements is not guaranteed (and normally it's not ... | 1 | 2016-07-04T22:37:12Z | [
"python",
"configuration-files"
] |
How can I update a specific value on a custom configuration file? | 38,192,920 | <p>Assuming I have a configuration txt file with this content:</p>
<pre><code>{"Mode":"Classic","Encoding":"UTF-8","Colors":3,"Blue":80,"Red":90,"Green":160,"Shortcuts":[],"protocol":"2.1"}
</code></pre>
<p>How can i change a specific value like <code>"Red":90</code> to <code>"Red":110</code> in the file without chan... | 0 | 2016-07-04T22:26:26Z | 38,193,129 | <p>Here's how you can do it:</p>
<pre><code>import json
d = {} # store your data here
with open('config.txt','r') as f:
d = json.loads(f.readline())
d['Red']=14
d['Green']=15
d['Blue']=20
result = "{\"Mode\":\"%s\",\"Encoding\":\"%s\",\"Colors\":%s,\
\"Blue\":%s,\"Red\":%s,\"Green\":%s,\"Shortcuts\":%s,... | 0 | 2016-07-04T22:54:36Z | [
"python",
"configuration-files"
] |
Python: how to ping a server? | 38,192,924 | <p>How do I ping a server from within Python?</p>
<p>I am trying to get a ping script working. I am using pxssh to login to a server and once logged in, pinging an IP address. I need to check if there is any loss etc..Below is my script but an seeing some error..Can anyone help. I am using sendline to send commands to... | 2 | 2016-07-04T22:26:39Z | 38,193,350 | <p>If you are just interested in pinging from within python:</p>
<pre><code>import ping
ping.verbose_ping("example.com")
</code></pre>
<p><a href="https://pypi.python.org/pypi/ping/0.2" rel="nofollow">https://pypi.python.org/pypi/ping/0.2</a></p>
<p>Regarding your original question, sendline() does not do what you t... | 0 | 2016-07-04T23:31:14Z | [
"python"
] |
How can I return similar filenames on one line | 38,192,974 | <p>I'm a bit of a newbie at this so please bare with... I've written a programme for my work to return filenames and duration's so I can easily add them to spreadsheets. I'd like similar filenames to be returned on the same line so I can copy a whole line of the same files at once.</p>
<p>This is my code so far:</p>
... | -1 | 2016-07-04T22:33:31Z | 38,193,321 | <pre><code>import os, wave
def main():
directory = input("What is the directory? ")
current = None
similar = []
for file in sorted(os.listdir(directory)):
if file.endswith(".wav"):
with wave.open(file, 'rb') as f:
frames = f.getnframes()
rate = f.ge... | 1 | 2016-07-04T23:26:39Z | [
"python"
] |
How can I return similar filenames on one line | 38,192,974 | <p>I'm a bit of a newbie at this so please bare with... I've written a programme for my work to return filenames and duration's so I can easily add them to spreadsheets. I'd like similar filenames to be returned on the same line so I can copy a whole line of the same files at once.</p>
<p>This is my code so far:</p>
... | -1 | 2016-07-04T22:33:31Z | 38,193,323 | <p>Instead of printing the information you need at the end of the main function, simply put this result in a string variable:</p>
<pre><code>results= ''
</code></pre>
<p>Instead of the print:</p>
<pre><code>results += file[:-4] + ' ' + duration + '\n'
</code></pre>
<p>The <code>\n</code> is for the return.</p>
| 1 | 2016-07-04T23:26:47Z | [
"python"
] |
How can I return similar filenames on one line | 38,192,974 | <p>I'm a bit of a newbie at this so please bare with... I've written a programme for my work to return filenames and duration's so I can easily add them to spreadsheets. I'd like similar filenames to be returned on the same line so I can copy a whole line of the same files at once.</p>
<p>This is my code so far:</p>
... | -1 | 2016-07-04T22:33:31Z | 38,193,891 | <p>To answer your question, I created a dictionary (containing the file names and their corresponding duration) and a list (containing the file names): both of them are returned by the main() function. Next, I created a function that prints the values according to your needs. In short, the function checks if the names ... | 0 | 2016-07-05T01:06:36Z | [
"python"
] |
concat MultiIndex pandas DataFrame columns | 38,193,003 | <p>I have a grouped MultiIndex pandas dataframe like the following:</p>
<pre><code>In [10]: arrays = [np.array(['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux']),
....: np.array(['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two'])]
....:
In [11]: s = pd.Series(np.random.randn(8), index=ar... | 1 | 2016-07-04T22:36:12Z | 38,193,167 | <p>Those first two columns are actually the index of a series object.</p>
<pre><code>s.index.to_series().str.join(' ') + ' ' + s.astype(str)
</code></pre>
<p>This gets you:</p>
<pre><code>s.index.to_series().str.join(' ') + ' ' + s.astype(str)
s.index.to_series().str.join(' ') + ' ' + s.astype(str)
bar one bar... | 1 | 2016-07-04T23:00:21Z | [
"python",
"pandas",
"concat"
] |
for looping and appending into list | 38,193,013 | <pre><code>list = []
def lecture(x):
for x in range(1,x):
print 'lecture', x
</code></pre>
<p>so I have this code that gives the result of </p>
<pre><code>lecture 1
lecture 2
</code></pre>
<p>for an input of <code>lecture(3)</code>. Now, when I change the code to </p>
<pre><code>list = []
def lec... | 1 | 2016-07-04T22:37:04Z | 38,193,073 | <p>Swap <code>y = 'lecture', x</code> with:</p>
<pre><code>y = 'lecture ' + str(x)
</code></pre>
<p>This will append the variable <code>x</code> to <code>'lecture'</code> and set it in variable <code>y</code></p>
| 0 | 2016-07-04T22:45:59Z | [
"python",
"python-2.7"
] |
for looping and appending into list | 38,193,013 | <pre><code>list = []
def lecture(x):
for x in range(1,x):
print 'lecture', x
</code></pre>
<p>so I have this code that gives the result of </p>
<pre><code>lecture 1
lecture 2
</code></pre>
<p>for an input of <code>lecture(3)</code>. Now, when I change the code to </p>
<pre><code>list = []
def lec... | 1 | 2016-07-04T22:37:04Z | 38,193,103 | <p>You are getting that strange notation because <code>'lecture', x</code> is a <a href="http://www.tutorialspoint.com/python/python_tuples.htm" rel="nofollow">tuple</a>. A datatype which acts like a list, but a non-flexible list. You can't change them that easily. You have to use the +-operator instead of a comma to p... | 1 | 2016-07-04T22:51:13Z | [
"python",
"python-2.7"
] |
for looping and appending into list | 38,193,013 | <pre><code>list = []
def lecture(x):
for x in range(1,x):
print 'lecture', x
</code></pre>
<p>so I have this code that gives the result of </p>
<pre><code>lecture 1
lecture 2
</code></pre>
<p>for an input of <code>lecture(3)</code>. Now, when I change the code to </p>
<pre><code>list = []
def lec... | 1 | 2016-07-04T22:37:04Z | 38,193,111 | <p>With the expression <code>y = 'lecture', x</code>, you are creating a tuple. Create an empty list instead, and append values to it with the for loop:</p>
<pre><code>def lecture(x):
lecture_list=[]
for item in range(1,x+1):
y='lecture '+str(item)
lecture_list.append(y)
return lecture_list... | 0 | 2016-07-04T22:52:30Z | [
"python",
"python-2.7"
] |
for looping and appending into list | 38,193,013 | <pre><code>list = []
def lecture(x):
for x in range(1,x):
print 'lecture', x
</code></pre>
<p>so I have this code that gives the result of </p>
<pre><code>lecture 1
lecture 2
</code></pre>
<p>for an input of <code>lecture(3)</code>. Now, when I change the code to </p>
<pre><code>list = []
def lec... | 1 | 2016-07-04T22:37:04Z | 38,193,199 | <p>An alternative way:</p>
<pre><code>class Lectures(object):
def __init__(self, x):
self.x = x
def __iter__(self):
for i in range(1, self.x):
yield "lecture" + i
</code></pre>
<p>Here an iterable class Lectures is made.</p>
<p>First you need to initialize it, passing x as an attribute:</p>... | 0 | 2016-07-04T23:05:45Z | [
"python",
"python-2.7"
] |
create a dynamic image slideshow with python | 38,193,082 | <p>I need to dynamically add images to a video template with place holders for photos in order to generate a slide-show.
I need something of
<a href="http://videohive.net/item/watercolor-frames/15594607?s_rank=1" rel="nofollow">this format</a>. Basically I will have a video template and images as my input. And the out... | -1 | 2016-07-04T22:46:57Z | 38,193,133 | <p>Verify is <a href="https://pypi.python.org/pypi/moviepy" rel="nofollow">moviepy</a> can help you.</p>
<p>Maybe you can use ffmeg to encode based on some input generated by python.</p>
| 1 | 2016-07-04T22:55:00Z | [
"python",
"opencv",
"ffmpeg",
"pillow"
] |
Web2py scheduler - Best practices to rerun task continuously and to add task at startup | 38,193,123 | <p>I want to add a task to the queue at app startup, currently adding a <code>scheduler.queue_task(...)</code> to the main <em>db.py</em> file. This is not ideal as I had to define the task function in this file.</p>
<p>I also want the task to repeat every 2 minutes continuously.</p>
<p>I would like to know what is ... | 1 | 2016-07-04T22:53:55Z | 38,244,323 | <p>There is no real mechanism for this within web2py it seems.</p>
<p>There are a few hacks one could do to continuously repeat tasks or schedule at startup but as far as I can see the web2py scheduler needs alot of work.</p>
<p>Best option is to just abondon this web2py feature and use <a href="http://www.celeryproj... | 0 | 2016-07-07T11:29:21Z | [
"python",
"scheduled-tasks",
"web2py"
] |
Web2py scheduler - Best practices to rerun task continuously and to add task at startup | 38,193,123 | <p>I want to add a task to the queue at app startup, currently adding a <code>scheduler.queue_task(...)</code> to the main <em>db.py</em> file. This is not ideal as I had to define the task function in this file.</p>
<p>I also want the task to repeat every 2 minutes continuously.</p>
<p>I would like to know what is ... | 1 | 2016-07-04T22:53:55Z | 38,613,477 | <p><a href="http://web2py.com/books/default/chapter/29/04/the-core#queue_task-" rel="nofollow">As stated in web2py doc</a>, to rerun task continuously, you just have to specify it at task queuing time :</p>
<pre><code>scheduler.queue_task(your_function,
pargs=your_args,
timeou... | 1 | 2016-07-27T12:49:40Z | [
"python",
"scheduled-tasks",
"web2py"
] |
Pygame DLL load failed | 38,193,226 | <p>I just installed Pygame 1.9.2.
When I try to run Pygame I get the error message "ImportError: DLL load failed"</p>
<p>I'm running Python 3.5 32bit, with a Pygame version for 3.4. Can this be the problem?
Unfortunatly i didnt find a version for Python 3.5</p>
<p>Thanks so much in advance.</p>
| 0 | 2016-07-04T23:10:20Z | 38,193,736 | <p>As stated earlier by MattDMo, there might be some ABI changes in between Python 3.4 and Python 3.5.</p>
<p>To save you the hassle, an unofficial PyGame 1.9.2 build for Windows is available <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/#pygame" rel="nofollow">here</a>.</p>
| 0 | 2016-07-05T00:38:44Z | [
"python",
"dll",
"pygame"
] |
Print on a single line not working Python 3 | 38,193,275 | <p>I'm very new to programming and am working on some code to extract data from a bunch of text files. I've been able to do this however the data is not useful to me in Excel. Therefore, I would like to print it all on a single line and separate it by a special character, which I can then delimit in Excel.</p>
<p>Here... | 0 | 2016-07-04T23:17:37Z | 38,193,301 | <p>Your immediate problem is that you're not removing the newline characters from your lines before printing them. The usual way to do this is with <code>strip()</code>, eg:</p>
<pre><code>print(line.strip(), end='*')
</code></pre>
<p>You'll also print multiple copies of the line if more than one of your special phra... | 1 | 2016-07-04T23:23:08Z | [
"python",
"printing",
"text-files",
"readfile"
] |
What is the pythonic way for 'do_this() if condition else pass '? | 38,193,278 | <p>There is exists a way for writing this in a single line?</p>
<pre><code>>> list.append(elem) if condition else pass
</code></pre>
<p>I have needed sometimes something like that and I don't know the best way for accomplish it.</p>
| -5 | 2016-07-04T23:18:09Z | 38,193,286 | <pre><code>if condition:
list.append(elem)
else:
other_list.append(elem)
</code></pre>
<p>There are other ways possible, but this is the most Pythonic.</p>
| 2 | 2016-07-04T23:21:19Z | [
"python",
"if-statement"
] |
What is the pythonic way for 'do_this() if condition else pass '? | 38,193,278 | <p>There is exists a way for writing this in a single line?</p>
<pre><code>>> list.append(elem) if condition else pass
</code></pre>
<p>I have needed sometimes something like that and I don't know the best way for accomplish it.</p>
| -5 | 2016-07-04T23:18:09Z | 38,193,291 | <p><code>if</code> statements are exactly meant for conditionally executing a statement!</p>
<pre><code>if condition:
list.append(elem)
</code></pre>
<p>If you <em>really</em> wanted it all in one line, I suppose you could do:</p>
<pre><code>if condition: list.append(elem)
</code></pre>
<p>But this would defini... | 5 | 2016-07-04T23:21:44Z | [
"python",
"if-statement"
] |
How to handle state / conditionally modify fields within Django forms | 38,193,293 | <p>I have a django model representing a task. This task will go through multiple states from 'DRAFT' to 'COMPLETION' and during that time, various fields will change from requiring user input to explicitly refusing it. For example, you can't change the date a task was completed while it's in draft. Additionally i want ... | 1 | 2016-07-04T23:21:59Z | 38,193,423 | <p>Try putting the logic in the form instantiation code as so:</p>
<pre><code>class TaskForm(forms.ModelForm):
class Meta:
model = Task
def handle_state(self, *args, **kwargs):
task = getattr(self, 'instance', None)
if task:
if task.status = Task.ACCEPTED:
... | 1 | 2016-07-04T23:43:19Z | [
"python",
"django"
] |
PEP 479, map() and StopIteration | 38,193,355 | <p>It appears that <a href="https://www.python.org/dev/peps/pep-0479/" rel="nofollow">PEP 479</a> (Change StopIteration handling inside generators) has brought many inconveniences. Example code of a zip equivalent( from python's 2.7 docs, slightly changed by myself):</p>
<pre><code>def izip(*iterables):
# izip('ABC... | 1 | 2016-07-04T23:32:35Z | 38,193,647 | <p>In this case you could check the length of <code>tuple</code> that you're going to <code>yield</code> and break the loop in case it's less than length of <code>iterators</code>:</p>
<pre><code>def izip(*iterables):
iterators = list(map(iter, iterables))
while True:
t = tuple(map(next,iterators))
... | 1 | 2016-07-05T00:22:43Z | [
"python",
"python-3.x"
] |
downloading PPTX created by python-pptx in a flask app | 38,193,438 | <p>I am using Python-pptx in a web app, that programmatically creates a powerpoint and then allows the user to download at the end. People can upload images, etc, and it inserts it into the powerpoint for them.</p>
<p>Works great, however currently I am saving the PowerPoint to the "static" folder and then creating a... | 0 | 2016-07-04T23:45:32Z | 38,193,902 | <p>You can save the presentation to an "in-memory" file, something roughly like this:</p>
<pre><code>from StringIO import StringIO
out_file = StringIO()
prs.save(out_file)
</code></pre>
<p><code>python-pptx</code> likes memory streams like StringIO just fine and will happily write the file to it just like it was a d... | 0 | 2016-07-05T01:08:43Z | [
"python",
"flask",
"python-pptx"
] |
python xml - multiple child nodes to dataframe | 38,193,462 | <p>Hi Guys I have the following XML</p>
<pre><code><Batch>
<Date></Date>
<Customer>
<CustType>1</CustType>
<CustomerId>123</CustomerId>
<Address>1 abc st</Address>
<Letters>
<Letter>
<LetterId>123456</LetterId>
<LetterDate>1/1/20... | 0 | 2016-07-04T23:48:53Z | 38,194,831 | <p>I have actually worked this out.</p>
<pre><code>from lxml import etree
doc = etree.parse(filename)
root = doc.getroot()
list1 = []
for i in range(len(root.xpath('/Customer/Letters/Letter'))):
dict1 = {}
record = root.xpath('/Customer/Letters/Letter')[i]
for ancestor in record.iterancestors('Customer'):
... | 0 | 2016-07-05T03:36:10Z | [
"python",
"xml"
] |
karger min cut algorithm using networkX is very slow in running time | 38,193,485 | <p>new to python. Try to use the networkX package to get work done but it seems to have much longer running time than "creating a list of list" to represent graph. Is that just because the data structure of nextworkX too much for this simple task?
BTW, the result will output twice of the answer. Because the read_adjli... | 0 | 2016-07-04T23:52:58Z | 39,679,750 | <p>To solve the double counting on the edges I simply returned:</p>
<pre><code>int(G.number_of_edges()/2)
</code></pre>
<p>Instead of:</p>
<pre><code>G.number_of_edges()
</code></pre>
<p>To solve the problem with the algorithm being slow I didn´t use nx.contracted_edge, that function returns a new graph, taking a ... | 0 | 2016-09-24T18:41:41Z | [
"python",
"performance",
"networkx"
] |
Problems while extractiong association rules with Orange? | 38,193,495 | <p>I have a dataset with the dimensions <code>(878049, 6)</code>.</p>
<p>It looks like this:</p>
<p><a href="http://i.stack.imgur.com/m4NKv.png" rel="nofollow"><img src="http://i.stack.imgur.com/m4NKv.png" alt="enter image description here"></a></p>
<p>I would like to extract association rules that link the category... | 1 | 2016-07-04T23:54:52Z | 38,200,718 | <p>You are trying to induce classification rules without having any class variable in your data domain. If you print <code>data.domain</code>, you will see you only have regular attributes and metas.</p>
<pre><code>[Category, DayOfWeek, PdDistrict, Resolution] {Descript, Address}
</code></pre>
<p>To solve this, you n... | 0 | 2016-07-05T10:11:32Z | [
"python",
"pandas",
"machine-learning",
"data-mining",
"orange"
] |
Problems while extractiong association rules with Orange? | 38,193,495 | <p>I have a dataset with the dimensions <code>(878049, 6)</code>.</p>
<p>It looks like this:</p>
<p><a href="http://i.stack.imgur.com/m4NKv.png" rel="nofollow"><img src="http://i.stack.imgur.com/m4NKv.png" alt="enter image description here"></a></p>
<p>I would like to extract association rules that link the category... | 1 | 2016-07-04T23:54:52Z | 38,216,428 | <p>You can see what your found itemsets contain with:</p>
<pre><code># Minimum 20% support. Decrease for more results
itemsets = dict(frequent_itemsets(X, .2))
for itemset, _support in itemsets.items():
print(' '.join('{}={}'.format(var.name, val)
for _, var, val in OneHot.decode(itemset, data,... | 1 | 2016-07-06T04:41:55Z | [
"python",
"pandas",
"machine-learning",
"data-mining",
"orange"
] |
More Effecient Way to Format Dates for in Python for MySQL | 38,193,501 | <p>Say I have a list of dates that are formatted in one of the five ways below:</p>
<pre><code>Date_Type_1 = 2001 Apr 15
Date_Type_2 = 2001 Apr
Date_Type_3 = 2000 Spring
Date_Type_4 = 2000 Nov-Dec
Date_Type_5 = 2001
</code></pre>
<p>So that my date list will look like this.</p>
<pre><code>Date_list = ["2001 Apr 15",... | 0 | 2016-07-04T23:56:30Z | 38,193,732 | <p>I think you can do it like this:</p>
<pre><code>>>> import datetime
>>> dates = ["2001 Apr 15", "2004 May 15", "2011 Jan", "2011 Fall", "2000 Nov-Dec", "2012", "2000 Spring" ]
>>>
>>> def convert(date_str):
... tokens = date_str.split(' ')
... if len(tokens) == 1:
... ... | 1 | 2016-07-05T00:37:43Z | [
"python",
"python-3.x",
"date-format",
"mysql-connector-python"
] |
More Effecient Way to Format Dates for in Python for MySQL | 38,193,501 | <p>Say I have a list of dates that are formatted in one of the five ways below:</p>
<pre><code>Date_Type_1 = 2001 Apr 15
Date_Type_2 = 2001 Apr
Date_Type_3 = 2000 Spring
Date_Type_4 = 2000 Nov-Dec
Date_Type_5 = 2001
</code></pre>
<p>So that my date list will look like this.</p>
<pre><code>Date_list = ["2001 Apr 15",... | 0 | 2016-07-04T23:56:30Z | 38,193,765 | <p>You should use the Python regular expression module <code>re</code>. It's a lot better for this than trying to mess with slices and <code>in</code>.</p>
<pre><code>import re
MONTHS = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul',
'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
SEASONS = { 'Spring': 'Mar', 'Summer': 'J... | 1 | 2016-07-05T00:44:05Z | [
"python",
"python-3.x",
"date-format",
"mysql-connector-python"
] |
How to test get request on flask server using curl? | 38,193,515 | <p>I'm building a flask server that connects to a database, and I want to test if the GET requests work. However, I don't know how to send request data using curl. </p>
<p>When I enter</p>
<pre><code>curl http://127.0.0.1:5000
</code></pre>
<p>I get back the data I need, but <code>'/'</code> doesn't require any requ... | 1 | 2016-07-04T23:58:58Z | 38,194,113 | <p>Alan, you need to request the proper <code>route</code> and pass the additional information in the <a href="https://en.wikipedia.org/wiki/Query_string" rel="nofollow">query string</a>. Try:</p>
<p><code>curl http://127.0.0.1:5000/stream?name=Alan</code></p>
| 0 | 2016-07-05T01:47:36Z | [
"python",
"curl",
"get"
] |
Picking which ip address to use for ftp connection | 38,193,564 | <p>I got a question. My NIC has several secondary ip addresses.
I was not able to find a library for ftp in python which allows to pick which ip address to use to connect to a ftp server.
Does anyone know how it can be implemented, i looked into raw sockets and didn't find it too.
I know it's implemented for http/https... | 1 | 2016-07-05T00:07:40Z | 38,193,805 | <p>As noted by <a href="http://stackoverflow.com/users/3212865/">spectras</a>, the FTP client in the Python 3 standard library allows specifying a <a href="https://docs.python.org/3/library/ftplib.html#ftplib.FTP" rel="nofollow">source address</a> as a tuple. Unless you have a known or static port for the source, sett... | 1 | 2016-07-05T00:51:41Z | [
"python",
"networking",
"ftp",
"ip"
] |
Picking which ip address to use for ftp connection | 38,193,564 | <p>I got a question. My NIC has several secondary ip addresses.
I was not able to find a library for ftp in python which allows to pick which ip address to use to connect to a ftp server.
Does anyone know how it can be implemented, i looked into raw sockets and didn't find it too.
I know it's implemented for http/https... | 1 | 2016-07-05T00:07:40Z | 38,194,229 | <p>As I mentionned, standard python ftp lib has a <a href="https://docs.python.org/3/library/ftplib.html#ftplib.FTP" rel="nofollow">source_address</a> parameter. However it's not available for python 2, which you apparently need.</p>
<p>So I suggest the following kludge for python2.7. That's copy-pasting python3 imple... | 1 | 2016-07-05T02:06:44Z | [
"python",
"networking",
"ftp",
"ip"
] |
mean of absolute value of groupby object pandas | 38,193,583 | <p>I want to compute the mean of the absolute value of a grouped object. </p>
<p>I.e. </p>
<pre><code>grouped = df.groupby([pd.TimeGrouper(3MS)])
dct['x'] = grouped['profit'].agg('mean') / grouped['cost'].abs().agg('mean')
</code></pre>
<p>However, the above code results in an error. I have tried various variants o... | -1 | 2016-07-05T00:11:30Z | 38,193,693 | <p>You're probably getting the error because you can't use <code>.agg</code> on a Sereis object.</p>
<p>You didn't post your grouped object so I don't know if there are other issues but you should try it this way. I think this should work:</p>
<pre><code>dct['x'] = grouped['profit'].mean() / grouped['cost'].abs().mea... | 0 | 2016-07-05T00:30:22Z | [
"python",
"pandas",
"group-by",
"absolute-value"
] |
mean of absolute value of groupby object pandas | 38,193,583 | <p>I want to compute the mean of the absolute value of a grouped object. </p>
<p>I.e. </p>
<pre><code>grouped = df.groupby([pd.TimeGrouper(3MS)])
dct['x'] = grouped['profit'].agg('mean') / grouped['cost'].abs().agg('mean')
</code></pre>
<p>However, the above code results in an error. I have tried various variants o... | -1 | 2016-07-05T00:11:30Z | 38,230,571 | <p>Based on your update, I think you are looking for one mean taken on absolute values for the group.</p>
<p>Using <code>grouped.apply(abs).mean()</code> will apply the <code>abs</code> function to values in your group (<code>cost1</code> etc), and the <code>mean</code> will give you the average for whatever your grou... | 0 | 2016-07-06T17:52:35Z | [
"python",
"pandas",
"group-by",
"absolute-value"
] |
asyncio + multiprocessing + unix | 38,193,596 | <p>I have a pet project with the following logic:</p>
<pre><code>import asyncio, multiprocessing
async def sub_main():
print('Hello from subprocess')
def sub_loop():
asyncio.get_event_loop().run_until_complete(sub_main())
def start():
multiprocessing.Process(target=sub_loop).start()
start()
</code></pr... | 1 | 2016-07-05T00:14:13Z | 38,193,770 | <p>You should always add a check to see how you're running the code (the <code>if __name__ == '__main__':</code> part. Your subprocess is running everything in the module a 2nd time, giving you <em>grief</em> (couldn't resist).</p>
<pre><code>import asyncio, multiprocessing
async def sub_main():
print('Hello from... | 1 | 2016-07-05T00:44:59Z | [
"python",
"unix",
"python-3.5",
"python-multiprocessing",
"python-asyncio"
] |
asyncio + multiprocessing + unix | 38,193,596 | <p>I have a pet project with the following logic:</p>
<pre><code>import asyncio, multiprocessing
async def sub_main():
print('Hello from subprocess')
def sub_loop():
asyncio.get_event_loop().run_until_complete(sub_main())
def start():
multiprocessing.Process(target=sub_loop).start()
start()
</code></pr... | 1 | 2016-07-05T00:14:13Z | 38,198,509 | <p>First, you should consider using <a href="https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.BaseEventLoop.run_in_executor" rel="nofollow">loop.run_in_executor</a> with a <a href="https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Executor" rel="nofollow">ProcessPoolExecutor</... | 1 | 2016-07-05T08:21:45Z | [
"python",
"unix",
"python-3.5",
"python-multiprocessing",
"python-asyncio"
] |
How to make string indices circular when string index out of range | 38,193,625 | <p>Suppose I have this string:</p>
<pre><code>myString = 'abcdefghijklmnopqrstuvwxyz'
</code></pre>
<p>If I ask for myString[26], I will get an error saying string index out of range. Only myString[0] through myString[25] are valid. </p>
<p>My desired result is to ask for myString[26] and return 'a', because I have ... | 1 | 2016-07-05T00:18:49Z | 38,193,638 | <p>You just need to do <code>myString[<index> % len(myString)]</code>. <code><index></code> would be any integer that will be an index.</p>
<p>For example:</p>
<pre><code>myString[26 % len(myString)]
>>> 'a'
</code></pre>
| 5 | 2016-07-05T00:20:18Z | [
"python"
] |
How to make string indices circular when string index out of range | 38,193,625 | <p>Suppose I have this string:</p>
<pre><code>myString = 'abcdefghijklmnopqrstuvwxyz'
</code></pre>
<p>If I ask for myString[26], I will get an error saying string index out of range. Only myString[0] through myString[25] are valid. </p>
<p>My desired result is to ask for myString[26] and return 'a', because I have ... | 1 | 2016-07-05T00:18:49Z | 38,193,642 | <p>Use modulo.</p>
<pre><code>myString = 'abcdefghijklmnopqrstuvwxyz'
def access_char(string, i):
return string[i % len(string)]
print(access_char(myString, 57))
# >>> f
</code></pre>
<p>This will also work for any other sequence datatype (list, tuple, etc.)</p>
| 6 | 2016-07-05T00:21:11Z | [
"python"
] |
Finding the self-consistent solution to an equation | 38,193,730 | <p>At the bottom of this question are a set of functions transcribed from a published neural-network model. When I call <code>R</code>, I get the following error:</p>
<blockquote>
<p>RuntimeError: maximum recursion depth exceeded while calling a Python object</p>
</blockquote>
<p>Note that within each call to <cod... | 1 | 2016-07-05T00:37:42Z | 38,193,838 | <p>Change the maximum recursion depth using <code>sys.setrecursionlimit</code></p>
<pre><code>import sys
sys.setrecursionlimit(10000)
def rec(i):
if i > 1000:
print 'i is over 1000!'
return
rec(i + 1)
rec(0)
</code></pre>
<p>More info: <a href="https://docs.python.org/3/library/sys.html#sy... | 0 | 2016-07-05T00:58:04Z | [
"python",
"numpy",
"scipy",
"neural-network",
"wolfram-mathematica"
] |
Finding the self-consistent solution to an equation | 38,193,730 | <p>At the bottom of this question are a set of functions transcribed from a published neural-network model. When I call <code>R</code>, I get the following error:</p>
<blockquote>
<p>RuntimeError: maximum recursion depth exceeded while calling a Python object</p>
</blockquote>
<p>Note that within each call to <cod... | 1 | 2016-07-05T00:37:42Z | 38,193,912 | <p>This recursion never ends since there is no termination condition before recursive call, adjusting maximum recursion depth does not help</p>
<pre><code>def R(x_i):
...
for x_j in x:
sum_term += J(x_i - x_j) * R(x_j)
</code></pre>
<p>Perhaps you should be doing something like</p>
<pre><code># some su... | 1 | 2016-07-05T01:11:04Z | [
"python",
"numpy",
"scipy",
"neural-network",
"wolfram-mathematica"
] |
I keep getting a syntax error, somehow due to the colon at the end of a function definition | 38,193,735 | <p>I'm brand new to python, and programming in general, so this is probably something extremely simple, but I'm persistently getting this syntax error at the end of the line defining my function for minPayment. I can't see any problem with it... here is the program so far.</p>
<h1>Problem set 1: credit card balance c... | 1 | 2016-07-05T00:38:36Z | 38,193,760 | <p>Add parentheses to your functions. Python syntax dictates so.</p>
<p>So, instead of <code>def minPayment:</code>, write <code>def minPayment():</code> instead.</p>
| 1 | 2016-07-05T00:43:18Z | [
"python",
"syntax"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.