title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
Delete line in file | 38,437,619 | <p>I wanna show the lines in a file, let the user decide which line should be deleted and then write all lines back to the file, except the one the user wants to delete. </p>
<p>This is what I tried so far, but I'm kinda stuck.</p>
<pre><code>def delete_result():
text_file = open('minigolf.txt', 'r')
zork = 0... | 3 | 2016-07-18T13:11:44Z | 38,438,822 | <p>All other answers are valid so you probably got a good idea on how to do it by loading the file, changing the content and then saving the file back.</p>
<p>I just want to point out that there is a possibility of changing the content of the file directly in storage memory. It is not always wise to do so, the thing h... | 2 | 2016-07-18T14:06:17Z | [
"python"
] |
Issue by deleting an item from a list | 38,437,631 | <p>I have this script:</p>
<pre><code>import urllib.request, re
sourcecode = urllib.request.urlopen("https://www.inforge.net/xi/threads/dichvusocks-us-15h10-pm-update-24-24-good-socks.455588/")
sourcecode = str(sourcecode.read())
out_file = open("proxy.txt","w")
out_file.write(sourcecode)
out_file.close()
with open... | 2 | 2016-07-18T13:12:07Z | 38,439,372 | <p>Because you assign <code>ip[-1]</code> to an empty list. If you need to strip the first three and last entry in the <code>ip</code> list, do it with slicing like this:</p>
<pre><code>ip = ip[3:-1]
</code></pre>
<p>This will start from the entry <code>3</code> and go up until the second from last.</p>
| 2 | 2016-07-18T14:32:48Z | [
"python",
"list",
"python-3.x"
] |
Does time.sleep help the processor? | 38,437,670 | <p>Recently I was surfing on Stack Overflow (Python) and saw <a href="http://stackoverflow.com/a/18406512/6063416">this post</a> where Aaron Hall claims that </p>
<blockquote>
<p>constantly running while loops can consume a lot of processing power. Adding a sleep period (even only a second) can greatly reduce that u... | 7 | 2016-07-18T13:14:14Z | 38,440,489 | <p>TL;DR If you are polling for an event that happens once a minute, you might want to not check every nano second.</p>
<p>Yes, it is really true. Sleeping in a thread does reduce the CPU usage of that thread. While a thread sleeps, it hardly consumes any CPU time.</p>
<p>Yes, this is true for largely any language as... | 5 | 2016-07-18T15:22:02Z | [
"python",
"c++"
] |
Xpath - get text separated by <p> tags | 38,437,680 | <p>I can't figure out how to get formatted text using xpath from tag which contain's many <code><span></code> tag's and <code><p></code> tag's. </p>
<p>It's in this form:</p>
<pre><code><span>This</span>
<span> is</span>
<span> main</span>
<span> text</span>... | 0 | 2016-07-18T13:15:03Z | 38,439,288 | <p>I'm not sure which Python library you are using (xml.etree?). But concering the XPath try <code>'.//div[@class="description"]//*'</code>. That will select all subelements beginnen at the <code>div</code>. </p>
<p>Using xml.etree it would look like this (assuming the HTML source code is given as a string):</p>
<pre... | -1 | 2016-07-18T14:28:59Z | [
"python",
"xpath",
"web-scraping"
] |
how to put a login form using django | 38,437,727 | <p>After hours and hours of trying, i still cannot seem to make it happen.</p>
<p>basically Im trying to put a login form inside this .post_list.html using django along with the postform. (so there are 2 forms)</p>
<p>this is the views.py</p>
<pre><code>from django.contrib import messages
from django.http import Htt... | 0 | 2016-07-18T13:16:37Z | 38,438,649 | <p>My guess is you got this issue because of naming.
You passing into context the following things:</p>
<pre><code>form = AuthenticationForm()
postform = PostForm(request.POST or None)
...
context = {
"object_list": queryset,
"title": "List",
"form": postform,
"form2":... | 1 | 2016-07-18T13:58:06Z | [
"python",
"django"
] |
Preserve changes in multiple function when testing a Flask app | 38,437,820 | <p>I'm following a talk on Flask about creating an API. I want to write some tests for it. Upon testing creating a resource does testing deleting the resource in another function work? How do I make the creation of a resource persist to be tested for deletion and editing?</p>
<p><a href="https://www.youtube.com/wat... | 0 | 2016-07-18T13:20:27Z | 38,439,151 | <p>You're testing the wrong thing. You <em>can</em> persist changes to a database, simply by committing it, when you run a test, but you really don't want to do that.</p>
<p>With unit testing you're testing simple units. With integration testing, which is what you're talking about here, you <em>still</em> want each te... | 3 | 2016-07-18T14:22:16Z | [
"python",
"testing",
"flask",
"py.test"
] |
OnevsrestClassifier and random forest | 38,437,845 | <p>I am trying to reproduce the example at <a href="http://scikit-learn.org/stable/auto_examples/model_selection/plot_roc.html" rel="nofollow">http://scikit-learn.org/stable/auto_examples/model_selection/plot_roc.html</a> but using RandomForestClassifer.</p>
<p>I can't see how to transform this part of the code</p>
<... | -1 | 2016-07-18T13:22:04Z | 38,438,055 | <p>Well you should know what is <code>decision_function</code> used for. Its only used with a SVM classifier reason being it gives out the distance of your data points from the hyperplane that separates the data, whereas when you do it using a <code>RandomForestClassifier</code> it makes no sense. You can use other met... | 3 | 2016-07-18T13:30:56Z | [
"python",
"scikit-learn"
] |
Pandas split name column into first and last name if contains one space | 38,437,847 | <p>Let's say I have a pandas DataFrame containing names like so:</p>
<p><code>name_df = pd.DataFrame({'name':['Jack Fine','Kim Q. Danger','Jane Smith', 'Juan de la Cruz']})</code></p>
<pre><code> name
0 Jack Fine
1 Kim Q. Danger
2 Jane Smith
3 Juan de la Cruz
</code></pre>
<p>and I want to split the <code... | 1 | 2016-07-18T13:22:13Z | 38,437,887 | <p>You can use <code>str.split</code> to split the strings, then test the number of splits using <code>str.len</code> and use this as a boolean mask to assign just those rows with the last component of the split:</p>
<pre><code>In [33]:
df.loc[df['name'].str.split().str.len() == 2, 'last name'] = df['name'].str.split(... | 1 | 2016-07-18T13:24:09Z | [
"python",
"pandas"
] |
How can I use django to realize real time? | 38,437,967 | <p>I have a rethinkdb. Data will get in database for every five minutes.
I want to create a website to real-time inspect this data flow from rethinkdb.
That is, when surfing the webpage, the data from db on webpages can update automatically without refreshing the webpage.
I know there are several ways to make it real-t... | 1 | 2016-07-18T13:26:56Z | 38,443,267 | <p>If you make your question more specific, the community here will be able to offer you better support.</p>
<p>However, here is a general solution to your problem.</p>
<p>You will need to do two things:</p>
<ol>
<li><p><strong>Create a backend API</strong> that allows you to:</p>
<ul>
<li>Check if new data has bee... | 1 | 2016-07-18T18:06:16Z | [
"python",
"django",
"websocket",
"real-time",
"rethinkdb"
] |
Python tkinter: Continuously updating labels in frame | 38,438,106 | <p>In my code I have a spin box that the user uses to select the number of teams they want, then in a separate frame columns are created to match the number of teams they chose, and when they use the spin box to change this value it also changes the number of columns</p>
<pre><code>frame=Frame(root)
frame.pack(anchor=... | 0 | 2016-07-18T13:33:19Z | 38,438,925 | <p>You can use the <code>command</code> argument to specify a method to be run whenever your spinbox changes values. I'm not entirely sure what type of columns you mean, but hopefully you can work with this.</p>
<pre><code>from Tkinter import *
def on_spin():
num_teams.set("New text")
root = Tk()
frame = Frame(... | 1 | 2016-07-18T14:10:59Z | [
"python",
"tkinter"
] |
Call resolution order in Python with multiple inheritance | 38,438,108 | <p>I was watching a Python talk at <a href="https://youtu.be/EiOglTERPEo?t=1147" rel="nofollow">Youtube</a> and found an interesting language feature. However when I tried to run a test code it didn't work and I'd like to understand why.</p>
<p>I was expecting this to print this:</p>
<pre><code>Parent
OtherParent
</c... | 0 | 2016-07-18T13:33:29Z | 38,438,264 | <p>Ah my friend pointed out to a small deviation from the example on Youtube:</p>
<pre><code>class Parent:
def get_message(self):
return "Parent"
class Child(Parent):
def do_print(self):
print(super().get_message())
class OtherParent(Parent): # <----- Inheritance of Parent makes it work
... | -2 | 2016-07-18T13:40:21Z | [
"python",
"multiple-inheritance"
] |
Call resolution order in Python with multiple inheritance | 38,438,108 | <p>I was watching a Python talk at <a href="https://youtu.be/EiOglTERPEo?t=1147" rel="nofollow">Youtube</a> and found an interesting language feature. However when I tried to run a test code it didn't work and I'd like to understand why.</p>
<p>I was expecting this to print this:</p>
<pre><code>Parent
OtherParent
</c... | 0 | 2016-07-18T13:33:29Z | 38,438,537 | <p>The correct explanation is mentioned in the comments of the question, ie from MRO of the <code>OtherChild</code> class (link posted in the comment: <a href="http://stackoverflow.com/questions/10018757/how-does-the-order-of-mixins-affect-the-derived-class/10018792#10018792">How does the order of mixins affect the der... | 1 | 2016-07-18T13:52:46Z | [
"python",
"multiple-inheritance"
] |
Unique validation on nested serializer on Django Rest Framework | 38,438,167 | <p>I have a case like this, where you have a custom nested serializer relation with a unique field. Sample case:</p>
<pre><code>class GenreSerializer(serializers.ModelSerializer):
class Meta:
fields = ('name',) #This field is unique
model = Genre
class BookSerializer(serializers.ModelSerializer):... | 1 | 2016-07-18T13:36:42Z | 38,438,394 | <p>You should drop the unique validator for the nested serializer:</p>
<pre><code>class GenreSerializer(serializers.ModelSerializer):
class Meta:
fields = ('name',) #This field is unique
model = Genre
extra_kwargs = {
'name': {'validators': []},
}
</code></pre>
<p>You ... | 3 | 2016-07-18T13:46:22Z | [
"python",
"django",
"rest",
"django-rest-framework",
"django-serializer"
] |
Django nose giving "ImportError: cannot import name setup"? | 38,438,170 | <p>Django-nose installed in virtualenv is giving "ImportError: cannot import name setup" in runner.py when I run default server. On doing traceback I get this:</p>
<pre><code>File "/home/sid/.virtualenvs/workbench/local/lib/python2.7/site-packages/django/core/management/base.py", line 222, in run_from_argv
self.ex... | 2 | 2016-07-18T13:36:44Z | 38,439,955 | <p>Django 1.5 hasn't been supported for quite a while now, and django-nose has dropped compatibility in their more recent versions. <code>django.setup()</code> was added in Django 1.7. </p>
<p>You need to upgrade Django or downgrade django-nose to a compatible version. I would recommend to upgrade Django to a <a href=... | 5 | 2016-07-18T14:58:06Z | [
"python",
"django",
"django-nose"
] |
Arrangement of pie charts using matplotlib subplot | 38,438,220 | <p>I have 7 pi-charts (4 are listed below). I am trying to create a dashboard with 4 pie charts in first row and 3 pie charts in second row. Not sure where I am going wrong with the below code. Are there any other alternatives to achieve this? Any help would be appreciated.</p>
<pre><code>from matplotlib import pyplot... | 1 | 2016-07-18T13:38:40Z | 38,438,533 | <p>A better method which I always use and is more intuitive, at-least for me, is to use <code>subplot2grid</code>....</p>
<pre><code>fig = plt.figure(figsize=(18,10), dpi=1600)
#this line will produce a figure which has 2 row
#and 4 columns
#(0, 0) specifies the left upper coordinate of your plot
ax1 = plt.subplot2g... | 1 | 2016-07-18T13:52:33Z | [
"python",
"matplotlib",
"subplot"
] |
Picking Values from a List to Update Dictionary | 38,438,385 | <p>My scenario is like this:</p>
<pre><code>pic_from_list = ['best', 'good', 'ok']
dict_list = [{id = "1", food_source : "this food;is;good"}, {id = "2", food_source : "this food;is;ok"}, {id = "3", food_source : "this food is the best"}, {id = "4", food_source : none}, {id = "5", food_source : "no source"}]
</code></... | -4 | 2016-07-18T13:46:00Z | 38,449,397 | <p>I have fixed this issue. Apparently, i was defining the dictionary outside the loop ! So each time, the code make a loop the dictionary is getting overwritten with no change in the key, but only value. When I defined the dictionary within the loop, it gets started afresh as an empty dictionary, and then the key and ... | 0 | 2016-07-19T04:02:05Z | [
"python",
"dictionary"
] |
Average of each day over multiple years | 38,438,397 | <p>Quick Q:</p>
<p>Have a dataset: That is a measurment per day over several years.
Trying to work out the average of all the same dates. i.e the average of 01/01/1995 and 01/01/1996 and 01/01/1997 etc.</p>
<p>Tried this: </p>
<pre><code>z=df.groupby(df.index.day,df.index.month).mean()
</code></pre>
<p>But get:</p... | 1 | 2016-07-18T13:46:40Z | 38,438,426 | <p>IIUC you need to pass a list:</p>
<pre><code>z=df.groupby([df.index.day,df.index.month]).mean()
</code></pre>
<p>What you did was pass multiple args so it interpreted the months array as an arg for <code>axis</code>, see the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.ht... | 2 | 2016-07-18T13:48:02Z | [
"python",
"numpy",
"pandas"
] |
Groupby and Cumulative count in Pandas | 38,438,432 | <p>I want to group by two columns and get their cumulative count. I tried looking for relevant code in the group ,couldn't find it, but got few hints based on what I have coded, but it is ending up with an error. Can this be solved?</p>
<pre><code>ID ABC XYZ
1 A .512
2 A .123
3 B .999
4 B .999... | 2 | 2016-07-18T13:48:13Z | 38,438,997 | <p>I got the desired results like this.</p>
<pre><code>c1 = df.ABC != DF.ABC.shift()
c2 = df.XYZ != DF.XYZ.shift()
DF['GID'] = (c1 | c2).cumsum()
DF
</code></pre>
<p><a href="http://i.stack.imgur.com/TmnLj.png" rel="nofollow"><img src="http://i.stack.imgur.com/TmnLj.png" alt="enter image description here"></a></p>
| 2 | 2016-07-18T14:14:34Z | [
"python",
"python-2.7",
"pandas"
] |
how to run a scrapy crawler from another folder in Debian | 38,438,517 | <p>I use <strong>Python Scrapy</strong> in <strong>Debian</strong>, i have a PHP script for run my spider.
my php script is in the projectâs top level directory </p>
<pre><code><?php
$cp = $argv[1];
shell_exec('scrapy crawl mySpider -a idcrawl="'.$cp.'" ');
?>
</code></pre>
<p>but i just can run it when i... | 1 | 2016-07-18T13:52:02Z | 38,440,030 | <p>I should use <code>chdir</code> to change my directory and go to top level directory.</p>
| 0 | 2016-07-18T15:01:23Z | [
"python",
"web-scraping",
"scrapy",
"web-crawler"
] |
FindContours support only 8uC1 and 32sC1 images | 38,438,646 | <p>i hava problem in fire detection
my code is : </p>
<pre><code>ret, frame = cap.read()
lab_image = cv2.cvtColor(frame, cv2.COLOR_BGR2LAB)
L , a , b = cv2.split(lab_image)
ret,thresh_L = cv2.threshold(L,70,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)
ret,thresh_a = cv2.threshold(a,70,255,cv2.THRESH_BINARY_INV+cv2.THRE... | 0 | 2016-07-18T13:58:01Z | 38,440,016 | <p>The documention of <code>findContours</code> is clearly saying that it can afford to take single channel images as inputs(i.e 8uc1 and 32sc1) But you are sending 3 channel image.here is the documentation of findcontours <a href="http://docs.opencv.org/2.4/modules/imgproc/doc/structural_analysis_and_shape_descriptors... | 0 | 2016-07-18T15:00:48Z | [
"python",
"opencv"
] |
FindContours support only 8uC1 and 32sC1 images | 38,438,646 | <p>i hava problem in fire detection
my code is : </p>
<pre><code>ret, frame = cap.read()
lab_image = cv2.cvtColor(frame, cv2.COLOR_BGR2LAB)
L , a , b = cv2.split(lab_image)
ret,thresh_L = cv2.threshold(L,70,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)
ret,thresh_a = cv2.threshold(a,70,255,cv2.THRESH_BINARY_INV+cv2.THRE... | 0 | 2016-07-18T13:58:01Z | 38,446,031 | <pre><code>cv2.cvtColor(cv2.COLOR_BGR2GRAY);
</code></pre>
<p>Use this line on the Mat you wish to find contours on and it should work, because it will convert your image to 8UC1 format (grayscale).</p>
| 0 | 2016-07-18T21:09:44Z | [
"python",
"opencv"
] |
"Sorted" function doesn't work in Python task | 38,438,719 | <p>Here's my code:</p>
<pre><code>def Descending_Order(num):
return int(''.join(sorted(str(num).split(), reverse = True)))
print Descending_Order(0)
print Descending_Order(15)
print Descending_Order(123456789)
</code></pre>
<p>"num" is supposed to be printed in descending order, but the code doesn't work, althoug... | -3 | 2016-07-18T14:01:03Z | 38,438,788 | <p>The <code>split</code> is superfluous, redundant and the cause of your problem. The <a href="https://docs.python.org/2/library/stdtypes.html#str.split" rel="nofollow">split</a> method of a string requires a delimiter which in your case there is none so defaults to consecutive whitespace. As your string does not have... | 2 | 2016-07-18T14:04:48Z | [
"python"
] |
"Sorted" function doesn't work in Python task | 38,438,719 | <p>Here's my code:</p>
<pre><code>def Descending_Order(num):
return int(''.join(sorted(str(num).split(), reverse = True)))
print Descending_Order(0)
print Descending_Order(15)
print Descending_Order(123456789)
</code></pre>
<p>"num" is supposed to be printed in descending order, but the code doesn't work, althoug... | -3 | 2016-07-18T14:01:03Z | 38,439,066 | <p>You can also split the numbers using <a href="https://docs.python.org/2/library/functions.html#list" rel="nofollow"><code>list</code></a>, then sort the list that way:</p>
<pre><code>def Descending_Order(num):
digits = [digit for digit in list(str(num))]
return int("".join(sorted(digits, reverse = True)))... | 0 | 2016-07-18T14:18:20Z | [
"python"
] |
Number of vehicles each T seconds | 38,438,773 | <p>I wrote the script below with python and i implemented it on sumo,in order to obtain the number of vehicles between two inductionLoop,every 60 seconds,in a lane.
But this one gives each second .</p>
<pre><code> #!/usr/bin/env python
# -*-coding:Latin-1 -*
import os, sys
import optparse
import subpr... | 0 | 2016-07-18T14:03:50Z | 38,446,227 | <p>You probably want to have have the value every 60 simulation seconds not every 60 wallclock seconds, so a timer is pointless here. Simply ask for the value after 60 simulation steps (assuming you use sumo's default step length of one second). So you could write something like:</p>
<pre><code> if step % 60 == 0:... | 0 | 2016-07-18T21:23:06Z | [
"python",
"sumo"
] |
elementwise multiplication between two dataframes | 38,438,901 | <pre><code>data = [['aaa', 1, 110, 2, 0],
['bbb', 0, 123, 10, 11],
['ccc', 0, 134, 1, 2],
['ddd', 1, 333, 2, 3],
['eee', 1, 444, 2, 0]]
data2 = [['Average', 0.1, 0.2, 0.3],
['Mean', 0.5, 0.5, 0.5],
['denom', 0.3, 0.35, 0.4]]
df1 = pd.DataFrame(data=data, columns=['use... | 2 | 2016-07-18T14:09:56Z | 38,439,021 | <p>Well that's basically a dot-product. So, one way would be -</p>
<pre><code>df1[df2.columns].dot(df2.loc['denom'])
</code></pre>
<p>Sample run -</p>
<pre><code>In [55]: df1
Out[55]:
A A1 B C
user
aaa 1 110 2 0
bbb 0 123 10 11
ccc 0 134 1 2
ddd 1 333 2 3
eee ... | 3 | 2016-07-18T14:16:03Z | [
"python",
"pandas",
"dataframe"
] |
elementwise multiplication between two dataframes | 38,438,901 | <pre><code>data = [['aaa', 1, 110, 2, 0],
['bbb', 0, 123, 10, 11],
['ccc', 0, 134, 1, 2],
['ddd', 1, 333, 2, 3],
['eee', 1, 444, 2, 0]]
data2 = [['Average', 0.1, 0.2, 0.3],
['Mean', 0.5, 0.5, 0.5],
['denom', 0.3, 0.35, 0.4]]
df1 = pd.DataFrame(data=data, columns=['use... | 2 | 2016-07-18T14:09:56Z | 38,439,061 | <p>By default, multiplying a series (<code>df2.loc['denom']</code>) with a DataFrame (<code>df1</code>) will match the series elements to the columns, so do what you want:</p>
<pre><code>In [74]: df1 * df2.loc['denom']
Out[74]:
A A1 B C
user
aaa 0.3 NaN 0.70 0.0
bbb 0.0 NaN 3.50 4.4
ccc 0.0 N... | 3 | 2016-07-18T14:18:13Z | [
"python",
"pandas",
"dataframe"
] |
In Python, can I use the value of a global variable in a method at the time of it's definition, but not change when that variable is changed? | 38,439,026 | <p>It's difficult to describe the behavior that I need, so I'll give an example. When running the following code, <code>f()</code> prints <code>"eggs"</code>, but I would like a way to make <code>f()</code> print <code>"spam"</code>, which is the value of <code>x</code> at the time of <code>f</code>'s declaration.</p>... | 0 | 2016-07-18T14:16:20Z | 38,439,090 | <p>Then bind <code>x</code> to <code>f</code> as soon as <code>f</code> is defined:</p>
<pre><code>x = "spam"
def f(x=x):
print(x)
x = "eggs"
f()
# spam
</code></pre>
<p>Probably not a good idea though.</p>
| 3 | 2016-07-18T14:19:45Z | [
"python",
"python-3.x",
"methods",
"global-variables"
] |
In Python, can I use the value of a global variable in a method at the time of it's definition, but not change when that variable is changed? | 38,439,026 | <p>It's difficult to describe the behavior that I need, so I'll give an example. When running the following code, <code>f()</code> prints <code>"eggs"</code>, but I would like a way to make <code>f()</code> print <code>"spam"</code>, which is the value of <code>x</code> at the time of <code>f</code>'s declaration.</p>... | 0 | 2016-07-18T14:16:20Z | 38,439,852 | <p>Moses Koledoye's answer is sufficient, but through experimentation I have found that the following also works in Python 3:</p>
<pre><code>from functools import partial
x = "spam"
f = partial(print, x)
x = "eggs"
f()
</code></pre>
<p>I'm just making note of this because it always helps to have options</p>
| 0 | 2016-07-18T14:52:50Z | [
"python",
"python-3.x",
"methods",
"global-variables"
] |
In Python, can I use the value of a global variable in a method at the time of it's definition, but not change when that variable is changed? | 38,439,026 | <p>It's difficult to describe the behavior that I need, so I'll give an example. When running the following code, <code>f()</code> prints <code>"eggs"</code>, but I would like a way to make <code>f()</code> print <code>"spam"</code>, which is the value of <code>x</code> at the time of <code>f</code>'s declaration.</p>... | 0 | 2016-07-18T14:16:20Z | 38,440,558 | <p>You can also simply just call the function before you set x equal to spam, like this: </p>
<pre><code>x = 'spam'
def f():
print(x)
f()
x = "eggs"
</code></pre>
<p>The output for that would be 'spam' since you are calling the function before you are setting x equal to "eggs". Hope this helped</p>
| 0 | 2016-07-18T15:25:31Z | [
"python",
"python-3.x",
"methods",
"global-variables"
] |
python pandas merge/vlookup tables | 38,439,070 | <p>I was writing the Python code below to merge two tables, which could be done in Excel using Vlookup, but wanted to automate this process for a larger data set. However, it seems the output data is too big and contains all columns from both tables. I just wanted to use the second table, df_pos to lookup some columns.... | 0 | 2016-07-18T14:18:25Z | 38,439,385 | <p>You didn't provide us with enough information. You are outputting the merged dataframe but you have not told up which columns are necessary in the output. Ideally, you'd want to keep only the columns that are needed in the output plus the columns needed for the merge.</p>
<p>You can limit the columns that you imp... | 0 | 2016-07-18T14:33:06Z | [
"python",
"csv",
"pandas",
"merge",
"lookup"
] |
python pandas merge/vlookup tables | 38,439,070 | <p>I was writing the Python code below to merge two tables, which could be done in Excel using Vlookup, but wanted to automate this process for a larger data set. However, it seems the output data is too big and contains all columns from both tables. I just wanted to use the second table, df_pos to lookup some columns.... | 0 | 2016-07-18T14:18:25Z | 38,439,604 | <p>If you are just using <code>df_pos</code> to lookup data from another matrix, just use the field in <code>df_pos</code> as an index to the frame you're looking up data from, i.e. datasourcematrix[df_pos.LOOKUPCOLUMNNAME] or if you don't have a column name, you can do datasourcematrix[df_pos.ix[5]] or whatever. Much... | 0 | 2016-07-18T14:42:20Z | [
"python",
"csv",
"pandas",
"merge",
"lookup"
] |
Is there a way to directly "decorate" a block of Python code? | 38,439,105 | <p>I have a bunch of code:</p>
<pre><code>statement1(args)
statement2(args)
statement3(args)
statement4(args)
statement5(args)
</code></pre>
<p>I want to divide the statements into blocks and write to a log after each block. The logging is a bit complex: I want to log things like the running time of each block and t... | 1 | 2016-07-18T14:20:21Z | 38,439,190 | <p><a href="https://docs.python.org/3/reference/datamodel.html#context-managers" rel="nofollow">Context managers</a> are exactly what you are looking for. You use them with the <code>with</code> statement, and they define code to be run on entering and exiting the with block.</p>
| 2 | 2016-07-18T14:23:29Z | [
"python",
"python-decorators"
] |
Function return discarding changes | 38,439,205 | <p>So I have a file, <code>main.py</code>. The contents are such:</p>
<pre><code>var = 0
def func():
var = 1
def pr():
func()
print(var)
pr()
</code></pre>
<p>When run, this prints out <code>0</code> instead of my expected <code>1</code>. Why and how can I get the changes in <code>func()</code> to stic... | 0 | 2016-07-18T14:24:22Z | 38,439,225 | <p>You do it like this by refering to var as a global in func():</p>
<pre><code>var = 0
def func():
global var
var = 1
def pr():
func()
print(var)
pr()
</code></pre>
| 2 | 2016-07-18T14:25:17Z | [
"python"
] |
Download Jasper report using Python-requests library | 38,439,344 | <p>I'm using jasper server report API(rest_v2). </p>
<p>executed below api to generate reports and get requestsID and exportID.</p>
<p><a href="http://localhost:8080/jasperserver/rest_v2/reportExecutions" rel="nofollow">http://localhost:8080/jasperserver/rest_v2/reportExecutions</a></p>
<pre><code>{
"status": "rea... | 2 | 2016-07-18T14:31:11Z | 38,453,085 | <p>Ok. I solved it by passing cookies</p>
<pre><code>report_resp = requests.get(report_url, headers=headers, cookies=response.cookies)
</code></pre>
| 2 | 2016-07-19T08:23:11Z | [
"python",
"python-requests",
"jasperserver"
] |
Python - Remove Single Quotes From List Items When Adding To Dictionary | 38,439,424 | <p>I have tried all the recommendations on similar posts, but have had no luck. I have a list of items that I'm using to create values for a list of dictionaries. That list ultimately becomes a JSON object, so I can't have the single quotes around each list item that I add to it.</p>
<pre><code>metrics = ["test_met_1"... | 0 | 2016-07-18T14:34:44Z | 38,439,963 | <p>Once you have resultant dictionary, convert it to json object using json.dumps(yourdict)</p>
<p>Don't forget import json</p>
<p>Make sure your dictionary is a good.</p>
| 0 | 2016-07-18T14:58:27Z | [
"python",
"list",
"dictionary",
"single-quotes"
] |
Python - Remove Single Quotes From List Items When Adding To Dictionary | 38,439,424 | <p>I have tried all the recommendations on similar posts, but have had no luck. I have a list of items that I'm using to create values for a list of dictionaries. That list ultimately becomes a JSON object, so I can't have the single quotes around each list item that I add to it.</p>
<pre><code>metrics = ["test_met_1"... | 0 | 2016-07-18T14:34:44Z | 38,440,099 | <p>If you want to create a JSON string (or file), use the <a href="https://docs.python.org/3/library/json.html" rel="nofollow"><code>json</code></a> module.</p>
<pre><code>>>> data["reportDescription"]["metrics"] = [{"id": m} for m in metrics]
>>> json.dumps(data)
'{"reportDescription": {"metrics": [... | 1 | 2016-07-18T15:04:58Z | [
"python",
"list",
"dictionary",
"single-quotes"
] |
Set a Subdirectory's File's Working Path Relative to A Parent Directory in Python | 38,439,493 | <p>I have a project folder, <code>PythonProject</code>.
Within that Project folder I have a 2 subdirectories: <code>SubDirectory</code> & <code>DataSubDirectory</code>.</p>
<p>Within SubDirectory, I have a python file, TestFile.py which opens an external file, datafile.txt, contained in DataSubDirectory. </p>
<p... | 0 | 2016-07-18T14:36:53Z | 38,439,753 | <p>If you are running from Project folder, set a variable(PRJ_PATH) to os.getcwd() and use it for opening the file like open(os.path.join(PRJ_PATH, 'data', 'data.txt'))</p>
<p>If you are running from subdirectories, set a variable(PRJ_PATH) to os.path.join(os.getcwd(), '..') and then use it for opening the file like o... | 1 | 2016-07-18T14:48:49Z | [
"python",
"filepath"
] |
Set a Subdirectory's File's Working Path Relative to A Parent Directory in Python | 38,439,493 | <p>I have a project folder, <code>PythonProject</code>.
Within that Project folder I have a 2 subdirectories: <code>SubDirectory</code> & <code>DataSubDirectory</code>.</p>
<p>Within SubDirectory, I have a python file, TestFile.py which opens an external file, datafile.txt, contained in DataSubDirectory. </p>
<p... | 0 | 2016-07-18T14:36:53Z | 38,439,755 | <p>You can use <code>PythonProject = os.path.dirname(os.path.realpath(sys.argv[0]))</code> to set the PythonProject Path</p>
| 0 | 2016-07-18T14:48:52Z | [
"python",
"filepath"
] |
Print dict in reverse python | 38,439,535 | <p>So I have a dict of numbers and strings, like so:</p>
<pre><code>d = {"Hi": None, 2110: 1110, 1110: None}
</code></pre>
<p>And I want to print it right to left. Like this:</p>
<pre><code>{1110: None, 2110: 1110, "Hi": None}
</code></pre>
<p>How would I go about doing this? If possible I would like to avoid sorti... | -3 | 2016-07-18T14:38:49Z | 38,439,823 | <p>You can use the code below to achieve this:</p>
<pre><code>d = {"Hi": None, 2110: 1110, 1110: None}
print str(d)
print '{' + ','.join(str(d)[1:-1].split(',')[::-1]) + '}'
</code></pre>
<p>But actually dictionaries don't have any order at all and I think you maybe want to consider to use ordered dictionaries instea... | 0 | 2016-07-18T14:51:35Z | [
"python",
"dictionary"
] |
Print dict in reverse python | 38,439,535 | <p>So I have a dict of numbers and strings, like so:</p>
<pre><code>d = {"Hi": None, 2110: 1110, 1110: None}
</code></pre>
<p>And I want to print it right to left. Like this:</p>
<pre><code>{1110: None, 2110: 1110, "Hi": None}
</code></pre>
<p>How would I go about doing this? If possible I would like to avoid sorti... | -3 | 2016-07-18T14:38:49Z | 38,440,203 | <p>You would have to use <a href="https://docs.python.org/2/library/collections.html?highlight=ordereddict#collections.OrderedDict" rel="nofollow"><code>OrderedDict</code></a> from the <a href="https://docs.python.org/3/library/collections.html" rel="nofollow"><code>collections</code></a> module, and you're starting di... | 0 | 2016-07-18T15:09:35Z | [
"python",
"dictionary"
] |
Pandas: groupby quantile with agg values | 38,439,608 | <p>I'm trying to group numerical values by quantiles and create columns for the sum of the values falling into the quantile bands. Here's a simplified, reproducible example:</p>
<pre><code> raw_data = {'female': [0, 1, 0, 1, 0, 1, 0, 1],
'male': [1, 0, 1, 0, 1, 0, 1, 0],
'number': [25000, 34000, 486... | 1 | 2016-07-18T14:42:32Z | 38,439,958 | <p>You want to use <code>pd.qcut</code> to create the groupings:</p>
<pre><code>qs = pd.qcut(df.number, [0, .1, .2, .3, .4, .5, 1], ['q%d' % i for i in xrange(6)])
qs
0 q2
1 q5
2 q5
3 q1
4 q5
5 q0
6 q4
7 q5
Name: number, dtype: category
Categories (6, object): [q0 < q1 < q2 < q3 < ... | 1 | 2016-07-18T14:58:19Z | [
"python",
"pandas"
] |
R²-value calculation for non linear least squares curve fittingin Python | 38,439,615 | <p>I have written a code in which I would like to calculate the R²-value for a nonlinear fit by a given Force-Depth relation.</p>
<p>The Code I am using for the given x- and y- data is:</p>
<blockquote>
<pre><code> ydata=npy.array(N)
xdata=npy.array(depth)
#Exponential Law
def func1 (x,Bo,k):
ret... | 0 | 2016-07-18T14:42:48Z | 38,442,400 | <p>From <a href="https://en.wikipedia.org/wiki/Coefficient_of_determination" rel="nofollow">Wikipedia</a></p>
<blockquote>
<p>Values of R2 outside the range 0 to 1 can occur where it is used to measure the agreement between observed and modeled values and where the "modeled" values are not obtained by linear regress... | 1 | 2016-07-18T17:08:36Z | [
"python",
"scipy"
] |
Assignments just bind names to objects? | 38,439,658 | <p>According to the Python tutorial, 9.2. Python Scopes and Namespaces:</p>
<blockquote>
<p>Assignments do not copy data â they just bind names to objects.</p>
</blockquote>
<p>So I'm surprised that the following code doesn't surprise me:</p>
<pre><code>>>> a = 42
>>> b = a
>>> b = b /... | 1 | 2016-07-18T14:44:28Z | 38,439,703 | <p>after b =b/2, b is new object </p>
<pre><code>>>> a = 42
>>> id(a)
8006428
>>> b = a
>>> id(b)
8006428
>>> b = b/2
>>> id(b)
8006680
</code></pre>
| 2 | 2016-07-18T14:46:44Z | [
"python",
"python-2.7",
"reference",
"namespaces"
] |
Assignments just bind names to objects? | 38,439,658 | <p>According to the Python tutorial, 9.2. Python Scopes and Namespaces:</p>
<blockquote>
<p>Assignments do not copy data â they just bind names to objects.</p>
</blockquote>
<p>So I'm surprised that the following code doesn't surprise me:</p>
<pre><code>>>> a = 42
>>> b = a
>>> b = b /... | 1 | 2016-07-18T14:44:28Z | 38,439,706 | <p>Well, you do make another assignment to <code>b</code>:</p>
<pre><code>b = b / 2
</code></pre>
<p>and since operations on <code>int</code> (immutable) types will <strong>always</strong> return a new object there's no changes made to the original value <strong>whatever</strong> the operation may be. </p>
<p>This d... | 3 | 2016-07-18T14:46:57Z | [
"python",
"python-2.7",
"reference",
"namespaces"
] |
Assignments just bind names to objects? | 38,439,658 | <p>According to the Python tutorial, 9.2. Python Scopes and Namespaces:</p>
<blockquote>
<p>Assignments do not copy data â they just bind names to objects.</p>
</blockquote>
<p>So I'm surprised that the following code doesn't surprise me:</p>
<pre><code>>>> a = 42
>>> b = a
>>> b = b /... | 1 | 2016-07-18T14:44:28Z | 38,439,763 | <p>Here is a trace of it:</p>
<p><code>>>> a = 42</code><br>
a = 42<br>
b is undefined</p>
<p><code>>>> b = a</code><br>
a = 42<br>
b = a</p>
<p><code>>>> b = b / 2</code><br>
a = 42<br>
b = 21 </p>
<p>The operation <code>b = b / 2</code> is creating a new object using <code>b</code> whi... | 0 | 2016-07-18T14:49:17Z | [
"python",
"python-2.7",
"reference",
"namespaces"
] |
Saving attachments from outlook, error when loading with pandas/xlrd | 38,439,774 | <p>I have this script, which has previously worked for other emails, to download attachments:</p>
<pre><code>import win32com.client as win
import xlrd
outlook = win.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder("6")
all_inbox = inbox.Items
subject = 'Email w/Attachment'
attac... | 0 | 2016-07-18T14:49:34Z | 38,440,673 | <p>take a look at this <a href="http://stackoverflow.com/questions/9623029/python-xlrd-unsupported-format-or-corrupt-file">question</a>. It's possible the file you are trying to download is not a true excel file, but a csv saved as an .xls file. The evidence is the error message <code>Expected BOF record; found b'\r\n... | 0 | 2016-07-18T15:30:54Z | [
"python",
"pandas",
"xlrd"
] |
Create a script to catch links on a webpage with python 3 | 38,439,788 | <p>I have to catch all the links of the topics in this page: <a href="https://www.inforge.net/xi/forums/liste-proxy.1118/" rel="nofollow">https://www.inforge.net/xi/forums/liste-proxy.1118/</a></p>
<p>I've tried with this script:</p>
<pre><code>import urllib.request
from bs4 import BeautifulSoup
url = (urllib.reques... | 0 | 2016-07-18T14:50:14Z | 38,440,428 | <p>You can use BeautifulSoup to parse the HTML:</p>
<pre><code>from bs4 import BeautifulSoup
from urllib2 import urlopen
url= 'https://www.inforge.net/xi/forums/liste-proxy.1118/'
soup= BeautifulSoup(urlopen(url))
</code></pre>
<p>Then find the links with</p>
<pre><code>soup.find_all('a', {'class':'PreviewTooltip'}... | 2 | 2016-07-18T15:19:02Z | [
"python",
"python-3.x",
"hyperlink",
"try-catch",
"webpage"
] |
Python print process in another language | 38,439,791 | <p>I want to print all the running processes in my computer. One of my processes is called <code>åå.exe</code>.
This is my code:</p>
<pre><code># -*- coding: utf-8 -*-
import psutil
for proc in psutil.process_iter():
print proc.name().encode('utf-8')
</code></pre>
<p>I get the output <code>??.exe</code> f... | 1 | 2016-07-18T14:50:28Z | 38,440,137 | <p>Maybe try doing a format like this?</p>
<pre><code>import psutil
for proc in psutil.process_iter():
try:
pinfo = proc.as_dict(attrs=['name'])
except psutil.NoSuchProcess:
pass
else:
print pinfo
</code></pre>
| 0 | 2016-07-18T15:06:23Z | [
"python",
"encoding",
"psutil"
] |
Python print process in another language | 38,439,791 | <p>I want to print all the running processes in my computer. One of my processes is called <code>åå.exe</code>.
This is my code:</p>
<pre><code># -*- coding: utf-8 -*-
import psutil
for proc in psutil.process_iter():
print proc.name().encode('utf-8')
</code></pre>
<p>I get the output <code>??.exe</code> f... | 1 | 2016-07-18T14:50:28Z | 38,440,145 | <p><a href="https://docs.python.org/3/library/stdtypes.html#str.encode" rel="nofollow"><code>encode</code></a> is the wrong method for this: The result of encoding is a binary value, ready to be output to file. What you are thinking of is the <a href="https://docs.python.org/3/library/stdtypes.html#bytes.decode" rel="... | 0 | 2016-07-18T15:06:47Z | [
"python",
"encoding",
"psutil"
] |
Python print process in another language | 38,439,791 | <p>I want to print all the running processes in my computer. One of my processes is called <code>åå.exe</code>.
This is my code:</p>
<pre><code># -*- coding: utf-8 -*-
import psutil
for proc in psutil.process_iter():
print proc.name().encode('utf-8')
</code></pre>
<p>I get the output <code>??.exe</code> f... | 1 | 2016-07-18T14:50:28Z | 38,440,704 | <p>Your os is Chinese and run the script in cmd window? You could <code>proc.name().encode('gbk')</code></p>
| 0 | 2016-07-18T15:32:11Z | [
"python",
"encoding",
"psutil"
] |
Correct data structure for point location algorithm | 38,439,846 | <p>I am dealing with a programming challenge, In that I need to find the region which the given point belongs to. There is some methods here for that problem.</p>
<p><a href="https://en.wikipedia.org/wiki/Point_location" rel="nofollow">Point Location</a></p>
<p>So I decide to use slab decomposition, It is fast enough... | 1 | 2016-07-18T14:52:30Z | 38,452,239 | <p>I would advise to use your vertices only to reference too. Use an edge list to represent the graph and assign a left and right incident region to each edge. Now use these edges in your slab decomposition. As soon as you find your slab and your slab part you know also its region as both edges near your point referenc... | 0 | 2016-07-19T07:37:28Z | [
"python",
"algorithm",
"computer-science",
"computational-geometry",
"planar-graph"
] |
Correct data structure for point location algorithm | 38,439,846 | <p>I am dealing with a programming challenge, In that I need to find the region which the given point belongs to. There is some methods here for that problem.</p>
<p><a href="https://en.wikipedia.org/wiki/Point_location" rel="nofollow">Point Location</a></p>
<p>So I decide to use slab decomposition, It is fast enough... | 1 | 2016-07-18T14:52:30Z | 38,690,487 | <p>If you know that your data will be used many times to locate multiple points, then it'll make sense to <em>preprocess</em> the original planar graph and decompose it into slabs. Then the data structure problem you're facing will be reduced to a slab representation problem.</p>
<p>And what is a slab? It's actually a... | 0 | 2016-08-01T03:11:22Z | [
"python",
"algorithm",
"computer-science",
"computational-geometry",
"planar-graph"
] |
C# WPF Process getting StandardOutput is intermittent | 38,439,879 | <p>I have a Python Process running in my C# file for WPF:</p>
<pre><code> ProcessStartInfo StartInfo = new ProcessStartInfo(@"python ", location);
StartInfo.UseShellExecute = false;
StartInfo.CreateNoWindow = true;
StartInfo.RedirectStandardOutput = true;
StartInfo.RedirectStanda... | 0 | 2016-07-18T14:54:24Z | 38,674,003 | <p>In case anyone has a similar issue, I eventually solved it. Add the following after any time output is needed:</p>
<pre><code>import sys
sys.stdout.flush()
</code></pre>
| 0 | 2016-07-30T12:31:14Z | [
"c#",
"python",
"process"
] |
Define test requirements for Bluemix Python application | 38,439,898 | <p>We have a Python 3 application that is deployed and running fine in Bluemix.</p>
<p>In order to have Python 3 on the platform (and not Python 2) we pushed a file to Bluemix titled <code>runtime.txt</code> with one line of content:</p>
<pre><code>python-3.5.1
</code></pre>
<p>Everything works fine, but when it com... | 0 | 2016-07-18T14:55:06Z | 38,576,359 | <p>I talked to a member of the squad, and I've posted their message below.</p>
<hr>
<p>I added this to the job script and it seems like django gets installed</p>
<pre><code>sudo pip install django==1.9
django-admin --version
</code></pre>
<p>Output of the django-admin command is 1.9</p>
<p>Then run the Python scri... | 0 | 2016-07-25T19:57:40Z | [
"python",
"ibm-bluemix"
] |
Python SQLAlchemy - Error IM001 reflecting table | 38,439,910 | <p>first of all, sorry if I'm not writing in the right place or I'm not providing enough info about the issue.</p>
<p>Using SQL Alchemy, with pyodbc. I'm trying to reflect a table.
When I try to do that, i get this message </p>
<blockquote>
<p>DBAPIError: (pyodbc.Error) ('IM001', '[IM001] [unixODBC][Driver
Manag... | 0 | 2016-07-18T14:55:59Z | 38,483,965 | <p>I do a try with <strong>pymmsql</strong> and it works without issues. The problem was on <em>pyodbc</em>, maybe it still have some problems with <strong>ms sql odbc drivers on Linux</strong>.</p>
| 0 | 2016-07-20T14:24:34Z | [
"python",
"sql-server",
"sqlalchemy",
"pyodbc"
] |
How to raise an exception in the init method for a CPython module | 38,439,988 | <p>I am writing a <code>CPython</code> extension on top of a library that was written in <code>C</code> and I couldn't find a solution on how to raise an exception in the <code>init</code> method. So, I split it up and, basically, the constructor will save the attributes to the object and then you have to call an init ... | 1 | 2016-07-18T14:59:21Z | 38,441,017 | <p>You should return a negative value in <code>libzihc_MRLoader_init</code>, usually <code>-1</code> for Python to catch it, search if an exception is set and end execution. At least, that's what <a href="https://hg.python.org/cpython/file/2.7/Objects/typeobject.c#l762" rel="nofollow"><code>type_call</code></a> checks ... | 0 | 2016-07-18T15:48:08Z | [
"python",
"python-2.7",
"cpython",
"python-internals"
] |
How to use access credentials in code instead of environment variables with PynamoDB | 38,440,179 | <p>I have a python app that uses several services from aws. I have one access key and secret for each service. For most of the services I use boto and don't need AWS_ACCESS_KEY_ID or AWS_SECRET_ACCESS_KEY in the environment. For dynamoDB I use pynamoDB and I have no idea how to set the credentials without these variabl... | 1 | 2016-07-18T15:08:43Z | 38,440,448 | <p>From <a href="http://pynamodb.readthedocs.io/en/latest/awsaccess.html" rel="nofollow">the PynamoDB documentation</a>:</p>
<blockquote>
<p>PynamoDB uses botocore to interact with the DynamoDB API. Thus, any
method of configuration supported by botocore works with PynamoDB. For
local development the use of envi... | 1 | 2016-07-18T15:19:46Z | [
"python",
"amazon-web-services",
"amazon-dynamodb"
] |
RelatedObjectDoesNotExist | 38,440,251 | <p>Am working on testing a django model called Authenticator, the Authenticator model has a field with ManyToManyField and OneToOneField.
When i test the model i get RelatedObjectDoesNotExist and ValueError: Cannot assign "'matt'": "Authenticator.authenticator" must be a "User" instance.</p>
<p>Here is my model</p>
... | 0 | 2016-07-18T15:11:14Z | 38,440,716 | <p>In the line:</p>
<p><code>auth = Authenticator(authenticator = "matt")</code></p>
<p>You attempt to initialize an <code>Authenticator</code> with an "<code>authenticator</code>" property value <code>"matt"</code>. Since you declared that this attribute should be a user model, you should assign a User instance here... | 1 | 2016-07-18T15:32:57Z | [
"python",
"django",
"django-testing",
"django-tests"
] |
Efficient regex parsing of html | 38,440,266 | <p>I have a piece of Python code scrapping datapoints value from what seems to be a Javascript graph on a webpage. The data looks like:</p>
<pre><code>...html/javascript...
{'y':765000,...,'x':1248040800000,...},
{'y':1020000,...,'x':1279144800000,...},
{'y':1105000,...,'x':1312754400000,...}
...html/javascript...
</c... | 0 | 2016-07-18T15:12:00Z | 38,440,441 | <p>You can do it a little bit easier:</p>
<pre><code>htmlContent = """
...html/javascript...
{'y':765000,...,'x':1248040800000,...},
{'y':1020000,...,'x':1279144800000,...},
{'y':1105000,...,'x':1312754400000,...}
...html/javascript...
"""
# Get the numbers
xData = [int(_) for _ in re.findall("'x':(\d+)", htmlContent)... | 1 | 2016-07-18T15:19:25Z | [
"python",
"regex"
] |
Tkinter commands are always after commands like print(), Input(), etc.? | 38,440,293 | <p>Here is my code (It is not ready yet.)</p>
<pre><code># NumbrimängGUI/NumberGameGUI
from time import *
from random import *
from tkinter import *
from datetime import *
# Keele valimine/Choosing language
def Eesti ():
sleep (0.25)
global keel
keel.destroy()
global valik
valik = 'eesti'
p... | 0 | 2016-07-18T15:13:06Z | 38,440,545 | <p>Your GUI won't do anything until you call <a href="http://stackoverflow.com/questions/8683217/when-do-i-need-to-call-mainloop-in-a-tkinter-application"><code>keel.mainloop()</code></a>. And using <code>time.sleep()</code> in a GUI program is generally a bad idea, take a look at the <a href="http://effbot.org/tkinter... | 1 | 2016-07-18T15:24:47Z | [
"python",
"python-3.x",
"tkinter"
] |
getopts behaving strangely in python | 38,440,338 | <p>I am using getops for args management and for some reason my -s variable is not working. My code is below, as well as the output I am getting</p>
<pre><code>try:
opts, args = getopt.getopt(sys.argv[1:], "hadsp:v", ["help", "all", "display", "single=", "present="])#, "search="])
except getopt.GetoptError as err:
... | 0 | 2016-07-18T15:14:48Z | 38,440,639 | <pre><code>import argparse
argParser = argparse.ArgumentParser()
argParser.add_argument(
'-p', '--present', dest='present', help='write help here for this parameter')
args = argParser.parse_args()
if args.present:
search(a)
</code></pre>
<p>Sample code to use argparse, which is easier to manage and use
... | 1 | 2016-07-18T15:29:20Z | [
"python",
"arguments",
"getopts"
] |
Search a File for Today's Date in Python | 38,440,371 | <p>UPDATE: If you are attempting to search a file for today's date in Python, I have posted my final code in the answers section below. </p>
<p>I have a folder containing logs created by a program. The log title contains the user's name and the date the log was created. I am trying to write a Python script that op... | 0 | 2016-07-18T15:16:04Z | 38,441,120 | <p>I suggest using a for-loop instead a while-loop, which would look like</p>
<pre><code>for i, file in enumerate(logFolderContent):
if file.startswith(today): # Assuming the files always start with the date
eligibleLogs.append(i)
# -1 gets last item in list | most recent
print("eligibleLog... | 2 | 2016-07-18T15:52:56Z | [
"python",
"python-3.x",
"datetime",
"search"
] |
Search a File for Today's Date in Python | 38,440,371 | <p>UPDATE: If you are attempting to search a file for today's date in Python, I have posted my final code in the answers section below. </p>
<p>I have a folder containing logs created by a program. The log title contains the user's name and the date the log was created. I am trying to write a Python script that op... | 0 | 2016-07-18T15:16:04Z | 38,462,210 | <p>Thanks to Steven Summers (see his answer above) and a little time playing with my code, I have finally got the script working as desired. If anyone else is trying to search a string for today's date in Python, I have rewritten my code to serve a more general purpose and put it below. Thank you to everyone who help... | 0 | 2016-07-19T15:03:27Z | [
"python",
"python-3.x",
"datetime",
"search"
] |
Retrieve and Rank in Python-Configuration File Type? | 38,440,483 | <p>I'm using the <code>retrieve_and_rank</code> class in Python from the <code>watson_developer_cloud</code> package.</p>
<p><strong>Main question:</strong> </p>
<p>In the <code>create_config</code> function, what type of object do we pass in for the <code>config</code> argument? A zip folder?</p>
<p>I'm using IBM's... | 0 | 2016-07-18T15:21:47Z | 38,446,183 | <p>I successfully got my configuration uploaded to Retrieve and Rank using the Python SDK.</p>
<p>Here are the steps and code:</p>
<p><strong>1. Upgrade to the latest <code>watson-developer-cloud</code> Python SDK:</strong></p>
<pre><code>pip install --upgrade watson-developer-cloud
</code></pre>
<p><strong>2. Crea... | 0 | 2016-07-18T21:20:33Z | [
"python",
"ibm-bluemix",
"ibm-watson-cognitive",
"retrieve-and-rank"
] |
Retrieve and Rank in Python-Configuration File Type? | 38,440,483 | <p>I'm using the <code>retrieve_and_rank</code> class in Python from the <code>watson_developer_cloud</code> package.</p>
<p><strong>Main question:</strong> </p>
<p>In the <code>create_config</code> function, what type of object do we pass in for the <code>config</code> argument? A zip folder?</p>
<p>I'm using IBM's... | 0 | 2016-07-18T15:21:47Z | 38,458,440 | <p>I realized the key was that I was incorrectly passing in a string, as opposed to an open file object. </p>
<p>You need to use the </p>
<pre><code>with open("file.zip", "rb) as fp:
...
</code></pre>
<p>as in joe's answer.</p>
| 0 | 2016-07-19T12:21:38Z | [
"python",
"ibm-bluemix",
"ibm-watson-cognitive",
"retrieve-and-rank"
] |
How to edit an XML file in Python? | 38,440,505 | <p>I have a resx file that uses XML with a bunch of data that looks like this:</p>
<pre><code><data name="key_first" xml:space="preserve">
<value>Text 1</value>
</data>
<data name="key_second" xml:space="preserve">
<value>Text 2</value>
</data>
<data name="key... | 0 | 2016-07-18T15:22:54Z | 38,440,698 | <p>Use the ElementTree API to read the XML file and then you can use find to find the world you want to replace or use it as an index and then from there you can insert what you need to insert. See links below: </p>
<p><a href="http://stackoverflow.com/questions/1591579/how-to-update-modify-a-xml-file-in-python">How t... | 0 | 2016-07-18T15:32:03Z | [
"python",
"xml",
"database",
"loops",
"resx"
] |
How to edit an XML file in Python? | 38,440,505 | <p>I have a resx file that uses XML with a bunch of data that looks like this:</p>
<pre><code><data name="key_first" xml:space="preserve">
<value>Text 1</value>
</data>
<data name="key_second" xml:space="preserve">
<value>Text 2</value>
</data>
<data name="key... | 0 | 2016-07-18T15:22:54Z | 38,440,723 | <p>Which XML parser to choose is up to you, but here is how you can approach this problem with <a href="https://docs.python.org/2/library/xml.etree.elementtree.html" rel="nofollow"><code>xml.etree.ElementTree</code></a>: the idea is to iterate over all <code>data</code> nodes, get the <code>name</code> attribute value ... | 1 | 2016-07-18T15:33:15Z | [
"python",
"xml",
"database",
"loops",
"resx"
] |
Python, best way to find out location of a color | 38,440,520 | <p>A black and white image showing a smile face inside a frame.</p>
<p><a href="http://i.stack.imgur.com/sbqcu.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/sbqcu.jpg" alt="enter image description here"></a></p>
<p>What I want is to find out the location of most right point of the smile face. (in this case, ... | 1 | 2016-07-18T15:23:42Z | 38,461,579 | <p>As an indirect way, maybe I can:
1. remove the frame
2. trim the white</p>
<p>Whatâs left is the core image itself. The dimension of the image can tell the coordinates if the core image is of regular pattern.</p>
<pre><code>from PIL import Image
img = Image.open("c:\\smile.jpg")
img2 = img.crop((30, 26, 218, ... | 0 | 2016-07-19T14:37:33Z | [
"python",
"image"
] |
$.get function not working on chromium-browser raspberry pi3 but working on chrome desktop | 38,440,587 | <p>I have a function which is supposed to communicate with the flask server and get the latest state of the gpio buttons so that the color property of the buttons can be synced across all the clients. On desktop chrome the function works perfectly but on the raspberry pi chromium-browser the function isn't even being c... | 0 | 2016-07-18T15:27:17Z | 38,440,679 | <p>just try fetch() first install polyfills <code>npm i --save es6-promise isomorphic-fetch</code></p>
<p>and then:</p>
<pre><code>require('es6-promise').polyfill();
require('isomorphic-fetch');
</code></pre>
| 0 | 2016-07-18T15:31:04Z | [
"jquery",
"python",
"flask",
"chromium",
"raspberry-pi3"
] |
Pandas compute hourly average | 38,440,596 | <p>I have a dataframe where time is a float relevant to the dataset:</p>
<pre><code> Time Value
-47.88333 90
-46.883333 23
-45.900000 66
-45.883333 87
-45.383333 43
</code></pre>
<p>The time column ranges from -48 to 0. What I would like to do is compute the average valu... | 1 | 2016-07-18T15:27:50Z | 38,440,892 | <p>Try binning the time variables with <code>pd.cut</code>:</p>
<pre><code>#change the bins arg to modify the size of the bins
df.loc[:, 'TimeBin'] = pd.cut(df.Time, bins=[i for i in range (-48, 0)])
#groupby the time bin and take the mean:
df[['TimeBin', 'Value']].groupby('TimeBin').mean()
</code></pre>
| 2 | 2016-07-18T15:42:36Z | [
"python",
"pandas"
] |
Pandas compute hourly average | 38,440,596 | <p>I have a dataframe where time is a float relevant to the dataset:</p>
<pre><code> Time Value
-47.88333 90
-46.883333 23
-45.900000 66
-45.883333 87
-45.383333 43
</code></pre>
<p>The time column ranges from -48 to 0. What I would like to do is compute the average valu... | 1 | 2016-07-18T15:27:50Z | 38,440,961 | <p>You can do this with a groupby pretty easily:</p>
<pre><code>(df.groupby(df.Time.apply(lambda x: np.floor(x) + 0.5))
.mean()
.Value
.reindex(np.arange(-47.5, -42.5))
.ffill())
Time
-47.5 90.000000
-46.5 23.000000
-45.5 65.333333
-44.5 65.333333
-43.5 65.333333
Name: Value, dtype: float64... | 2 | 2016-07-18T15:45:56Z | [
"python",
"pandas"
] |
How do I choose the package to solve this convex optimization in Python? | 38,440,642 | <p>My problem is defined as below,</p>
<blockquote>
<p>minΣ(||xi-Xci||^2+ λ||ci||),</p>
<p>s.t cii = 0,</p>
<p>where X is a matrix of shape d * n and C is of the shape n * n, xi and
ci means a column of X and C separately.</p>
<p>X is known here and based on X we want to find C.</p>
</blockquote>
... | 2 | 2016-07-18T15:29:24Z | 38,448,624 | <p>The objective function, I guess, is related to dictionary learning (e.g. your X) and sparse coding (your ci) for which there are several good libraries in Python. </p>
<p>Take a look at <a href="http://scikit-learn.org/stable/modules/generated/sklearn.decomposition.sparse_encode.html" rel="nofollow">scikit-learn's ... | 1 | 2016-07-19T02:27:11Z | [
"python",
"machine-learning",
"tensorflow",
"cvxopt",
"convex-optimization"
] |
Convert python timezone aware datetime string to utc time | 38,440,700 | <p>I have a Python datetime string that is timezone aware and need to convert it to UTC timestamp.</p>
<pre><code>'2016-07-15T10:00:00-06:00'
</code></pre>
<p>Most of the SO links talks about getting the current datetime in UTC but not on converting the given datetime to UTC.</p>
| 1 | 2016-07-18T15:32:07Z | 38,440,912 | <p>Hi this was a bit tricky, but here is my, probably far from perfect, answer:</p>
<pre><code>[IN]
import datetime
import pytz
date_str = '2016-07-15T10:00:00-06:00'
# Have to get rid of that bothersome final colon for %z to work
datetime_object = datetime.datetime.strptime(date_str[:-3] + date_str[-2:],
'%Y-%m-%dT%... | 1 | 2016-07-18T15:43:38Z | [
"python"
] |
Dereference void pointer to numpy array or list | 38,440,719 | <p>I've received a void pointer from a foreign function via <code>ctypes</code>, containing an array of <code>c_double</code> arrays:
<code>[[12.0, 13.0], [14.0, 15.0], â¦]</code></p>
<p>I'm accessing it via the <code>restype</code> parameter:</p>
<pre><code>from ctypes import Structure, POINTER, c_void_p, c_size_t,... | 3 | 2016-07-18T15:33:04Z | 38,443,322 | <p>I can't test this right now, but this is what I would try:</p>
<pre><code>import numpy as np
result = ...
shape = (10, 2)
array_size = np.prod(shape)
mem_size = 8 * array_size
array_str = ctypes.string_at(result, mem_size)
array = np.frombuffer(array_str, float, array_size).reshape(shape)
</code></pre>
<p><code>a... | 2 | 2016-07-18T18:09:09Z | [
"python",
"numpy",
"ctypes"
] |
Dereference void pointer to numpy array or list | 38,440,719 | <p>I've received a void pointer from a foreign function via <code>ctypes</code>, containing an array of <code>c_double</code> arrays:
<code>[[12.0, 13.0], [14.0, 15.0], â¦]</code></p>
<p>I'm accessing it via the <code>restype</code> parameter:</p>
<pre><code>from ctypes import Structure, POINTER, c_void_p, c_size_t,... | 3 | 2016-07-18T15:33:04Z | 38,606,682 | <p>Here is a solution that uses <code>ctypes.cast</code> or <code>numpy.ctypeslib.as_array</code>, and no <code>ctypes.string_at</code> just in case if it makes an extra copy of memory region.</p>
<pre><code>class _FFIArray(Structure):
_fields_ = [("data", c_void_p), ("len", c_size_t)]
class Coordinate(Structure)... | 1 | 2016-07-27T07:36:53Z | [
"python",
"numpy",
"ctypes"
] |
Pass a method to a function before object instantiation in python | 38,440,799 | <p>I have a class called "App" which has several methods. I want to write a function which creates several instances of App and use one of those methods for each instance. How can I pass the method name as argument to the function ?</p>
<p>Code example:</p>
<pre><code>class App(object):
def __init__(self, id):
... | 1 | 2016-07-18T15:38:12Z | 38,440,886 | <p>You can <em>pass</em> the name of the method as a <em>string</em> and then you can use <a href="https://docs.python.org/2/library/functions.html#getattr" rel="nofollow"><code>getattr</code></a> to retrieve the method from your <code>app_instance</code>.</p>
<p>Like so:</p>
<pre><code>def use_method_for_each_instan... | 2 | 2016-07-18T15:42:19Z | [
"python",
"oop"
] |
Pass a method to a function before object instantiation in python | 38,440,799 | <p>I have a class called "App" which has several methods. I want to write a function which creates several instances of App and use one of those methods for each instance. How can I pass the method name as argument to the function ?</p>
<p>Code example:</p>
<pre><code>class App(object):
def __init__(self, id):
... | 1 | 2016-07-18T15:38:12Z | 38,440,963 | <p>You can use function from class namespace.</p>
<pre><code>def use_method_for_each_instance(method):
all_results = []
for id in id_list:
app_instance = App(id)
all_results.append( method(app_instance) )
return all_results
id_list = [1,2,3]
use_method_for_each_instance(App.method_1)
</cod... | 4 | 2016-07-18T15:45:59Z | [
"python",
"oop"
] |
python how to append new data by literately checking the existing data | 38,440,895 | <p>I am working on machine learning project and would like to append data to the current table by literately checking the current data:</p>
<p>to be specific</p>
<pre><code>X, y = form_results(results)
// X & y are numpy arrays
</code></pre>
<p>the current data set looks like the following:</p>
<pre><code>x[0]... | 0 | 2016-07-18T15:42:52Z | 38,443,087 | <pre><code>x = [[1, 2, 3], [4, 5, 6]]
y = [1, 3, 4]
new_data = []
for i, x0 in enumerate(x[0]):
for j, x1 in enumerate(x[1]):
#print x0, x1, y[i] if i == j else 0
new_data.append([x0, x1, y[i] if i == j else 0])
</code></pre>
<p>This makes an array with the rows being as you want them to be.</p>
<... | 1 | 2016-07-18T17:54:40Z | [
"python"
] |
Archiving a group of gzipped files | 38,440,916 | <p>I have a group of about 10 gzipped files that I would like to archive into a single file in order for a user to download. I am wondering what the best approach to this would be.</p>
<ol>
<li>Gunzip everything, then tar-gz the complete set of files into a <code>myfiles.tar.gz</code>?</li>
<li>Tar the set of gz files... | 0 | 2016-07-18T15:43:53Z | 38,442,022 | <p>A gzipped tar archive is not an archive of compressed files. It is a compressed archive of files. In contrast, a zip archive is an archive of compressed files.</p>
<p>An archive of compressed files is a better archive format, if you want to be able to extract (or update) individual files. But it is an inferior comp... | 1 | 2016-07-18T16:44:46Z | [
"python",
"compression",
"gzip",
"tar",
"gzipstream"
] |
Archiving a group of gzipped files | 38,440,916 | <p>I have a group of about 10 gzipped files that I would like to archive into a single file in order for a user to download. I am wondering what the best approach to this would be.</p>
<ol>
<li>Gunzip everything, then tar-gz the complete set of files into a <code>myfiles.tar.gz</code>?</li>
<li>Tar the set of gz files... | 0 | 2016-07-18T15:43:53Z | 38,445,383 | <p>An gzipped archive of uncompressed files is definitely what your users will want. Since you are using Python, you can skip shelling out and make things a bit cleaner (IMO). It uses <a href="https://docs.python.org/3/library/tarfile.html#tarfile.open" rel="nofollow">tarfile</a> and <a href="https://docs.python.org/... | 0 | 2016-07-18T20:22:54Z | [
"python",
"compression",
"gzip",
"tar",
"gzipstream"
] |
Python 3 determine which part of "or" operation was true | 38,440,967 | <p>I have a functioning piece of code that suits my purposes but I wasn't sure if there was a better way to meet the end I am looking for. Here is my code : </p>
<pre><code>def eitherOne(image1, image2):
curIm1 = pyautogui.locateOnScreen(image1)
curIm2 = pyautogui.locateOnScreen(image2)
while curIm1 == Non... | 0 | 2016-07-18T15:46:08Z | 38,441,272 | <p>I'd probably do something like this. You create an infinite loop that repeatedly tries one image, then the other, breaking once one of them suceeds.</p>
<pre><code>def eitherOne(image1, image2):
images = itertools.cycle([image1, image2])
for img in images:
curIm = pyautogui.locateOnScreen(img)
... | 3 | 2016-07-18T16:00:26Z | [
"python"
] |
Python 3 determine which part of "or" operation was true | 38,440,967 | <p>I have a functioning piece of code that suits my purposes but I wasn't sure if there was a better way to meet the end I am looking for. Here is my code : </p>
<pre><code>def eitherOne(image1, image2):
curIm1 = pyautogui.locateOnScreen(image1)
curIm2 = pyautogui.locateOnScreen(image2)
while curIm1 == Non... | 0 | 2016-07-18T15:46:08Z | 38,441,985 | <p>A v2.7 example of @tobias_k's comment to your question. In <a href="https://docs.python.org/3/reference/expressions.html#boolean-operations" rel="nofollow">Boolean Operation</a>s, the <em>value</em> of the <code>True</code> espresion is returned.</p>
<pre><code>class Img(object):
def __init__(self, name):
... | 1 | 2016-07-18T16:42:20Z | [
"python"
] |
Tkinter Text widget: search for anything outside a list | 38,441,001 | <p>In Python Tkinter, how can you put a <code>search</code> function to a Text widget so it searches only text outside a given list ?</p>
<pre><code>from tkinter import *
root = Tk()
text = Text(root)
text.pack()
def searchForTextOutsideList(event):
list=["bacon","ham","sandwich"]
... # How can I search the ... | 0 | 2016-07-18T15:47:36Z | 38,441,238 | <p>I'm not sure of what you want to do exactly. If you only want to get the words not in your list, just use <code>text.get("1.0","end")</code> to get the content of the Text widget, then split it in words and check if each word is in your list or not.</p>
<p>Edit: If you want the index of the first letter of each wor... | 1 | 2016-07-18T15:58:37Z | [
"python",
"list",
"search",
"text",
"tkinter"
] |
Python sum and then multiply values of several lists | 38,441,079 | <p>Is there way to write following code in one line?</p>
<pre><code>my_list = [[1, 1, 1], [1, 2], [1, 3]]
result = 1
for l in list:
result = result * sum(l)
</code></pre>
| 1 | 2016-07-18T15:50:30Z | 38,441,148 | <p>Here you go:</p>
<pre><code>import operator
my_list = [[1, 1, 1], [1, 2], [1, 3]]
print reduce(operator.mul, [sum(l) for l in my_list])
</code></pre>
| 3 | 2016-07-18T15:54:11Z | [
"python"
] |
Python sum and then multiply values of several lists | 38,441,079 | <p>Is there way to write following code in one line?</p>
<pre><code>my_list = [[1, 1, 1], [1, 2], [1, 3]]
result = 1
for l in list:
result = result * sum(l)
</code></pre>
| 1 | 2016-07-18T15:50:30Z | 38,441,149 | <p>Use <code>reduce</code> on the <em>summed</em> sublists gotten from <code>map</code>.</p>
<p>This does it:</p>
<pre><code>>>> from functools import reduce
>>> reduce(lambda x,y: x*y, map(sum, my_list))
36
</code></pre>
<hr>
<p>In python 2.x, the <code>import</code> will not be needed as <code>r... | 5 | 2016-07-18T15:54:13Z | [
"python"
] |
Python sum and then multiply values of several lists | 38,441,079 | <p>Is there way to write following code in one line?</p>
<pre><code>my_list = [[1, 1, 1], [1, 2], [1, 3]]
result = 1
for l in list:
result = result * sum(l)
</code></pre>
| 1 | 2016-07-18T15:50:30Z | 38,441,197 | <p>with <code>numpy</code></p>
<pre><code>In [1]: from numpy import prod
In [2]: prod([sum(i) for i in my_list])
Out[2]: 36
</code></pre>
<p>Another method.</p>
<pre><code>In [1]: eval('*'.join(str(item) for item in [sum(i) for i in my_list]))
Out[1]: 36
</code></pre>
| 0 | 2016-07-18T15:56:59Z | [
"python"
] |
Python sum and then multiply values of several lists | 38,441,079 | <p>Is there way to write following code in one line?</p>
<pre><code>my_list = [[1, 1, 1], [1, 2], [1, 3]]
result = 1
for l in list:
result = result * sum(l)
</code></pre>
| 1 | 2016-07-18T15:50:30Z | 38,442,599 | <p>Maybe there are some people out there who think that a one-liner which requires an <code>import</code> statement is not a true one-liner. Just for fun, those who think so might prefer this admittedly obfuscated solution to the approaches suggested so far:</p>
<pre><code>In [389]: (lambda f: lambda n: f(f, n))(lambd... | 0 | 2016-07-18T17:22:33Z | [
"python"
] |
iterate over a subset of dictionary keys | 38,441,098 | <p>I am looking to learn how to pass certain keys/values in a dictionary to another function within a for loop. The "certain" keys all share the same initial string and are incremented by a trailing integer like this:</p>
<pre><code>data = {}
data["HMD1"] = [a,b,c]
data["HMD2"] = [d,f,g] #and so on...
</code></pre>
<... | 0 | 2016-07-18T15:52:01Z | 38,441,226 | <p>Just iterate through the dictionary using a for loop and use an if statement to check for validity of the keys:</p>
<pre><code>for key in yourDict: #a for loop for dict iterates through its keys
if 'HMD' in key: #or you can replace with any other conditional
#DO WHAT YOU WANT TO DO HERE
</code></pre>
<... | 1 | 2016-07-18T15:58:08Z | [
"python",
"for-loop",
"dictionary"
] |
iterate over a subset of dictionary keys | 38,441,098 | <p>I am looking to learn how to pass certain keys/values in a dictionary to another function within a for loop. The "certain" keys all share the same initial string and are incremented by a trailing integer like this:</p>
<pre><code>data = {}
data["HMD1"] = [a,b,c]
data["HMD2"] = [d,f,g] #and so on...
</code></pre>
<... | 0 | 2016-07-18T15:52:01Z | 38,442,493 | <p>You don't need <code>eval</code> at all for this. You only need to build the string with <code>.format</code> for example</p>
<pre><code>for f in range(1,4): #range don't include the end point
out = dummyfun(data["HMD{}".format(f)])
</code></pre>
<p>with this you get the desire result. But that will fail if th... | 1 | 2016-07-18T17:15:32Z | [
"python",
"for-loop",
"dictionary"
] |
Parsing out data from a flat file | 38,441,100 | <p>I am trying to read some data from a flat file and displaying it on other application using Python. My flat file has 12,000 lines, and I do not need all of the data. I need to parse out some data. What I have on my flat file is 12,000 lines. A chunk of lines have 00 besides other data, and another chunk has 10 besid... | 1 | 2016-07-18T15:52:04Z | 38,441,971 | <p>If I understand your question correctly (and I'm not sure that I do) you have a file with lines that look like this:</p>
<pre><code>@45 0 0 5 10 *
@45 0 0 5 10 *
@45 0 0 5 10 *
@45 0 0 6 10 *
@45 0 0 6 00 *
@45 0 0 6 00 *
@45 0 0 6 00 *
@45 0 0 5 00 *
</code></pre>
<p>... an... | 1 | 2016-07-18T16:41:18Z | [
"python"
] |
Parsing out data from a flat file | 38,441,100 | <p>I am trying to read some data from a flat file and displaying it on other application using Python. My flat file has 12,000 lines, and I do not need all of the data. I need to parse out some data. What I have on my flat file is 12,000 lines. A chunk of lines have 00 besides other data, and another chunk has 10 besid... | 1 | 2016-07-18T15:52:04Z | 38,442,083 | <pre><code>import re
filename = <path to file>
lines = [line.strip() for line in open(filename) if re.match(r'^\$.*LOB.*00 &$', line)]
</code></pre>
<p><a href="https://regex101.com/r/pD3wB7/7" rel="nofollow">A regex101 example</a></p>
<p>Regex explained:</p>
<p>The <code>^</code> indicates the start of a... | 1 | 2016-07-18T16:49:05Z | [
"python"
] |
Plotting 3d line graph using matplotlib. TypeError: Cannot cast array data from dtype('float64') to dtype('S32') according to the rule 'safe' | 38,441,165 | <p>This is my code :</p>
<pre><code> import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt
with open("TestGraph.txt") as f:
data = f.read()
data = data.split('\n')
fig = plt.figure()
ax = fig.add_subplot(111,proj... | 1 | 2016-07-18T15:55:25Z | 38,467,591 | <p>Your <code>x</code>, <code>y</code> and <code>z</code> variables are lists of strings (<code>S32</code>). The <code>plot_wireframe</code> expects <code>float</code> (<code>float64</code>). Here's a simpler solution. You can use <code>pandas</code> too.</p>
<pre><code>import numpy as np
import matplotlib.pyplot as p... | 0 | 2016-07-19T20:08:44Z | [
"python",
"numpy",
"matplotlib",
"computer-science"
] |
Determining Data Type From Value in Row of CSV File | 38,441,191 | <p>I wrote a Python program that reads CSV files and spits them out as insert statements for MySQL. Now I want an additional program that is able to form the <code>CREATE</code> statements for each new table using the column headers. Due to MySQL formatting I need to be able to determine the type of each value in a col... | 2 | 2016-07-18T15:56:33Z | 38,441,406 | <p>Here is one possibility to distinguish between float and int and assume that everything else is a string. If the value has a decimal point then it tries to convert it to a float and tries to convert it to an int if not. If either conversion fails, the value is left as a string.</p>
<pre><code>if '.' in val:
t... | 1 | 2016-07-18T16:08:41Z | [
"python",
"mysql",
"python-3.x",
"csv"
] |
Determining Data Type From Value in Row of CSV File | 38,441,191 | <p>I wrote a Python program that reads CSV files and spits them out as insert statements for MySQL. Now I want an additional program that is able to form the <code>CREATE</code> statements for each new table using the column headers. Due to MySQL formatting I need to be able to determine the type of each value in a col... | 2 | 2016-07-18T15:56:33Z | 38,441,421 | <p>This would be the <em>simple</em> way to do it:</p>
<pre><code>def find_type(a):
try:
var_type = type(int(a))
except ValueError:
try:
var_type = type(float(a))
except ValueError:
var_type = type(a)
return var_type
a = ['123123', '11.21', 'Some Bank', '11/... | 2 | 2016-07-18T16:09:14Z | [
"python",
"mysql",
"python-3.x",
"csv"
] |
How to set pandas dataframe to NaN using last_valid_index() of another column | 38,441,230 | <p>How to set the column of a pandas dataframe to NaN using the index above the <code>last_valid_index()</code> of another column to NaN. </p>
<p>In [2]: df</p>
<pre><code> A B
0 1.068932 -0.794307
2 -0.470056 1.192211
4 -0.284561 0.756029
6 1.037563 -0.267820
8 -0.538478 NaN
9. 1.03733 NaN
10.1... | 2 | 2016-07-18T15:58:19Z | 38,441,316 | <p><code>last_valid_index</code> returns a row label. Therefore use <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#different-choices-for-indexing" rel="nofollow"><code>df.loc</code></a> to select columns and rows by label, and assign a new value:</p>
<pre><code>idx = df['B'].last_valid_index()
df.l... | 4 | 2016-07-18T16:03:25Z | [
"python",
"pandas"
] |
What is the equivalent function in openpyxl? | 38,441,248 | <p>In xlrd and xlwt to append the rows of a sheet to an array I can do: </p>
<pre><code>Stuff = []
column_count = sheet.ncols - 1
for i in range (0, column_count):
Stuff.append([sheet.cell_value(row, i) for row in range(sheet.nrows)])
</code></pre>
<p><strong>How do I do the equivalent in openpyxl?</strong></p... | 0 | 2016-07-18T15:59:12Z | 38,441,314 | <p>You can iterate through the rows of a worksheet:</p>
<pre><code>stuff = [[cell.value for cell in row] for row in sheet]
</code></pre>
<p>Or, if you rather group it by columns, use <code>.columns</code>:</p>
<pre><code>stuff = [[cell.value for cell in column] for column in sheet.columns]
</code></pre>
<p>The colu... | 2 | 2016-07-18T16:02:56Z | [
"python",
"excel",
"openpyxl",
"xlrd",
"xlwt"
] |
AttributeError: 'Resultset' object has no attribute ' findAll | 38,441,352 | <p>I am trying to write some code that will scrape financial data from the internet and then present it as a table in table. The problem I am having is that I keep returning an error that says- AttributeError: 'ResultSet' object has no attribute 'findAll'
I have no idea why it keeps returning this, I have tried many th... | 1 | 2016-07-18T16:05:29Z | 38,442,593 | <p>In this section of your code:</p>
<pre><code>data = map(parse_string, rows.findAll('td'))
if len(data)>1:
</code></pre>
<p>You either need to use a <code>for</code> loop to traverse over your <code>data</code> object or use <code>rows.find('td')</code> instead of <code>findAll</code> if you only have one <code>... | 0 | 2016-07-18T17:22:08Z | [
"python",
"beautifulsoup"
] |
Python - Remove all characters until final alpha letter in string | 38,441,354 | <p>I have several strings where I need to remove all characters until the final alphabetical letter. I'm trying to keep the final numerical tag and store it into a variable. If there is no numerical tag at the end (like in the case of <code>Serial</code> and <code>Management</code>), then the variable should be empty. ... | 0 | 2016-07-18T16:05:39Z | 38,441,455 | <p>To follow Lawrence's comment, you can use a combination of reversing a string, <a href="https://docs.python.org/2.7/library/itertools.html#itertools.takewhile" rel="nofollow"><code>itertools.takewhile()</code></a> and <a href="https://docs.python.org/2/library/stdtypes.html#str.join" rel="nofollow"><code>str.join()<... | 2 | 2016-07-18T16:11:06Z | [
"python",
"string"
] |
Python code only working for title tag not for table | 38,441,378 | <p>In regex when writing <code><title>(.+?)</title></code> it is working but when this title tag is change to <code><table>(.+?)</table></code> it gives '[]' (square brackets) as output.
My code is :</p>
<pre><code>import urllib
import re
urls = ["http://physics.iitd.ac.in/content/list-faculty... | 1 | 2016-07-18T16:06:46Z | 38,441,459 | <p>Use <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/" rel="nofollow">BeautifulSoup</a>:</p>
<pre><code>import urllib
import re
from BeautifulSoup import BeautifulSoup as bs
urls = ["http://physics.iitd.ac.in/content/list-faculty-members",
"http://www.iitkgp.ac.in/commdir3/list.php?division... | 1 | 2016-07-18T16:11:24Z | [
"python",
"python-2.7"
] |
How to use distutils or setuptools in setup.py to make a cython extention importable (without needing to append to sys.path before every import)? | 38,441,424 | <p>I have cython extention which I install in the following way:</p>
<pre><code>from distutils.core import setup
from Cython.Build import cythonize
setup(ext_modules=cythonize(
"package.pyx",
language="c++")
)
</code></pre>
<p>When I want to import this package, I need to append the build folder to path usin... | 1 | 2016-07-18T16:09:24Z | 38,442,701 | <p>Try my <code>setup.py</code> as a template... these things aren't exactly well documented. One thing to remember here is if you build <code>inplace</code> you probably will have to <code>from projectname.module import module</code>:</p>
<pre><code>try:
from setuptools import setup
from setuptools import Ext... | 2 | 2016-07-18T17:29:07Z | [
"python",
"cython",
"setuptools",
"setup.py",
"cythonize"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.