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:
How to make two elements in gtk have the same size?
I'm using pyGTK. I want to layout a large element with 2 smaller ones on each side. For aesthetic reasons, I want the 2 smaller ones to be the same size. As it is, they differ by a few pixels, and the middle element is not centered as a result.
I tried using gtk.... | How to make two elements in gtk have the same size? | I'm using pyGTK. I want to layout a large element with 2 smaller ones on each side. For aesthetic reasons, I want the 2 smaller ones to be the same size. As it is, they differ by a few pixels, and the middle element is not centered as a result.
I tried using gtk.Table with 3 cells, but having homogeneous=True doesn't h... | [
"You should use GtkSizeGroup for this. Create a GtkSizeGroup, add both widgets to it. This will ensure that both widgets have the same size. If you want that widget have the same size in only one direction (width or height), set the \"mode\" property of SizeGroup.\n"
] | [
6
] | [] | [] | [
"gtk",
"layout",
"pygtk",
"python"
] | stackoverflow_0001229933_gtk_layout_pygtk_python.txt |
Q:
Can anyone explain this strange python turtle occurance?
If you don't know, python turtle is an application for helping people learn python.
You are given a python interpreter and an onscreen turtle that you can pass directions to using python.
go(10) will cause the turtle to move 10 pixels
turn(10) will cause it... | Can anyone explain this strange python turtle occurance? | If you don't know, python turtle is an application for helping people learn python.
You are given a python interpreter and an onscreen turtle that you can pass directions to using python.
go(10) will cause the turtle to move 10 pixels
turn(10) will cause it to turn 10 degrees clockwise
now look at this
code:
import ... | [
"When debugging a problem like this, it might be worthwhile to print out the value of each instruction as you perform it. Hopefully your turtle environment has a way to print values to some window on the screen. You might do something like this:\nwhile(1):\n r = random.randint(1,10)\n print \"going:\", r\n ... | [
7,
1,
0
] | [] | [] | [
"python",
"random"
] | stackoverflow_0001224944_python_random.txt |
Q:
Decode complex JSON in Python
I have a JSON object created in PHP, that JSON object contains another escaped JSON string in one of it's cells:
php > $insidejson = array('foo' => 'bar','foo1' => 'bar1');
php > $arr = array('a' => array('a1'=>json_encode($insidejson)));
php > echo json_encode($arr);
{"a":{"a1":"{\"... | Decode complex JSON in Python | I have a JSON object created in PHP, that JSON object contains another escaped JSON string in one of it's cells:
php > $insidejson = array('foo' => 'bar','foo1' => 'bar1');
php > $arr = array('a' => array('a1'=>json_encode($insidejson)));
php > echo json_encode($arr);
{"a":{"a1":"{\"foo\":\"bar\",\"foo1\":\"bar1\"}"}}... | [
"Try prefixing your string with 'r' to make it a raw string:\n# Python 2.6.2\n>>> import json\n>>> s = r'{\"a\":{\"a1\":\"{\\\"foo\\\":\\\"bar\\\",\\\"foo1\\\":\\\"bar1\\\"}\"}}'\n>>> json.loads(s)\n{u'a': {u'a1': u'{\"foo\":\"bar\",\"foo1\":\"bar1\"}'}}\n\nWhat Alex says below is true: you can just double the slas... | [
9,
1,
1
] | [] | [] | [
"json",
"php",
"python",
"simplejson"
] | stackoverflow_0001230347_json_php_python_simplejson.txt |
Q:
Does Django have a built in way of getting the last app url the current user visited?
I was hoping that Django had a built in way of getting the last url that was visited in the app itself. As I write this I realize that there are some complications in doing something like that (excluding pages that redirect, for... | Does Django have a built in way of getting the last app url the current user visited? | I was hoping that Django had a built in way of getting the last url that was visited in the app itself. As I write this I realize that there are some complications in doing something like that (excluding pages that redirect, for example) but i thought I'd give it a shot.
if there isn't a built-in for this, what stra... | [
"No, there is nothing like that built in to Django core (and it's not built in because it isn't a common usage pattern).\nLike Javier suggested, you could make some middleware which does what you want. Something like this:\nclass PreviousURLMiddleware(object):\n def process_response(request, response):\n ... | [
5,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0001230392_django_python.txt |
Q:
XML Parsing in Python using document builder factory
I am working in STAF and STAX. Here python is used for coding . I am new to python.
Basically my task is to parse a XML file in python using Document Factory Parser.
The XML file I am trying to parse is :
<?xml version="1.0" encoding="utf-8"?>
<operating_system>... | XML Parsing in Python using document builder factory | I am working in STAF and STAX. Here python is used for coding . I am new to python.
Basically my task is to parse a XML file in python using Document Factory Parser.
The XML file I am trying to parse is :
<?xml version="1.0" encoding="utf-8"?>
<operating_system>
<unix_80sp1>
<tests type="quick_sanity_test">
... | [
"You are need to instantiate vmware_value, vmware_attr and machname as lists not as strings, so instead of this:\nvmware_value = None\nvmware_attr = None\nmachname = None\n\ndo this:\nvmware_value = []\nvmware_attr = []\nmachname = []\n\nThen, to add items to the list, use the append method on your lists. E.g.:\nfa... | [
0
] | [] | [] | [
"parsing",
"python",
"xml"
] | stackoverflow_0001229507_parsing_python_xml.txt |
Q:
Need to make multiple files from a single excel file
I have a excel file. With many columns . I need to make multiple files using this
Eg: 0 0 0 0 0 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2. So these are the excel columns with each having many rows. I need one file which would contain 0 0 0 0 0 1 1 1 1 1 2 then second... | Need to make multiple files from a single excel file | I have a excel file. With many columns . I need to make multiple files using this
Eg: 0 0 0 0 0 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2. So these are the excel columns with each having many rows. I need one file which would contain 0 0 0 0 0 1 1 1 1 1 2 then second will contain only the second no 0 0 0 0 0 1 1 1 1 1 2..... | [
"You can use Spreadsheet::ParseExcel to read a spreadsheet. Unfortunately that is all I can help you with because, frankly, the description of your problem makes no sense.\n",
"Use Python and xlrd & xlwt. See http://www.python-excel.org\nThe following script should do what you want:\nimport xlrd, xlwt, sys\n\nde... | [
6,
2,
1,
1,
1,
0
] | [
"You could use Visual Basic for Applications to loop over the cells and then save to a text file.\nOR\nSave the file as a comma separated value file and use perl or python to easily parse the lines. (split on the comma for columns, end of line character for rows)\n"
] | [
-1
] | [
"perl",
"python"
] | stackoverflow_0001225550_perl_python.txt |
Q:
python unittest assertRaises throws exception when assertRaises fails
I've got code where assertRaises throws an exception when assertRaises fails. I thought that if assertRaises fails then the test would fail and I'd get a report at the end that says the test failed. I wasn't expecting the exception to be throw... | python unittest assertRaises throws exception when assertRaises fails | I've got code where assertRaises throws an exception when assertRaises fails. I thought that if assertRaises fails then the test would fail and I'd get a report at the end that says the test failed. I wasn't expecting the exception to be thrown. Below is my code. I'm I doing something wrong? I'm using Python 2.6.2... | [
"The code as posted is wrong. For a start, class myClass(): shoudl be class myClass:. Also if name == \"main\": should be:\nif __name__ == \"__main__\":\n unittest.main()\n\nApart from these problems, this fails because getName() is raising exception myExcOne and your test expects exception myExcTwo.\nHere is so... | [
6,
6
] | [] | [] | [
"python",
"python_unittest",
"unit_testing"
] | stackoverflow_0001230498_python_python_unittest_unit_testing.txt |
Q:
Unicode utf-8/utf-16 encoding in Python
In python:
u'\u3053\n'
Is it utf-16?
I'm not really aware of all the unicode/encoding stuff, but this type of thing is coming up in my dataset,
like if I have a=u'\u3053\n'.
print gives an exception and
decoding gives an exception.
a.encode("utf-16") > '\xff\xfeS0\n\x00'
... | Unicode utf-8/utf-16 encoding in Python | In python:
u'\u3053\n'
Is it utf-16?
I'm not really aware of all the unicode/encoding stuff, but this type of thing is coming up in my dataset,
like if I have a=u'\u3053\n'.
print gives an exception and
decoding gives an exception.
a.encode("utf-16") > '\xff\xfeS0\n\x00'
a.encode("utf-8") > '\xe3\x81\x93\n'
print a... | [
"It's a unicode character that doesn't seem to be displayable in your terminals encoding. print tries to encode the unicode object in the encoding of your terminal and if this can't be done you get an exception.\nOn a terminal that can display utf-8 you get:\n>>> print u'\\u3053'\nこ\n\nYour terminal doesn't seem to... | [
10,
8,
3,
1
] | [] | [] | [
"decoding",
"encoding",
"python",
"unicode"
] | stackoverflow_0001229414_decoding_encoding_python_unicode.txt |
Q:
How should I close a multi-line variable/comment in Python?
I am receiving this error:
File "/DateDbLoop.py", line 33
d.Id""" % (str(day), str(2840))"
^
SyntaxError: EOL while scanning single-quoted string
Here is the script. There are 4 double quotes to open this, but I am unsure how to correc... | How should I close a multi-line variable/comment in Python? | I am receiving this error:
File "/DateDbLoop.py", line 33
d.Id""" % (str(day), str(2840))"
^
SyntaxError: EOL while scanning single-quoted string
Here is the script. There are 4 double quotes to open this, but I am unsure how to correctly close this out?
Follow Up Question:
Does this % (str(day), st... | [
"You have 4 double-quotes at your sql= line, make it 3 instead. Also remove the single quote after your %-substitution value.\n#!/usr/bin/python\n\nimport datetime\nimport sys, os, time, string\n\na = datetime.date(2009, 1, 1)\nb = datetime.date(2009, 2, 1)\none_day = datetime.timedelta(1)\n\nday = a\n\nwhile day <... | [
5,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0001231333_python.txt |
Q:
Python Multiprocessing Exit Elegantly How?
import multiprocessing
import time
class testM(multiprocessing.Process):
def __init__(self):
multiprocessing.Process.__init__(self)
self.exit = False
def run(self):
while not self.exit:
pass
print "You exited!"
... | Python Multiprocessing Exit Elegantly How? | import multiprocessing
import time
class testM(multiprocessing.Process):
def __init__(self):
multiprocessing.Process.__init__(self)
self.exit = False
def run(self):
while not self.exit:
pass
print "You exited!"
return
def shutdown(self):
self.e... | [
"The reason you are not seeing this happen is because you are not communicating with the subprocess. You are trying to use a local variable (local to the parent process) to signal to the child that it should shutdown.\nTake a look at the information on synchonization primatives. You need to setup a signal of some... | [
57
] | [] | [] | [
"multiprocessing",
"python"
] | stackoverflow_0001231599_multiprocessing_python.txt |
Q:
Classes nested in functions and attribute lookup
The following works Ok, i.e. it doesn't give any errors:
def foo(arg):
class Nested(object):
x = arg
foo('hello')
But the following throws an exception:
def foo(arg):
class Nested(object):
arg = arg # note that names are the same
foo('hell... | Classes nested in functions and attribute lookup | The following works Ok, i.e. it doesn't give any errors:
def foo(arg):
class Nested(object):
x = arg
foo('hello')
But the following throws an exception:
def foo(arg):
class Nested(object):
arg = arg # note that names are the same
foo('hello')
Traceback:
Traceback (most recent call last):
F... | [
"The arg property shadows the arg function argument (inner scoping)\ndef foo(arg):\n class Nested(object):\n arg = arg # you try to read the `arg` property which isn't initialized\n\n\nYou get the same error if you type i = i in the interpreter window without having initialized the i variable.\n",
"If ... | [
5,
3,
3
] | [] | [] | [
"class",
"nested",
"python"
] | stackoverflow_0001231814_class_nested_python.txt |
Q:
New to Python. Need info on the environment for it
I'm a complete newbie to Python. I've worked on PHP/JavaScript earlier but starting today I'm moving onto Python. I have no idea about the environment needed for it. I could use some suggestions on it for me to get started.
A:
Under Unix, Emacs is a good choice... | New to Python. Need info on the environment for it | I'm a complete newbie to Python. I've worked on PHP/JavaScript earlier but starting today I'm moving onto Python. I have no idea about the environment needed for it. I could use some suggestions on it for me to get started.
| [
"Under Unix, Emacs is a good choice, to which I always come back, because it is convenient to have a single editor for everything, and because it's open source.\nWhat is best for you depends on your past experience with IDEs. I'd say: stick with what you've been using, or take this opportunity to try an even bette... | [
3,
2,
1,
1,
1,
0,
0,
0,
0
] | [] | [] | [
"ide",
"python"
] | stackoverflow_0001231397_ide_python.txt |
Q:
Does using properties on an old-style python class cause problems
Pretty simple question. I've seen it mentioned in many places that using properties on an old-style class shouldn't work, but apparently Qt classes (through PyQt4) aren't new-style and there are properties on a few of them in the code I'm working w... | Does using properties on an old-style python class cause problems | Pretty simple question. I've seen it mentioned in many places that using properties on an old-style class shouldn't work, but apparently Qt classes (through PyQt4) aren't new-style and there are properties on a few of them in the code I'm working with (and as far as I know the code isn't showing any sorts of problems)... | [
"property works because QObject has a metaclass that takes care of them. Witness this small variation on @quark's code...:\nfrom PyQt4.QtCore import QObject\n\ndef makec(base):\n class X( base ):\n def __init__(self):\n self.__x = 10\n def get_x(self):\n print 'getting',\n retu... | [
4,
3,
1
] | [] | [] | [
"class",
"properties",
"pyqt",
"python"
] | stackoverflow_0001230383_class_properties_pyqt_python.txt |
Q:
Django - Following a foreign key relationship (i.e JOIN in SQL)
Busy playing with django, but one thing seems to be tripping me up is following a foreign key relationship. Now, I have a ton of experience in writing SQL, so i could prob. return the result if the ORM was not there.
Basically this is the SQL query i... | Django - Following a foreign key relationship (i.e JOIN in SQL) | Busy playing with django, but one thing seems to be tripping me up is following a foreign key relationship. Now, I have a ton of experience in writing SQL, so i could prob. return the result if the ORM was not there.
Basically this is the SQL query i want returned
Select
table1.id
table1.text
table1.user
table... | [
"Something like this should work:\nu = Table1.objects.get(id=1)\nprint u.id\nprint u.user.user_name\n\nIf you want to follow a foreign key, you must do it explicitly. You don't get an automatic join, when you retrieve an object from Table1. You will only get an object from Table2, when you access a foreign key fiel... | [
4,
2
] | [] | [] | [
"django",
"django_models",
"django_urls",
"python"
] | stackoverflow_0001232172_django_django_models_django_urls_python.txt |
Q:
How to get a reference to the module something is implemented in from within that implementation?
Say I have the following code:
from foo.bar import Foo
from foo.foo import Bar
__all__ = ["Foo", "Bar"]
def iterate_over_all():
...
How can I implement code in the function iterate_over_all() that can dyna... | How to get a reference to the module something is implemented in from within that implementation? | Say I have the following code:
from foo.bar import Foo
from foo.foo import Bar
__all__ = ["Foo", "Bar"]
def iterate_over_all():
...
How can I implement code in the function iterate_over_all() that can dynamically obtain references to whatever is referenced in __all__ the module where the function is impleme... | [
"Would this do?\ndef iterate_over_all():\n for name in __all__:\n value = globals()[name]\n yield value # or do whatever with it\n\n",
"eval is one way. e.g. eval(\"Foo\") would give you Foo. However you can also just put Foo and Bar directly in your list e.g. __all__ = [Foo, Bar] \nIt would depe... | [
2,
0,
0
] | [] | [] | [
"module",
"python"
] | stackoverflow_0001231631_module_python.txt |
Q:
python String Formatting Operations
Faulty code:
pos_1 = 234
pos_n = 12890
min_width = len(str(pos_n)) # is there a better way for this?
# How can I use min_width as the minimal width of the two conversion specifiers?
# I don't understand the Python documentation on this :(
raw_str = '... from %(pos1)0*d to %(pos... | python String Formatting Operations | Faulty code:
pos_1 = 234
pos_n = 12890
min_width = len(str(pos_n)) # is there a better way for this?
# How can I use min_width as the minimal width of the two conversion specifiers?
# I don't understand the Python documentation on this :(
raw_str = '... from %(pos1)0*d to %(posn)0*d ...' % {'pos1':pos_1, 'posn': pos_n... | [
"pos_1 = 234\npos_n = 12890\nmin_width = len(str(pos_n))\n\nraw_str = '... from %0*d to %0*d ...' % (min_width, pos_1, min_width, pos_n)\n\n",
"\"1234\".rjust(13,\"0\")\n\nShould do what you need\naddition:\na = [\"123\", \"12\"] \nmax_width = sorted([len(i) for i in a])[-1]\n\nput max_width instead of 13 abov... | [
2,
1,
1
] | [] | [] | [
"formatting",
"python",
"string"
] | stackoverflow_0001231784_formatting_python_string.txt |
Q:
Django Model Sync Table
If I change a field in a Django model, how can I synchronize it with the database tables? Do I need to do it manually on the database or is there a tool that does helps with the process?
A:
Alas, Django does not support any easy solution to this.
The only thing django will do for you, i... | Django Model Sync Table | If I change a field in a Django model, how can I synchronize it with the database tables? Do I need to do it manually on the database or is there a tool that does helps with the process?
| [
"Alas, Django does not support any easy solution to this. \nThe only thing django will do for you, is restart your database with new tables that match your new models:\n$ #DON'T DO THIS UNLESS YOU CAN AFFORD TO LOSE ALL YOUR DATA!\n$ python PROJECT_DIR/manage.py syncdb\n\nthe next option is to use the various sql*... | [
6,
4,
3,
2,
0
] | [] | [] | [
"database",
"django",
"django_models",
"python",
"synchronization"
] | stackoverflow_0001115238_database_django_django_models_python_synchronization.txt |
Q:
Python multiprocessing easy way to implement a simple counter?
Hey everyone, I am using multiprocessing in python now. and I am just wondering whether there exists some sort of simple counter variable that each process when they are done processing some task could just increment ( kind of like how much work done i... | Python multiprocessing easy way to implement a simple counter? | Hey everyone, I am using multiprocessing in python now. and I am just wondering whether there exists some sort of simple counter variable that each process when they are done processing some task could just increment ( kind of like how much work done in total).
I looked up the API for Value, don't think it's mutable.
| [
"Value is indeed mutable; you specify the datatype you want from the ctypes module and then it can be mutated. Here's a complete, working script that demonstrates this:\nfrom time import sleep\nfrom ctypes import c_int\nfrom multiprocessing import Value, Lock, Process\n\ncounter = Value(c_int) # defaults to 0\nco... | [
27
] | [] | [] | [
"multiprocessing",
"python"
] | stackoverflow_0001233222_multiprocessing_python.txt |
Q:
Django ManyToMany Template Questions
Good Morning All,
I've been a PHP programmer for quite some time, but I've felt the need to move more towards the Python direction and what's better than playing around with Django.
While in the process, I'm come to a stopping point where I know there is an easy solution, but I... | Django ManyToMany Template Questions | Good Morning All,
I've been a PHP programmer for quite some time, but I've felt the need to move more towards the Python direction and what's better than playing around with Django.
While in the process, I'm come to a stopping point where I know there is an easy solution, but I'm just missing it - How do I display many... | [
"From what I can see, I think you've got a small syntax error:\n{% photo.image %}\n\nshould instead be:\n{{ photo.image }}\n\nThe {% %} notation is used for django template tags. Variables, on the other hand, are expressed with the {{ }} notation.\nTo make it dynamic, you can take advantage of the fact that your Ph... | [
3
] | [] | [] | [
"django",
"django_templates",
"many_to_many",
"python",
"templates"
] | stackoverflow_0001233709_django_django_templates_many_to_many_python_templates.txt |
Q:
How long do zipimported module imports remain cached in memory when using appengine / python and is there a way to keep them in memory?
I've recently uploaded an app that uses django appengine patch and currently have a cron job that runs every two minutes. On each invocation of the worker url it consumes quite a ... | How long do zipimported module imports remain cached in memory when using appengine / python and is there a way to keep them in memory? | I've recently uploaded an app that uses django appengine patch and currently have a cron job that runs every two minutes. On each invocation of the worker url it consumes quite a bit of resources
/worker_url 200 7633ms 34275cpu_ms 28116api_ms
That is because on each invocation it does a cold zipimport of all the lib... | [
"app engine keeps everything in memory according to normal Python semantics as long as it's serving one or more requests in the same process in the same node; if and when it needs those resources, the process goes away (so nothing stays in memory that it used to have), and new processes may be started (on the same ... | [
1
] | [] | [] | [
"django",
"google_app_engine",
"import",
"python"
] | stackoverflow_0001233826_django_google_app_engine_import_python.txt |
Q:
PIL does not save transparency
from PIL import Image
img = Image.open('1.png')
img.save('2.png')
The first image has a transparent background, but when I save it, the transparency is gone (background is white)
What am I doing wrong?
A:
Probably the image is indexed (mode "P" in PIL), so the transparency is not... | PIL does not save transparency | from PIL import Image
img = Image.open('1.png')
img.save('2.png')
The first image has a transparent background, but when I save it, the transparency is gone (background is white)
What am I doing wrong?
| [
"Probably the image is indexed (mode \"P\" in PIL), so the transparency is not set in PNG alpha channel, but in metadata info.\nYou can get transparent background palette index with the following code:\nfrom PIL import Image\n\nimg = Image.open('1.png')\npng_info = img.info\nimg.save('2.png', **png_info)\n\nimage i... | [
31,
6
] | [] | [] | [
"png",
"python",
"python_imaging_library"
] | stackoverflow_0001233772_png_python_python_imaging_library.txt |
Q:
PyQt : why adding a dummy class definition in my file make the application crash?
Consider the code below:
#!/usr/bin/env python
from PyQt4 import QtCore, QtGui
import os,sys
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
se... | PyQt : why adding a dummy class definition in my file make the application crash? | Consider the code below:
#!/usr/bin/env python
from PyQt4 import QtCore, QtGui
import os,sys
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.listWidget = QtGui.QListWidget(None)
self.setCentralWidget(self.listWidget)... | [
"Can't reproduce the problem as reported: the following exact code\nfrom PyQt4 import QtCore, QtGui\n\nimport os, sys\n\nclass MainWindow(QtGui.QMainWindow):\n def __init__(self, parent=None):\n super(MainWindow, self).__init__(parent) \n self.listWidget = QtGui.QListWidget(None)\n self.set... | [
1,
0
] | [] | [] | [
"pyqt4",
"python"
] | stackoverflow_0001233711_pyqt4_python.txt |
Q:
In GTK, how do I get the actual size of a widget on screen?
First I looked at the get_size_request method. The docs there end with:
To get the size a widget will actually use, call the size_request() instead of this method.
I look at size_request(), and it ends with
Also remember that the size request is not n... | In GTK, how do I get the actual size of a widget on screen? | First I looked at the get_size_request method. The docs there end with:
To get the size a widget will actually use, call the size_request() instead of this method.
I look at size_request(), and it ends with
Also remember that the size request is not necessarily the size a widget will actually be allocated.
So, is ... | [
"This should be it (took some time to find):\n\nThe get_allocation() method returns a gtk.gdk.Rectangle containing the bounds of the widget's allocation.\n\nFrom here.\n"
] | [
15
] | [] | [] | [
"api",
"gtk",
"pygtk",
"python",
"user_interface"
] | stackoverflow_0001234223_api_gtk_pygtk_python_user_interface.txt |
Q:
Concatenating Dictionaries
I have three lists, the first is a list of names, the second is a list of dictionaries, and the third is a list of data. Each position in a list corresponds with the same positions in the other lists. List_1[0] has corresponding data in List_2[0] and List_3[0], etc. I would like to turn ... | Concatenating Dictionaries | I have three lists, the first is a list of names, the second is a list of dictionaries, and the third is a list of data. Each position in a list corresponds with the same positions in the other lists. List_1[0] has corresponding data in List_2[0] and List_3[0], etc. I would like to turn these three lists into a diction... | [
">>> a = [1,2,3]\n>>> b = [4,5,6]\n>>> c = [7,8,9]\n>>> dict(zip(a, zip(b, c)))\n{1: (4, 7), 2: (5, 8), 3: (6, 9)}\n\nSee the documentation for more info on zip.\nAs lionbest points out below, you might want to look at itertools.izip() if your input data is large. izip does essentially the same thing as zip, but it... | [
13,
1,
0
] | [] | [] | [
"dictionary",
"key",
"merge",
"python"
] | stackoverflow_0001232904_dictionary_key_merge_python.txt |
Q:
k-means clustering implementation in python, running out of memory
Note: updates/solutions at the bottom of this question
As part of a product recommendation engine, I'm trying to segment my users based on their product preferences starting with using the k-means clustering algorithm.
My data is a dictionary of t... | k-means clustering implementation in python, running out of memory | Note: updates/solutions at the bottom of this question
As part of a product recommendation engine, I'm trying to segment my users based on their product preferences starting with using the k-means clustering algorithm.
My data is a dictionary of the form:
prefs = {
'user_id_1': { 1L: 3.0f, 2L: 1.0f, },
'user_i... | [
"Not all these observations are directly relevant to your issues as expressed, but..:\na. why are the key in prefs, as shown, longs? unless you have billions of users, simple ints will be fine and save you a little memory.\nb. your code:\ncentroids = [prefs[random.choice(users)] for i in range(k)]\n\ncan give you r... | [
6,
0
] | [] | [] | [
"python"
] | stackoverflow_0001233593_python.txt |
Q:
Should I learn Python after C++?
I`m currently studying C++ and want to learn another language.
For work I use C# + ASP (just started learning it, actually), but I want something "less Microsoft" and powerful.
I have heard Python is a popular and powerful language, not so complicated as C++. But many people mentio... | Should I learn Python after C++? | I`m currently studying C++ and want to learn another language.
For work I use C# + ASP (just started learning it, actually), but I want something "less Microsoft" and powerful.
I have heard Python is a popular and powerful language, not so complicated as C++. But many people mentioned it was hard for them to get back t... | [
"There's no right or wrong answer, really. But I think you'll benefit more from learning Python. Given the similarities between C# and C++, you'll learn a different way of thinking from Python. The more ways you learn to think about a problem, the better it makes you as a programmer, regardless of the language.\... | [
30,
9,
4,
4,
2,
2,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0
] | [] | [] | [
"c++",
"python"
] | stackoverflow_0000615100_c++_python.txt |
Q:
Searching a Unicode file using Python
Setup
I'm writing a script to process and annotate build logs from Visual Studio. The build logs are HTML, and from what I can tell, Unicode (UTF-16?) as well. Here's a snippet from one of the files:
c:\anonyfolder\anonyfile.c(17169) : warning C4701: potentially uninitializ... | Searching a Unicode file using Python | Setup
I'm writing a script to process and annotate build logs from Visual Studio. The build logs are HTML, and from what I can tell, Unicode (UTF-16?) as well. Here's a snippet from one of the files:
c:\anonyfolder\anonyfile.c(17169) : warning C4701: potentially uninitialized local variable 'object_adrs2' used
... | [
"Try using the codecs package:\nimport codecs\nbuildLog = codecs.open(sys.argv[1], \"r\", \"utf-16\").readlines()\n\nAlso you may run into trouble with your print statement as it may try to convert the strings to your console encoding. If you're printing for your review you could use,\nprint repr(line)\n\n",
"Tri... | [
7,
0
] | [] | [] | [
"encoding",
"python",
"unicode"
] | stackoverflow_0001235588_encoding_python_unicode.txt |
Q:
how can I add a QMenu and QMenuItems to a window from Qt Designer
Is there any reason why a QMenu cannot be added from the Qt Designer? I find it weird that you can add other widget types but not this.
A:
When you edit a QMainWindow you can right click the window and then choose "create menu bar".
Or are you tal... | how can I add a QMenu and QMenuItems to a window from Qt Designer | Is there any reason why a QMenu cannot be added from the Qt Designer? I find it weird that you can add other widget types but not this.
| [
"When you edit a QMainWindow you can right click the window and then choose \"create menu bar\".\nOr are you talking about a \"context menu\" aka \"right click menu\"?\n",
"I have a single main window with a QGraphicsView and lots of QGraphicsItem objects. Each type of the Items have a different context menu.\nI... | [
3,
3,
0
] | [] | [] | [
"designer",
"python",
"qt",
"widget"
] | stackoverflow_0000960467_designer_python_qt_widget.txt |
Q:
Introspecting a given function's nested (local) functions in Python
Given the function
def f():
x, y = 1, 2
def get():
print 'get'
def post():
print 'post'
is there a way for me to access its local get() and post() functions in a way that I can call them? I'm looking for a function t... | Introspecting a given function's nested (local) functions in Python | Given the function
def f():
x, y = 1, 2
def get():
print 'get'
def post():
print 'post'
is there a way for me to access its local get() and post() functions in a way that I can call them? I'm looking for a function that will work like so with the function f() defined above:
>>> get, post ... | [
"You are pretty close of doing that - just missing new module:\nimport inspect\nimport new\n\ndef f():\n x, y = 1, 2\n def get():\n print 'get'\n def post():\n print 'post'\n\nfor c in f.func_code.co_consts:\n if inspect.iscode(c):\n f = new.function(c, globals())\n print f #... | [
4,
2,
2,
1
] | [] | [] | [
"function",
"inspect",
"introspection",
"python"
] | stackoverflow_0001234672_function_inspect_introspection_python.txt |
Q:
py2app error: "can't copy '%s': doesn't exist or not a regular file"
I'm trying to pack my Python app with py2app. I'm running the setup.py I created, and I get this error:
File "C:\Python26\lib\distutils\file_util.py", line 119, in copy_file
"can't copy '%s': doesn't exist or not a regular file" % src
Distu... | py2app error: "can't copy '%s': doesn't exist or not a regular file" | I'm trying to pack my Python app with py2app. I'm running the setup.py I created, and I get this error:
File "C:\Python26\lib\distutils\file_util.py", line 119, in copy_file
"can't copy '%s': doesn't exist or not a regular file" % src
DistutilsFileError: can't copy '--dist-dir': doesn't exist or not a regular fil... | [
"It looks like, for some reason or other, it's trying to interpret the command-line switch --dist-dir as a filename. Perhaps the actual switch is named something else and you typo'd it? Or perhaps it needs to be specified in a different order?\n"
] | [
2
] | [] | [] | [
"macos",
"py2app",
"python"
] | stackoverflow_0001236104_macos_py2app_python.txt |
Q:
py2app error: "'module' object has no attribute 'symlink'"
I'm trying to pack my Python app with py2app. I'm running the setup.py I created, and I get this error:
Traceback (most recent call last):
File "C:\Python26\lib\site-packages\py2app-0.3.6-py2.6.egg\py2app\build_app.py
", line 548, in _run
self.run_no... | py2app error: "'module' object has no attribute 'symlink'" | I'm trying to pack my Python app with py2app. I'm running the setup.py I created, and I get this error:
Traceback (most recent call last):
File "C:\Python26\lib\site-packages\py2app-0.3.6-py2.6.egg\py2app\build_app.py
", line 548, in _run
self.run_normal()
File "C:\Python26\lib\site-packages\py2app-0.3.6-py2.6.... | [
"os.symlink is only available on Unix and Unix-like operating systems (including the Mac), not Windows.\npy2app is for the Mac - are you deliberately running it on Windows? Did you mean to use py2exe?\n"
] | [
2
] | [] | [] | [
"macos",
"py2app",
"python"
] | stackoverflow_0001236172_macos_py2app_python.txt |
Q:
In Twisted Python - Make sure a protocol instance would be completely deallocated
I have a pretty intensive chat socket server written in Twisted Python, I start it using internet.TCPServer with a factory and that factory references to a protocol object that handles all communications with the client.
How should I... | In Twisted Python - Make sure a protocol instance would be completely deallocated | I have a pretty intensive chat socket server written in Twisted Python, I start it using internet.TCPServer with a factory and that factory references to a protocol object that handles all communications with the client.
How should I make sure a protocol instance completely destroys itself once a client has disconnecte... | [
"ok, for sorting out this issue I have set a __del__ method in the protocol class and I am now logging protocol instances that have not been garbage collected within 1 minute from the time the client has disconnected. \nIf anybody has any better solution I'll still be glad to hear about it but so far I have already... | [
0
] | [] | [] | [
"python",
"sockets",
"twisted",
"twisted.words"
] | stackoverflow_0001234292_python_sockets_twisted_twisted.words.txt |
Q:
Creating multiple Python modules in different directories that share a portion of the package structure
I'm working on a Django project that contains a single application. The application will be released under the GPL so I want to develop it separately from the project - a personal site using the app. I'm attem... | Creating multiple Python modules in different directories that share a portion of the package structure | I'm working on a Django project that contains a single application. The application will be released under the GPL so I want to develop it separately from the project - a personal site using the app. I'm attempting to use a package structure based on my domain name for both the project and the app, and that's where I... | [
"Here's how __path__ in a package's __init__.py is intended to be used:\n$ export PYTHONPATH=$HOME/django-sites\n$ ls -d $HOME/django*\ndjango-apps/ django-sites/ \n$ cat /tmp/django-sites/mydomain/__init__.py\nimport os\n\n_components = __path__[0].split(os.path.sep)\nif _components[-2] == 'django-sites':\n _com... | [
4,
1,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0001236443_django_python.txt |
Q:
Is 'for x in array' always result in sorted x? [Python/NumPy]
For arrays and lists in Python and Numpy are the following lines equivalent:
itemlist = []
for j in range(len(myarray)):
item = myarray[j]
itemlist.append(item)
and:
itemlist = []
for item in myarray:
itemlist.append(item)
I'm interested i... | Is 'for x in array' always result in sorted x? [Python/NumPy] | For arrays and lists in Python and Numpy are the following lines equivalent:
itemlist = []
for j in range(len(myarray)):
item = myarray[j]
itemlist.append(item)
and:
itemlist = []
for item in myarray:
itemlist.append(item)
I'm interested in the order of itemlist. In a few examples that I have tried they a... | [
"Yes, it's entirely guaranteed. for item in myarray (where myarray is a sequence, which includes numpy's arrays, builtin lists, Python's array.arrays, etc etc), is in fact equivalent in Python to:\n_aux = 0\nwhile _aux < len(myarray):\n item = myarray[_aux]\n ...etc...\n\nfor some phantom variable _aux;-). Btw, ... | [
10,
10,
6
] | [] | [] | [
"arrays",
"list",
"numpy",
"python"
] | stackoverflow_0001236695_arrays_list_numpy_python.txt |
Q:
Are there any examples on python-purple floating around?
I want to learn it but I have no idea where to start. Everything out there suggests reading the libpurple source but I don't think I understand enough c to really get a grasp of it.
A:
There isn't much about it yet... the intro, the howto, and the sources... | Are there any examples on python-purple floating around? | I want to learn it but I have no idea where to start. Everything out there suggests reading the libpurple source but I don't think I understand enough c to really get a grasp of it.
| [
"There isn't much about it yet... the intro, the howto, and the sources (here browsing them online but of course you can git clone them) are about it. In particular, the tiny example client you can get from here does have some miniscule example of use of purple's facilities (definitely not enough, but maybe it can ... | [
2,
1,
0
] | [] | [] | [
"libpurple",
"python"
] | stackoverflow_0001186062_libpurple_python.txt |
Q:
Cron job python Google App Engine
I want to add a scheduled task to fetch a URL via cron job using google app engine. I am continuously getting a failure. I am just fetching www.google.com. Why is the url fetch failing? Am I missing something?
A:
"fetch" your OWN url (on appspot.com probably, but, who cares -- u... | Cron job python Google App Engine | I want to add a scheduled task to fetch a URL via cron job using google app engine. I am continuously getting a failure. I am just fetching www.google.com. Why is the url fetch failing? Am I missing something?
| [
"\"fetch\" your OWN url (on appspot.com probably, but, who cares -- use a relative url anywau1-), not google.com, the homepage of the search engine -- what's that got to do w/your app anyway?!-)...\n"
] | [
0
] | [] | [] | [
"cron",
"google_app_engine",
"python",
"scheduled_tasks"
] | stackoverflow_0001237126_cron_google_app_engine_python_scheduled_tasks.txt |
Q:
wxPython gauge problem (skipping)
Pastebin link: http://pastebin.com/f40ae1bcf
The problem: I made a wx.Gauge, with the range of 50. Then a function that updates Gauge's value when the program is idle. When the gauge is filled by around 50% it empties and doesn't show anything for a while. The value is actually 50... | wxPython gauge problem (skipping) | Pastebin link: http://pastebin.com/f40ae1bcf
The problem: I made a wx.Gauge, with the range of 50. Then a function that updates Gauge's value when the program is idle. When the gauge is filled by around 50% it empties and doesn't show anything for a while. The value is actually 50 when it does this, and I think that wh... | [
"A few things.\n\nI can't reproduce this on my iMac, it goes all the way to full. Python 2.5.4, wxPython 2.8.9.2\nIdle events can come at strange times. Try adding print event to your idle handler to see exactly when those events are coming. A timer would be best. Is the gauge moving really fast or flickering?\... | [
2,
0,
0
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0001235884_python_wxpython.txt |
Q:
launching vs2008 build from python
The first batch file launches a command prompt, i need the second command to be in the ccontext of the first. how can I do this in python?
As is, it launches the batch, and blocks until the batch (with its command prompt context) terminates, and then executes devenv without the ... | launching vs2008 build from python | The first batch file launches a command prompt, i need the second command to be in the ccontext of the first. how can I do this in python?
As is, it launches the batch, and blocks until the batch (with its command prompt context) terminates, and then executes devenv without the necessary context.
os.system(r'%comspec%... | [
"I think that the proper way for achieving this would be running this command:\n%comspec% /C \"%VCINSTALLDIR%\\vcvarsall.bat\" x86 && vcbuild \"project.sln\"\n\nBelow you'll see the Python version of the same command:\nos.system('%comspec% /C \"%VCINSTALLDIR%\\\\vcvarsall.bat\" x86 && vcbuild \"project.sln\"')\n\nT... | [
3,
2,
2,
2
] | [] | [] | [
"build_automation",
"python",
"visual_studio_2008",
"windows"
] | stackoverflow_0000263820_build_automation_python_visual_studio_2008_windows.txt |
Q:
how to overwrite User model
I don't like models.User, but I like Admin view, and I will keep admin view in my application.
How to overwirte models.User ?
Make it just look like following:
from django.contrib.auth.models import User
class ShugeUser(User)
username = EmailField(uniqute=True, verbose_name='EMai... | how to overwrite User model | I don't like models.User, but I like Admin view, and I will keep admin view in my application.
How to overwirte models.User ?
Make it just look like following:
from django.contrib.auth.models import User
class ShugeUser(User)
username = EmailField(uniqute=True, verbose_name='EMail as your
username', ...)
e... | [
"That isn't possible right now. If all you want is to use the email address as the username, you could write a custom auth backend that checks if the email/password combination is correct instead of the username/password combination (here's an example from djangosnippets.org).\nIf you want more, you'll have to hack... | [
4,
0
] | [] | [] | [
"django",
"django_admin",
"django_models",
"python"
] | stackoverflow_0001231943_django_django_admin_django_models_python.txt |
Q:
Choose the filename of an uploaded file with Django
I'm uploading images (represented by a FileField) and I need to rename those files when they are uploaded.
I want them to be formated like that:
"%d-%d-%s.%s" % (width, height, md5hash, original_extension)
I've read the documentation but I don't know if I need to... | Choose the filename of an uploaded file with Django | I'm uploading images (represented by a FileField) and I need to rename those files when they are uploaded.
I want them to be formated like that:
"%d-%d-%s.%s" % (width, height, md5hash, original_extension)
I've read the documentation but I don't know if I need to write my own FileSystemStorage class or my own FileField... | [
"You don't need to write your own FileStorage class or anything that complicated.\nThe 'upload_to' parameter on File/ImageFields can take a function that returns the path/file to use.\nHow to do this has already been answered here\n"
] | [
19
] | [
"My initial instinct when reading this was that you need to overload the save method on the model, and use the os.rename() method, but that causes a lot of overhead, and is just generally a hassle from start to finish. If you simply want to rename the file, but don't want to make any physical changes to it (resizin... | [
-1
] | [
"django",
"django_models",
"python"
] | stackoverflow_0001237602_django_django_models_python.txt |
Q:
Is it possible to utilize a python module that isnt installed into the python directories in linux?
I have a python application that depends on the uuid module, but on the server where I need to run it, uuid is not installed. I do not have root on the server so I cannot place the uuid .pys in the /usr/lib/python2.... | Is it possible to utilize a python module that isnt installed into the python directories in linux? | I have a python application that depends on the uuid module, but on the server where I need to run it, uuid is not installed. I do not have root on the server so I cannot place the uuid .pys in the /usr/lib/python2.4/site-packages folder... is there a way that I can utilize the .py's from elsewhere? like my ~ ?
| [
"There are several ways to do this. The fastest is the simple command:\nexport PYTHONPATH=path/to/module/directory\n\nAlternatively, you can use virtualenv. Just sudo apt-get install python-virtualenv (?). It's a very common development tool used for using modules that you don't necessarily want installed in you... | [
5,
1,
0,
0,
0
] | [] | [] | [
"linux",
"python"
] | stackoverflow_0001213448_linux_python.txt |
Q:
What does % do to strings in Python?
I have failed to find documentation for the operator % as it is used on strings in Python. What does this operator do when it is used with a string on the left hand side?
A:
It's the string formatting operator. Read up on string formatting in Python.
format % values
Creates ... | What does % do to strings in Python? | I have failed to find documentation for the operator % as it is used on strings in Python. What does this operator do when it is used with a string on the left hand side?
| [
"It's the string formatting operator. Read up on string formatting in Python.\nformat % values\n\nCreates a string where format specifies a format and values are the values to be filled in.\n",
"It applies printf-like formatting to a string, so that you can substitute certain parts of a string with values of vari... | [
39,
9,
8,
6
] | [] | [] | [
"documentation",
"operators",
"python",
"string"
] | stackoverflow_0001238306_documentation_operators_python_string.txt |
Q:
Does 'a+' mode allow random access to files, on all systems?
According to the documentation of open function
'a' means appending, which on some Unix systems means that all writes append to the end of the file regardless of the current seek position.
Will 'a+' allow random writes to any position in the file on all ... | Does 'a+' mode allow random access to files, on all systems? | According to the documentation of open function
'a' means appending, which on some Unix systems means that all writes append to the end of the file regardless of the current seek position.
Will 'a+' allow random writes to any position in the file on all systems?
| [
"On my linux system with Python 2.5.2 writes to a file opened with 'a+' appear to always append to the end, regardless of the current seek position.\nHere is an example:\nimport os\n\nif __name__ == \"__main__\":\n\n f = open(\"test\", \"w\")\n f.write(\"Hello\")\n f.close()\n\n f = open(\"test\", \"a+\... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0001238922_python.txt |
Q:
Can all language constructs be first-class in languages with offside-rules?
In LISP-like languages all language constructs are first-class citizens.
Consider the following example in Dylan:
let x = if (c)
foo();
else
bar();
end;
and in LISP:
(setf x (if c (foo) (bar)))
In Pyth... | Can all language constructs be first-class in languages with offside-rules? | In LISP-like languages all language constructs are first-class citizens.
Consider the following example in Dylan:
let x = if (c)
foo();
else
bar();
end;
and in LISP:
(setf x (if c (foo) (bar)))
In Python you would have to write:
if c:
x = foo();
else:
x = bar();
Because Py... | [
"Python has the following syntax that performs the same thing:\nx = foo() if c else bar()\n\n",
"I don't see the relation with first-classness here - you're not passing the if statement to the function, but the object it returns, which is as fully first class in python as in lisp. However as far as having a stat... | [
9,
5
] | [] | [] | [
"expression",
"if_statement",
"indentation",
"lisp",
"python"
] | stackoverflow_0001238975_expression_if_statement_indentation_lisp_python.txt |
Q:
comparing and sorting array
From two unequal arrays, i need to compare & delete based on the last value of an array.
Example:
m[0] and n[0] are read form a text file & saved as a array, [0] - their column number in text file.
m[0] = [0.00, 1.15, 1.24, 1.35, 1.54, 2.32, 2.85, 3.10, 3.40, 3.80, 4.10, 4.21, 4.44]
n[... | comparing and sorting array | From two unequal arrays, i need to compare & delete based on the last value of an array.
Example:
m[0] and n[0] are read form a text file & saved as a array, [0] - their column number in text file.
m[0] = [0.00, 1.15, 1.24, 1.35, 1.54, 2.32, 2.85, 3.10, 3.40, 3.80, 4.10, 4.21, 4.44]
n[0] = [0.00, 1.12, 1.34, 1.45, 2.5... | [
"Some details are a little unclear, but this should do what you want:\np[0] = [x for x in m[0] if x < n[0][-1]]\n\n",
"if both lists are ordered, you can do:\nimport bisect\nm[0][:bisect.bisect(m[0],n[0][-1])]\n\n",
"I haven't been able to test this but here you go...\np = []\nfor item in m[0]:\n if (item < ... | [
6,
1,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0001239509_list_python.txt |
Q:
Pythonic Comparison Functions
For the sake of simplicity, let's say I have a Person class in Python. This class has fields for firstname, lastname, and dob.
class Person:
def __init__(self, firstname, lastname, dob):
self.firstname = firstname;
self.lastname = lastname;
self.dob = dob;
In some situ... | Pythonic Comparison Functions | For the sake of simplicity, let's say I have a Person class in Python. This class has fields for firstname, lastname, and dob.
class Person:
def __init__(self, firstname, lastname, dob):
self.firstname = firstname;
self.lastname = lastname;
self.dob = dob;
In some situations I want to sort lists of Pers... | [
"If you really want a comparison function, you can use\ndef comparepeople(p1, p2):\n o1 = p1.lastname, p1.firstname, p1.dob\n o2 = p2.lastname, p2.firstname, p2.dob\n return cmp(o1,o2)\n\nThis relies on tuple comparison. If you want to sort a list, you shouldn't write a comparison function, though, but a k... | [
10,
4,
0
] | [] | [] | [
"comparison",
"metaprogramming",
"python"
] | stackoverflow_0001239751_comparison_metaprogramming_python.txt |
Q:
is it ever useful to define a class method with a reference to self not called 'self' in Python?
I'm teaching myself Python and I see the following in Dive into Python section 5.3:
By convention, the first argument of any Python class method (the reference to the current instance) is called self. This argument fi... | is it ever useful to define a class method with a reference to self not called 'self' in Python? | I'm teaching myself Python and I see the following in Dive into Python section 5.3:
By convention, the first argument of any Python class method (the reference to the current instance) is called self. This argument fills the role of the reserved word this in C++ or Java, but self is not a reserved word in Python, mere... | [
"No, unless you want to confuse every other programmer that looks at your code after you write it. self is not a keyword because it is an identifier. It could have been a keyword and the fact that it isn't one was a design decision.\n",
"As a side observation, note that Pilgrim is committing a common misuse of ... | [
9,
5,
4,
2,
1,
1
] | [] | [] | [
"naming_conventions",
"python"
] | stackoverflow_0001240229_naming_conventions_python.txt |
Q:
Python SOAP document handling
I've been trying to use suds for Python to call a SOAP WSDL. I just need to call the service programmatically and write the output XML document. However suds automatically parses this data into it's own pythonic data format. I've been looking through the examples and the documentation... | Python SOAP document handling | I've been trying to use suds for Python to call a SOAP WSDL. I just need to call the service programmatically and write the output XML document. However suds automatically parses this data into it's own pythonic data format. I've been looking through the examples and the documentation, but I can't seem to find a way to... | [
"At this early stage in suds development, the easiest way to get to the raw XML content is not what one would expect.\nThe examples on the site show us with something like this:\nclient = Client(url)\nresult = client.service.Invoke(subm)\n\nhowever, the result is a pre-parsed object that is great for access by Pyth... | [
3,
0
] | [] | [] | [
"python",
"soap",
"suds",
"wsdl",
"xml"
] | stackoverflow_0001239538_python_soap_suds_wsdl_xml.txt |
Q:
How to scale matplotlib subplot heights individually
Using matplotlib/pylab....
How do I plot 5 heatmaps as subplots which have the same number of columns but different row counts? In other words, I need each subplot's height to be scaled differently.
Perhaps an image better illustrates the problem...
alt text htt... | How to scale matplotlib subplot heights individually | Using matplotlib/pylab....
How do I plot 5 heatmaps as subplots which have the same number of columns but different row counts? In other words, I need each subplot's height to be scaled differently.
Perhaps an image better illustrates the problem...
alt text http://img98.imageshack.us/img98/5853/heatmap.png
I need the ... | [
"I haven't tried this for any of my own work, but perhaps the matplotlib AxesGrid toolkit might be what you are looking for.\n",
"Don't use subplot but axes to create your subplots - the latter allows arbitrary positioning of the subplot.\n"
] | [
4,
2
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0001228315_matplotlib_python.txt |
Q:
GTK: create a colored regular button
How do I do it? A lot of sites say I can just call .modify_bg() on the button, but that doesn't do anything. I'm able to add an EventBox to the button, and add a label to that, and then change its colors, but it looks horrendous - there is a ton of gray space between the edge o... | GTK: create a colored regular button | How do I do it? A lot of sites say I can just call .modify_bg() on the button, but that doesn't do anything. I'm able to add an EventBox to the button, and add a label to that, and then change its colors, but it looks horrendous - there is a ton of gray space between the edge of the button that doesn't change. I just w... | [
"Here's a little example:\nimport gtk\n\nwin = gtk.Window()\nwin.connect(\"destroy\", gtk.main_quit)\n\nbtn = gtk.Button(\"test\")\n\n#make a gdk.color for red\nmap = btn.get_colormap() \ncolor = map.alloc_color(\"red\")\n\n#copy the current style and replace the background\nstyle = btn.get_style().copy()\nstyle.bg... | [
16
] | [] | [] | [
"button",
"colors",
"gtk",
"pygtk",
"python"
] | stackoverflow_0001241020_button_colors_gtk_pygtk_python.txt |
Q:
How to filter a dictionary by value?
Newbie question here, so please bear with me.
Let's say I have a dictionary looking like this:
a = {"2323232838": ("first/dir", "hello.txt"),
"2323221383": ("second/dir", "foo.txt"),
"3434221": ("first/dir", "hello.txt"),
"32232334": ("first/dir", "hello.txt"),
... | How to filter a dictionary by value? | Newbie question here, so please bear with me.
Let's say I have a dictionary looking like this:
a = {"2323232838": ("first/dir", "hello.txt"),
"2323221383": ("second/dir", "foo.txt"),
"3434221": ("first/dir", "hello.txt"),
"32232334": ("first/dir", "hello.txt"),
"324234324": ("third/dir", "dog.txt")}... | [
"The code below will result in two variables, matches and remainders. matches is an array of dictionaries, in which matching items from the original dictionary will have a corresponding element. remainder will contain, as in your example, a dictionary containing all the unmatched items.\nNote that in your example... | [
10,
4,
1,
1,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0001241029_dictionary_python.txt |
Q:
What is the recommended Python module for fast Fourier transforms (FFT)?
Taking speed as an issue it may be better to choose another language, but what is your library/module/implementation of choice for doing a 1D fast Fourier transform (FFT) in Python?
A:
I would recommend numpy library, I not sure if it's the... | What is the recommended Python module for fast Fourier transforms (FFT)? | Taking speed as an issue it may be better to choose another language, but what is your library/module/implementation of choice for doing a 1D fast Fourier transform (FFT) in Python?
| [
"I would recommend numpy library, I not sure if it's the fastest implementation that exist but but surely it's one of best scientific module on the \"market\". \n",
"FFTW would probably be the fastest implementation, if you can find a python binding that actually works.\nThe easiest thing to use is certainly scip... | [
8,
5,
3
] | [] | [] | [
"benchmarking",
"fft",
"python"
] | stackoverflow_0001241797_benchmarking_fft_python.txt |
Q:
Python script knows how much memory it's using
How can a python script know the amount of system memory it's currently using? (assuming a unix-based OS)
A:
If you want to know the total memory that the interpreter uses, on Linux, read /proc/self/statm.
If you want to find out how much memory your objects use, us... | Python script knows how much memory it's using | How can a python script know the amount of system memory it's currently using? (assuming a unix-based OS)
| [
"If you want to know the total memory that the interpreter uses, on Linux, read /proc/self/statm.\nIf you want to find out how much memory your objects use, use Pympler.\n",
"Similar question:\nPython memory profiler\nLooks like there are memory profilers for python. \nPySizer seems popular. \nHeapy is another. ... | [
11,
4,
2,
1,
0
] | [] | [] | [
"memory_management",
"python"
] | stackoverflow_0001240581_memory_management_python.txt |
Q:
Specifying relative path in py2exe
When specifying my script file in setup.py, e.g. "script": 'pythonturtle.py', how can I specify its relative position in the file system? In my case, I need to go down two folders and then go into the "src" folder and it's in there. How do I write this in a cross-platform way?
A... | Specifying relative path in py2exe | When specifying my script file in setup.py, e.g. "script": 'pythonturtle.py', how can I specify its relative position in the file system? In my case, I need to go down two folders and then go into the "src" folder and it's in there. How do I write this in a cross-platform way?
| [
"How can you speak of py2exe and cross-platform? py2exe is windows only.\nAs far as I know, you have to keep your setup file in the same place as your script. Or if you don't have to it is certainly a strong convention.\nWhat you can do is define a dist_dir option so that your program gets built in the right place.... | [
3
] | [] | [] | [
"path",
"py2exe",
"python"
] | stackoverflow_0001241708_path_py2exe_python.txt |
Q:
Optimal way to replace characters in large string with Python?
I'm dealing with cleaning relatively large (30ish lines) blocks of text. Here's an excerpt:
PID|1||06225401^^^PA0^MR||PATIENT^FAKE
R|||F
PV1|1|I|||||025631^DoctorZ^^^^^^^PA0^^^^DRH|DRH||||...
ORC|RE||CYT-09-06645^AP||||||200912110333|INTERFACE07
O... | Optimal way to replace characters in large string with Python? | I'm dealing with cleaning relatively large (30ish lines) blocks of text. Here's an excerpt:
PID|1||06225401^^^PA0^MR||PATIENT^FAKE
R|||F
PV1|1|I|||||025631^DoctorZ^^^^^^^PA0^^^^DRH|DRH||||...
ORC|RE||CYT-09-06645^AP||||||200912110333|INTERFACE07
OBR|1||CYT09-06645|8104^^L|||20090602|||||||200906030000[conditio...
... | [
"You may find the answers here helpful.\nIterative find/replace from a list of tuples in Python\n",
"Here's an outline (untested) ... basically you do it a line at a time\nfor line in infile:\n data = line.rstrip(\"\\n\").split(\"|\")\n kind = data[0]\n # start of changes\n if kind == \"OBR\":\n ... | [
2,
2
] | [] | [] | [
"python"
] | stackoverflow_0001242209_python.txt |
Q:
How to co host django app with php5 on apache2 with mod_python?
I have django+python+apache2+mod_python installed hosted and working on ubuntu server/ linode VPS. php5 is installed and configured. We don't have a domain name as in example.com. Just IP address. So my apache .conf file looks like this
Serve... | How to co host django app with php5 on apache2 with mod_python? | I have django+python+apache2+mod_python installed hosted and working on ubuntu server/ linode VPS. php5 is installed and configured. We don't have a domain name as in example.com. Just IP address. So my apache .conf file looks like this
ServerAdmin webmaster@localhost
DocumentRoot /var/www
<Locatio... | [
"I need to test it, but this should get your Django project running at /mysite/:\n<VirtualHost *:80>\n DocumentRoot /var/www/vtigercrm/\n ErrorLog /var/log/apache2/vtiger.error_log\n CustomLog /var/log/apache2/vtiger.access_log combined\n <Directory /var/www/vtigercrm>\n Options Indexes FollowSym... | [
1
] | [] | [] | [
"apache",
"django",
"mod_python",
"php",
"python"
] | stackoverflow_0001239246_apache_django_mod_python_php_python.txt |
Q:
Do I only need to check the users machine for the version of the MSVCR90.dll that was installed with my python installation?
I was working on an update to my application and before I began I migrated to 2.62 because it seemed to be the time to. I walked right into the issue of having problems building my applicat... | Do I only need to check the users machine for the version of the MSVCR90.dll that was installed with my python installation? | I was working on an update to my application and before I began I migrated to 2.62 because it seemed to be the time to. I walked right into the issue of having problems building my application using py2exe because of the MSVCR90.dlls. There seems to be a fair amount of information on how to solve this issue, includin... | [
"Vista 64bit has a 32 bit emulator I believe, so you will not need to worry about this.\nHowever, I would just tell them to install the msvcrt runtime which is supposed to be the correct way to deal with this sxs mess.\n",
"From what I have gathered and learned the correct answer is that I have to worry about the... | [
1,
0
] | [] | [] | [
"msvcr90.dll",
"py2exe",
"python"
] | stackoverflow_0001230479_msvcr90.dll_py2exe_python.txt |
Q:
How can I highlight a row in a gtk.Table?
I want to highlight specific rows in a gtk.Table. I also want a mouseover to highlight it w/ a different color (like on a link in a web browser). I thought of just packing each cell with an eventBox and changing the STATE_NORMAL and STATE_PRELIGHT bg colors, which does wor... | How can I highlight a row in a gtk.Table? | I want to highlight specific rows in a gtk.Table. I also want a mouseover to highlight it w/ a different color (like on a link in a web browser). I thought of just packing each cell with an eventBox and changing the STATE_NORMAL and STATE_PRELIGHT bg colors, which does work, but mousing over the eventbox doesn't work. ... | [
"This seems to work:\n def attach(w,c1,c2,r1,r2):\n eb = gtk.EventBox()\n a = gtk.Alignment(xalign=0.0,yalign=0.5)\n a.add(w)\n eb.add(a)\n eb.set_style(self.rowStyle)\n def ene(eb,ev):\n eb.set_state(gtk.STATE_PRELIGHT)\n def lne(eb,ev):\n e... | [
2
] | [] | [] | [
"colors",
"gtk",
"pygtk",
"python"
] | stackoverflow_0001242531_colors_gtk_pygtk_python.txt |
Q:
What's the point of alloc_color() in gtk?
Various examples always use alloc_color() and stuff like gtk.color.parse('red'), etc. I just do gtk.gdk.Color(65535,0,0), and that seems to work. What's the need for alloc_color?
A:
If you're running on a system that uses a palette display (as opposed to a true-colour di... | What's the point of alloc_color() in gtk? | Various examples always use alloc_color() and stuff like gtk.color.parse('red'), etc. I just do gtk.gdk.Color(65535,0,0), and that seems to work. What's the need for alloc_color?
| [
"If you're running on a system that uses a palette display (as opposed to a true-colour display), then you must allocate new colours in the palette before you can use them. This is because palette-based displays can only display a limited number of colours at once (usually 256 or sometimes 65536).\nMost displays th... | [
2
] | [] | [] | [
"colors",
"gtk",
"pygtk",
"python"
] | stackoverflow_0001242541_colors_gtk_pygtk_python.txt |
Q:
pygtk: free variable referenced before assignment in enclosing scope
Very bizarre scoping error which I can't even see. Inside of an updater function, I have a nested helper function to... help w/ something:
def attach_row(ws,r1,r2):
es = []
for i,w in enumerate(ws):
eb = gtk.EventB... | pygtk: free variable referenced before assignment in enclosing scope | Very bizarre scoping error which I can't even see. Inside of an updater function, I have a nested helper function to... help w/ something:
def attach_row(ws,r1,r2):
es = []
for i,w in enumerate(ws):
eb = gtk.EventBox()
a = gtk.Alignment(xalign=0.0,yalign=0.5)
a.ad... | [
"Pretty mysterious indeed -- looks like the closure's disappearing out from under the inner functions. Wonder if that's related to how pygtk holds such callback functions (I'm not familiar with its internals). To try to probe for that -- what happens if you also append ene and lne to a global list at the end of att... | [
4,
0
] | [] | [] | [
"closures",
"gtk",
"programming_languages",
"python",
"semantics"
] | stackoverflow_0001242593_closures_gtk_programming_languages_python_semantics.txt |
Q:
why does this python program print True
x=True
def stupid():
x=False
stupid()
print x
A:
You don't need to declare a function-local variable in Python. The "x=False" is referring to an x local to stupid(). If you really want to modify the global x inside stupid:
def stupid():
global x
x=False
A:
... | why does this python program print True | x=True
def stupid():
x=False
stupid()
print x
| [
"You don't need to declare a function-local variable in Python. The \"x=False\" is referring to an x local to stupid(). If you really want to modify the global x inside stupid:\ndef stupid():\n global x\n x=False\n\n",
"To answer your next question, use global:\nx=True\ndef stupid():\n global x\n x=... | [
18,
10,
6,
5,
3,
2,
2,
2
] | [] | [] | [
"python"
] | stackoverflow_0001242460_python.txt |
Q:
subclassing int to attain a Hex representation
Basically I want to have access to all standard python int operators, eg __and__ and __xor__ etc, specifically whenever the result is finally printed I want it represented in Hex format. (Kind of like putting my calculator into Hex mode)
class Hex(int):
def __repr_... | subclassing int to attain a Hex representation | Basically I want to have access to all standard python int operators, eg __and__ and __xor__ etc, specifically whenever the result is finally printed I want it represented in Hex format. (Kind of like putting my calculator into Hex mode)
class Hex(int):
def __repr__(self):
return "0x%x"%self
__str__=__repr__ #... | [
"You should define __repr__ and __str__ separately:\nclass Hex(int):\n def __repr__(self):\n return \"Hex(0x%x)\" % self\n def __str__(self):\n return \"0x%x\" % self\n\nThe __repr__ function should (if possible) provide Python text that can be eval()uated to reconstruct the original object. On the other ha... | [
7,
6,
1,
1,
0
] | [] | [] | [
"hex",
"python",
"representation",
"subclassing"
] | stackoverflow_0001242589_hex_python_representation_subclassing.txt |
Q:
How to disable Control-C in a WindowsXP Python console program?
I'd like to put my cmd.com window into a mode where Control-C does not generate a SIGINT signal to Python (ActiveState if it matters).
I know I can use the signal module to handle SIGINT. The problem is that handling SIGINT is too late; by the time it... | How to disable Control-C in a WindowsXP Python console program? | I'd like to put my cmd.com window into a mode where Control-C does not generate a SIGINT signal to Python (ActiveState if it matters).
I know I can use the signal module to handle SIGINT. The problem is that handling SIGINT is too late; by the time it is handled, it has already interrupted a system call.
I'd like somet... | [
"You need to call the win32 API function SetConsoleCtrlHandler with NULL (0) as its first parameter and TRUE (1) as its second parameter. If you're already using pywin32, win32.SetConsoleCtrlHandler is fine for the purpose, otherwise ctypes should work, specifically via ctypes.windll.kernel32.SetConsoleCtrlHandler(... | [
4
] | [] | [] | [
"console_application",
"control_c",
"copy_paste",
"python",
"windows_xp"
] | stackoverflow_0001243047_console_application_control_c_copy_paste_python_windows_xp.txt |
Q:
Qt Image From Web
I'd like PyQt to load an image and display it from the web. Dozens of examples I've found online did not work, as they are for downloading the image.
I simply want to view it.
Something like
from PyQt4.QtWebKit import *
web = QWebView()
web.load(QUrl("http://stackoverflow.com/content/img/so/logo.... | Qt Image From Web | I'd like PyQt to load an image and display it from the web. Dozens of examples I've found online did not work, as they are for downloading the image.
I simply want to view it.
Something like
from PyQt4.QtWebKit import *
web = QWebView()
web.load(QUrl("http://stackoverflow.com/content/img/so/logo.png"))
| [
"import sys\nfrom PyQt4 import QtCore, QtGui, QtWebKit\n\napp = QtGui.QApplication(sys.argv) \n\nweb = QtWebKit.QWebView()\nweb.load(QtCore.QUrl(\"http://upload.wikimedia.org/wikipedia/commons/a/af/Tux.png\"))\nweb.show()\n\nsys.exit(app.exec_()) \n\n"
] | [
5
] | [] | [] | [
"pyqt",
"python",
"qt",
"qwebelement",
"qwebview"
] | stackoverflow_0001243064_pyqt_python_qt_qwebelement_qwebview.txt |
Q:
Access a large file in a zip archive with HTML in a python-webkit WebView without extracting
I apologize for any confusion from the question title. It's kind of a complex situation with components that are new to me so I'm unsure of how to describe it succinctly.
I have some xml data and an image in an archive (zi... | Access a large file in a zip archive with HTML in a python-webkit WebView without extracting | I apologize for any confusion from the question title. It's kind of a complex situation with components that are new to me so I'm unsure of how to describe it succinctly.
I have some xml data and an image in an archive (zip in this case, but could easily be tar or tar.gz) and using python, gtk, and webkit, place the im... | [
"The zipfile module in the standard Python library provides tools to create, read, write, append, and list a ZIP file. \nUsing ZipFile.read(name[, pwd]) ( return the bytes of the file name in the archive),\nyou can apply base64.b64encode(s[, altchars]) to the content. Note that in this straightforward process, the... | [
1
] | [] | [] | [
"gzip",
"python",
"tar",
"virtualfilesystem",
"zip"
] | stackoverflow_0001243485_gzip_python_tar_virtualfilesystem_zip.txt |
Q:
Validating XML in Python without non-python dependencies
I'm writing a small Python app for distribution. I need to include simple XML validation (it's a debugging tool), but I want to avoid any dependencies on compiled C libraries such as lxml or pyxml as those will make the resulting app much harder to distribut... | Validating XML in Python without non-python dependencies | I'm writing a small Python app for distribution. I need to include simple XML validation (it's a debugging tool), but I want to avoid any dependencies on compiled C libraries such as lxml or pyxml as those will make the resulting app much harder to distribute. I can't find anything that seems to fit the bill - for DTDs... | [
"Do you mean something like MiniXsv? I have never used it, but from the website, we can read that\n\nminixsv is a lightweight XML schema\n validator package written in pure\n Python (at least Python 2.4 is\n required).\n\nso, it should work for you.\nI believe that ElementTree could also be used for that goal, b... | [
4,
1,
1,
0
] | [] | [] | [
"dtd",
"python",
"schema",
"validation",
"xml"
] | stackoverflow_0001243449_dtd_python_schema_validation_xml.txt |
Q:
Is there a Python module/recipe (not numpy) for 2d arrays for small games
I am writing some small games in Python with Pygame & Pyglet as hobby projects.
A class for 2D array would be very handy. I use py2exe to send the games to relatives/friends and numpy is just too big and most of it's features are unnecessar... | Is there a Python module/recipe (not numpy) for 2d arrays for small games | I am writing some small games in Python with Pygame & Pyglet as hobby projects.
A class for 2D array would be very handy. I use py2exe to send the games to relatives/friends and numpy is just too big and most of it's features are unnecessary for my requirements.
Could you suggest a Python module/recipe I could use for... | [
"How about using a defaultdict?\n>>> import collections\n>>> Matrix = lambda: collections.defaultdict(int)\n>>> m = Matrix()\n>>> m[3,2] = 6\n>>> print m[3,4] # deliberate typo :-)\n0\n>>> m[3,2] += 4\n>>> print m[3,2]\n10\n>>> print m\ndefaultdict(<type 'int'>, {(3, 2): 10, (3, 4): 0})\n\nAs the underlying dict ... | [
6,
3,
2,
0
] | [] | [] | [
"arrays",
"multidimensional_array",
"python"
] | stackoverflow_0000929274_arrays_multidimensional_array_python.txt |
Q:
Consuming COM events in Python
I am trying to do a sample app in python which uses some COM objects. I've read the famous chapter 12 from Python Programing on Win32 but regarding this issue it only states:
All event handling is done using
normal IConnectionPoint interfaces,
and although beyond the scope of th... | Consuming COM events in Python | I am trying to do a sample app in python which uses some COM objects. I've read the famous chapter 12 from Python Programing on Win32 but regarding this issue it only states:
All event handling is done using
normal IConnectionPoint interfaces,
and although beyond the scope of this
book, is fully supported by the... | [
"I haven't automated Excel, but I'm using some code from Microsoft's Speech API that may be similar enough to get you started:\nListenerBase = win32com.client.getevents(\"SAPI.SpInProcRecoContext\")\nclass Listener(ListenerBase):\n def OnRecognition(self, _1, _2, _3, Result):\n \"\"\"Callback whenever som... | [
6
] | [] | [] | [
"com",
"python",
"pywin32"
] | stackoverflow_0001244463_com_python_pywin32.txt |
Q:
Accessing a pointer in an object's internal structure
I'm using the pyOpenSSL interface to the OpenSSL library but it is missing some functions I need and I can't or don't want to modify it to support these methods (for various reasons).
So what I want to achieve, is to retrieve the OpenSSL object pointer. After t... | Accessing a pointer in an object's internal structure | I'm using the pyOpenSSL interface to the OpenSSL library but it is missing some functions I need and I can't or don't want to modify it to support these methods (for various reasons).
So what I want to achieve, is to retrieve the OpenSSL object pointer. After that, I will be able to call the missing functions through c... | [
"Pointers doesn't really make much sense in Python, as you can't do anything with them. They would just be an integer. As you have noticed you can get the address of an object with the id method. But that's just what it is, the address. It's not a pointer, so you can't do anything with it.\nYou could also see it li... | [
3
] | [] | [] | [
"internals",
"pointers",
"python"
] | stackoverflow_0001243806_internals_pointers_python.txt |
Q:
Flexible 'em' style Fonts with wxPython
Im looking for a way to present a flexible font, that will increase and decrease in size according to to the size of the screen resolution. I want to be able to do this without the HTML window class. Is there a way? I thought I've done quite a bit of googling without succ... | Flexible 'em' style Fonts with wxPython | Im looking for a way to present a flexible font, that will increase and decrease in size according to to the size of the screen resolution. I want to be able to do this without the HTML window class. Is there a way? I thought I've done quite a bit of googling without success.
EDIT
This seems a good question, I chan... | [
"Maybe something like this? You can scale any wx.Window in this way. Not sure if this is exactly what you mean though.\nimport wx\n\ndef scale(widget, percentage):\n font = widget.GetFont()\n font.SetPointSize(int(font.GetPointSize() * percentage / 100.0))\n widget.SetFont(font)\n\nclass Frame(wx.Frame):... | [
1
] | [] | [] | [
"font_size",
"fonts",
"python",
"wxpython"
] | stackoverflow_0001225248_font_size_fonts_python_wxpython.txt |
Q:
Disable console output from subprocess.Popen in Python
I run Python 2.5 on Windows, and somewhere in the code I have
subprocess.Popen("taskkill /PID " + str(p.pid))
to kill IE window by pid. The problem is that without setting up piping in Popen I still get output to console - SUCCESS: The process with PID 2068 h... | Disable console output from subprocess.Popen in Python | I run Python 2.5 on Windows, and somewhere in the code I have
subprocess.Popen("taskkill /PID " + str(p.pid))
to kill IE window by pid. The problem is that without setting up piping in Popen I still get output to console - SUCCESS: The process with PID 2068 has been terminated. I debugged it to CreateProcess in subpro... | [
"import os\nfrom subprocess import check_call, STDOUT\n\nDEVNULL = open(os.devnull, 'wb')\ntry:\n check_call((\"taskkill\", \"/PID\", str(p.pid)), stdout=DEVNULL, stderr=STDOUT)\nfinally:\n DEVNULL.close()\n\nI always pass in tuples to subprocess as it saves me worrying about escaping. check_call ensures (a) ... | [
17,
9
] | [] | [] | [
"console",
"popen",
"python",
"subprocess"
] | stackoverflow_0001244723_console_popen_python_subprocess.txt |
Q:
How to implement a state-space tree?
I'm trying to solve a knapsack like problem from MIT OCW.
Its problem set 5.
I need use branch and bound algorithm to find the optimal states.
So I need implement a state-space tree.
I understand the idea of this algorithm, but I find it's not so easy to implement.
If I find a ... | How to implement a state-space tree? | I'm trying to solve a knapsack like problem from MIT OCW.
Its problem set 5.
I need use branch and bound algorithm to find the optimal states.
So I need implement a state-space tree.
I understand the idea of this algorithm, but I find it's not so easy to implement.
If I find a node where the budget is not enough, I sho... | [
"I hope I understood correctly the problem, if not please direct me :)\n(sorry for the confusion arising from the two different meanings of \"state\")\nYou can of course add the attribute in the node (it's part of the state!), since it's a very tiny amount of data. Mind that it is not mandatory to save it though, s... | [
2
] | [] | [] | [
"algorithm",
"python"
] | stackoverflow_0001237634_algorithm_python.txt |
Q:
Can I use more than a single filter on a variable in template?
For example:
{{test|linebreaksbr|safe}}
A:
Yes you can, this is common practice to string together many filters consecutively.
Could you turn debugging on and see what the error is and update the question?
Make sure this is set in your settings.py
D... | Can I use more than a single filter on a variable in template? | For example:
{{test|linebreaksbr|safe}}
| [
"Yes you can, this is common practice to string together many filters consecutively.\nCould you turn debugging on and see what the error is and update the question?\nMake sure this is set in your settings.py\nDEBUG = True\nTEMPLATE_DEBUG = DEBUG\n\n",
"Yes, have you tried it? Did something go wrong?\n"
] | [
2,
2
] | [] | [] | [
"django",
"filter",
"python",
"templates"
] | stackoverflow_0001246968_django_filter_python_templates.txt |
Q:
How can I process this text file and parse what I need?
I'm trying to parse ouput from the Python doctest module and store it in an HTML file.
I've got output similar to this:
**********************************************************************
File "example.py", line 16, in __main__.factorial
Failed example:
... | How can I process this text file and parse what I need? | I'm trying to parse ouput from the Python doctest module and store it in an HTML file.
I've got output similar to this:
**********************************************************************
File "example.py", line 16, in __main__.factorial
Failed example:
[factorial(n) for n in range(6)]
Expected:
[0, 1, 2, 6,... | [
"You can write a Python program to pick this apart, but maybe a better thing to do would be to look into modifying doctest to output the report you want in the first place. From the docs for doctest.DocTestRunner:\n ... the display output\ncan be also customized by subclassing DocTe... | [
4,
1,
1,
0
] | [] | [] | [
"doctest",
"parsing",
"python",
"shell"
] | stackoverflow_0001246752_doctest_parsing_python_shell.txt |
Q:
how to include % sign in docutils html template
I want to generate HTML pages with rst2html, using my own templates. these templates include many % signs, like in
<TABLE border="0" cellpadding="0" cellspacing="0" width="100%">
now, when I call rst2html using the command
rst2html --template=layout2.tpl rst/index.r... | how to include % sign in docutils html template | I want to generate HTML pages with rst2html, using my own templates. these templates include many % signs, like in
<TABLE border="0" cellpadding="0" cellspacing="0" width="100%">
now, when I call rst2html using the command
rst2html --template=layout2.tpl rst/index.rst > index.html
i get the error
ValueError: unsuppo... | [
"Have you tried obvious things: escaping the '%' with '%'? \nHere is normal string formatting to display a percent sign in the result:\n>>> print \"%d%%\" % 100\n100%\n\nMaybe rst2html is the same? (I haven't tried this in rst2html -- I don't have it installed.)\nOkay, now I've installed docutils. This works for me... | [
7,
0
] | [] | [] | [
"python"
] | stackoverflow_0001247284_python.txt |
Q:
Open-source fractal maps
I'm interested in creating a game that uses fractal maps for more realistic geography. However, the only fractal map programs I have found are Windows-only, for example Fractal Mapper. Needless to say, they are also not open-sourced.
Are there any open-sourced fractal map creators availabl... | Open-source fractal maps | I'm interested in creating a game that uses fractal maps for more realistic geography. However, the only fractal map programs I have found are Windows-only, for example Fractal Mapper. Needless to say, they are also not open-sourced.
Are there any open-sourced fractal map creators available, preferably in Python or C/C... | [
"Fracplanet may be of use.\n",
"Basic terrain generation involves creating a height map (an image) and rendering it using the pixel colour as height. So you may find image or texture generation code useful. This is a good tutorial.\n",
"For the terrain aspect take a look at libnoise.\nIt's packaged for Debian, ... | [
9,
4,
1,
1,
0,
0
] | [] | [] | [
"c++",
"fractals",
"maps",
"open_source",
"python"
] | stackoverflow_0000157211_c++_fractals_maps_open_source_python.txt |
Q:
Python: StopIteration exception and list comprehensions
I'd like to read at most 20 lines from a csv file:
rows = [csvreader.next() for i in range(20)]
Works fine if the file has 20 or more rows, fails with a StopIteration exception otherwise.
Is there an elegant way to deal with an iterator that could throw a St... | Python: StopIteration exception and list comprehensions | I'd like to read at most 20 lines from a csv file:
rows = [csvreader.next() for i in range(20)]
Works fine if the file has 20 or more rows, fails with a StopIteration exception otherwise.
Is there an elegant way to deal with an iterator that could throw a StopIteration exception in a list comprehension or should I use... | [
"You can use itertools.islice. It is the iterator version of list slicing. If the iterator has less than 20 elements, it will return all elements.\nimport itertools\nrows = list(itertools.islice(csvreader, 20))\n\n",
"itertools.izip (2) provides a way to easily make list comprehensions work, but islice looks to b... | [
15,
0
] | [
"If for whatever reason you need also to keep track of the line number, I'd recommend you:\nrows = zip(xrange(20), csvreader)\n\nIf not, you can strip it out after or... well, you'd better try other option more optimal from the beginning :-)\n"
] | [
-1
] | [
"iterator",
"list_comprehension",
"python",
"stopiteration"
] | stackoverflow_0001106903_iterator_list_comprehension_python_stopiteration.txt |
Q:
Web Service require Python List as argument. Need to invoke from C#
I need to consume a webservice over XML-RPC. The webservice is written in Python, and one of the arguments is a Python list.
I'm using XML-RPC.NET to invoke all the methods and it works fine, except for those that require a Python list argument.
W... | Web Service require Python List as argument. Need to invoke from C# | I need to consume a webservice over XML-RPC. The webservice is written in Python, and one of the arguments is a Python list.
I'm using XML-RPC.NET to invoke all the methods and it works fine, except for those that require a Python list argument.
What would be the corresponding structure in C# which, if I pass as the ar... | [
"You need to use arrays of System.Object[]. See http://www.xml-rpc.net/faq/xmlrpcnetfaq.html#1.12 These are generally equivalent to Python lists.\n",
"What you need to obtain in the underlying XML is an <array> tag, e.g.\n<array>\n <data>\n <value><i4>12</i4></value>\n <value><string>Egypt</string><... | [
2,
1
] | [] | [] | [
"c#",
"python",
"xml_rpc"
] | stackoverflow_0001247638_c#_python_xml_rpc.txt |
Q:
Finding the domain name of a site that is hotlinking in Google app engine using web2py
Let's say we have an image in the Google App Engine and sites are hotlinking it.
How can I find the domain names of the sites?
My first thought was:
request.client
and then do a reverse lookup but that it's not possible in GAE... | Finding the domain name of a site that is hotlinking in Google app engine using web2py | Let's say we have an image in the Google App Engine and sites are hotlinking it.
How can I find the domain names of the sites?
My first thought was:
request.client
and then do a reverse lookup but that it's not possible in GAE and would take a lot of time.
I am pretty sure that there is a property that allows me to g... | [
"You can easily get the referrer from the request headers. This referrer can be spoofed, but most people do not spoof it and it is already resolved.\nThere is no automatic way to resolve the DNS other than manually resolving it. Like you said, a DNS resolution takes extra time and it makes no sense for Web2Py or an... | [
2,
1
] | [] | [] | [
"google_app_engine",
"python",
"reverse_lookup",
"web2py"
] | stackoverflow_0001247593_google_app_engine_python_reverse_lookup_web2py.txt |
Q:
Python - printing out all references to a specific instance
I am investigating garbage collection issues in a Python app. What would be the best readable option to print out all variables referencing a specific instance?
A:
Use the inspect module. This script helps if you just want to track down reference leaks... | Python - printing out all references to a specific instance | I am investigating garbage collection issues in a Python app. What would be the best readable option to print out all variables referencing a specific instance?
| [
"Use the inspect module. This script helps if you just want to track down reference leaks:\nhttp://mg.pov.lt/objgraph.py http://mg.pov.lt/blog/hunting-python-memleaks http://mg.pov.lt/blog/python-object-graphs.html\n",
"Try Finding objects' names, it prints all names that reference a given object.\n"
] | [
2,
1
] | [] | [] | [
"garbage_collection",
"oop",
"python"
] | stackoverflow_0001247697_garbage_collection_oop_python.txt |
Q:
Python plotting: How can I make matplotlib.pyplot stop forcing the style of my markers?
I am trying to plot a bunch of data points (many thousands) in Python using matplotlib so I need each marker to be very small and precise. How do I get the smallest most simple marker possible? I use this command to plot my d... | Python plotting: How can I make matplotlib.pyplot stop forcing the style of my markers? | I am trying to plot a bunch of data points (many thousands) in Python using matplotlib so I need each marker to be very small and precise. How do I get the smallest most simple marker possible? I use this command to plot my data:
matplotlib.pyplot( x , y ,'.',markersize=0.1,linewidth=None,markerfacecolor='black')
T... | [
"For nice-looking vectorized output, don't use the '.' marker style. Use e.g. 'o' (circle) or 's' (square) (see help(plot) for the options) and set the markersize keyword argument to something suitably small, e.g.:\nplot(x, y, 'ko', markersize=2)\nsavefig('foo.ps')\n\nThat '.' (point) produces less nice results cou... | [
20,
10,
2
] | [] | [] | [
"coding_style",
"matplotlib",
"python"
] | stackoverflow_0000544542_coding_style_matplotlib_python.txt |
Q:
django extreme slowness
I have a slowness problem with Django and I can't find the source .. I'm not sure what I'm doing wrong, but at least twice while working on projects Django became really slow.
Requests takes age to complete (~15 seconds) and Validating model when starting the development server is also very... | django extreme slowness | I have a slowness problem with Django and I can't find the source .. I'm not sure what I'm doing wrong, but at least twice while working on projects Django became really slow.
Requests takes age to complete (~15 seconds) and Validating model when starting the development server is also very slow (12+ seconds on a quad ... | [
"I've posted this question on serverfault maybe it will help you. \nIf you are serving big static files - those will slow down response.\nThis will be the case in any mode if your mod_python or development server process big static files like images, client scripts, etc.\nYou want to configure the production server... | [
6,
0,
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0001247501_django_python.txt |
Q:
django binary (no source code) deployment
is there possible only to deploy binary version of web application based on django , no source code publish?
Thanks
A:
Oh, again that old one... Simply stated, you can't deploy an application in a non-compiled language (Python, Perl, PHP, Ruby...) in a source-safe way - ... | django binary (no source code) deployment | is there possible only to deploy binary version of web application based on django , no source code publish?
Thanks
| [
"Oh, again that old one... Simply stated, you can't deploy an application in a non-compiled language (Python, Perl, PHP, Ruby...) in a source-safe way - all existing tricks are extremely easy to circumvent. Anyway, that doesn't matter at all: the contract you have with your customer does. Even for Java there are n... | [
14,
5,
3
] | [] | [] | [
"binary",
"django",
"python"
] | stackoverflow_0001241813_binary_django_python.txt |
Q:
Using Cheetah Templating system with windows and python 2.6.1 (namemapper problem)
So I am trying to use the Cheetah templating engine in conjunction with the Django web framework, and that is actually working fine. I did some simple tests with that and I was able to render pages and whatnot.
However, problems ar... | Using Cheetah Templating system with windows and python 2.6.1 (namemapper problem) | So I am trying to use the Cheetah templating engine in conjunction with the Django web framework, and that is actually working fine. I did some simple tests with that and I was able to render pages and whatnot.
However, problems arise whenever doing anything other than using very simple variable/attribute/methods in t... | [
"I have compiled the PYD file for Python 2.6 as well as Windows installers that have it bundled in, so that users don't have to figure out where to drop the PYD on Windows.\nInstallers: http://feisley.com/python/cheetah/ (pyd files are in the /pyd folder)\nHope this helps!\n"
] | [
6
] | [] | [] | [
"cheetah",
"django",
"python",
"template_engine",
"windows"
] | stackoverflow_0001155065_cheetah_django_python_template_engine_windows.txt |
Q:
Dropping the Unicode markers in Html output
I have a python list which holds a few email ids accepted as unicode strings:
[u'one@example.com',u'two@example.com',u'three@example.com']
This is assigned to values['Emails'] and values is passed to render as html.
The Html renders as this:
Emails: [u'one@example.com'... | Dropping the Unicode markers in Html output | I have a python list which holds a few email ids accepted as unicode strings:
[u'one@example.com',u'two@example.com',u'three@example.com']
This is assigned to values['Emails'] and values is passed to render as html.
The Html renders as this:
Emails: [u'one@example.com',u'two@example.com',u'three@example.com']
I woul... | [
"In Python:\n'[%s]' % ', '.join(pythonlistwithemails)\n\nIn bare HTML it is impossible... you'd have to use javascript.\n",
"I don't know any Python, but if those u-markers and the single quotes show, doesn't that actually indicate that you're accessing the list members in the wrong way? \nYou're printing the who... | [
4,
2,
2,
1,
1,
0,
0,
-1
] | [] | [] | [
"django",
"html",
"html_lists",
"python",
"unicode"
] | stackoverflow_0001222508_django_html_html_lists_python_unicode.txt |
Q:
What does the "s!" operator in Perl do?
I have this Perl snippet from a script that I am translating into Python. I have no idea what the "s!" operator is doing; some sort of regex substitution. Unfortunately searching Google or Stackoverflow for operators like that doesn't yield many helpful results.
$var =~ s!<... | What does the "s!" operator in Perl do? | I have this Perl snippet from a script that I am translating into Python. I have no idea what the "s!" operator is doing; some sort of regex substitution. Unfortunately searching Google or Stackoverflow for operators like that doesn't yield many helpful results.
$var =~ s!<foo>.+?</foo>!!;
$var =~ s!;!/!g;
What is e... | [
"s!foo!bar! is the same as the more common s/foo/bar/, except that foo and bar can contain unescaped slashes without causing problems. What it does is, it replaces the first occurence of the regex foo with bar. The version with g replaces all occurences.\n",
"It's doing exactly the same as $var =~ s///. i.e. perf... | [
15,
13,
10,
3,
3,
3,
0
] | [] | [] | [
"perl",
"python",
"regex"
] | stackoverflow_0001248812_perl_python_regex.txt |
Q:
Recursive? looping to n levels in Python
Working in python I want to extract a dataset with the following structure:
Each item has a unique ID and the unique ID of its parent. Each parent can have one or more children, each of which can have one or more children of its own, to n levels i.e. the data has an upturne... | Recursive? looping to n levels in Python | Working in python I want to extract a dataset with the following structure:
Each item has a unique ID and the unique ID of its parent. Each parent can have one or more children, each of which can have one or more children of its own, to n levels i.e. the data has an upturned tree-like structure. While it has the potent... | [
"Are you saying that each item only maintains a reference to its parents? If so, then how about\ndef getChildren(item) :\n children = []\n for possibleChild in allItems :\n if (possibleChild.parent == item) :\n children.extend(getChildren(possibleChild))\n return children\n\nThis returns ... | [
1,
1,
1,
0
] | [] | [] | [
"python",
"recursion"
] | stackoverflow_0001247133_python_recursion.txt |
Q:
Store data series in file or database if I want to do row level math operations?
I'm developing an app that handle sets of financial series data (input as csv or open document), one set could be say 10's x 1000's up to double precision numbers (Simplifying, but thats what matters).
I plan to do operations on that ... | Store data series in file or database if I want to do row level math operations? | I'm developing an app that handle sets of financial series data (input as csv or open document), one set could be say 10's x 1000's up to double precision numbers (Simplifying, but thats what matters).
I plan to do operations on that data (eg. sum, difference, averages etc.) as well including generation of say another ... | [
"\"I plan to do operations on that data (eg. sum, difference, averages etc.) as well including generation of say another column based on computations on the input.\"\nThis is the standard use case for a data warehouse star-schema design. Buy Kimball's The Data Warehouse Toolkit. Read (and understand) the star sch... | [
2,
1,
0,
0
] | [] | [] | [
"database",
"database_design",
"file_io",
"python"
] | stackoverflow_0001241758_database_database_design_file_io_python.txt |
Q:
Is the default configuration of re incorrect on macbooks? Or have I simply misunderstood something?
Python came pre-installed on my macbook and I have been slowly getting acquainted with the langauge. However, it seems that my configuration of the re library is incorrect, or I simply misunderstand something and t... | Is the default configuration of re incorrect on macbooks? Or have I simply misunderstood something? | Python came pre-installed on my macbook and I have been slowly getting acquainted with the langauge. However, it seems that my configuration of the re library is incorrect, or I simply misunderstand something and things are amiss. Whenever I run a python script with "import re", I recieve the following error:
Traceba... | [
"Pretty mysterious problem, given that line 4 in that file (and many other lines around that line number) is a comment (indeed the error msg itself shows that comment line!-) so even with the worst misconfiguration I'd be hard put to reproduce the problem as given.\nLet's try to simplify things and check how they m... | [
3
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0001249390_python_regex.txt |
Q:
Run Python script without opening Pythonwin
I have a python script which I can run from pythonwin on which I give the arguments.
Is it possible to automate this so that when I just click on the *.py file, I don't see the script and it asks for the path in a dos window?
A:
You're running on Windows, so you need... | Run Python script without opening Pythonwin | I have a python script which I can run from pythonwin on which I give the arguments.
Is it possible to automate this so that when I just click on the *.py file, I don't see the script and it asks for the path in a dos window?
| [
"You're running on Windows, so you need an association between .py files and some binary to run them. Have a look at this post.\nWhen you run \"assoc .py\", do you get Python.File? When you run \"ftype Python.File\", what do you get? If \"ftype Python.File\" points at some python.exe, your python script should run ... | [
4,
3,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0001245818_python.txt |
Q:
Is it safe to track trunk in Django?
I'm currently using Django 1.1 beta for some personal projects, and plan to start messing arround with the trunk to see the new stuff under the hood. But I might start using it on a professional basis, and I'd need to know if trunk is stable enough for using in production, or I... | Is it safe to track trunk in Django? | I'm currently using Django 1.1 beta for some personal projects, and plan to start messing arround with the trunk to see the new stuff under the hood. But I might start using it on a professional basis, and I'd need to know if trunk is stable enough for using in production, or I should stick to 1.0 for mission critical ... | [
"You probably shouldn't pull Django trunk every day, sometimes there are big commits that might break some things on your site. Also it depends what features you use, the new ones will of cause be a bit more buggy than older features. But all in all there shouldn't be a problem using trunk for production. You just ... | [
2,
1,
0,
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0001165631_django_python.txt |
Q:
How to write a setup.py for a program that depends on packages outside pypi
For instance, what if PIL, python-rsvg and libev3 are dependencies of the program? These dependencies are not in pypi index, the latter two are Debian package names.
A:
You could use setuptools. setuptools allows you to add any kind of P... | How to write a setup.py for a program that depends on packages outside pypi | For instance, what if PIL, python-rsvg and libev3 are dependencies of the program? These dependencies are not in pypi index, the latter two are Debian package names.
| [
"You could use setuptools. setuptools allows you to add any kind of Python installable (any distutils/setuptools enabled package) as a dependency, no matter if it is on PyPI or not.\nFor example, to depend on PIL 1.1.6, use something like:\nsetup(...,\n install_requires = [\"http://effbot.org/downloads/Imaging... | [
4,
2,
0,
0
] | [] | [] | [
"python",
"setuptools"
] | stackoverflow_0001244784_python_setuptools.txt |
Q:
`cat filename | grep -B 5 -C 5 foo`
for filename in os.listdir("."):
for line in open(filename).xreadlines():
if "foo" in line:
print line
So this is a simple python equivalent of cat filename | grep foo. However, I would like the equivalent of cat filename | grep -B 5 -C 5 foo, how should... | `cat filename | grep -B 5 -C 5 foo` | for filename in os.listdir("."):
for line in open(filename).xreadlines():
if "foo" in line:
print line
So this is a simple python equivalent of cat filename | grep foo. However, I would like the equivalent of cat filename | grep -B 5 -C 5 foo, how should the above code be modified?
| [
"Simplest way is:\nfor filename in os.listdir(\".\"):\n lines = open(filename).readlines()\n for i, line in enumerate(lines):\n if \"foo\" in line:\n for x in lines[i-5 : i+6]:\n print x,\n\nadd line numbers, breaks between blocks, etc, to taste;-).\nIn the extremely unlikely ... | [
7,
1
] | [] | [] | [
"grep",
"python"
] | stackoverflow_0001249412_grep_python.txt |
Q:
Convert Python exception information to string for logging
I try logging exceptions in Python 2.5, but I can't do it. All formatting functions do something else than what I want.
I came up with this:
def logexception(type, value, traceback):
print traceback.format_exception(type, value, traceback)
sys.excepthoo... | Convert Python exception information to string for logging | I try logging exceptions in Python 2.5, but I can't do it. All formatting functions do something else than what I want.
I came up with this:
def logexception(type, value, traceback):
print traceback.format_exception(type, value, traceback)
sys.excepthook = logexception
but it bails out with an argument error when c... | [
"Why should that traceback argument have a format_exception method just like the function in the traceback module whose name it's usurping, and if it had one why would that method require the same object on which it's called to be passed in as the last argument as well?\nI suspect you just want to give the third ar... | [
5
] | [
"you can use this very simpe logging solution\nor this one \n"
] | [
-1
] | [
"exception",
"python"
] | stackoverflow_0001249795_exception_python.txt |
Q:
Is there a string-collapse library function in python?
Is there a cross-platform library function that would collapse a multiline string into a single-line string with no repeating spaces?
I've come up with some snip below, but I wonder if there is a standard function which I could just import which is perhaps eve... | Is there a string-collapse library function in python? | Is there a cross-platform library function that would collapse a multiline string into a single-line string with no repeating spaces?
I've come up with some snip below, but I wonder if there is a standard function which I could just import which is perhaps even optimized in C?
def collapse(input):
import re
rn ... | [
"The built-in string.split() method will split on runs of whitespace, so you can use that and then join the resulting list using spaces, like this:\n' '.join(my_string.split())\n\nHere's a complete test script:\nTEST = \"\"\"This\nis a test\\twith a\n mix of\\ttabs, newlines and repeating\nwhitespace\"\... | [
12,
4,
0
] | [] | [] | [
"line_breaks",
"python",
"string"
] | stackoverflow_0001249786_line_breaks_python_string.txt |
Q:
Comparing persistent storage solutions in python
I'm starting on a new scientific project which has a lot of data (millions of entries) I'd like to store in an easily and quickly accessible format. I've come across a number of different potential options, but I'm not sure how to pick amongst them. My data can prob... | Comparing persistent storage solutions in python | I'm starting on a new scientific project which has a lot of data (millions of entries) I'd like to store in an easily and quickly accessible format. I've come across a number of different potential options, but I'm not sure how to pick amongst them. My data can probably just be stored as a dictionary, or potentially a ... | [
"Might want to give mongodb a shot - the PyMongo library works with dictionaries and supports most Python types. Easy to install, very performant + scalable. MongoDB (and PyMongo) is also used in production at some big names.\n",
"A RDBMS.\nNothing is more realiable than using tables on a well known RDBMS. Postgr... | [
13,
9,
5,
4,
3,
2,
1,
1,
1
] | [] | [] | [
"orm",
"persistence",
"python"
] | stackoverflow_0001235594_orm_persistence_python.txt |
Q:
If a python module says its dependent on debhelper and cdbs is there no way to get it to run on a nondebian linux?
I want to try python purple but I don't have debian. Is there a way to get it to run on either windows or a different linux?
A:
I suppose compiling from source (if availiable) or looking for dbhelpe... | If a python module says its dependent on debhelper and cdbs is there no way to get it to run on a nondebian linux? | I want to try python purple but I don't have debian. Is there a way to get it to run on either windows or a different linux?
| [
"I suppose compiling from source (if availiable) or looking for dbhelper and cbds install files for your distribution\n"
] | [
0
] | [] | [] | [
"cdbs",
"debian",
"linux",
"python"
] | stackoverflow_0001249873_cdbs_debian_linux_python.txt |
Q:
is it possible to get python purple running either in cygwin or on a linux that isn't debian?
python purple says it needs dbms and debhelper in order to run, but I don't run debian. Is there a way to get this running on a different linux? or in cygwin?
A:
Both cdbs and debhelper are only needed if you are trying... | is it possible to get python purple running either in cygwin or on a linux that isn't debian? | python purple says it needs dbms and debhelper in order to run, but I don't run debian. Is there a way to get this running on a different linux? or in cygwin?
| [
"Both cdbs and debhelper are only needed if you are trying to build a debian package. Just do a regular python setup.py build, and it should work fine (assuming you have the other prerequisites available).\n"
] | [
5
] | [] | [] | [
"cygwin",
"debhelper",
"linux",
"python"
] | stackoverflow_0001224726_cygwin_debhelper_linux_python.txt |
Q:
What is best way to remove duplicate lines matching regex from string using Python?
This is a pretty straight forward attempt. I haven't been using python for too long. Seems to work but I am sure I have much to learn. Someone let me know if I am way off here. Needs to find patterns, write the first line which mat... | What is best way to remove duplicate lines matching regex from string using Python? | This is a pretty straight forward attempt. I haven't been using python for too long. Seems to work but I am sure I have much to learn. Someone let me know if I am way off here. Needs to find patterns, write the first line which matches, and then add a summary message for remaining consecutive lines which match pattern ... | [
"The rematcher function seems to do what you want:\ndef rematcher(re_str, iterable):\n\n matcher= re.compile(re_str)\n in_match= 0\n for item in iterable:\n if matcher.match(item):\n if in_match == 0:\n yield item\n in_match+= 1\n else:\n if in_... | [
1,
1,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0000167923_python_regex.txt |
Q:
parsing XML file in python with cElementTree: dealing with errors and line number in the file
I am using the cElementTree library to parse XML files in Python.
Everything is working fine
But I would like to provide full error messages for the user when a value in the XML is not correct.
For example, let's suppose ... | parsing XML file in python with cElementTree: dealing with errors and line number in the file | I am using the cElementTree library to parse XML files in Python.
Everything is working fine
But I would like to provide full error messages for the user when a value in the XML is not correct.
For example, let's suppose I have the following XML:
<A name="xxxx" href="yyyy"/>
and want to tell the user if the href attri... | [
"The equivalent library that you should be using is lxml. lxml is a wrapper on very fast c libraries libxml2 and libxslt and is generally considered superior to the built in ones.\nIt, luckly, tries to keep to the element tree api and extend it in lxml.etree.\nlxml.etree has an attribute sourceline for all elements... | [
4
] | [] | [] | [
"celementtree",
"error_handling",
"line_numbers",
"python"
] | stackoverflow_0001250192_celementtree_error_handling_line_numbers_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.