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: Checking row and column for a word in python I am trying to create a checking program to see if the word is in a matrix horizontally or vertically. I have the code for checking the row, but would checking the column be similar to the row code? def checkRow(table, r, pos, word): for i in range(0, len(word)): ...
Checking row and column for a word in python
I am trying to create a checking program to see if the word is in a matrix horizontally or vertically. I have the code for checking the row, but would checking the column be similar to the row code? def checkRow(table, r, pos, word): for i in range(0, len(word)): if table[r][pos+i] != word[i]: r...
[ "Isn't it simple like this:\ndef checkCol(table, r, pos, word):\n for i in range(0, len(word)):\n if table[r+i][pos] != word[i]:\n return False\n return True\n\n", "import itertools\n\ndef checkRow(table, r, pos, word):\n return all(w==x for w, x in itertools.izip(word, table[r][pos:]))\n\n...
[ 4, 4, 2, 1 ]
[]
[]
[ "list", "matrix", "python" ]
stackoverflow_0001705933_list_matrix_python.txt
Q: Python if else condition error This is my code snippet, but it not execute the way that I want.The first if statement executes successfully if the input is a non-negative/character value, but if it is a negative value it ignores the elif statement. What's the issue.I'm using Python 2.6 from math import sqrt imp...
Python if else condition error
This is my code snippet, but it not execute the way that I want.The first if statement executes successfully if the input is a non-negative/character value, but if it is a negative value it ignores the elif statement. What's the issue.I'm using Python 2.6 from math import sqrt import cmath y = raw_input("Enter your ...
[ "The s.isdigit() string method means \"string s is one or more characters long and all characters are digits\", meaning each character one of 0123456789. Note how other characters such as + and - are signally absent from that set;-).\nYour elif y < 0: test is applied to a string y and therefore is nonsensical. If...
[ 5, 1, 0, 0 ]
[]
[]
[ "python", "syntax" ]
stackoverflow_0001706009_python_syntax.txt
Q: How might I handle development versions of Python packages without relying on SCM? One issue that comes up during Pinax development is dealing with development versions of external apps. I am trying to come up with a solution that doesn't involve bringing in the version control systems. Reason being I'd rather not...
How might I handle development versions of Python packages without relying on SCM?
One issue that comes up during Pinax development is dealing with development versions of external apps. I am trying to come up with a solution that doesn't involve bringing in the version control systems. Reason being I'd rather not have to install all the possible version control systems on my system (or force that up...
[ "Could you handle this using the \"==dev\" version specifier? If the distribution's page on PyPI includes a link to a .tgz of the current dev version (such as both github and bitbucket provide automatically) and you append \"#egg=project_name-dev\" to the link, both easy_install and pip will use that .tgz if ==dev ...
[ 3, 3, 1, 0 ]
[]
[]
[ "django", "external_dependencies", "packaging", "pinax", "python" ]
stackoverflow_0001705955_django_external_dependencies_packaging_pinax_python.txt
Q: Access violation on run function from dll I have DLL, interface on C++ for work with he. In bcb, msvc it works fine. I want to use Python-scripts to access function in this library. Generate python-package using Swig. File setup.py import distutils from distutils.core import setup, Extension setup(name = "DCM"...
Access violation on run function from dll
I have DLL, interface on C++ for work with he. In bcb, msvc it works fine. I want to use Python-scripts to access function in this library. Generate python-package using Swig. File setup.py import distutils from distutils.core import setup, Extension setup(name = "DCM", version = "1.3.2", ext_modules = [E...
[ "I find bug.\nIf you using DLL, you must write calling conventions in an explicit form like this:\nclass IRegistrationMessage\n{\npublic:\n...\n virtual int _cdecl GetLength() const = 0;\n virtual void _cdecl SetLength(int value) = 0;\n...\n};\n\nI append calling conventions and now all work fine.\n" ]
[ 0 ]
[]
[]
[ "c++", "python", "swig" ]
stackoverflow_0001631755_c++_python_swig.txt
Q: Useful Inheritance in Python resp. Alternative for interfaces Hi as far as I see in Python variables are untyped. So now I want to have a baseclass class baseClass: def x(): print "yay" and two subClasses class sub1(baseClass): def x(): print "sub1" class sub2(baseClass): def x(): print "sub2" in oth...
Useful Inheritance in Python resp. Alternative for interfaces
Hi as far as I see in Python variables are untyped. So now I want to have a baseclass class baseClass: def x(): print "yay" and two subClasses class sub1(baseClass): def x(): print "sub1" class sub2(baseClass): def x(): print "sub2" in other programming languages I can develop against interfaces just like...
[ "Yes.\nc = sub1()\nc = sub2()\n\nBut the base class and concept of defining an interface are unnecessary, since python is not statically typed.\nEDIT:\nTo rewrite your code in valid Python:\n# This space where baseClass was defined intentionally left blank, \n# because it serves no purpose\n\nclass Sub1(object):\n ...
[ 5, 2, 1 ]
[]
[]
[ "inheritance", "interface", "python" ]
stackoverflow_0001706167_inheritance_interface_python.txt
Q: Loading and saving numpy matrix I'm having troubles loading a numpy matrix. I successfully saved it to disk through: self.q.dump(fileName) and now I want to be able to load it. From what I understand, the load command should do the trick: self.q.load(fileName) but it seems not. Anyone knows what might be wrong? ...
Loading and saving numpy matrix
I'm having troubles loading a numpy matrix. I successfully saved it to disk through: self.q.dump(fileName) and now I want to be able to load it. From what I understand, the load command should do the trick: self.q.load(fileName) but it seems not. Anyone knows what might be wrong? Maybe the function is not called load...
[ "help(numpy.ndarray)\n\n | dump(...)\n | a.dump(file)\n | \n | Dump a pickle of the array to the specified file.\n | The array can be read back with pickle.load or numpy.load.\n | \n | Parameters\n | ----------\n | file : str\n | A string naming the dump file.\n\nnu...
[ 3 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0001706665_numpy_python.txt
Q: setting up virtualenv for django development on windows, Setting up a virtualenv for the first time, when i try to install MySQL-python using pip -E <<some virtual env>> install MySQL-python i get File "setup_windows.py", line 7, in get_config serverKey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, options['...
setting up virtualenv for django development on windows,
Setting up a virtualenv for the first time, when i try to install MySQL-python using pip -E <<some virtual env>> install MySQL-python i get File "setup_windows.py", line 7, in get_config serverKey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, options['registry_key']) WindowsError: [Error 2] The system cannot fin...
[ "site.cfg in the same dir as setup.py was looking for the wrong regsitry key, at the end of the file is \n# The Windows registry key for MySQL.\n# This has to be set for Windows builds to work.\n# Only change this if you have a different version.\nregistry_key = SOFTWARE\\MySQL AB\\MySQL Server 5.0\n\nI dipped into...
[ 5 ]
[]
[]
[ "django", "mysql", "python", "virtualenv", "windows" ]
stackoverflow_0001706989_django_mysql_python_virtualenv_windows.txt
Q: I want to use ZopeInterfaces, however my project is based on Python 3.x - any suggestions? Zope Interfaces are a great way to get some Java-style "design by contract" into a python program. It provides some great features such as implement-able interfaces and a really neat pattern for writing adaptors for objects....
I want to use ZopeInterfaces, however my project is based on Python 3.x - any suggestions?
Zope Interfaces are a great way to get some Java-style "design by contract" into a python program. It provides some great features such as implement-able interfaces and a really neat pattern for writing adaptors for objects. Unfortunately, since it's part of a very mature platform which runs just fine on Python 2.x th...
[ "There appears to be a Python 3 branch of Zope Interfaces here and announced here.\n", "Use python 2.x. It is more supported by most libraries. It has many 3.x features plus all 3rd party libraries. Later when dependencies are available you can migrate to py3 using 2to3.\n" ]
[ 2, 0 ]
[]
[]
[ "python", "zope.interface" ]
stackoverflow_0001704589_python_zope.interface.txt
Q: How to disable the OptionParser default help view? I am using the OptionParser from optparse module to parse my command that I get using the raw_input(). When I give a -h it displays the help screen and exits my application. I dont want it to display the help screen or exit the application. How can this be accompl...
How to disable the OptionParser default help view?
I am using the OptionParser from optparse module to parse my command that I get using the raw_input(). When I give a -h it displays the help screen and exits my application. I dont want it to display the help screen or exit the application. How can this be accomplished? Thanx in advance.
[ "optparse has a strange penchange for exiting your program, which I think is really unfortunate. You can initialize it like this to prevent it:\noparser = OptionParser(add_help_option=False, ...)\n\nNote that now you have to handle the -h and --help options yourself. You can print the help message formatted by Op...
[ 8, 7 ]
[]
[]
[ "python" ]
stackoverflow_0001707380_python.txt
Q: Use a Descriptor (EDIT: Not a single decorator) for multiple attributes? Python 2.5.4. Fairly new to Python, brand new to decorators as of last night. If I have a class with multiple boolean attributes: class Foo(object): _bool1 = True _bool2 = True _bool3 = True #et cetera def __init__(): ...
Use a Descriptor (EDIT: Not a single decorator) for multiple attributes?
Python 2.5.4. Fairly new to Python, brand new to decorators as of last night. If I have a class with multiple boolean attributes: class Foo(object): _bool1 = True _bool2 = True _bool3 = True #et cetera def __init__(): self._bool1 = True self._bool2 = False self._bool3 = True...
[ "You can try using a descriptor:\nclass BooleanDescriptor(object):\n def __init__(self, attr):\n self.attr = attr\n\n def __get__(self, instance, owner):\n return getattr(instance, self.attr)\n\n def __set__(self, instance, value):\n if value in (True, False):\n return setattr(insta...
[ 3, 2 ]
[]
[]
[ "decorator", "descriptor", "python" ]
stackoverflow_0001708349_decorator_descriptor_python.txt
Q: convert decimal to hex python Im building a server in python, i need to convert a decimal value to hex like this : let's say the packet start by 4 bytes which define the packet lenght : 00 00 00 00 if the len(packet) = 255 we would send : 00 00 00 ff Now my problem is that sometimes the packet is bigger than 256 a...
convert decimal to hex python
Im building a server in python, i need to convert a decimal value to hex like this : let's say the packet start by 4 bytes which define the packet lenght : 00 00 00 00 if the len(packet) = 255 we would send : 00 00 00 ff Now my problem is that sometimes the packet is bigger than 256 as for example 336, then it would be...
[ ">>> import struct\n>>> struct.pack(\">i\", 336)\n'\\x00\\x00\\x01P'\n\nThe struct module packs and unpacks python values into bytes. The \">i\" format means big-endian 4-byte integer.\n", "What about\n\"%0.8x\" % data\n\nSample:\n>>> print \"%0.8x\" % 366\n0000016e\n\n>>> print \"%0.8x\" % 336\n00000150\n\n" ]
[ 8, 3 ]
[]
[]
[ "decimal", "hex", "networking", "python" ]
stackoverflow_0001708598_decimal_hex_networking_python.txt
Q: Combining two record arrays I have two Numpy record arrays that have exactly the same fields. What is the easiest way to combine them into one (i.e. append one table on to the other)? A: Use numpy.hstack(): >>> import numpy >>> desc = {'names': ('gender','age','weight'), 'formats': ('S1', 'f4', 'f4')} >>> a = n...
Combining two record arrays
I have two Numpy record arrays that have exactly the same fields. What is the easiest way to combine them into one (i.e. append one table on to the other)?
[ "Use numpy.hstack():\n>>> import numpy\n>>> desc = {'names': ('gender','age','weight'), 'formats': ('S1', 'f4', 'f4')} \n>>> a = numpy.array([('M',64.0,75.0),('F',25.0,60.0)], dtype=desc)\n>>> numpy.hstack((a,a))\narray([('M', 64.0, 75.0), ('F', 25.0, 60.0), ('M', 64.0, 75.0),\n ('F', 25.0, 60.0)], \n dt...
[ 7, 0, 0 ]
[]
[]
[ "numpy", "python", "recarray" ]
stackoverflow_0001708775_numpy_python_recarray.txt
Q: Python/Django Model overriding the cleaned data Hello I am currently working on a django project, in one of my Models I have a file upload and image upload, with the parameters of these two fields both are set to blank=True, however there is a stipulatation with this and it is that field can only be blank if one o...
Python/Django Model overriding the cleaned data
Hello I am currently working on a django project, in one of my Models I have a file upload and image upload, with the parameters of these two fields both are set to blank=True, however there is a stipulatation with this and it is that field can only be blank if one of the two is not, so for example, if the imagefield i...
[ "You just need to define a custom clean() method on the ModelForm that checks if one or both of the fields is populated.\ndef clean(self):\n file_field = self.cleaned_data.get('file_field')\n image_field = self.cleaned_data.get('image_field')\n\n if file_field and image_field:\n raise forms.Validati...
[ 4 ]
[]
[]
[ "django", "django_forms", "django_models", "model_view_controller", "python" ]
stackoverflow_0001708780_django_django_forms_django_models_model_view_controller_python.txt
Q: What does 'u' mean in a list? This is the first time I've came across this. Just printed a list and each element seems to have a u in front of it i.e. [u'hello', u'hi', u'hey'] What does it mean and why would a list have this in front of each element? As I don't know how common this is, if you'd like to s...
What does 'u' mean in a list?
This is the first time I've came across this. Just printed a list and each element seems to have a u in front of it i.e. [u'hello', u'hi', u'hey'] What does it mean and why would a list have this in front of each element? As I don't know how common this is, if you'd like to see how I came across it, I'll happi...
[ "it's an indication of unicode string. similar to r'' for raw string.\n>>> type(u'abc')\n<type 'unicode'>\n>>> r'ab\\c'\n'ab\\\\c'\n\n", "Unicode.\n", "The u just means that the following string is a unicode string (as opposed to a plain ascii string). It has nothing to do with the list that happens to contain ...
[ 47, 11, 9, 4 ]
[]
[]
[ "python", "string", "unicode" ]
stackoverflow_0001709110_python_string_unicode.txt
Q: Python OCR library or handwritten character recognition engine Could you recommend some python libraries or source code for OCR and handwritten character recognition? A: Have you tried pytesser?
Python OCR library or handwritten character recognition engine
Could you recommend some python libraries or source code for OCR and handwritten character recognition?
[ "Have you tried pytesser?\n" ]
[ 11 ]
[]
[]
[ "image_recognition", "ocr", "python" ]
stackoverflow_0001708779_image_recognition_ocr_python.txt
Q: python/scons help: maintaining lists of source files + object files I know next to nothing about Python and I'm using scons. (if you're reading this and know Python but not scons, you can probably help me!) Could someone help me out and explain how I could have a variable that contains two lists? I'm not sure of t...
python/scons help: maintaining lists of source files + object files
I know next to nothing about Python and I'm using scons. (if you're reading this and know Python but not scons, you can probably help me!) Could someone help me out and explain how I could have a variable that contains two lists? I'm not sure of the syntax. Is this right? buildinfo = // how do you initialize a variable...
[ "How about something like this:\nclass BuildInfo(object):\n def __init__(self, objectFiles = [], sourceFiles = []):\n self.objectFiles = objectFiles\n self.sourceFiles = sourceFiles \n def append(self, build_info):\n self.objectFiles.extend(build_info.objectFiles)\n self.sourceFile...
[ 2, 1, 1, 0 ]
[]
[]
[ "python", "scons" ]
stackoverflow_0001708789_python_scons.txt
Q: Class Objects and comparing specific attributes I have the following code. class person(object): def __init__(self, keys): for item in keys: setattr(self, item, None) def __str__(self): return str(self.__dict__) def __eq__(self, other) : return self.__dict...
Class Objects and comparing specific attributes
I have the following code. class person(object): def __init__(self, keys): for item in keys: setattr(self, item, None) def __str__(self): return str(self.__dict__) def __eq__(self, other) : return self.__dict__ == other.__dict__ Now I want to take this code an...
[ "There are minor enhancements (bug fixes) I'd definitely do.\nIn particular, getattr called with two arguments raises an ArgumentError if the attribute's not present, so you could get that exception if you were comparing two instances with different keys. You could just call it with three args instead (the third o...
[ 2, 1 ]
[]
[]
[ "coding_style", "python" ]
stackoverflow_0001708878_coding_style_python.txt
Q: getting started with django-cms: error on page_submit_row I am getting started with django-cms and I am facing an exception when I try to edit a page in the admin inteface. A TemplateSyntaxError exception is raised due to the {% page_submit_row %} templatetag. TemplateSyntaxError at /admin/cms/page/1/ Caught an...
getting started with django-cms: error on page_submit_row
I am getting started with django-cms and I am facing an exception when I try to edit a page in the admin inteface. A TemplateSyntaxError exception is raised due to the {% page_submit_row %} templatetag. TemplateSyntaxError at /admin/cms/page/1/ Caught an exception while rendering: admin/page_submit_line.html Reques...
[ "You may need to {% load %} the template tag library at the top of your file.\n", "It seems that the problem comes from the django-cms installer. It was with RC2 and RC3 is out now.\nMoreover, It is recommended to use easy_install for the installation\neasy_instaling RC3 fixed the problem\nBest\n" ]
[ 0, 0 ]
[]
[]
[ "django", "django_cms", "python" ]
stackoverflow_0001709201_django_django_cms_python.txt
Q: Is there code out there to subclass set in Python for big xranges? I'm trying to write some Python code that includes union/intersection of sets that potentially can be very large. Much of the time, these sets will be essentially set(xrange(1<<32)) or something of the kind, but often there will be ranges of values...
Is there code out there to subclass set in Python for big xranges?
I'm trying to write some Python code that includes union/intersection of sets that potentially can be very large. Much of the time, these sets will be essentially set(xrange(1<<32)) or something of the kind, but often there will be ranges of values that do not belong in the set (say, 'bit 5 cannot be clear'), or extra ...
[ "You say:\n\nFor the most part, the set contents can be expressed algorithmically.\n\nHow about writing a class which presents the entire set API, but determines set inclusion algorithmically. Then with a number of classes which wrap around other sets to perform the union and intersection algorithmically.\nFor exam...
[ 3, 1, 0, 0, 0 ]
[]
[]
[ "python", "set" ]
stackoverflow_0001708392_python_set.txt
Q: Python __str__: Magic Console Suppose one decided (yes, this is horrible) to create handle input in the following manner: A user types in a command on the python console after importing your class, the command is actually a class name, the class name's __str__ function is actually a function with side effects (e.g...
Python __str__: Magic Console
Suppose one decided (yes, this is horrible) to create handle input in the following manner: A user types in a command on the python console after importing your class, the command is actually a class name, the class name's __str__ function is actually a function with side effects (e.g. the command is "north" and the fu...
[ "What you are looking for is the metaclass\nclass Magic(type):\n def __str__(self):\n return 'Something crazy'\n def __repr__(self):\n return 'Another craziness'\n\nclass Foo(object):\n __metaclass__ = Magic\n\n>>> print Foo\nSomething crazy\n>>> Foo\nAnother craziness\n\n", "in console you...
[ 5, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001709845_python.txt
Q: How can I sort a coordinate list for a rectangle counterclockwise? I need to sort a coordinate list for a rectangle counterclockwise, and make the north-east corner the first coordinate. These are geographic coordinates (i.e. Longitude, Latitude) in decimal form.1 For example, here are the 4 corners of a rectangle...
How can I sort a coordinate list for a rectangle counterclockwise?
I need to sort a coordinate list for a rectangle counterclockwise, and make the north-east corner the first coordinate. These are geographic coordinates (i.e. Longitude, Latitude) in decimal form.1 For example, here are the 4 corners of a rectangle, starting with the north-west corner and moving clockwise: [ { "lat":...
[ "solution seems pretty straightforward:\n>>> import math\n>>> mlat = sum(x['lat'] for x in l) / len(l)\n>>> mlng = sum(x['lng'] for x in l) / len(l)\n>>> def algo(x):\n return (math.atan2(x['lat'] - mlat, x['lng'] - mlng) + 2 * math.pi) % (2*math.pi)\n\n>>> l.sort(key=algo)\n\nbasically, algo normalises the inpu...
[ 11, 5, 3, 3, 1, 1, 0 ]
[]
[]
[ "algorithm", "coordinates", "geospatial", "python", "sorting" ]
stackoverflow_0001709283_algorithm_coordinates_geospatial_python_sorting.txt
Q: Making sense of Python I am reading the book Programming Collective Intelligence, What exactly the following piece of python code do? # Add up the squares of all the differences sum_of_squares=sum([pow(prefs[person1][item]-prefs[person2][item],2) for item in prefs[person1] if item in pr...
Making sense of Python
I am reading the book Programming Collective Intelligence, What exactly the following piece of python code do? # Add up the squares of all the differences sum_of_squares=sum([pow(prefs[person1][item]-prefs[person2][item],2) for item in prefs[person1] if item in prefs[person2]]) I am trying...
[ "First it constructs a list containing the results from:\nfor each item in prefs for person1:\n if that is also an item in the prefs for person2:\n find the difference between the number of prefs for that item for the two people\n and square it (Math.pow(x,2) is \"x squared\")\n\nThen it adds those...
[ 6, 2, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001708064_python.txt
Q: How does wrapping an unsafe python method (e.g os.chdir) in a class make it thread/exception safe? In the question How do I "cd" in python, the accepted answer recommended wrapping the os.chdir call in a class to make the return to your original dir exception safe. Here was the recommended code: class Chdir: ...
How does wrapping an unsafe python method (e.g os.chdir) in a class make it thread/exception safe?
In the question How do I "cd" in python, the accepted answer recommended wrapping the os.chdir call in a class to make the return to your original dir exception safe. Here was the recommended code: class Chdir: def __init__( self, newPath ): self.savedPath = os.getcwd() os.chdir(newPath) def __d...
[ "Thread safety and exception safety are not really the same thing at all. Wrapping the os.chdir call in a class like this is an attempt to make it exception safe not thread safe.\nException safety is something you'll frequently hear C++ developers talk about. It isn't talked about nearly as much in the Python commu...
[ 8, 5, 1 ]
[ "This code alone is neither thread-safe nor exception-safe. Actually I'm not really sure what you mean by exception-safe. Following code comes to mind:\ntry:\n # something thrilling\nexcept:\n pass\n\nAnd this is a terrible idea. Exceptions are not for guarding against. Well written code should catch exceptio...
[ -2 ]
[ "exception_handling", "python" ]
stackoverflow_0001709770_exception_handling_python.txt
Q: How do I profile `paster serve`'s startup time? Python's paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I would like it to not fork a thread pool and quit as soon as it is read...
How do I profile `paster serve`'s startup time?
Python's paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I would like it to not fork a thread pool and quit as soon as it is ready to serve so the time after it's ready doesn't show ...
[ "In general your methodology could be to do timing blocks around the sections of code and then issue logging statements. As far as the shutdown after init, I'm not familiar with the specifics of what you're using. \nEdit: I've used this middleware to help me find performance sinkholes. It's currently a werkzeug ...
[ 1, 1, 1 ]
[]
[]
[ "paster", "performance", "profiling", "python" ]
stackoverflow_0001702024_paster_performance_profiling_python.txt
Q: What is the difference between converting to hex on the client end and using rawtohex? I have a table that's created like this: CREATE TABLE bin_test (id INTEGER PRIMARY KEY, b BLOB) Using Python and cx_Oracle, if I do this: value = "\xff\x00\xff\x00" #The string represented in hex by ff00ff00 self.connection.exe...
What is the difference between converting to hex on the client end and using rawtohex?
I have a table that's created like this: CREATE TABLE bin_test (id INTEGER PRIMARY KEY, b BLOB) Using Python and cx_Oracle, if I do this: value = "\xff\x00\xff\x00" #The string represented in hex by ff00ff00 self.connection.execute("INSERT INTO bin_test (b) VALUES (rawtohex(?))", (value,)) self...
[ "RAWTOHEX in Oracle is bit order insensitive, while on your machine it's of course sensitive.\nAlso note that an argument to RAWTOHEX() can be implicitly converted to VARCHAR2 by your library (i. e. transmitted as SQLT_STR), which makes it also encoding and collation sensitive.\n", "rawtohex() is for converting O...
[ 1, 1, 0 ]
[]
[]
[ "blob", "cx_oracle", "oracle", "oracle10g", "python" ]
stackoverflow_0001034068_blob_cx_oracle_oracle_oracle10g_python.txt
Q: Using QFrame to display different panes of information? I'm trying to get a QFrame to serve as a "display area" for a couple different kinds of information, eg: you click on something in a list view and an info pane shows up in the frame to give you information about it, you click on a different item and a differ...
Using QFrame to display different panes of information?
I'm trying to get a QFrame to serve as a "display area" for a couple different kinds of information, eg: you click on something in a list view and an info pane shows up in the frame to give you information about it, you click on a different item and a different pane shows up. Having trouble swapping the different fram...
[ "Using QStackedWidget is probably the most standard solution.\n" ]
[ 2 ]
[]
[]
[ "pyqt", "python", "qt" ]
stackoverflow_0001710274_pyqt_python_qt.txt
Q: Pygame and blitting: white on white = gray? I'm using pygame (1.9.0rc3, though this also happens in 1.8.1) to create a heatmap. To build the heatmap, I use a small, 24-bit 11x11px dot PNG image with a white background and a very low-opacity grey dot that stops exactly at the edges: Dot image http://img442.imagesha...
Pygame and blitting: white on white = gray?
I'm using pygame (1.9.0rc3, though this also happens in 1.8.1) to create a heatmap. To build the heatmap, I use a small, 24-bit 11x11px dot PNG image with a white background and a very low-opacity grey dot that stops exactly at the edges: Dot image http://img442.imageshack.us/img442/465/dot.png The area around the dot ...
[ "After trying around, the only thing I could see was that you're 100% right. Multiplication by 255 results in a subtraction of 1 -- every time. In the end, I downloaded the pygame source code, and the answer is right there, in surface.h:\n#define BLEND_MULT(sR, sG, sB, sA, dR, dG, dB, dA) \\\n dR = (dR && sR) ? ...
[ 6, 1 ]
[]
[]
[ "image", "imaging", "pygame", "python" ]
stackoverflow_0001157385_image_imaging_pygame_python.txt
Q: Python 2.6 on Debian Lenny. Where should the executable go? I am building python2.6 from source on Debian Lenny. ( ./configure make make altinstall ) I don't want it to conflict with anything existing, but I want it to be in the default search path for bash. Suggestions? (ps, I'm using a vm, so I can trash it an...
Python 2.6 on Debian Lenny. Where should the executable go?
I am building python2.6 from source on Debian Lenny. ( ./configure make make altinstall ) I don't want it to conflict with anything existing, but I want it to be in the default search path for bash. Suggestions? (ps, I'm using a vm, so I can trash it and rebuild.)
[ "That's the purpose of /usr/local according to the FHS.\n\nThe /usr/local hierarchy is for use by the system administrator when installing software locally.\n\nI think configure typically defaults to /usr/local unless told otherwise, but to be sure you could run ./configure --prefix=/usr/local ....\n", "I strongl...
[ 9, 3, 2, 0 ]
[]
[]
[ "debian", "linux", "python" ]
stackoverflow_0001711200_debian_linux_python.txt
Q: Komodo - watch variables and execute code while on pause in the program With c# in the Visual Studio IDE I can pause at anytime a program and watch its variables, inspect whatever I want. I noticed that with the Komodo IDE when something crashes and it stops the flow of the program, I can do exactly the same. But ...
Komodo - watch variables and execute code while on pause in the program
With c# in the Visual Studio IDE I can pause at anytime a program and watch its variables, inspect whatever I want. I noticed that with the Komodo IDE when something crashes and it stops the flow of the program, I can do exactly the same. But for some reason, it seems that when I try to do the same when I manually paus...
[ "If you put \nimport code\ncode.interact(local=locals())\n\nin your program, then you will be dumped to a python interpreter. (See Method to peek at a Python program running right now)\nThis is a little different than pausing Komodo, but perhaps you can use it to achieve the same goal.\nPressing Ctrl-d exits the py...
[ 3 ]
[]
[]
[ "komodo", "komodoedit", "python" ]
stackoverflow_0001711193_komodo_komodoedit_python.txt
Q: wxPython won't close Frame with a parent who is a window handle I have a program in Python that gets a window handle via COM from another program (think of the Python program as an addin) I set this window to be the main Python frame's parent so that if the other program minimizes, the python frame will too. The ...
wxPython won't close Frame with a parent who is a window handle
I have a program in Python that gets a window handle via COM from another program (think of the Python program as an addin) I set this window to be the main Python frame's parent so that if the other program minimizes, the python frame will too. The problem is when I go to exit, and try to close or destroy the main fr...
[ "I wonder if your Close call may be hanging in the close-handler. Have you tried calling Destroy instead? If that doesn't help, then the only solution would seem to be \"reparenting\" or \"detaching\" your frame -- I don't see a way to do that in wx, but maybe you could drop down to win32 API for that one task...?...
[ 1, 0, 0 ]
[]
[]
[ "handle", "python", "windows", "wxpython" ]
stackoverflow_0000941470_handle_python_windows_wxpython.txt
Q: Python web hosting: Why are server restarts necessary? We currently run a small shared hosting service for a couple of hundred small PHP sites on our servers. We'd like to offer Python support too, but from our initial research at least, a server restart seems to be required after each source code change. Is this...
Python web hosting: Why are server restarts necessary?
We currently run a small shared hosting service for a couple of hundred small PHP sites on our servers. We'd like to offer Python support too, but from our initial research at least, a server restart seems to be required after each source code change. Is this really the case? If so, we're just not going to be able to...
[ "Python is a compiled language; the compiled byte code is cached by the Python process for later use, to improve performance. PHP, by default, is interpreted. It's a tradeoff between usability and speed.\nIf you're using a standard WSGI module, such as Apache's mod_wsgi, then you don't have to restart the server --...
[ 7, 4, 3 ]
[]
[]
[ "python", "web_hosting" ]
stackoverflow_0001711483_python_web_hosting.txt
Q: How do I get the value of a property corresponding to a SQLAlchemy InstrumentedAttribute? Given a SQLAlchemy mapped class Table and an instance of that class t, how do I get the value of t.colname corresponding to the sqlalchemy.org.attributes.InstrumentedAttribute instance Table.colname? What if I need to ask the...
How do I get the value of a property corresponding to a SQLAlchemy InstrumentedAttribute?
Given a SQLAlchemy mapped class Table and an instance of that class t, how do I get the value of t.colname corresponding to the sqlalchemy.org.attributes.InstrumentedAttribute instance Table.colname? What if I need to ask the same question with a Column instead of an InstrumentedAttribute? Given a list of columns in an...
[ "To get an objects attribute value corresponding to an InstrumentedAttribute it should be enough to just get the key of the attribute from it's ColumnProperty and fetch it from the object:\nt.colname == getattr(t, Table.colname.property.key)\n\nIf you have a Column it can get a bit more complicated because the prop...
[ 7 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0001709895_python_sqlalchemy.txt
Q: Accessing a matrix element by matrix[(a, b), c] instead of matrix[a, b, c] I want to achieve the following: Have a AxBxC matrix (where A,B,C are integers). Access that matrix not as matrix[a, b, c] but as matrix[(a, b), c], this is, I have two variables, var1 = (x, y) and var2 = z and want access my matrix as mat...
Accessing a matrix element by matrix[(a, b), c] instead of matrix[a, b, c]
I want to achieve the following: Have a AxBxC matrix (where A,B,C are integers). Access that matrix not as matrix[a, b, c] but as matrix[(a, b), c], this is, I have two variables, var1 = (x, y) and var2 = z and want access my matrix as matrix[var1, var2]. How can this be done? I am using numpy matrix, if it makes any...
[ "If var1 = (x,y), and var2 = z, you can use\nmatrix[var1][var2]\n\n", "I think you can simply subclass the NumPy matrix type, with a new class of your own; and overload the __getitem__() nethod to accept a tuple. Something like this:\nclass SpecialMatrix(np.matrix):\n def __getitem__(self, arg1, arg2, arg3=No...
[ 3, 1 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0001711865_numpy_python.txt
Q: Does anyone have examples of integrating Haystack/Solr with Django? Note: This question originally applied to Xapian, but due to cross-platform issues and poor understanding of Xapian I (our team) chose Solr instead. I'm looking for snippets, tricks, tips, links, and anything to watch out for (gotchas). My technol...
Does anyone have examples of integrating Haystack/Solr with Django?
Note: This question originally applied to Xapian, but due to cross-platform issues and poor understanding of Xapian I (our team) chose Solr instead. I'm looking for snippets, tricks, tips, links, and anything to watch out for (gotchas). My technology stack includes: MySQL 5.1 (Not really pertinent) Red Hat and Windows...
[ "A few notes and resources. My advice is mostly related to Haystack in general since I don't have experience with Xapian as a backend.\n\nInstalling Xapian (from the Haystack\ndocs) - note that Haystack doesn't\nsupport Xapian on its own:\nhttp://haystacksearch.org/docs/installing_search_engines.html#xapian\nIt may...
[ 4 ]
[]
[]
[ "django", "django_haystack", "python", "solr" ]
stackoverflow_0001708915_django_django_haystack_python_solr.txt
Q: How do I copy local Google App Engine Python datastore to local Google App Engine Java datastore? I have around 4000 entities that I need to insert into a Java App Engine datastore. As I understand it, only the Python version of App Engine currently has tools to upload data from a CSV file to a datastore. So, wh...
How do I copy local Google App Engine Python datastore to local Google App Engine Java datastore?
I have around 4000 entities that I need to insert into a Java App Engine datastore. As I understand it, only the Python version of App Engine currently has tools to upload data from a CSV file to a datastore. So, what I have done thus far is follow the instructions at http://code.google.com/appengine/docs/python/tool...
[ "The Python and Java local datastore files are not compatible. You can't move directly from one to the other. remote_api support is forthcoming for Java, but until then, you will have to implement your own data loading for the local Java datastore (you can still use the Python loader for the production server).\n",...
[ 3, 1 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "java", "local", "python" ]
stackoverflow_0001685810_google_app_engine_google_cloud_datastore_java_local_python.txt
Q: Custom distutils commands I have a library called "example" that I'm installing into my global site-packages directory. However, I'd like to be able to install two versions, one for production and one for testing (I have a web application and other things that are versioned this way). Is there a way to specify, s...
Custom distutils commands
I have a library called "example" that I'm installing into my global site-packages directory. However, I'd like to be able to install two versions, one for production and one for testing (I have a web application and other things that are versioned this way). Is there a way to specify, say "python setup.py stage" that...
[ "This can easily be done with distutils by subclassing distutils.core.Command inside of setup.py.\nFor example:\nfrom distutils.core import setup, Command\nimport os, sys\n\nclass CleanCommand(Command):\n description = \"custom clean command that forcefully removes dist/build directories\"\n user_options = []...
[ 56, 14, 5, 2 ]
[]
[]
[ "deployment", "distutils", "python" ]
stackoverflow_0001710839_deployment_distutils_python.txt
Q: Making a multi-table inheritance design generic in Django First of all, some links to pages I've used for reference: A SO question, and the Django docs on generic relations and multi-table inheritance. So far, I have a multi-table inheritance design set up. Objects (e.g: Car, Dog, Computer) can inherit an Item cla...
Making a multi-table inheritance design generic in Django
First of all, some links to pages I've used for reference: A SO question, and the Django docs on generic relations and multi-table inheritance. So far, I have a multi-table inheritance design set up. Objects (e.g: Car, Dog, Computer) can inherit an Item class. I need to be able to retrieve Items from the DB, get the su...
[ "I have done something similar to method 2 in one of my projects:\nfrom django.db import models\nfrom django.contrib.contenttypes.models import ContentType\n\nclass BaseModel(models.Model):\n type = models.ForeignKey(ContentType,editable=False)\n # other base fields here\n\n def save(self,force_insert=Fals...
[ 5, 1 ]
[]
[]
[ "django", "inheritance", "python" ]
stackoverflow_0001712683_django_inheritance_python.txt
Q: Python JSON RPC server with ability to stream I have come across several guides and packages on implementing a python JSON RPC server, e.g.: http://json-rpc.org/wiki/python-json-rpc http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/552751 http://pythonpaste.org/webob/jsonrpc-example.html They all do a good...
Python JSON RPC server with ability to stream
I have come across several guides and packages on implementing a python JSON RPC server, e.g.: http://json-rpc.org/wiki/python-json-rpc http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/552751 http://pythonpaste.org/webob/jsonrpc-example.html They all do a good job in the sense that the server/application imple...
[ "if the typical JSON-RPC frameworks doesn't allow you to dump such huge data effectively, why not just use a HTTP server and return json data, that way you can stream and read streamed data, good thing is you may even gzip it for faster transfer, and you will be able to use many standard servers too e.g. apache .\n...
[ 2 ]
[]
[]
[ "json", "python", "rpc" ]
stackoverflow_0001712249_json_python_rpc.txt
Q: Pylons deployment questions I'm a beginner with Pylons and I've mostly developed on my localhost using the built-in web server. I think it's time to start deployment for my personal blog, I have a Debian Lenny server with apache2-mpm-prefork module and mod_wsgi - I've never really used mod_wsgi or fastcgi and I he...
Pylons deployment questions
I'm a beginner with Pylons and I've mostly developed on my localhost using the built-in web server. I think it's time to start deployment for my personal blog, I have a Debian Lenny server with apache2-mpm-prefork module and mod_wsgi - I've never really used mod_wsgi or fastcgi and I hear either of these are the way to...
[ "\nmod_wsgi. It's more efficient. FastCGI can be troublesome to setup, whereas I've never known anyone to have a problem using mod_wsgi with a supported version of Python (2.5, 2.6, 3.1 included). WSGI exists for Python (by Python, &c.) and so it makes for a more \"Pythonic\" experience. Prior to WSGI I used to...
[ 2 ]
[]
[]
[ "apache", "apache2", "deployment", "pylons", "python" ]
stackoverflow_0001712883_apache_apache2_deployment_pylons_python.txt
Q: ImportError: No module named etree.ElementTree when running Yahoo BOSS for the first time I installed Yahoo BOSS (it's a Python installation that allows you to use their search features). I followed everything perfectly. However, when I run the example to confirm that it works, I get this: $ python ex3.py Tracebac...
ImportError: No module named etree.ElementTree when running Yahoo BOSS for the first time
I installed Yahoo BOSS (it's a Python installation that allows you to use their search features). I followed everything perfectly. However, when I run the example to confirm that it works, I get this: $ python ex3.py Traceback (most recent call last): File "ex3.py", line 16, in ? from yos.yql import db File "/u...
[ "Use Python 2.5 or above: xml.etree.ElementTree was added in 2.5.\nhttp://docs.python.org/library/xml.etree.elementtree.html\n", "A google search reveals that you need to install the effbot elementtree Python module.\n" ]
[ 3, 0 ]
[]
[]
[ "python", "python_2.4", "yahoo_boss_api" ]
stackoverflow_0001713015_python_python_2.4_yahoo_boss_api.txt
Q: Python, Asyncore and forks Just for starters, I used Twisted and SocketServer with both ForkMixIn, ThreadMixIn and tried the "thread-pool" recepies. However, I wanted to make something particular work in Python. Alittle background. Previously I wrote in C a simple TCP deamon that would bind to a socket and listen ...
Python, Asyncore and forks
Just for starters, I used Twisted and SocketServer with both ForkMixIn, ThreadMixIn and tried the "thread-pool" recepies. However, I wanted to make something particular work in Python. Alittle background. Previously I wrote in C a simple TCP deamon that would bind to a socket and listen on it, then pre-fork X many time...
[ "You should use code markup for traceback, otherwise it's displayed messed and we don't see exception type. \nBut I believe it's TypeError: 'NoneType' object is not iterable since self.accept() can return None. The reason is that several processes can get read event for listening socket, but only one can accept it....
[ 2 ]
[]
[]
[ "asyncore", "python", "sockets", "twisted" ]
stackoverflow_0001713078_asyncore_python_sockets_twisted.txt
Q: how to split a string matching a pattern in python I have string looking like this: 'Toy Story..(II) (1995)' I want to split the line into two parts like this: ['Toy Story..(II)','1995'] How can I do it? Thanks. A: This code will get you started: 'Toy Stroy..(II) (1995)'.rstrip(')').rsplit('(',1) Other than t...
how to split a string matching a pattern in python
I have string looking like this: 'Toy Story..(II) (1995)' I want to split the line into two parts like this: ['Toy Story..(II)','1995'] How can I do it? Thanks.
[ "This code will get you started:\n'Toy Stroy..(II) (1995)'.rstrip(')').rsplit('(',1)\n\nOther than that, you can use r'\\s*[(]\\d{4}[)]\\s*$' to match a four-digit number in parentheses at the end of the string. If you find it, you can chop it off:\ns = ''\nl = [s]\nmatch = re.compile(r'\\s*[(]\\d+[)]\\s*$').search...
[ 4, 1, 0, 0 ]
[]
[]
[ "python", "split", "string" ]
stackoverflow_0001713876_python_split_string.txt
Q: Mac OS X app/service and stdin? I'm debugging a service I'm developing, which basically will open my .app and pass it some data to stdin. But it doesn't seem like it's possible to something like: open -a myapp.app < foo_in.txt Is it possible to pass stuff to an .app's stdin at all? Edit: Sorry, I should have post...
Mac OS X app/service and stdin?
I'm debugging a service I'm developing, which basically will open my .app and pass it some data to stdin. But it doesn't seem like it's possible to something like: open -a myapp.app < foo_in.txt Is it possible to pass stuff to an .app's stdin at all? Edit: Sorry, I should have posted this on SO and been more clear. Wh...
[ "What do you mean with using it as a service?\nThe example you show won't work, the open command calls LaunchServices to launch the application, and there is no place in the LaunchServices API to pass stdin data or similar to the application.\nIf you mean adding an item to the OS X Services Menu, you should look at...
[ 1, 0, 0, 0, 0 ]
[]
[]
[ "macos", "py2app", "python", "service" ]
stackoverflow_0001713329_macos_py2app_python_service.txt
Q: Strange behavior with python import So I am trying to import a module "foo" that contains directories "bar" and "wiz". "bar" contains python files a.py, b.py, and c.py. "wiz" contains python files x.py, y.py and z.py. $ ls foo __init__.py bar wiz $ ls foo/bar __init__.py a.py b.py c.py $ ...
Strange behavior with python import
So I am trying to import a module "foo" that contains directories "bar" and "wiz". "bar" contains python files a.py, b.py, and c.py. "wiz" contains python files x.py, y.py and z.py. $ ls foo __init__.py bar wiz $ ls foo/bar __init__.py a.py b.py c.py $ ls foo/wiz __init__.py x.py y.py...
[ "When importing foo, Python will just load foo/__init__.py, it will not (automatically) load foo.bar or foo.wiz. Therefore, trying to access those without explicitely importing them will raise a AttributeError.\nIf some module imports sub-modules like foo.bar or foo.bar.a, Python will load the respective files and ...
[ 2, 1 ]
[]
[]
[ "import", "module", "python" ]
stackoverflow_0001714111_import_module_python.txt
Q: Strange error in google app engine I would like to mention before hand that I am a novice to python and with that to python platform of GAE. I have been finding this very strange error/fault when I am trying to get an entity using its key ID... Here's what I do, I am querying the datastore entity model UserDetails...
Strange error in google app engine
I would like to mention before hand that I am a novice to python and with that to python platform of GAE. I have been finding this very strange error/fault when I am trying to get an entity using its key ID... Here's what I do, I am querying the datastore entity model UserDetails for the key corresponding to the user n...
[ "You're getting this error because 'accounts' is a list rather than a single instance. Based on your code, I can't see why this would be the case, but try doing the following:\nsrc_key = db.GqlQuery('SELECT __key__ FROM UserDetails WHERE user_name = :uname', uname = src_username).get()\nif src_key:\n account = Use...
[ 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0001714200_google_app_engine_python.txt
Q: Can't use a data obj with timeit.Time module in python I'm trying to measure how long it takes read then encrypt some data (independently). But I can't seem to access the a pre-created data obj within timeit (as it runs in its own virtual environment) This works fine (timing file read operation): t = timeit.Timer(...
Can't use a data obj with timeit.Time module in python
I'm trying to measure how long it takes read then encrypt some data (independently). But I can't seem to access the a pre-created data obj within timeit (as it runs in its own virtual environment) This works fine (timing file read operation): t = timeit.Timer(""" openFile = open('mytestfile.bmp', "rb") fileData = openF...
[ "timeit takes a setup argument that only runs once\nfrom the docs:\n\nsetup: statement to be executed once\n initially (default 'pass')\n\nfor example:\nsetup = \"\"\"\nfrom Crypto.Cipher import AES\nimport os\nnewFile = []\nfileData = open('filename').read()\n\"\"\"\nstmt = \"\"\"\nkey = os.urandom(32)\ncipher = ...
[ 1, 0 ]
[]
[]
[ "performance", "python", "timeit" ]
stackoverflow_0001714352_performance_python_timeit.txt
Q: How to wrap built-in methods in Python? (or 'how to pass them by reference') I want to wrap the default open method with a wrapper that should also catch exceptions. Here's a test example that works: truemethod = open def fn(*args, **kwargs): try: return truemethod(*args, **kwargs) except (IOError,...
How to wrap built-in methods in Python? (or 'how to pass them by reference')
I want to wrap the default open method with a wrapper that should also catch exceptions. Here's a test example that works: truemethod = open def fn(*args, **kwargs): try: return truemethod(*args, **kwargs) except (IOError, OSError): sys.exit('Can\'t open \'{0}\'. Error #{1[0]}: {1[1]}'.format(ar...
[ "The problem with your code is that inside wrap, your method = fn statement is simply changing the local value of method, it isn't changing the larger value of open. You'll have to assign to those names yourself:\ndef wrap(method, exceptions = (OSError, IOError)):\n def fn(*args, **kwargs):\n try:\n ...
[ 4, 2, 1 ]
[]
[]
[ "exception_handling", "python", "wrapper" ]
stackoverflow_0001714725_exception_handling_python_wrapper.txt
Q: Python code comments In C# and through Visual Studio, it is possible to comment your functions, so you can tell whoever is using your class what the input arguments should be, what it is supposed to return, etc. Is there anything remotely similar in python? A: In Python you use docstrings like this: def foo(): ...
Python code comments
In C# and through Visual Studio, it is possible to comment your functions, so you can tell whoever is using your class what the input arguments should be, what it is supposed to return, etc. Is there anything remotely similar in python?
[ "In Python you use docstrings like this:\ndef foo():\n \"\"\" Here is the docstring \"\"\"\n\nBasically you need to have a triple quoted string be on the first line of a function, class, or module to be considered a docstring. \nNote: Actually I you don't have to use a triple quoted string but that is the conven...
[ 9, 7, 5, 2 ]
[]
[]
[ "python" ]
stackoverflow_0001714633_python.txt
Q: Check String for / against Characters in Python I need to be able to tell the difference between a string that can contain letters and numbers, and a string that can contain numbers, colons and hyphens. >>> def checkString(s): ... pattern = r'[-:0-9]' ... if re.search(pattern,s): ... print "Matches pattern...
Check String for / against Characters in Python
I need to be able to tell the difference between a string that can contain letters and numbers, and a string that can contain numbers, colons and hyphens. >>> def checkString(s): ... pattern = r'[-:0-9]' ... if re.search(pattern,s): ... print "Matches pattern." ... else: ... print "Does not match pattern....
[ "you need to match the whole string, not a single character as you do at the moment:\n>>> re.search('^[-:0-9]+$', \"12:24:-14\")\n<_sre.SRE_Match object at 0x01013758>\n>>> re.search('^[-:0-9]+$', \"hello\")\n>>> re.search('^[-:0-9]+$', \"hello2\")\n\nTo explain regex: \n\nwithin square brackets (character class): ...
[ 5, 1, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0001714569_python_regex.txt
Q: Couple of questions regarding PyQt I have a couple of questions. I have an algorithm that will generate a couple of pictures in python that must be displayed on a form. I am using PyGt for this. My question is: where should I run my code? Right from the initializer? In that case from what I tested, the form won't ...
Couple of questions regarding PyQt
I have a couple of questions. I have an algorithm that will generate a couple of pictures in python that must be displayed on a form. I am using PyGt for this. My question is: where should I run my code? Right from the initializer? In that case from what I tested, the form won't show up. Should I set up a timer in th...
[ "You might want to check the Mandelbrot example.\nBasically the idea is to use a worker thread to do the heavy computations (I'd suggest a QThread to ease the communication to the main thread by using signals/slots), then once the work is done emit a signal with the computed data and have the main thread paint it. ...
[ 4, 1 ]
[]
[]
[ "pyqt", "pyqt4", "python" ]
stackoverflow_0001715098_pyqt_pyqt4_python.txt
Q: Inline editing of ManyToMany relation in Django After working through the Django tutorial I'm now trying to build a very simple invoicing application. I want to add several Products to an Invoice, and to specify the quantity of each product in the Invoice form in the Django admin. Now I've to create a new Product ...
Inline editing of ManyToMany relation in Django
After working through the Django tutorial I'm now trying to build a very simple invoicing application. I want to add several Products to an Invoice, and to specify the quantity of each product in the Invoice form in the Django admin. Now I've to create a new Product object if I've got different quantites of the same Pr...
[ "You need to change your model structure a bit. As you recognise, the quantity doesn't belong on the Product model - it belongs on the relationship between Product and Invoice. \nTo do this in Django, you can use a ManyToMany relationship with a through table:\nclass Product(models.Model):\n ...\n\nclass Product...
[ 9 ]
[]
[]
[ "django", "django_admin", "inline_editing", "python" ]
stackoverflow_0001714995_django_django_admin_inline_editing_python.txt
Q: Exception message (Python 2.6) In Python, if I open a binary file that doesn't exist, the program exits with an error and prints: Traceback (most recent call last): File "C:\Python_tests\Exception_Handling\src\exception_handling.py", line 4, in <module> pkl_file = open('monitor.dat', 'rb') IOError: [Errno...
Exception message (Python 2.6)
In Python, if I open a binary file that doesn't exist, the program exits with an error and prints: Traceback (most recent call last): File "C:\Python_tests\Exception_Handling\src\exception_handling.py", line 4, in <module> pkl_file = open('monitor.dat', 'rb') IOError: [Errno 2] No such file or directory: 'moni...
[ "This prints the exception message:\nexcept Exception, e:\n print \"Couldn't do it: %s\" % e\n\nThis will show the whole traceback:\nimport traceback\n\n# ...\n\nexcept Exception, e:\n traceback.print_exc()\n\nBut you might not want to catch Exception. The narrower you can make your catch, the better, genera...
[ 90, 22, 9, 6 ]
[]
[]
[ "exception_handling", "message", "python" ]
stackoverflow_0001715198_exception_handling_message_python.txt
Q: How can I get an accurate UTC time with Python? I wrote a desktop application and was using datetime.datetime.utcnow() for timestamping, however I've recently noticed that some people using the application get wildly different results than I do when we run the program at the same time. Is there any way to get the...
How can I get an accurate UTC time with Python?
I wrote a desktop application and was using datetime.datetime.utcnow() for timestamping, however I've recently noticed that some people using the application get wildly different results than I do when we run the program at the same time. Is there any way to get the UTC time locally without using urllib to fetch it fr...
[ "Python depends on the underlying operating system to provide an accurate time-of-day clock. If it isn't doing that, you don't have much choice other than to bypass the o/s. There's a pure-Python implementation of an NTP client here. A very simple-minded approach:\n>>> import ntplib,datetime\n>>> x = ntplib.NTPC...
[ 24, 7 ]
[]
[]
[ "datetime", "python", "timestamp", "utc" ]
stackoverflow_0001599060_datetime_python_timestamp_utc.txt
Q: How to read, in a line, all characters from column A to B is it possible in Python, given a file with 10000 lines, where all of them have this structure: 1, 2, xvfrt ert5a fsfs4 df f fdfd56 , 234 or similar, to read the whole string, and then to store in another string all characters from column 7 to column ...
How to read, in a line, all characters from column A to B
is it possible in Python, given a file with 10000 lines, where all of them have this structure: 1, 2, xvfrt ert5a fsfs4 df f fdfd56 , 234 or similar, to read the whole string, and then to store in another string all characters from column 7 to column 17, including spaces, so the new string would be "xvfrt ert5a" ...
[ "lst = [line[6:17] for line in open(fname)]\n\n", "another_list = []\nfor line in f:\n another_list.append(line[6:17])\n\nOr as a generator (a memory friendly solution):\nanother_list = (line[6:17] for line in f)\n\n", "I'm going to take Michael Dillon's answer a little further. If by \"columns 6 through 17...
[ 7, 5, 2, 1, 1, 0, 0 ]
[]
[]
[ "python", "text_processing" ]
stackoverflow_0001710030_python_text_processing.txt
Q: Euclidian Distance Python Implementation I am playing with the following code from programming collective intelligence, this is a function from the book that calculated eclidian distance between two movie critics. This function sums the difference of the rankings in the dictionary, but euclidean distance in n dime...
Euclidian Distance Python Implementation
I am playing with the following code from programming collective intelligence, this is a function from the book that calculated eclidian distance between two movie critics. This function sums the difference of the rankings in the dictionary, but euclidean distance in n dimensions also includes the square root of that s...
[ "The reason the square root is not used is because it is computationally expensive; it is monotonic (i.e., it preserves order) with the square function, so if all you're interested in is the order of the distances, the square root is unnecessary (and, as mentioned, very expensive computationally).\n", "That's cor...
[ 12, 3, 2, 1 ]
[]
[]
[ "euclidean_distance", "python" ]
stackoverflow_0001709720_euclidean_distance_python.txt
Q: Best way to decode unknown unicoding encoding in Python 2.5 Have I got that all the right way round? Anyway, I am parsing a lot of html, but I don't always know what encoding it's meant to be (a surprising number lie about it). The code below easily shows what I've been doing so far, but I'm sure there's a better ...
Best way to decode unknown unicoding encoding in Python 2.5
Have I got that all the right way round? Anyway, I am parsing a lot of html, but I don't always know what encoding it's meant to be (a surprising number lie about it). The code below easily shows what I've been doing so far, but I'm sure there's a better way. Your suggestions would be much appreciated. import logging i...
[ "There are two general purpose libraries for detecting unknown encodings:\n\nchardet, part of Universal Feed Parser\nUnicodeDammit, part of Beautiful Soup\n\nchardet is supposed to be a port of the way that firefox does it\nYou can use the following regex to detect utf8 from byte strings:\nimport re\n\nutf8_detecto...
[ 10, 3, 2 ]
[]
[]
[ "character_encoding", "encoding", "html", "python", "unicode" ]
stackoverflow_0001715772_character_encoding_encoding_html_python_unicode.txt
Q: adding a keyword argument to an overridden method and using **kwarg I am subclassing an object in order to override a method that I want to add some functionality to. I don't want to completely replace it or add a differently named method but remain compatible to the superclasses method by just adding an optional ...
adding a keyword argument to an overridden method and using **kwarg
I am subclassing an object in order to override a method that I want to add some functionality to. I don't want to completely replace it or add a differently named method but remain compatible to the superclasses method by just adding an optional argument to the method. Is it possible to work with *args and **kwargs to...
[ "class A(object):\n def foo(self, arg1, arg2, argopt1=\"bar\"):\n print arg1, arg2, argopt1\n\nclass B(A):\n def foo(self, *args, **kwargs):\n argopt2 = kwargs.get('argopt2', default_for_argopt2)\n # remove the extra arg so the base class doesn't complain. \n del kwargs['argopt2']\...
[ 13, 6, 1 ]
[]
[]
[ "python" ]
stackoverflow_0001715840_python.txt
Q: Local import statements in Python I think putting the import statement as close to the fragment that uses it helps readability by making its dependencies more clear. Will Python cache this? Should I care? Is this a bad idea? def Process(): import StringIO file_handle=StringIO.StringIO('hello world') #d...
Local import statements in Python
I think putting the import statement as close to the fragment that uses it helps readability by making its dependencies more clear. Will Python cache this? Should I care? Is this a bad idea? def Process(): import StringIO file_handle=StringIO.StringIO('hello world') #do more stuff for i in xrange(10): Proc...
[ "The other answers evince a mild confusion as to how import really works.\nThis statement:\nimport foo\n\nis roughly equivalent to this statement:\nfoo = __import__('foo', globals(), locals(), [], -1)\n\nThat is, it creates a variable in the current scope with the same name as the requested module, and assigns it t...
[ 89, 14, 13, 8, 3, 1 ]
[]
[]
[ "python", "python_import" ]
stackoverflow_0001699108_python_python_import.txt
Q: Which Python 2.x DHT implementation is going to be easiest to port to Python 3.x? Previously I asked which DHT implementations are compatible with Python 3.x - StackOverflow's answer confirmed my worst fear: So far nobody has released a Python 3.x compatible Distributed Hash Table implementation. That means it's t...
Which Python 2.x DHT implementation is going to be easiest to port to Python 3.x?
Previously I asked which DHT implementations are compatible with Python 3.x - StackOverflow's answer confirmed my worst fear: So far nobody has released a Python 3.x compatible Distributed Hash Table implementation. That means it's to roll up my sleeves and get to work myself. My project does not necessarily require th...
[ "Try running 2to3 on each of them, then run the resulting code. If one of them works, then it was the easiest to port. If none of them do, then take a guess based on which of their errors you understand best.\n" ]
[ 3 ]
[]
[]
[ "dht", "python" ]
stackoverflow_0001716526_dht_python.txt
Q: Which DHT implementations are compatible with Python 3.x? Following on from this question about DHTs in Python, my question is the same except that I'm developing on Python 3.x - I only want to know about implementations of the DHT concept which are known to work with Python 3. There seem to be plenty of DHT produ...
Which DHT implementations are compatible with Python 3.x?
Following on from this question about DHTs in Python, my question is the same except that I'm developing on Python 3.x - I only want to know about implementations of the DHT concept which are known to work with Python 3. There seem to be plenty of DHT products, for example Khashmir, however as far as I'm aware nobody ...
[ "I don't think you'll get simultaneous 2.6 and 3.x support - that is not what Guido is recommending. To do that they'd have to maintain two equivalent parallel code-lines, because the same code is unlikely to work on both python 2 and 3.\n" ]
[ 1 ]
[]
[]
[ "dht", "p2p", "python", "python_3.x" ]
stackoverflow_0001708315_dht_p2p_python_python_3.x.txt
Q: How to make a custom command line interface using OptionParser? I am using the OptionParser from optparse module to parse my command that I get using the raw_input(). I have these questions. 1.) I use OptionParser to parse this input, say for eg. (getting multiple args) my prompt> -a foo -b bar -c spam eggs I...
How to make a custom command line interface using OptionParser?
I am using the OptionParser from optparse module to parse my command that I get using the raw_input(). I have these questions. 1.) I use OptionParser to parse this input, say for eg. (getting multiple args) my prompt> -a foo -b bar -c spam eggs I did this with setting the action='store_true' in add_option() for '-...
[ "For part 2: you want a new OptionParser instance for each line you process. And look at the cmd module for writing a command loop like this.\n", "You can also solve #1 using the nargs option attribute as follows:\nparser = OptionParser()\nparser.add_option(\"-c\", \"\", nargs=2)\nparser.add_option(\"-d\", \"\",...
[ 4, 2, 1 ]
[]
[]
[ "optparse", "python" ]
stackoverflow_0001716554_optparse_python.txt
Q: Python not sorting Unicode correctly data = [unicode('č', "cp1250"), unicode('d', "cp1250"), unicode('a', "cp1250")] data.sort(key=unicode.lower) for x in range(0,len(data)): print data[x].encode("cp1250") and I get: a d č It should be: a č d Slovenia Alphabet goes like: a b c č d e f g...
Python not sorting Unicode correctly
data = [unicode('č', "cp1250"), unicode('d', "cp1250"), unicode('a', "cp1250")] data.sort(key=unicode.lower) for x in range(0,len(data)): print data[x].encode("cp1250") and I get: a d č It should be: a č d Slovenia Alphabet goes like: a b c č d e f g..... I'm using WIN XP(Active code page: 8...
[ "I solved this problem an now have a working program:\nimport locale\nlocale.setlocale(locale.LC_ALL, 'slovenian')\ndata = ['č', 'ab', 'aa', 'a', 'd', 'ć', 'B', 'c']\ndata.sort(key=locale.strxfrm)\nprint \"Sorted...\"\nfor x in range(0,len(data)):\n print data[x]\n\n", "See the locale module for language-aware...
[ 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0001596091_python.txt
Q: Something like pubsubhubbub that does not depend on google app engine I am looking for something like PubSubHubbub that does not depend on google app engine to run. What I need is a tool that can track for me a big very large number of rss or atom feeds and issue events when they are updated. A: pubsubhubbub is ...
Something like pubsubhubbub that does not depend on google app engine
I am looking for something like PubSubHubbub that does not depend on google app engine to run. What I need is a tool that can track for me a big very large number of rss or atom feeds and issue events when they are updated.
[ "pubsubhubbub is a protocol, and, as such, does not depend on app engine. For example, superfeedr is another implementation of this protocol (I believe it's free for the first 1000 feeds, then something like 50 dollars a month for the next 1000 feeds, then decreasing gradually for even larger number of feeds).\n",...
[ 12, 3 ]
[]
[]
[ "atom_feed", "feed", "python", "rss", "websub" ]
stackoverflow_0001716117_atom_feed_feed_python_rss_websub.txt
Q: Synthesis of general programming language (Python) with tailored language (PureData/MaxMSP/ChucK) I am learning Python because it appeals to me as a mathematician but also has many useful libraries for scientific computing, image processing, web apps, etc etc. It is frustrating to me that for certain of my inter...
Synthesis of general programming language (Python) with tailored language (PureData/MaxMSP/ChucK)
I am learning Python because it appeals to me as a mathematician but also has many useful libraries for scientific computing, image processing, web apps, etc etc. It is frustrating to me that for certain of my interests (eletronic music or installation art) there are very specific programming languages which seem bet...
[ "I would say learn them all. While it's true that many languages can do many things, specialised languages are usually more expressive and easier to use for a particular task. Case-in-point is while most languages allow shell interaction and process control very few are as well suited to the task as bash scripts.\n...
[ 8, 4, 1, 1 ]
[]
[]
[ "chuck", "puredata", "python" ]
stackoverflow_0001016301_chuck_puredata_python.txt
Q: What Jabber/XMPP libraries are available for PyS60 (Python for Symbian S60) interpreter? I'm interested in developing a XMPP client on the mobile S60 Symbian platform using the Python interpreter PyS60. I've done a search on Google for possible libraries, but turned up empty. I'm hoping that by asking this on SO,...
What Jabber/XMPP libraries are available for PyS60 (Python for Symbian S60) interpreter?
I'm interested in developing a XMPP client on the mobile S60 Symbian platform using the Python interpreter PyS60. I've done a search on Google for possible libraries, but turned up empty. I'm hoping that by asking this on SO, I can get a definite answer on whether there is actually an existing library that I just hadn...
[ "It's fairly easy to add native extensions to Python and there are lots of C/C++ libraries for XMPP that would port easily.\nThe previous pyexpat module is just bindings for native expat on Symbian, which is ported to S60 3rd Edition, so you should be able to get pyexpat working too. Of course you need some abilit...
[ 0 ]
[]
[]
[ "pys60", "python", "symbian", "xmpp" ]
stackoverflow_0001712768_pys60_python_symbian_xmpp.txt
Q: Untrusted templates in Python - what is a safe library to use? I am building a library that will be used in several Python applications. It get multilingual e-mail templates from an RMDBS, and then variable replacement will be performed on the template in Python before the e-mail is sent. In addition to variable r...
Untrusted templates in Python - what is a safe library to use?
I am building a library that will be used in several Python applications. It get multilingual e-mail templates from an RMDBS, and then variable replacement will be performed on the template in Python before the e-mail is sent. In addition to variable replacement, I need the template library to support if, elif, and for...
[ "From the Django book:\n\nFor that reason, it’s impossible to call Python code directly within Django templates. All “programming” is fundamentally limited to the scope of what template tags can do. It is possible to write custom template tags that do arbitrary things, but the out-of-the-box Django template tags in...
[ 4, 3 ]
[]
[]
[ "email", "python", "templates" ]
stackoverflow_0001716869_email_python_templates.txt
Q: Strange decorator result on related object comparison On views that allow updating/deleting objects, I need a decorator that verifies that the object to be edited belongs to a group(model "loja). Both defined in the url: /[slug model loja--s_loja]/[viewname-ex:addmenu]/[object id--obj_id] Because the model of the ...
Strange decorator result on related object comparison
On views that allow updating/deleting objects, I need a decorator that verifies that the object to be edited belongs to a group(model "loja). Both defined in the url: /[slug model loja--s_loja]/[viewname-ex:addmenu]/[object id--obj_id] Because the model of the object can vary, the decorator the model of the object as a...
[ "Replace is not with !=.\nnot loja is evaluating to True, and the if statement is testing the equality between objecto.loja and True.\n" ]
[ 1 ]
[]
[]
[ "decorator", "django", "python" ]
stackoverflow_0001716946_decorator_django_python.txt
Q: Google Python Image Library - How to resize an image based on its width? I have this code to make a resize of an uploaded image as a thumbnail. project.thumbnail = db.Blob(images.resize(self.request.get("img"),188,96)) However, it does not do what I want. It always resize the image to have the fixed height of 96....
Google Python Image Library - How to resize an image based on its width?
I have this code to make a resize of an uploaded image as a thumbnail. project.thumbnail = db.Blob(images.resize(self.request.get("img"),188,96)) However, it does not do what I want. It always resize the image to have the fixed height of 96. Instead, I want to have all the resized images to have the same width of 188....
[ "You can call this as images.resize(data, width=188)\n" ]
[ 4 ]
[]
[]
[ "google_app_engine", "image_manipulation", "python" ]
stackoverflow_0001717070_google_app_engine_image_manipulation_python.txt
Q: Python using PRE-FETCH on Oracle 10 import cx_Oracle import wx print "Start..." + str(wx.Now()) base = cx_Oracle.makedsn('xxx', port, 'yyyy') connection = cx_Oracle.connect(user name, password, base) cursor = connection.cursor() cursor.execute('select data from t_table') li_row = cursor.fetchall() data = []...
Python using PRE-FETCH on Oracle 10
import cx_Oracle import wx print "Start..." + str(wx.Now()) base = cx_Oracle.makedsn('xxx', port, 'yyyy') connection = cx_Oracle.connect(user name, password, base) cursor = connection.cursor() cursor.execute('select data from t_table') li_row = cursor.fetchall() data = [] for row in li_row: data.append(row...
[ "Fetching 10000 rows...\ncursor.arraysize = 10000\n" ]
[ 0 ]
[]
[]
[ "oracle10g", "python" ]
stackoverflow_0001716606_oracle10g_python.txt
Q: Client Digest Authentication Python with URLLIB2 will not remember Authorization Header Information I am trying to use Python to write a client that connects to a custom http server that uses digest authentication. I can connect and pull the first request without problem. Using TCPDUMP (I am on MAC OS X--I am bo...
Client Digest Authentication Python with URLLIB2 will not remember Authorization Header Information
I am trying to use Python to write a client that connects to a custom http server that uses digest authentication. I can connect and pull the first request without problem. Using TCPDUMP (I am on MAC OS X--I am both a MAC and a Python noob) I can see the first request is actually two http requests, as you would expec...
[ "Although it's not available out of the box, urllib2 is flexible enough to add it yourself. Subclass HTTPDigestAuthHandler, hack it (retry_http_digest_auth method I think) to remember authentication information and define an http_request(self, request) method to use it for all subsequent requests (add WWW-Authentic...
[ 1 ]
[]
[]
[ "authentication", "digest", "python", "urllib2" ]
stackoverflow_0001706644_authentication_digest_python_urllib2.txt
Q: Why does Pylons use StackedObjectProxies instead of threading.local? It seems like threading.local is more straightforward and more robust. A: StackedObjectProxy uses a threading.local underneath it. Pylons doesn't use plain threading.locals for 2 reasons: 1) it'd be a more intrusive API than a proxy. E.g. reque...
Why does Pylons use StackedObjectProxies instead of threading.local?
It seems like threading.local is more straightforward and more robust.
[ "StackedObjectProxy uses a threading.local underneath it. Pylons doesn't use plain threading.locals for 2 reasons:\n1) it'd be a more intrusive API than a proxy. E.g. request().POST.get('file') vs request.POST.get('file')\n2) StackedObjectProxys are not only thread safe, but also \"request safe\" -- meaning it's sa...
[ 5, 1 ]
[]
[]
[ "pylons", "python" ]
stackoverflow_0001686768_pylons_python.txt
Q: def next() for Python pre-2.6? (instead of object.next method) Python 2.6+ and 3.* have next(), but pre-2.6 only offers the object.next method. Is there a way to get the next() style in pre-2.6; some "def next():" construction perhaps? A: class Throw(object): pass throw = Throw() # easy sentinel hack def next(i...
def next() for Python pre-2.6? (instead of object.next method)
Python 2.6+ and 3.* have next(), but pre-2.6 only offers the object.next method. Is there a way to get the next() style in pre-2.6; some "def next():" construction perhaps?
[ "class Throw(object): pass\nthrow = Throw() # easy sentinel hack\ndef next(iterator, default=throw):\n \"\"\"next(iterator[, default])\n\n Return the next item from the iterator. If default is given\n and the iterator is exhausted, it is returned instead of\n raising StopIteration.\n \"\"\"\n try:\n iterne...
[ 11, 6, 2 ]
[]
[]
[ "next", "python" ]
stackoverflow_0001716428_next_python.txt
Q: Python socket not receiving anything I'm trying to receive a variable length stream from a camera with python, but get weird behaviour. This is Python 2.6.4 (r264:75706) on linux(Ubuntu 9.10) The message is supposed to come with a static header followed by the size, and rest of the stream. here is the code from so...
Python socket not receiving anything
I'm trying to receive a variable length stream from a camera with python, but get weird behaviour. This is Python 2.6.4 (r264:75706) on linux(Ubuntu 9.10) The message is supposed to come with a static header followed by the size, and rest of the stream. here is the code from socket import * import array import select ...
[ "You don't really know how many bytes you received, since your code is:\ndata=''\nwhile len(data)<10:\n chunk = tcpCliSock.recv(1024)\n print 'recv\\'d %d bites'%len(data)\n data=data+chunk\n\ni.e., you're receiving bytes in chunk, but what you're printing is len(data) before you update data. ...
[ 1, 0 ]
[]
[]
[ "nonblocking", "python", "sockets" ]
stackoverflow_0001710070_nonblocking_python_sockets.txt
Q: Supervisord RPC - UNKNOWN_METHOD on any request I've configured (almost default) supervisord.conf and started supervisord. Tasks launched and xmlrpc interfaces are up, but gives xmlrpclib.Fault: <Fault 1: 'UNKNOWN_METHOD'> on evey xmlrpc request, even when launching supervisorctl itself. There is a same message in...
Supervisord RPC - UNKNOWN_METHOD on any request
I've configured (almost default) supervisord.conf and started supervisord. Tasks launched and xmlrpc interfaces are up, but gives xmlrpclib.Fault: <Fault 1: 'UNKNOWN_METHOD'> on evey xmlrpc request, even when launching supervisorctl itself. There is a same message in the log: TRAC XML-RPC method called: supervisor.getA...
[ "I suspect you removed these lines from the supervisord.conf config file:\n; the below section must remain in the config file for RPC\n; (supervisorctl/web interface) to work, additional interfaces may be\n; added by defining them in separate rpcinterface: sections\n[rpcinterface:supervisor]\nsupervisor.rpcinterfac...
[ 11 ]
[]
[]
[ "python", "supervisord", "xml_rpc" ]
stackoverflow_0001714174_python_supervisord_xml_rpc.txt
Q: How can I make WSGI(Python) stateful? I'm quite new in Python world. I come from java and ABAP world, where their application server are able to handle stateful request. Is it also possible in python using WSGI? Or stateful and stateless are handled in other layer? A: Usually, you don't work with "bare" WSGI. Y...
How can I make WSGI(Python) stateful?
I'm quite new in Python world. I come from java and ABAP world, where their application server are able to handle stateful request. Is it also possible in python using WSGI? Or stateful and stateless are handled in other layer?
[ "Usually, you don't work with \"bare\" WSGI. You work with web-frameworks, such as Pylons or TurboGears2.\nAnd these contain a session-middleware, based on WSGI - called \"Beaker\". But if you work with the framework, you don't have to worry about that - you just use it.\nBut if you insist, you can of course use Be...
[ 5, 2, 1 ]
[]
[]
[ "python", "wsgi" ]
stackoverflow_0001703440_python_wsgi.txt
Q: how to process long-running requests in python workers? I have a python (well, it's php now but we're rewriting) function that takes some parameters (A and B) and compute some results (finds best path from A to B in a graph, graph is read-only), in typical scenario one call takes 0.1s to 0.9s to complete. This fun...
how to process long-running requests in python workers?
I have a python (well, it's php now but we're rewriting) function that takes some parameters (A and B) and compute some results (finds best path from A to B in a graph, graph is read-only), in typical scenario one call takes 0.1s to 0.9s to complete. This function is accessed by users as a simple REST web-service (GET ...
[ "The typical way to handle this sort of arrangement using threads in Python is to use the standard library module Queue. An example of using the Queue module for managing workers can be found here: Queue Example\n", "Looks like you need the \"workers\" to be separate processes (at least some of them, and therefor...
[ 2, 2, 1, 1, 0, 0, 0 ]
[]
[]
[ "load_balancing", "nginx", "python", "reverse_proxy", "wsgi" ]
stackoverflow_0001674696_load_balancing_nginx_python_reverse_proxy_wsgi.txt
Q: What's the nearest equivalent of Beautiful Soup for Ruby? I love the Beautiful Soup scraping library in Python. It just works. Is there a close equivalent in Ruby? A: Nokogiri is another HTML/XML parser. It's faster than hpricot according to these benchmarks. Nokogiri uses libxml2 and is a drop in replacement f...
What's the nearest equivalent of Beautiful Soup for Ruby?
I love the Beautiful Soup scraping library in Python. It just works. Is there a close equivalent in Ruby?
[ "Nokogiri is another HTML/XML parser. It's faster than hpricot according to these benchmarks. Nokogiri uses libxml2 and is a drop in replacement for hpricot. It also has css3 selector support which is pretty nice.\nEdit: There's a new benchmark comparing nokogiri, libxml-ruby, hpricot and rexml here.\nRuby Toolbox ...
[ 10, 4, 3, 1 ]
[]
[]
[ "beautifulsoup", "python", "ruby" ]
stackoverflow_0000640068_beautifulsoup_python_ruby.txt
Q: save Exceptions to file in python I want to save all following Exceptions in a file. The reason why I need this is because the IDLE for python 3.1.1 in Ubuntu raises an Exception at calltipps, but close to fast, that it isn't readble. Also I need this for testing. The best, would be if I just call a function which...
save Exceptions to file in python
I want to save all following Exceptions in a file. The reason why I need this is because the IDLE for python 3.1.1 in Ubuntu raises an Exception at calltipps, but close to fast, that it isn't readble. Also I need this for testing. The best, would be if I just call a function which saves all Exception to a file. Thank y...
[ "If you have a convenient main() function (whatever it's called), then you can use the logging module:\nimport logging\n\ndef main():\n raise Exception(\"Hey!\")\n\nlogging.basicConfig(level=logging.DEBUG, filename='/tmp/myapp.log')\n\ntry:\n main()\nexcept:\n logging.exception(\"Oops:\")\n\nlogging.except...
[ 38 ]
[]
[]
[ "exception", "file", "python", "ubuntu" ]
stackoverflow_0001718295_exception_file_python_ubuntu.txt
Q: Understanding an error message while writing code for a Fibonacci program My apologies in advance should I butcher any Python vocabulary, this is my first programming class and we are not permitted to post or share our code. I will do my best to explain the problem. I am defining my function as variable one and va...
Understanding an error message while writing code for a Fibonacci program
My apologies in advance should I butcher any Python vocabulary, this is my first programming class and we are not permitted to post or share our code. I will do my best to explain the problem. I am defining my function as variable one and variable two. I then gave values to both variables. I used a for statement with...
[ "To invoke your function, you have to use parens: appendNextFib(). It looks like you simply used appendNextFib, which would show you its value, which is that function object.\n", "While I personally think you may be stressing too much about the sharing of your code, a recursive solution to the problem is a lot m...
[ 3, 0 ]
[]
[]
[ "fibonacci", "python" ]
stackoverflow_0001718681_fibonacci_python.txt
Q: The choice of XML/XSL lib for Python 2.6.x Currently I have 2 varieties, LXML and libXML2 that both seem to work. I have tried benchmarking both, specifically for parsing memory string and files into XML and importing XSLT stylesheets and applying them. While pure performance based tests indicate that LXML comes o...
The choice of XML/XSL lib for Python 2.6.x
Currently I have 2 varieties, LXML and libXML2 that both seem to work. I have tried benchmarking both, specifically for parsing memory string and files into XML and importing XSLT stylesheets and applying them. While pure performance based tests indicate that LXML comes on top (applying stylesheets specifically) libxml...
[ "I've used LXML and been very impressed. The flexibility offered by having both the etree-like and objectify interfaces is pretty handy. I also like the fact that I don't have to have any separate text nodes.\nAs far as entity substitutions, I had a few issues too, but for me it was a matter of giving the parser ...
[ 2 ]
[]
[]
[ "benchmarking", "libxml2", "lxml", "python", "xslt" ]
stackoverflow_0001716647_benchmarking_libxml2_lxml_python_xslt.txt
Q: Are there database testing tools for python (like sqlunit)? Are there database testing tools for python (like sqlunit)? I want to test the DAL that is built using sqlalchemy A: Follow the design pattern that Django uses. Create a disposable copy of the database. Use SQLite3 in-memory, for example. Create the d...
Are there database testing tools for python (like sqlunit)?
Are there database testing tools for python (like sqlunit)? I want to test the DAL that is built using sqlalchemy
[ "Follow the design pattern that Django uses.\n\nCreate a disposable copy of the database. Use SQLite3 in-memory, for example.\nCreate the database using the SQLAlchemy table and index definitions. This should be a fairly trivial exercise.\nLoad the test data fixture into the database. \nRun your unit test case i...
[ 4 ]
[]
[]
[ "database", "python", "sqlalchemy", "testing" ]
stackoverflow_0001719279_database_python_sqlalchemy_testing.txt
Q: javascript error: "data.getElementsByTagName is not a function" I've spent hours on this stupid error, so any help would be appreciated! I'm using Jquery to request xml from a python file hosted on google appengine. I'm then trying to process the xml. Here's the response to the post request obtained from firebug: ...
javascript error: "data.getElementsByTagName is not a function"
I've spent hours on this stupid error, so any help would be appreciated! I'm using Jquery to request xml from a python file hosted on google appengine. I'm then trying to process the xml. Here's the response to the post request obtained from firebug: <?xml version="1.0" encoding="ISO-8859-1"?><building key='agdhcHRydXN...
[ "Try to force jQuery to recognize the returned data as xml by using\njQuery.post(toLoad, formInput,\n function(data, textStatus) {\n // now check if data is set and what the status is\n alert(data);\n alert(textStatus);\n //alert(data.getElementsByTagName(\"building\"));\n },\n 'xml'\n);\n\nBtw. what...
[ 1, 0, 0 ]
[]
[]
[ "javascript", "python", "xml" ]
stackoverflow_0001719161_javascript_python_xml.txt
Q: Multiple rows share a value in a column, how do I put all of these rows into one single row? I'm working with a text file that looks something like this: rs001 EEE /n rs008 EEE /n rs345 EEE /n rs542 CHG /n re432 CHG /n I want to be able to collapse all of the rows that share the same value in column 2 into ...
Multiple rows share a value in a column, how do I put all of these rows into one single row?
I'm working with a text file that looks something like this: rs001 EEE /n rs008 EEE /n rs345 EEE /n rs542 CHG /n re432 CHG /n I want to be able to collapse all of the rows that share the same value in column 2 into one single row (for example, rs001 rs008 rs345 EEE). Is there an easy way to do this using unix ...
[ "#!/usr/bin/env python\nfrom __future__ import with_statement\nfrom itertools import groupby\nwith open('file','r') as f:\n # We define \"it\" to be an iterator, for each line\n # it yields pairs like ('rs001','EEE') \n it=(line.strip().split() for line in f)\n # groupby does the heave work.\n # lamb...
[ 2, 0, 0 ]
[]
[]
[ "python", "row", "text", "unix" ]
stackoverflow_0001719068_python_row_text_unix.txt
Q: Jython exception handling within loops I am using Marathon 2.0b4 to automate tests for an application. A shortcoming of wait_p, one of the script elements provided by Marathon, is that its default timeout is hardcoded to be 60 seconds. I needed a larger timeout due to the long loading times in my application. [I c...
Jython exception handling within loops
I am using Marathon 2.0b4 to automate tests for an application. A shortcoming of wait_p, one of the script elements provided by Marathon, is that its default timeout is hardcoded to be 60 seconds. I needed a larger timeout due to the long loading times in my application. [I considered patching Marathon, but didn't want...
[ "@Hank's explanation is correct, but I would suggest a different approach:\ndef wait_p_long(times, compID_name, ppty_name, ppty_value, compID_cell=None):\n from marathon.playback import *\n for i in range(times-1):\n try:\n wait_p(compID_name, ppty_name, ppty_value, compID_cell)\n ...
[ 3, 2 ]
[]
[]
[ "automated_tests", "exception_handling", "jython", "python" ]
stackoverflow_0001719262_automated_tests_exception_handling_jython_python.txt
Q: Python website convert into Adobe Dreamweaver CS3 I am comfortable in Adobe Dreamweaver CS3. Is there a way to convert a website written in the Python language into Dreamweaver for those who aren't familiar with writing in code? A: Assuming that any functionality needs to remain intact… no. A: If you mean a to...
Python website convert into Adobe Dreamweaver CS3
I am comfortable in Adobe Dreamweaver CS3. Is there a way to convert a website written in the Python language into Dreamweaver for those who aren't familiar with writing in code?
[ "Assuming that any functionality needs to remain intact… no.\n", "If you mean a tool which can convert a python site into dreamweaver, not possible yet, such intelligent machines are not yet invented, but evolution has produced you,\nso what you can do is see the site page by page, and make it again in dreamweave...
[ 1, 1, 0 ]
[]
[]
[ "dreamweaver", "python" ]
stackoverflow_0001719127_dreamweaver_python.txt
Q: Python organizing data with multiple dictionaries I am trying to create a small server type application and have a question regarding organizing data with dicts. Right now I am grouping the data using the connection socket (mainly to verify where it's coming from and for sending data back out). Something like this...
Python organizing data with multiple dictionaries
I am trying to create a small server type application and have a question regarding organizing data with dicts. Right now I am grouping the data using the connection socket (mainly to verify where it's coming from and for sending data back out). Something like this: connected[socket] = account_data. Basically, each con...
[ "First off, the data, needn't be be replicated. You can well have 3 dictionaries each using a different key, but having the same reference as its value.\nDoing so you only need to change the value object once and this will be reflected in all dictionaries (or more precisely since the the dictionaries only store a ...
[ 2, 1, 0, 0 ]
[]
[]
[ "dictionary", "grouping", "python" ]
stackoverflow_0001719742_dictionary_grouping_python.txt
Q: How to trigger post-build using setuptools/distutils I am building an application using py2app/setuptools, so once it creates application bundle I want to take some action on dist folder e.g. create a installer/upload it. Is there a way? I have found some post-install solution but no post-build Alternatively I can...
How to trigger post-build using setuptools/distutils
I am building an application using py2app/setuptools, so once it creates application bundle I want to take some action on dist folder e.g. create a installer/upload it. Is there a way? I have found some post-install solution but no post-build Alternatively I can call 'python setup.py py2app' from my own script and do t...
[ "I responded to a similar question yesterday about subclassing distutils.core.Command.\nThe core of it is that by doing this you are able to precisely control the behavior of each stage of the preparation process, and are able to create your own commands that can do pretty much anything you can think of. \nPlease h...
[ 4, 0, 0 ]
[]
[]
[ "distutils", "py2app", "python", "setuptools" ]
stackoverflow_0001421709_distutils_py2app_python_setuptools.txt
Q: Euler #26, how to convert rational number to string with better precision? I want to get 1/7 with better precision, but it got truncated. How can I get better precision when I convert a rational number? >>> str(1.0/7)[:50] '0.142857142857' A: Python has a built-in library for arbitrary-precision calculations: De...
Euler #26, how to convert rational number to string with better precision?
I want to get 1/7 with better precision, but it got truncated. How can I get better precision when I convert a rational number? >>> str(1.0/7)[:50] '0.142857142857'
[ "Python has a built-in library for arbitrary-precision calculations: Decimal. For example:\n>>>from decimal import Decimal, getcontext\n>>>getcontext().prec = 50\n>>>x = Decimal(1)/Decimal(7)\n>>>x\nDecimal('0.14285714285714285714285714285714285714285714285714')\n>>>str(x)\n'0.14285714285714285714285714285714285714...
[ 9, 6, 3, 2 ]
[]
[]
[ "floating_point", "floating_point_precision", "python" ]
stackoverflow_0001719776_floating_point_floating_point_precision_python.txt
Q: Python decorators and class methods and evaluation -- django memoize I have a working memoize decorator which uses Django's cache backend to remember the result of a function for a certain amount of time. I am specifically applying this to a class method. My decorator looks like: def memoize(prefix='mysite', time...
Python decorators and class methods and evaluation -- django memoize
I have a working memoize decorator which uses Django's cache backend to remember the result of a function for a certain amount of time. I am specifically applying this to a class method. My decorator looks like: def memoize(prefix='mysite', timeout=300, keygenfunc=None): # MUST SPECIFY A KEYGENFUNC(args, kwargs) W...
[ "Descriptors must always be set on the class, not on the instance (see the how-to guide for all details). Of course, in this case you're not even setting it on the instance, but rather on another function (and fetching it as an attribute of a bound method). I think that the only way to use the syntax you want is ...
[ 2 ]
[ "While I agree with AlexM, I did have some spare time and thought this would be interesting:\n# from django.whereever import cache\nclass memoize(object):\n def __init__(self,prefix='mysite', timeout=300, keygenfunc=None):\n class memo_descriptor(object):\n def __init__(self,func):\n ...
[ -1 ]
[ "class", "decorator", "methods", "python", "scope" ]
stackoverflow_0001719527_class_decorator_methods_python_scope.txt
Q: Filtering odd numbers M = [[1,2,3], [4,5,6], [7,8,9]] col2 = [row[1] + 1 for row in M if row[1] % 2 == 0] print (col2) Output: [3, 9] I'm expecting it to filter out the odd numbers, but it does the opposite. A: The code is doing exactly what you would expect - if the second item is even, increase it ...
Filtering odd numbers
M = [[1,2,3], [4,5,6], [7,8,9]] col2 = [row[1] + 1 for row in M if row[1] % 2 == 0] print (col2) Output: [3, 9] I'm expecting it to filter out the odd numbers, but it does the opposite.
[ "The code is doing exactly what you would expect - if the second item is even, increase it by one and put it into the list.\nSo for the first row, it sees that 2 % 2 == 0 is True, and sets col2[0] = 2 + 1 = 3. For the second row, 5 % 2 == 0 is False. For the third row, 8%2 == 0 is True, and col2[1] = 8 + 1 = 9.\n",...
[ 6, 2, 0, 0 ]
[]
[]
[ "list_comprehension", "modulo", "python" ]
stackoverflow_0001719929_list_comprehension_modulo_python.txt
Q: How to load a bitmap on a window on PyQt I currently have a PIL Image that I'd like to display on a PyQt window. I know this must be easy, but I can't find anywhere how to do it. Could anyone give me a hand on this? Here is the code of the window I currently have: import sys from PyQt4 import QtGui class Window(Q...
How to load a bitmap on a window on PyQt
I currently have a PIL Image that I'd like to display on a PyQt window. I know this must be easy, but I can't find anywhere how to do it. Could anyone give me a hand on this? Here is the code of the window I currently have: import sys from PyQt4 import QtGui class Window(QtGui.QWidget): def __init__(self, parent=N...
[ "try something like this, you can use http://svn.effbot.org/public/stuff/sandbox/pil/ImageQt.py to convert any pil image to qimage\nimport sys\nfrom PyQt4 import QtGui\nfrom PIL import Image\n\ndef get_pil_image(w, h):\n clr = chr(0)+chr(255)+chr(0)\n im = Image.fromstring(\"RGB\", (w,h), clr*(w*h))\n retu...
[ 2, 1 ]
[]
[]
[ "pyqt", "pyqt4", "python" ]
stackoverflow_0001713306_pyqt_pyqt4_python.txt
Q: CherryPy (or other Python framework) with FastCGI on shared host I am trying to configure the Python mini-framework CherryPy with FastCGI (actually fcgid) on Apache. I am on a shared host, so I don't have access to httpd.conf, just htaccess. I have followed these tutorials to no avail: http://tools.cherrypy.org/w...
CherryPy (or other Python framework) with FastCGI on shared host
I am trying to configure the Python mini-framework CherryPy with FastCGI (actually fcgid) on Apache. I am on a shared host, so I don't have access to httpd.conf, just htaccess. I have followed these tutorials to no avail: http://tools.cherrypy.org/wiki/FastCGIWSGI http://tools.cherrypy.org/wiki/BluehostDeployment I k...
[ "Apache + Bluehost + fastcgi + cherrypy + wsgi is unfortunately a lot of pieces. I wish I had a year to write the Definitive Guide for you, but alas. You might gain some insight from the rather long mailing list thread which resulted in those links you posted.\n", "An idea: make sure your .fcgi file has a referen...
[ 1, 1, 1, 0 ]
[]
[]
[ "cherrypy", "fastcgi", "mod_fcgid", "python" ]
stackoverflow_0001665742_cherrypy_fastcgi_mod_fcgid_python.txt
Q: What does this Python code do: shell=(sys.platform!="win32")) I don't understand what this code is doing, I'm wanting to run a command line, in Mac OS X, the code I'm using is from somebody running a Windows command line. The command still executes, but I'd like to know what the sys.platform!="win32" is for, an...
What does this Python code do: shell=(sys.platform!="win32"))
I don't understand what this code is doing, I'm wanting to run a command line, in Mac OS X, the code I'm using is from somebody running a Windows command line. The command still executes, but I'd like to know what the sys.platform!="win32" is for, and if I should change it to something else for Mac OS X. It seems t...
[ "Here is what this code does and does not:\n\nIt doesn't compile (syntax error -\nyou need a comma between the\narguments) , - not anymore.\nIt starts a subprocess\nand, if you are not on win32 it\nstarts it through the shell. The\n\"shell\" argument can be True or\nFalse and sys.platform != 'win32' can also evalua...
[ 6, 3 ]
[]
[]
[ "command_line", "macos", "python" ]
stackoverflow_0001720169_command_line_macos_python.txt
Q: On Windows in python, possibly using the Outlook API, how can I get the full name of a user from their smaller login name? At work, we have short login names, e.g. hastingsg, but Outlook and I believe other parts of the Windows system also have access to a longer name, e.g. Jeff Hastings. In cpython (not IronPytho...
On Windows in python, possibly using the Outlook API, how can I get the full name of a user from their smaller login name?
At work, we have short login names, e.g. hastingsg, but Outlook and I believe other parts of the Windows system also have access to a longer name, e.g. Jeff Hastings. In cpython (not IronPython), if I have the shorter login name, how can I get the longer full name? I have pywin32 and ExchangeCDO installed.
[ "Via the COM parts of pywin32, you need to get Outlook's Application object, and from it its attribute Session, which gives you the Namespace object (the GetNamespace method should also work for the same purpose, when called with the only supported argument value, 'MAPI'). From there you can use the Accounts prope...
[ 2, 1, 0 ]
[]
[]
[ "outlook", "python", "pywin32", "windows" ]
stackoverflow_0001720077_outlook_python_pywin32_windows.txt
Q: Remove first 4 letters from a folder name using Bash scripting As the title says I want to remove the first 4 letters from a folder name using a Bash script. If you have another way to do it in Linux I don't really mind e.g. Python. Also I need the script to be executed regularly (daily). A: Another way in Bash:...
Remove first 4 letters from a folder name using Bash scripting
As the title says I want to remove the first 4 letters from a folder name using a Bash script. If you have another way to do it in Linux I don't really mind e.g. Python. Also I need the script to be executed regularly (daily).
[ "Another way in Bash:\n$ dname=mydirectory\n$ echo ${dname:4}\nrectory\n\n", "Since you don't mention to rename a directory or so, I assume you want simple string editing. If you want more, you should ask the right questions.\n# name of the DIRECTORY (not ''folder''...)\nname=fooodir\n\n# compute a new name\nedit...
[ 9, 3 ]
[]
[]
[ "bash", "linux", "python" ]
stackoverflow_0001720286_bash_linux_python.txt
Q: how to run parallel job in python I am doing a data mining project in Python, and during the experiment phase I have to run many experiments at the same time. How could I create n processes, so that each process is dedicated to an experiment? Which module I should use? A: Have a look at Does python support multi...
how to run parallel job in python
I am doing a data mining project in Python, and during the experiment phase I have to run many experiments at the same time. How could I create n processes, so that each process is dedicated to an experiment? Which module I should use?
[ "Have a look at Does python support multiprocessor/multicore programming?\nThen look at http://wiki.python.org/moin/ParallelProcessing for more options\nbut generally python multiprocessing(http://docs.python.org/library/multiprocessing.html) module will be enough\n", "Have a look at the multiprocessing module.\n...
[ 7, 6 ]
[]
[]
[ "python" ]
stackoverflow_0001720603_python.txt
Q: Python Twisted and database connections Our projects at work include synchronous applications (short lived) and asynchronous Twisted applications (long lived). We're re-factoring our database and are going to build an API module to decouple all of the SQL in that module. I'd like to create that API so both synchro...
Python Twisted and database connections
Our projects at work include synchronous applications (short lived) and asynchronous Twisted applications (long lived). We're re-factoring our database and are going to build an API module to decouple all of the SQL in that module. I'd like to create that API so both synchronous and asynchronous applications can use it...
[ "twisted.enterprise.adbapi seems the way to go -- do you think it fails to match your requirements, and if so, can you please explain why?\n", "Within Twisted, you basically want a wrapper around a function which returns a Deferred (such as the Twisted DB layer), waits for it's results, and returns them. However...
[ 3, 1, 0, 0 ]
[]
[]
[ "database", "mysql", "python", "twisted" ]
stackoverflow_0001705444_database_mysql_python_twisted.txt
Q: I just installed a Ubuntu Hardy server. In Python, I tried to import _mysql and MySQLdb But, they were unable to be found!? How do I install both of them? A: Have you installed python-mysqldb? If not install it using apt-get install python-mysqldb. And how are you importing mysql.Is it import MySQLdb? Python is ...
I just installed a Ubuntu Hardy server. In Python, I tried to import _mysql and MySQLdb
But, they were unable to be found!? How do I install both of them?
[ "Have you installed python-mysqldb? If not install it using apt-get install python-mysqldb. And how are you importing mysql.Is it import MySQLdb? Python is case sensitive.\n", "This should do the trick.\nsudo apt-get install mysql-server \nsudo apt-get install python-mysqldb\n\n", "I believe this should make...
[ 2, 0, 0 ]
[]
[]
[ "installation", "linux", "python", "unix" ]
stackoverflow_0001720867_installation_linux_python_unix.txt
Q: Is this python code thread-safe? I am trying to make my chunk of code non-thread-safe, in order to toy with some exceptions that I want to add on later. This is my python code: from time import sleep from decimal import * from threading import Lock import random def inc_gen(c): """ Increment generator ...
Is this python code thread-safe?
I am trying to make my chunk of code non-thread-safe, in order to toy with some exceptions that I want to add on later. This is my python code: from time import sleep from decimal import * from threading import Lock import random def inc_gen(c): """ Increment generator """ while True: #getting ...
[ "You have a Read-Modify-Write operation basically. If you want to ensure things go haywire, the best is to intruduce delay between the read and the write.\ndef inc(self):\n v = self.c\n time.sleep(random.random()) # Should probably limit it to a few hundred ms\n self.c = v + 1\n\ndef dec(self):\n v = se...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0001720882_python.txt
Q: How non blocking read/write throught remote FileSystem Is there a way to write and read files on a remote filesystem (such as NFS, SSHFS, or sambafs) in a way that read or write or even open return immediately with an error code? In fact I'm using Twisted and I want to know whether there is a safe way to access re...
How non blocking read/write throught remote FileSystem
Is there a way to write and read files on a remote filesystem (such as NFS, SSHFS, or sambafs) in a way that read or write or even open return immediately with an error code? In fact I'm using Twisted and I want to know whether there is a safe way to access remote files without blocking my reactor.
[ "In Twisted, for remote filesystems just like for any other blocking calls, you can use threads.deferToThread -- a reasonably elegant way to deal with pesky blocking syscalls!-)\n", "This is actually very similar to my question asked here. It seems that the only way to get around the limitations of the operating ...
[ 7, 1 ]
[]
[]
[ "filesystems", "networking", "python", "twisted" ]
stackoverflow_0001682515_filesystems_networking_python_twisted.txt