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 |
|---|---|---|---|---|---|---|---|---|---|
Dependant subqueries in Django | 38,596,189 | <p>I'm been bashing my head against the wall trying to make this query using the Django ORM, I searched everywhere but couldn't find an answer.
This is my model.</p>
<pre><code>class Decision(models.Model):
ACTION_CHOICES = [('include', _('Include')), ('exclude', _('Exclude'))]
user = models.ForeignKey(setting... | 0 | 2016-07-26T17:19:16Z | 38,597,159 | <p>If the dataset is small, you could make multiple passes, but that is not a very good idea.</p>
<p>A couple of options, depending on the database you are using.</p>
<p>1) You can change the sql to use rank or dense_rank function to make the query much simpler.</p>
<pre><code>select decision.id, decision.content_ty... | 0 | 2016-07-26T18:16:39Z | [
"python",
"sql",
"django-queryset"
] |
Can I use annotation in django model like this and how? | 38,596,356 | <p>models.py</p>
<pre><code>matches = models.ManyToManyField('Matches')
...
def get_rating(self):
from django.db.models import Sum, Value, IntegerField
from django.db.models.functions import Coalesce
return self.matches.annotate(rating=Coalesce(Sum('matches__rating_difference'), Value(0), output_field=IntegerFi... | 1 | 2016-07-26T17:28:39Z | 38,612,363 | <p><strong>it works</strong></p>
<p>models.py</p>
<pre><code>matches = models.ManyToManyField('Matches')
...
def get_rating(self):
from django.db.models import Sum, Value, IntegerField
from django.db.models.functions import Coalesce
return self.matches.aggregate(rating=Coalesce(Sum('rating_difference'), Value(... | 0 | 2016-07-27T12:00:49Z | [
"python",
"django",
"django-models",
"django-templates"
] |
Python usersite directory points to file that doesn't exist | 38,596,404 | <p>I have downloaded and installed python modules before with no problem. Recently, however, none of the modules(They did install correctly) I have installed have been importable.</p>
<p>The modules installed where I expected them to - C:\Python27\lib\site-packages, and I have a .pth file created in that directory tha... | 0 | 2016-07-26T17:32:10Z | 38,596,660 | <p>Add PYTHONPATH as system variable and add all the desired paths as values to that variable</p>
| 0 | 2016-07-26T17:48:02Z | [
"python",
"windows"
] |
Python: how to retain the file extension when renaming files with os? | 38,596,511 | <p>Say I have a folder with n <code>csv</code> files which I want to rename. The new filename is going to be something like <code>ABxxxx</code>, with <code>xxxx</code> being a progressive number from 1 to 1000.</p>
<p><strong>While doing this, how can I retain the original file extension, which is <code>csv</code>?</s... | 0 | 2016-07-26T17:38:38Z | 38,596,535 | <p>You can simply append <code>'.csv'</code> to your new filename:</p>
<pre><code>os.rename(file, newname + '.csv')
</code></pre>
<p>In general (for any file type), a better way to do this would be to get the existing extension first using <a href="https://docs.python.org/2/library/os.path.html#os.path.splitext" rel=... | 3 | 2016-07-26T17:39:51Z | [
"python",
"csv",
"file-extension",
"file-rename"
] |
Python: how to retain the file extension when renaming files with os? | 38,596,511 | <p>Say I have a folder with n <code>csv</code> files which I want to rename. The new filename is going to be something like <code>ABxxxx</code>, with <code>xxxx</code> being a progressive number from 1 to 1000.</p>
<p><strong>While doing this, how can I retain the original file extension, which is <code>csv</code>?</s... | 0 | 2016-07-26T17:38:38Z | 38,596,807 | <p>Use <code>os.path.splitext</code> to build a tuple of <code>(basepath, extension)</code> and <code>enumerate</code> to generate your "uniquifier". Now you can just use vanilla string formatting to glue it together</p>
<pre><code>for i in subdir:
temp_dir=r''+i
os.chdir(temp_dir)
a='A'
b='B'
for ... | 1 | 2016-07-26T17:56:42Z | [
"python",
"csv",
"file-extension",
"file-rename"
] |
Pop value from dictionary stored in Flask session | 38,596,514 | <p>Here is my session variable,</p>
<pre><code>session['data'] = json.loads(request.data.decode())
print(session.pop('data', None))
</code></pre>
<p>Print looks like this:</p>
<pre><code>{u'mark': u'all', u'chr': u'1A', u'distmin': 5, u'distmax': 10}
</code></pre>
<p>My question is, how to subset this dict,</p>
<p... | 0 | 2016-07-26T17:38:55Z | 38,598,101 | <p>That isn't how Python's mappings work. <code>data["mark"]</code> is a valid key. To access nested mappings, you need to specify the keys separately.</p>
<pre><code>session['data']['mark'] = 'spam'
</code></pre>
<p>The key used for <code>pop</code> should match that for <code>__getitem__</code>. Just as you don't u... | 3 | 2016-07-26T19:13:25Z | [
"python",
"session",
"flask"
] |
Removing certain rows in Pandas Dataframe by string format | 38,596,519 | <p>I have a Pandas dataframe with a column called Zip Code. The column is an object data type and some rows are not in proper zip code format. I would like to remove rows that do not contain ##### format zipcode. </p>
<pre><code> Subscriber Type Zip Code
0 Subscriber 94040
1 Customer 11231... | 2 | 2016-07-26T17:39:07Z | 38,596,575 | <p>try this:</p>
<pre><code>In [23]: df = df[df['Zip Code'].str.contains(r'^\d{5}$')]
In [24]: df
Out[24]:
Subscriber Type Zip Code
0 Subscriber 94040
1 Customer 11231
2 Customer 11231
</code></pre>
<p>Explanation:</p>
<pre><code>In [22]: df['Zip Code'].str.contains(r'^\d{5}$')
Out[22]... | 3 | 2016-07-26T17:41:50Z | [
"python",
"pandas",
"dataframe"
] |
Sympy algebraic solution to series summation | 38,596,569 | <p>I am trying to solve for <code>C</code> in the following equation</p>
<p><a href="http://i.stack.imgur.com/zcTYW.gif" rel="nofollow"><img src="http://i.stack.imgur.com/zcTYW.gif" alt="enter image description here"></a></p>
<p>I can do this with <code>sympy</code> for an enumrated number of <code>x's</code>, e.g <c... | 2 | 2016-07-26T17:41:34Z | 38,597,392 | <p>Thanks to @bryans for pointing me in the direction of <code>Sum</code>. Elaborating on his comment, here is one solution that seems to work. As I am fairly new to <code>sympy</code> if anyone has a more concise approach please share.</p>
<pre><code>from sympy import summation, symbols, solve, Function, Sum
alpha, ... | 1 | 2016-07-26T18:29:52Z | [
"python",
"sympy"
] |
Using Python and elasticsearch, how can I loop through the returned JSON object? | 38,596,580 | <p>My code is as follows:</p>
<pre><code>import json
from elasticsearch import Elasticsearch
es = Elasticsearch()
resp = es.search(index="mynewcontacts", body={"query": {"match_all": {}}})
response = json.dumps(resp)
data = json.loads(response)
#print data["hits"]["hits"][0]["_source"]["email"]
for r... | 0 | 2016-07-26T17:42:08Z | 38,596,741 | <p>I could be wrong, but looks like you might not be starting the for loop based on the correct json item. Try:</p>
<pre><code>for row in data['hits']['hits']:
# Rest of loop here.
</code></pre>
| 1 | 2016-07-26T17:53:14Z | [
"python",
"json",
"elasticsearch"
] |
Using Python and elasticsearch, how can I loop through the returned JSON object? | 38,596,580 | <p>My code is as follows:</p>
<pre><code>import json
from elasticsearch import Elasticsearch
es = Elasticsearch()
resp = es.search(index="mynewcontacts", body={"query": {"match_all": {}}})
response = json.dumps(resp)
data = json.loads(response)
#print data["hits"]["hits"][0]["_source"]["email"]
for r... | 0 | 2016-07-26T17:42:08Z | 38,596,750 | <p>Your retrieved response <code>data</code> is a Python dictionary - if you make a <code>for</code> loop over it, it will yield the dictionary keys - in this case, teh strigns <code>timed_out</code>, <code>took</code>, <code>shards</code>, etc...</p>
<p>Aparently yu want to iterate over teh list provided in the posi... | 0 | 2016-07-26T17:53:34Z | [
"python",
"json",
"elasticsearch"
] |
Using Python and elasticsearch, how can I loop through the returned JSON object? | 38,596,580 | <p>My code is as follows:</p>
<pre><code>import json
from elasticsearch import Elasticsearch
es = Elasticsearch()
resp = es.search(index="mynewcontacts", body={"query": {"match_all": {}}})
response = json.dumps(resp)
data = json.loads(response)
#print data["hits"]["hits"][0]["_source"]["email"]
for r... | 0 | 2016-07-26T17:42:08Z | 38,597,013 | <p>What you're doing is looping through keys of the dictionary. To print each email in the response you'd do this:</p>
<pre><code>for row in data["hits"]["hits"]:
print row["_source"]["email"]
</code></pre>
<p>Also converting to json isn't necessary. This should accomplish what you're looking to do:</p>
<pre><... | 2 | 2016-07-26T18:08:25Z | [
"python",
"json",
"elasticsearch"
] |
numpy concatenate not appending new array to empty multidimensional array | 38,596,674 | <p>I bet I am doing something very simple wrong. I want to start with an empty 2D numpy array and append arrays to it (with dimensions 1 row by 4 columns).</p>
<pre><code>open_cost_mat_train = np.matrix([])
for i in xrange(10):
open_cost_mat = np.array([i,0,0,0])
open_cost_mat_train = np.vstack([open_cost_mat... | 2 | 2016-07-26T17:49:04Z | 38,596,760 | <p>You need to reshape your original matrix so that the number of columns match the appended arrays:</p>
<pre><code>open_cost_mat_train = np.matrix([]).reshape((0,4))
</code></pre>
<p>After which, it gives:</p>
<pre><code>open_cost_mat_train
# matrix([[ 0., 0., 0., 0.],
# [ 1., 0., 0., 0.],
# ... | 3 | 2016-07-26T17:53:59Z | [
"python",
"arrays",
"numpy",
"multidimensional-array",
"concatenation"
] |
numpy concatenate not appending new array to empty multidimensional array | 38,596,674 | <p>I bet I am doing something very simple wrong. I want to start with an empty 2D numpy array and append arrays to it (with dimensions 1 row by 4 columns).</p>
<pre><code>open_cost_mat_train = np.matrix([])
for i in xrange(10):
open_cost_mat = np.array([i,0,0,0])
open_cost_mat_train = np.vstack([open_cost_mat... | 2 | 2016-07-26T17:49:04Z | 38,598,378 | <p>If <code>open_cost_mat_train</code> is large I would encourage you to replace the for loop by a <strong>vectorized algorithm</strong>. I will use the following funtions to show how efficiency is improved by vectorizing loops:</p>
<pre><code>def fvstack():
import numpy as np
np.random.seed(100)
ocmt = np... | 2 | 2016-07-26T19:29:38Z | [
"python",
"arrays",
"numpy",
"multidimensional-array",
"concatenation"
] |
Tkinter text not displayed in order | 38,596,720 | <p>I wanted to display the progress status of a file analysis by a few independent routines in a sequential manner, as each analysis routine takes some time. The attached demo code shows the problem I had. The problem is that the display only gets updated after the analyses are over? Appreciate to know why the code is ... | 0 | 2016-07-26T17:52:25Z | 38,597,188 | <p>You need to update the display manually by calling the <code>update_idletasks()</code> <a href="http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/universal.html" rel="nofollow">universal widget method</a> after changing something in the GUI. Note that the last update will only be visible for a very short time becaus... | 1 | 2016-07-26T18:18:01Z | [
"python",
"tkinter"
] |
Reading From Google Sheets Periodically | 38,596,793 | <p>I'm trying to read from a Google sheet say every 2 hours. I have looked at both the API for Google sheets and also the Google Apps Script.</p>
<p>I'm using Python/Flask, and what I'm specifically confused about is how to add the time trigger. I can use the Google Sheets API to read from the actual file,but I'm uns... | 0 | 2016-07-26T17:56:24Z | 38,600,670 | <p>If you want to do this with only manipulating your Python program, you would have to run it all day. This would waste CPU resources.</p>
<p>It's best to use cron to schedule your unix system to run a command for you every 2 hours. In this case, it'd be your python program.</p>
| 1 | 2016-07-26T22:09:04Z | [
"python",
"google-spreadsheet-api"
] |
regex for parsing imports in other scripts? | 38,596,798 | <p>We have a large library of custom scripts (300+) on a network share and I have been cleaning up a few deprecated modules and I need to know what scripts import these so I can point them to the new modules. Therefore, I'm trying to come up with a reg ex that will allow me to search for any deprecated module.</p>
<p>... | 0 | 2016-07-26T17:56:29Z | 38,596,970 | <p>Use <code>\b</code> to look for a word boundary before & after (sql_db):</p>
<pre><code>\s*(import|from)(.*)\b(sql_db)\b
</code></pre>
<p>This will not match with sql_db1 because sql_db does not end in a word boundary -- it ends in a 1. Commas <em>are</em> considered word boundaries, so it works with the rest ... | 3 | 2016-07-26T18:05:43Z | [
"python",
"regex"
] |
Which is more efficient way to monitor progress of a long running code? print on screen or log to a text file? | 38,596,808 | <p>I have a java code that as part of the code it handles a very big matrix (1 million by 4 million) and it takes several hours to run, before it crashes!</p>
<p>I would like to monitor the progress of the code, so know when it runs out of memory and crashes what percentage of matrix was already processes.</p>
<p>I a... | -1 | 2016-07-26T17:56:47Z | 38,596,984 | <p>Without having any context about what this code <em>does</em>, my advice would be that you could place an <code>if</code> condition check for every 1000<sup>th</sup> iteration, then does something (<em>print statement, calculation, output to log, check or what have you</em>). This <code>if</code> condition's affect ... | 2 | 2016-07-26T18:06:29Z | [
"java",
"python",
"progress"
] |
why is name of all threads same in python threading module? | 38,596,877 | <pre><code>from threading import *
def myfunc(i,name):
print("This is " + str(name))
for i in range(4):
name = current_thread().name
t = Thread(target=myfunc, args=(i,name,))
t.start()
</code></pre>
<hr>
<p><code>current_thread().getName()</code> also gives same results.I was wondering is this the w... | -1 | 2016-07-26T18:00:13Z | 38,596,921 | <p><code>current_thread()</code> always returns the thread that called <code>current_thread()</code>. You're repeatedly retrieving the name of the thread that's executing the loop, not the name of any of the threads that thread launches.</p>
<p>If you want to get the names of the threads launched in the loop, you coul... | 3 | 2016-07-26T18:02:54Z | [
"python",
"multithreading",
"python-3.x",
"python-multithreading"
] |
How to save PIL image with negative values | 38,596,995 | <p>I am trying to save an image with negative values using PIL, however, after saving, the image files has all negative values clipped to 0.</p>
<pre><code>from PIL import Image
import numpy as np
# generate random image for demo
img_arr = np.random.random_integers(-1000,1000, size=[10,10]).astype(np.int32)
print "or... | 1 | 2016-07-26T18:06:59Z | 38,597,658 | <p>Note that there is such a thing as storing your pixels as 32-bit signed integers according to PIL, and the image mode 'I' is meant to handle this in PIL. So the comments saying this makes no sense due to technical reasons are mistaken.</p>
<p>I don't think the PNG format supports this mode(Despite no errors being t... | 1 | 2016-07-26T18:46:24Z | [
"python",
"image",
"image-processing",
"python-imaging-library"
] |
Python - PyQt window became unmovable after adding some codes | 38,597,091 | <p>i am trying to set a window(i used QLabel) to look like an image in PyQt4
so i wrote this code :</p>
<pre><code> self.background_update = QPixmap(":/work/window.png")
update.setPixmap(self.background_update)
update.resize(self.background.width(), self.background.height())
update.show()
</code></pre>
... | 0 | 2016-07-26T18:12:51Z | 38,598,822 | <p>Not sure what platform you are on, but on Linux you can move any window by pressing <kbd>Alt</kbd> and dragging with the mouse. But if that doesn't work, you can quite easily implement similar functionality in your own code.</p>
<p>Here's a simple demo (left-click and drag):</p>
<pre><code>from PyQt4 import QtCore... | 0 | 2016-07-26T19:56:33Z | [
"python",
"pyqt4"
] |
How do I use socket.emit in python? | 38,597,119 | <p>Help!!
I'm helping my friend with his game, and I'm doing the online system(client, and server).
I've started working/using an example on a website, and i need to convert it to python somehow.
I need to, in python, connect too the server and send + receive some data in a package:</p>
<pre><code><script src="http... | -1 | 2016-07-26T18:14:33Z | 38,598,074 | <p>You can use the socketIO-client library.</p>
<pre><code>from socketIO_client import SocketIO, LoggingNamespace
with SocketIO('localhost', 8000, LoggingNamespace) as socketIO:
socketIO.emit('aaa')
</code></pre>
<p>A lot more detailed information, including examples, can be found in the Python Package Index <a ... | 0 | 2016-07-26T19:11:22Z | [
"javascript",
"python",
"sockets"
] |
How to always select the last file in a list? | 38,597,167 | <p>Long story short, I am using Python to plot many files on the same grid. I won't post the whole program, as it would be unhelpful and unnecessarily long. This is what I need help with</p>
<p>To summarize, how to I get <code>ifl == 1</code> to say something that in pythonic language would equal <code>ifl == last fil... | 0 | 2016-07-26T18:16:59Z | 38,597,233 | <p>If you just want to get the last item in an iteration, you can do this:</p>
<pre><code>for fl in file_location:
pass
# do stuff with fl
</code></pre>
<p>After the loop finishes, <code>fl</code> will be set to whatever was the last iterated item.</p>
| 2 | 2016-07-26T18:20:45Z | [
"python",
"function",
"file",
"loops"
] |
How to always select the last file in a list? | 38,597,167 | <p>Long story short, I am using Python to plot many files on the same grid. I won't post the whole program, as it would be unhelpful and unnecessarily long. This is what I need help with</p>
<p>To summarize, how to I get <code>ifl == 1</code> to say something that in pythonic language would equal <code>ifl == last fil... | 0 | 2016-07-26T18:16:59Z | 38,597,241 | <p>What about:</p>
<pre><code>if ifl == len(file_location):
....
</code></pre>
<p>Also, you don't actually need the index, you can do this:</p>
<pre><code>file_location = glob.glob('../Data/2016/July/*.nc')
for fl in file_location:
...
if fl == file_location[-1]:
Plot_Map(temp,lon,lat)
...
<... | 1 | 2016-07-26T18:20:57Z | [
"python",
"function",
"file",
"loops"
] |
How to always select the last file in a list? | 38,597,167 | <p>Long story short, I am using Python to plot many files on the same grid. I won't post the whole program, as it would be unhelpful and unnecessarily long. This is what I need help with</p>
<p>To summarize, how to I get <code>ifl == 1</code> to say something that in pythonic language would equal <code>ifl == last fil... | 0 | 2016-07-26T18:16:59Z | 38,597,280 | <p>how about, traversing the list backwards?</p>
<pre><code>for f in reversed(file_location):
</code></pre>
<p>so, your condition can stay the same.</p>
| 2 | 2016-07-26T18:23:34Z | [
"python",
"function",
"file",
"loops"
] |
How to stop logged in users from accessing login/register pages with Flask-Stormpath? | 38,597,204 | <p>I'm building a Flask app which uses Stormpath and Flask-Stormpath for auth. I wish to prevent a logged in user from accessing the /login or /register pages (since this doesn't make much sense - a logged in user has no need to log in, and you are registered by definition if you are already logged in). I have attempte... | 0 | 2016-07-26T18:18:45Z | 38,619,033 | <p>You can create a <a href="http://flask.pocoo.org/docs/0.11/patterns/viewdecorators/#view-decorators" rel="nofollow">decorator</a> containing the code below. It will redirect logged in users to another page if they try to access the login page.</p>
<pre><code>if current_user.is_authencticated():
return redirect ... | 0 | 2016-07-27T16:54:38Z | [
"python",
"flask",
"authorization",
"flask-login",
"stormpath"
] |
How to stop logged in users from accessing login/register pages with Flask-Stormpath? | 38,597,204 | <p>I'm building a Flask app which uses Stormpath and Flask-Stormpath for auth. I wish to prevent a logged in user from accessing the /login or /register pages (since this doesn't make much sense - a logged in user has no need to log in, and you are registered by definition if you are already logged in). I have attempte... | 0 | 2016-07-26T18:18:45Z | 38,624,250 | <p>Heyo!</p>
<p>So, I'm the author of Flask-Stormpath, I thought I'd jump in here. Instead of trying to modify the behavior of login / register (which I wouldn't recommend, as we change that stuff periodically with library releases), a better solution is to simply hide those URLs from the user once they've logged in.<... | 1 | 2016-07-27T22:30:11Z | [
"python",
"flask",
"authorization",
"flask-login",
"stormpath"
] |
Django Primary key acting as a foreign key | 38,597,221 | <p>I have a MySQL database with 9 tables. They are all related in some way, but I am having trouble with being able to connect with foreign keys. For example here are two of my tables that I am getting an error when I try to python manage.py migrate:</p>
<pre><code>class Release(models.Model):
release_ID = models... | 0 | 2016-07-26T18:19:57Z | 38,597,369 | <p>You could try to use the <a href="https://docs.djangoproject.com/en/1.8/ref/models/fields/#django.db.models.ForeignKey.to_field" rel="nofollow"><code>to_field</code></a> and <a href="https://docs.djangoproject.com/en/1.8/ref/models/fields/#django.db.models.Field.db_column" rel="nofollow"><code>db_column</code></a> o... | 0 | 2016-07-26T18:28:44Z | [
"python",
"mysql",
"django"
] |
Pandas: groupby forward fill with datetime index | 38,597,253 | <p>I have a dataset that has two columns: company, and value.<br>
It has a datetime index, which contains duplicates (on the same day, different companies have different values). The values have missing data, so I want to forward fill the missing data with the previous datapoint from the same company. </p>
<p>However,... | 3 | 2016-07-26T18:21:45Z | 38,597,362 | <p>One way is to use the <code>transform</code> function to fill the <code>value</code> column after group by:</p>
<pre><code>import pandas as pd
a['value'] = a.groupby('company')['value'].transform(lambda v: v.ffill())
a
# company value
#level_1
#2010-01-01 a 1.0
#2010-01-01 b 12.0
#... | 2 | 2016-07-26T18:28:21Z | [
"python",
"datetime",
"pandas",
"group-by",
"missing-data"
] |
Pandas: groupby forward fill with datetime index | 38,597,253 | <p>I have a dataset that has two columns: company, and value.<br>
It has a datetime index, which contains duplicates (on the same day, different companies have different values). The values have missing data, so I want to forward fill the missing data with the previous datapoint from the same company. </p>
<p>However,... | 3 | 2016-07-26T18:21:45Z | 38,597,491 | <p>You can add <code>'company'</code> to the index, making it unique, and do a simple <code>ffill</code> via <code>groupby</code>:</p>
<pre><code>a = a.set_index('company', append=True)
a = a.groupby(level=1).ffill()
</code></pre>
<p>From here, you can use <code>reset_index</code> to revert the index back to the just... | 3 | 2016-07-26T18:35:57Z | [
"python",
"datetime",
"pandas",
"group-by",
"missing-data"
] |
Pandas: groupby forward fill with datetime index | 38,597,253 | <p>I have a dataset that has two columns: company, and value.<br>
It has a datetime index, which contains duplicates (on the same day, different companies have different values). The values have missing data, so I want to forward fill the missing data with the previous datapoint from the same company. </p>
<p>However,... | 3 | 2016-07-26T18:21:45Z | 38,597,704 | <p>I like to use stacking and unstacking. In this case, it requires that I append the index with <code>'company'</code>.</p>
<pre><code>a.set_index('company', append=True).unstack().ffill() \
.stack().reset_index('company')
</code></pre>
<p><a href="http://i.stack.imgur.com/0THlw.p... | 1 | 2016-07-26T18:49:10Z | [
"python",
"datetime",
"pandas",
"group-by",
"missing-data"
] |
Extracting data from irregular form using openCV and OCR | 38,597,272 | <p>I'm trying to extract information from a form (scanned images of a form) and place that information into a table. I have used pytesseract to OCR the image with good success, but the problem with the output is the fact that Tesseract attempts to extract text line by line. </p>
<p>My scanned form looks like this:
<a ... | 1 | 2016-07-26T18:23:08Z | 38,605,235 | <p>In this case, what you should do is take a look at <a href="http://docs.opencv.org/trunk/d3/dc0/group__imgproc__shape.html#ga17ed9f5d79ae97bd4c7cf18403e1689a" rel="nofollow">OpenCV findContours</a>. Make sure to use the <code>RETR_TREE</code> retrieval method to obtain a hierarchy of contours. </p>
<p>Your windows ... | 1 | 2016-07-27T06:24:58Z | [
"c#",
"python",
"c++",
"opencv"
] |
Extracting data from irregular form using openCV and OCR | 38,597,272 | <p>I'm trying to extract information from a form (scanned images of a form) and place that information into a table. I have used pytesseract to OCR the image with good success, but the problem with the output is the fact that Tesseract attempts to extract text line by line. </p>
<p>My scanned form looks like this:
<a ... | 1 | 2016-07-26T18:23:08Z | 38,624,418 | <p>It's possible to separate them section wise using contours and simple contour properties alone.</p>
<p><strong>Note : These procedures will only work properly for this particular form. It's not a universal solution for all kinds of irregular forms. However you can implement or tweak certain methods in order to make... | 2 | 2016-07-27T22:46:43Z | [
"c#",
"python",
"c++",
"opencv"
] |
Distributing a cross platform python3 script | 38,597,275 | <p>I have a python project which I want to work cross-platform.
The approach I am taking to make sure that all the dependencies are installed on the user's machine is that I have a setup script that tries to import all the dependencies for my project, and if it encounters an import error, It installs the dependencies ... | 0 | 2016-07-26T18:23:14Z | 38,598,150 | <p>If you dont want to <a href="https://docs.python.org/2/distributing/index.html" rel="nofollow">go the normal way</a>, the simplest solution would be to create a <a href="https://pip.pypa.io/en/stable/user_guide/#requirements-files" rel="nofollow">requirements.txt</a> for the dependencies.</p>
<p>If you dont want to... | 0 | 2016-07-26T19:15:49Z | [
"python"
] |
Gmail Settings API Backend error - Python | 38,597,342 | <p>Last month i finished working on a GAE app with Python which makes extensive use of various Google APIs for managing the google resources within the company's domain by the google admin. The app was finished!!!, but this month google announced that the EmailSettings API which i am currently implementing is no longer... | 1 | 2016-07-26T18:27:20Z | 38,618,485 | <p>Update: As of 2016-08-11, this issue should be fixed.</p>
<p>As of 2016-07-27, there is a bug in the authorization backend that is leading to this error, although it only appears to affect certain domains / users. We are working on a fix. Please star <a href="https://code.google.com/a/google.com/p/apps-api-issues/i... | 0 | 2016-07-27T16:25:18Z | [
"python",
"google-app-engine",
"gmail-api",
"google-admin-sdk",
"google-admin-settings-api"
] |
Why bisect slower than sort | 38,597,378 | <p>I know that bisect is using binary search to keep lists sorted. However I did a timing test that the values are being read and sorted. But, on the contrary to my knowledge, keeping the values and then sorting them win the timing by high difference. Could more experienced users please explain this behavior ? Here is ... | 0 | 2016-07-26T18:29:20Z | 38,597,517 | <p>Your algorithmic complexity will be worse in the bisect case ...</p>
<p>In the <code>bisect</code> case, you have <code>N</code> operations (each at an average cost of <code>log(N)</code> to find the insertion point and then an additional <code>O(N)</code> step to insert the item). <strong>Total complexity: <code... | 3 | 2016-07-26T18:37:18Z | [
"python",
"algorithm",
"performance",
"sorting"
] |
Why bisect slower than sort | 38,597,378 | <p>I know that bisect is using binary search to keep lists sorted. However I did a timing test that the values are being read and sorted. But, on the contrary to my knowledge, keeping the values and then sorting them win the timing by high difference. Could more experienced users please explain this behavior ? Here is ... | 0 | 2016-07-26T18:29:20Z | 38,597,519 | <p>Sorting a list takes about <code>O(N*log(N))</code> time. Appending N items to a list takes <code>O(N)</code> time. Doing these things consecutively takes about <code>O(N*log(N))</code> time.</p>
<p>Bisecting a list takes <code>O(log(n))</code> time. Inserting an item into a list takes <code>O(N)</code> time. Doing... | 2 | 2016-07-26T18:37:18Z | [
"python",
"algorithm",
"performance",
"sorting"
] |
Why bisect slower than sort | 38,597,378 | <p>I know that bisect is using binary search to keep lists sorted. However I did a timing test that the values are being read and sorted. But, on the contrary to my knowledge, keeping the values and then sorting them win the timing by high difference. Could more experienced users please explain this behavior ? Here is ... | 0 | 2016-07-26T18:29:20Z | 38,597,622 | <p>To understand the time difference, letâs look at what you are actually doing there.</p>
<p>In your first example, you are taking an empty list, and append items to it, and sorting it in the end.</p>
<p>Appending to lists is really cheap, it has an <a href="https://en.wikipedia.org/wiki/Amortized_analysis" rel="n... | 1 | 2016-07-26T18:44:08Z | [
"python",
"algorithm",
"performance",
"sorting"
] |
Why bisect slower than sort | 38,597,378 | <p>I know that bisect is using binary search to keep lists sorted. However I did a timing test that the values are being read and sorted. But, on the contrary to my knowledge, keeping the values and then sorting them win the timing by high difference. Could more experienced users please explain this behavior ? Here is ... | 0 | 2016-07-26T18:29:20Z | 38,597,723 | <p>Insertion and deletion operations in a data structure can be surprisingly expensive sometimes, particularly if the distribution of incoming data values is random. Whereas, <em>sorting</em> can be unexpectedly fast.</p>
<p>A key consideration is whether-or-not you can "accumulate all the values," then sort them <em>... | 0 | 2016-07-26T18:50:09Z | [
"python",
"algorithm",
"performance",
"sorting"
] |
Replacing ' ' Values in a List with '0' | 38,597,390 | <p>I have a few <code>.csv</code> files that contain <code>NULL</code> values that are viewed as empty in the table. For example:</p>
<pre><code>ID Volts Current Watts
0 383 0
1 383 1 383
2 382 2 764
</code></pre>
<p>This <code>.csv</code> file is input into my pro... | 0 | 2016-07-26T18:29:49Z | 38,597,450 | <p>Because <code>list.index</code> only returns index of the first occurrence of the item in the list. You can instead use a list comprehension on each row to do the replacement:</p>
<pre><code>def removeNull(row):
return ['0' if i=='' else i for i in row]
# |<- ternary op. ->|
</code></pre>
<p>... | 5 | 2016-07-26T18:33:05Z | [
"python",
"string",
"csv",
null
] |
python - how to log everything without instrumentation | 38,597,475 | <p>I want to log <strong>everything:</strong></p>
<ol>
<li>Function entered + values of parameters + function exited</li>
<li>Result of every assignment or operation</li>
<li>etc.</li>
</ol>
<p>Is it possible to log "everything" in a Python execution without instrumenting the code?</p>
<p>Since things are executing ... | 1 | 2016-07-26T18:34:51Z | 38,600,368 | <p>You would need to use the <a href="https://docs.python.org/3/library/trace.html" rel="nofollow"><code>trace</code></a> module and/or perhaps the <a href="https://docs.python.org/3/library/pdb.html" rel="nofollow"><code>pdb</code></a> module. They may not give you everything you need, but it would be a starting point... | 0 | 2016-07-26T21:41:41Z | [
"python",
"logging",
"pycharm"
] |
In NLTK, get the number of occurrences of a trigram | 38,597,503 | <p>I'd like to get the "commonly used phrases" from a text, defined as the trigrams which occur more than once. Till now I have this:</p>
<pre><code>import nltk
def get_words(string):
tokenizer = nltk.tokenize.RegexpTokenizer(r'\w+')
return tokenizer.tokenize(string)
string = "Hello, world. This is a dog. Th... | 0 | 2016-07-26T18:36:34Z | 38,597,744 | <p>To get frequencies with normalization you can just call ngram_fd.
In your case:</p>
<pre><code>trigram_freqs = finder.ngram_fd
</code></pre>
| 0 | 2016-07-26T18:51:45Z | [
"python",
"nltk"
] |
In NLTK, get the number of occurrences of a trigram | 38,597,503 | <p>I'd like to get the "commonly used phrases" from a text, defined as the trigrams which occur more than once. Till now I have this:</p>
<pre><code>import nltk
def get_words(string):
tokenizer = nltk.tokenize.RegexpTokenizer(r'\w+')
return tokenizer.tokenize(string)
string = "Hello, world. This is a dog. Th... | 0 | 2016-07-26T18:36:34Z | 38,612,097 | <p>You can get number of occurrences using <strong>finder.ngram_fd.items()</strong></p>
<pre><code># To get Trigrams with occurrences
trigrams = finder.ngram_fd.items()
print trigrams
# To get Trigrams with occurrences in descending order
trigrams = sorted(finder.ngram_fd.items(), key=lambda t: (-t[1], t[0]))
print t... | 1 | 2016-07-27T11:47:41Z | [
"python",
"nltk"
] |
In NLTK, get the number of occurrences of a trigram | 38,597,503 | <p>I'd like to get the "commonly used phrases" from a text, defined as the trigrams which occur more than once. Till now I have this:</p>
<pre><code>import nltk
def get_words(string):
tokenizer = nltk.tokenize.RegexpTokenizer(r'\w+')
return tokenizer.tokenize(string)
string = "Hello, world. This is a dog. Th... | 0 | 2016-07-26T18:36:34Z | 38,623,755 | <p>In the end I went with 'post-multiplying' the <code>raw_freq</code> attribute because it is already sorted. Here is my implementation:</p>
<pre><code>import nltk
def get_words(string):
tokenizer = nltk.tokenize.RegexpTokenizer(r'\w+')
return tokenizer.tokenize(string)
string = "Hello, world. This is a dog... | 0 | 2016-07-27T21:47:56Z | [
"python",
"nltk"
] |
Reading multiple files in real time? | 38,597,535 | <p>I'm trying to listen log files that are constantly updated and work with the lines continuously.
The thing is that I have multiple files to listen. The logs are separated by the jboss instances and I have to work with all them together to insert them on a database. </p>
<p>I've got a good example of how to read a f... | -1 | 2016-07-26T18:38:29Z | 38,598,072 | <p>You can print the lines of each file at the same time using the following code:</p>
<pre><code>lock = threading.Lock()
def printFile(logfile):
loglines = follow(logfile)
for line in loglines:
#only one thread at a time can print to the user
lock.acquire()
print line
lock.rel... | 2 | 2016-07-26T19:11:13Z | [
"python",
"multithreading",
"file-io"
] |
What does it mean if get_ident() returns the same value? | 38,597,538 | <p>If <code>get_ident()</code> returns the same value during the execution of a program, does that mean the thread is the same thread, or is it possible that the thread was restarted but got the same identifier as a previous thread?</p>
<p>If it is possible, how likely is it - pretty likely?</p>
<p>I ask because I ex... | 0 | 2016-07-26T18:38:41Z | 38,597,574 | <blockquote>
<p>is it possible that the thread was restarted but got the same identifier as a previous thread?</p>
</blockquote>
<p>Yep, it seems so. From <a href="https://docs.python.org/2/library/thread.html#thread.get_ident" rel="nofollow">the documentation</a>:</p>
<blockquote>
<p>Thread identifiers may be re... | 1 | 2016-07-26T18:41:07Z | [
"python",
"multithreading"
] |
Python - How to replace adjacent list elements with a different value | 38,597,578 | <p>I have been stumped trying to figure how to locate and change the values of the area bordered around a single element of an list without affecting the element values needing to be bordered. This is what I'm trying to execute:</p>
<p>BEFORE:</p>
<pre><code>[[0,0,0,0,0],
[0,1,1,0,0],
[0,1,0,1,0],
[0,0,1,0,0],
[0... | -7 | 2016-07-26T18:41:22Z | 38,597,765 | <p>For loops and if/else statements will suffice.</p>
| 0 | 2016-07-26T18:52:57Z | [
"python",
"list",
"python-2.7"
] |
Python - How to replace adjacent list elements with a different value | 38,597,578 | <p>I have been stumped trying to figure how to locate and change the values of the area bordered around a single element of an list without affecting the element values needing to be bordered. This is what I'm trying to execute:</p>
<p>BEFORE:</p>
<pre><code>[[0,0,0,0,0],
[0,1,1,0,0],
[0,1,0,1,0],
[0,0,1,0,0],
[0... | -7 | 2016-07-26T18:41:22Z | 38,597,986 | <p>And yes , you can just pass with if/else and for loops : </p>
<pre><code> a = [[0,0,0,0,0],
[0,1,1,0,0],
[0,1,0,1,0],
[0,0,1,0,0],
[0,0,0,0,0]]
to_replace = 1
replacement = 9
for i in range(len(a)):
for x in range(len(a[i])):
if a[i][x] == to_replace:
for pos_x... | 0 | 2016-07-26T19:06:01Z | [
"python",
"list",
"python-2.7"
] |
How to perform an operation on every element in a numpy matrix? | 38,597,587 | <p>Say I have a function foo() that takes in a single float and returns a single float. What's the fastest/most pythonic way to apply this function to every element in a numpy matrix or array?</p>
<p>What I essentially need is a version of this code that doesn't use a loop:</p>
<pre><code>import numpy as np
big_matr... | 1 | 2016-07-26T18:41:53Z | 38,600,740 | <p>If <code>foo</code> is really a black box that takes a scalar, and returns a scalar, then you must use some sort of iteration. People often try <code>np.vectorize</code> and realize that, as documented, it does not speed things up much. It is most valuable as a way of broadcasting several inputs. It uses <code>n... | 3 | 2016-07-26T22:13:56Z | [
"python",
"arrays",
"numpy",
"matrix"
] |
Cx_oracle in Python giving "missing expression error" - date and timestamp literals? | 38,597,620 | <p>I have a chunk of code that is supporting a procedure for making survey records. 1 line is causing it to fail and I can't figure out why. Here is a snippet:</p>
<pre><code>data = [4, 1, 5, '2015-01-01', '2016-07-26 14:32:19']
insert_query2 = 'INSERT INTO SURVEY_RESPONSE (ID, SURVEY_ID, RESPONDENT_ID, DATE_TAKEN, DA... | 0 | 2016-07-26T18:44:02Z | 38,597,766 | <p>I just found the answer - the literals are not good to use, to_date() and to_timestamp() are the correct methods for passing the correct formatting of the date and timestamp.</p>
<p>Discussion here: <a href="http://stackoverflow.com/questions/13518506/oracle-literal-does-not-match-format-string-error">Oracle - lite... | 0 | 2016-07-26T18:52:58Z | [
"python",
"python-3.x",
"cx-oracle",
"ora-00936"
] |
Image skewing when applying cartopy transformations | 38,597,656 | <p>I'm doing some plotting using cartopy and matplotlib, and I was recently using the PlateCarree transformation, but I changed to Mercator because Louisiana was a bit too squished for my liking. Prior to the switch, I had a logo displayed in the bottom left corner, using these two lines of code <code>logo = matplotlib... | 1 | 2016-07-26T18:46:22Z | 38,598,940 | <p>You might get better results if you plot the image logo in axes coordinates rather than data coordinates. You can use the <code>ax.transAxes</code> transform for this, and specify the extent in axes coordinates ([0, 0] in bottom left, [1, 1] in top right).</p>
| 2 | 2016-07-26T20:04:08Z | [
"python",
"image",
"matplotlib",
"transformation",
"cartopy"
] |
Django Datatables from model | 38,597,764 | <p>I have a simple model in my django app that I am displaying as a table. I would like to change the table to a datatable. However even after following all the steps listed ont eh datatables.net website I cant seem to convert my table into a datatable:</p>
<p><strong>models.py</strong></p>
<pre><code>from __future__... | 0 | 2016-07-26T18:52:47Z | 38,597,883 | <p>Unless your table has an id of <code>myTable</code>, then it's not going to work. It looks like you should change your jquery selector to be <code>$('#users')</code> because that's the table id that you have set in the code posted above.</p>
| 0 | 2016-07-26T18:59:53Z | [
"jquery",
"python",
"django",
"datatable"
] |
Django Datatables from model | 38,597,764 | <p>I have a simple model in my django app that I am displaying as a table. I would like to change the table to a datatable. However even after following all the steps listed ont eh datatables.net website I cant seem to convert my table into a datatable:</p>
<p><strong>models.py</strong></p>
<pre><code>from __future__... | 0 | 2016-07-26T18:52:47Z | 38,598,154 | <p>From the <a href="https://datatables.net/manual/installation" rel="nofollow">datatables manual</a>:</p>
<blockquote>
<p>For DataTables to be able to enhance an HTML table, the table must be valid, well formatted HTML, with a header (thead) and a body (tbody). An optional footer (tfoot) can also be used.</p>
</blo... | 1 | 2016-07-26T19:16:03Z | [
"jquery",
"python",
"django",
"datatable"
] |
Django Datatables from model | 38,597,764 | <p>I have a simple model in my django app that I am displaying as a table. I would like to change the table to a datatable. However even after following all the steps listed ont eh datatables.net website I cant seem to convert my table into a datatable:</p>
<p><strong>models.py</strong></p>
<pre><code>from __future__... | 0 | 2016-07-26T18:52:47Z | 39,442,713 | <p>In addition to thr table thead and tbody comment, Jquery datatables will automatically sort your table by the 1st column if you are using the default datatables constructor.</p>
| 0 | 2016-09-12T02:42:21Z | [
"jquery",
"python",
"django",
"datatable"
] |
create user input directory name in python | 38,597,824 | <p>I am trying to generate a python script that takes 3 input arguments and creates a directory whose name is a concatenation of the 3 arguments. The command i give is python new.py user1 32 male and I should get a directory name created as user1_32_male, but I am getting directory name as user_name + "<em>" + age + "<... | 1 | 2016-07-26T18:56:26Z | 38,597,896 | <p>You put the expression you want to <em>evaluate</em> to the directory name you want in quotes, so it doesn't get evaluated. Try:</p>
<pre><code>newpath = r'./' + user_name + "_" + age + "_" + gender
</code></pre>
| 0 | 2016-07-26T19:00:37Z | [
"python"
] |
create user input directory name in python | 38,597,824 | <p>I am trying to generate a python script that takes 3 input arguments and creates a directory whose name is a concatenation of the 3 arguments. The command i give is python new.py user1 32 male and I should get a directory name created as user1_32_male, but I am getting directory name as user_name + "<em>" + age + "<... | 1 | 2016-07-26T18:56:26Z | 38,598,043 | <p>First of all, I noticed that you're importing things more than once. There's no reason to import <code>os.path</code> since it's included in <code>os</code>. The same goes with <code>sys</code>.</p>
<p>It's easier to use string substitution in cases like this. The tuple that comes after the <code>%</code> contains ... | 0 | 2016-07-26T19:08:51Z | [
"python"
] |
Dictionary to JSON object conversion | 38,597,831 | <p>I have 2 long lists (extracted from a csv) both of the same index length.
Example:</p>
<pre><code>l1 = ['Apple','Tomato','Cocos'] #name of product
l2 = ['1','2','3'] #some id's
</code></pre>
<p>I made my dictionary with this method:</p>
<pre><code>from collections import defaultdict
d = defaultdict(list)
for x ... | -1 | 2016-07-26T18:56:49Z | 38,597,851 | <p>Rather than using a <code>defaultdict</code> (which doesn't buy you anything in this case), you're better off <code>zip</code>ping the lists and creating a <code>dict</code> from each pair:</p>
<pre><code>[{'Product': product, 'Plu': plu} for product, plu in zip(l1, l2)]
</code></pre>
| 0 | 2016-07-26T18:58:14Z | [
"python",
"json",
"dictionary"
] |
How are file objects cleaned up in Python when the process is killed? | 38,597,876 | <p>What happens to a file object in Python when the process is terminated? Does it matter whether Python is terminated with <code>SIGTERM</code>, <code>SIGKILL</code>, <code>SIGHUP</code> (etc.) or by a <code>KeyboardInterrupt</code> exception?</p>
<p>I have some logging scripts that continually acquire data and write... | 1 | 2016-07-26T18:59:36Z | 38,598,186 | <p>It's not how files are "cleaned up" so much as how they are written to. It's possible that a program might perform multiple writes for a single "chunk" of data (row, or whatever) and you could interrupt in the middle of this process and end up with partial records written.</p>
<p>Looking at the <a href="https://hg.... | 1 | 2016-07-26T19:18:16Z | [
"python",
"io",
"terminate"
] |
Double Group-by then apply some functions? | 38,597,921 | <p>I have data that looks like this:</p>
<pre><code> country source
0 UK Ads
1 US Seo
2 US Seo
3 China Seo
4 US Seo
5 US Seo
6 China Seo
7 US Ads
</code></pre>
<p>For each country I want to get the ratio of each source. I did a groupby on country and source... | 2 | 2016-07-26T19:01:51Z | 38,598,087 | <p>You can use <code>unstack</code> to transform the result from long to wide format and then calculate the ratio row by row using <code>apply</code> method:</p>
<pre><code>import pandas as pd
df1 = df.groupby(['country', 'source']).size().unstack(level=1,fill_value = 0).apply(lambda r: r/r.sum(), axis = 1)
df1
# sou... | 1 | 2016-07-26T19:11:59Z | [
"python",
"pandas",
"group-by",
"aggregate-functions"
] |
Double Group-by then apply some functions? | 38,597,921 | <p>I have data that looks like this:</p>
<pre><code> country source
0 UK Ads
1 US Seo
2 US Seo
3 China Seo
4 US Seo
5 US Seo
6 China Seo
7 US Ads
</code></pre>
<p>For each country I want to get the ratio of each source. I did a groupby on country and source... | 2 | 2016-07-26T19:01:51Z | 38,598,138 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.crosstab.html" rel="nofollow"><code>pd.crosstab</code></a> to perform the frequency counts, followed by <code>apply</code> to normalize:</p>
<pre><code>df = pd.crosstab(df['country'], df['source']).apply(lambda r: r/r.sum(), axis=1)
<... | 1 | 2016-07-26T19:15:12Z | [
"python",
"pandas",
"group-by",
"aggregate-functions"
] |
Double Group-by then apply some functions? | 38,597,921 | <p>I have data that looks like this:</p>
<pre><code> country source
0 UK Ads
1 US Seo
2 US Seo
3 China Seo
4 US Seo
5 US Seo
6 China Seo
7 US Ads
</code></pre>
<p>For each country I want to get the ratio of each source. I did a groupby on country and source... | 2 | 2016-07-26T19:01:51Z | 38,598,272 | <h3>Large sample set</h3>
<pre><code>np.random.seed([3,1415])
n = 100000
df = pd.DataFrame(
dict(country=np.random.choice(('UK', 'US', 'China'), n),
source=np.random.choice(('Ads', 'Seo', 'Direct'), n)))
</code></pre>
<h3>Solution</h3>
<pre><code>size = df.groupby(['country', 'source']).size().unstack()... | 1 | 2016-07-26T19:23:11Z | [
"python",
"pandas",
"group-by",
"aggregate-functions"
] |
Match lists based on Name and DOB | 38,597,953 | <p>This seems like it should be easy, but I can't seem to find what I'm looking for...I have two lists of people, FirstName, LastName, Date of Birth, and I just want to know which people are in both lists, and which ones are in one but not the other. </p>
<p>I've tried something like </p>
<pre><code>common = pd.merg... | -1 | 2016-07-26T19:03:41Z | 38,599,668 | <p>Try this , it should work</p>
<pre><code>import sys
from StringIO import StringIO
import pandas as pd
TESTDATA=StringIO("""DOB;First;Last
2016-07-26;John;smith
2016-07-27;Mathew;George
2016-07-28;Aryan;Singh
2016-07-29;Ella;Gayau
""")
list1 = pd.read_csv(TESTDATA, sep=";")
TESTDATA=StringIO... | 0 | 2016-07-26T20:51:42Z | [
"python"
] |
How to do a regex replace *and* capture in python? | 38,597,979 | <p>I have a custom data format with open/close tags that I need to parse, e.g.:</p>
<pre><code><t1> 15 </t1> <t2> 25 </t2>
</code></pre>
<p>Tags are never nested, but I don't know the tag names in advance. I can't count on data conforming to XML (e.g. may have "<" or ">" characters be... | -1 | 2016-07-26T19:05:47Z | 38,598,388 | <p>Setup (I kept your regex but added a few words to the string so we can see that the replacing actually works):</p>
<pre><code>>>> import re
>>> s = 'front <t1> 15 </t1> middle <t2> 25 </t2> back'
>>> p = r'\s* < ([^>]+) > \s* (.+\S) \s* < / \1 ... | 0 | 2016-07-26T19:30:30Z | [
"python",
"regex"
] |
How to do a regex replace *and* capture in python? | 38,597,979 | <p>I have a custom data format with open/close tags that I need to parse, e.g.:</p>
<pre><code><t1> 15 </t1> <t2> 25 </t2>
</code></pre>
<p>Tags are never nested, but I don't know the tag names in advance. I can't count on data conforming to XML (e.g. may have "<" or ">" characters be... | -1 | 2016-07-26T19:05:47Z | 38,598,427 | <p>You don't need the substitution in Python. Use <code>re.findall()</code> or <code>re.finditer()</code>, like so:</p>
<pre><code>import re
with open('input.txt') as input_file:
data = input_file.read()
tags = {}
for match in re.finditer(r'<\s*(.*?)\s*>\s*(.*?)\s*</\1>', data):
tags[match.group(1... | 2 | 2016-07-26T19:32:38Z | [
"python",
"regex"
] |
Passing node object as parameter in graph query Py2neo | 38,598,024 | <p>I have the following code in which I am obtaining a node. How can I pass it to graph.evaluate as a parameter. Is there a possible method to do so if this is incorrect ? Or some alternative method</p>
<pre><code>user_node = selector.select("User", user_id=95)
lib_node = graph.evaluate("match {param}-[:LISTENS_TO]-&g... | 0 | 2016-07-26T19:07:40Z | 38,611,159 | <p>The <code>select</code> method returns a selection of as many matches as it can find. This may or may not be a sequence of one but either way, you'll need to use the <code>.first()</code> method to grab the first (and probably only) one returned.</p>
<p><a href="http://py2neo.org/v3/database.html#py2neo.database.se... | 0 | 2016-07-27T11:03:24Z | [
"python",
"neo4j",
"py2neo"
] |
how to programatically open an executable in program files? | 38,598,034 | <p>I am trying to open an executable as follows and running into below error,how to I take care of the spaces between <code>Program Files</code> and open this executable?</p>
<pre><code>C:\Windows\system32>python
Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyri... | 0 | 2016-07-26T19:08:08Z | 38,598,208 | <p>Please run as below:</p>
<pre><code>os.system(r'"C:\Program Files (x86)\company\POST\bin\POSTConfig.exe"')
</code></pre>
| 0 | 2016-07-26T19:19:42Z | [
"python"
] |
how to programatically open an executable in program files? | 38,598,034 | <p>I am trying to open an executable as follows and running into below error,how to I take care of the spaces between <code>Program Files</code> and open this executable?</p>
<pre><code>C:\Windows\system32>python
Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyri... | 0 | 2016-07-26T19:08:08Z | 38,598,211 | <p>Use a raw string, imbed double quotes inside single quotes:</p>
<pre><code>os.system(r'"C:\Program Files (x86)\company\POST\bin\POSTConfig.exe"')
</code></pre>
<p>But please look at the <a href="https://docs.python.org/2/library/subprocess.html" rel="nofollow">subprocess</a> module instead.</p>
| 0 | 2016-07-26T19:19:52Z | [
"python"
] |
Can't draw function using python | 38,598,110 | <p>I have made a function RC(n) that given any n changes the digits of n according to a rule. The function is the following </p>
<pre><code>def cfr(n):
return len(str(n))-1
def n_cfr(k,n):
J=str(k)
if "." in J:
J2=J.replace(".", "")
return J2[n-1]
else:
return J[n]
def RC(n):... | 0 | 2016-07-26T19:13:44Z | 38,598,308 | <p>The line in your function should be <code>x = list(range(a, b, res))</code> the first two arguments of <code>range</code> are <code>start</code> and <code>stop</code>. Here is a better version of draw:</p>
<pre><code>def draw(f, a, b, res):
import numpy as np
import matplotlib.pyplot as plt
x = list(ran... | 1 | 2016-07-26T19:25:31Z | [
"python",
"graphing"
] |
Issue when setting-up wsgi as an alias path in apache | 38,598,157 | <p>NOTE: This question is different from '<a href="http://stackoverflow.com/questions/18967441/add-a-prefix-to-all-flask-routes">Add a prefix to all Flask routes</a>' as I am trying to resolve this at apache level. Additional, the suggested fix for flask routes did not work!</p>
<p>Following on from <a href="http://st... | 0 | 2016-07-26T19:16:18Z | 38,673,945 | <p>Instead of:</p>
<pre><code> Alias / /var/www/html/
<Directory "/var/www/html">
Order Deny,Allow
Allow from all
Require all granted
</Directory>
</code></pre>
<p>use:</p>
<pre><code> DocumentRoot /var/www/html/
<Directory "/var/www/html">
Order De... | 1 | 2016-07-30T12:26:01Z | [
"python",
"apache",
"flask",
"virtualhost"
] |
Odoo 8 store=False not working | 38,598,158 | <p>I'm creating a simple form that you have to enter a password so the action can be executed but I can't figure out how not to store the password in the database. When I put <strong>store=False</strong> my module doesn't compile. Also I would like to know if there's a way to hide the password while the user is writing... | 0 | 2016-07-26T19:16:22Z | 38,630,889 | <p>Some points to keep in mind</p>
<ul>
<li>"store" is a parameter for calculated fields. It defines if it should
calculate the value each time you open the record or calculate it
only when it's edited.</li>
<li>After you've hit the confirm button it saves the current data. I'd suggest that you'd set the password to F... | 1 | 2016-07-28T08:24:58Z | [
"python",
"xml",
"odoo-8"
] |
Odoo 8 store=False not working | 38,598,158 | <p>I'm creating a simple form that you have to enter a password so the action can be executed but I can't figure out how not to store the password in the database. When I put <strong>store=False</strong> my module doesn't compile. Also I would like to know if there's a way to hide the password while the user is writing... | 0 | 2016-07-26T19:16:22Z | 38,689,829 | <p>you can just simple use the <em>PASSWORD</em> since you have declared it as var name of self.password. SO: password = False</p>
| 0 | 2016-08-01T01:23:12Z | [
"python",
"xml",
"odoo-8"
] |
Training CNN using cifar10 solver | 38,598,161 | <p>I'm trying to train a CNN with my own data, using <a href="https://github.com/BVLC/caffe/blob/master/examples/cifar10/cifar10_quick_train_test.prototxt" rel="nofollow">cifar10</a> network layers.
but, when I'm running this command:</p>
<pre><code>roishik@roishik-System-Product-Name:~/Desktop/caffe/caffe$ /home/rois... | 0 | 2016-07-26T19:16:34Z | 38,611,471 | <p>It is because you are doing it wrong.</p>
<p>The files that you are using:</p>
<pre><code>Solver: /home/roishik/Desktop/Thesis/Code/cafe_cnn/first/caffe_models/cifar_10_fast/cifar10_quick_solver.prototxt
Net: /home/roishik/Desktop/Thesis/Code/cafe_cnn/first/caffe_models/cifar_10_fast/cifar10_quick_train_test.proto... | 1 | 2016-07-27T11:17:30Z | [
"python",
"python-2.7",
"caffe",
"conv-neural-network",
"pycaffe"
] |
Python -- Client Waiting for Server Input (and vice versa) | 38,598,238 | <p>I'm fairly new to Python and I'm very new to sockets and servers in Python, so please bear with me! Basically, I'm trying to set up a hangman game between a client and server to play a game. I know this system has a bunch of weaknesses (including having most of the code on the client side instead of the server side,... | 0 | 2016-07-26T19:21:29Z | 38,598,528 | <p>Maybe you could make loop instead of just creating only one Hangman instance, like this:</p>
<pre><code>while True:
game = Hangman()
</code></pre>
<p>instead of an infinite loop you can make an exit condition.For example in your class you may have a boolean variable that indicates if the game has ended or not... | 1 | 2016-07-26T19:38:56Z | [
"python",
"serversocket"
] |
Merging two CSV files by a common column python | 38,598,316 | <p>I am trying to merge two csv files with a common id column and write the merge to a new file. I have tried the following but it is giving me an error - </p>
<pre><code>import csv
from collections import OrderedDict
filenames = "stops.csv", "stops2.csv"
data = OrderedDict()
fieldnames = []
for filename in filenames... | 0 | 2016-07-26T19:26:01Z | 38,599,858 | <p>Here is an example using pandas</p>
<pre><code>import sys
from StringIO import StringIO
import pandas as pd
TESTDATA=StringIO("""DOB;First;Last
2016-07-26;John;smith
2016-07-27;Mathew;George
2016-07-28;Aryan;Singh
2016-07-29;Ella;Gayau
""")
list1 = pd.read_csv(TESTDATA, sep=";")
TESTDATA=Stri... | 0 | 2016-07-26T21:04:48Z | [
"python",
"csv"
] |
Merging two CSV files by a common column python | 38,598,316 | <p>I am trying to merge two csv files with a common id column and write the merge to a new file. I have tried the following but it is giving me an error - </p>
<pre><code>import csv
from collections import OrderedDict
filenames = "stops.csv", "stops2.csv"
data = OrderedDict()
fieldnames = []
for filename in filenames... | 0 | 2016-07-26T19:26:01Z | 38,664,595 | <p>Thanks Shijo.</p>
<p>This is what worked for me after - merged by the first column in each csv.</p>
<pre><code>import csv
from collections import OrderedDict
with open('stops.csv', 'rb') as f:
r = csv.reader(f)
dict2 = {row[0]: row[1:] for row in r}
with open('stops2.csv', 'rb') as f:
r = csv.reader(... | 0 | 2016-07-29T17:40:17Z | [
"python",
"csv"
] |
How to specify a priori correlation between samples drawn randomly from two multinomial distributions? | 38,598,441 | <p>Consider the following game: in each trial, you are presented with <em>x</em> red and <em>y</em> blue dots. You have to decide whether there are more red than blue dots. For each trial, the minimum number of dots in a given color is 10, the maximum is 50. Red and blue dots follow an identical multinomial distributio... | 0 | 2016-07-26T19:33:15Z | 38,599,237 | <p>Basically you ask how to <a href="https://www.mathworks.com/matlabcentral/answers/101802-how-can-i-generate-two-correlated-random-vectors-with-values-drawn-from-a-normal-distribution" rel="nofollow">create 2 vectors with a specified correlation</a>, so it is more statistics than programing question, but it can be do... | 1 | 2016-07-26T20:24:34Z | [
"python",
"matlab",
"correlation",
"multinomial"
] |
Run Multiple BigQuery Jobs via Python API | 38,598,558 | <p>I've been working off of <a href="https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/bigquery/api/async_query.py" rel="nofollow">Google Cloud Platform's Python API library</a>. I've had much success with these API samples out-of-the-box, but I'd like to streamline it a bit further by combining th... | 0 | 2016-07-26T19:40:09Z | 38,600,157 | <p>The idea of running multiple jobs asynchronously is in creating/preparing as many jobs as you need and kick them off using <a href="https://cloud.google.com/bigquery/docs/reference/v2/jobs/insert" rel="nofollow">jobs.insert</a> API (important you should either collect all respective jobids or set you own - they just... | 0 | 2016-07-26T21:26:47Z | [
"python",
"google-bigquery",
"google-cloud-platform"
] |
Dictionaries pointing to another dictionary in Python | 38,598,679 | <p>Let's say I have a dictionary <code>dic = {k: v}</code>. My goal is to create another data structure that will point to a subset of a dictionary, accessed under a single key. </p>
<p>E.g: <code>dic = {1: 'a', 2: 'b', 3: 'c', 4: 'f'}</code>.
I would like a pointer only to keys <code>1</code> and <code>3</code>, for... | -1 | 2016-07-26T19:47:21Z | 38,598,790 | <p>You can create a second dictionary like this</p>
<pre><code>dic2 = {'k1': (dic[1], dic[3])}
</code></pre>
<p>Doing so, you don't actually use extra memory (only marginally) because the objects in the tuple are the same as the ones in your original <code>dic</code> (they occupy the same space in memory). You can ch... | 2 | 2016-07-26T19:54:27Z | [
"python",
"dictionary"
] |
How to find the diameter of objects using image processing in Python? | 38,598,690 | <p>Given an image with some irregular objects in it, I want to find their individual diameter.</p>
<p><a href="http://stackoverflow.com/questions/33707095/how-to-locate-a-particular-region-of-values-in-a-2d-numpy-array?answertab=active#tab-top">Thanks to this answer</a>, I know how to identify the objects. <strong>How... | 2 | 2016-07-26T19:48:01Z | 38,616,904 | <p>You could use <code>skimage.measure.regionprops</code> to determine the bounding box of all the regions in your image. For roughly circular blobs the diameter of the minimum enclosing circle can be approximated by the <strong>largest side of the bounding box</strong>. To do so you just need to add the following snip... | 3 | 2016-07-27T15:09:26Z | [
"python",
"numpy",
"image-processing",
"geometry",
"ndimage"
] |
Copying several columns from a csv file to an existing xls file using Python | 38,598,705 | <p>I'm pretty new to Python but I was having some difficulty on getting started on this. I am using Python 3.</p>
<p>I've googled and found quite a few python modules that help with this but was hoping for a more defined answer here. So basically, I need to read from a csv file certain columns i.e G, H, I, K, and M. T... | 0 | 2016-07-26T19:48:54Z | 38,598,804 | <p>I recommend using pandas. It has convenient functions to read and write csv and xls files.</p>
<pre><code>import pandas as pd
from openpyxl import load_workbook
#read the csv file
df_1 = pd.read_csv('c:/test/test.csv')
#lets say df_1 has columns colA and colB
print(df_1)
#read the xls(x) file
df_2=pd.read_excel(... | 1 | 2016-07-26T19:55:28Z | [
"python",
"excel",
"python-3.x",
"csv"
] |
Copying several columns from a csv file to an existing xls file using Python | 38,598,705 | <p>I'm pretty new to Python but I was having some difficulty on getting started on this. I am using Python 3.</p>
<p>I've googled and found quite a few python modules that help with this but was hoping for a more defined answer here. So basically, I need to read from a csv file certain columns i.e G, H, I, K, and M. T... | 0 | 2016-07-26T19:48:54Z | 38,599,184 | <p>You could try XlsxWriter , which is fully featured python module for writing Excel 2007+ XLSX file format.
<a href="https://pypi.python.org/pypi/XlsxWriter" rel="nofollow">https://pypi.python.org/pypi/XlsxWriter</a> </p>
| 1 | 2016-07-26T20:20:04Z | [
"python",
"excel",
"python-3.x",
"csv"
] |
Selenium Python - How to get class id by clicking on it manually | 38,598,709 | <p>I'm trying to click on a button on a page that has a lot of JavaScript but no matter what I try, can't click it. Is there a way for me to click the button manually and get what I need to click?</p>
<p>I've tried inspecting elements and FirePath but those aren't giving me the correct class or id that I need to click... | 0 | 2016-07-26T19:48:59Z | 38,599,105 | <p>You may try
<a href="http://www.seleniumhq.org/projects/ide/" rel="nofollow">http://www.seleniumhq.org/projects/ide/</a></p>
<p>This has a feature to find web element path</p>
| 0 | 2016-07-26T20:15:00Z | [
"javascript",
"python",
"selenium-webdriver"
] |
Accessing Cell history (python, smartsheets) | 38,598,720 | <p>I'm looking for a way to access elements of a cell's history. I have used various iterations of the following code to get at the keys inside the cell history dict, but I'm (obviously) doing something wrong. When running the code as below I get this error - <code>TypeError: 'CellHistory' object has no attribute '__ge... | 0 | 2016-07-26T19:49:47Z | 38,602,364 | <p>Seems like you're using the wrong attribute name and syntax in the <code>print</code> statement. Try something like this instead:</p>
<pre><code>#print out revision history
for rev in revisions:
print(rev.modified_at)
print(rev.modified_by.name)
print('')
</code></pre>
| 1 | 2016-07-27T01:41:05Z | [
"python",
"smartsheet-api"
] |
Date/Time formatting | 38,598,738 | <p>I'm creating a python script that will display busy, no-answer and failed calls for a specific date but I'm stuck on the formatting of the date that's displayed. The start_time and end_time "variables" from Twilio print something like this: "Mon, 25 Jul 2016 16:03:53 +0000". I want to get rid of the day name and ... | 0 | 2016-07-26T19:51:13Z | 38,598,939 | <p>The code I've provided does simple date and time format.</p>
<pre><code>from datetime import datetime
from time import sleep
print('The Time is shown below!')
while True:
time = str(datetime.now())
time = list(time)
for i in range(10):
time.pop(len(time)-1)
time = ('').join(time)
time = ... | 1 | 2016-07-26T20:04:01Z | [
"python",
"datetime",
"formatting",
"twilio"
] |
Date/Time formatting | 38,598,738 | <p>I'm creating a python script that will display busy, no-answer and failed calls for a specific date but I'm stuck on the formatting of the date that's displayed. The start_time and end_time "variables" from Twilio print something like this: "Mon, 25 Jul 2016 16:03:53 +0000". I want to get rid of the day name and ... | 0 | 2016-07-26T19:51:13Z | 38,598,996 | <p>The format you need to parse is dictated by the timestamp provided by Twillo. You will likely need the following format string to properly parse the timestamp:</p>
<pre><code>print(datetime.datetime.strptime(call.start_time, "%a, %d %b %Y %H:%M:%S %z"))
</code></pre>
<p>A great guide for the formatting string is <... | 1 | 2016-07-26T20:08:02Z | [
"python",
"datetime",
"formatting",
"twilio"
] |
Raising errors without traceback | 38,598,740 | <p>I would like to use <code>raise</code> without printing the traceback on the screen. I know how to do that using <code>try ..catch</code> but doesn't find a way with <code>raise</code>.</p>
<p>Here is an example:</p>
<pre><code>def my_function(self):
resp = self.resp
if resp.status_code == 404:
rai... | 0 | 2016-07-26T19:51:18Z | 38,598,793 | <p>The problem is not with raising anything, but with what python interpreter does, when your program terminates with an exception (and it simply prints the stack trace). What you should do if you want to avoid it, is to put try except block around everything that you want to "hide" the stack trace, like:</p>
<pre><co... | 1 | 2016-07-26T19:54:41Z | [
"python",
"api",
"wrapper"
] |
Raising errors without traceback | 38,598,740 | <p>I would like to use <code>raise</code> without printing the traceback on the screen. I know how to do that using <code>try ..catch</code> but doesn't find a way with <code>raise</code>.</p>
<p>Here is an example:</p>
<pre><code>def my_function(self):
resp = self.resp
if resp.status_code == 404:
rai... | 0 | 2016-07-26T19:51:18Z | 38,598,932 | <p>Catch the exception, log it and return something that indicates something went wrong to the consumer (sending a 200 back when a query failed will likely cause problems for your client).</p>
<pre><code>try:
return do_something()
except NoSuchElementError as e:
logger.error(e)
return error_response()
</c... | 0 | 2016-07-26T20:03:42Z | [
"python",
"api",
"wrapper"
] |
Continuous random questions? | 38,598,837 | <p>I want the code I currently have to go through a list of questions infinitely or until someone gets an answer wrong. I am currently using</p>
<pre><code>random.shuffle(questions)
for question in questions:
question.ask()
</code></pre>
<p>to ask every question in a list once.</p>
<p>How do I make it continuou... | -3 | 2016-07-26T19:57:25Z | 38,599,164 | <p>you could loop through the list with a while loop something like this possibly</p>
<pre><code>score = 0
currIndex = 0
#ask a question to start off
q1 = questions[currIndex]
#get the answer
answer = q1.ask()
while(answer == q1.answer):
#ask the question at this index
score+=1
q1=questions[currIndex]
... | 0 | 2016-07-26T20:18:53Z | [
"python",
"class"
] |
Continuous random questions? | 38,598,837 | <p>I want the code I currently have to go through a list of questions infinitely or until someone gets an answer wrong. I am currently using</p>
<pre><code>random.shuffle(questions)
for question in questions:
question.ask()
</code></pre>
<p>to ask every question in a list once.</p>
<p>How do I make it continuou... | -3 | 2016-07-26T19:57:25Z | 38,600,682 | <p>It might be worth a try giving ask() a return value. True if the answer was correct and False if the answer was incorrect. That could look like this:</p>
<pre><code>def ask(self):
response = input(self.question)
if response == self.answer:
print "CORRECT"
return True
else:
print ... | 0 | 2016-07-26T22:09:47Z | [
"python",
"class"
] |
How do I install modules on qpython3 (Android port of python) | 38,598,880 | <p>I found this great module on within and downloaded it as a zip file. Once I extracted the zip file, i put the two modules inside the file(setup and the main one) on the module folder including an extra read me file I needed to run. I tried installing the setup file but I couldn't install it because the console could... | 0 | 2016-07-26T20:00:23Z | 39,323,863 | <p>Extract the zip file to the site-packages folder.
Find the qpyplus folder in that Lib/python3.2/site-packages extract here that's it.Now you can directly use your module from REPL terminal by importing it.</p>
| 0 | 2016-09-05T04:16:58Z | [
"python",
"module",
"qpython",
"qpython3"
] |
How do I install modules on qpython3 (Android port of python) | 38,598,880 | <p>I found this great module on within and downloaded it as a zip file. Once I extracted the zip file, i put the two modules inside the file(setup and the main one) on the module folder including an extra read me file I needed to run. I tried installing the setup file but I couldn't install it because the console could... | 0 | 2016-07-26T20:00:23Z | 39,722,699 | <p>The cleanest and simplest way I have found is to use pip from within QPython console as in <a href="http://stackoverflow.com/questions/12332975/installing-python-module-within-code">This Answer</a></p>
<pre><code>import pip
pip.main(['install', 'networkx'])
</code></pre>
| 0 | 2016-09-27T10:49:51Z | [
"python",
"module",
"qpython",
"qpython3"
] |
Python - Iterate through CSV rows and replace in XML | 38,598,927 | <p>I have a <strong>CSV with values that I would like to replace inside an XML template</strong>. Generating <strong>XMLs for each row</strong> that have filenames based on data in the same row. These are basically just copies of the template with a find and replace.
So far I have gotten the filenames to work correct... | 0 | 2016-07-26T20:03:33Z | 38,598,976 | <p>Check these examples , they are working perfectly</p>
<p><a href="http://stackoverflow.com/questions/20063987/python-create-xml-from-csv-within-a-loop">Python create XML from Csv within a loop</a></p>
<p><a href="http://code.activestate.com/recipes/577423-convert-csv-to-xml/" rel="nofollow">http://code.activestate... | 0 | 2016-07-26T20:07:08Z | [
"python",
"xml",
"csv"
] |
Python - Iterate through CSV rows and replace in XML | 38,598,927 | <p>I have a <strong>CSV with values that I would like to replace inside an XML template</strong>. Generating <strong>XMLs for each row</strong> that have filenames based on data in the same row. These are basically just copies of the template with a find and replace.
So far I have gotten the filenames to work correct... | 0 | 2016-07-26T20:03:33Z | 38,599,362 | <p>You have mentioned 'COLUMN_F' in the xml tag and you are trying to replace 'COLUMN_E' in the code </p>
<p>xml = xml.replace('COLUMN_E', exampleData[i+3][10])</p>
| 0 | 2016-07-26T20:33:00Z | [
"python",
"xml",
"csv"
] |
Python - Iterate through CSV rows and replace in XML | 38,598,927 | <p>I have a <strong>CSV with values that I would like to replace inside an XML template</strong>. Generating <strong>XMLs for each row</strong> that have filenames based on data in the same row. These are basically just copies of the template with a find and replace.
So far I have gotten the filenames to work correct... | 0 | 2016-07-26T20:03:33Z | 38,618,030 | <p>I was able to resolve this simply by moving the loop to the very top of the code.
The problem was it was replacing the text but then could not find the "COLUMN_*" because it had been replaced with a value. Moving the loop to the top resolved this.</p>
<pre><code>import csv
for i in range(5): #loops through 5... | 0 | 2016-07-27T16:01:22Z | [
"python",
"xml",
"csv"
] |
is there a detailed documentation for libpd Python API? | 38,598,973 | <p>I'm working with <a href="https://github.com/libpd" rel="nofollow">libpd</a> for Python, and I can't seem to find a detailed API. I would at least like a simple list of methods available.</p>
<p>The best I can find is here: <a href="https://github.com/libpd/libpd/wiki/Python-API" rel="nofollow">https://github.com/... | -1 | 2016-07-26T20:06:46Z | 38,607,028 | <p>assuming that you are really asking for a <code>detailed documentation for the API</code> rather than a <code>detailed API</code>:</p>
<p>the python-API of libpd is just a thin wrapper around the C-API.</p>
<p>Since the C-API is <a href="https://github.com/libpd/libpd/wiki/libpd" rel="nofollow">documented in the ... | 0 | 2016-07-27T07:55:00Z | [
"python",
"puredata",
"libpd"
] |
is there a detailed documentation for libpd Python API? | 38,598,973 | <p>I'm working with <a href="https://github.com/libpd" rel="nofollow">libpd</a> for Python, and I can't seem to find a detailed API. I would at least like a simple list of methods available.</p>
<p>The best I can find is here: <a href="https://github.com/libpd/libpd/wiki/Python-API" rel="nofollow">https://github.com/... | -1 | 2016-07-26T20:06:46Z | 38,857,181 | <p>So, what I found was you can use the C API documentation, BUT there are more methods and a PdManager class added to the Python version which were not documented (which were the things I wanted to know about)</p>
<p>So I documented those extra things here:</p>
<p><a href="http://mikesperone.com/files/libpdPythonAPI... | 0 | 2016-08-09T17:36:55Z | [
"python",
"puredata",
"libpd"
] |
Multi-Indexed fillna in Pandas | 38,599,012 | <p>I have a multi-indexed dataframe and I'm looking to backfill missing values within a group. The dataframe I have currently looks like this:</p>
<pre><code>df = pd.DataFrame({
'group': ['group_a'] * 7 + ['group_b'] * 3 + ['group_c'] * 2,
'Date': ["2013-06-11",
... | 1 | 2016-07-26T20:08:49Z | 38,599,152 | <p>Use <code>groupby(level=0)</code> then <code>bfill</code> and <code>update</code>:</p>
<pre><code>df.update(df.groupby(level=0).bfill())
df
</code></pre>
<p>Note: <code>update</code> changes <code>df</code> inplace.</p>
<p><a href="http://i.stack.imgur.com/XQU4B.png" rel="nofollow"><img src="http://i.stack.imgur.... | 2 | 2016-07-26T20:18:20Z | [
"python",
"pandas",
"missing-data",
"multi-index"
] |
print object/instance name in python | 38,599,015 | <p>I was wondering if there is a way to print the object name in python as a string. For example I want to be able to say ENEMY1 has 2 hp left or ENEMY2 has 4 hp left. Is there a way of doing that?\</p>
<pre><code>class badguy:
def __init__(self):
self.hp = 4
def attack(self):
print("hit")
... | 3 | 2016-07-26T20:09:18Z | 38,599,084 | <p>You'd have to first give them names. E.g.</p>
<pre><code>class badguy:
def __init__(self, name):
self.hp = 4
self.name = name
def attack(self):
print("hit")
self.hp -= 1
def still_alive(self):
if self.hp <=0:
print("enemy destroyed")
else ... | 1 | 2016-07-26T20:14:06Z | [
"python",
"object"
] |
print object/instance name in python | 38,599,015 | <p>I was wondering if there is a way to print the object name in python as a string. For example I want to be able to say ENEMY1 has 2 hp left or ENEMY2 has 4 hp left. Is there a way of doing that?\</p>
<pre><code>class badguy:
def __init__(self):
self.hp = 4
def attack(self):
print("hit")
... | 3 | 2016-07-26T20:09:18Z | 38,599,196 | <p>A much better <strong>design principle</strong> is not to rely on the specific name of the object as shown below:</p>
<pre><code>class badguy(object):
def __init__(self):
pass
b = badguy()
print b
>>> <__main__.badguy object at 0x7f2089a74e50> # Not a great name huh? :D
</code></pre>
<... | 5 | 2016-07-26T20:20:40Z | [
"python",
"object"
] |
Removing some of the duplicates from a list in Python | 38,599,066 | <p>I would like to remove a certain number of duplicates of a list without removing all of them. For example, I have a list <code>[1,2,3,4,4,4,4,4]</code> and I want to remove 3 of the 4's, so that I am left with <code>[1,2,3,4,4]</code>. A naive way to do it would probably be</p>
<pre><code>def remove_n_duplicates(... | 5 | 2016-07-26T20:13:25Z | 38,599,197 | <p>If you just want to remove the first <code>n</code> occurrences of something from a list, this is pretty easy to do with a generator:</p>
<pre><code>def remove_n_dupes(remove_from, what, how_many):
count = 0
for item in remove_from:
if item == what and count < how_many:
count += 1
... | 6 | 2016-07-26T20:20:48Z | [
"python",
"list",
"duplicates"
] |
Removing some of the duplicates from a list in Python | 38,599,066 | <p>I would like to remove a certain number of duplicates of a list without removing all of them. For example, I have a list <code>[1,2,3,4,4,4,4,4]</code> and I want to remove 3 of the 4's, so that I am left with <code>[1,2,3,4,4]</code>. A naive way to do it would probably be</p>
<pre><code>def remove_n_duplicates(... | 5 | 2016-07-26T20:13:25Z | 38,599,411 | <p>I can solve it in different way using collections.</p>
<pre><code>from collections import Counter
li = [1,2,3,4,4,4,4]
cntLi = Counter(li)
print cntLi.keys()
</code></pre>
| -1 | 2016-07-26T20:35:38Z | [
"python",
"list",
"duplicates"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.