content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
pyftpdlib slow .read on file blocks entire mainloop
Helllo,
I am using a custom AbstractFS on pyftpdlib that maps files on a HTTP server to FTP.
This files are returned by my implementation of open (of AbstractFS) which returns a httplib.HTTPResponse wrapped by the following class:
class HTTPConnWrapper:
def _... | pyftpdlib slow .read on file blocks entire mainloop | Helllo,
I am using a custom AbstractFS on pyftpdlib that maps files on a HTTP server to FTP.
This files are returned by my implementation of open (of AbstractFS) which returns a httplib.HTTPResponse wrapped by the following class:
class HTTPConnWrapper:
def __init__(self, obj, filename):
# make it more file... | [
"pyftpdlib uses Python's asyncore module which polls and interacts with dispatchers. Each time you map an FTP request to a request to the HTTP server you're blocking the asyncore loop that pydftpdlib is using. You should implement your HTTP requests as dispatchers that fit the asyncore model, or generate threads to... | [
2,
0
] | [] | [] | [
"asynchronous",
"asyncore",
"eventlet",
"ftp",
"python"
] | stackoverflow_0008599104_asynchronous_asyncore_eventlet_ftp_python.txt |
Q:
Django method to change User email not working
I am attempting to create a page where a user can see what their current email is and change it if they would like. I am just testing with a very simple form and a very simple HttpResponseRedirect if the form is not valid. However neither my email is changing for the ... | Django method to change User email not working | I am attempting to create a page where a user can see what their current email is and change it if they would like. I am just testing with a very simple form and a very simple HttpResponseRedirect if the form is not valid. However neither my email is changing for the user nor is my failure response if the form is not v... | [
"ChangeEmail is a normal form. These don't have save methods - only ModelForms do. You're correctly setting the user email from the form's cleaned_data - but you should be saving the user1 object, not the form.\nAlso, it's best not to redirect away on validation failure. Leave out that first else clause, and move t... | [
12,
2
] | [] | [] | [
"django",
"forms",
"python"
] | stackoverflow_0008619025_django_forms_python.txt |
Q:
Time out decorator on a multprocessing function
I have this decorator taken directly from an example I found on the net:
class TimedOutExc(Exception):
pass
def timeout(timeout):
def decorate(f):
def handler(signum, frame):
raise TimedOutExc()
def new_f(*args, **kwargs):
... | Time out decorator on a multprocessing function | I have this decorator taken directly from an example I found on the net:
class TimedOutExc(Exception):
pass
def timeout(timeout):
def decorate(f):
def handler(signum, frame):
raise TimedOutExc()
def new_f(*args, **kwargs):
old = signal.signal(signal.SIGALRM, handler)
... | [
"While I agree with the main point of Aaron's answer, I would like to elaborate a bit.\nThe processes launched by multiprocessing must be stopped in the function to be decorated; I don't think that this can be done generally and simply from the decorator itself (the decorated function is the only entity that knows ... | [
10,
2
] | [] | [] | [
"multiprocessing",
"python",
"signals",
"timeout"
] | stackoverflow_0008616630_multiprocessing_python_signals_timeout.txt |
Q:
Why do pythonistas call the current reference "self" and not "this"?
Python is the language I know the most, and strangely I still don't know why I'm typing "self" and not "this" like in Java or PHP.
I know that Python is older than Java, but I can't figure out where does this come from. Especially since you can u... | Why do pythonistas call the current reference "self" and not "this"? | Python is the language I know the most, and strangely I still don't know why I'm typing "self" and not "this" like in Java or PHP.
I know that Python is older than Java, but I can't figure out where does this come from. Especially since you can use any name instead of "self": the program will work fine.
So where does t... | [
"Smalltalk-80, released by Xerox in 1980, used self. Objective-C (early 1980s) layers Smalltalk features over C, so it uses self too. Modula-3 (1988), Python (late 1980s), and Ruby (mid 1990s) also follow this tradition.\nC++, also dating from the early 1980s, chose this instead of self. Since Java was designed ... | [
77,
31,
19,
18,
8,
7,
6,
2
] | [] | [] | [
"python"
] | stackoverflow_0001079983_python.txt |
Q:
threading with python : local variables trouble
I have some trouble using threading and scipy.stats.randint module. Indeed, when several threads are launched, a local array (bootIndexs in the code below) seems to be used for all launched thread.
This is the raised Error
> Exception in thread Thread-559:
Tracebac... | threading with python : local variables trouble | I have some trouble using threading and scipy.stats.randint module. Indeed, when several threads are launched, a local array (bootIndexs in the code below) seems to be used for all launched thread.
This is the raised Error
> Exception in thread Thread-559:
Traceback (most recent call last):
...
File "..\calculDomai... | [
"\nIndeed, when several threads are launched, a local array (bootIndexs in the code below) seems to be used for all launched thread.\n\nThat's the entire point of threads: lightweight tasks that share everything with their spawning process! :) If you are looking for a share-nothing solution, than you should perhaps... | [
2,
1
] | [] | [] | [
"local",
"multithreading",
"python",
"scipy"
] | stackoverflow_0008591737_local_multithreading_python_scipy.txt |
Q:
Serving html files in /var/www alongwith Django over Apache
I got my Apache Mod_WSGI and Django working following http://blog.stannard.net.au/2010/12/11/installing-django-with-apache-and-mod_wsgi-on-ubuntu-10-04/ with a twist that my 000-default site has the contents
<VirtualHost *:80>
ServerAdmin webmaster@localh... | Serving html files in /var/www alongwith Django over Apache | I got my Apache Mod_WSGI and Django working following http://blog.stannard.net.au/2010/12/11/installing-django-with-apache-and-mod_wsgi-on-ubuntu-10-04/ with a twist that my 000-default site has the contents
<VirtualHost *:80>
ServerAdmin webmaster@localhost
DocumentRoot /home/nipun/webdev/demo/demo
<Directory /ho... | [
"Firstly, I don't know why you keep talking about 'running' your HTML file. It's not a script, even if it has Javascript in it - that's just for the client. There's nothing to run, Apache just needs to serve the file.\nSecondly, you will obviously need some way of distinguishing requests that go to Django versus th... | [
1,
1
] | [] | [] | [
"apache",
"django",
"mod_wsgi",
"python"
] | stackoverflow_0008612961_apache_django_mod_wsgi_python.txt |
Q:
Show values in bar chart using pyplot
I have developed a tool to statistically analyze bugs and calculate metrics. I am using pyplot to generate graphs for the same. For bar chart, I have values on the Y axis and names of QA members on X- axis. So for each qa there is a bar. This is the code I am using right now -... | Show values in bar chart using pyplot | I have developed a tool to statistically analyze bugs and calculate metrics. I am using pyplot to generate graphs for the same. For bar chart, I have values on the Y axis and names of QA members on X- axis. So for each qa there is a bar. This is the code I am using right now -
xco = []
for i in range(len(labels)):
... | [
"If you want text on the top and bottom of the bars, see this answer, where you create an array 'names' that goes on the top and another array that is displayed for the tickmarks, such as:\nplt.xticks(ind+width/2., ('a', 'b','c', 'd', 'e'))\n\n"
] | [
1
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0008614065_matplotlib_python.txt |
Q:
SOAPpy - how to pass a security Header?
Im currently developing a python webservice for an application which uses Axis2 WS-Security
the simplified relevant code is
from SOAPpy import SOAPProxy
from SOAPpy import WSDL
file = 'path/to/my/file?wsdl'
server = WSDL.Proxy(file)
server.foo(bar)
when doing this i get:... | SOAPpy - how to pass a security Header? | Im currently developing a python webservice for an application which uses Axis2 WS-Security
the simplified relevant code is
from SOAPpy import SOAPProxy
from SOAPpy import WSDL
file = 'path/to/my/file?wsdl'
server = WSDL.Proxy(file)
server.foo(bar)
when doing this i get:
Traceback (most recent call last):
File "<... | [
"Check out the documentation on adding headers to a soapy request (https://svn.origo.ethz.ch/playmobil/trunk/contrib/pywebsvcs/SOAPpy/docs/UsingHeaders.txt). This way you can add your own custom headers to any request.\nHope this helps\n"
] | [
1
] | [] | [] | [
"axis2",
"python",
"soappy",
"web_services",
"webservice_client"
] | stackoverflow_0006301413_axis2_python_soappy_web_services_webservice_client.txt |
Q:
PyQT OSX Media Keys
I'm creating a music player app with PyQT and I've defined a couple them as toolbar buttons. I can easily set the shortcut with setShortcut, but how can I set them to the OS X Media Keys? I already have iTunes disabled on launch so that's no problem. The music player Clementine has them also wo... | PyQT OSX Media Keys | I'm creating a music player app with PyQT and I've defined a couple them as toolbar buttons. I can easily set the shortcut with setShortcut, but how can I set them to the OS X Media Keys? I already have iTunes disabled on launch so that's no problem. The music player Clementine has them also working when the applicatio... | [
"Did you try:\nQKeySequence(Qt.Key_MediaPlay)\n\nand others from http://developer.qt.nokia.com/doc/qt-4.8/qt.html ?\n",
"You only get global hot keys when you use the OSX native methods which seemingly change every minor release. An older example of this (i.e. doesn't work in Lion AFAIK) is available in libQxt\nh... | [
1,
1
] | [] | [] | [
"pyqt",
"pyqt4",
"python"
] | stackoverflow_0008535867_pyqt_pyqt4_python.txt |
Q:
In Python IDLE, what's the difference between 'print'ing a variable and just writing the variable?
At the IDLE interpreter I do the following with dpkt:
for ts, buf in pcap:
eth = dpkt.ethernet.Ethernet(buf)
Now, when I try to see the contents of 'eth' I can either print it, or just write the variable name.
Wh... | In Python IDLE, what's the difference between 'print'ing a variable and just writing the variable? | At the IDLE interpreter I do the following with dpkt:
for ts, buf in pcap:
eth = dpkt.ethernet.Ethernet(buf)
Now, when I try to see the contents of 'eth' I can either print it, or just write the variable name.
When I do:
print eth
I get:
O&áÿE(r @,òÀ¨
DYP?Jò}PªpÉ
However, when I simply write:
eth
I get the more ... | [
"print(variable) equals to print(str(variable))\nwhereas\nvariable equals to print(repr(variable))\nMy guess is that the __repr__ and __str__ method of the class dpkt.ethernet.Ethernet produce these completely different results.\nUpdate: Having a look at the source code tells me I am right.\n",
"There are two fun... | [
10,
3
] | [] | [] | [
"printing",
"python",
"python_idle",
"variables"
] | stackoverflow_0008621000_printing_python_python_idle_variables.txt |
Q:
proper way to distribute run scripts with python package?
Suppose I have a python package called mypackage, which has a series of scripts. Once mypackage is in the site-packages dir, the user can refer to various Python files within mypackage as mypackage.submodule1, mypackage.submodule2 from Python, as usual. Ho... | proper way to distribute run scripts with python package? | Suppose I have a python package called mypackage, which has a series of scripts. Once mypackage is in the site-packages dir, the user can refer to various Python files within mypackage as mypackage.submodule1, mypackage.submodule2 from Python, as usual. However, some of these are scripts that are meant to be called fr... | [
"See http://docs.python.org/distutils/setupscript.html#installing-scripts\nThe general idea is to distribute a setup.py file, such that when a user runs python setup.py install, the script gets placed on the path. Nearly all of the package distribution methods support this. If you follow the above documentation, us... | [
4,
0
] | [] | [] | [
"distutils",
"module",
"package",
"python",
"pythonpath"
] | stackoverflow_0008620789_distutils_module_package_python_pythonpath.txt |
Q:
numpy: ndenumerate for masked arrays?
Is there a way to enumerate over the non-masked locations of a masked numpy ndarray (e.g. in the way that ndenumerate does it for regular ndarrays, but omitting all the masked entries)?
EDIT: to be more precise: the enumeration should not only skip over the masked entries, but... | numpy: ndenumerate for masked arrays? | Is there a way to enumerate over the non-masked locations of a masked numpy ndarray (e.g. in the way that ndenumerate does it for regular ndarrays, but omitting all the masked entries)?
EDIT: to be more precise: the enumeration should not only skip over the masked entries, but also show the indices of the non-masked on... | [
"You can access only valid entries using inverse of a mask as an index:\n>>> import numpy as np\n>>> import numpy.ma as ma\n>>> x = np.array([11, 22, -1, 44])\n>>> m_arr = ma.masked_array(x, mask=[0, 0, 1, 0])\n>>> for index, i in np.ndenumerate(m_arr[~m_arr.mask]): \n print index, i\n(0,) 11\n(1,) 22\n(2,) ... | [
8,
3
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0008620798_numpy_python.txt |
Q:
xgoogle library fails with AttributeError
I am try to use the xgoogle python library for the purpose of me entering a term, and it returning how many search results there are for it. Here is my code:
from xgoogle.search import GoogleSearch
word1 = 'aardvark'
word2 = 'ablaze'
words = word1,"",word2
gs = GoogleSearc... | xgoogle library fails with AttributeError | I am try to use the xgoogle python library for the purpose of me entering a term, and it returning how many search results there are for it. Here is my code:
from xgoogle.search import GoogleSearch
word1 = 'aardvark'
word2 = 'ablaze'
words = word1,"",word2
gs = GoogleSearch(words)
num = gs.num_results
print num
This i... | [
"You're passing words as a tuple. Try to concat the words together instead:\ngs = GoogleSearch(word1 + \" \" + word2)\n\n",
"Passing a string is simplest -- there is no need to create multiple variables.\ngs = GoogleSearch(\"hello world\")\n\nOr, if you have strings bound to multiple variables, you can join them,... | [
1,
1
] | [] | [] | [
"python",
"search",
"xgoogle"
] | stackoverflow_0005227773_python_search_xgoogle.txt |
Q:
Discrepency in Python's lxml's equivalent parsing methods on HTML: cssselect vs xpath
I was attempting to parse example.com's home page with xpath and cssselect but it seems as though either I don't know how xpath works, or lxml's xpath is broken, as it is missing matches.
Here's the quick and dirty code.
from lxm... | Discrepency in Python's lxml's equivalent parsing methods on HTML: cssselect vs xpath | I was attempting to parse example.com's home page with xpath and cssselect but it seems as though either I don't know how xpath works, or lxml's xpath is broken, as it is missing matches.
Here's the quick and dirty code.
from lxml.html import *
mySearchTree = parse('http://www.example.com').getroot()
for a in mySearchT... | [
"Possibly something else is going on (I didn't examine the sample document closely), but your CSS selector and XPath are not equivalent.\nCSS tr a is //tr//a in XPath. .//tr/*/a means (conceptually, not precisely):\n\n.: current node\n//: all descendants of current node\ntr: all tr elements among all descendants o... | [
3,
1
] | [] | [] | [
"css_selectors",
"lxml",
"python",
"xpath"
] | stackoverflow_0008621113_css_selectors_lxml_python_xpath.txt |
Q:
Python Matrix: Value not in list error
I am writing a Python program that creates a 9x9 matrix with all of the values being 0. Then I have to manually put in the a actual values I want to be in it. (That is why I have all of the inserts.) I am trying to use the list.remove(x) command with list being the matrix and... | Python Matrix: Value not in list error | I am writing a Python program that creates a 9x9 matrix with all of the values being 0. Then I have to manually put in the a actual values I want to be in it. (That is why I have all of the inserts.) I am trying to use the list.remove(x) command with list being the matrix and x being the value I am trying to remove. I ... | [
"In Python, a string is not the same as a list. You want\nmatrix.remove([0, 0, ..., 0])\n\nand not\nmatrix.remove(\"[0, 0, ..., 0]\")\n\nBut simpler would be just to construct the matrix correctly in the first place.\nmatrix = [\n [0, 0, 0, 5, 0, 0, 0, 0, 6],\n [8, 0, 0, 0, 4, 7, 5, 0, 3],\n [0, 5, 0, 0, 0... | [
4,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0008621240_python.txt |
Q:
wx.Validator doesn't get called
I have a simple form with a multi line text control and Ok/Cancel buttons on it. I want to check whether the text control has text when Ok button is clicked or not. I'm trying to use the wx.Validator for this purpose, but for some reason it is never get called even the extra style w... | wx.Validator doesn't get called | I have a simple form with a multi line text control and Ok/Cancel buttons on it. I want to check whether the text control has text when Ok button is clicked or not. I'm trying to use the wx.Validator for this purpose, but for some reason it is never get called even the extra style wx.WS_EX_VALIDATE_RECURSIVELY is appli... | [
"Instead of:\nself.txt.Validate()\n\nuse:\nself.Validate()\n\n"
] | [
2
] | [] | [] | [
"python",
"validation",
"wxpython"
] | stackoverflow_0008620805_python_validation_wxpython.txt |
Q:
(SWIG C++ to Python) warning 301: class keyword used, but not in C++ mode
I am attempting to compile a C++ extension for python.
I have created an interface file foo.i which looks like this:
%module foo
%include "typemaps.i" // For pointers to primitive types
%include "std_string.i" ... | (SWIG C++ to Python) warning 301: class keyword used, but not in C++ mode | I am attempting to compile a C++ extension for python.
I have created an interface file foo.i which looks like this:
%module foo
%include "typemaps.i" // For pointers to primitive types
%include "std_string.i" // std::string mapping
%apply const std::string& {std::stri... | [
"You need to call SWIG with -c++ when you call it if you're using C++.\n"
] | [
15
] | [] | [] | [
"c++",
"python",
"swig"
] | stackoverflow_0008619112_c++_python_swig.txt |
Q:
How to avoid the "This message may not have been sent by" warning when sending email using Google App Engine?
I have a python GAE app that sends emails like in the example using the address of a registered administrator for the application as the "sender" address. When an email arrives from such an API call, here'... | How to avoid the "This message may not have been sent by" warning when sending email using Google App Engine? | I have a python GAE app that sends emails like in the example using the address of a registered administrator for the application as the "sender" address. When an email arrives from such an API call, here's a pic of the attached warning.
This message may not have been sent by: EmergencyButtonApp@gmail.com
Learn mor... | [
"Assuming you're seeing this in production, it's probably because you're claiming to be from a gmail address, but sending via App Engine. Use one of your app's email addresses as the sender (foo@yourapp.appspotmail.com) and it should work fine.\n",
"I think the best solution is to use Google's SMTP servers... It'... | [
8,
0
] | [] | [] | [
"email",
"google_app_engine",
"python"
] | stackoverflow_0008620252_email_google_app_engine_python.txt |
Q:
Whats the most pythonic way to generate a list of dates from two dates
I want to generate a list of dates (Nth day of the week) between two dates.
For example, given the dates "20111101" and "20111201", Assume I want to generate the 3rd Wednesday of the month dates, I want to generate dates :
["20111116", "201112... | Whats the most pythonic way to generate a list of dates from two dates | I want to generate a list of dates (Nth day of the week) between two dates.
For example, given the dates "20111101" and "20111201", Assume I want to generate the 3rd Wednesday of the month dates, I want to generate dates :
["20111116", "20111221"]
So I want to write a function like this:
def generateNthWeekdayDatesLi... | [
"This is a case where using a generator is very suitable/pythonic.\ndef nth_day_of_month(start, end, nth, weekday):\n assert start.day == 1, \"start on the first day of a month\"\n assert nth > 0\n assert 1 <= weekday <= 7\n\n candidate = start\n seen_in_month = 0\n while candidate <= end:\n ... | [
1,
1,
1
] | [
"Ah yes - the IMM date problem.\nIt's an infinite series. So the solution needs to take care of that. \n\nDon't use strings, use datetime.date which you can then convert to strings.\n\nI would write something like this.\nclass IMMDate (object):\n\n @staticmethod\n def next (when):\n '''\n return... | [
-1
] | [
"python"
] | stackoverflow_0008613565_python.txt |
Q:
How to upload a file to a custom file path
I am trying to set up a system in which user uploaded files will be given a path based on username and filename. The answer to this question seems to have pointed me in the right direction, but I'm having a little trouble with the implementation from the view.
I have a mo... | How to upload a file to a custom file path | I am trying to set up a system in which user uploaded files will be given a path based on username and filename. The answer to this question seems to have pointed me in the right direction, but I'm having a little trouble with the implementation from the view.
I have a model that uses this:
class Document(models.Model)... | [
"Do you have enctype=\"multipart/form-data\" set in your <form> tag? If request.FILES is empty, the problem isn't with your dynamic path generation (it hasn't gotten that far yet).\n",
"First off, like @jknupp pointed out, don't forget to use enctype=\"multipart/form-data\". Next you can try creating a form for y... | [
1,
0
] | [] | [] | [
"django",
"file_upload",
"python"
] | stackoverflow_0008621359_django_file_upload_python.txt |
Q:
What is the difference between `>>> some_object` and `>>> print some_object` in the Python interpreter?
In the interpreter you can just write the name of an object e.g. a list a = [1, 2, 3, u"hellö"] at the interpreter prompt like this:
>>> a
[1, 2, 3, u'hell\xf6']
or you can do:
>>> print a
[1, 2, 3, u'hell\xf6'... | What is the difference between `>>> some_object` and `>>> print some_object` in the Python interpreter? | In the interpreter you can just write the name of an object e.g. a list a = [1, 2, 3, u"hellö"] at the interpreter prompt like this:
>>> a
[1, 2, 3, u'hell\xf6']
or you can do:
>>> print a
[1, 2, 3, u'hell\xf6']
which seems equivalent for lists. At the moment I am working with hdf5 to manage some data and I realized ... | [
"Typing an object into the terminal calls __repr__(), which is for a detailed representation of the object you are printing (unambiguous). When you tell something to 'print', you are calling __str__() and therefore asking for something human readable.\nAlex Martelli gave a great explanation here. Other responses ... | [
8,
2,
1,
0,
0
] | [] | [] | [
"behavior",
"printing",
"python"
] | stackoverflow_0007114675_behavior_printing_python.txt |
Q:
How to convert an array of dates (format 'mm/dd/yy HH:MM:SS') to numerics?
I have recently (1 week) decided to migrate my work to Python from matlab. Since I am used to matlab, I am finding it difficult sometimes to get the exact equivalent of what I want to do in python.
Here's my problem:
I have a set of csv f... | How to convert an array of dates (format 'mm/dd/yy HH:MM:SS') to numerics? | I have recently (1 week) decided to migrate my work to Python from matlab. Since I am used to matlab, I am finding it difficult sometimes to get the exact equivalent of what I want to do in python.
Here's my problem:
I have a set of csv files that I want to process. So far, I have succeeded in loading them into group... | [
"The closest thing in Python for matlab's matrix/vector operation is list comprehension. If you would like to apply a Python function on each item in a list you could do:\nnew_list = [date2num(data) for data in old_list]\n\nor\nnew_list = map(date2num, old_list)\n\n",
"you could use a generator:\ndef pre_process(... | [
0,
0
] | [] | [] | [
"date",
"python",
"time"
] | stackoverflow_0008621448_date_python_time.txt |
Q:
My Tkinter GUI is too ... static?
I use a Tkinter GUI to intiate a measurement and analysis process, which basically gets going with a clicked button. Since those measurements can take a while, I tried to include a progress bar, namely this one:
http://tkinter.unpythonic.net/wiki/ProgressMeter
But when I do initia... | My Tkinter GUI is too ... static? | I use a Tkinter GUI to intiate a measurement and analysis process, which basically gets going with a clicked button. Since those measurements can take a while, I tried to include a progress bar, namely this one:
http://tkinter.unpythonic.net/wiki/ProgressMeter
But when I do initiate the process, my whole Tkinter window... | [
"Make a progressbar (these are snippets from my code that processes a 67MB file.)\nprogress = ttk.Progressbar(bottommenuframe, orient=HORIZONTAL, length=100, maximum=190073, mode='determinate')\nprogress.pack(side=RIGHT)\n\nprogress.start() ## this starts the progressbar\n\nthen during your analysis:\ndef analy... | [
2,
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0007684900_python_tkinter.txt |
Q:
Optimizing 3d point hash function
I have a 3-dimensional point class whose hash function, according to the profiler, would be a good place to do some optimizing. Right now, I'm just passing a tuple of the coordinates to the built-in hash function:
def __hash__(self):
return hash((self.x, self.y, self.z))
... | Optimizing 3d point hash function | I have a 3-dimensional point class whose hash function, according to the profiler, would be a good place to do some optimizing. Right now, I'm just passing a tuple of the coordinates to the built-in hash function:
def __hash__(self):
return hash((self.x, self.y, self.z))
How can I make this faster? I'm assumin... | [
"Using a tuple instead of your own class will be much faster.\nIf you really want to write p.x instead of p[0] then you can make your class a subclass of tuple and have accessors. It will still be much faster than implementing your own tuple.\nclass Point3d(tuple):\n @property\n def x(self):\n return s... | [
5,
1
] | [] | [] | [
"hash",
"optimization",
"python"
] | stackoverflow_0008621283_hash_optimization_python.txt |
Q:
Make a window appear on top of another, block access to other windows until button clicked
Python 2.7, PyQt4.8.5
I want to have a main app window and then a second pop up window to display com port settings. This window should always be on top of the parent window until either the ok or the cancel button is click... | Make a window appear on top of another, block access to other windows until button clicked | Python 2.7, PyQt4.8.5
I want to have a main app window and then a second pop up window to display com port settings. This window should always be on top of the parent window until either the ok or the cancel button is clicked; closing the child window. (sort of like a required answer i.e. cant process until you choose... | [
"You want a modal dialog. For example:\ndialog = QInputDialog()\ndialog.exec_()\n\nYou can either implement your own dialog widget (by subclassing QDialog) or use one of the several available.\n"
] | [
3
] | [] | [] | [
"always_on_top",
"pyqt",
"python"
] | stackoverflow_0008622090_always_on_top_pyqt_python.txt |
Q:
Which optimization algorithm does scipy.optimize.leastsq use?
Does anyone know which optimization algorithm specifically is implemented in scipy.optimize.leastsq?
A:
According to the documentation:
“leastsq” is a wrapper around MINPACK’s lmdif and lmder algorithms.
So (as @tillsten points out) that’s a Levenbe... | Which optimization algorithm does scipy.optimize.leastsq use? | Does anyone know which optimization algorithm specifically is implemented in scipy.optimize.leastsq?
| [
"According to the documentation:\n\n“leastsq” is a wrapper around MINPACK’s lmdif and lmder algorithms.\n\nSo (as @tillsten points out) that’s a Levenberg–Marquardt implementation.\n"
] | [
8
] | [] | [] | [
"least_squares",
"optimization",
"python",
"scipy"
] | stackoverflow_0008622145_least_squares_optimization_python_scipy.txt |
Q:
Python application builder/packager
I'm writing a program in python using PySide(PyQt) and I want to distribute it to friends and family when I'm finished. I have looked at other posts in stack overflow, but I can't seem to find any good ones showing an easy solution(command line or otherwise) that will create an ... | Python application builder/packager | I'm writing a program in python using PySide(PyQt) and I want to distribute it to friends and family when I'm finished. I have looked at other posts in stack overflow, but I can't seem to find any good ones showing an easy solution(command line or otherwise) that will create an executable for my program to be run on ot... | [
"I have used PyInstaller to create executables for scripts using PyQt4 under Windows without any trouble. Though I have not used it on Linux, it claims Linux (and OSX) support as well. You may need to create your Windows binaries in a Windows system or through Wine according to the FAQ:\n\n\nCan I package Windows b... | [
1
] | [] | [] | [
"build",
"executable",
"python",
"qt"
] | stackoverflow_0008622086_build_executable_python_qt.txt |
Q:
Fast duplicates removal in numpy and python
Is there any fast way to obtain unique elements in numpy? I have code similar to this (the last line)
tab = numpy.arange(100000000)
indices1 = numpy.random.permutation(10000)
indices2 = indices1.copy()
indices3 = indices1.copy()
indices4 = indices1.copy()
result = nump... | Fast duplicates removal in numpy and python | Is there any fast way to obtain unique elements in numpy? I have code similar to this (the last line)
tab = numpy.arange(100000000)
indices1 = numpy.random.permutation(10000)
indices2 = indices1.copy()
indices3 = indices1.copy()
indices4 = indices1.copy()
result = numpy.unique(numpy.array([tab[indices1], tab[indices2... | [
"[What follows is actually partially incorrect (see the PS):] \nThe following way of obtaining the unique elements in all sub-arrays is very fast:\nseq = itertools.chain(tab[indices1].flat, tab[indices2].flat, tab[indices3].flat, tab[indices4].flat)\nresult = set(seq)\n\nNote that flat (which returns an iterator) i... | [
4,
3
] | [] | [] | [
"arrays",
"numpy",
"optimization",
"performance",
"python"
] | stackoverflow_0008620521_arrays_numpy_optimization_performance_python.txt |
Q:
How to parse FQL response of Facebook pages by category and/or location? (Python)
Long time listener, first time caller..
I'm getting a good result from my Facebook Open Graph API query:
fbtest = graph.request("/fql", {"q": "SELECT name, page_id, categories, location
FROM page WHERE page_id IN (SELECT page_id FRO... | How to parse FQL response of Facebook pages by category and/or location? (Python) | Long time listener, first time caller..
I'm getting a good result from my Facebook Open Graph API query:
fbtest = graph.request("/fql", {"q": "SELECT name, page_id, categories, location
FROM page WHERE page_id IN (SELECT page_id FROM page_fan WHERE uid=me())"})
And although I've taken Zed's great course on Learning P... | [
"If I understand correctly, you're just looking to filter the end result here? If you haven't already, go ahead and convert the json string to a python object\nimport json\nresp = json.loads(fql_resp)\ndata = resp['data']\n\nThe loads stands for load string which is what you'll be getting back from the service. Fro... | [
1
] | [] | [] | [
"facebook",
"facebook_fql",
"facebook_opengraph",
"python"
] | stackoverflow_0008621634_facebook_facebook_fql_facebook_opengraph_python.txt |
Q:
Shift+Backspace is Writing a Checkmark Symbol?
I can't even copy and paste a strange checkmark looking character from my IDLE interpreter session into this text field...I am running Linux Mint Julia, python version 2.6, but it also happens in 3.1. This occurs after holding the shift key and pressing backspace.
I t... | Shift+Backspace is Writing a Checkmark Symbol? | I can't even copy and paste a strange checkmark looking character from my IDLE interpreter session into this text field...I am running Linux Mint Julia, python version 2.6, but it also happens in 3.1. This occurs after holding the shift key and pressing backspace.
I tried doing this:
>>> ord('[strange-checkmark]')
8
T... | [
"It's a confirmed bug within Tkinter, and not necessarily IDLE. See Issue 1482122.\nIn brief: If you want to fix it, you're welcome to try xmodmap -e \"keycode 22 = BackSpace\", but you run the risk of no longer being able to issue a Ctrl+Alt+Backspace to kill your X Server.\nI can keep looking for more informati... | [
2
] | [] | [] | [
"backspace",
"ordinals",
"python",
"python_idle"
] | stackoverflow_0008622408_backspace_ordinals_python_python_idle.txt |
Q:
Python using urllib to authenticate to a webpage
I have read the other posts on this, but my situation is a bit unique I think. I am trying to use python to read my grades off of the school's home access center website, but I think there is something peculiar in the way they have it programmed, here is the code th... | Python using urllib to authenticate to a webpage | I have read the other posts on this, but my situation is a bit unique I think. I am trying to use python to read my grades off of the school's home access center website, but I think there is something peculiar in the way they have it programmed, here is the code that I am using:
import urllib
def WebLogin(password):
... | [
"urlopen returns a file-like object. In particular, you can only call read() once (with no arguments -- you can read in chunks by passing a size to read, but ya) -- subsequent calls to read() will return None because you've exhausted it (and unlike regular file objects, there is no seek method). You should store th... | [
3
] | [] | [] | [
"parsing",
"python",
"urllib"
] | stackoverflow_0008622754_parsing_python_urllib.txt |
Q:
Using python, how can I merge or join two lists so that their values don't overlap?
First off, I apologize for my inaccurate vocabulary. I am an absolute ground-zero beginner. Anyways, I am attempting to solve this problem:
http://projecteuler.net/problem=1
To be brief, I'm trying to write a script that will find... | Using python, how can I merge or join two lists so that their values don't overlap? | First off, I apologize for my inaccurate vocabulary. I am an absolute ground-zero beginner. Anyways, I am attempting to solve this problem:
http://projecteuler.net/problem=1
To be brief, I'm trying to write a script that will find the sum of all the multiples of 3 or 5 below 1000.
My (extremely basic) approach was wit... | [
"You can use a set to eliminate the duplicates:\n>>> len(x)\n333\n>>> len(y)\n199\n>>> s = set(x + y)\n>>> len(s)\n532\n\nThen you can sum the members of the set instead.\n",
"It is called inclusion exclusion principle so you can do like\n##Multiples of 3\nx = range(3, 1000, 3)\n\n##Multiples of 5\ny = range(5, 1... | [
4,
4,
2,
1,
1,
0
] | [] | [] | [
"list",
"python",
"range"
] | stackoverflow_0008622493_list_python_range.txt |
Q:
Installing a library in Eclipse?
I am looking for the step by step process for installing a new library. I am new to Eclipse and real development work (I only roughly know what a 'bin' and 'lib' are for).
There are similar questions but none have a step by step walkthrough. Thanks for your time!
Some details if it... | Installing a library in Eclipse? | I am looking for the step by step process for installing a new library. I am new to Eclipse and real development work (I only roughly know what a 'bin' and 'lib' are for).
There are similar questions but none have a step by step walkthrough. Thanks for your time!
Some details if it helps your example:
I am using Eclip... | [
"All you should need to do is\neasy_install pydelicious\n\nin Terminal.app. It says so right on the project home page.\n"
] | [
0
] | [] | [] | [
"eclipse",
"installation",
"python"
] | stackoverflow_0008622961_eclipse_installation_python.txt |
Q:
Passing a pointer to a list in Python
Is there any way to pass a pointer to a list, so I could have
update_list(list, data)
Instead of having to do
list = update_list(list, data)
Independent of whether this is possible, what is advisable and Pythonic in this situation?
A:
I recommend reading Semantics of Python ... | Passing a pointer to a list in Python | Is there any way to pass a pointer to a list, so I could have
update_list(list, data)
Instead of having to do
list = update_list(list, data)
Independent of whether this is possible, what is advisable and Pythonic in this situation?
| [
"I recommend reading Semantics of Python variable names from a C++ perspective:\n\nAll variables are references\n\nThis is oversimplification of the entire article, but this (and the understanding that a list is a mutable type) should help you understand how the following example works.\nIn [5]: def update_list(lst... | [
10,
4,
1,
1,
0
] | [] | [] | [
"list",
"pointers",
"python"
] | stackoverflow_0008622769_list_pointers_python.txt |
Q:
How can I add certain values that were produced in a 'while' loop using Python
I was solving a Project Euler problem that goes as follows:
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms."
So I used this script to print the Fibonac... | How can I add certain values that were produced in a 'while' loop using Python | I was solving a Project Euler problem that goes as follows:
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms."
So I used this script to print the Fibonacci sequence up to four million:
a = 0
b = 1
while b < 4000000:
print b
a, b ... | [
"If you're averse to variable assignments, you might enjoy a functional approach:\n>>> from itertools import takewhile, ifilter\n\n>>> def fib():\n a, b = 0, 1\n while True:\n yield a\n a, b = b, a+b\n\n>>> def is_even(x):\n return x % 2 == 0\n\n>>> sum(ifilter(is_even, (t... | [
6,
2,
1
] | [] | [] | [
"fibonacci",
"python",
"while_loop"
] | stackoverflow_0008622889_fibonacci_python_while_loop.txt |
Q:
converting a list of strings into a tuple
Hello i am trying to do a dictionary by using Python,
What needs to be done is python reads a text file which has values inside such as:
good buono
What I have done was, open the file with file function and replace tabs and add reversed comma to create a list so it loo... | converting a list of strings into a tuple | Hello i am trying to do a dictionary by using Python,
What needs to be done is python reads a text file which has values inside such as:
good buono
What I have done was, open the file with file function and replace tabs and add reversed comma to create a list so it looks like
["('good', 'buono')", "('afternoon', '... | [
"Assuming that every pair of words is on a separate line in your file, you could do this:\nmydict = {line.split()[0]: line.split()[1] for line in myfile}\n\nThis transforms a file like\ngood buono\nafternoon pomeriggo\nthanks grazie\n\ninto\n{\"good\": \"buono\", \"afternoon\": \"pomeriggo\", \"thanks\": \"... | [
4,
4,
1
] | [] | [] | [
"dictionary",
"list",
"python",
"tuples"
] | stackoverflow_0008623395_dictionary_list_python_tuples.txt |
Q:
Python: comparing lists by rules
Input data:
rules = (
("1|1": "A"),
("2|1": "B"),
("3|1": "C"),
("2|2": "X")
)
pattern = [[1,2,3], [7,8]]
I need a function to do this job for the below result:
list1 = [[1,3,4], [7,9]] # result: B
list2 = [[1,2,3], [7,9]] # result: C
list3 = [[0,5,4], [8,5]] # re... | Python: comparing lists by rules | Input data:
rules = (
("1|1": "A"),
("2|1": "B"),
("3|1": "C"),
("2|2": "X")
)
pattern = [[1,2,3], [7,8]]
I need a function to do this job for the below result:
list1 = [[1,3,4], [7,9]] # result: B
list2 = [[1,2,3], [7,9]] # result: C
list3 = [[0,5,4], [8,5]] # result: None
list4 = [[1,6,2], [7,8]] # ... | [
"A bit of functional Python:\n>>> rules = {\n \"1|1\": \"A\",\n \"2|1\": \"B\",\n \"3|1\": \"C\",\n \"2|2\": \"X\"\n}\n>>> pattern = [[1,2,3], [7,8]]\n>>> l = [[1,3,4], [7,9]]\n>>> diffs = '|'.join(map(lambda x: str(len(set(x[0]) & set(x[1]))),\n zip(pattern, l)))\n>>> rules.get(... | [
3
] | [] | [] | [
"algorithm",
"python"
] | stackoverflow_0008623549_algorithm_python.txt |
Q:
How to go about internationalization?
I'm building a web application that will be in a single language (Dutch) at launch. However, at some point it might be translated to other languages as well, which is why I want to have internationalization build in from the start.
The problem is that currently there are 3 se... | How to go about internationalization? | I'm building a web application that will be in a single language (Dutch) at launch. However, at some point it might be translated to other languages as well, which is why I want to have internationalization build in from the start.
The problem is that currently there are 3 separate places that display strings, namely ... | [
"As far as I know, gettext is the most widely used tool for i18n. However, every language and framework implements it's own wrappers around this:\n\npython: gettext module\nflask, jinja2, WTForms: flask-babel extension\njavascript, jquery: gettext plugin\n\nAll of them should use the same translation files, so they... | [
5
] | [] | [] | [
"flask",
"internationalization",
"javascript",
"jinja2",
"python"
] | stackoverflow_0008623576_flask_internationalization_javascript_jinja2_python.txt |
Q:
django - reusing a login template
I'm just curious if I'm doing this right.
I'm coding a private section of a website and wrote a login view which throws up a login window. I want to reuse this view for several urls which all go to a different views once access is granted. It doesn't appear that you can pass argu... | django - reusing a login template | I'm just curious if I'm doing this right.
I'm coding a private section of a website and wrote a login view which throws up a login window. I want to reuse this view for several urls which all go to a different views once access is granted. It doesn't appear that you can pass arguments in the statements in urls.py, so ... | [
"\nIt doesn't appear that you can pass arguments in the statements in\n urls.py\n\nYou can, actually. \nThe third item in the url conf can be a dictionary of kwargs which will be passed your view function.\n(r'^my_url/$', 'login', {'redirect': admin}),\n(r'^my_other_url/$', 'login', {'redirect': beta}),\n\n",
"Y... | [
5,
2,
0
] | [] | [] | [
"authentication",
"django",
"python"
] | stackoverflow_0008623101_authentication_django_python.txt |
Q:
Python, MySQL and cursors that fetch maps
After executing a query statement on a MySQL database connection, I perform:
rows = cursor.fetchall()
This gives an array of arrays. I'd like to have an array of dictionaries, where each dictionary takes its keys from the requested column names of my table and associates ... | Python, MySQL and cursors that fetch maps | After executing a query statement on a MySQL database connection, I perform:
rows = cursor.fetchall()
This gives an array of arrays. I'd like to have an array of dictionaries, where each dictionary takes its keys from the requested column names of my table and associates the values from the table.
How do I do this?
| [
"Well, you forgot to mention which mysql library you're using.\n\nIf using oursql (which I recommend, it is certainly the best one), use oursql's DictCursor. Example:\nconn = oursql.connect(...)\ncurs = conn.cursor(oursql.DictCursor)\n\nIf using MySQLdb (why?) Use MySQLdb's DictCursor. Example:\nconn = MySQLdb.conn... | [
15
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0008623938_mysql_python.txt |
Q:
BigInteger exponentiation with negative number
How can I do the same as in this python (using sage) code:
def elGamalDecrypt(c1, c2, p, x):
return Mod(c2*c1^(-x),p)
with standard Java 7 libraries? All numbers are BigInteger.
I've tried a lot with no avail. In Python it's really simple and FAST.
A:
The BigIn... | BigInteger exponentiation with negative number | How can I do the same as in this python (using sage) code:
def elGamalDecrypt(c1, c2, p, x):
return Mod(c2*c1^(-x),p)
with standard Java 7 libraries? All numbers are BigInteger.
I've tried a lot with no avail. In Python it's really simple and FAST.
| [
"The BigInteger class in Java 7 has a modPow method, which handles modular exponentiation. So, something like the following should work (although I haven't tested it):\nc2.multiply(c1.modPow(x.negate(), p)).mod(p)\n\nThe modPow method will only accept a negative exponent -x if c1 and p are coprime. (The name p su... | [
3,
0
] | [] | [] | [
"algorithm",
"encryption",
"java",
"python",
"security"
] | stackoverflow_0008623862_algorithm_encryption_java_python_security.txt |
Q:
Why does python output to a file like this?
Trying to have a user input their name, copy that variable to a file, and then read it back. However, when read back, it only says [][]
My code looks like this (currently)
Name = raw_input("What is your Name? ")
print "you entered ", Name
fo = open("foo.txt", "r+")
fo.wr... | Why does python output to a file like this? | Trying to have a user input their name, copy that variable to a file, and then read it back. However, when read back, it only says [][]
My code looks like this (currently)
Name = raw_input("What is your Name? ")
print "you entered ", Name
fo = open("foo.txt", "r+")
fo.write (Name)
str = fo.read();
print "Read String is... | [
"First, you've opened the file in mode \"r+\" which is read-write. This will not empty the file, and anything you write will overwrite existing bytes. This is almost certainly not what you want: either 'a' if you want to append to the file, or 'w' if you want to delete the file first if it already exists.\nSecond, ... | [
5,
0,
0
] | [] | [] | [
"python",
"python_2.7",
"windows"
] | stackoverflow_0008624185_python_python_2.7_windows.txt |
Q:
Documenting files with "from x import *"
Can sphinx's .. automodule:: and other automatic features be used to document modules that include from x import * statements without including all of the documentation from imported modules?
EDIT:
As per mzjn's point, as long as the imported methods' __module__ attribute a... | Documenting files with "from x import *" | Can sphinx's .. automodule:: and other automatic features be used to document modules that include from x import * statements without including all of the documentation from imported modules?
EDIT:
As per mzjn's point, as long as the imported methods' __module__ attribute are not the same as the module name, they shoul... | [
"Yes, that should work. From the documentation:\n\nIn an automodule directive with the members option set, only module members whose __module__ attribute is equal to the module name as given to automodule will be documented. This is to prevent documentation of imported classes or functions.\n\n\nUpdate:\nThe proble... | [
4
] | [] | [] | [
"matplotlib",
"python",
"python_sphinx"
] | stackoverflow_0008608341_matplotlib_python_python_sphinx.txt |
Q:
Django Paginate by Year
I was able to preview the 100 most recent items in my news clipping database on my website's index page with a generic view:
DPRM
Now I need to paginate my database in a separate logical section of my website. I need to paginate by year. I don't care how many entries are in each year, I j... | Django Paginate by Year | I was able to preview the 100 most recent items in my news clipping database on my website's index page with a generic view:
DPRM
Now I need to paginate my database in a separate logical section of my website. I need to paginate by year. I don't care how many entries are in each year, I just want to take the year fro... | [
"With the new Class Based Views the easies would be to use the YearArchiveView\nclass ArticleYearArchiveView(YearArchiveView):\n model = Article\n paginate_by = 100\n context_object_name = 'article_list'\n date_field = 'date'\n allow_empty = True\n\nAllow empty is to show the page even when there's n... | [
7,
1
] | [] | [] | [
"django",
"django_class_based_views",
"pagination",
"python"
] | stackoverflow_0008624507_django_django_class_based_views_pagination_python.txt |
Q:
Regex Expression generating extra output
I have a string like this-:
st = "url=these,url=are,url=test,url=questions"
Now from this string i need to generate value of all the url. Now the regexp am using is something like this-:
import re
re.findall(r'([^\(url=\)]+)',st)
Now my desired output is ['these,', 'are,'... | Regex Expression generating extra output | I have a string like this-:
st = "url=these,url=are,url=test,url=questions"
Now from this string i need to generate value of all the url. Now the regexp am using is something like this-:
import re
re.findall(r'([^\(url=\)]+)',st)
Now my desired output is ['these,', 'are,', 'test,', 'questions'] but my regexp is givin... | [
"You probably want something like the next:\n>>> re.findall(r'url=(\\w+)',st)\n['these', 'are', 'test', 'questions']\n\n",
"You've used square brackets [] which select characters. You've got [^\\(url=\\)] which matches any character except (, u, r, l, = and ).\nInstead, you want url=([^,]+) which matches 'url=' t... | [
5,
4,
2,
2,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0008624628_python_regex.txt |
Q:
Not breaking out of for loop
For some reason, when the candidate number reaches 21, it realises 21 is divisible by 3, but then won't break out of the for loop/ By contrast, for example for 25, is notes 25 is divisible by 5 then breaks out.
It seems specifically, when div == 3, it doesn't break out of the loop. Why... | Not breaking out of for loop | For some reason, when the candidate number reaches 21, it realises 21 is divisible by 3, but then won't break out of the for loop/ By contrast, for example for 25, is notes 25 is divisible by 5 then breaks out.
It seems specifically, when div == 3, it doesn't break out of the loop. Why is this?
for cand in range (3,100... | [
"A for loop is not a while loop.\nIn Python, the only type of for loop is what in other languages is 'foreach' - it iterates through a list of elements. In your case, you're iterating through a range, ie a list of integers from 3 to y+2. It's the number of elements in the list that determines when the iteration sto... | [
4,
1,
1,
1
] | [] | [] | [
"for_loop",
"loops",
"python"
] | stackoverflow_0008624620_for_loop_loops_python.txt |
Q:
Python object methods dict
I need to have a class instance variable that contains a list of handlers (the specified methods of this class instance). The list of handlers is available upon request.
I have two solutions, but none of them does not suit me.
http://www.ideone.com/3aSkT - You will get a cyclic referenc... | Python object methods dict | I need to have a class instance variable that contains a list of handlers (the specified methods of this class instance). The list of handlers is available upon request.
I have two solutions, but none of them does not suit me.
http://www.ideone.com/3aSkT - You will get a cyclic reference. GC can clean it up, but we do... | [
"If I got you right, you could simply use the built-in function dir(). Example:\n>>> class Foo(object):\n... def m1(self):\n... pass\n... def m2(self):\n... pass\n... \n>>> dir(Foo)\n['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__',... | [
2,
1,
1
] | [] | [] | [
"dictionary",
"methods",
"python"
] | stackoverflow_0008624455_dictionary_methods_python.txt |
Q:
My Python program is very slow! How can I speed it up? Am I doing something wrong?
EDIT: I ran the python profiler and the two most time-consuming things (this is after I decided to comment out the webbrowser portion and Firefox portion of the code, because I knew they were going to be the slowest part...) , the s... | My Python program is very slow! How can I speed it up? Am I doing something wrong? | EDIT: I ran the python profiler and the two most time-consuming things (this is after I decided to comment out the webbrowser portion and Firefox portion of the code, because I knew they were going to be the slowest part...) , the slowest part of my program is re.findall and re.compile and also (len) and (append to lis... | [
"The first thing to do when a program is slow is to identify bottlenecks; in fact, you want to optimize things that take a long time, not things that may actually be fast. In Python, the most efficient way to do this is with one of the Python profilers, which are dedicated tools for performance analysis. Here is ... | [
33,
3
] | [] | [] | [
"performance",
"python"
] | stackoverflow_0008624779_performance_python.txt |
Q:
Generating batches of n-dimensional Perlin noise using Python and NumPy
I managed to grasp the way Perlin noise works and implement a pixel-at-a-time version using this awesome PDF as a reference, but, quite obviously it's incredibly slow.
First thought would be to generate it as batches - instead going through ev... | Generating batches of n-dimensional Perlin noise using Python and NumPy | I managed to grasp the way Perlin noise works and implement a pixel-at-a-time version using this awesome PDF as a reference, but, quite obviously it's incredibly slow.
First thought would be to generate it as batches - instead going through every pixel from 0.0 to 1.0, generate a numpy.linspace and then act on it using... | [
"If guess correctly, then Asmagedon wants to per-calculate his noise textures and then later paint them onto some other target of a different size. \nOne way to do this is with scipy.signal.resample which can both interpolate and subsample a signal. From memory it only works on one dimension at a time -- just loo... | [
1
] | [] | [] | [
"numpy",
"perlin_noise",
"python"
] | stackoverflow_0008624732_numpy_perlin_noise_python.txt |
Q:
How to keep global variables persistent over multiple google appengine instances?
Our situation is as follows:
We are working on a schoolproject where the intention is that multiple teams walk around in a city with smarthphones and play a city game while walking.
As such, we can have 10 active smarthpones walking ... | How to keep global variables persistent over multiple google appengine instances? | Our situation is as follows:
We are working on a schoolproject where the intention is that multiple teams walk around in a city with smarthphones and play a city game while walking.
As such, we can have 10 active smarthpones walking around in the city, all posting their location, and requesting data from the google app... | [
"You should be using memcache. If you use the ndb (new database) library, you can automatically cache the results of queries. Obviously this won't improve your writes much, but it should significantly improve the numbers of reads you can do.\nYou need to back it with the datastore as data can be ejected from memcac... | [
3,
0,
0,
0
] | [] | [] | [
"global",
"google_app_engine",
"python",
"variables"
] | stackoverflow_0008616487_global_google_app_engine_python_variables.txt |
Q:
Program doesn't work completely when run outside eclipse
I have a small python application, which uses pyttsx for some text to speech.
How it works:
simply say whatever is there in the clipboard.
The program works as expected inside eclipse. But if run on cmd.exe it only works partly if the text on the clipboard ... | Program doesn't work completely when run outside eclipse | I have a small python application, which uses pyttsx for some text to speech.
How it works:
simply say whatever is there in the clipboard.
The program works as expected inside eclipse. But if run on cmd.exe it only works partly if the text on the clipboard is too large(a few paras). Why ?
when run from cmd, it prints... | [
"Checked that the problem is not in the code that reads the text from the clipboard. \nYou should check if your eclipse setup specifies custom environment variables for the project which do not exist outside Eclipse. Especially:\n\nPYTHONPATH (and also additional projects on which your program could depend in your ... | [
2,
0
] | [
"turns out pythonpath wasn't set properly on my system. \nEdit: turns out pythonpath isn't the problem. I have no idea whats the problem. arghhhhhhhhhhhhhhhhhhhhhhhh\n"
] | [
-2
] | [
"eclipse",
"python"
] | stackoverflow_0007007400_eclipse_python.txt |
Q:
time series for binary shapes
I have been working around extracting the time series from shapes based on distances to center of mass clockwise starting from angle 0 to 360.
My Implementation that arranges contour points based on their angle to the [1,0], vector might be good for some shapes but is not useful for ... | time series for binary shapes | I have been working around extracting the time series from shapes based on distances to center of mass clockwise starting from angle 0 to 360.
My Implementation that arranges contour points based on their angle to the [1,0], vector might be good for some shapes but is not useful for shapes that has much articulation. ... | [
"If I understood, there's a geometrical figure in a discretized plane, represented as a matrix. If the entry is 1, you're inside the figure. If it's 0, you're outside. He wants to determine de distance between the edge of the figure and the center of the figure for all points in the edge. He parametrized it with a ... | [
0
] | [] | [] | [
"contour",
"numpy",
"python",
"scipy",
"time_series"
] | stackoverflow_0008340023_contour_numpy_python_scipy_time_series.txt |
Q:
Custom authentication in suds library (Python)
I need to access a SOAP server with WSDL where the authentication is done by sending two parameters, UserId and AccessToken. I tried this way:
token = UsernameToken(
UserId,
AccessToken
)
token.setnonce()
token.setcreated()
security... | Custom authentication in suds library (Python) | I need to access a SOAP server with WSDL where the authentication is done by sending two parameters, UserId and AccessToken. I tried this way:
token = UsernameToken(
UserId,
AccessToken
)
token.setnonce()
token.setcreated()
security = Security()
security.tokens.append(token)
client... | [
"If the parameters are supposed to part of a header, you can do it that way:\nheader = client.factory.create('HeaderNameInWSDL')\nheader.UserId = 'foo'\nheader.AccessToken = 'bar%n3'\nclient.set_options(soapheaders=header)\n\nThen do you stuff.\n"
] | [
1
] | [] | [] | [
"python",
"soap",
"suds"
] | stackoverflow_0005422613_python_soap_suds.txt |
Q:
ISO human-readable parser for Python in Python
I'm looking for a parser for Python (preferably v. 2.7) written in human-readable Python. Performance or flexibility are not important. The accuracy/correctness of the parsing and the clarity of the parser's code are far more important considerations here.
Searching... | ISO human-readable parser for Python in Python | I'm looking for a parser for Python (preferably v. 2.7) written in human-readable Python. Performance or flexibility are not important. The accuracy/correctness of the parsing and the clarity of the parser's code are far more important considerations here.
Searching online I've found a few parser generators that gene... | [
"PyPy is a Python implementation written entirely in Python. I am not an expert, but here's the link to their parser which - obviously - has been written in Python itself:\nhttps://bitbucket.org/pypy/pypy/src/819faa2129a8/pypy/interpreter/pyparser\n",
"I think you should invest your effort in ast. An excerpt from... | [
3,
2
] | [] | [] | [
"parsing",
"python",
"recursive_descent"
] | stackoverflow_0008625276_parsing_python_recursive_descent.txt |
Q:
Python: server side detect whether user is logged in to facebook (and not necessarily connected to my app)
is there a server side equivalent to the javascript api FB.getLoginStatus()
There seems to be something similar in the PHP SDK, but I don't want to use PHP. If it is possible in PHP it must be possible in Pyt... | Python: server side detect whether user is logged in to facebook (and not necessarily connected to my app) | is there a server side equivalent to the javascript api FB.getLoginStatus()
There seems to be something similar in the PHP SDK, but I don't want to use PHP. If it is possible in PHP it must be possible in Python - but does this mean I'd have to reverse engineer the PHP SDK to be able to do it?
| [
"You can use this\nPython client library for the Facebook Platform from https://gist.github.com/1190267 \nThen you can parse signed_request or parse facebook cookie written by fb js sdk:\nsample code for parsing signed_request: \nsigned_request = pyface.parse_signed_request(request.POST['signed_request'], fb_app_s... | [
1
] | [] | [] | [
"facebook",
"python"
] | stackoverflow_0008622294_facebook_python.txt |
Q:
Filtering across a relationship doesn't work in my admin list page
I have an admin setup that includes a lookup that spans a relationship, "school__year" as one of my list_filter options. This appears to work properly (the set of distinct years shows up as options to filter by in the list page sidebar) but when I ... | Filtering across a relationship doesn't work in my admin list page | I have an admin setup that includes a lookup that spans a relationship, "school__year" as one of my list_filter options. This appears to work properly (the set of distinct years shows up as options to filter by in the list page sidebar) but when I click on them I get a 302 redirect to "/?e=1".
This is the same behavior... | [
"This is a known bug in django: https://code.djangoproject.com/ticket/11670\nThe easiest workaround is to not name your columns 'year'.\n"
] | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0007211174_django_python.txt |
Q:
Best way to uninstall/delete everything related to Emacs/Python/Django on OSX Lion
I am starting (and loving it) with python django or emacs on my OSX Lion. However I am pretty sure that I messed some stuff, and now I get some errors due to my ignorance when I was installing stuff or maybe because I did what I was... | Best way to uninstall/delete everything related to Emacs/Python/Django on OSX Lion | I am starting (and loving it) with python django or emacs on my OSX Lion. However I am pretty sure that I messed some stuff, and now I get some errors due to my ignorance when I was installing stuff or maybe because I did what I wasn't suppose to do in the Terminal.
Is there any way to clean all my emacs, python and dj... | [
"\nIs there any way to clean all my emacs, python and django stuff from my system? \n\nSlow down.\nDo NOT remove Python. Mac OS X relies, absolutely on Python. You can -- with some difficulty -- try to remove some versions, but it usually ends badly. Mac OS X already included Python. There probably was no reaso... | [
4
] | [] | [] | [
"django",
"emacs",
"python",
"uninstallation"
] | stackoverflow_0008624637_django_emacs_python_uninstallation.txt |
Q:
Python BitTorrent Library
Is there a Python BitTorrent library that just works?
I need to tinker around with BitTorrent protocol for a research project and I don't want to reinvent the wheel and write my own implementation of the protocol (and neither I am capable of doing so)
I looked at the sources for the offic... | Python BitTorrent Library | Is there a Python BitTorrent library that just works?
I need to tinker around with BitTorrent protocol for a research project and I don't want to reinvent the wheel and write my own implementation of the protocol (and neither I am capable of doing so)
I looked at the sources for the official BitTorrent client, but that... | [
"You might want to have a look at the python-libtorrent project. It's a wrapper around the libtorrent C++ library, which claims to be efficient and easy to use.\n",
"BitTornado is pure Python library written by John Hoffman.\n"
] | [
19,
12
] | [] | [] | [
"bittorrent",
"python"
] | stackoverflow_0004418157_bittorrent_python.txt |
Q:
Scripts that Rely on Docstrings?
From the 2.7.2 docs, Section 6, Modules:
Passing two -O flags to the Python interpreter (-OO) will cause the bytecode compiler to perform optimizations that could in some rare cases result in malfunctioning programs. Currently only __doc__ strings are removed from the bytecode, res... | Scripts that Rely on Docstrings? | From the 2.7.2 docs, Section 6, Modules:
Passing two -O flags to the Python interpreter (-OO) will cause the bytecode compiler to perform optimizations that could in some rare cases result in malfunctioning programs. Currently only __doc__ strings are removed from the bytecode, resulting in more compact .pyo files.
Th... | [
"For example ply is a module that does lexing and parsing which uses docstrings to describe the grammar. Stripping docstrings would break the code.\n",
"The -OO option only affects whether a doc string is stored -- it does not affect parsing. For example the following code works with and without optimizations en... | [
3,
1
] | [] | [] | [
"compiler_optimization",
"docstring",
"python",
"removing_whitespace"
] | stackoverflow_0008625847_compiler_optimization_docstring_python_removing_whitespace.txt |
Q:
Use Python os.walk to identify a list of files
Possible Duplicate:
In Python, fastest way to build a list of files in a directory with a certain extension
I currently am using os.walk to recursively scan through a directory identifying .MOV files
def fileList():
matches = []
for root, dirnames, filenames... | Use Python os.walk to identify a list of files |
Possible Duplicate:
In Python, fastest way to build a list of files in a directory with a certain extension
I currently am using os.walk to recursively scan through a directory identifying .MOV files
def fileList():
matches = []
for root, dirnames, filenames in os.walk(source):
for filename in fnmatc... | [
"Try something like this:\ndef fileList(source):\n matches = []\n for root, dirnames, filenames in os.walk(source):\n for filename in filenames:\n if filename.endswith(('.mov', '.MOV', '.avi', '.mpg')):\n matches.append(os.path.join(root, filename))\n return matches\n\n",
... | [
19,
2,
2
] | [] | [] | [
"python"
] | stackoverflow_0008625991_python.txt |
Q:
PyQt: How do I figure out which encoding is used?
I have a py file using Qt Designer,i have a combobox and i read from a csv file.If the combobox choice is in the file,it prints something.
At the top of the script it says that: # -*- coding: utf-8 -*-
So, the error i get is this:
PyQt4.QtCore.QString(u'choice') is... | PyQt: How do I figure out which encoding is used? | I have a py file using Qt Designer,i have a combobox and i read from a csv file.If the combobox choice is in the file,it prints something.
At the top of the script it says that: # -*- coding: utf-8 -*-
So, the error i get is this:
PyQt4.QtCore.QString(u'choice') is not in list
The 'choice' is of course in list.I belie... | [
"This has got nothing to do with encodings.\nThe error occurs simply because there are no strings in the list read from the csv file:\n>>> import csv\n>>> with open('tmp.csv', 'wb') as stream:\n... csv.writer(stream).writerow(['choice'])\n... \n>>> lst = []\n>>> with open('tmp.csv', 'rb') as stream:\n... fo... | [
0
] | [] | [] | [
"pyqt",
"python"
] | stackoverflow_0008624573_pyqt_python.txt |
Q:
Need to replace some token in a file with the name of the file
In a list of textfiles I need to replace a token with the name of the file.
Is there an easy way to do this? The prefered tool for me would be notepad++, but grep, python, powershell or other other ways are also ok. I work on windows.
Example:
filename... | Need to replace some token in a file with the name of the file | In a list of textfiles I need to replace a token with the name of the file.
Is there an easy way to do this? The prefered tool for me would be notepad++, but grep, python, powershell or other other ways are also ok. I work on windows.
Example:
filenames
contact.aspx
default.aspx
content first file
Hallo <%= Html.Res... | [
"You could use the fileinput module. It feels a little awkward to have some module redirect stdout, but it should work like this:\n#usage: python thisscript.py token file file2 file3\nimport sys\nfrom fileinput import input\ntoken = sys.argv[1]\nfile_input = input(sys.argv[2:], inplace=True)\nfor line in file_input... | [
1,
0,
0,
0,
0
] | [] | [] | [
"grep",
"notepad++",
"powershell",
"python",
"replace"
] | stackoverflow_0008595788_grep_notepad++_powershell_python_replace.txt |
Q:
Most efficient way to delete a file if it's below a certain size
What's the most efficient way to delete a file if it's less than 100k?
file = '/path/to/file.mov'
A:
You can use os.path.getsize (returns file size in bytes) and os.remove like that:
import os
file = '/path/to/file.mov'
if os.path.getsize(file) < ... | Most efficient way to delete a file if it's below a certain size | What's the most efficient way to delete a file if it's less than 100k?
file = '/path/to/file.mov'
| [
"You can use os.path.getsize (returns file size in bytes) and os.remove like that:\nimport os\n\nfile = '/path/to/file.mov'\nif os.path.getsize(file) < 100 * 1024:\n os.remove(file)\n\n"
] | [
16
] | [] | [] | [
"python"
] | stackoverflow_0008626325_python.txt |
Q:
How GAE(python) need to Receive mail and post on Message Board then send mail to all user?
anybody knows what wrong with my program??
I write a main.py. and launch it to GAE.
but when I key some word on GAE,it can't send mail to the authors in the table
class Send(webapp.RequestHandler):
def ... | How GAE(python) need to Receive mail and post on Message Board then send mail to all user? | anybody knows what wrong with my program??
I write a main.py. and launch it to GAE.
but when I key some word on GAE,it can't send mail to the authors in the table
class Send(webapp.RequestHandler):
def send(self):
mail.send_mail(sender=users.get_current_user(),
... | [
"For recieving email see http://code.google.com/appengine/docs/python/mail/receivingmail.html\nFor sending email see http://code.google.com/appengine/docs/python/mail/sendingmail.html\ne.g.\nimport logging, email\nfrom google.appengine.ext import webapp \nfrom google.appengine.ext.webapp.mail_handlers import Inboun... | [
2
] | [] | [] | [
"email",
"google_app_engine",
"python"
] | stackoverflow_0008626331_email_google_app_engine_python.txt |
Q:
Sanitizing UTF-8 encoded strings
I want to sanitise a UTF-8 encoded string before using it as part of a MySQL SELECT statement.
For example, I have:
query = MySQLdb.escape_string(query)
but this line is leading to a raised exception that reads
'ascii' codec can't encode characters in position 0-2: ordinal not i... | Sanitizing UTF-8 encoded strings | I want to sanitise a UTF-8 encoded string before using it as part of a MySQL SELECT statement.
For example, I have:
query = MySQLdb.escape_string(query)
but this line is leading to a raised exception that reads
'ascii' codec can't encode characters in position 0-2: ordinal not in
range(128).
How can I handle this... | [
"In your example query is of type 'str'. If you put a 'u' before the string, it becomes of type 'unicode'.\n>>> query = \"こうえん\"\n>>> print type(query)\n<type 'str'>\n>>> query = u\"こうえん\"\n>>> print type(query)\n<type 'unicode'>\n\nThis is one of the main differences between Python versions 2.x and 3.x. Starting... | [
3,
3,
0
] | [] | [] | [
"mysql",
"python",
"sanitization"
] | stackoverflow_0008625475_mysql_python_sanitization.txt |
Q:
Joining multiple strings if they are not empty in Python
I have four strings and any of them can be empty. I need to join them into one string with spaces between them. If I use:
new_string = string1 + ' ' + string2 + ' ' + string3 + ' ' + string4
The result is a blank space on the beginning of the new string if ... | Joining multiple strings if they are not empty in Python | I have four strings and any of them can be empty. I need to join them into one string with spaces between them. If I use:
new_string = string1 + ' ' + string2 + ' ' + string3 + ' ' + string4
The result is a blank space on the beginning of the new string if string1 is empty. Also, I have three blank spaces if string2 a... | [
">>> strings = ['foo','','bar','moo']\n>>> ' '.join(filter(None, strings))\n'foo bar moo'\n\nBy using None in the filter() call, it removes all falsy elements.\n",
"If you KNOW that the strings have no leading/trailing whitespace:\n>>> strings = ['foo','','bar','moo']\n>>> ' '.join(x for x in strings if x)\n'foo ... | [
268,
29
] | [
"strings = ['foo','','bar','moo']\n' '.join([x for x in strings if x is not ''])\n'foo bar moo'\n\n"
] | [
-3
] | [
"join",
"python",
"string"
] | stackoverflow_0008626694_join_python_string.txt |
Q:
Why isn't my Python program working? It uses HTTP Headers
EDIT: I changed the code and it still doesn't work! I used the links from the answer to do it but it didn't work!
Why does this not work? When I run it takes a long time to run and never finishes!
import urllib
import urllib2
url = 'https://www.locationar... | Why isn't my Python program working? It uses HTTP Headers | EDIT: I changed the code and it still doesn't work! I used the links from the answer to do it but it didn't work!
Why does this not work? When I run it takes a long time to run and never finishes!
import urllib
import urllib2
url = 'https://www.locationary.com/index.jsp?ACTION_TOKEN=tile_loginBar_jsp$JspView$LoginA... | [
"The remote server (the one at www.locationary.com) is waiting for the content of your HTTP post request, based on the Content-Type and Content-Length headers. Since you're never actually sending said awaited data, the remote server waits — and so does read() — until you do so.\n\n\nI need to know how to send the c... | [
2
] | [] | [] | [
"header",
"http",
"python",
"urllib2"
] | stackoverflow_0008626904_header_http_python_urllib2.txt |
Q:
Python MySQL cursor - escaping percents
How do I escape percents in MySQL cursors in Python?
I got this query:
query = "SELECT * FROM foods where food_description = %s"
cursor.execute(query, ("1% milk"))
However, it's not working because of the % in 1% milk.
A:
Escape it with a \:
cursor.execute(query, ("1% mil... | Python MySQL cursor - escaping percents | How do I escape percents in MySQL cursors in Python?
I got this query:
query = "SELECT * FROM foods where food_description = %s"
cursor.execute(query, ("1% milk"))
However, it's not working because of the % in 1% milk.
| [
"Escape it with a \\:\ncursor.execute(query, (\"1% milk\".replace('%', '\\\\%')))\n\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0008627022_python.txt |
Q:
Fastest way to replace elements of a file's path and extension?
Given the path of a file:
file = "/directory/date/2011/2009-01-11 This is a file's path/file.jpg"
How can I quickly replace it with:
new_file = "/newdirectory/date/2011/2009-01-11 This is a file's path/file.MOV"
Changing both directory for "newdirec... | Fastest way to replace elements of a file's path and extension? | Given the path of a file:
file = "/directory/date/2011/2009-01-11 This is a file's path/file.jpg"
How can I quickly replace it with:
new_file = "/newdirectory/date/2011/2009-01-11 This is a file's path/file.MOV"
Changing both directory for "newdirectory" and ".jpg" for ".MOV"
| [
"Well this can be done in different way's, but this is how I would do\nFirst change the extension. This can be easily done via os.path.splitext something like\npath = \"/directory/date/2011/2009-01-11 This is a file's path/file.jpg\"\nnew_file=os.path.splitext(path)[0]+\".MOV\"\n\nThis gives the path as\n\"/directo... | [
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0008626177_python.txt |
Q:
Improvement in python script involved in solving euler n°357
I know that this is a weird and annoying question, but I hope that Christmas atmosphere will make the work easier to be done.
In a few words: I have tried to write a python script aimed to solve Euler problem number 357, which says: "Find the sum of all ... | Improvement in python script involved in solving euler n°357 | I know that this is a weird and annoying question, but I hope that Christmas atmosphere will make the work easier to be done.
In a few words: I have tried to write a python script aimed to solve Euler problem number 357, which says: "Find the sum of all positive integers n not exceeding 100000000 such that for every di... | [
"Don't build up a list of divisors and then test them all. Test each as you find them, and skip the number as soon as you find an invalid one.\nAnother way to phrase the problem: \"the sum of integers n not exceeding 100000000 such that there are no divisors d where n/d + d is composite\". We can express this much ... | [
2,
1,
1,
1,
1,
0
] | [] | [] | [
"algorithm",
"math",
"python"
] | stackoverflow_0008627012_algorithm_math_python.txt |
Q:
Code for determining number of 15 minute periods
I have the following problem. I have a data set that has the beginning (STRTTIME) and ending time (ENDTIME) of a trip in military time format. I want to figure out the number of trips in each 15 minute time increment. My goal is to determine the number of trips that... | Code for determining number of 15 minute periods | I have the following problem. I have a data set that has the beginning (STRTTIME) and ending time (ENDTIME) of a trip in military time format. I want to figure out the number of trips in each 15 minute time increment. My goal is to determine the number of trips that take place in each 15 minute time period starting fro... | [
"Let me try to present the solution the exact way you represented\n\nFirst Lets Define the 15 min Time Ranges. Itertools.product is used to create the entire time range formatted with the datetime strftime after converting with time.\ntimeset=[datetime.time(h,m).strftime(\"%H%M\") for h,m in itertools.product(xrang... | [
4,
4,
3,
0
] | [] | [] | [
"python",
"r"
] | stackoverflow_0008626809_python_r.txt |
Q:
What would you use the heapq Python module for in real life?
After reading Guido's Sorting a million 32-bit integers in 2MB of RAM using Python, I discovered the heapq module, but the concept is pretty abstract to me.
One reason is that I don't understand the concept of a heap completely, but I do understand how G... | What would you use the heapq Python module for in real life? | After reading Guido's Sorting a million 32-bit integers in 2MB of RAM using Python, I discovered the heapq module, but the concept is pretty abstract to me.
One reason is that I don't understand the concept of a heap completely, but I do understand how Guido used it.
Now, beside his kinda crazy example, what would you ... | [
"The heapq module is commonly use to implement priority queues. \nYou see priority queues in event schedulers that are constantly adding new events and need to use a heap to efficiently locate the next scheduled event. Some examples include:\n\nPython's own sched module: http://hg.python.org/cpython/file/2.7/Lib/... | [
19,
6,
3
] | [] | [] | [
"algorithm",
"data_structures",
"heap",
"priority_queue",
"python"
] | stackoverflow_0008627109_algorithm_data_structures_heap_priority_queue_python.txt |
Q:
how to print out when a new record is set (within an array) using random numbers
I've generated a graph of random numbers (standard deviation 1, mean 0). I need to run through the list and print out each number if it is the biggest one currently seen. For example, given the list [10, 5, 15, 18, 5, 7, 9, 100], the ... | how to print out when a new record is set (within an array) using random numbers | I've generated a graph of random numbers (standard deviation 1, mean 0). I need to run through the list and print out each number if it is the biggest one currently seen. For example, given the list [10, 5, 15, 18, 5, 7, 9, 100], the code would print out:
10 (first number is always going to be the biggest currently see... | [
"The simplest approach may be to plot a separate stairstep curve for the running maximum:\n>>> def running_maximum(data):\n result = data[:1]\n for x in data[1:]:\n result.append(max(x, result[-1]))\n return result\n\n>>> data = [10, 5, 15, 18, 5, 7, 9, 100]\n>>> running_maximum(data... | [
1,
0,
0
] | [] | [] | [
"arrays",
"graph",
"matplotlib",
"python",
"random"
] | stackoverflow_0008626572_arrays_graph_matplotlib_python_random.txt |
Q:
How can I stay logged in to a website and send a cookie or http header or something for my python program?
Ok. This is what my program (in Python) does. First it downloads the html of a page on this website, locationary.com, and then it takes all of the business pages from that page and finds all of the yellowpage... | How can I stay logged in to a website and send a cookie or http header or something for my python program? | Ok. This is what my program (in Python) does. First it downloads the html of a page on this website, locationary.com, and then it takes all of the business pages from that page and finds all of the yellowpages.com links for those businesses. After it finds them it inserts them into the website with the webbrowser modul... | [
"You might try pycurl which will allow you to interact with web pages without using a browser. \npycurl allows cookie storage (and reuse), form submission (including login), as well as page navigation from Python. Your code above already seems to retrieve the resources you want via urllib. You can easily adapt your... | [
0
] | [] | [] | [
"cookies",
"header",
"http",
"python",
"urllib2"
] | stackoverflow_0008627125_cookies_header_http_python_urllib2.txt |
Q:
Python's math module & "Think Python"
I'm stucked on the chapter 3.3 "Math functions" of "Think Python".
It tells me to import math (through the interpreter).
Then print math and that I should get something like this:
<module 'math' from '/usr/lib/python2.5/lib-dynload/math.so'>
Instead I get <module 'math' <built... | Python's math module & "Think Python" | I'm stucked on the chapter 3.3 "Math functions" of "Think Python".
It tells me to import math (through the interpreter).
Then print math and that I should get something like this:
<module 'math' from '/usr/lib/python2.5/lib-dynload/math.so'>
Instead I get <module 'math' <built-in>>
Anyway that's not the problem. Though... | [
"You've figured it out - you have to set signal_power's value before using it. As to what you have to set it to - it's not really a Python related question, but 1 is always a safe choice :) While you are at it, don't forget to define noise_power.\n",
"The book is for an older version of python apparently. But tha... | [
3,
1,
1,
1
] | [] | [] | [
"function",
"module",
"python"
] | stackoverflow_0008627414_function_module_python.txt |
Q:
Grabbing headers from webpage with python
How can I use python 3 to get access to the HTTP Headers. Specifically, I am trying to recreate the headers you can gain access to through network in the developer tools in chrome.
A:
>>> import pprint
>>> import urllib.request
>>> u = urllib.request.urlopen('http://www.... | Grabbing headers from webpage with python | How can I use python 3 to get access to the HTTP Headers. Specifically, I am trying to recreate the headers you can gain access to through network in the developer tools in chrome.
| [
">>> import pprint\n>>> import urllib.request\n>>> u = urllib.request.urlopen('http://www.python.org')\n>>> pprint.pprint(dict(u.getheaders()))\n{'Accept-Ranges': 'bytes',\n 'Connection': 'close',\n 'Content-Length': '18882',\n 'Content-Type': 'text/html',\n 'Date': 'Sat, 24 Dec 2011 23:51:27 GMT',\n 'ETag': '\"105... | [
5
] | [] | [] | [
"html",
"http",
"python",
"python_3.x"
] | stackoverflow_0008627493_html_http_python_python_3.x.txt |
Q:
Python Stack Corruption?
I'm relatively new to python (but not to programming), and I can't explain the following behavior. It appears that a variable (the list "children" in my example) from one object ("child") is getting overwritten by the value for that variable in a completely different object ("node"). To ... | Python Stack Corruption? | I'm relatively new to python (but not to programming), and I can't explain the following behavior. It appears that a variable (the list "children" in my example) from one object ("child") is getting overwritten by the value for that variable in a completely different object ("node"). To give some context, I'm trying ... | [
"The children variable was declared as a class-level variable so it is shared amongst all instances of your Nodes. You need to declare it an instance variable by setting it in the initializer.\nclass Node:\n #children = [] # not here...\n parent = 0 # might want to rethink where you initialize these\n ... | [
6,
2
] | [] | [] | [
"python"
] | stackoverflow_0008627628_python.txt |
Q:
IPython: How to save 2 ranges of lines with the save magic command?
I'd like to save something like 1-4 and 8-14.
save two-line-ranges.py 1-4, 8-14
Currently I can only save either or the whole range 1-14.
A:
Try the following:
save two-line-ranges.py 1-4 8-14
| IPython: How to save 2 ranges of lines with the save magic command? | I'd like to save something like 1-4 and 8-14.
save two-line-ranges.py 1-4, 8-14
Currently I can only save either or the whole range 1-14.
| [
"Try the following:\nsave two-line-ranges.py 1-4 8-14\n\n"
] | [
3
] | [] | [] | [
"ipython",
"python",
"save"
] | stackoverflow_0008627651_ipython_python_save.txt |
Q:
SQLAlchemy: One-Way Relationship, Correlated Subquery
thanks in advance for your help.
I have two entities, Human and Chimp. Each has a collection of metrics, which can contain subclasses of a MetricBlock, for instance CompleteBloodCount (with fields WHITE_CELLS, RED_CELLS, PLATELETS).
So my object model looks lik... | SQLAlchemy: One-Way Relationship, Correlated Subquery | thanks in advance for your help.
I have two entities, Human and Chimp. Each has a collection of metrics, which can contain subclasses of a MetricBlock, for instance CompleteBloodCount (with fields WHITE_CELLS, RED_CELLS, PLATELETS).
So my object model looks like (forgive the ASCII art):
--------- metrics ---------... | [
"Each primate should have a unique ID, regardless of what type of primate they are. I'm not sure why each set of attributes (MB, CBC, CC) are separate tables, but I assume that they have more than one dimension (primate) such as time, otherwise I would only have one giant table.\nThus, I would structure this proble... | [
3
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0008627567_python_sqlalchemy.txt |
Q:
Python, date validation
I'm trying to think of a way to accomplish this in the best pythonic way possible. Right now the only method I can think of is to brute force it.
User inputs a date (via command line) in one of the following manners (ex. ./mypy.py date='20110909.00 23' )
date='20110909'
date='20110909.00 ... | Python, date validation | I'm trying to think of a way to accomplish this in the best pythonic way possible. Right now the only method I can think of is to brute force it.
User inputs a date (via command line) in one of the following manners (ex. ./mypy.py date='20110909.00 23' )
date='20110909'
date='20110909.00 23'
date='20110909.00 2011090... | [
"You can create a mask and parse it, using try...except to determine whether the date string matches one of the many masks. I had this code for a project, so I've slightly modified it:\nfrom time import mktime, strptime\nfrom datetime import datetime\n\ndate = '20110909.00 20110909.23'.split(' ')[0]\nresult = None\... | [
7,
1,
0,
0
] | [] | [] | [
"datetime",
"python"
] | stackoverflow_0007367204_datetime_python.txt |
Q:
BeautifulSoup 4.0b markupMassage
I installed BeautifulSoup 4.0b yesterday, and now I want to add a regex-replace pair that would be ran during the pre-parser stage. In the documentation it says I can simply use the markupMassage parameter to __init__ which assigns to MARKUP_MASSAGE, but it seems that 4.0b no long... | BeautifulSoup 4.0b markupMassage | I installed BeautifulSoup 4.0b yesterday, and now I want to add a regex-replace pair that would be ran during the pre-parser stage. In the documentation it says I can simply use the markupMassage parameter to __init__ which assigns to MARKUP_MASSAGE, but it seems that 4.0b no longer has these attributes, despite not m... | [
"The README does (sort of) cover this issue, but it has to be inferred by reading between the lines of this section:\n\n= About Beautiful Soup 4 =\nThis is a nearly-complete rewrite that removes Beautiful Soup's custom\n HTML parser in favor of a system that lets you write a little glue\n code and plug in any HTM... | [
3
] | [] | [] | [
"beautifulsoup",
"python",
"python_3.x"
] | stackoverflow_0008626554_beautifulsoup_python_python_3.x.txt |
Q:
URL Decode with Python 3
Is there a way to URL decode a string in Python 3
to take something like this
id%253D184ff84d27c3613d%26quality%3Dmedium
and decode it twice to get
id=184ff84d27c3613d&quality=medium
A:
Just use urllib.parse.unquote():
>>> import urllib.parse
>>> urllib.parse.unquote('id%253D184ff84d27... | URL Decode with Python 3 | Is there a way to URL decode a string in Python 3
to take something like this
id%253D184ff84d27c3613d%26quality%3Dmedium
and decode it twice to get
id=184ff84d27c3613d&quality=medium
| [
"Just use urllib.parse.unquote():\n>>> import urllib.parse\n>>> urllib.parse.unquote('id%253D184ff84d27c3613d%26quality%3Dmedium')\n'id%3D184ff84d27c3613d&quality=medium'\n>>> urllib.parse.unquote('id%3D184ff84d27c3613d&quality=medium')\nid=184ff84d27c3613d&quality=medium\n\n",
"Try this:\nfrom urllib.parse impor... | [
122,
17
] | [] | [] | [
"html",
"python",
"python_3.x"
] | stackoverflow_0008628152_html_python_python_3.x.txt |
Q:
Generate .pyc from Python AST?
How would I generate a .pyc file from a Python AST such that I could import the file from Python?
I've used compile to create a code object, then written the co_code attribute to a file, but when I try to import the file from Python, I get an ImportError: Bad magic number in output.p... | Generate .pyc from Python AST? | How would I generate a .pyc file from a Python AST such that I could import the file from Python?
I've used compile to create a code object, then written the co_code attribute to a file, but when I try to import the file from Python, I get an ImportError: Bad magic number in output.pyc.
| [
"The solution can be adapted from the py_compile module:\nimport marshal\nimport py_compile\nimport time\nimport ast\n\ncodeobject = compile(ast.parse('print \"Hello World\"'), '<string>', 'exec')\n\nwith open('output.pyc', 'wb') as fc:\n fc.write('\\0\\0\\0\\0')\n py_compile.wr_long(fc, long(time.time()))\n ... | [
18,
2
] | [] | [] | [
"abstract_syntax_tree",
"bytecode",
"python",
"python_ast"
] | stackoverflow_0008627835_abstract_syntax_tree_bytecode_python_python_ast.txt |
Q:
How does the 'for' function work if it is used in a 'for' loop?
I'm using the python documentation to begin learning everything, and it introduces the 'for' loop with the 'for' function inside the said 'for' loop. I'm doing an awful job of explaining because I'm having such a hard time keeping up with the terminol... | How does the 'for' function work if it is used in a 'for' loop? | I'm using the python documentation to begin learning everything, and it introduces the 'for' loop with the 'for' function inside the said 'for' loop. I'm doing an awful job of explaining because I'm having such a hard time keeping up with the terminology, so I'll just show you:
for n in range(2, 10):
for x in range... | [
"for n in range(2, 10): \nmeans that n will take on the values of 2 - 10, one at a time, and each time it takes on a new value, run the inner loop.\nThe inner loop,\nfor x in range(2, n):\nmeans that x will take on the values of 2 - n, one at a time, and execute its innards, the if/else.\nSo the outer loop starts a... | [
2,
2,
2,
1
] | [] | [] | [
"for_loop",
"python"
] | stackoverflow_0008628143_for_loop_python.txt |
Q:
Python Phone Class --- printing None
class Phone:
def __init__(self):
self.types = ["Touch Screen","Flip", "Slider", "Bar", "Bag"]
self.brand = "No Brand Determined"
self.type_of_phone = "No Type of Phone has been selected"
def get_type(self):
return self.type_of_phone
... | Python Phone Class --- printing None | class Phone:
def __init__(self):
self.types = ["Touch Screen","Flip", "Slider", "Bar", "Bag"]
self.brand = "No Brand Determined"
self.type_of_phone = "No Type of Phone has been selected"
def get_type(self):
return self.type_of_phone
def change_type(self, changeTo):
i... | [
"it's because of the: \ninput(print(\"(1) See your phone specs \\n(2) Change information\\n Enter a Number: \"))\n\nThe print() function returns nothing (i.e. None) that gets printed by input(), you don't need to call the print() function, therefore it should look like:\ninput(\"(1) See your phone specs \\n(2) Chan... | [
6,
1
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0008628317_python_python_3.x.txt |
Q:
if block not evaluating as expected
answer == raw_input("Do you like python?")
if answer == "yes":
print "That is great"
elif answer == "no"
print "that is disappointing"
else:
print "that is not the answer to my question"
The problem with this code is that python 2.7.2 ignores my first two cond... | if block not evaluating as expected | answer == raw_input("Do you like python?")
if answer == "yes":
print "That is great"
elif answer == "no"
print "that is disappointing"
else:
print "that is not the answer to my question"
The problem with this code is that python 2.7.2 ignores my first two conditions, but responds to the last one. Why... | [
"You're using == instead of = in the first line of code. As far as the code you've shown, answer is never actually assigned a value.\nOh, and there's a missing colon in the line elif answer == \"no\".\n\nHere, have a cookie:\nanswer = raw_input(\"Do you like python?\")\nif answer == \"yes\":\n print \"That is gr... | [
11,
6,
0
] | [] | [] | [
"python"
] | stackoverflow_0008628538_python.txt |
Q:
PyGTK "assertion GTK_IS_WINDOW failed
I'm trying to build a web browser using PyGTK and PyWebKit
However, I'm pretty sure my question only concerns PyGTK
I have a custom gtk.Notebook class, with an "add tab" button as the last tab.
When I click it, it gives me the error
/home/ruiqimao/workspace/PyBrowser/src/brows... | PyGTK "assertion GTK_IS_WINDOW failed | I'm trying to build a web browser using PyGTK and PyWebKit
However, I'm pretty sure my question only concerns PyGTK
I have a custom gtk.Notebook class, with an "add tab" button as the last tab.
When I click it, it gives me the error
/home/ruiqimao/workspace/PyBrowser/src/browser/__init__.py:161: GtkWarning: IA__gdk_win... | [
"This question has been sitting in \"unanswered\" for months, without any answer. However, the problem was indeed solved (see comments). Thus, as a service to get this question OUT of \"unanswered\", I'll restate the apparent answer. If anyone else can top me, pleeeeeeeease do. :)\nYou forgot to show the new tab.\n... | [
2
] | [] | [] | [
"gtk",
"pygtk",
"python"
] | stackoverflow_0006447861_gtk_pygtk_python.txt |
Q:
Twisted Installation Failed on Linux
I tried to install twisted on Linux from source code on my Linux sever.
When I use this command setup.py install, it failed with a error message below:
twisted/runner/portmap.c:10:20: error: Python.h: No such file or directory
twisted/runner/portmap.c:14: error: expected ‘=’, ... | Twisted Installation Failed on Linux | I tried to install twisted on Linux from source code on my Linux sever.
When I use this command setup.py install, it failed with a error message below:
twisted/runner/portmap.c:10:20: error: Python.h: No such file or directory
twisted/runner/portmap.c:14: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ... | [
"The compiler can't find python development headers. Asking the system administrator to install python-devel in case of CentOS or to install python-dev on Debian, Ubuntu and their derivatives. That should help.\n"
] | [
42
] | [] | [] | [
"python",
"twisted"
] | stackoverflow_0008629198_python_twisted.txt |
Q:
How to use the expando properties for a User object in webapp2?
I'm trying to use to expando proprties of the User object:
user = self.auth.store.user_model.create_user(username, password_raw=password)
user.name = username
But I receive an error message:
user.name = username
AttributeError: 'tuple... | How to use the expando properties for a User object in webapp2? | I'm trying to use to expando proprties of the User object:
user = self.auth.store.user_model.create_user(username, password_raw=password)
user.name = username
But I receive an error message:
user.name = username
AttributeError: 'tuple' object has no attribute 'name'
How should I do this for a User obj... | [
"create_user returns a tuple of created, user - the first is a boolean flag which shows whether or not the object was created.\ncreated, user = self.auth.store.user_model.create_user(...\n\n"
] | [
3
] | [] | [] | [
"google_app_engine",
"python",
"webapp2"
] | stackoverflow_0008628042_google_app_engine_python_webapp2.txt |
Q:
python resettable instance method memoization decorator
I'm attempting to build a decorator for an instance method of a class that will memoize the result. (This has been done a million times before) However, I'd like the option of being able to reset the memoized cache at any point (say, if something in the insta... | python resettable instance method memoization decorator | I'm attempting to build a decorator for an instance method of a class that will memoize the result. (This has been done a million times before) However, I'd like the option of being able to reset the memoized cache at any point (say, if something in the instance state changes, which might change the result of the metho... | [
"Rather than trying to work out the mechanics of your implementation, I've taken the memoized decorator class from PythonDecoratorLibrary, and have modified it to add reset. Below is the result; the trick I've used is to add a callable reset attribute to the decorated function itself.\n class memoized2(object):\... | [
7,
4,
0
] | [] | [] | [
"decorator",
"descriptor",
"memoization",
"python"
] | stackoverflow_0004431703_decorator_descriptor_memoization_python.txt |
Q:
Regex stemmer code explanation
Can someone please explain what does this code do?
def stemmer(word):
[(stem,end)] = re.findall('^(.*ss|.*?)(s)?$',word)
return stem
A:
It splits a word into two parts: stem and end. There are three cases:
The word ends with ss (or even more s): stem <- word and end <- ""... | Regex stemmer code explanation | Can someone please explain what does this code do?
def stemmer(word):
[(stem,end)] = re.findall('^(.*ss|.*?)(s)?$',word)
return stem
| [
"It splits a word into two parts: stem and end. There are three cases: \n\nThe word ends with ss (or even more s): stem <- word and end <- \"\"\nThe word ends with a single s: stem <- word without \"s\" and end <- \"s\"\nThe word does not end with s: stem <- word and end <- \"\"\n\nThis is done by a regular express... | [
4
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0008629433_python_regex.txt |
Q:
What is the proper way to verify an EmailMessage for proper recipient email addresses?
I am developing an application with Django. In forms.py, where the classes for my forms are stored, I have written a clean function to verify that all the emails typed into a textbox adhere to the proper format (person@site.com)... | What is the proper way to verify an EmailMessage for proper recipient email addresses? | I am developing an application with Django. In forms.py, where the classes for my forms are stored, I have written a clean function to verify that all the emails typed into a textbox adhere to the proper format (person@site.com).
In this clean function, I build the email message with an EmailMessage object:
def clean_r... | [
"Try to clean recipients emails format only in the clean_recipients. There is snippet how to check email. http://djangosnippets.org/snippets/1093/ . Raise validation error if email format does not match.\nCreate email and send it from the form's clean method (if you need show sending errors. You will need check fo... | [
0
] | [] | [] | [
"django",
"django_email",
"django_forms",
"python"
] | stackoverflow_0008627773_django_django_email_django_forms_python.txt |
Q:
calling function in print(""" """)
I want to call a function in formatted output of string using print(""" """) function of Python. For example:
print("""
something.......something...
abs(-10.5)
and then again some string......
""")
Is there any way to do it?
A:
This is how you can do it using the new and impro... | calling function in print(""" """) | I want to call a function in formatted output of string using print(""" """) function of Python. For example:
print("""
something.......something...
abs(-10.5)
and then again some string......
""")
Is there any way to do it?
| [
"This is how you can do it using the new and improved string formatting method (Python 2.6 and up):\nprint(\"\"\"\nsomething.......something...\n{0}\nand then again some string......\n\"\"\".format(abs(-10.5)))\n\n",
"You should do it like this:\nprint(\"\"\"\nsomething.......something...\n%s\nand then again some... | [
14,
4,
0
] | [] | [] | [
"python"
] | stackoverflow_0008629699_python.txt |
Q:
Python, os.system fails when script not in same folder
I have a bat.bat file containing the following command: 'setup.py build'
I have a script that executes this bat command using:
os.system('E:/bla/FPtest/retryURL/Temp_installed/bat.bat'
If i run the script from the same folder as the bat.bat ... it works perfec... | Python, os.system fails when script not in same folder | I have a bat.bat file containing the following command: 'setup.py build'
I have a script that executes this bat command using:
os.system('E:/bla/FPtest/retryURL/Temp_installed/bat.bat'
If i run the script from the same folder as the bat.bat ... it works perfectly perfectly.
If i run it in ANY other folder, the followin... | [
"In Windows 2000 and beyond the .py extension is associated with an open command that runs the interpreter. This is actually done during installation. But inorder to run the python script via the interpreter, either the script should be in the current directory or should be in one of the directories concatenated in... | [
3,
0,
0
] | [] | [] | [
"os.system",
"pydev",
"python",
"subprocess"
] | stackoverflow_0008628390_os.system_pydev_python_subprocess.txt |
Q:
Python subprocess to Bash: curly braces
I have the following Python lines:
import subprocess
subprocess.Popen("egrep -r --exclude=*{.git,.svn}* \"text\" ~/directory", stdout=subprocess.PIPE, shell=True).communicate()[0]
Unfortunately, bash completely ignores the --exclude=*{.git,.svn}* flag.
I've narrowed down th... | Python subprocess to Bash: curly braces | I have the following Python lines:
import subprocess
subprocess.Popen("egrep -r --exclude=*{.git,.svn}* \"text\" ~/directory", stdout=subprocess.PIPE, shell=True).communicate()[0]
Unfortunately, bash completely ignores the --exclude=*{.git,.svn}* flag.
I've narrowed down the problem to the curly braces. --exclude=*.gi... | [
"When you pass shell=True, python translates the command to /bin/sh -c <command> (as described here). /bin/sh apparently does not support the curly braces expansion. You can try the following instead:\nimport subprocess\nsubprocess.Popen([\"/bin/bash\", \"-c\", \"egrep -r --exclude=*{.git,.svn}* \\\"text\\\" ~/dire... | [
3,
2,
0,
0
] | [] | [] | [
"bash",
"popen",
"python"
] | stackoverflow_0008629618_bash_popen_python.txt |
Q:
pisa django displaying chinese characters as black blocks
I am trying to display Chinese characters using reportlab pisa. The generated Chinese words become black blocks. I am using UTF-8 to generate the PDFs
def render_to_pdf(template_src, context_dict):
"""Function to render html template into a pdf file"""
... | pisa django displaying chinese characters as black blocks | I am trying to display Chinese characters using reportlab pisa. The generated Chinese words become black blocks. I am using UTF-8 to generate the PDFs
def render_to_pdf(template_src, context_dict):
"""Function to render html template into a pdf file"""
template = get_template(template_src)
context = Context... | [
"This is a font problem, as whatever font you need to display is not embeddable by reportlabs in the pdf.\nSuggest you check the reportlabs ftp server for the font packages you need.\n"
] | [
3
] | [] | [] | [
"cjk",
"django",
"encoding",
"python",
"reportlab"
] | stackoverflow_0008629521_cjk_django_encoding_python_reportlab.txt |
Q:
Python Bottle.py decorator confusion
i have a decorator named "auth"
def auth(check_func=validate_login):
def decorator(view):
def wrapper(*args, **kwargs):
auth = check_func()
if auth:
return view(*args, **kwargs)
return bottle.redirect('/login.html... | Python Bottle.py decorator confusion | i have a decorator named "auth"
def auth(check_func=validate_login):
def decorator(view):
def wrapper(*args, **kwargs):
auth = check_func()
if auth:
return view(*args, **kwargs)
return bottle.redirect('/login.html')
return wrapper
return decor... | [
"Bottle route decorators are able to apply decorators to you without destroy auto json feature.\n@get('/', apply=[auth])\ndef handler():\n ...\n\nIf you don't want a view, just remove your @view decorator, Bottle handle dicts gracefully, converting it to a JSON answer.\n",
"I dont believe its right to have aut... | [
3,
1,
0
] | [] | [] | [
"bottle",
"decorator",
"python"
] | stackoverflow_0008619681_bottle_decorator_python.txt |
Q:
Beautiful Soup raises UnicodeEncodeError "ordinal not in range(128)"
I am trying to parse arbitrary documents download from the wild web, and yes, I have no control of their content.
Since Beautiful Soup won't choke if you give it bad markup... I wonder why does it giving me those hick-ups when sometimes, part of ... | Beautiful Soup raises UnicodeEncodeError "ordinal not in range(128)" | I am trying to parse arbitrary documents download from the wild web, and yes, I have no control of their content.
Since Beautiful Soup won't choke if you give it bad markup... I wonder why does it giving me those hick-ups when sometimes, part of the doc is malformed, and whether there is a way to make it resume to next... | [
"Yeah, It will choke if you have elements with non-ASCII names (<café>). And that's not even ‘bad markup’, for XML...\nIt's a bug in sgmllib which BeautifulSoup is using: it tries to find custom methods with the same names as tags, but in Python 2 method names are byte strings so even looking for a method with a no... | [
2,
0
] | [] | [] | [
"beautifulsoup",
"python",
"unicode"
] | stackoverflow_0008629792_beautifulsoup_python_unicode.txt |
Q:
Render Unified Diff with Python
I have a string which contains svn unified diff. My PyGTK app need to show this diff to user, and I want to render it like other diff tools do, or at least have it colorized.
Do you have something to suggest, external tool, library, custom implementation...? I was loking at http://k... | Render Unified Diff with Python | I have a string which contains svn unified diff. My PyGTK app need to show this diff to user, and I want to render it like other diff tools do, or at least have it colorized.
Do you have something to suggest, external tool, library, custom implementation...? I was loking at http://kafka.fr.free.fr/diff2html/ but I pref... | [
"You could use difflib to generate diffs, and pygtkscintilla for syntax-highlighting, line-numbering, code-folding, etc.\nIf you only want syntax-highlighting (as opposed to all the editor features offered by pygtkscintilla), then you could also look at pygments.\n",
"The difflib.HtmlDiff class provides facilitie... | [
4,
0
] | [
"GtkSourceView is a drop in replacement for pygtk's TextView that can syntax-highlight diff files, including unified diffs.\n"
] | [
-1
] | [
"diff",
"pygtk",
"python",
"svn",
"unified_diff"
] | stackoverflow_0008626226_diff_pygtk_python_svn_unified_diff.txt |
Q:
Python does not recognize a "New Line" command
I am a newbie when it comes to programming but I do have a little experience. My problem is this. I installed Python on my laptop on which the "Return" key is "Shift+Enter." For Python, the Return key gives the command to start a new line while enter gives the command... | Python does not recognize a "New Line" command | I am a newbie when it comes to programming but I do have a little experience. My problem is this. I installed Python on my laptop on which the "Return" key is "Shift+Enter." For Python, the Return key gives the command to start a new line while enter gives the command to run the line of code. Python does not recognize ... | [
"This should be\ndef f(n):\n\nNote the :.\n",
"A function declaration ends in a colon (:). Type\ndef f(n):\n\nand Python will allow you to enter more lines.\n"
] | [
4,
1
] | [] | [] | [
"enter",
"newline",
"python",
"return"
] | stackoverflow_0008630032_enter_newline_python_return.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.