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
kth smallest element sorted matrix using QuickSelect
38,772,873
<p>I know this has been asked before but this question is about my specific code. I am trying to do a psuedo QuickSelect algorithm where I compare k to the midpoint of a sub interval of a sorted matrix. </p> <p>I keep getting a timeout error.</p> <p>Here is the matrix:</p> <pre><code>matrix = [ [ 1, 5, 9], [...
0
2016-08-04T16:33:14Z
38,773,490
<p>Your above approach will not work. As your matrix is row and column wise sorted. Consider the matrix like below</p> <pre><code>10, 20, 30, 40 15, 25, 35, 45 24, 29, 37, 48 32, 33, 39, 50 </code></pre> <p>Your approach will fail in this case. You are getting time out because you are traversing the whole 2D matrix. ...
0
2016-08-04T17:07:52Z
[ "python", "algorithm", "matrix" ]
Signaling between parent and child widgets in tkinter
38,772,877
<p>I have a moderately complex GUI that I'm building for interacting with and observing some simulations. I would like to be able to continue to refactor and add features as the project progresses. For this reason, I would like as loose as possible a coupling between different widgets in the application.</p> <p>My app...
1
2016-08-04T16:33:26Z
38,773,229
<p>My code in <a href="http://stackoverflow.com/a/38161946/5781248">answer</a> avoids the issue of class A having to know about internals of class B by calling methods of a handler object. In the following code methods in class <code>Scanner</code> do not need to know about the internals of a <code>ScanWindow</code> i...
0
2016-08-04T16:53:38Z
[ "python", "python-3.x", "user-interface", "design", "tkinter" ]
How to insert several lists into sqlite column
38,772,878
<p>I am going to insert information from the following list into sqlite column:</p> <pre><code>a = [1, 2, 3] b = ['MAR', 'PAR', 'ZAR'] c = [1000, 2000, 3000] </code></pre> <p>column AA of database should have information in list a, column BB should have information in list b, and column CC should have information in...
0
2016-08-04T16:33:31Z
38,772,893
<p>You have shadowed the <code>c</code> variable. It does not refer to the opened cursor anymore:</p> <pre><code>c = conn.cursor() # ... c = [1000, 2000, 3000] </code></pre> <p>This is one of the many reasons to have <em>meaningful variable names</em>. I doubt you would have made this error if you named the cursor as...
2
2016-08-04T16:34:22Z
[ "python", "sqlite", "python-3.x", "insert-into" ]
Ending an infinite loop issue (Python)
38,772,896
<p>I am attempting to create a loop which a user can stop at the end of the program. I've tried various solutions, none of which have worked, all I have managed to do is create the loop but I can't seem to end it. I only recently started learning Python and I would be grateful if someone could enlighten me on this issu...
0
2016-08-04T16:34:35Z
38,773,031
<p>You can change the return to break and it will exit the while loop</p> <pre><code>if again =="No": print("Goodbye!") break </code></pre>
0
2016-08-04T16:42:42Z
[ "python", "loops" ]
Ending an infinite loop issue (Python)
38,772,896
<p>I am attempting to create a loop which a user can stop at the end of the program. I've tried various solutions, none of which have worked, all I have managed to do is create the loop but I can't seem to end it. I only recently started learning Python and I would be grateful if someone could enlighten me on this issu...
0
2016-08-04T16:34:35Z
38,773,088
<p>Instead of this:</p> <pre><code>while True: </code></pre> <p>You should use this:</p> <pre><code>again = True while again: ... usrIn = raw_input("Would you like to process another customer? y/n") if usrIn == 'y': again = True else again = False </code></pre> <p>I just made it def...
0
2016-08-04T16:45:43Z
[ "python", "loops" ]
Ending an infinite loop issue (Python)
38,772,896
<p>I am attempting to create a loop which a user can stop at the end of the program. I've tried various solutions, none of which have worked, all I have managed to do is create the loop but I can't seem to end it. I only recently started learning Python and I would be grateful if someone could enlighten me on this issu...
0
2016-08-04T16:34:35Z
38,773,606
<p>I checked your code with python 3.5 and it worked after I changed the <code>raw_input</code> to <code>input</code>, since input in 3.5 is the raw_input of 2.7. Since you're using print() as a function, you should have an import of the print function from future package in your import section. I can't see no import s...
0
2016-08-04T17:14:10Z
[ "python", "loops" ]
How to index one array with another using SciPy CSR Sparse Arrays?
38,772,900
<p>I have two arrays A and B. In NumPy you can use A as an index to B e.g.</p> <pre><code>A = np.array([[1,2,3,1,7,3,1,2,3],[4,5,6,4,5,6,4,5,6],[7,8,9,7,8,9,7,8,9]]) B= np.array([1,2,3,4,5,6,7,8,9,0]) c = B[A] </code></pre> <p>Which produces:</p> <blockquote> <p>[[2 3 4 2 8 4 2 3 4] [5 6 7 5 6 7 5 6 7] [8 9 0 8 ...
0
2016-08-04T16:34:41Z
38,777,215
<p>Sparse indexing is less developed. <code>coo</code> format for example doesn't implement it at all.</p> <p>I haven't tried to implement this problem, though I have answered others that involve working with the sparse format attributes. So I'll just make some general observations.</p> <p><code>B_sparse</code> is ...
1
2016-08-04T20:53:45Z
[ "python", "arrays", "numpy", "scipy" ]
What exactly does ./configure --enable-shared do during python altinstall?
38,772,946
<p>When I altinstall python 2.7.12 with </p> <blockquote> <p>./configure --prefix=/opt/python --enable-shared</p> </blockquote> <p>it comes up as python 2.7.5 (system default python)</p> <p>But without </p> <blockquote> <p>--enable-shared</p> </blockquote> <p>it comes up as 2.7.12, what am I missing?</p> <p>T...
0
2016-08-04T16:37:34Z
38,773,027
<p>I'm not sure why the version number is different, but Graham Dumpleton says at <a href="https://github.com/docker-library/python/issues/21" rel="nofollow">this</a> website that "When running configure, you should be supplying the --enable-shared option to ensure that shared libraries are built for Python. By not doi...
1
2016-08-04T16:42:33Z
[ "python", "python-2.7" ]
What exactly does ./configure --enable-shared do during python altinstall?
38,772,946
<p>When I altinstall python 2.7.12 with </p> <blockquote> <p>./configure --prefix=/opt/python --enable-shared</p> </blockquote> <p>it comes up as python 2.7.5 (system default python)</p> <p>But without </p> <blockquote> <p>--enable-shared</p> </blockquote> <p>it comes up as 2.7.12, what am I missing?</p> <p>T...
0
2016-08-04T16:37:34Z
38,781,440
<p>Compiling python like this fixed my issue:</p> <pre><code>./configure --enable-shared --prefix=/opt/python LDFLAGS=-Wl,-rpath=/opt/python/lib </code></pre> <p>Courtesy Ned Deily:</p> <p>The problem is, that on most Unix systems (with the notable exception of Mac OS X), the path to shared libraries is not an absol...
0
2016-08-05T05:00:46Z
[ "python", "python-2.7" ]
Looping help needed in python pandas for calculating Precision and Recall from confusion matrix
38,773,087
<p>I have a confusion matrix for 2 classes with pre-calculated totals in a pandas dataframe format:</p> <pre><code> Actual_class Predicted_class_0 Predicted_class_1 Total 0 0 39 73 112 1 1 52 561 613 2 ...
0
2016-08-04T16:45:39Z
38,776,214
<p>I found a solution using numpy diagonal: </p> <pre><code>import numpy as np cols = [c for c in cross_tab.columns if c.lower()[:4] == 'pred' or c == 'Total'] denomPrecision=[] for c in cols: denomPrecision.append(cross_tab[c].iloc[-1]) diag = np.diagonal(cross_tab.values,1) cross_tab["Precision"] = np.rou...
0
2016-08-04T19:49:03Z
[ "python", "pandas", "matrix" ]
Get normalised value counts weighted by another column?
38,773,095
<p>I have a dataframe like this in Pandas:</p> <pre><code>df = pd.DataFrame({ 'org': ['A1', 'B1', 'A1', 'B2'], 'DIH': [True, False, True, False], 'Quantity': [10,20,10,20], 'Items': [1, 2, 3, 4] }) </code></pre> <p>Now I want to get the value counts and modal value of <code>Quantity</code>, but weighted by...
0
2016-08-04T16:46:06Z
38,773,385
<p>This worked for me</p> <pre><code>df.groupby('Quantity').agg({'Items': 'sum'}).sort_values('Items', ascending=False)/df['Items'].sum()*100 </code></pre>
2
2016-08-04T17:02:23Z
[ "python", "pandas" ]
Get normalised value counts weighted by another column?
38,773,095
<p>I have a dataframe like this in Pandas:</p> <pre><code>df = pd.DataFrame({ 'org': ['A1', 'B1', 'A1', 'B2'], 'DIH': [True, False, True, False], 'Quantity': [10,20,10,20], 'Items': [1, 2, 3, 4] }) </code></pre> <p>Now I want to get the value counts and modal value of <code>Quantity</code>, but weighted by...
0
2016-08-04T16:46:06Z
38,773,396
<p>Just add one more line to your code:</p> <pre><code>df2 = df.groupby('Quantity').agg({'Items': 'sum'}).sort_values('Items', ascending=False) df2['Items']=(df2['Items']*100)/df2['Items'].sum() print (df2) Output : Items Quantity 20 60.0 10 40.0 </code></pre>
0
2016-08-04T17:02:42Z
[ "python", "pandas" ]
Get normalised value counts weighted by another column?
38,773,095
<p>I have a dataframe like this in Pandas:</p> <pre><code>df = pd.DataFrame({ 'org': ['A1', 'B1', 'A1', 'B2'], 'DIH': [True, False, True, False], 'Quantity': [10,20,10,20], 'Items': [1, 2, 3, 4] }) </code></pre> <p>Now I want to get the value counts and modal value of <code>Quantity</code>, but weighted by...
0
2016-08-04T16:46:06Z
38,773,524
<p>try this instead (one line) :</p> <pre><code>df.groupby('Quantity').agg({'Items': 'sum'}).sort_values('Items', ascending=False).apply(lambda x: 100*x/float(x.sum())) </code></pre>
0
2016-08-04T17:09:16Z
[ "python", "pandas" ]
Flask contexts (application and request) vs thread-local variables
38,773,099
<p><a href="http://flaskbook.com/" rel="nofollow">Flask Web Development</a> says:</p> <pre><code>from flask import request @app.route('/') def index(): user_agent = request.headers.get('User-Agent') return '&lt;p&gt;Your browser is %s&lt;/p&gt;' % user_agent </code></pre> <blockquote> <p>Note how in this view f...
1
2016-08-04T16:46:14Z
38,774,237
<p>This was simply a design decision by Armin (the author of Flask). You could indeed rewrite Flask to operate as a thread-local, but that was not what he wanted to do here.</p> <p>The idea of Flask (in general) is to keep things as simple as possible, and abstract a lot of thinking away. This is why a lot of Flask he...
1
2016-08-04T17:53:23Z
[ "python", "python-3.x", "flask", "python-multithreading" ]
How to set up Flask on pythonanyhwere based on flask megatutorial
38,773,135
<p>I am currently developing an application. this web app has its <strong>own domain</strong>. when initially created i set up the domain and the registrar using the cname and it succesfully displayed after a couple of hours <strong>"this is a flask app..."</strong> something like that.</p> <p>i decided to follow the ...
2
2016-08-04T16:48:18Z
38,773,714
<p>PythonAnywhere dev here.</p> <p>If you run a Flask app from a console on PythonAnywhere, it's not actually accessible from anywhere else. It may well run, but nothing will route any requests to it. So there's no need to run anything from the console (unless you're just testing for syntax errors, I guess).</p> <p...
2
2016-08-04T17:20:01Z
[ "python", "mysql", "flask", "pythonanywhere", "flask-migrate" ]
How do I edit this algorithm so that it creates combinations without replacement or reusing an element?
38,773,201
<p>I'm very new to computer science - this is my first program. I wrote a python program that takes data in two columns from an excel sheet "Labels":"Values" and reconfigures them into lists of Labels whose respective values sum to 30. Each label is unique and only occurs once, but the different labels can have the sam...
1
2016-08-04T16:51:44Z
38,774,201
<p>Here's a linear programming approach that I mentioned in the comments:</p> <pre><code>import pandas as pd from pulp import * import random random.seed(0) num_items = 50 labels = ['Label{0:02d}'.format(i) for i in range(num_items)] values = [random.randint(5, 30) for _ in range(num_items)] df = pd.DataFrame({'Value'...
3
2016-08-04T17:50:25Z
[ "python", "excel", "algorithm", "python-2.7", "xlrd" ]
Slowly scroll in python selenium javascript
38,773,273
<pre><code>url = correct_url(url) browser = webdriver.Chrome() browser.get(url) browser.find_element_by_xpath('//*[@title="New chat"]').click() drawer_body = browser.find_elements_by_class_name('drawer-body') browser.execute_script('arguments[0].scrollTop = arguments[0].scrollHeight', drawer_body) </code></pre> <block...
0
2016-08-04T16:55:46Z
38,849,968
<p>Most browsers support <em>Spacebar</em> key as a keyboard shortcut for scrolling page down. Using this feature, you can do the following:</p> <ol> <li>Visit page</li> <li>Parse what is loaded so far</li> <li>Simulate press spacebar using Selenium</li> <li>Wait 2-3 seconds till more data is loaded</li> <li>Continue<...
0
2016-08-09T11:52:17Z
[ "javascript", "python", "selenium", "web-scraping" ]
django 1.10 custom user model and user manager
38,773,279
<p>Im trying to create a custom user model and his manager</p> <p><a href="https://gist.github.com/bitgandtter/9fc0de497a3cc13440e24a86ba6626b1" rel="nofollow">gist with code</a></p> <p>But for some reason when y try to create a user with the</p> <p><code>python manage.py createsuperuser</code></p> <p>It rise an er...
0
2016-08-04T16:56:14Z
38,774,184
<p>The solition was to specify the missing property on the model</p> <pre><code>last_login = None </code></pre> <p>the same as </p> <pre><code>is_active = True </code></pre> <p>In deed those need to be correctly handled in the future but at list this issue was fixed.</p>
0
2016-08-04T17:49:43Z
[ "python", "django" ]
simplest python equivalent to R's gsub
38,773,379
<p>Is there a simple/one-line python equivalent to R's <code>gsub</code> function?</p> <pre><code>strings = c("Important text, !Comment that could be removed", "Other String") gsub("(,[ ]*!.*)$", "", strings) # [1] "Important text" "Other String" </code></pre>
0
2016-08-04T17:01:56Z
38,773,433
<p>For a a string:</p> <pre><code>import re string = "Important text, !Comment that could be removed" re.sub("(,[ ]*!.*)$", "", string) </code></pre> <p>Since you updated your question to be a list of strings, you can use a list comprehension.</p> <pre><code>import re strings = ["Important text, !Comment t...
1
2016-08-04T17:04:33Z
[ "python", "python-2.7" ]
Need to scrap a table which is loaded through ajax using python(selenium)
38,773,397
<p>I have a <a href="https://seahawks.strmarketplace.com/Charter-Seat-Licenses/Charter-Seat-Licenses.aspx" rel="nofollow" title="page">page</a> that has a table (table id= "ctl00_ContentPlaceHolder_ctl00_ctl00_GV" class="GridListings" )i need to scrap. I usually use BeautifulSoup &amp; urllib for it,but in this case t...
2
2016-08-04T17:02:42Z
38,773,801
<p>If you want to scrap something, it will be nice first to install a web debugger ( <a href="http://getfirebug.com/" rel="nofollow">Firebug</a> for <a href="https://www.mozilla.org/en-US/firefox/new/" rel="nofollow">Mozilla Firefox</a> for example) to watch how the website you want to scrap is working.</p> <p>Next, y...
0
2016-08-04T17:26:36Z
[ "python", "selenium", "selenium-webdriver" ]
Need to scrap a table which is loaded through ajax using python(selenium)
38,773,397
<p>I have a <a href="https://seahawks.strmarketplace.com/Charter-Seat-Licenses/Charter-Seat-Licenses.aspx" rel="nofollow" title="page">page</a> that has a table (table id= "ctl00_ContentPlaceHolder_ctl00_ctl00_GV" class="GridListings" )i need to scrap. I usually use BeautifulSoup &amp; urllib for it,but in this case t...
2
2016-08-04T17:02:42Z
38,775,553
<p>You can get the data using <em>requests</em> and <em>bs4,</em>, with almost if not all asp sites there are a few post params that always need to be provided like <em>__EVENTTARGET</em>, <em>__EVENTVALIDATION</em> etc.. :</p> <pre><code>from bs4 import BeautifulSoup import requests data = {"__EVENTTARGET": "ctl00$C...
2
2016-08-04T19:12:40Z
[ "python", "selenium", "selenium-webdriver" ]
Raspberry pi - arduino Serial Communication
38,773,451
<p>I need to communicate raspberry pi with the arduino over serial communication. And to communicate, I'm using same baud rates in both side but still i'm unable to do this thing..</p> <p>this is my Arduino code</p> <pre><code>int ledPinSpeedOne = 11; int ledPinSpeedTwo = 12; int ledPinSpeedThree = 13; char inbyte; ...
1
2016-08-04T17:05:45Z
38,873,836
<p>i have solved my problem.There was a time gap to access the value, i just had to add a while loop in order to get the value. In my arduino code i have added a delay in line no 24.</p>
0
2016-08-10T12:45:15Z
[ "python", "arduino-uno", "serial-communication" ]
Undefined index: HTTP_ACCEPT_LANGUAGE using BeatifulSoup/Python
38,773,480
<p>I'm learning Python and I'm trying to parse a webpage made with PHP using BeautifulSoup. My problem is my script show this error:</p> <pre><code>&lt;div style="border:1px solid #990000;padding-left:20px;margin:0 0 10px 0;"&gt; &lt;h4&gt;A PHP Error was encountered&lt;/h4&gt; &lt;p&gt;Severity: Notice&lt;/p&gt; &lt;...
1
2016-08-04T17:07:32Z
38,773,569
<p>Looks like the page requires you to have the <code>Accept-Language</code> header passed along with your request. Here is an example how to do that with <a href="http://docs.python-requests.org/en/master/" rel="nofollow"><code>requests</code></a>:</p> <pre><code>import requests url = "my url" response = requests.g...
0
2016-08-04T17:11:50Z
[ "python", "html-parsing" ]
How to push notifications to Test Client in Flask-SocketIO?
38,773,484
<p>I'm trying to receive pushes from the server as a client; using my test client as follows:</p> <p>Client:</p> <pre><code>socket_client = socketio.test_client(app) @socketio.on('hit_client') def recieve_message(json_data): print("Server has called!") </code></pre> <p>Server:</p> <pre><code>socketio.emit('hit_...
1
2016-08-04T17:07:45Z
38,777,691
<p>The test client is not a Socket.IO client. It's only purpose is to help you write unit tests for your Socket.IO server. It is similar in concept to the Flask's test client for HTTP routes. It only makes sense to use it in unit tests.</p> <p>When the server emits something to the client, the test client will just st...
0
2016-08-04T21:28:55Z
[ "python", "sockets", "socket.io", "flask-socketio", "flask-sockets" ]
python capture URLError code
38,773,515
<p>I want to use Python to monitor a website that uses HTTPS. The problem is that the certificate on the website is invalid. I don't care about that, I just want to know that the website is running.</p> <p>My working code looks like this:</p> <pre><code>from urllib.request import Request, urlopen from urllib.error im...
0
2016-08-04T17:08:56Z
38,773,823
<p>Please have a look at the great <code>requests</code> package. It will simplify your life when doing http communication. See <a href="http://requests.readthedocs.io/en/master/" rel="nofollow">http://requests.readthedocs.io/en/master/</a>.</p> <pre><code>pip install requests </code></pre> <p>To skip certificate che...
1
2016-08-04T17:27:46Z
[ "python" ]
python capture URLError code
38,773,515
<p>I want to use Python to monitor a website that uses HTTPS. The problem is that the certificate on the website is invalid. I don't care about that, I just want to know that the website is running.</p> <p>My working code looks like this:</p> <pre><code>from urllib.request import Request, urlopen from urllib.error im...
0
2016-08-04T17:08:56Z
38,774,845
<p>I couldn't install the SLL library (egg_info error). This is what I ended up doing</p> <pre><code>from urllib.request import Request, urlopen from urllib.error import URLError, HTTPError def sendEmail(r): #send notification print('send notify') req = Request("https://somedomain.com") try: respons...
1
2016-08-04T18:28:13Z
[ "python" ]
Rabbit MQ python script. Socket closed when connection was open
38,773,522
<p>Need some help! While running the python script using Rabbit MQ RPC. I am getting a <code>Socket 104</code>,<code>Socket closed when connection was open</code> error. Below is python traceback and some code:</p> <pre><code>Traceback (most recent call last): File "./server.py", line 34, in &lt;module&gt; chann...
0
2016-08-04T17:09:08Z
38,774,111
<p>Apologies as i am unable to comment due to low reputation. Could you provide a little more information on how you are opening your connection. Is it really open?</p> <p>It might be because of loss of connection with rabbitmq server as pika doesn't deal with disconnects and often results in similar stacktrace.</p> ...
0
2016-08-04T17:45:40Z
[ "python", "sockets", "rabbitmq", "pika" ]
How to move the legend in Seaborn FacetGrid outside of the plot?
38,773,560
<p>I have the following code:</p> <pre><code>g = sns.FacetGrid(df, row="Type", hue="Name", size=3, aspect=3) g = g.map(sns.plt.plot, "Volume", "Index") g.add_legend() sns.plt.show() </code></pre> <p>This results in the following plot:</p> <p><a href="http://i.stack.imgur.com/OWdku.png" rel="nofollow"><img src="http:...
0
2016-08-04T17:11:05Z
38,774,322
<p>You can do this by resizing the plots:</p> <pre><code>g = sns.FacetGrid(df, row="Type", hue="Name", size=3, aspect=3) g = g.map(sns.plt.plot, "Volume", "Index") for ax in g.axes.flat: box = ax.get_position() ax.set_position([box.x0,box.y0,box.width*0.9,box.height]) sns.plt.legend(loc='center left',bbox_to_...
0
2016-08-04T17:58:27Z
[ "python", "plot", "seaborn" ]
How to move the legend in Seaborn FacetGrid outside of the plot?
38,773,560
<p>I have the following code:</p> <pre><code>g = sns.FacetGrid(df, row="Type", hue="Name", size=3, aspect=3) g = g.map(sns.plt.plot, "Volume", "Index") g.add_legend() sns.plt.show() </code></pre> <p>This results in the following plot:</p> <p><a href="http://i.stack.imgur.com/OWdku.png" rel="nofollow"><img src="http:...
0
2016-08-04T17:11:05Z
38,828,456
<p>According to mwaskom's comment above, this is a bug in OS X. Indeed switching to another backend solves the issue.</p> <p>For instance, I put this into my <code>matplotlibrc</code>:</p> <pre><code>backend : TkAgg # use Tk with antigrain (agg) rendering </code></pre>
0
2016-08-08T11:48:58Z
[ "python", "plot", "seaborn" ]
Python library project structure best practice: imports and tests
38,773,669
<p>I want to refactor a python library i am using a lot in my day to day work to publish it on github as open source. Before doing so, i would like to be compliant with some kind of best practice for python projects structure. I am going to describe below want i would like to do and i would appreciate your suggestions....
3
2016-08-04T17:17:51Z
38,774,189
<p>When running your test code, you want to do absolute imports. This is because when you're running unit tests, etc., you should assume your 'library' is installed in local development mode for testing -- don't use relative imports because you are not in the same package.</p> <p>Here's how you would do an import in y...
1
2016-08-04T17:50:01Z
[ "python", "python-unittest", "project-structure" ]
Is it possible to add a value named 'None' to enum type?
38,773,832
<p>can I add a value named 'None' to a enum? for example </p> <pre><code>from enum import Enum class Color(Enum): None=0 #represent no color at all red = 1 green = 2 blue = 3 color=Color.None if (color==Color.None): #don't fill the rect else: #fill the rect with the color </code></pre> <p>Th...
3
2016-08-04T17:28:38Z
38,773,896
<p>Not quite the way you tried, but you can do this:</p> <pre><code># After defining the class Color as normal, but excluding the part for None... setattr(Color, 'None', 0) color = Color.None if color == Color.None: ... </code></pre> <p>Note: I did this in Python 2. Not sure if you want this in Python 2 or 3 bec...
-1
2016-08-04T17:32:49Z
[ "python", "enums" ]
Is it possible to add a value named 'None' to enum type?
38,773,832
<p>can I add a value named 'None' to a enum? for example </p> <pre><code>from enum import Enum class Color(Enum): None=0 #represent no color at all red = 1 green = 2 blue = 3 color=Color.None if (color==Color.None): #don't fill the rect else: #fill the rect with the color </code></pre> <p>Th...
3
2016-08-04T17:28:38Z
38,774,019
<p>You can do this using the <code>Enum</code> constructor rather than creating a subclass</p> <pre><code>&gt;&gt;&gt; from enum import Enum &gt;&gt;&gt; &gt;&gt;&gt; Color = Enum('Color', {'None': 0, 'Red': 1, 'Green': 2, 'Blue': 3}) &gt;&gt;&gt; Color.None &lt;Color.None: 0 </code></pre> <p>EDIT: This works using ...
0
2016-08-04T17:39:43Z
[ "python", "enums" ]
Is it possible to add a value named 'None' to enum type?
38,773,832
<p>can I add a value named 'None' to a enum? for example </p> <pre><code>from enum import Enum class Color(Enum): None=0 #represent no color at all red = 1 green = 2 blue = 3 color=Color.None if (color==Color.None): #don't fill the rect else: #fill the rect with the color </code></pre> <p>Th...
3
2016-08-04T17:28:38Z
38,774,049
<p>You can not do this directly because it is a syntax error to assign to <code>None</code>. </p> <p>Neither should you set an attribute on your enum class dynamically, because this will interfere with the metaclass logic that <code>Enum</code> uses to prepare your class. </p> <p>You should just use a lowercase nam...
1
2016-08-04T17:41:59Z
[ "python", "enums" ]
Installation error for language_check in python 2.7
38,773,841
<p>I have tried to install language_check library in Python 2.7 by using...</p> <pre><code>pip install language_check </code></pre> <p>and...</p> <pre><code>pip install language_check --upgrade </code></pre> <p>In both cases, I get the following error...</p> <pre><code>Collecting language-check Using cached langua...
2
2016-08-04T17:29:33Z
38,814,889
<p>I check the sources of the file <code>download_lt.py</code> (<a href="https://github.com/myint/language-check" rel="nofollow">github language_check</a>). It appears that the error occurs when you try to move the folder <code>language_check/LanguageTool-X.Y</code> with the command <a href="https://docs.python.org/3/l...
2
2016-08-07T14:03:33Z
[ "python", "python-2.7", "pip", "easy-install" ]
Getting dimensions right for regression with lasagne
38,773,866
<p>I'm trying to learn a network that outputs a value in the range -1.0..1.0. There are only six features so far, all floats. I'm having real trouble getting types and shapes aligned. So far I have:</p> <pre><code>#!/usr/bin/env python3 import lasagne import numpy as np import sys import theano import theano.tensor a...
0
2016-08-04T17:31:05Z
39,149,486
<p>I copy your code and your data input , modify some thing and ran for no error.</p> <p>code: </p> <pre><code>import lasagne import numpy as np import sys import theano import theano.tensor as T infilename = 'tt_lasagne.input' #sys.argv[1] split_size = 500 epochs = 100 theano.config.exception_verbosity = 'high' ...
0
2016-08-25T15:40:45Z
[ "python", "numpy", "theano", "lasagne" ]
Odoo. TypeError: 'int' object is not iterable
38,773,888
<p>I have problrem with my code.</p> <pre><code>class SiteTrip(models.Model): _name = 'vips_vc.site_trip' name = fields.Char() session_ids = fields.One2many('vips_vc.session', 'site_trip_id', string='Session ID', index=True) url_prevouse_ids = fields.Many2one('vips_vc.url_list', string='Prevouse URL',...
0
2016-08-04T17:32:08Z
38,789,480
<p>I found error. I don't know how it working early...</p> <pre><code>result = table.create({'session_ids': sessionID, 'url_prevouse_ids': prevouseURLid, 'url_current_ids': currentURLid}) </code></pre> <p>Here present ID record from other tables(models). When I removed all data (mod...
0
2016-08-05T12:38:53Z
[ "python", "orm", "openerp", "typeerror", "odoo-8" ]
Python pinging local IPs
38,773,953
<p>So yesterday I was practicing what I learnt over the past few days and decided to create a script to scan through all the IPs in the local network and check which ones are being used.</p> <p>I used subprocess the use the "ping" command with a given timeout, and other few libraries such as docopt, threading and time...
1
2016-08-04T17:35:58Z
38,774,454
<p>Python 3.3 implements a <code>timeout=</code> keyword parameter to <code>subprocess.check_call()</code>:</p> <p><a href="https://docs.python.org/3.3/library/subprocess.html#subprocess.check_call" rel="nofollow">https://docs.python.org/3.3/library/subprocess.html#subprocess.check_call</a></p> <p>Otherwise I would u...
0
2016-08-04T18:06:41Z
[ "python", "linux", "multithreading", "command-line", "timeout" ]
Writing python function to extract matching rows from pandas dataframe
38,773,954
<pre><code>df1 = pd.DataFrame({'A' : [5,5,5,5], 'B' : [4,2,1, 1], 'C' : [2,2,7,1]}) </code></pre> <p>I want to get those rows in df1 based on foll. condition:</p> <pre><code>df1.loc[(df1['A'] == 5) &amp; (df1['B'] == 4) &amp; (df1['C'] == 2)] </code></pre> <p>How can I make it more generic i.e. I want to have a func...
1
2016-08-04T17:35:58Z
38,774,119
<p>You need something like this,filterdf is your function :</p> <pre><code>import pandas as pd df1 = pd.DataFrame({'A' : [5,5,5,5], 'B' : [4,2,1,1], 'C' : [2,2,7,1]}) def filterdf(df,col1,col2,val1,val2): return df[(df[col1] == val1) &amp; (df[col2] == val2)] df2 = filterdf(df1,'A','B',5,4) print(df2) Out: A...
1
2016-08-04T17:46:00Z
[ "python", "pandas" ]
Writing python function to extract matching rows from pandas dataframe
38,773,954
<pre><code>df1 = pd.DataFrame({'A' : [5,5,5,5], 'B' : [4,2,1, 1], 'C' : [2,2,7,1]}) </code></pre> <p>I want to get those rows in df1 based on foll. condition:</p> <pre><code>df1.loc[(df1['A'] == 5) &amp; (df1['B'] == 4) &amp; (df1['C'] == 2)] </code></pre> <p>How can I make it more generic i.e. I want to have a func...
1
2016-08-04T17:35:58Z
38,774,297
<p>Assign what you are looking for to a series</p> <pre><code># first row of df1 looking_for = df1.iloc[0, :] </code></pre> <p>Then evaluate the equality and find where all are equal in a row.</p> <pre><code>df1.eq(looking_for).all(1) 0 True 1 False 2 False 3 False dtype: bool </code></pre> <p>Use thi...
3
2016-08-04T17:56:54Z
[ "python", "pandas" ]
Writing python function to extract matching rows from pandas dataframe
38,773,954
<pre><code>df1 = pd.DataFrame({'A' : [5,5,5,5], 'B' : [4,2,1, 1], 'C' : [2,2,7,1]}) </code></pre> <p>I want to get those rows in df1 based on foll. condition:</p> <pre><code>df1.loc[(df1['A'] == 5) &amp; (df1['B'] == 4) &amp; (df1['C'] == 2)] </code></pre> <p>How can I make it more generic i.e. I want to have a func...
1
2016-08-04T17:35:58Z
38,774,330
<p>One option would be to use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.query.html" rel="nofollow"><code>query</code></a>. For the conditions in your question, this would involve constructing a string along the lines of <code>'A==5 &amp; B==4 &amp; C==2'</code>.</p> <p>To setup t...
3
2016-08-04T17:59:03Z
[ "python", "pandas" ]
Vectorizing multiple outer-products in Python?
38,773,999
<p>I have read <a href="http://stackoverflow.com/questions/35549082/summing-outer-product-of-multiple-vectors-in-einsum">this question here</a> which seems similar, but my question may be simpler. </p> <p>I have a matrix <strong>A</strong> that is of size [N x C], and a matrix <strong>X</strong> that is of size [N x D...
0
2016-08-04T17:38:49Z
38,774,356
<p>Take the nth rows outer: element (c,d) is A[n,c]*X[n,d]. Now sum over all n and you get Sum_n A[n,c]*X[n,d] which is exactly (AT.X)[c,d]</p>
1
2016-08-04T18:00:15Z
[ "python", "matrix", "vectorization" ]
How to calculate product weight in odoo?
38,774,036
<p>I want to calculate total product weight in odoo quotations and sale orders, but i don't know that how to write the method for it, can someone give me hint about it? <a href="http://i.stack.imgur.com/2g3ST.png" rel="nofollow"><img src="http://i.stack.imgur.com/2g3ST.png" alt="here is in image total weight written in...
0
2016-08-04T17:41:09Z
38,797,502
<p>Well I suggest using the following code</p> <pre><code>from openerp import models, fields, api class ProductWeight(models.Model): _inherit = 'sale.order.line' th_weight = fields.Float(string='Weight', store=True, related='product_id.weight') clas...
2
2016-08-05T20:43:20Z
[ "python", "openerp", "odoo-8" ]
How do you access the Z axis in Tiff's when they are converted to a numpy array? The shape is only in 2 dimensions
38,774,059
<p>When you convert a Tiff to a numpy array I can't access or control the Z axis. Any help is appreciated.</p> <p>Edit: Adding code</p> <pre><code>img = Image.open("annotation_50.tif") imgarray = np.array(img) print imgarray.shape() </code></pre> <p>Results in (160,228) The x and y values are accurate but the z ax...
0
2016-08-04T17:42:44Z
38,774,509
<p>Well without seeing any of your code I don't know exactly what you are doing but here is a suggestion:</p> <pre><code> from PIL import Image import numpy as np img = Image.open('multi-tiff.tiff') #multi-tiff.tiff is your image individual_imgs = np.zeros(len_Z,len_Y,len_X) #input the proper size ...
0
2016-08-04T18:10:21Z
[ "python", "numpy", "matplotlib" ]
Get the input text from Entry widget in Tkinter and use it
38,774,071
<p>I have searched for a couple of hours but can't find someone with the same problem. My question comes after the code.</p> <pre><code>class Interface: def __init__(self, root): --- Stuff Here --- self.hEntry = Entry(lFrame) self.hEntry.bind("&lt;Return&gt;", self.aMethodToGetT...
-1
2016-08-04T17:43:20Z
38,775,103
<p>don't know if would work, but have you tried with lambda? something like:</p> <pre><code>lambda event, h = event.widget.get(): self.aMethodToGetText(event) </code></pre>
-2
2016-08-04T18:43:31Z
[ "python", "python-3.x", "tkinter" ]
Get the input text from Entry widget in Tkinter and use it
38,774,071
<p>I have searched for a couple of hours but can't find someone with the same problem. My question comes after the code.</p> <pre><code>class Interface: def __init__(self, root): --- Stuff Here --- self.hEntry = Entry(lFrame) self.hEntry.bind("&lt;Return&gt;", self.aMethodToGetT...
-1
2016-08-04T17:43:20Z
38,790,899
<p><strong>EDIT:</strong> Example has two entry widgets that configures the label to displays if the contents match.</p> <pre><code>import tkinter as tk class Example(object): def __init__(self, master): self._master = master self._lbl = tk.Label(master, text = '?') self._lbl.pack(side = ...
0
2016-08-05T13:48:37Z
[ "python", "python-3.x", "tkinter" ]
Selecting using random pairs of data in pandas
38,774,118
<p>I have a very large file with three columns. The first two are integers and the third is a string. I read it in using pandas using</p> <pre><code>data = pd.read_csv("edges+stuff.txt", sep=' ', header=None, dtype={0:np.uint32, 1:np.uint32, 2:np.str}) </code></pre> <p>Here is some example fake data:</p> <pre><cod...
0
2016-08-04T17:45:58Z
38,774,349
<p>Here's one way:</p> <pre><code>df.head() Out: col1 col2 col3 0 2 0 Somestuff9 1 2 0 Somestuff0 2 1 1 Somestuff5 3 0 0 Somestuff7 4 2 0 Somestuff9 </code></pre> <p>Select one pair randomly:</p> <pre><code>df[['col1', 'col2']].drop_duplicates().sample(n=1) Ou...
2
2016-08-04T18:00:01Z
[ "python", "pandas" ]
Tasks in CELERYBEAT_SCHEDULE not being processed
38,774,128
<p>I am trying to setup a dummy task in Celery that runs every 3 seconds but have had little success so far. This is the output I am getting:</p> <p><a href="http://i.stack.imgur.com/zbTG5.png" rel="nofollow"><img src="http://i.stack.imgur.com/zbTG5.png" alt="enter image description here"></a></p> <p>I've set up cele...
0
2016-08-04T17:46:34Z
38,775,069
<p>Okay the very basic mistake I see is that most of the settings you've mentioned in your <code>settings.py</code> need to go in <code>celery.py</code></p> <p>Specially the <code>CELERYBEAT_SCHEDULE</code></p> <p>You are doing everything write, its just that your Celery is waiting for a task, which it is never recei...
1
2016-08-04T18:41:51Z
[ "python", "django", "celery", "django-celery" ]
Django conditional filter based on local variable
38,774,133
<p>I'm new with django and was wondering if there is a more efficient way to filter conditionally besides if statement.</p> <p>Given:</p> <pre><code>test_names = ["all"] test_types = ["a", "b", "c"] ... (more lists) </code></pre> <p>I know I can do this:</p> <pre><code>q = tests.objects.all() if test_names[0] == "...
1
2016-08-04T17:46:50Z
38,774,324
<p>You have conditions in your list, so you need <code>if</code>s for different conditions for sure. You might be able to get away with one query statement but you need to work on your lists:</p> <pre><code>test_name_filter = {} if test_names[0] == 'all' else {'name__in': test_names} test_type_filter = {} if test_type...
0
2016-08-04T17:58:30Z
[ "python", "django", "filter" ]
Slicing a MultiIndex DataFrame by multiple values from a specifid level
38,774,134
<p>I want to slice a MultiIndex <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html" rel="nofollow">DataFrame</a> by multiple values from a secondary level. For example, in the following DataFrame:</p> <pre><code> val1 val2 ind1 ind2 ind3 1 6 s1 1...
1
2016-08-04T17:46:51Z
38,774,234
<p>As with most selection from a DataFrame, you can use a mask or an indexer (<code>loc</code> in this case).</p> <p>To get the mask, you can use <code>get_level_values</code> (<a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.get_level_values.html" rel="nofollow">docs</a>) on the MultiIndex ...
3
2016-08-04T17:53:13Z
[ "python", "python-3.x", "pandas", "dataframe", "multi-index" ]
Slicing a MultiIndex DataFrame by multiple values from a specifid level
38,774,134
<p>I want to slice a MultiIndex <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html" rel="nofollow">DataFrame</a> by multiple values from a secondary level. For example, in the following DataFrame:</p> <pre><code> val1 val2 ind1 ind2 ind3 1 6 s1 1...
1
2016-08-04T17:46:51Z
38,774,266
<p>You can use an <code>IndexSlice</code>:</p> <pre><code>idx = pd.IndexSlice result = df.loc[idx[:, :, ['s1', 's3']], idx[:]] result.index = result.index.droplevel('ind3') print(result) </code></pre> <p>Output:</p> <pre class="lang-none prettyprint-override"><code> val1 val2 ind1 ind2 1 6 ...
4
2016-08-04T17:54:49Z
[ "python", "python-3.x", "pandas", "dataframe", "multi-index" ]
Tiff median filter exports as single frame OpenCV Python
38,774,135
<p>I'm trying to have a program run over a sequence of 60 frames (in a tiff file) and apply a noise reduction filter (Median) in order to clean the frames up a bit before analysis. However, my program (which takes it frame by frame) will output a single-frame tiff; why is that? How could I take care of that?</p> <pre>...
1
2016-08-04T17:46:51Z
38,774,695
<p>I think you are not re-composing your final stack correctly (not shown above?), and saving a single frame (the last frame)?</p> <p>An alternative is to forgo OpenCV and use scipy:</p> <pre><code>import numpy import scipy from scipy import ndimage a = numpy.random.randint(0,255,(100,100,60)) a.shape #(100L, 100L, ...
1
2016-08-04T18:20:28Z
[ "python", "opencv", "numpy", "tiff" ]
Django Select widget not updating in UpdateView
38,774,209
<p>In my Django program, I have an UpdateView that takes an Event object (one of my models) and populates the form fields with the object's data. Everything works fine for the most part, including textboxes, datepicker fields, and autocomplete boxes. The one thing that consistently does not populate is my select field:...
0
2016-08-04T17:50:57Z
38,778,072
<p>Hit me with a brick, it was that JavaScript snippet that messed me up. I switched my Select over to a jQuery Select2 widget so I could set a placeholder label; the only reason I needed that snippet in the first place.</p> <p>Case closed!</p>
0
2016-08-04T21:56:39Z
[ "jquery", "python", "django" ]
http request and regex in Python for HTML parser
38,774,213
<p>When I execute the script, the result is empty. Why? The script connected with a site and parse html tag <code>&lt;a&gt;</code>:</p> <pre><code>#!/usr/bin/python3 import re import socket import urllib, urllib.error import http.client import sys conn = http.client.HTTPConnection('www.guardaserie.online'); headers ...
0
2016-08-04T17:51:10Z
38,774,564
<p>It's likely the pattern you are searching for is non-existent in the read response, or it chokes at some point trying to parse html.</p> <pre><code>re.search( 'href="(.*)" class="box-link-serie"', str(response.read()), re.M | re.I ) </code></pre> <p>Using something more generic or another parser method will likely...
1
2016-08-04T18:13:21Z
[ "python", "get", "http.client" ]
Emails are not getting received by the user while using celery with Django
38,774,347
<p>I am using Django1.8.2, celery3.1.23 and RabbitMq as the broker. I am using Amazon ses for email. Now when I'm sending email from django shell it is getting received by the users but when I schedule it through celery it's getting received.</p> <p>here is project files:</p> <p><strong>project/src/settings/base.py</...
0
2016-08-04T18:00:00Z
38,793,865
<p>It's solved. I used post_save signal to call the task and save with the task_id.</p> <pre><code>@receiver(post_save, sender=Reminder) def send_email_signal(sender,instance, created, **kwargs): if not created: return self = instance date_time = datetime.combine(self.date,self.time) reminder_t...
0
2016-08-05T16:26:03Z
[ "python", "django", "rabbitmq", "celery", "amazon-ses" ]
Remove duplicate rows from CSV
38,774,380
<p>I have a CSV file that looks like this</p> <pre><code>red,75,right red,344,right green,3,center yellow,3222,right blue,9,center black,123,left white,68,right green,47,left purple,48,left purple,988,right pink,2677,left white,34,right </code></pre> <p>I am using Python and am trying to remove rows that have duplica...
1
2016-08-04T18:01:47Z
38,774,561
<p>You can try this :</p> <pre><code>import fileinput def main(): seen = set() # set for fast O(1) amortized lookup for line in fileinput.FileInput('1.csv', inplace=1): cell_1 = line.split(',')[0] if cell_1 not in seen: seen.add(cell_1) print line, # standard output i...
0
2016-08-04T18:13:18Z
[ "python", "csv" ]
Remove duplicate rows from CSV
38,774,380
<p>I have a CSV file that looks like this</p> <pre><code>red,75,right red,344,right green,3,center yellow,3222,right blue,9,center black,123,left white,68,right green,47,left purple,48,left purple,988,right pink,2677,left white,34,right </code></pre> <p>I am using Python and am trying to remove rows that have duplica...
1
2016-08-04T18:01:47Z
38,774,837
<p>You can simply use a dictionary where the color is the key and the value is the row. Ignore the color if it is already in the dictionary, otherwise add it and write the row to a new csv file.</p> <pre><code>import csv file_in = 'input_file.csv' file_out = 'output_file.csv' with open(file_in, 'rb') as fin, open(fi...
1
2016-08-04T18:27:51Z
[ "python", "csv" ]
PRAW Get message author?
38,774,410
<p>I'm trying to build a when I get a message on Reddit to display an alert on my device and tell it the author. Something like this: </p> <p><a href="http://i.stack.imgur.com/glCEF.png" rel="nofollow"><img src="http://i.stack.imgur.com/glCEF.png" alt="enter image description here"></a></p> <p>I tried searching for R...
0
2016-08-04T18:03:35Z
38,774,727
<p>I don't know how you couldn't find it in the PRAW docs because a quick google search "praw author" gave me this <a href="http://stackoverflow.com/a/20939233/1459669">Stack Overflow</a> answer.</p> <p>A comment has an <code>author</code> attribute, which is a <code>Redditor</code> object. And to get the name from th...
1
2016-08-04T18:21:44Z
[ "python", "reddit", "praw" ]
Python 3.x: How to compare two lists containing dictionaries where order doesn't matter
38,774,549
<p>I have nested dictionaries that may contain other dictionaries or lists. I need to be able to compare a list (or set, really) of these dictionaries to show that they are equal. </p> <p>The order of the list is not uniform. Typically, I would turn the list into a set, but it is not possible since there are values th...
2
2016-08-04T18:12:39Z
38,774,680
<p>In this case they are the same dicts so you can compare ids (<a href="https://docs.python.org/3/library/functions.html#id" rel="nofollow">docs</a>). Note that if you introduced a new <code>dict</code> whose values were identical it would still be treated differently. I.e. <code>d = {'color': 'red'}</code> would be t...
0
2016-08-04T18:19:37Z
[ "python", "python-3.x" ]
Python 3.x: How to compare two lists containing dictionaries where order doesn't matter
38,774,549
<p>I have nested dictionaries that may contain other dictionaries or lists. I need to be able to compare a list (or set, really) of these dictionaries to show that they are equal. </p> <p>The order of the list is not uniform. Typically, I would turn the list into a set, but it is not possible since there are values th...
2
2016-08-04T18:12:39Z
38,774,700
<p>You can use a simple loop to check if each of one list is in the other:</p> <pre><code>def areEqual(a, b): if len(a) != len(b): return False for d in a: if d not in b: return False return True </code></pre>
2
2016-08-04T18:20:40Z
[ "python", "python-3.x" ]
Python 3.x: How to compare two lists containing dictionaries where order doesn't matter
38,774,549
<p>I have nested dictionaries that may contain other dictionaries or lists. I need to be able to compare a list (or set, really) of these dictionaries to show that they are equal. </p> <p>The order of the list is not uniform. Typically, I would turn the list into a set, but it is not possible since there are values th...
2
2016-08-04T18:12:39Z
38,778,180
<p>If the elements in both lists are shallow, the idea of sorting them, and then comparing with equality can work. The problem with @Alex's solution is that he is only using "id" - but if instead of id, one uses a function that will sort dictionaries properly, things shuld just work:</p> <pre><code>def sortkey(element...
0
2016-08-04T22:06:48Z
[ "python", "python-3.x" ]
Python 3.x: How to compare two lists containing dictionaries where order doesn't matter
38,774,549
<p>I have nested dictionaries that may contain other dictionaries or lists. I need to be able to compare a list (or set, really) of these dictionaries to show that they are equal. </p> <p>The order of the list is not uniform. Typically, I would turn the list into a set, but it is not possible since there are values th...
2
2016-08-04T18:12:39Z
38,779,216
<p>An elegant and relatively fast solution:</p> <pre><code>class QuasiUnorderedList(list): def __eq__(self, other): """This method isn't as ineffiecient as you think! It runs in O(1 + 2 + 3 + ... + n) time, possibly better than recursively freezing/checking all the elements.""" for item in...
-1
2016-08-05T00:05:32Z
[ "python", "python-3.x" ]
Python 3.x: How to compare two lists containing dictionaries where order doesn't matter
38,774,549
<p>I have nested dictionaries that may contain other dictionaries or lists. I need to be able to compare a list (or set, really) of these dictionaries to show that they are equal. </p> <p>The order of the list is not uniform. Typically, I would turn the list into a set, but it is not possible since there are values th...
2
2016-08-04T18:12:39Z
38,779,290
<p>I suggest writing a function that turns any Python object into something orderable, with its contents, if it has any, in sorted order. If we call it <code>canonicalize</code>, we can compare nested objects with:</p> <pre><code>canonicalize(test_a) == canonicalize(test_b) </code></pre> <p>Here's my attempt at writi...
0
2016-08-05T00:17:16Z
[ "python", "python-3.x" ]
Pandas DataFrame- Finding Index Value for a Column
38,774,705
<p>I have a DataFrame that has columns such as ID, Name, Specification, Time.</p> <p>my file path to open them </p> <pre><code>mc = pd.read_csv("C:\\data.csv", sep = ",", header = 0, dtype = str) </code></pre> <p>When I checked my columns values, using</p> <pre><code>mc.coulumns.values </code></pre> <p>I found my...
2
2016-08-04T18:20:59Z
38,774,760
<p>That's utf-16 BOM, pass <code>encoding='utf-16'</code> to <code>read_csv</code> see: <a href="https://en.wikipedia.org/wiki/Byte_order_mark#Representations_of_byte_order_marks_by_encoding" rel="nofollow">https://en.wikipedia.org/wiki/Byte_order_mark#Representations_of_byte_order_marks_by_encoding</a></p> <pre><code...
2
2016-08-04T18:23:56Z
[ "python", "pandas", "dataframe" ]
write on file from serial in python in windows
38,774,745
<p>I trying to have a very simple script to read data from serial port and write it on a txt file. My data are always the same and for example look like this : '4\r\n'</p> <pre><code>import serial import time ser = serial.Serial('COM5', 9600, timeout=0) while 1: data=ser.readline() print data f = open('myfi...
0
2016-08-04T18:22:45Z
38,775,329
<p>Using the <code>'w'</code> option in <code>open()</code> tells python to delete your file first, then open it. Try changing the <code>'w'</code> to an <code>'a'</code> so that Python appends new data to the end of the file, rather than deleting the file every time.</p> <pre><code>f = open('myfile.txt', 'a') </code...
0
2016-08-04T18:57:55Z
[ "python", "windows", "serial-port", "writefile" ]
Difference between Kivy camera and opencv camera
38,774,748
<p>What is the difference between Kivy Camera and opencv ? I am asking this because in Kivy Camera the image gets adjusted according to frame size but in opencv this does not happen. Also I am not able to do motion detection in kivy camera whereas I found a great tutorial for motion detection on opencv. If someone can ...
0
2016-08-04T18:23:08Z
38,774,932
<p>opencv is a computer vision framework (hence the c-v) which can interact with device cameras. Kivy is a cross-platform development tool which can interact with device cameras. It makes sense that there are good motion detection tutorials for opencv but not kivy camera, since this isnt really what kivy is for. </p>...
0
2016-08-04T18:34:09Z
[ "python", "opencv", "camera", "kivy", "motion-detection" ]
Django 1.9 FormView never reach get_context_data
38,774,792
<p>I have a FormView called LeagueTransferView based on a form LeagueTransferForm.</p> <p>I'm trying to override get_context_data to add extra players to render in the template.</p> <p>But get_context_data is never reached. It's working fine on other views like, DetailView, ListView,...</p> <p>I'm missing something?...
1
2016-08-04T18:25:52Z
38,774,968
<p>Your code is never reaching <code>get_context_data()</code> because you have overridden the <code>get()</code> method and not calling the <code>get_context_data()</code> function there. You need to manually call the <code>get_context_data()</code> function at the time of passing <code>context</code> to <code>render(...
3
2016-08-04T18:36:06Z
[ "python", "django", "django-forms", "django-views" ]
Multi-indexing plotting with Matplotlib
38,774,805
<p>I am trying to graph multi indexing plot using matplotlib. However, I was struggling to find the exact code from the previously answered code. Can anyone assist me how can I produce similar graph.</p> <p><a href="http://i.stack.imgur.com/FJ35y.png" rel="nofollow"><img src="http://i.stack.imgur.com/FJ35y.png" alt="e...
0
2016-08-04T18:26:18Z
38,796,413
<p>I created a DataFrame from some of the values I see on your attached plot and plotted it.</p> <pre><code>index = pd.MultiIndex.from_tuples(tuples=[(2011, ), (2012, ), (2016, 'M'), (2016, 'J')], names=['year', 'month']) df = pd.DataFrame(index=index, data={'1': [10, 140, 6, 9], '2': [23, 31, 4, 5], '3': [33, 23, 1, ...
1
2016-08-05T19:19:23Z
[ "python", "pandas", "matplotlib", "bar-chart" ]
Pandas Datetime Formatting
38,774,823
<p>Currently my dates are formatted as a string. I was able to get the string converted to date time using the following:</p> <pre><code>df['submitted_on'] = df['submitted_on'].apply(lambda x: dt.datetime.strptime(x, '%Y-%m-%d %H:%M:%S.%f')) </code></pre> <p>I would like to remove the time stamp, but I am having an ...
2
2016-08-04T18:27:01Z
38,774,902
<p>You can use <code>normalize</code> (<a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DatetimeIndex.normalize.html" rel="nofollow">docs</a>).</p> <pre><code>dti = pd.DatetimeIndex(start='today', periods=4, freq='D') dti </code></pre> <p>outputs</p> <pre><code>DatetimeIndex(['2016-08-04 14:30:3...
2
2016-08-04T18:32:07Z
[ "python", "datetime", "pandas" ]
Pandas Datetime Formatting
38,774,823
<p>Currently my dates are formatted as a string. I was able to get the string converted to date time using the following:</p> <pre><code>df['submitted_on'] = df['submitted_on'].apply(lambda x: dt.datetime.strptime(x, '%Y-%m-%d %H:%M:%S.%f')) </code></pre> <p>I would like to remove the time stamp, but I am having an ...
2
2016-08-04T18:27:01Z
38,775,038
<p>You could convert the <code>Timestamp</code> object to <code>datetime.datetime</code> object and extract the <code>datetime.date</code> part as shown:</p> <pre><code>In [7]: import pandas as pd In [8]: print(pd.Timestamp('2015-02-26 16:45:36.0').to_datetime().date()) 2015-02-26 &lt;class 'datetime.date'&gt; </code...
2
2016-08-04T18:40:05Z
[ "python", "datetime", "pandas" ]
Pandas Datetime Formatting
38,774,823
<p>Currently my dates are formatted as a string. I was able to get the string converted to date time using the following:</p> <pre><code>df['submitted_on'] = df['submitted_on'].apply(lambda x: dt.datetime.strptime(x, '%Y-%m-%d %H:%M:%S.%f')) </code></pre> <p>I would like to remove the time stamp, but I am having an ...
2
2016-08-04T18:27:01Z
38,775,471
<pre><code>s = pd.Series(['2010-01-01 10:00', '2010-06-01 11:00']) pd.to_datetime(pd.to_datetime(s).dt.date) </code></pre>
2
2016-08-04T19:06:44Z
[ "python", "datetime", "pandas" ]
I keep getting a read issue [Errno 22] Invalid argument
38,774,907
<p>I have tried putting the <code>(r"F:\Server\ ... "r")</code> it says:</p> <pre>file.write(float(u) + '\n') TypeError: unsupported operand type(s) for +: 'float' and 'str'. </pre> <p>When I don't put the <code>r</code> were it is it will double \\ on me saying:</p> <pre>read issue [Errno 22] Invalid argument: 'F:\...
-1
2016-08-04T18:32:26Z
38,775,282
<p>You have two separate errors here.</p> <h1>1: Filename with Escape Characters</h1> <p>This error:</p> <blockquote> <p>read issue [Errno 22] Invalid argument: 'F:\Server\Frames\Server_Stats_GUI\x08yteS-F_FS_Input.toff'.</p> </blockquote> <p>Is in the open() function.</p> <p>Your filename has an escape charac...
0
2016-08-04T18:55:30Z
[ "python", "windows" ]
Prevent numpy from creating a multidimensional array
38,774,922
<p>NumPy is really helpful when creating arrays. If the first argument for <code>numpy.array</code> has a <code>__getitem__</code> and <code>__len__</code> method these are used on the basis that it might be a valid sequence.</p> <p>Unfortunatly I want to create an array containing <code>dtype=object</code> without Nu...
2
2016-08-04T18:33:23Z
38,776,596
<p>A workaround is of course to create an array of the desired shape and then copy the data:</p> <pre><code>In [19]: lst = [Test([1, 2, 3]), Test([3, 2, 1])] In [20]: arr = np.empty(len(lst), dtype=object) In [21]: arr[:] = lst[:] In [22]: arr Out[22]: array([Test([1, 2, 3]), Test([3, 2, 1])], dtype=object) </code>...
3
2016-08-04T20:10:43Z
[ "python", "arrays", "numpy" ]
Prevent numpy from creating a multidimensional array
38,774,922
<p>NumPy is really helpful when creating arrays. If the first argument for <code>numpy.array</code> has a <code>__getitem__</code> and <code>__len__</code> method these are used on the basis that it might be a valid sequence.</p> <p>Unfortunatly I want to create an array containing <code>dtype=object</code> without Nu...
2
2016-08-04T18:33:23Z
38,776,674
<p>This behavior has been discussed a number of times before (e.g. <a href="http://stackoverflow.com/questions/36663919/override-a-dict-with-numpy-support">Override a dict with numpy support</a>). <code>np.array</code> tries to make as high a dimensional array as it can. The model case is nested lists. If it can ite...
2
2016-08-04T20:15:27Z
[ "python", "arrays", "numpy" ]
Reshape array to rgb matrix
38,774,977
<p>I have loaded a 100x100 rgb image in a numpy array. I then converted it to a 30000x1 numpy array to pass through a machine learning model. The output of this model is also a 30000x1 numpy array. How do I convert this array back to a numpy array of 100x100 3-tuples so I can print the generated rgb image?</p> <p>If t...
2
2016-08-04T18:36:34Z
38,794,395
<p>Answering because I can't comment. Try <code>reshape((3, 100, 100))</code></p> <pre><code>a = np.random.random((3, 2, 2)) # array([[[ 0.28623689, 0.96406455], # [ 0.55002183, 0.73325715]], # # [[ 0.44293834, 0.08118479], # [ 0.28732176, 0.94749812]], # # [[ 0.40169829, 0.0265604 ]...
0
2016-08-05T17:00:17Z
[ "python", "arrays", "numpy" ]
Installing OpenCV/python on Amazon Linux (apache)?
38,775,044
<p>I am trying to use OpenCV on a python web application I created on an Amazon EC2 Micro instance running apache.</p> <p>I've got everything configured and working, except OpenCV isn't installing. This is the output I got from the Apache Error Log.</p> <pre><code>[Thu Aug 04 18:31:54 2016] [error] [client 72.219.147...
2
2016-08-04T18:40:29Z
38,867,965
<p>tested and working on <code>amzn-ami-hvm-2016.03.1.x86_64-gp2</code></p> <pre><code>sudo yum install git cmake gcc-c++ numpy python-devel sudo pip install --upgrade pip sudo ln -rs /usr/local/bin/pip /usr/bin/ wget https://pypi.python.org/packages/18/eb/707897ab7c8ad15d0f3c53e971ed8dfb64897ece8d19c64c388f44895572/...
4
2016-08-10T08:26:13Z
[ "python", "apache", "opencv", "amazon-web-services", "amazon-ec2" ]
Slicing list inside a method (Python 3)
38,775,048
<p>I have a method like the following:</p> <pre><code>def slice_list(my_list, slice_point): my_list = my_list[:slice_point] print("Inside method: ", my_list) return </code></pre> <p>I have a test for it like the following:</p> <pre><code>if __name__ == "__main__": my_list = [1,2,3,4,5] slice_po...
2
2016-08-04T18:40:41Z
38,775,109
<p>Try this instead:</p> <pre><code>my_list[:] = my_list[:slice_point] </code></pre> <p>Your old method just points the name <code>my_list</code> at a new object, i.e. at the copy returned by the slice. </p> <p>The suggestion I've proposed above, however, modifies the object which <code>my_list</code> originally po...
3
2016-08-04T18:43:38Z
[ "python", "list", "python-3.4", "slice" ]
How does object.__getattribute__ avoid a RuntimeError?
38,775,062
<p>In the rare cases that an object's <code>__getattribute__</code> method must be overridden, a common mistake is to try and return the attribute in question like so:</p> <pre><code>class WrongWay: def __getattribute__(self, name): # Custom functionality goes here return self.__dict__[name] </code...
2
2016-08-04T18:41:25Z
38,775,389
<blockquote> <p>at the end of the line somebody will eventually have to return <code>self.</code><em>something</em>, and by definition that attribute reference must first get through the child's <code>__getattribute__()</code> method.</p> </blockquote> <p>That's not correct. <code>object.__getattribute__</code> is n...
2
2016-08-04T19:01:06Z
[ "python", "recursion", "magic-methods" ]
How to avoid defunct processes with python fork?
38,775,178
<p>In python3 I am creating forked child processes, which I exit - I think - correctly. Here is some code example:</p> <pre><code>import os child_pid = os.fork() if child_pid == 0: print("I am in the child with PID "+str(os.getpid())) # doing something a = 1+1 print("Ending child with PID "+str(os.get...
0
2016-08-04T18:48:45Z
38,775,811
<p>You can use the double fork idiom if you don't want the parent to wait. (See <a href="http://stackoverflow.com/questions/881388/what-is-the-reason-for-performing-a-double-fork-when-creating-a-daemon">What is the reason for performing a double fork when creating a daemon?</a>)</p> <p>The basic idea is for the paren...
0
2016-08-04T19:27:05Z
[ "python", "python-3.x" ]
Efficient ndarray operations
38,775,253
<p>I'm converting some Matlab code in Python. I need to do some matrix manipulation. My matrix (A) is (right now) a 65x3 matrix. However, the number of rows is variable depending on what step I'm at in the program.</p> <p>In Matlab, the code I'm working on is:</p> <pre><code>output = inv(A'*A) * A'; </code></pre> <p...
2
2016-08-04T18:53:18Z
38,775,309
<p>You can use a the <code>T</code> attribute (transposes the array). Also, if using Python 3.5, you can use <code>@</code> for the dot product (see <a href="https://docs.python.org/3/whatsnew/3.5.html#whatsnew-pep-465" rel="nofollow">PEP 465</a> for details).</p> <pre><code>output = np.linalg.inv(A.T @ A) @ A.T </cod...
1
2016-08-04T18:56:39Z
[ "python", "matlab", "numpy", "matrix" ]
Python socket, send an int, which informs the client about the length of the following data
38,775,307
<p>I have a server, which listens for connections on a socket and once the client connects a dictionary of varying size is sent.</p> <p>To inform the client, how many bytes it should receive, I want to send the size of the dictionary first.</p> <pre><code>dic={'asdf':'1234', 'ghkj':'5678'} serialized_dict = pickle.du...
0
2016-08-04T18:56:38Z
38,775,371
<p>I wouldn't do it like this. The general way to alert a socket buffer of the end of a stream is to send a delimiter/end marker of some sort after the dictionary and have the client look for the end marker. Once the end marker is received they know they have received the end of the dictionary. </p> <p>I believe in SM...
0
2016-08-04T18:59:54Z
[ "python", "sockets", "serialization" ]
Use SQL functions like substr(X, Y, Z) in SQLAlchemy query
38,775,417
<p>I could not figure out how to use SQLite's functions like <a href="https://www.sqlite.org/lang_corefunc.html" rel="nofollow">substr(X, Y, Z)</a> with SQLAlchemy's query expression syntax. I am aware that I could use raw queries, but that would make it more difficult to reuse my where clauses. Here is my use case:</p...
0
2016-08-04T19:02:34Z
38,775,597
<p>Ok. This was way too simple.</p> <pre><code>from sqlalchemy.sql import func exif_conditions = [func.substr(Blob.header, 7, 4) == b'Exif'] </code></pre>
1
2016-08-04T19:15:27Z
[ "python", "sqlite", "sqlalchemy", "sql-function" ]
Is there a way to use compiled C modules with zipimport?
38,775,427
<p>When I have a python shared object file <em>(<code>.so</code>)</em> in my sys.path, I can simply do :</p> <pre><code>import _ctypes </code></pre> <p>And it will import <code>python2.7/lib-dynload/_ctypes.so</code>.</p> <p>However, if I use a zipfile called <code>tmp.zip</code> that contains :</p> <pre><code>He...
-5
2016-08-04T19:03:28Z
38,779,287
<p>It seems I have definitely huge problems at reading texts entirely :</p> <blockquote> <p><a href="https://docs.python.org/2/library/zipimport.html" rel="nofollow">This module adds the ability to import Python modules (<code>*.py</code>, <code>*.py[co]</code>) and packages from ZIP-format archives.</a>.</p> </blo...
-2
2016-08-05T00:16:53Z
[ "python", "linux", "cpython" ]
Python How to top list of dicts up
38,775,434
<pre><code>[{'month': 7.0, 'sumd': 11}, {'month': 8.0, 'sumd': 20}] </code></pre> <p>I have this list. This is aggregation of months and some values. How to top it up by 0 to get something like this?</p> <pre><code>[0, 0, 0, 0, 0, 0, 0, 11, 20, 0, 0, 0, 0] </code></pre> <p>EDIT This first list has dicts with only th...
-1
2016-08-04T19:04:10Z
38,775,599
<p>If i understood what you want to do, the result would be a list of 12 elements not 13.</p> <p>So if you cant to put the value of the month number (value of the month key) in the array representing a year (12 elements) you can do this :</p> <pre><code>month_dictionaries = [{'month': 7.0, 'sumd': 11}, {'month': 8.0,...
1
2016-08-04T19:15:28Z
[ "python" ]
Python How to top list of dicts up
38,775,434
<pre><code>[{'month': 7.0, 'sumd': 11}, {'month': 8.0, 'sumd': 20}] </code></pre> <p>I have this list. This is aggregation of months and some values. How to top it up by 0 to get something like this?</p> <pre><code>[0, 0, 0, 0, 0, 0, 0, 11, 20, 0, 0, 0, 0] </code></pre> <p>EDIT This first list has dicts with only th...
-1
2016-08-04T19:04:10Z
38,775,611
<p>For the sample you have provided this should work:</p> <pre><code>values = [0,0,0,0,0,0,0,0,0,0,0,0] month_values = [{'month': 7.0, 'sumd': 11}, {'month': 8.0, 'sumd': 20}] for m in month_values: values[(int(m['month'])-1)]=m['sumd'] </code></pre>
0
2016-08-04T19:16:02Z
[ "python" ]
Python How to top list of dicts up
38,775,434
<pre><code>[{'month': 7.0, 'sumd': 11}, {'month': 8.0, 'sumd': 20}] </code></pre> <p>I have this list. This is aggregation of months and some values. How to top it up by 0 to get something like this?</p> <pre><code>[0, 0, 0, 0, 0, 0, 0, 11, 20, 0, 0, 0, 0] </code></pre> <p>EDIT This first list has dicts with only th...
-1
2016-08-04T19:04:10Z
38,775,623
<p>I'll take <code>sumd</code> to imply that you want to add up overlapping months. And you can fix the indexing to get 12 months, not 13</p> <pre><code>data = [{'month': 7.0, 'sumd': 11}, {'month': 8.0, 'sumd': 20}] months = [0]*12 for d in data: idx = int(d['month']) - 1 v = d['sumd'] months[idx] += v ...
0
2016-08-04T19:16:45Z
[ "python" ]
Add new functions to a class with import
38,775,464
<p>I have a class which has the function of parsing data.</p> <pre><code>class DataContainer(object): def parser1(data): # Handle data in one way self.parsed_data = parsed_data def parser2(data): # Handle data another way self.parsed_data = parsed_data </code></pre> <p>The par...
1
2016-08-04T19:06:02Z
38,775,650
<p>It depends on exactly how you want to use your object, but I would <code>import parsers</code>, and then have your DataContainer serve as an interface to those functions</p> <pre class="lang-py prettyprint-override"><code>import parsers class DataContainer(object): def __init__(self): # If this kind o...
1
2016-08-04T19:18:31Z
[ "python" ]
Questions about read_csv and str dtype
38,775,494
<p>I have a large text file where the columns are of the following form:</p> <pre><code>1255 32627 some random stuff which might have numbers 1245 </code></pre> <p>1.I would like to use <code>read_csv</code> to give me a data frame with three columns. The first two columns should be dtype uint32 and the third just ha...
1
2016-08-04T19:08:36Z
38,776,163
<p>You can use the Series.str.cat method, documentation for which is available <a href="http://pandas.pydata.org/pandas-docs/version/0.17.1/generated/pandas.Series.str.cat.html" rel="nofollow">here</a>:</p> <pre><code>df = pd.read_csv("foo.txt", sep=' ', header=None) # Create a new column which concatenates all colum...
1
2016-08-04T19:46:06Z
[ "python", "pandas" ]
Questions about read_csv and str dtype
38,775,494
<p>I have a large text file where the columns are of the following form:</p> <pre><code>1255 32627 some random stuff which might have numbers 1245 </code></pre> <p>1.I would like to use <code>read_csv</code> to give me a data frame with three columns. The first two columns should be dtype uint32 and the third just ha...
1
2016-08-04T19:08:36Z
38,776,506
<ol> <li><p>Is there a reason you need to use <code>pd.read_csv()</code>? The code below is straightforward and easily modifies your column values to your requirements.</p> <pre><code>from numpy import uint32 from csv import reader from pandas import DataFrame file = 'path/to/file.csv' with open(file, 'r') as f: ...
1
2016-08-04T20:04:50Z
[ "python", "pandas" ]
Python, Tkinter; How to use grid_forget() when deselecting a check box?
38,775,523
<p>Hello I have a script I am working on and I am having a problem trying to get a frame to hide when a check box is deselected. The script I am working on uses a check button to call a command to show a frame containing some text entry fields. The problem is when I deselect the check box the frame does not disappear. ...
1
2016-08-04T19:11:03Z
38,776,033
<p>Would something like this work?</p> <pre><code>def show_name3(): if self.check_var4.get() == 1: self.name3.grid(row=3, column=1, sticky='E', padx=15, pady=5, ipadx=15, ipady=5) else: self.name3.grid_forget() </code></pre> <p>It will get the value of <code>check_var</code>, which indicates i...
1
2016-08-04T19:40:16Z
[ "python", "tkinter" ]
Facebook API query on /me with access token and fields only returns status=True. What am I doing wrong?
38,775,586
<p>The following python code:</p> <pre><code> # user profile information args = { 'access_token':access_token, 'fields':'id,name', } print 'ACCESSED', urllib.urlopen('https://graph.facebook.com/me', urllib.urlencode(args)).read() </code></pre> <p>Prints the following:</p> <p><em>ACCESSED {"success":tr...
0
2016-08-04T19:14:35Z
38,775,927
<p>You have to add a <code>/</code> to the URL to get <code>https://graph.facebook.com/me/</code> instead of <code>https://graph.facebook.com/me</code>.</p> <pre><code># user profile information args = { 'access_token':access_token, 'fields':'id,name' } print 'ACCESSED', urllib.urlopen('https://graph.facebook...
-1
2016-08-04T19:32:51Z
[ "python", "facebook-graph-api" ]
Facebook API query on /me with access token and fields only returns status=True. What am I doing wrong?
38,775,586
<p>The following python code:</p> <pre><code> # user profile information args = { 'access_token':access_token, 'fields':'id,name', } print 'ACCESSED', urllib.urlopen('https://graph.facebook.com/me', urllib.urlencode(args)).read() </code></pre> <p>Prints the following:</p> <p><em>ACCESSED {"success":tr...
0
2016-08-04T19:14:35Z
38,778,700
<p>Turns out urllib.urlopen will send the data as a POST when the data parameter is provided. Facebook Graph API works using GET not POST. Change the call to trick the function into calling just a URL ( no data ):</p> <pre><code>print 'ACCESSED', urllib.urlopen('https://graph.facebook.com/me/?' + urllib.urlencode(ar...
1
2016-08-04T23:03:02Z
[ "python", "facebook-graph-api" ]
How can I merge together several pandas dataframes on a certain column without 'pandas.merge'?
38,775,588
<p>I often find myself with several pandas dataframes in the following form: </p> <pre><code>import pandas as pd df1 = pd.read_table('filename1.dat') df2 = pd.read_table('filename2.dat') df3 = pd.read_table('filename3.dat') print(df1) columnA first_values name1 342 name2 822 name3 121 name4 3434 pr...
0
2016-08-04T19:14:55Z
38,778,189
<p>Assuming that the three dataframes have the same index, you could just add columns to get the desired dataframes and not worry about merging, like so,</p> <pre><code>import pandas as pd #create the dataframe colA = ['name1', 'name2', 'name3', 'name4'] first = [ 342, 822, 121, 3434] second = [ 8,1,1,2] third = [ 91...
0
2016-08-04T22:07:19Z
[ "python", "pandas", "dataframe", "merge", "concatenation" ]
How can I merge together several pandas dataframes on a certain column without 'pandas.merge'?
38,775,588
<p>I often find myself with several pandas dataframes in the following form: </p> <pre><code>import pandas as pd df1 = pd.read_table('filename1.dat') df2 = pd.read_table('filename2.dat') df3 = pd.read_table('filename3.dat') print(df1) columnA first_values name1 342 name2 822 name3 121 name4 3434 pr...
0
2016-08-04T19:14:55Z
38,780,348
<p>You can set columnA as the index and concat (reset index at the end):</p> <pre><code>dfs = [df1, df2, df3] pd.concat([df.set_index('columnA') for df in dfs], axis=1).reset_index() Out: columnA first_values second_values third_values 0 name1 342 8 910 1 name2 822...
1
2016-08-05T02:50:55Z
[ "python", "pandas", "dataframe", "merge", "concatenation" ]
Flask deployed with twistd: Failed to load application: 'NoneType' object has no attribute 'startswith'
38,775,663
<p>I am trying to <a href="http://twistedmatrix.com/documents/current/core/howto/application.html" rel="nofollow">deploy my Twisted application using .tac files and twistd</a></p> <p>I tried to deploy it with the command line:</p> <p><code>twistd -y service.tac</code></p> <p>I have the error:</p> <p>...</p> <pre><...
0
2016-08-04T19:19:02Z
38,789,837
<p>Your application import_name can't be identified properly in *.tac file. If you create flask application in *.py file and import it in *.tac it will work just fine.</p> <p>But you also need another list of <a href="http://twistedmatrix.com/documents/current/web/howto/web-in-60/wsgi.html" rel="nofollow">instructions...
0
2016-08-05T12:57:50Z
[ "python", "flask", "twisted", "daemon", "twisted.web" ]
multiprocessing numpy not defined error
38,775,754
<p>I am using the following test code:</p> <pre><code>from pathos.multiprocessing import ProcessingPool as Pool import numpy def foo(obj1, obj2): a = obj1**2 b = numpy.asarray(range(1,5)) return obj1, b if __name__ == '__main__': p = Pool(5) res = p.map(foo, [1,2,3], [4,5,6]) </code></pre> <p>It gi...
-1
2016-08-04T19:23:51Z
38,777,032
<p>It seems like imports are not shared between processes. Therefore you need to <code>import numpy</code> in all your processes seperatly.</p> <p>In your case this means adding the <code>import numpy</code> in your <code>foo</code> function. Processes are not light-weight so the <code>import</code> won't slow you dow...
0
2016-08-04T20:39:15Z
[ "python", "numpy", "multiprocessing", "pathos" ]
Is there a straightforward way to write to a file open in r+ mode without overwriting existing bytes?
38,775,760
<p>I have a text file test.txt, with the following contents:</p> <pre><code>Thing 1. string </code></pre> <p>And I'm creating a python file that will increment the number every time it gets run without affecting the rest of the string, like so.</p> <p>Run once:</p> <pre><code>Thing 2. string </code></pre> <p>Run t...
0
2016-08-04T19:24:06Z
38,775,904
<p>Unfortunately, what you want to do is not possible. This is a limitation at a lower level than Python, in the operating system. Neither the Unix nor the Windows file access API offers any way to insert new bytes in the middle of a file without overwriting the bytes that were already there.</p> <p>Reading the rest...
2
2016-08-04T19:31:48Z
[ "python", "file", "io" ]
Is there a straightforward way to write to a file open in r+ mode without overwriting existing bytes?
38,775,760
<p>I have a text file test.txt, with the following contents:</p> <pre><code>Thing 1. string </code></pre> <p>And I'm creating a python file that will increment the number every time it gets run without affecting the rest of the string, like so.</p> <p>Run once:</p> <pre><code>Thing 2. string </code></pre> <p>Run t...
0
2016-08-04T19:24:06Z
38,776,272
<p>No, the disk doesn't work like you think it does. You have to remember that your file is stored on disk as one contiguous chunk of data* Your disk happens to be wound up in a great big spool, a bit like a record, but if you were to unwind your file, you'd get something that looks like this:</p> <pre><code>+--------...
1
2016-08-04T19:52:29Z
[ "python", "file", "io" ]
How to write a construction of code as a function
38,775,794
<p>I am new to programming and python and would like to write the following piece of code as a function using the 'def' 'return' construction:</p> <pre><code>df.loc[df['DATE_INT'].shift(-1) - df['DATE_INT'] == 1, 'CONSECUTIVE_DAY'] = True df.loc[(df['DATE_INT'].shift(-1) - df['DATE_INT'] == 1) | (df['DATE_INT'].shift(...
2
2016-08-04T19:26:12Z
38,776,195
<pre><code>def ConsecutiveID(df): df = df.copy() cond1 = df['DATE_INT'].shift(-1) - df['DATE_INT'] == 1 cond2 = df['DATE_INT'].shift(1) - df['DATE_INT'] == -1 df.loc[cond1 | cond2, 'CONSECUTIVE_DAY'] = True return df </code></pre>
2
2016-08-04T19:48:02Z
[ "python", "python-2.7", "function", "pandas", "split-apply-combine" ]
wxPython return value from Wizard to calling Frame
38,775,804
<p>My problem is as follows:</p> <p>I am designing a wizard for the construction of an object to be added to a list of objects in the calling frame of my program. At the end of the wizard I would like to pass the newly created object back to the calling frame to be inserted into the list. In order to simulate this b...
0
2016-08-04T19:26:39Z
38,837,666
<p>I was able to solve this problem through the use of the "pubsub" capability within the wxPython library. Specifically, I added a pub.subscribe() instance immediately prior to the instantiation of my wizard within the calling frame. Inside of the wizard I pass the value via pub.sendMessage() just before destroying ...
0
2016-08-08T20:07:09Z
[ "python", "events", "wxpython", "frame", "wizard" ]
Python pandas calculate time until value in a column is greater than it is in current period
38,775,814
<p>I have a pandas dataframe in python with several columns and a datetime stamp. I want to create a new column, that calculates the time until output is less than what it is in the current period.</p> <p>My current table looks something like this:</p> <pre><code> datetime output 2014-05-01 01:00:00 ...
4
2016-08-04T19:27:07Z
38,776,309
<pre><code>upper_triangle = np.triu(df.output.values &lt; df.output.values[:, None]) df['s_until_dec'] = df['datetime'][upper_triangle.argmax(axis=1)].values - df['datetime'] df.loc[~upper_triangle.any(axis=1), 's_until_dec'] = np.nan df datetime output s_until_dec 0 2014-05-01 01:00:00 3 ...
3
2016-08-04T19:54:24Z
[ "python", "datetime", "pandas", "time" ]