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 |
|---|---|---|---|---|---|---|---|---|---|
django.db.utils.IntegrityError: (1062, "Duplicate entry for user_id") | 38,015,891 | <p>I have a certain model:</p>
<pre><code>class Problem(models.Model):
title = models.CharField(max_length=80)
problem_text = models.TextField(max_length=5000)
pub_date = models.DateTimeField(default=timezone.now)
votes = models.IntegerField(default=0)
wiki_answer = models.TextField(max_length=500... | 1 | 2016-06-24T14:32:21Z | 38,016,271 | <p>The error happens here:</p>
<pre><code>"/Users/artemdremov/Documents/python/interview_project/interview_questions/views.py" in post
55. post.save()
</code></pre>
<p>And that's because you have this in your model.</p>
<pre><code>user = models.OneToOneField(User, null=True, blank=False, unique=False)
... | 0 | 2016-06-24T14:51:07Z | [
"python",
"mysql",
"django"
] |
Connecting 2 Django Projects on Different Servers | 38,015,942 | <p>For reasons out of my control, 2 Django projects were placed on 2 different AWS servers, both using the same RDS AWS database.</p>
<p>I want Project B to be able to access and manipulate the models (tables) used in Project A (where they were originally created).</p>
<p>Is this at all possible? Importing the Projec... | 0 | 2016-06-24T14:34:46Z | 38,016,040 | <p>Sorry...I lack the reputation to comment otherwise I would not have posted.</p>
<p>I think in this situation, you may need to make use of the <a href="http://www.django-rest-framework.org/" rel="nofollow">Django REST Framework</a>. </p>
<p>This way you can simple authorize the projects to talk to each other, DRF c... | 1 | 2016-06-24T14:39:51Z | [
"python",
"django",
"pythonpath"
] |
adding a popup file browser to a QtVariantPropertyManager | 38,015,994 | <p>I have a field in a property browser where the user sets a file path. I would like for them to get a file browser when the click on the line to edit it.
the file browser is</p>
<pre><code>class TargetPropertiesBrowser(QtTreePropertyBrowser):
def __init__(self):
self._variantManager = QtVariantPropertyM... | 0 | 2016-06-24T14:37:38Z | 38,016,146 | <p>Connect one of the Widget's Signals (e.g. clicked()) to a slot method in your class: <a href="http://pyqt.sourceforge.net/Docs/PyQt5/signals_slots.html" rel="nofollow">http://pyqt.sourceforge.net/Docs/PyQt5/signals_slots.html</a></p>
| 0 | 2016-06-24T14:44:37Z | [
"python",
"pyqt5"
] |
DataFrame created with read_csv() gives unexpected query() results | 38,016,003 | <p>I'm using <code>DataFrame.query()</code> to find rows, and I've come across a problem that I can only replicate if the data is loaded from CSV. If I create what I think is the same DataFrame in pure Python, the query() works as expected.</p>
<p>This is the CSV of data:</p>
<pre><code>,ASK_PRICE,ASK_QTY,BID_PRICE,B... | 1 | 2016-06-24T14:38:14Z | 38,016,267 | <p>It's a <a href="http://stackoverflow.com/questions/588004/is-floating-point-math-broken?lq=1">well known problem of comparing float values</a></p>
<p>Try this:</p>
<pre><code>In [70]: df2.query('(abs(BID_PRICE - 104.254) < 0.000001) and (BID_QTY >= 50)')
Out[70]:
ASK_PRICE ASK_QTY ... | 1 | 2016-06-24T14:50:59Z | [
"python",
"pandas"
] |
DataFrame created with read_csv() gives unexpected query() results | 38,016,003 | <p>I'm using <code>DataFrame.query()</code> to find rows, and I've come across a problem that I can only replicate if the data is loaded from CSV. If I create what I think is the same DataFrame in pure Python, the query() works as expected.</p>
<p>This is the CSV of data:</p>
<pre><code>,ASK_PRICE,ASK_QTY,BID_PRICE,B... | 1 | 2016-06-24T14:38:14Z | 38,016,722 | <p>I don't know the answer but it seems related to the index column.
I ran a simplified version of your code and it works as expected.</p>
<pre><code>#!/usr/bin/env python
import pandas as pd
timestamp = [1, 2, 3, 4, 5, 6]
bid_price = [104, 105, 106, 107, 107, 107]
bid_qty = [100.0, 100.0, 50.0, 50.0, 150.0, 100.0]
... | 0 | 2016-06-24T15:15:10Z | [
"python",
"pandas"
] |
Loop from excel data into a dictionary with multiple values per key | 38,016,017 | <p>I am fairly new to Python and I think this question is fairly easy but I can't figure it out...</p>
<p>I have a data table in excel in which I have B column strings and C through I columns as values. I want to create a dictionary in which for each key value in
B column, I assign values of the columns C through I. I... | 1 | 2016-06-24T14:38:47Z | 38,016,210 | <p>Have you considered using Pandas? I'm not sure what your goal is with the data, but it seems like the most robust way to do what you want.</p>
<p>If you use <code>pandas.read_excel(path, sheetname=None)</code> then it will default to creating a dictionary where each key is a sheet and each value is a dataframe of ... | 1 | 2016-06-24T14:47:35Z | [
"python",
"excel",
"for-loop",
"dictionary",
"openpyxl"
] |
Loop from excel data into a dictionary with multiple values per key | 38,016,017 | <p>I am fairly new to Python and I think this question is fairly easy but I can't figure it out...</p>
<p>I have a data table in excel in which I have B column strings and C through I columns as values. I want to create a dictionary in which for each key value in
B column, I assign values of the columns C through I. I... | 1 | 2016-06-24T14:38:47Z | 38,016,587 | <p>You could try something like this:</p>
<pre><code>from collections import defaultdict
d = defaultdict(list)
for line in open("pyex.csv").readlines():
line = line.strip()
line = line.split(",")
key, value = line[0], line[1:]
d[key] += value
print(d)
</code></pre>
<p>So if you have a csv file that l... | 1 | 2016-06-24T15:08:19Z | [
"python",
"excel",
"for-loop",
"dictionary",
"openpyxl"
] |
Plotting multiple lines to a single Python figure | 38,016,070 | <p>This is my first Stack Overflow question so please excuse me if the formatting of this question does not follow the conventions of the Stack Overflow community. </p>
<p>My question is how can you (if possible) add a line to an existing Python figure using pyplot? Essentially, what I want to accomplish is I want to ... | 1 | 2016-06-24T14:40:50Z | 38,020,102 | <p>Try adding the <code>num</code> argument to <code>plt.figure</code>. In other words, replace <code>fig=plt.figure(figsize=(20,10))</code>, with <code>fig=plt.figure(num=1, figsize=(20,10))</code>.</p>
<p>From the docs,</p>
<blockquote>
<p>num : integer or string, optional, default: none</p>
<p>If not provid... | 1 | 2016-06-24T18:40:53Z | [
"python",
"python-2.7",
"matplotlib",
"plot"
] |
Classify strings via class using sklearn | 38,016,107 | <p>I'm having issues with presenting my data in a form which sklearn will accept
My raw data is a few hundred strings, and these are classified into one of 5 classes, I've a list of the strings i'd like to classify, and a parallel list of their respective classes. I'm using <code>GaussianNB()</code></p>
<p>Example Dat... | 1 | 2016-06-24T14:42:29Z | 38,040,726 | <p>Since your input data are in the format of raw text and not in the format of a dictionary where like {"word":number_of_occurrences, } I believe you should go with a <a href="http://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html#sklearn.feature_extraction.text.CountVect... | 1 | 2016-06-26T16:36:25Z | [
"python",
"string",
"scipy",
"scikit-learn",
"gaussian"
] |
How can I override the date_hierarchy function for a single ModelAdmin? | 38,016,202 | <p>I would like to set <code>date_hierarchy</code> on a ModelAdmin to a field on a related model, for example:</p>
<pre><code>date_hierarchy = 'item__menu__date'
</code></pre>
<p>This is not possible in Django 1.9, but will be possible in Django 1.11. The code for the 1.11 feature already exists. (ref. <a href="https... | 0 | 2016-06-24T14:47:18Z | 38,249,942 | <p>It appears that this is not possible.</p>
<p>Instead, I <a href="https://en.wikipedia.org/wiki/Monkey_patch" rel="nofollow">monkey-patched</a> the changes into our local copy of the library, and accepted the <a href="https://en.wikipedia.org/wiki/Technical_debt" rel="nofollow">technical debt</a> associated with thi... | 0 | 2016-07-07T15:49:09Z | [
"python",
"django",
"django-templates",
"django-admin"
] |
Assign new value to variable used in while loop comparison after loop is entered | 38,016,238 | <p>I was wondering if anything speaks against assigning a new value to a variable that is used in a comparison in a while loop after the while loop has been entered. A dummy example:</p>
<pre><code>i = 0
target = 10
while i < target:
print i
if i == 9:
target = 20
i = i + 1
</code></pre>
| 0 | 2016-06-24T14:49:10Z | 38,016,262 | <p>No, nothing stops you from doing that. Your example in and of itself is a proof.</p>
<p>Although, a better practice would be to use a <code>while True:</code> loop and <code>break</code> on a condition. Since your loop condition itself is prone to change, it's not really an invariant condition at all. Hence, I sugg... | 6 | 2016-06-24T14:50:41Z | [
"python"
] |
Encrypting a SQL Login in a Python program using MD5 | 38,016,242 | <p>I have a python program that accesses SQL databases with the database login currently encoded in base64 in a text file. I'd like to encode the login instead using MD5 and store it in a config file, but after some research, I couldn't find much on the topic. Could someone point me in the right direction on where to s... | 0 | 2016-06-24T14:49:26Z | 38,016,323 | <p>See <a href="https://docs.python.org/3.5/library/hashlib.html" rel="nofollow">https://docs.python.org/3.5/library/hashlib.html</a></p>
<pre><code>import hashlib
print( hashlib.md5(b"stackoverflow").hexdigest() )
</code></pre>
| 0 | 2016-06-24T14:54:21Z | [
"python",
"sql",
"python-3.x",
"config",
"md5"
] |
Encrypting a SQL Login in a Python program using MD5 | 38,016,242 | <p>I have a python program that accesses SQL databases with the database login currently encoded in base64 in a text file. I'd like to encode the login instead using MD5 and store it in a config file, but after some research, I couldn't find much on the topic. Could someone point me in the right direction on where to s... | 0 | 2016-06-24T14:49:26Z | 38,016,382 | <p>MD5, unfortunately, is a <em>hash signature</em> protocol, not an encryption protocol. It is used to generate strings that are used to detect even the very-slightest change to the value from which the MD5 hash was produced. But . . . (by design) . . . you <em>cannot</em> recover the value that was originally used ... | 1 | 2016-06-24T14:57:22Z | [
"python",
"sql",
"python-3.x",
"config",
"md5"
] |
StratifiedKfold over heterogeneous DataFrame | 38,016,303 | <p>I have a pandas DataFrame which contains string and float columns that needs to be split into balanced slices in order to train a sklearn pipeline.</p>
<p>Ideally I'd use <a href="http://scikit-learn.org/stable/modules/generated/sklearn.cross_validation.StratifiedKFold.html" rel="nofollow">StratifiedKFold</a> over ... | 1 | 2016-06-24T14:53:03Z | 38,019,795 | <p><code>StratifiedKFold</code> takes the <code>label</code> as input. Assuming your <code>label</code> is <code>target</code>, you would:</p>
<pre><code>from sklearn.cross_validation import StratifiedKFold
skf = StratifiedKFold(dataset.target, n_folds=2)
for train_index, test_index in skf:
X_train, X_test = datas... | 3 | 2016-06-24T18:19:24Z | [
"python",
"pandas",
"machine-learning",
"scikit-learn",
"cross-validation"
] |
Python - mechanize/requests get Title | 38,016,357 | <p>So, I have this brute-forcing script, that basically brute-forces web forms. Say my example site's web-form redirects to the same URL when logged in successfully or not. For example, to login I'd have to go to this site: <a href="https://example.com/account/" rel="nofollow">https://example.com/account/</a>, when I t... | 1 | 2016-06-24T14:56:04Z | 38,019,152 | <p>This is very simple with requests:</p>
<pre><code>import requests
data ={"login":"yourlogin",
"pass": "yourpass"}
r = requests.post("https://bagar.io/engine/modules/login.php", data=data)
print("success" in r.json())
</code></pre>
<p>A successful login returns <code>{u'success': u'allow'}</code> and an unsuccess... | 1 | 2016-06-24T17:36:11Z | [
"python",
"python-requests",
"mechanize"
] |
apply median filter on pixels of a certain value? | 38,016,490 | <p>I Have a matrix with int inside it.</p>
<p>I need to replace the <code>111</code> with the median of its immediate 4 neighbourhood if any of the neighbors are <code>111</code> then they are ignored.</p>
<p>For eg:-</p>
<pre><code>matrix = 1 2 3 4 5 6
101 111 1 3 44 3
111 3 4 ... | 0 | 2016-06-24T15:03:27Z | 38,017,689 | <pre><code>def func(array):
if array[2]==111:
return np.median(array[array!=111])
else:
return array[2]
fp = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]])
a = np.fromstring("""1 2 3 4 5 6
101 111 1 3 44 3
111 3 4 4 5 6
1 2 4 5 7 7""",... | 0 | 2016-06-24T16:07:16Z | [
"python",
"list",
"numpy",
"filter"
] |
How to use a maybe unallocated target iterator in Python? | 38,016,640 | <p>If one would like to run an algorithm on an arbitrary interchangeable data source, it's a good idea to use iterators:</p>
<pre><code>def do_something(iter):
for x in iter:
print(x)
l = list([1, 2, 3])
do_something(iter(l))
</code></pre>
<p>In the given example, the iterator is a <em>source</em>. But h... | 0 | 2016-06-24T15:11:32Z | 38,016,882 | <p>One option would be to use a generator and use the <code>.send</code> method to return values to the <code>yield</code> statement:</p>
<pre><code>def is_prime(n): #for this demo
return not any(n%i==0 for i in range(2,n))
def do_something(iter, target):
for x in iter:
if is_prime(x):
tar... | 1 | 2016-06-24T15:22:41Z | [
"python",
"iterator"
] |
How to use a maybe unallocated target iterator in Python? | 38,016,640 | <p>If one would like to run an algorithm on an arbitrary interchangeable data source, it's a good idea to use iterators:</p>
<pre><code>def do_something(iter):
for x in iter:
print(x)
l = list([1, 2, 3])
do_something(iter(l))
</code></pre>
<p>In the given example, the iterator is a <em>source</em>. But h... | 0 | 2016-06-24T15:11:32Z | 38,017,067 | <p>First, just a terminology note: an iterator is a read-only construct; it's an object that has a <code>next</code> method. So <code>target</code> is not an iterator, but something else.</p>
<p>What you want is something that is guaranteed to have an <code>append</code> method, which is any class that inherits from <... | 2 | 2016-06-24T15:33:51Z | [
"python",
"iterator"
] |
Communicate beetween two virtual machines through another virtual machine | 38,016,670 | <p>Here is my problem. I have 3 virtual machines running on linux and three bridges
Each of them have two interface (one for each bridge)
For example:</p>
<ul>
<li>VM1 : i0 for br0 and i2 for br2</li>
<li>VM2 : i1 for br1 and i0 for br0</li>
<li>VM3 : i1 for br1 and i2 for br2</li>
</ul>
<p>Here are the conditions:
... | 0 | 2016-06-24T15:12:54Z | 38,017,405 | <p>Assuming all the VMs are in the same IP subnet, they will try to reach directly one another. </p>
<p>Now, for example, you want to force VM1 to talk to VM3 trough VM2. If you let VM1 figure out how to reach VM3, it will broadcast an arp request and VM3 will respond <em>"hey, that's me! Here is my mac address"</em>.... | 0 | 2016-06-24T15:51:14Z | [
"python",
"virtual-machine",
"iptables",
"kvm",
"bridge"
] |
Accessing Username and Password in django request header returns None | 38,016,684 | <p>I'm creating a view which is expected to be accessed by a bot passing a username and password in the header. (It's a google feed bot to be specific). However, I can never seem to access the username and password to authenticate the bot's credentials. <code>request.GET.get('username')</code> and <code>request.GET.get... | 0 | 2016-06-24T15:13:52Z | 38,017,566 | <p>Neither <code>request.GET</code> nor <code>request.POST</code> refers to request headers. The data you're looking for is most likely available in the dictionary at <code>request.META</code> -- more details on that in the <a href="https://docs.djangoproject.com/en/1.9/ref/request-response/#django.http.HttpRequest.MET... | 1 | 2016-06-24T16:00:38Z | [
"python",
"django",
"basic-authentication"
] |
Accessing Username and Password in django request header returns None | 38,016,684 | <p>I'm creating a view which is expected to be accessed by a bot passing a username and password in the header. (It's a google feed bot to be specific). However, I can never seem to access the username and password to authenticate the bot's credentials. <code>request.GET.get('username')</code> and <code>request.GET.get... | 0 | 2016-06-24T15:13:52Z | 38,044,377 | <p>Thank you <a href="http://stackoverflow.com/users/354176/nthall">nthall</a> for pointing me in the right direction - finding the <code>request.META</code> dictionary was key. </p>
<p>Since I couldn't find much in the way of resources which explained the process, I'll post the entire Django process for retrieving an... | 0 | 2016-06-27T00:22:24Z | [
"python",
"django",
"basic-authentication"
] |
Catch line and modify it with python | 38,016,785 | <p>I'm a newbie in python.
I'm currently trying to modify a line in a file, this after catching this line by using linecache.</p>
<h2>Exemple:</h2>
<pre><code>run_D = open('toto.dat','r')
lines = run_D.readlines()
print "Name of the file: ", run_D.name
seq=["%s'retrieve'"]
line_1 = linecache.getline('toto.dat', 5... | -1 | 2016-06-24T15:17:20Z | 38,128,190 | <p>I think you mix two things: <code>linecache</code> and <code>readlines</code>.</p>
<h2>1. linecache</h2>
<p>From the <a href="https://docs.python.org/2/library/linecache.html" rel="nofollow">docs</a>:</p>
<blockquote>
<p>The linecache module allows one to get any line from any file, while attempting to optimize... | 0 | 2016-06-30T16:00:42Z | [
"python",
"linecache"
] |
Importing issue with python 3 | 38,016,846 | <p>I have a code that runs in Python 2.7 but not in 3.5 and I can't find the reason. It has to do with importing.</p>
<p>The root folder has a subfolder called <code>s</code>. From the root folder, I am running the script <code>a.py</code> which includes the line <code>from s import *</code>.</p>
<p>In the folder <co... | 0 | 2016-06-24T15:20:19Z | 38,017,432 | <p>Implicit imports within packages are not available for Python 3, so to get this to work you will need to use an explicit relative import:</p>
<pre><code>from .s import *
</code></pre>
<p>This should work for both Python 2 and Python 3. This also makes your intention more clear that you want to import from a relat... | 3 | 2016-06-24T15:53:13Z | [
"python",
"python-3.x",
"import",
"python-import"
] |
How do I check for typos in a user submitted domain name? | 38,016,885 | <p>Basically, I'm trying to automatically correct user submitted emails with typos that are only a few letters off. For instance, if a user accidentally submits gamil.com or gmial.com instead of gmail.com, I would like to correct it. <strong>What's a good method for handling this task?</strong></p>
| 0 | 2016-06-24T15:23:01Z | 38,016,974 | <p>Use pymailcheck:</p>
<p><a href="https://pypi.python.org/pypi/pymailcheck/1.0.0" rel="nofollow">https://pypi.python.org/pypi/pymailcheck/1.0.0</a> or <a href="https://github.com/dbarlett/pymailcheck" rel="nofollow">https://github.com/dbarlett/pymailcheck</a></p>
<p>You can use it to check the email-addresses enter... | 1 | 2016-06-24T15:28:16Z | [
"python",
"spell-checking",
"email-validation",
"spelling"
] |
Python List Comprehension with Sum | 38,016,898 | <p>I have some python code that looks like this: </p>
<pre><code>mat = [[3], [4], [4], [0], [1, 2]]
nwalls = 5*[1]
for i in range(1,3):
nwalls = [sum(nwalls[k] for k in mat[j]) for j in range(5)]
# nwalls = [1, 2, 2, 1, 2]
</code></pre>
<p>I can't for the life of me unroll this into syntax without using list comp... | 0 | 2016-06-24T15:23:44Z | 38,017,102 | <p>instead of recreating the <code>nwalls</code> list every time just assign a new value to the specific slot in the list, just keep a record of the previous values in the list so that you do not end up using the value generated earlier in the loop:</p>
<pre><code>mat = [[3], [4], [4], [0], [1, 2]]
nwalls = 5*[1]
prev... | 1 | 2016-06-24T15:35:32Z | [
"python",
"list-comprehension"
] |
Python List Comprehension with Sum | 38,016,898 | <p>I have some python code that looks like this: </p>
<pre><code>mat = [[3], [4], [4], [0], [1, 2]]
nwalls = 5*[1]
for i in range(1,3):
nwalls = [sum(nwalls[k] for k in mat[j]) for j in range(5)]
# nwalls = [1, 2, 2, 1, 2]
</code></pre>
<p>I can't for the life of me unroll this into syntax without using list comp... | 0 | 2016-06-24T15:23:44Z | 38,017,209 | <p>The direct translation would be</p>
<pre><code>mat = [[3], [4], [4], [0], [1, 2]]
nwalls = 5*[1]
for i in range(1, 3):
_nwalls = []
for j in range(5):
tot = 0 # - sum
for k in mat[j]: # /
tot += nwalls[k] # /
_nwalls.append(tot)
nwalls = _nwall... | 2 | 2016-06-24T15:41:24Z | [
"python",
"list-comprehension"
] |
How can I use a JSON response in conditional python logic? | 38,017,002 | <p>I'm using ajax to asynchronously update a boolean variable in my Django project. I'm able to successfully display this variable using the template but I'm not sure how I can use this variable in the template's embedded python logic.</p>
<p>Basically</p>
<pre><code>{% if JSON_BOOL %}
<p>this</p>
{% el... | 0 | 2016-06-24T15:29:53Z | 38,020,359 | <p>There are two ways to solve this. If I were you, I would just leave the variable in text format and in your code say:</p>
<pre><code>{% if JSON_BOOL == "True" %}
...
{% else %}
...the rest of your code
</code></pre>
<p>Otherwise you could cast it to a boolean on the python side of things. This would look as follow... | 1 | 2016-06-24T18:58:16Z | [
"python",
"json",
"ajax",
"django"
] |
Simple script for importing csv, modifying columns and writing back in python | 38,017,006 | <p>I am working on a project and I have a large csv doc in Excel that I'd like to modify with python so that I can correctly run it through a statistical analysis program. I am learning python as my first language and know enough to be dangerous but I'm getting flustered with piecing together code from several sources.... | 0 | 2016-06-24T15:30:02Z | 38,017,216 | <p>If the input file is sorted by <code>person_id</code>, then you could just read the rows in pairs and merge them into a single row:</p>
<pre><code>rows = ['person_id', 'person_name', 'sex', 'blood_pressure_type',
'blood_pressure_value', 'blood_pressure_type', 'blood_pressure_value']
for first, second in zi... | 0 | 2016-06-24T15:41:32Z | [
"python",
"excel",
"csv"
] |
Simple script for importing csv, modifying columns and writing back in python | 38,017,006 | <p>I am working on a project and I have a large csv doc in Excel that I'd like to modify with python so that I can correctly run it through a statistical analysis program. I am learning python as my first language and know enough to be dangerous but I'm getting flustered with piecing together code from several sources.... | 0 | 2016-06-24T15:30:02Z | 38,018,065 | <p>I like to use <a href="https://docs.python.org/3.5/library/csv.html#csv.DictWriter" rel="nofollow"><code>DictWriter()</code></a> and <a href="https://docs.python.org/3.5/library/csv.html#csv.DictReader" rel="nofollow"><code>DictReader()</code></a> for things like this.</p>
<p><code>DictReader()</code> operates like... | 0 | 2016-06-24T16:26:48Z | [
"python",
"excel",
"csv"
] |
dropping a row while iterating through pandas dataframe | 38,017,007 | <p>I have a dataframe df</p>
<pre><code>Name dist
aaaa 10
bbbb 11
cccc 41
dddd 77
</code></pre>
<p>I want to delete rows which have dist less than 10 to the next row. The expexted output is </p>
<pre><code>Name dist
aaaa 10
cccc 41
dddd 77
</code></pre>
<p>To do this I used the fol... | 1 | 2016-06-24T15:30:11Z | 38,017,460 | <p>IIUC you can do it this way:</p>
<pre><code>In [110]: df = df[df.dist.diff().fillna(100) >= 10]
In [111]: df
Out[111]:
Name dist
0 aaaa 10
2 cccc 41
3 dddd 77
</code></pre>
<p>Explanation:</p>
<pre><code>In [100]: df.dist.diff()
Out[100]:
0 NaN
1 1.0
2 30.0
3 36.0
Name: dist, dty... | 0 | 2016-06-24T15:54:46Z | [
"python",
"pandas"
] |
Run your own python script in background | 38,017,022 | <p>I have my own python library which gets installed wide when I do this</p>
<pre><code>python setup.py install
</code></pre>
<p>inside python project directory, it copies the executable file in bin also, but basically I am doing all this so, that it can be run as a service and I should be able to include it in upsta... | 0 | 2016-05-31T07:35:23Z | 38,017,099 | <p><code>&</code> is used to run a process in the background. It's still very much attached to the terminal (<code>tty</code>) you run it from.</p>
<p>These are the basic steps to making a process a daemon:</p>
<ol>
<li>Fork your process and kill its parent so that it becomes an orphan (handled directly by <code>... | 1 | 2016-06-24T15:35:25Z | [
"linux",
"unix",
"python",
"monit"
] |
Pandas transform aggregated clolumns with factors to rows | 38,017,024 | <p>I have a data frame like this:</p>
<pre><code>a1xbxc,a2xbxc
show 1 2
</code></pre>
<p>where a,b,c are attributes that can have different values e.g. a1,a2 for a and so on. Now the way I have this df is not good for plotting barcharts. I want to have it in a normal way like this:</p>
<pre><code>show factor... | 1 | 2016-06-24T15:31:18Z | 38,018,127 | <p>Try this:</p>
<pre><code>df.columns = pd.MultiIndex.from_tuples(df.columns.str.split('x').to_series().apply(tuple))
df.stack([0, 1])
c
show a1 b 1
a2 b 2
</code></pre>
| 1 | 2016-06-24T16:30:16Z | [
"python",
"pandas"
] |
How to parse a text file with the below pattern | 38,017,043 | <p>I am trying to parse the text file which is listed like below.</p>
<pre><code> BIOSReleaseDate = 04/13/2016
BIOSVersionString = 2.1.5
BaseBoardChassisSlot = Slot 08
BatteryRollupStatus = 1
BladeGeometry = 0
</code></pre>
<p>with this sort of text file having around 40 to 50 lines. I am able to read this outp... | -3 | 2016-06-24T15:32:29Z | 38,017,094 | <p>Try the .split() method</p>
<pre><code>with open('file.txt') as f:
lines = f.readlines()
d = {} #optional dictionary to store data
for l in lines:
parts = l.split(' = ') #stores the LHS and RHS of the line in a list
lhs = parts[0]
rhs = parts[1]
d[lhs] = rhs #store data i... | 1 | 2016-06-24T15:35:20Z | [
"python"
] |
How to parse a text file with the below pattern | 38,017,043 | <p>I am trying to parse the text file which is listed like below.</p>
<pre><code> BIOSReleaseDate = 04/13/2016
BIOSVersionString = 2.1.5
BaseBoardChassisSlot = Slot 08
BatteryRollupStatus = 1
BladeGeometry = 0
</code></pre>
<p>with this sort of text file having around 40 to 50 lines. I am able to read this outp... | -3 | 2016-06-24T15:32:29Z | 38,017,128 | <p>The <a href="https://docs.python.org/2/library/stdtypes.html#str.split" rel="nofollow">split()</a> method might come in handy here. You need to iterate over the lines.</p>
<pre><code>>>> string = "name=foo"
>>> print string.split("=")
["name", "foo"]
</code></pre>
| 1 | 2016-06-24T15:37:01Z | [
"python"
] |
Paho(MQTT) client can't connect | 38,017,111 | <p>I'm using this python script to implement a basic Paho(MQTT) subscriber but under certain circumstances it doesn't invoke <strong>on_connect</strong>. </p>
<p>I tried the following, all with exactly the same code:</p>
<ul>
<li>Running in a Raspbery pi, broker on desktop Pc (Ubuntu). <strong>Works</strong>.</li>
<l... | 3 | 2016-06-24T15:35:47Z | 38,060,817 | <p>I had the same problem and changing the version of MQTT protocol in <a href="https://pypi.python.org/pypi/paho-mqtt/1.1#constructor-reinitialise" rel="nofollow">Client's constructor</a> solved it.</p>
<pre><code>mqtt_client = mqtt.Client("", True, None, mqtt.MQTTv31)
</code></pre>
<p>Since you do not specify the p... | 4 | 2016-06-27T18:29:58Z | [
"python",
"ubuntu",
"mqtt",
"mosquitto",
"paho"
] |
How can I write SQL statements for psycopg2 for PostreSQL and sqlite3? | 38,017,127 | <p>I use the psycopg2 library for PostgreSQL in python for my production environment but I want to test my code with the sqlite3 library. The problem is that psycopg2 uses <code>%s</code> as a placeholder for parameter substitution, whereas sqlite3 uses <code>?</code>.</p>
<p>I am not happy with the code I got now, it... | 1 | 2016-06-24T15:37:00Z | 38,017,207 | <p>Using simple <code>?</code> to <code>%s</code> string replacement is dangerous, you may break your query, or harm the actual data in all sorts of unpredictable ways which could be difficult to debug.</p>
<hr>
<p>Look into the "SQL for humans" <a href="https://github.com/kennethreitz/records" rel="nofollow"><code>r... | 2 | 2016-06-24T15:41:21Z | [
"python",
"postgresql",
"sqlite",
"sqlite3"
] |
Why wont this code output the result? | 38,017,137 | <pre><code>print "HEllo !!"
print "Today, I will calculate something for you !!"
print "Enter your first number"
num1 = raw_input()
print "enter your second number"
num2 = raw_input()
print "type 1 for ADDITION"
print "type 2 for SUBTRACTION"
print "type 3 for MULTIPLICATION"
print "type 4 for DIVISION"
press=raw_input... | 0 | 2016-06-24T15:37:27Z | 38,017,172 | <p><a href="https://docs.python.org/2/library/functions.html#raw_input" rel="nofollow"><code>raw_input</code> returns a <code>str</code> object</a>, hence the <code>press == 1</code> can never be true:</p>
<pre><code>>>> a = raw_input()
1
>>> type(a)
<type 'str'>
>>> a == 1
False
>&... | 1 | 2016-06-24T15:39:25Z | [
"python"
] |
Why wont this code output the result? | 38,017,137 | <pre><code>print "HEllo !!"
print "Today, I will calculate something for you !!"
print "Enter your first number"
num1 = raw_input()
print "enter your second number"
num2 = raw_input()
print "type 1 for ADDITION"
print "type 2 for SUBTRACTION"
print "type 3 for MULTIPLICATION"
print "type 4 for DIVISION"
press=raw_input... | 0 | 2016-06-24T15:37:27Z | 38,017,175 | <ol>
<li>You're checking the input from <code>raw_input()</code>, which is a string, against integers. They never match, and your <code>if</code> blocks are never entered into.</li>
<li>You are accepting <code>num1</code> and <code>num2</code> as strings, not integers. Use <code>input()</code> instead.</li>
</ol>
<p>T... | 1 | 2016-06-24T15:39:36Z | [
"python"
] |
Why wont this code output the result? | 38,017,137 | <pre><code>print "HEllo !!"
print "Today, I will calculate something for you !!"
print "Enter your first number"
num1 = raw_input()
print "enter your second number"
num2 = raw_input()
print "type 1 for ADDITION"
print "type 2 for SUBTRACTION"
print "type 3 for MULTIPLICATION"
print "type 4 for DIVISION"
press=raw_input... | 0 | 2016-06-24T15:37:27Z | 38,017,197 | <p>Your issue here is that you are getting a string input, and then comparing it directly to an integer value. Since a <code>str</code> is not an <code>int</code> all your <code>if</code> statements evaluate to <code>False</code>. Either compare directly to a string, or convert the input to <code>int</code>.</p>
<p>... | 2 | 2016-06-24T15:40:53Z | [
"python"
] |
Calculating medoid of a cluster (Python) | 38,017,194 | <p>So I'm running a KNN in order to create clusters. From each cluster, I would like to obtain the medoid of the cluster.</p>
<p>I'm employing a fractional distance metric in order to calculate distances:</p>
<p><a href="http://i.stack.imgur.com/Xtqwi.png" rel="nofollow"><img src="http://i.stack.imgur.com/Xtqwi.png" ... | -1 | 2016-06-24T15:40:45Z | 38,022,636 | <ol>
<li>compute pairwise distance matrix</li>
<li>compute column or row sum</li>
<li>argmin to find medoid index</li>
</ol>
<p>i.e. <code>numpy.argmin(distMatrix.sum(axis=0))</code> or similar.</p>
| 1 | 2016-06-24T21:54:51Z | [
"python",
"numpy",
"cluster-analysis",
"distance"
] |
Calculating medoid of a cluster (Python) | 38,017,194 | <p>So I'm running a KNN in order to create clusters. From each cluster, I would like to obtain the medoid of the cluster.</p>
<p>I'm employing a fractional distance metric in order to calculate distances:</p>
<p><a href="http://i.stack.imgur.com/Xtqwi.png" rel="nofollow"><img src="http://i.stack.imgur.com/Xtqwi.png" ... | -1 | 2016-06-24T15:40:45Z | 38,577,250 | <p>So I've accepted the answer here, but I thought I'd provide my implementation if anyone else was trying to do something similar:</p>
<p>(1) This is the distance function:</p>
<pre><code>def fractional(p_coord_array, q_coord_array):
# f is an arbitrary value, but must be greater than zero and
# less than one. ... | 0 | 2016-07-25T20:53:46Z | [
"python",
"numpy",
"cluster-analysis",
"distance"
] |
Locate a specific line in a file based on user input then delete a specific number of lines | 38,017,264 | <p>I'm trying to delete specific lines in a text file the way I need to go about it is by prompting the user to input a string (a phrase that should exist in the file) the file is then searched and if the string is there the data on that line and the number line number are both stored. </p>
<p>After the phrase has be... | 0 | 2016-06-24T15:44:15Z | 38,017,816 | <p>Usually I would not think it's desirable to overwrite the source file - what if the user does something by mistake? If your project allows, I would write the changes out to a new file.</p>
<pre><code>with open('source.txt', 'r') as ifile:
with open('output.txt', 'w') as ofile:
locate = "example string"... | 0 | 2016-06-24T16:14:05Z | [
"python"
] |
Locate a specific line in a file based on user input then delete a specific number of lines | 38,017,264 | <p>I'm trying to delete specific lines in a text file the way I need to go about it is by prompting the user to input a string (a phrase that should exist in the file) the file is then searched and if the string is there the data on that line and the number line number are both stored. </p>
<p>After the phrase has be... | 0 | 2016-06-24T15:44:15Z | 38,017,829 | <p>You are appending to your file by using <a href="https://docs.python.org/3/library/functions.html#open" rel="nofollow"><code>open</code></a> with 'a'. Also, you are not closing your file (bad habit). <code>str.strip()</code> does not delete the line, it removes whitespace by default. Also, this would usually be done... | 0 | 2016-06-24T16:14:29Z | [
"python"
] |
Locate a specific line in a file based on user input then delete a specific number of lines | 38,017,264 | <p>I'm trying to delete specific lines in a text file the way I need to go about it is by prompting the user to input a string (a phrase that should exist in the file) the file is then searched and if the string is there the data on that line and the number line number are both stored. </p>
<p>After the phrase has be... | 0 | 2016-06-24T15:44:15Z | 38,017,845 | <p>You can find the occurrences, copy the list items between the occurrences to a new list and then save the new list into the file.</p>
<pre><code>_newData = []
_linesToSkip = 3
with open('data.txt', 'r') as _file:
data = _file.read().splitlines()
occurrences = [i for i, x in enumerate(data) if "example stri... | 0 | 2016-06-24T16:15:06Z | [
"python"
] |
Locate a specific line in a file based on user input then delete a specific number of lines | 38,017,264 | <p>I'm trying to delete specific lines in a text file the way I need to go about it is by prompting the user to input a string (a phrase that should exist in the file) the file is then searched and if the string is there the data on that line and the number line number are both stored. </p>
<p>After the phrase has be... | 0 | 2016-06-24T15:44:15Z | 38,017,954 | <p>There are a couple of points that you clearly misunderstand here:</p>
<h1><code>.strip()</code> removes whitespace or given characters:</h1>
<pre><code>>>> print(str.strip.__doc__)
S.strip([chars]) -> str
Return a copy of the string S with leading and trailing
whitespace removed.
If chars is given and... | 0 | 2016-06-24T16:21:27Z | [
"python"
] |
Patch all functions in module with decorator | 38,017,401 | <p>I have a python module with lots of functions and I want to apply a decorator for all of them.
Is there a way to patch all of them via monkey-patching to apply this decorator for every function without copy-pasting on line of applying decorator?</p>
<p>In other words, I want to replace this:</p>
<pre><code>@loggi... | 2 | 2016-06-24T15:51:02Z | 38,017,766 | <p>I'm really not certain that this is a good idea. <a href="https://www.python.org/dev/peps/pep-0020/" rel="nofollow">Explicit is better than implicit</a>, after all.</p>
<p>With that said, something like this should work, using <a href="https://docs.python.org/2/library/inspect.html" rel="nofollow">inspect</a> to fi... | 3 | 2016-06-24T16:11:36Z | [
"python"
] |
Patch all functions in module with decorator | 38,017,401 | <p>I have a python module with lots of functions and I want to apply a decorator for all of them.
Is there a way to patch all of them via monkey-patching to apply this decorator for every function without copy-pasting on line of applying decorator?</p>
<p>In other words, I want to replace this:</p>
<pre><code>@loggi... | 2 | 2016-06-24T15:51:02Z | 38,017,778 | <p>I ain't gonna be pretty ... but you can list all functions using dir() after their definition. Then I can't think of a way to patch them without a wrapper function.</p>
<pre><code>def patched(func):
@logging_decorator
def newfunc(*args, **kwargs):
return func(*args, **kwargs)
return newfunc
fun... | 1 | 2016-06-24T16:12:18Z | [
"python"
] |
Convert an address to a specific type in python gdb | 38,017,430 | <p>I have an user defined struct.</p>
<pre><code>struct foo {
int bar1;
char *name;
user_type_t *tba;
}foo_t;
</code></pre>
<p>While in gdb, I have an address that points to type foo_t.
e.g 0xfe83ba56 points to a structure in the memory that is of type foo_t.</p>
<p>I can convert that address to foo_t by... | 0 | 2016-06-24T15:53:04Z | 38,022,245 | <p>To cast, use the <code>Value.cast</code> method. Something like:</p>
<pre><code>t = gdb.lookup_type('foo_t').pointer()
value = value.cast(t)
</code></pre>
| 1 | 2016-06-24T21:17:01Z | [
"python",
"c++",
"c",
"gdb"
] |
How to add a line on top of a bar chart? | 38,017,465 | <p>I have a barplot on top of which I would like to draw a line segment between two coordinates (i.e., in the same figure). I tried by adding another plt statement, but the line is not drawn.</p>
<pre><code>plt.figure(figsize=(12, 10))
ax = freq_series.plot(kind='bar',color=colors)
plt.plot([coord_x1,coord_y1], [coord... | 3 | 2016-06-24T15:55:01Z | 38,017,981 | <p><strong>UPDATE:</strong></p>
<pre><code>import datetime
import matplotlib as mpl
import matplotlib.pyplot as plt
mpl.style.use('ggplot')
d = {
datetime.date(2015, 6, 21): 101.0,
datetime.date(2015, 6, 22): 81.0,
datetime.date(2015, 6, 23): 94.0,
datetime.date(2015, 4, 24): 67.5,
datetime.da... | 2 | 2016-06-24T16:22:30Z | [
"python",
"pandas",
"matplotlib"
] |
Why is Numpy inconsistent in ordering polynomial coefficients by degree? | 38,017,516 | <p><a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.polynomial.polynomial.Polynomial.html" rel="nofollow">numpy.polynomial.polynomial.Polynomial</a> stores polynomial coefficients in order of increasing degree, while <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.poly1d.html" rel="... | 3 | 2016-06-24T15:57:52Z | 38,017,661 | <p>According to the <a href="http://docs.scipy.org/doc/numpy/reference/routines.polynomials.html">SciPy reference on NumPy</a>:</p>
<blockquote>
<p>Prior to NumPy 1.4, numpy.poly1d was the class of choice and it is still available in order to maintain backward compatibility. However, the newer Polynomial package is ... | 5 | 2016-06-24T16:05:53Z | [
"python",
"numpy",
"scipy",
"polynomials",
"coefficients"
] |
Populate Month Based on Date Field in Django | 38,017,523 | <p>I would like to have a field auto-generate the month based on the date entered before it. </p>
<p>models.py</p>
<pre><code>class Projects(models.Model):
Name = models.CharField(max_length=100, null=True, blank=False)
Date = models.DateField(null=True, blank=False)
Month = models.CharField(max_length=1... | -1 | 2016-06-24T15:58:14Z | 38,017,631 | <p>You can simply override your <code>save</code> to add the <em>auto-field</em> instead of calling <code>save</code> in a new method:</p>
<pre><code>class Projects(models.Model):
Name = models.CharField(max_length=100, null=True, blank=False)
Date = models.DateField(null=True, blank=False)
Month = models... | 1 | 2016-06-24T16:03:42Z | [
"python",
"django",
"date",
"django-models",
"django-admin"
] |
Suit form include on list display in admin | 38,017,552 | <p>Im trying to use Django Suit's form includes to add a button to the list display of all my subscribers in the admin. In the documentation it says to add this to your admin.py file in the right app.</p>
<pre><code>class SubscriberAdmin(admin.ModelAdmin):
list_display = ('email', 'date')
readonly_fields = ('e... | 0 | 2016-06-24T16:00:00Z | 38,763,697 | <p>What's doing django-suit, here, is that it is including your HTML snippet in the change_form that is displayed for your model, the <strong>change_form</strong> being where you can modify your model and save the changes into the database.</p>
<p>Where you want it to appear is the "<strong>change_list</strong>", aka ... | 0 | 2016-08-04T09:36:45Z | [
"python",
"django",
"templates",
"admin"
] |
Call variable across different files in Python and dealing with circular imports | 38,017,696 | <p>I am currently building a docx/pdf converter in Python, and have decided to split up the files into 2 documents:</p>
<p><strong><code>main.py</code></strong> - controls the program's flow;</p>
<p><strong><code>convert_to_text.py</code></strong> - contains the function that converts pdf/docx files to txt.</p>
<p>A... | 1 | 2016-06-24T16:07:35Z | 38,017,979 | <p>You have a circular import that needs resolved. This is your script's execution path:</p>
<ol>
<li>main.py starts</li>
<li>main.py attempts to import everything from the convert_to_text module, triggering evaluation of convert_to_text.py</li>
<li>convert_to_text.py attempts to import the main module, triggering mai... | 2 | 2016-06-24T16:22:26Z | [
"python"
] |
Call variable across different files in Python and dealing with circular imports | 38,017,696 | <p>I am currently building a docx/pdf converter in Python, and have decided to split up the files into 2 documents:</p>
<p><strong><code>main.py</code></strong> - controls the program's flow;</p>
<p><strong><code>convert_to_text.py</code></strong> - contains the function that converts pdf/docx files to txt.</p>
<p>A... | 1 | 2016-06-24T16:07:35Z | 38,018,125 | <p>If the only thing you need from <code>main.py</code> is <code>cv</code>, you should simply pass <code>cv</code> in to the functions that need it. And since the functions don't actually <em>use</em> <code>cv</code> (other than to set it), there's no reason to do that either.</p>
<p>Your whole problem can be solved b... | 3 | 2016-06-24T16:30:00Z | [
"python"
] |
Python Selenium Click and Input Into Text Box | 38,017,774 | <p>I am running Python 3.5 trying to "click" a text box with selenium so I can input rows of numbers. I have already scripted the login and navigation to the text box but I can't get my code to type "1234".</p>
<p>Here is the code, maybe there is something bigger in the HTML I am missing but the inspector tool shows t... | 1 | 2016-06-24T16:12:01Z | 38,017,818 | <pre><code>//*[contains(class(), 'stb-SearchBox')]
</code></pre>
<p>Here you are incorrectly checking the <code>class</code> attribute. It needs to be <code>@class</code> instead of <code>class()</code>.</p>
<pre><code>driver.find_elements_by_class('stb-SearchBox').click()
</code></pre>
<p>There is no <code>find_ele... | 0 | 2016-06-24T16:14:12Z | [
"python",
"html",
"selenium"
] |
Monte-Carlo integration in spherical coordinates | 38,017,791 | <p>I tried to implement a simple Monte-Carlo integration in in 6 dimensions. The integral only covers two 3D spheres, in the following the coordinates for the spheres are labeled r1 and r2.
When using cartesian coordinates and ignoring anything outside of the spheres the integration works fine. Using spherical coordina... | 1 | 2016-06-24T16:12:50Z | 38,055,088 | <p>The problem with the above code is in the following line</p>
<pre><code>sin_phi = sqrt(1-cos_phi**2)
</code></pre>
<p>This only yields positive results, while <code>sin(phi)</code> yields negative results for <code>phi > pi</code></p>
| 1 | 2016-06-27T13:20:37Z | [
"python",
"numpy",
"montecarlo"
] |
Why a single element list is taking two inputs and then giving out of range error? | 38,017,833 | <p>The code below consists of a List having only one element but on running, it is taking two inputs and then giving an error rather than giving an error after first input. Why?</p>
<pre><code>def ani():
sales = [0]
index = 0
print('Enter the sales for each day')
while index < 5:
... | 0 | 2016-06-24T16:14:35Z | 38,017,883 | <p>Obviously your traceback would have told you that the error is on this line:</p>
<pre><code>sales[index] = float(input())
</code></pre>
<p>It succeeds on the first pass through the <code>while</code> loop because <code>index</code> is <code>0</code>. On the second pass through the loop, <code>index</code> is <cod... | 2 | 2016-06-24T16:17:20Z | [
"python",
"list",
"python-3.x"
] |
updating dataframe by row but not updating | 38,017,843 | <p>I am iterating through a dataframe and I am trying to add values to a specific column for each row but when I print the rulting data frame the values are not present</p>
<pre><code>#add two new blank columns to the dayData dataframe
dayData["myValue1"]=""
dayData["myValue2"]=""
#iterate over the dataframe
for idx... | 2 | 2016-06-24T16:14:59Z | 38,018,198 | <p>Instead of assigning to the row, assign back to the dataframe with index. The row is a copy of the row and changes to it won't persist in the parent dataframe.</p>
<p>Instead of:</p>
<pre><code> row["myValue1"]=value1
row["myValue2"]=value2
</code></pre>
<p>Do:</p>
<pre><code> dayData.loc[... | 3 | 2016-06-24T16:34:02Z | [
"python",
"pandas",
"dataframe"
] |
Script won't run on double-click in Windows | 38,017,875 | <p>I have a script and it won't actually run. </p>
<p>I have the defaults and such set correctly to interpret using Python, but double-clicking the file gets me a flash of the command prompt and the following error message: </p>
<blockquote>
<p>cannot find module openpyxl.</p>
</blockquote>
<p>However, running in ... | -1 | 2016-06-24T16:16:54Z | 38,024,639 | <p>you may add "import os" at the first line and add "os.system("pause")" at last line to see what exactly happen.if you both have python 2.x and python 3.x in your computer,maybe you can just uninstall python 2.x to finish off your trouble.</p>
| 0 | 2016-06-25T03:25:44Z | [
"python",
"python-3.x",
"openpyxl"
] |
Trouble using bash command in python script | 38,017,877 | <p>I'm trying to convert a bash script to python, and some of the commands don't seem to execute in the way I want them to. Basically, the script should install files, run tcpdump and the monkey command and then uninstall the package.</p>
<p>I'm iterating through apk files and installing them with this function which ... | 2 | 2016-06-24T16:16:59Z | 38,019,390 | <p>Like @Jobin suggested, you need to remove the space at the end of "/home/seed/Documents/Programs " since that would result in something like:</p>
<pre><code>sudo -i xterm -e tcpdump src 10.0.2.7 -vvv > /home/seed/Documents/Programs apkPackage.pcap
</code></pre>
<p>which obviously isn't right. You probably want ... | 0 | 2016-06-24T17:52:24Z | [
"python",
"linux",
"bash",
"tcpdump"
] |
Merge some columns of a csv file depending on a condition | 38,017,887 | <p>I have a csv file, that looks like this:</p>
<pre><code>5005284;5003485;C1; C2;A00.00;10-11-01;NULL;1;;
2006483;2003855;this is some text; and some 787; or even &[]\><;A87.03;30-09-86;NULL;1;
2006485;2003855;C;K86.00;31-12-91;NULL;1;;;
</code></pre>
<p>The file is <code>;</code> separated and unfortunate... | 0 | 2016-06-24T16:17:23Z | 38,018,281 | <h1>Removing ";"</h1>
<p><code>line.replace()</code> does not change the original line, it returns a new line with the requested changes. See documentation <a href="http://www.tutorialspoint.com/python/string_replace.htm" rel="nofollow">here</a> Therefore, this code is not doing what you think it is:</p>
<pre><code... | 0 | 2016-06-24T16:39:01Z | [
"python",
"csv"
] |
Merge some columns of a csv file depending on a condition | 38,017,887 | <p>I have a csv file, that looks like this:</p>
<pre><code>5005284;5003485;C1; C2;A00.00;10-11-01;NULL;1;;
2006483;2003855;this is some text; and some 787; or even &[]\><;A87.03;30-09-86;NULL;1;
2006485;2003855;C;K86.00;31-12-91;NULL;1;;;
</code></pre>
<p>The file is <code>;</code> separated and unfortunate... | 0 | 2016-06-24T16:17:23Z | 38,018,902 | <p>Try this code:</p>
<pre><code>import csv
import re
with open('file.csv') as f, open('newfile.csv', 'w', newline='') as newf:
reader = csv.reader(f, delimiter=';')
writer = csv.writer(newf, delimiter=';')
rows = []
for row in reader:
for i, e in enumerate(row):
if re.match('[A-... | 2 | 2016-06-24T17:18:50Z | [
"python",
"csv"
] |
Numpy: Create 2D array based on value from dict, using other 2D array value as index | 38,017,937 | <p>I have 2 2D numpy arrays:</p>
<pre><code>a = np.array([['a', 'b', 'c'], ['d', 'e', 'f']])
b = np.array([[0.01, 0.02, 0.03], [0.04, 0.05, 0.06]])
</code></pre>
<p>I aso have a dict with some values:</p>
<pre><code>d = {'a': 100, 'b': 200, ... 'f':600}
</code></pre>
<p>Now I want to create a 2D array, based on the... | 1 | 2016-06-24T16:20:24Z | 38,018,178 | <p>You can use the <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.vectorize.html" rel="nofollow">vectorize</a> function on the <code>d.get</code> method to use the values of <code>a</code> as keys for <code>d</code>:</p>
<pre><code>>>> np.vectorize(d.get)(a)
array([[100, 200, 300],
... | 0 | 2016-06-24T16:32:53Z | [
"python",
"arrays",
"numpy",
"dictionary"
] |
Numpy: Create 2D array based on value from dict, using other 2D array value as index | 38,017,937 | <p>I have 2 2D numpy arrays:</p>
<pre><code>a = np.array([['a', 'b', 'c'], ['d', 'e', 'f']])
b = np.array([[0.01, 0.02, 0.03], [0.04, 0.05, 0.06]])
</code></pre>
<p>I aso have a dict with some values:</p>
<pre><code>d = {'a': 100, 'b': 200, ... 'f':600}
</code></pre>
<p>Now I want to create a 2D array, based on the... | 1 | 2016-06-24T16:20:24Z | 38,018,405 | <p>Here's a vectorized approach making use of NumPy functions along the way -</p>
<pre><code># Convert strings in a to numeric labels
aID = (np.fromstring(a, dtype=np.uint8)-97).reshape(a.shape)
# Get the argsort for getting sorted keys from dictionary
dk = d.keys()
sidx = np.searchsorted(sorted(dk),dk)
# Extract va... | 0 | 2016-06-24T16:46:31Z | [
"python",
"arrays",
"numpy",
"dictionary"
] |
Python Tulpe Key For Dict Partial Lookup | 38,017,943 | <p>I have a dictionary with a tuple of 5 values as a key. For example:</p>
<p>D[i,j,k,g,h] = value.</p>
<p>Now i need to process all elements with a certain partial key pair (i1,g1):</p>
<p>I need now for each pair (i1,g1) all values that have i == i1 and g == g1 in the full key.</p>
<p>What is an pythonic and effi... | 0 | 2016-06-24T16:20:46Z | 38,018,141 | <pre><code>for k,v in D.iteritems():
if i in k and p in k:
print v
</code></pre>
| -1 | 2016-06-24T16:30:51Z | [
"python",
"python-2.7",
"dictionary"
] |
Python Tulpe Key For Dict Partial Lookup | 38,017,943 | <p>I have a dictionary with a tuple of 5 values as a key. For example:</p>
<p>D[i,j,k,g,h] = value.</p>
<p>Now i need to process all elements with a certain partial key pair (i1,g1):</p>
<p>I need now for each pair (i1,g1) all values that have i == i1 and g == g1 in the full key.</p>
<p>What is an pythonic and effi... | 0 | 2016-06-24T16:20:46Z | 38,020,386 | <p>Assuming you know all the valid values for the different indices you can get <strong>all possible</strong> keys using <code>itertools.product</code>:</p>
<pre><code>import itertools
I = [3,6,9]
J = range(10)
K = "abcde"
G = ["first","second"]
H = range(10,20)
for tup in itertools.product(I,J,K,G,H):
my_dict[tu... | 0 | 2016-06-24T19:00:14Z | [
"python",
"python-2.7",
"dictionary"
] |
Find difference between dates in df using python | 38,017,946 | <p>I have data </p>
<pre><code> date id request
0 2016-06-22 03:00:48 upi88@yandex.ru GET HTTP/1.1
1 2016-06-22 03:02:52 upi88@yandex.ru GET HTTP/1.1
2 2016-06-22 03:03:48 upi88@yandex.ru GET HTTP/1.1
3 2016-06-22 03:05:15 ... | 0 | 2016-06-24T16:20:53Z | 38,018,047 | <p>is that what you want?</p>
<pre><code>In [130]: df
Out[130]:
date id request
0 2016-06-22 03:00:48 upi88@yandex.ru GET HTTP/1.1
1 2016-06-22 03:02:52 upi88@yandex.ru GET HTTP/1.1
2 2016-06-22 03:03:48 upi88@yandex.ru GET HTTP/1.1
3 2016-06-22 03:05:15 upi88@yandex.ru G... | 0 | 2016-06-24T16:26:02Z | [
"python",
"datetime",
"pandas"
] |
Find difference between dates in df using python | 38,017,946 | <p>I have data </p>
<pre><code> date id request
0 2016-06-22 03:00:48 upi88@yandex.ru GET HTTP/1.1
1 2016-06-22 03:02:52 upi88@yandex.ru GET HTTP/1.1
2 2016-06-22 03:03:48 upi88@yandex.ru GET HTTP/1.1
3 2016-06-22 03:05:15 ... | 0 | 2016-06-24T16:20:53Z | 38,018,058 | <p>you code beginning index is 1 and i-1 is -1 </p>
<pre><code>dates = df1['date']
for i in range(1,len(dates)):
dates[i].to_datetime()
d = (dates[i] - dates[i-1]).total_seconds()
</code></pre>
| 0 | 2016-06-24T16:26:30Z | [
"python",
"datetime",
"pandas"
] |
Use pandas DataFrame / Panel .apply() together with index/column information | 38,017,972 | <p>I have a pandas DataFrame that looks like this:</p>
<pre><code> 2016 2017 2018 2019 2020
1 0.014199 0.020776 0.016393 0.010112 0.013346
2 0.025220 0.024088 0.035357 0.026878 0.031841
3 0.016345 0.014117 0.017157 0.019280 0.017307
4 0.021467 0.020389 0.027269 0.027727... | 2 | 2016-06-24T16:22:02Z | 38,018,104 | <p>try this:</p>
<pre><code>In [138]: df.apply(lambda x: int(x.name) + x)
Out[138]:
2016 2017 2018 2019 2020
1 2016.014199 2017.020776 2018.016393 2019.010112 2020.013346
2 2016.025220 2017.024088 2018.035357 2019.026878 2020.031841
3 2016.016345 2017.014117 2018.... | 2 | 2016-06-24T16:29:13Z | [
"python",
"pandas",
"apply"
] |
Use pandas DataFrame / Panel .apply() together with index/column information | 38,017,972 | <p>I have a pandas DataFrame that looks like this:</p>
<pre><code> 2016 2017 2018 2019 2020
1 0.014199 0.020776 0.016393 0.010112 0.013346
2 0.025220 0.024088 0.035357 0.026878 0.031841
3 0.016345 0.014117 0.017157 0.019280 0.017307
4 0.021467 0.020389 0.027269 0.027727... | 2 | 2016-06-24T16:22:02Z | 38,018,114 | <p>Assuming your column names are integers you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.add.html" rel="nofollow"><code>add</code></a> with the column values:</p>
<pre><code>df = df.add(df.columns.values)
</code></pre>
<p>If the column names are strings, use <code>map</co... | 2 | 2016-06-24T16:29:39Z | [
"python",
"pandas",
"apply"
] |
Python appending 2D array? | 38,018,031 | <p>it has been a while for me doing python scripting after about 8 months of hiatus. Really need some insights.
I have been trying to set or modify the camera filmback/film gate attribute via coding and after much trial and errors, I finally found the command for it but now I am meeting with some other issues..</p>
<p... | 1 | 2016-06-24T16:25:10Z | 38,018,209 | <p>You don't need to add a dummy element to your list enumerate has a second argument that indicates the position it should start from. using this you can store the index and the item side by side in a separate list</p>
<pre><code>list02 = []
list01 = ['itemA-01', 'itemB-02', 'itemC-02', 'itemD-01', 'itemE-01', 'item... | 1 | 2016-06-24T16:34:43Z | [
"python",
"maya"
] |
How to install pygame, cv2, anaconda, pip etc to any one version of python in ubuntu 14.04 | 38,018,045 | <p>I have Ubuntu 14.04 LTS. I guess different versions python are pre installed in Ubuntu 14.04. Right now when I type 'python' it opens python 2.7.11, but I guess the default version of Ubuntu 14.04 is 2.7.6. When I type '/usr/bin/python' it opens the default version. I know this can be done with making aliases. The r... | 0 | 2016-06-24T16:26:00Z | 38,018,893 | <p>If you have <code>easy_install</code> installed you can run</p>
<pre><code>sudo easy_install pip
</code></pre>
<p>to install pip. As far as installing Anaconda goes, try using <a href="http://askubuntu.com/questions/505919/installing-anaconda-python-on-ubuntu">this</a> stack overflow question's answer. If you can... | 0 | 2016-06-24T17:18:26Z | [
"python",
"pygame",
"ubuntu-14.04"
] |
How to install pygame, cv2, anaconda, pip etc to any one version of python in ubuntu 14.04 | 38,018,045 | <p>I have Ubuntu 14.04 LTS. I guess different versions python are pre installed in Ubuntu 14.04. Right now when I type 'python' it opens python 2.7.11, but I guess the default version of Ubuntu 14.04 is 2.7.6. When I type '/usr/bin/python' it opens the default version. I know this can be done with making aliases. The r... | 0 | 2016-06-24T16:26:00Z | 38,035,454 | <p>First of all I want to thanks Bennet for responding to my question so that I was able to figure out what the problem was. Actually the problem was with aliasing. When I installed cv2 or pygame using apt-get, they were installed for default version but when I installed any package by downloading the installer first (... | 0 | 2016-06-26T05:18:32Z | [
"python",
"pygame",
"ubuntu-14.04"
] |
How to compress a large file in Python? | 38,018,071 | <p>The problem I'm experiencing is the name of the stored file. The stored file isn't named with the original/uncompressed file name. Instead the stored file is named with the archive name (with the appended ".gz" extension).</p>
<p>Expected Result:<br>
file.txt.gz {archive name}<br>
....file.txt ... | 1 | 2016-06-24T16:27:15Z | 38,019,097 | <p>You are making a distinction between 'stored file name' and 'archive name', but for gzip compression, this is the wrong way to think, because gzip is not an archive format, but just a compression protocol.</p>
<p>When you store a 'gzip' file, it does not (necessarily) remember the original filename. There is only t... | -1 | 2016-06-24T17:32:28Z | [
"python",
"compression",
"gz"
] |
How to compress a large file in Python? | 38,018,071 | <p>The problem I'm experiencing is the name of the stored file. The stored file isn't named with the original/uncompressed file name. Instead the stored file is named with the archive name (with the appended ".gz" extension).</p>
<p>Expected Result:<br>
file.txt.gz {archive name}<br>
....file.txt ... | 1 | 2016-06-24T16:27:15Z | 38,020,236 | <p>You have to use <code>gzip.GzipFile()</code>; the shorthand <code>gzip.open()</code> won't do what you want.</p>
<p>Quoth <a href="https://docs.python.org/2.7/library/gzip.html#gzip.GzipFile" rel="nofollow">the doc</a>:</p>
<blockquote>
<p>When <em>fileobj</em> is not <code>None</code>, the <em>filename</em> arg... | 1 | 2016-06-24T18:49:40Z | [
"python",
"compression",
"gz"
] |
Reading hdf5 datasets with pandas | 38,018,186 | <p>I'm trying to open a group-less hdf5 file with pandas:</p>
<pre><code>import pandas as pd
foo = pd.read_hdf('foo.hdf5')
</code></pre>
<p>but I get an error:</p>
<blockquote>
<p>TypeError: cannot create a storer if the object is not existing nor a value are passed</p>
</blockquote>
<p>I tried solving this by as... | 1 | 2016-06-24T16:33:09Z | 38,018,296 | <p>I think you'are confused by different terminology - Pandas's HDF store <code>key</code> is a full path i.e. <code>Group + DataSet_name</code>...</p>
<p>demo:</p>
<pre><code>In [67]: store = pd.HDFStore(r'D:\temp\.data\hdf\test.h5')
In [68]: store.append('dataset1', df)
In [69]: store.append('/group1/sub_group1/d... | 0 | 2016-06-24T16:39:57Z | [
"python",
"pandas",
"dataset",
"hdf5"
] |
Why is the While statement is executing only 1 time? | 38,018,338 | <p>I just started programming and I was challenged to implement multiplication through addition. Here is my code.</p>
<pre><code>def multiply(a,b):
c=0
while a!=0 and b!=0:
a=(abs(a)-1)
c=b+b
return print(c)
multiply(5,3)
</code></pre>
<p>The problem is that it's giving me the answer 6. I... | 0 | 2016-06-24T16:42:34Z | 38,018,356 | <p>Because <code>c=b+b</code> replaces the value of <code>c</code> each time through the loop, no matter how many times the loop runs. Try <code>c=c+b</code> instead.</p>
| 4 | 2016-06-24T16:44:15Z | [
"python",
"python-2.7",
"python-3.x"
] |
How can I scrape content on the next page of the posts I have already scraped? | 38,018,359 | <p>I have been programming for almost a year, I am a novice. I am working on a django web app that scrapes posts and then follows the hyper link of each post and scrapes the body text so I can store it. I can scrape the posts fine, but following the link of each post and scraping it is not working out how I wanted. I t... | 1 | 2016-06-24T16:44:20Z | 38,018,504 | <p>You need to extract the hrefs from the titles inside <code>list/ResultSet</code>, <code>find_all</code> returns a list from 0-n matches:</p>
<pre><code>comments_urls = [ url_two + d.a[href] for d in titles]
</code></pre>
<p>That would give you a list of urls which you would need to iterate over. I would also rec... | 0 | 2016-06-24T16:53:25Z | [
"python",
"html",
"django",
"web-scraping",
"beautifulsoup"
] |
tensorflow ffmpeg contrib output | 38,018,423 | <p>First, I want to say that I'm completely new to TensorFlow and machine learning in general.<br>
I'm looking at the <a href="https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/ffmpeg" rel="nofollow">ffmpeg</a> contrib section and I see the example of decoding an audio file and I was wondering wha... | 1 | 2016-06-24T16:47:30Z | 38,021,033 | <p>Each of those float values in the waveform represent the <em>amplitude</em> of the corresponding audio at a discrete moment in time depending on the sample rate (in this case, every 1/16,000th of a second). If you were looking at 2 channels of audio rather than 1, you'd have another similar ndarray, thereby giving y... | 1 | 2016-06-24T19:46:20Z | [
"python",
"ffmpeg",
"tensorflow"
] |
pydispatch module installed but still couldn't be found | 38,018,426 | <p>I tried to install scrapy on my raspberry pi (raspbian os). The installation went okay, but when I run <code>scrapy</code> command, it showed that several modules are missing. So I installed them one by one:
<code>sudo pip install lxml', then 'sudo pip install cssselect'. Then 'sudo pip install pydispatch</code>. Th... | 3 | 2016-06-24T16:47:34Z | 38,019,462 | <p>The package's name is <a href="https://pypi.python.org/pypi/PyDispatcher" rel="nofollow">PyDispatcher</a>. So try installing it using this command and check if that works.</p>
<pre><code>pip install PyDispatcher
</code></pre>
<p>Problems during installation of scrapy varies on different platforms. Please share you... | 3 | 2016-06-24T17:58:00Z | [
"python",
"module",
"installation",
"raspberry-pi",
"scrapy"
] |
Python too many indices for array shape (0,) | 38,018,431 | <p>again continue from my previous work, I have manage to loop through the list into function but I am not able to plot the way I run the loop on a list </p>
<pre><code>%matplotlib inline
from pylab import *
import numpy as np
with open('/home/../Downloads/combinationplot.txt','rb') as file:
a = file.readlines()
... | 1 | 2016-06-24T16:47:59Z | 38,018,617 | <p>You're trying to reference at second dimension <code>X[:, 0]</code> on <code>X</code> when you specified it is a one dimensional array. Your loop will make <code>X</code> 2-dim only if it passes into the <code>else</code> clause. If it doesn't, it will remain 1-dim. From your print out, X is an empty one dim arra... | 0 | 2016-06-24T16:59:48Z | [
"python",
"pandas"
] |
Cannot connect to mongodb database with python pymongo ssh | 38,018,435 | <p>Sorry, I'm very much a noob with mongodb. There is a database that I can access by ssh that I want to write a script for, but I can't seem to be able to get that to work. I ssh with:</p>
<blockquote>
<p>ssh user@##.##...<br>
mongo</p>
</blockquote>
<p>And I try to connect with my python script by:</p>
<pre><c... | 0 | 2016-06-24T16:48:19Z | 38,018,611 | <p>I managed to fix this using port forwarding:</p>
<p><a href="https://help.ubuntu.com/community/SSH/OpenSSH/PortForwarding" rel="nofollow">https://help.ubuntu.com/community/SSH/OpenSSH/PortForwarding</a></p>
| 0 | 2016-06-24T16:59:29Z | [
"python",
"mongodb",
"ssh",
"connection",
"pymongo"
] |
Python 3 AttributeError even though attribute exists | 38,018,475 | <p>I have a set of python files which make up a program for saving tidbits of info and searching them via tag association. I had the program working for many versions, but I recently made what I thought was a minor change that caused the program to go haywire. The ENTRY object is the basis of the data storage - it hold... | 1 | 2016-06-24T16:51:57Z | 38,019,721 | <p>I figured out where I went wrong! My program is associated with a file called <code>myMemory.dat</code> which stores a pickled version of a <code>Memory</code> object and is loaded and saved with each run of the program. The <code>Memory</code> object is essentially a list of <code>ENTRY</code>s to be queried. At th... | 0 | 2016-06-24T18:14:43Z | [
"python",
"replace",
"attributes",
"find",
"attributeerror"
] |
Python Spark / Yarn memory usage | 38,018,477 | <p>I have a spark python application that is being killed by yarn for exceeding memory limits. I have a step that involves loading some resources that are a bit heavy (500+ MB), so I'm using mapPartitions. Basically:</p>
<pre><code>def process_and_output(partition):
resources = load_resources()
for record in p... | 9 | 2016-06-24T16:52:01Z | 38,117,248 | <p>As you see 11.2 GB is your max memory for a container created by yarn. It is equal to executor memory + overhead. So python memory is not counted for that. </p>
<p>Exception wants you to increase overhead but you can just increase executor-memory without increasing overheadmemory. Thats all i can say without knowin... | 3 | 2016-06-30T08:01:18Z | [
"python",
"hadoop",
"apache-spark",
"pyspark",
"yarn"
] |
Python Spark / Yarn memory usage | 38,018,477 | <p>I have a spark python application that is being killed by yarn for exceeding memory limits. I have a step that involves loading some resources that are a bit heavy (500+ MB), so I'm using mapPartitions. Basically:</p>
<pre><code>def process_and_output(partition):
resources = load_resources()
for record in p... | 9 | 2016-06-24T16:52:01Z | 38,122,923 | <p>Yarn kills executors when its </p>
<p><code>memory usage > (executor-memory + executor.memoryOverhead)</code> </p>
<p>From your setting it looks like it is a valid exception.</p>
<p><code>(memory usage)11.4GB > 11.18GB (executor-memory=6GB + memoryOverhead=5.18GB)</code></p>
<p>try with</p>
<p><code>--con... | 2 | 2016-06-30T12:20:08Z | [
"python",
"hadoop",
"apache-spark",
"pyspark",
"yarn"
] |
python 3.5 converting a list of bytes into ascii | 38,018,529 | <p>I have a list of words that is in bytes but I want to switch them into ascii. </p>
<p>What I'm trying to get:</p>
<pre><code>print(delimitednames)
['the\x00 ', 'tree\x00 ', 'grew\x00 ', 'tall\x00 ']
</code></pre>
<p>What I'm getting currently</p>
<pre><code>print(delimitednames)
[b'the\x00 ', b'tree\x00 ',... | 0 | 2016-06-24T16:55:15Z | 38,018,739 | <p>Use the str function instead in Python 3.x:</p>
<pre><code>delimitednames = [str(x,'ascii', 'ignore') for x in delimitednames]
</code></pre>
<p>Assuming you don't need the nullbytes and whitespaces, you can add .strip('\x00 ') to the string</p>
| 1 | 2016-06-24T17:07:48Z | [
"python",
"python-3.x",
"byte",
"ascii"
] |
SymPy: Evaluate given expression with given variables | 38,018,549 | <p>I have a sympy expression involving two variables <code>a</code>, <code>b</code>. I would now like to evaluate this expression for specific values of <code>a</code> and <code>b</code>. Using a <code>lambda</code> like</p>
<pre><code>import sympy
def get_expression(a, b):
# Complex function with a simple res... | 1 | 2016-06-24T16:56:17Z | 38,018,666 | <p>Turns out that <a href="http://docs.sympy.org/latest/modules/utilities/lambdify.html" rel="nofollow">lambdify</a> is what I need:</p>
<pre><code>f = sympy.lambdify([a, b], z)
print(f(1, 1))
</code></pre>
| 1 | 2016-06-24T17:02:23Z | [
"python",
"sympy"
] |
Creating a new user after extending Django user model | 38,018,697 | <p>Cant seem to find a response that clearly answers my question.</p>
<p>If you extend the Django user model with basic code like: </p>
<pre><code>class Employee(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
department = models.CharField(max_length=100)
</code></pre>
<p>How does ... | 1 | 2016-06-24T17:05:00Z | 38,018,883 | <p>The <code>employee</code> object is not created automatically. To create a <code>user</code> object and an <code>employee</code> object at the same time, you can use the <code>user</code> instance as such</p>
<pre><code>employee = Employee(user=user, depatment='xyz')
employee.save()
</code></pre>
| 1 | 2016-06-24T17:17:32Z | [
"python",
"django",
"python-3.x"
] |
Creating a new user after extending Django user model | 38,018,697 | <p>Cant seem to find a response that clearly answers my question.</p>
<p>If you extend the Django user model with basic code like: </p>
<pre><code>class Employee(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
department = models.CharField(max_length=100)
</code></pre>
<p>How does ... | 1 | 2016-06-24T17:05:00Z | 38,019,592 | <p>If you wish to create a employ instance at time or user creation you can use django signals which will create instance automatically when new user is created.</p>
<h1>models.py</h1>
<pre><code>from django.db.models.signals import *
from __future__ import unicode_literals
class Employee(models.Model):
userNam... | 4 | 2016-06-24T18:06:25Z | [
"python",
"django",
"python-3.x"
] |
Syntax Error 'break outside loop' | 38,018,714 | <p>Essentially, I'm trying to create a main function that can take input, and use that list of input to calculate the median, mode, and mean by using another function. I'm a novice coder (taking my first class) so any help that can point me in the right direction while still helping me learn will be greatly appreciated... | -2 | 2016-06-24T17:05:56Z | 38,018,898 | <p><code>break</code> and <code>continue</code> are to only be used in a loop such as <code>for</code> or <code>while</code></p>
<p>So your main () should have a while loop in it.</p>
<pre><code>def main():
yourlist = []
while True:
addons = input("Enter your list of number to be calculated(stop to st... | 1 | 2016-06-24T17:18:40Z | [
"python",
"function"
] |
Syntax Error 'break outside loop' | 38,018,714 | <p>Essentially, I'm trying to create a main function that can take input, and use that list of input to calculate the median, mode, and mean by using another function. I'm a novice coder (taking my first class) so any help that can point me in the right direction while still helping me learn will be greatly appreciated... | -2 | 2016-06-24T17:05:56Z | 38,019,106 | <p>Personal preference, but I would change your if statements to</p>
<pre><code>if 'stop' not in addons:
data.append(yourlist)
</code></pre>
<p>and the elif to</p>
<pre><code>elif not all(isinstance(number, float) for number in addons):
print("Bad input, try again")
</code></pre>
<p>This checks each inputte... | 0 | 2016-06-24T17:32:48Z | [
"python",
"function"
] |
Using type hints to translate Python to Cython | 38,018,780 | <p>Type Hints now are available in Python 3.5 version. In the specification (<a href="https://www.python.org/dev/peps/pep-0484/" rel="nofollow">PEP 484</a>) the goals (and the non-goals) are exposed clearly:</p>
<blockquote>
<h1>Rationale and Goals</h1>
<blockquote>
<p>This PEP aims to provide a standard sy... | 2 | 2016-06-24T17:10:29Z | 38,020,086 | <p>Someone else just asked about 484 and Cython, <a href="http://stackoverflow.com/questions/38005633/pep-484-type-annotations-with-own-types">PEP-484 Type Annotations with own types</a>, and I responded with a thread from a couple of months back about 484 and numpy. </p>
<p>I have doubts about the suitability of thi... | 1 | 2016-06-24T18:40:08Z | [
"python",
"optimization",
"cython",
"type-hinting"
] |
Staying on same tab after a form is submitted in django and angular | 38,018,876 | <p>I've got a <code>boards.html</code> page and on that page I have 3 tabs (written with angular); Your Boards, Join Board, and Create Board. Under the Join Board tab there is a join board button (which is a django function) that, when clicked, reloads the page so it goes back to the default Your Boards tab, I want it... | 2 | 2016-06-24T17:17:17Z | 38,326,171 | <p>Your whole page is reloading. That means you lose all the information you had on the page unless you store it somewhere. If you want to stay with Django forms I'd recommend adding query params to your angular routing, so that you can jump straight there when the page is loaded.</p>
<p>You're url would looks like <c... | 1 | 2016-07-12T10:24:26Z | [
"python",
"angularjs",
"django"
] |
Pandas parse date and set index- weird behavior | 38,018,877 | <p>I am experiencing some odd behavior when I try to both parse a date column and set that column as the index while reading from a CSV with pandas.</p>
<p>The csv file has both a throw-away header and a throw-away index column like below (by throw-away I mean I don't want to use them)</p>
<pre><code>"","X.m..d..y","... | 0 | 2016-06-24T17:17:18Z | 38,021,768 | <p>The strategy with <code>index_col=0</code> works for me (Python 3.5.1, pandas 0.18.1). There was a bug that showed up when using both <code>parse_dates</code> and <code>usecols</code> that has been fixed in 0.18.1 (<a href="https://github.com/pydata/pandas/commit/c6c201e27c7ed57a823ec7261340dfeec1e0226a" rel="nofoll... | 1 | 2016-06-24T20:39:57Z | [
"python",
"pandas",
"io",
"date-parsing"
] |
Labelled datatypes Python | 38,018,888 | <p>I am computing geodesic distances between a point and multiple line segments. Each line segment has a unique identifying number. I want to return distances from my distances function such that they are both intrinsically tied together. I would also like to maintain functionality, as in sort the distances, and index ... | 0 | 2016-06-24T17:17:47Z | 38,019,548 | <p>So, I think a data-frame whose index is the labels is probably the simplest</p>
<pre><code>distances = {25622 : 296780.2217658355,
25621 : 296572.4476883276,
25620 : 296364.21166884096,
25619 : 296156.4366241771,
25618 : 295948.6610171968}
df = pd.DataFrame([tup for tup in distances.items()],columns=["label", ... | 0 | 2016-06-24T18:03:53Z | [
"python",
"numpy",
"pandas"
] |
Labelled datatypes Python | 38,018,888 | <p>I am computing geodesic distances between a point and multiple line segments. Each line segment has a unique identifying number. I want to return distances from my distances function such that they are both intrinsically tied together. I would also like to maintain functionality, as in sort the distances, and index ... | 0 | 2016-06-24T17:17:47Z | 38,021,492 | <p>So I think your overall problem is you are creating a <code>DataFrame</code> where the column label is the <code>intercept</code> value. I think what you want to do is create a <code>DataFrame</code> where one column contains the intercept values, while another contains the distances. I will try to give you code t... | 1 | 2016-06-24T20:20:05Z | [
"python",
"numpy",
"pandas"
] |
Labelled datatypes Python | 38,018,888 | <p>I am computing geodesic distances between a point and multiple line segments. Each line segment has a unique identifying number. I want to return distances from my distances function such that they are both intrinsically tied together. I would also like to maintain functionality, as in sort the distances, and index ... | 0 | 2016-06-24T17:17:47Z | 38,023,443 | <p>After everything, and after trying to make TheBlackCat's answer work for about 3 hours, I have decided to use <a href="http://xarray.pydata.org/en/stable/" rel="nofollow">xarray</a>. So now the <code>pointer</code> function looks like this:</p>
<pre><code>def pointer(point, centroid, tree_idx):
intersect = list... | 0 | 2016-06-24T23:26:05Z | [
"python",
"numpy",
"pandas"
] |
Why can I not always import pandas | 38,018,921 | <p>I've done the following:</p>
<pre><code>conda install pandas
</code></pre>
<p>If I open iPython notebook and import like this everything is happy:</p>
<pre><code>import pandas
</code></pre>
<p>If I open cmd and type <code>python</code> I get the following:</p>
<pre><code>Python 3.5.1 (v3.5.1:37a07cee5969, Dec ... | 0 | 2016-06-24T17:20:21Z | 38,019,123 | <p>You have several instances of Python on your host machine. The one you launch with Anaconda has <code>pandas</code> installed but the default python does not.</p>
<p>You need to install <code>pandas</code> on your default version of python. You can do this in Windows with the following command:</p>
<pre><code>py... | 1 | 2016-06-24T17:33:56Z | [
"python",
"windows",
"pandas",
"ipython"
] |
Why can I not always import pandas | 38,018,921 | <p>I've done the following:</p>
<pre><code>conda install pandas
</code></pre>
<p>If I open iPython notebook and import like this everything is happy:</p>
<pre><code>import pandas
</code></pre>
<p>If I open cmd and type <code>python</code> I get the following:</p>
<pre><code>Python 3.5.1 (v3.5.1:37a07cee5969, Dec ... | 0 | 2016-06-24T17:20:21Z | 38,019,143 | <p>Step 1: Start ipython and find the path of the executable that it is using:</p>
<pre><code>$ ipython
In [1]: import sys
In [2]: print(sys.executable)
/home/anaconda3/bin/python3
</code></pre>
<p>Step 2: Do the same with your python</p>
<pre><code>$ python
>>> import sys
>>> print(sys.executable)... | 2 | 2016-06-24T17:35:48Z | [
"python",
"windows",
"pandas",
"ipython"
] |
Why can I not always import pandas | 38,018,921 | <p>I've done the following:</p>
<pre><code>conda install pandas
</code></pre>
<p>If I open iPython notebook and import like this everything is happy:</p>
<pre><code>import pandas
</code></pre>
<p>If I open cmd and type <code>python</code> I get the following:</p>
<pre><code>Python 3.5.1 (v3.5.1:37a07cee5969, Dec ... | 0 | 2016-06-24T17:20:21Z | 38,054,289 | <p>The suggested answers let to the solution. This was my original <code>PATH env variable</code>:</p>
<p><a href="http://i.stack.imgur.com/rklQ0.png" rel="nofollow"><img src="http://i.stack.imgur.com/rklQ0.png" alt="enter image description here"></a> </p>
<p>Even though Anaconda features in the above, and it is high... | 0 | 2016-06-27T12:42:20Z | [
"python",
"windows",
"pandas",
"ipython"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.