content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: How to convert an accented character in an unicode string to its unicode character code using Python? Just wonder how to convert a unicode string like u'é' to its unicode character code u'\xe9'? A: You can use Python's repr() function: >>> unicode_char = u'é' >>> repr(unicode_char) "u'\\xe9'" A: ord will give ...
How to convert an accented character in an unicode string to its unicode character code using Python?
Just wonder how to convert a unicode string like u'é' to its unicode character code u'\xe9'?
[ "You can use Python's repr() function:\n>>> unicode_char = u'é'\n>>> repr(unicode_char)\n\"u'\\\\xe9'\"\n\n", "ord will give you the numeric value, but you'll have to convert it into hex:\n>>> ord(u'é')\n233\n\n", "u'é' and u'\\xe9' are exactly the same, they are just different representations:\n>>> u'é' == u'\...
[ 3, 1, 1 ]
[]
[]
[ "character", "codepoint", "diacritics", "python", "unicode" ]
stackoverflow_0003499087_character_codepoint_diacritics_python_unicode.txt
Q: Trouble installing Django I'm having trouble installing Django, even if I follow the instructions here: http://www.djangobook.com/en/2.0/chapter02/ Could someone please provide baby steps to installing Django. I'm talking baby steps that really break it down, so that a retarded person could do it. I've installed D...
Trouble installing Django
I'm having trouble installing Django, even if I follow the instructions here: http://www.djangobook.com/en/2.0/chapter02/ Could someone please provide baby steps to installing Django. I'm talking baby steps that really break it down, so that a retarded person could do it. I've installed Django and unzipped the file, bu...
[ "OK. If you have Python installed, you can then proceed to execute setup.py given with Django. Head over to the directory where you unzipped Django.\ncd C:\\path\\to\\Django\\\n\nYou can now execute \npython setup.py install\n\nThis step requires your python executable to be present in the system's PATH environment...
[ 3 ]
[]
[]
[ "django", "installation", "python" ]
stackoverflow_0003500371_django_installation_python.txt
Q: Way to get value of this hex number import binascii f = open('file.ext', 'rb') print binascii.hexlify(f.read(4)) f.close() This prints: 84010100 I know that I must retrieve the hex number 184 out of this data. How can it be done in python? I've used the struct module before, but I don't know if its little endi...
Way to get value of this hex number
import binascii f = open('file.ext', 'rb') print binascii.hexlify(f.read(4)) f.close() This prints: 84010100 I know that I must retrieve the hex number 184 out of this data. How can it be done in python? I've used the struct module before, but I don't know if its little endian, big..whatever.. how can I get 184 fro...
[ ">>> x = b'\\x84\\x01\\x01\\x00'\n>>> import struct\n>>> struct.unpack_from('<h', x)\n(388,)\n>>> map(hex, struct.unpack_from('<h', x))\n['0x184']\n\n< means little endian, h means read a 16-bit integer (\"short\"). Detail is in the package doc.\n" ]
[ 2 ]
[]
[]
[ "binary", "python" ]
stackoverflow_0003500493_binary_python.txt
Q: Interacting with SVN from appengine I've got a couple of projects where it would be useful to be able to interact with an SVN server from Google App Engine. Pull specific files from the SVN (fairly easy, since there is a web interface which I can grab the data off automatically, but how do I authenticate) Commit ...
Interacting with SVN from appengine
I've got a couple of projects where it would be useful to be able to interact with an SVN server from Google App Engine. Pull specific files from the SVN (fairly easy, since there is a web interface which I can grab the data off automatically, but how do I authenticate) Commit changes to the SVN (this is the really ha...
[ "you can try using SVNKit with the java runtime\n", "DryDrop (http://drydrop.binaryage.com/) is a Git based solution you may want to look at for comparison of what you're trying to do.\n", "You can talk to a svn server(if setup with apache running mod_dav_svn) using the webdav protocol. See apache's implementat...
[ 4, 3, 1 ]
[]
[]
[ "google_app_engine", "java", "python", "svn" ]
stackoverflow_0001604220_google_app_engine_java_python_svn.txt
Q: Python Console Name Customization Usually the Python console looks like this: >>> command Is there a way to make it look like: SomeText>>> command A: sys.ps1 == ">>>" sys.ps2 == "..." You can also change this in the PYTHONSTARTUP environment variable. For example (this is not secure), put the following in a sc...
Python Console Name Customization
Usually the Python console looks like this: >>> command Is there a way to make it look like: SomeText>>> command
[ "sys.ps1 == \">>>\"\nsys.ps2 == \"...\"\n\nYou can also change this in the PYTHONSTARTUP environment variable.\nFor example (this is not secure), put the following in a script somewhere and set PYTHONSTARTUP to point at that script.\nimport sys\nimport getpass\nsys.ps1 = getpass.getuser( ) + \">>> \"\n\nOf course,...
[ 6, 2, 0 ]
[]
[]
[ "command_line_interface", "console", "customization", "python" ]
stackoverflow_0003500799_command_line_interface_console_customization_python.txt
Q: Your typical sheep counting regular expression in python question at night, after saying my prayers, i typically count sheep to help me fall asleep. i want a regular expression to help me with the correct count. i want the following strings to match 0 1sheep 2sheepsheep 3sheepsheepsheep and so on. what is the reg...
Your typical sheep counting regular expression in python question
at night, after saying my prayers, i typically count sheep to help me fall asleep. i want a regular expression to help me with the correct count. i want the following strings to match 0 1sheep 2sheepsheep 3sheepsheepsheep and so on. what is the regular expression for this? something like '(\d+)(sheep){\1}' if {\1} wou...
[ "Python's regular expression engine does not support parsing a matched subexpression to a repetition count, and I don't think this should be done with RegExp either. \nThe best bet is to combine RegExp matching and checking with code:\nrx = re.compile(r'^(\\d+)((?:sheep)*)$')\nm = rx.match(theString)\nif m and len(...
[ 3, 2, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003500753_python_regex.txt
Q: suitable replacement for python expression I want to replace the next expression with something simpler but i'm not sure what my changes impli? if not (self.permission_index_link == 0) \ or not (self.permission_index_link == 8): with if not self.permission_index_link == (0,8): ...
suitable replacement for python expression
I want to replace the next expression with something simpler but i'm not sure what my changes impli? if not (self.permission_index_link == 0) \ or not (self.permission_index_link == 8): with if not self.permission_index_link == (0,8):
[ "if self.permission_index_link not in (0,8):\n # code\n\nIs this what you are looking for? code will run if self.permission_index_link is not 0 or 8. \n", "Are you sure your initial expression is correct? It will always be true. Didn't you mean to use and rather than or?\nUse the not in operator:\nif self.perm...
[ 2, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003501007_python.txt
Q: Question about bdist directory hierarchy I just made a small app and then wrote a setup.py file for it. Everything seems to be working, except I can't figure out a small thing. When passing the bdist option to setup.py, it creates the archive gzipped tar file. When I open that file, I notice that the directory str...
Question about bdist directory hierarchy
I just made a small app and then wrote a setup.py file for it. Everything seems to be working, except I can't figure out a small thing. When passing the bdist option to setup.py, it creates the archive gzipped tar file. When I open that file, I notice that the directory structure is: > usr > lib > python2.6 ...
[ "I think that you want an sdist output .... so try python setup.py sdist\nQuote of Python documentation\n\nAs a simple example, if I run the following command in the Distutils source tree:\n\npython setup.py bdist\n\n\nthen the Distutils builds my module distribution (the Distutils itself in this case), does a “fak...
[ 2 ]
[]
[]
[ "distutils", "python" ]
stackoverflow_0003483243_distutils_python.txt
Q: Finding a function's parameters in Python I want to be able to ask a class's __init__ method what it's parameters are. The straightforward approach is the following: cls.__init__.__func__.__code__.co_varnames[:code.co_argcount] However, that won't work if the class has any decorators. It will give the parameter...
Finding a function's parameters in Python
I want to be able to ask a class's __init__ method what it's parameters are. The straightforward approach is the following: cls.__init__.__func__.__code__.co_varnames[:code.co_argcount] However, that won't work if the class has any decorators. It will give the parameter list for the function returned by the decorato...
[ "Consider this decorator:\ndef rickroll(old_function):\n return lambda junk, junk1, junk2: \"Never Going To Give You Up\"\n\nclass Foo(object):\n @rickroll\n def bar(self, p1, p2):\n return p1 * p2\n\nprint Foo().bar(1, 2)\n\nIn it, the rickroll decorator takes the bar method, discards it, replaces ...
[ 3 ]
[]
[]
[ "closures", "decorator", "function", "python" ]
stackoverflow_0003375573_closures_decorator_function_python.txt
Q: Fill a Form on the same page with different classes - write to DB and display values I have a model with 5 entities and intend to create a form (on the same page) but do not know how to integrate more than one form. In my main, i can play very well with the forms and write to database, but I need to put more fie...
Fill a Form on the same page with different classes - write to DB and display values
I have a model with 5 entities and intend to create a form (on the same page) but do not know how to integrate more than one form. In my main, i can play very well with the forms and write to database, but I need to put more fields on the page. These fields are of different models. ** My models: Teacher, Account...
[ "If I understood you correctly what you can do is create forms for each model and display them in the template having a single save button. Now when submitted, in your view you can validate each form and add or update the db as required.\nHere is a link to an answer to a question similar to what you have asked..\nD...
[ 1 ]
[]
[]
[ "djangoappengine", "google_app_engine", "python" ]
stackoverflow_0003488658_djangoappengine_google_app_engine_python.txt
Q: AttributeError: 'file' object has no attribute 'open' in Django while assigning a local file to the FileField Possible Duplicate: How to assign a local file to the FileField in Django? I was trying to assign a file from my disk to the FileField, but I have this error: AttributeError: 'file' object has no attribu...
AttributeError: 'file' object has no attribute 'open' in Django while assigning a local file to the FileField
Possible Duplicate: How to assign a local file to the FileField in Django? I was trying to assign a file from my disk to the FileField, but I have this error: AttributeError: 'file' object has no attribute 'open' My python code: pdfImage = FileSaver() myPdfFile = open('mytest.pdf') pdfImage.myfile.save('new', myPdfF...
[ "See http://www.nitinh.com/2009/02/django-example-filefield-and-imagefield/. You need to pass save a Django request.\n" ]
[ 0 ]
[]
[]
[ "django", "file", "filefield", "python" ]
stackoverflow_0003502128_django_file_filefield_python.txt
Q: Webservice with Python client I have a application wrote in Python. Now I must run many instances of this application, but it is one problem. Many instances have one device and access to this device must be synchronised. I think that the best way to synchronise these instances is to build webservice. In which lang...
Webservice with Python client
I have a application wrote in Python. Now I must run many instances of this application, but it is one problem. Many instances have one device and access to this device must be synchronised. I think that the best way to synchronise these instances is to build webservice. In which language you suggest to write webservic...
[ "\nIn which language you suggest to write webservice. \n\nPython/Django\n\nHow my client can edit data in webservice? \n\nRead about REST. A POST request instead of a GET request is an update.\nUse Piston with Django.\n" ]
[ 0 ]
[]
[]
[ "python", "webservice_client" ]
stackoverflow_0003501257_python_webservice_client.txt
Q: Weird idea: C# - declare a method insinde another method Okay, in python one can do this: def foo(monkeys): def bar(monkey): #process and return new monkey processed_monkeys = list() for monkey in monkeys: processed_monkeys += bar(monkey) return processed_monkeys (This is just a st...
Weird idea: C# - declare a method insinde another method
Okay, in python one can do this: def foo(monkeys): def bar(monkey): #process and return new monkey processed_monkeys = list() for monkey in monkeys: processed_monkeys += bar(monkey) return processed_monkeys (This is just a stupid example) I sometimes miss this functionality of declaring...
[ "\n...as the Func or\n Action Delegates are limited to 4\n parameters...\n\nStarting with .NET 4.0, these delegate types are defined for up to something like 17 parameters. You can also define your own quite simply for any arbitrary number of parameters; for example, below I define a delegate that takes 5 paramet...
[ 5, 2, 2, 0, 0 ]
[]
[]
[ "anonymous_methods", "c#", "methods", "python" ]
stackoverflow_0003502457_anonymous_methods_c#_methods_python.txt
Q: Is it good design to create a module-wide logger in python? When coding python, I use the logging module a lot. After some bad experiences and reading articles like this one, I try to prevent import-time executed code wherever possible. However, for the sake of simplicity, I tend to get my logging object right at ...
Is it good design to create a module-wide logger in python?
When coding python, I use the logging module a lot. After some bad experiences and reading articles like this one, I try to prevent import-time executed code wherever possible. However, for the sake of simplicity, I tend to get my logging object right at the beginning of the module file: # -*- coding: utf-8 -*- import ...
[ "It's fine. I even use the same variable name logger. Any logging is better than no logging, but I find it's nice practise to only expose the logger variable, keep the module hidden away so your code only references the logger, and hence the namespace you've designated for the module.\nIf you later need to refine t...
[ 8, 1, 0 ]
[]
[]
[ "coding_style", "import", "logging", "python" ]
stackoverflow_0003502558_coding_style_import_logging_python.txt
Q: python datetime help I have a big search field, where users could type in any peice of text and it would search for it. Now I have a requirement to add in dob to my search. I am not adding a new textbox with a dob picker. I just want users to be able to input a dob in a range of formats and it would figure it out...
python datetime help
I have a big search field, where users could type in any peice of text and it would search for it. Now I have a requirement to add in dob to my search. I am not adding a new textbox with a dob picker. I just want users to be able to input a dob in a range of formats and it would figure it out. IE users can search usin...
[ "Python-dateutil should make your life much easier. \nfrom dateutil.parser import parse as dparse\nfor each in ('25/08/1970', '25-08-1970', '1970/08/25', '1970-08-25'):\n dparse(each)\n\ndparse(each) will return a datetime.datetime instance. You can pick up the date, month and year from the datetime instance.\nU...
[ 2, 1 ]
[]
[]
[ "date_formatting", "datetime", "python" ]
stackoverflow_0003502784_date_formatting_datetime_python.txt
Q: Programmatically working with color gradients I have a python app that uses GIMP gradients to color images. Other than letting the user choose which GIMP gradient to use, the user doesn't have much more control over the coloring. I'm thinking of how to make it easier to let users edit or create color gradients. Ar...
Programmatically working with color gradients
I have a python app that uses GIMP gradients to color images. Other than letting the user choose which GIMP gradient to use, the user doesn't have much more control over the coloring. I'm thinking of how to make it easier to let users edit or create color gradients. Are there preexisting tools for working with creating...
[ "You can get some information about creating gradients from Here and it also provides some example code of how to use it.\n" ]
[ 3 ]
[]
[]
[ "colors", "gimp", "gradient", "python" ]
stackoverflow_0003503158_colors_gimp_gradient_python.txt
Q: how to send EOS message to the bus ok, I have something like this: self.pipeline = gst.Pipeline() self.tee = gst.element_factory_make self.source = gst.element_factory_make('subdevsrc') self.source.set_property('viewfinder-mode', 1) self.source.set_property('camera-device', 1) self.capsf...
how to send EOS message to the bus
ok, I have something like this: self.pipeline = gst.Pipeline() self.tee = gst.element_factory_make self.source = gst.element_factory_make('subdevsrc') self.source.set_property('viewfinder-mode', 1) self.source.set_property('camera-device', 1) self.capsfilter = gst.element_factory_make('capsfi...
[ "\nwell I solved it somehow:\nI added\nself.bus = self.pipeline.get_bus()\nself.bus.connect('message::eos', self.on_eos)\nself.loop = gobject.MainLoop()\n\nand three methods:\ndef location(self, filename):\n self.ready()\n gst.element_unlink_many(self.muxer, self.filesink)\n self.filesink.set_state(gst.STA...
[ 0 ]
[]
[]
[ "gstreamer", "python" ]
stackoverflow_0003495005_gstreamer_python.txt
Q: Using Mechanize to submit a form for web-automation - returning an error for control in form.controls: if control.type == 'text': if 'user' in control.name: control.value = 'blah' if 'mail' in control.name: control.value = 'blah' if control....
Using Mechanize to submit a form for web-automation - returning an error
for control in form.controls: if control.type == 'text': if 'user' in control.name: control.value = 'blah' if 'mail' in control.name: control.value = 'blah' if control.type == 'password': if 'pass' in control.name: con...
[ "Why not just submit the form as it is shown in the documentation sample:\nbr.select_form(name=\"whatever\")\nresponse = br.submit()\n\nClicking on the submit button is just one way to submit the form; using JavaScript is another. So you don't need to go through the trouble of finding the submit control.\n" ]
[ 0 ]
[]
[]
[ "form_submit", "mechanize", "python" ]
stackoverflow_0003502933_form_submit_mechanize_python.txt
Q: What is the difference in Python between a class call and a method call? Being probably one of the worst OOP programmers on the planet, I've been reading through a lot of example code to help 'get' what a class can be used for. Recently I found this example: class NextClass: # define cla...
What is the difference in Python between a class call and a method call?
Being probably one of the worst OOP programmers on the planet, I've been reading through a lot of example code to help 'get' what a class can be used for. Recently I found this example: class NextClass: # define class def printer(self, text): # define method self.me...
[ "There is no difference. instance.method(...) is class.method(instance, ...). But this doesn't go against the Zen, since it says (emphasis mine):\n\nThere should be one-- and preferably only one --obvious way to do it.\n\nThe second way is possible, and everyone with good knowledge of Python should know that (and w...
[ 2, 1, 0 ]
[]
[]
[ "call", "class", "instance", "methods", "python" ]
stackoverflow_0003503179_call_class_instance_methods_python.txt
Q: python html extract tags How would it be possible to do the following: Scan through an html page (preferably through a whole domain (www.python.org) and extract all h1 h2 ...hn Tags and write all Headings to a file. In the correct order: Start with h1 Than h2 until we reach the next h1 A: Use BeautifulSoup o...
python html extract tags
How would it be possible to do the following: Scan through an html page (preferably through a whole domain (www.python.org) and extract all h1 h2 ...hn Tags and write all Headings to a file. In the correct order: Start with h1 Than h2 until we reach the next h1
[ "Use BeautifulSoup or PyQuery.\n", "Given the requirement to scan a whole website, you might want to look into pycurl to grab the files to scrape. Be careful not to hit the site with the equivalent of a DoS attack though.\n" ]
[ 2, 1 ]
[]
[]
[ "html", "python" ]
stackoverflow_0003503329_html_python.txt
Q: Pipe between current process and other process I want to make pipe or queue in Python between one process (current) and other existing in system. how can I make it? I know current and other process ID. I work on Windows 32bit. A: Like this. python one_process.py | python the_other_process.py Make the OS do the ...
Pipe between current process and other process
I want to make pipe or queue in Python between one process (current) and other existing in system. how can I make it? I know current and other process ID. I work on Windows 32bit.
[ "Like this.\npython one_process.py | python the_other_process.py\n\nMake the OS do the work for you.\nIn one_process.py, you write to sys.stdout.\nIn the_other_process.py, you read from sys.stdin.\nThat's it.\n" ]
[ 3 ]
[]
[]
[ "multiprocessing", "python" ]
stackoverflow_0003503236_multiprocessing_python.txt
Q: Elegant way to extract values from a string parsed with a template I have a template like this: foo_tmplte = Template("fieldname_${ln}_${type} = $value") and a lot of strings parsed with this template like this: foo_str1 = "fieldname_ru_ln = journal" foo_str2 = "fieldname_zh_TW_ln = journal" foo_str3 = "fieldname...
Elegant way to extract values from a string parsed with a template
I have a template like this: foo_tmplte = Template("fieldname_${ln}_${type} = $value") and a lot of strings parsed with this template like this: foo_str1 = "fieldname_ru_ln = journal" foo_str2 = "fieldname_zh_TW_ln = journal" foo_str3 = "fieldname_uk_ln = номер запису" Now i want to extract back the variables from th...
[ "Why don't you use regexps? They have named groups and you can extract them in a dictionary.\nTue Aug 17 14:33:58 $ python\nPython 2.6.5 (r265:79063, Jun 12 2010, 17:07:01) \n[GCC 4.3.4 20090804 (release) 1] on cygwin\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import re \n>...
[ 2, 0 ]
[]
[]
[ "python", "templates" ]
stackoverflow_0003502388_python_templates.txt
Q: I change Python code, but can't see results Sorry for totally stupid question, but the situation is that I have to make some changes to the Django website, and I have about zero knowleges in python. I've been reading Django docs and found out where to make changes, but there is very strange situation. When I chang...
I change Python code, but can't see results
Sorry for totally stupid question, but the situation is that I have to make some changes to the Django website, and I have about zero knowleges in python. I've been reading Django docs and found out where to make changes, but there is very strange situation. When I change view, template, config or anything on web site ...
[ "Python web applications typically differ from PHP ones in that the software is not automatically reloaded once you change the source code. This makes sense because initialization, firing up the interpreter etc., doesn't have to be performed at each instance. It's not that the code is \"cached\"; it's only loaded o...
[ 3 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003503484_django_python.txt
Q: Python, With ... as ... AST/Symbol access Disclaimer: Sensible semantics do dictate that the LHS of as behaving differently depending on the RHS lexeme is ludicrous. But I am curious nontheless. Hi guys, Simple question, but one that somone may be able to answer better than my hack. I'm currently messing with met...
Python, With ... as ... AST/Symbol access
Disclaimer: Sensible semantics do dictate that the LHS of as behaving differently depending on the RHS lexeme is ludicrous. But I am curious nontheless. Hi guys, Simple question, but one that somone may be able to answer better than my hack. I'm currently messing with metaclasses etc and working out a comfortable syn...
[ "No, just like (say) in Dog = foo('fido') there is no \"serious\" way in which foo can know its result is about to be bound to name Dog in the caller. (By \"serious\" I'm excluding rummaging in the stack to find out the calling bytecode and disassembling it, &c -- basically the stuff that you know you'd never do i...
[ 1 ]
[]
[]
[ "python", "python_2.6", "python_3.x" ]
stackoverflow_0003503753_python_python_2.6_python_3.x.txt
Q: Getting started with Pylons I am just starting to use a web framework. I have decided I really like python and started looking at web frameworks. I don't really like django for a few reasons, but from what I have tried so far I found I really like pylons. The problem I have is that I can't find that many articles...
Getting started with Pylons
I am just starting to use a web framework. I have decided I really like python and started looking at web frameworks. I don't really like django for a few reasons, but from what I have tried so far I found I really like pylons. The problem I have is that I can't find that many articles/tutorials about pylons, especial...
[ "The book suggested by meder (http://pylonsbook.com/en/1.1/) is a very good start. I upvoted his anwser because that's where I learned Pylons.\nHowever, the book is written for Pylons 0.9.7 (the latest version before 0.10 and 1.0).\nPylons is the agglomeration of several high quality libraries. Learning Pylons is a...
[ 10, 6, 2, 1 ]
[]
[]
[ "authentication", "pylons", "python" ]
stackoverflow_0003428795_authentication_pylons_python.txt
Q: Importing python variables of a program after its execution I've written two python scripts script1.py and script2.py. I want to run script1.py from script2.py and get the content of the variables of script1 created during the execution of script1. Script1 has several functions in which the variables are created i...
Importing python variables of a program after its execution
I've written two python scripts script1.py and script2.py. I want to run script1.py from script2.py and get the content of the variables of script1 created during the execution of script1. Script1 has several functions in which the variables are created including in the main. Thank you for all your answers. I've examin...
[ "From script2 do\nimport script1\n\nThis will run any code inside script1; any global variables will be available as e.g. script1.result_of_calculation. You can set global variables as below.\n\nscript1:\nfrom time import sleep\ndef main( ):\n global result\n sleep( 1 ) # Big calculation here\n result = 3\...
[ 4, 0, 0, 0 ]
[ "Depending on how many variables you want to pass to script2.py you could pass them via arguments and pick them up as an argv array. You could run script1.py then from this script run os.system('script2.py arg0 arg1 arg2 arg3') to call script2.py.\nThen you can pick up your variables in you script2.py by doing this...
[ -2 ]
[ "import", "program_entry_point", "python", "variables" ]
stackoverflow_0003500957_import_program_entry_point_python_variables.txt
Q: SQLCLR & IronPython Im feeling crazy and I've decided I would really like to write a User-Defined Function in Python that would run in SQL Server 2008. I am interested in doing this as I have a few thousand lines of PL/Python functions written for PostgreSQL and I am interested to know if I can get the project run...
SQLCLR & IronPython
Im feeling crazy and I've decided I would really like to write a User-Defined Function in Python that would run in SQL Server 2008. I am interested in doing this as I have a few thousand lines of PL/Python functions written for PostgreSQL and I am interested to know if I can get the project running on SQL Server instea...
[ "According to this article you're wasting your time trying. Apparently you simply can't use dynamic languages in SQL CLR even in UNSAFE assemblies.\n" ]
[ 2 ]
[]
[]
[ "ironpython", "python", "sql_server", "sqlclr" ]
stackoverflow_0003503996_ironpython_python_sql_server_sqlclr.txt
Q: When java program is started using Python's subprocess.Popen() exits, why database connection opened by the subprocess is not closed? We use Robot Framework for test automation, and our jython test code spawns a java subprocess using subprocess.Popen(): cmd = "java -jar program.jar" process = subprocess.Po...
When java program is started using Python's subprocess.Popen() exits, why database connection opened by the subprocess is not closed?
We use Robot Framework for test automation, and our jython test code spawns a java subprocess using subprocess.Popen(): cmd = "java -jar program.jar" process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) process.wait() Java code utilizes a JDBC connection to Oracle dat...
[ "I'm not sure but it's possible that because you're using Jython, the interpreter is given ownership of the connections (and hence they survive until that process dies). Have you tried using process.terminate() after the process.wait()?\n", "Consider using os.kill (which is used by process.terminate in >= 2.6).\n...
[ 2, 1 ]
[]
[]
[ "java", "jython", "python" ]
stackoverflow_0003477440_java_jython_python.txt
Q: Help On Python program that can use to compile python coding into a standalone .exe file I am currently working on a python program with the use of wxpython to make out a gui application. However, i wish to compile my application to be like a standalone application where people can just get the .exe file and run i...
Help On Python program that can use to compile python coding into a standalone .exe file
I am currently working on a python program with the use of wxpython to make out a gui application. However, i wish to compile my application to be like a standalone application where people can just get the .exe file and run it without installing python and wxpython. I am not sure if it is possible, thus i hope that so...
[ "You need to create a frozen binary. You can use py2exe for this purpose.\nFor what it's worth, if you ever need to make executables on a unix system, you can use Freeze, a utility that comes with Python.\n", "For a nice cross-platform solution, I always recommend pyinstaller (actually, I find it better than py2e...
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003503988_python.txt
Q: Problem with inheritance and "self" reference This is my first post, so first of all I want to say a giant "Thank you!" to the community of stackoverflow for all the time an answer did the trick for me :) I have a problem while dealing with python's inheritance. I have a parent class which contains the following c...
Problem with inheritance and "self" reference
This is my first post, so first of all I want to say a giant "Thank you!" to the community of stackoverflow for all the time an answer did the trick for me :) I have a problem while dealing with python's inheritance. I have a parent class which contains the following code: def start(self): pid = os.fork() if (pid...
[ "Don't use TWO leading underscores in your method and other attribute names: they're specifically intended to isolate parent classes from subclasses, which is most definitely what you do not want here! Rename the method in question to _manage_request (single leading underscore) throughout, and live happily ever af...
[ 6 ]
[]
[]
[ "python" ]
stackoverflow_0003504136_python.txt
Q: How to best organize the rules component of a Django system? I'm designing (and ultimately writing) a system in Django that consists of two major components: A Game Manager: this is essentially a data-entry piece. Trusted (non-public) users will enter information on a gaming system, such as options that a player...
How to best organize the rules component of a Django system?
I'm designing (and ultimately writing) a system in Django that consists of two major components: A Game Manager: this is essentially a data-entry piece. Trusted (non-public) users will enter information on a gaming system, such as options that a player may have. The interface for this is solely the Django admin cons...
[ "I would create subdirectory named rules in the app with game logic and there create module named after each game, that you would like serve. Then create a common interface for those modules, that will be utilized by your games and import proper rules module by name (if your game is called adom, then simply __impor...
[ 1, 1 ]
[]
[]
[ "architecture", "code_organization", "django", "python" ]
stackoverflow_0003504405_architecture_code_organization_django_python.txt
Q: Reinstalling python on Mac OS 10.6 with a different gcc version I am trying to install a Python package that requires running gcc 4.2. My gcc is pointing correctly to gcc-4.2, i.e. $ gcc -v Using built-in specs. Target: i686-apple-darwin10 Configured with: /var/tmp/gcc/gcc-5664~38/src/configure --disable-checking...
Reinstalling python on Mac OS 10.6 with a different gcc version
I am trying to install a Python package that requires running gcc 4.2. My gcc is pointing correctly to gcc-4.2, i.e. $ gcc -v Using built-in specs. Target: i686-apple-darwin10 Configured with: /var/tmp/gcc/gcc-5664~38/src/configure --disable-checking --enable-werror --prefix=/usr --mandir=/share/man --enable-languages...
[ "On current OS X Pythons, Distutils tries to ensure that C extension modules are built using the same GCC and MACOSX_DEPLOYMENT_TARGET (ABI) as the Python interpreter itself was. This ensures that there won't be conflicts with the underlying system libraries.\nBut if you are on OS X 10.6, then the Python version y...
[ 3, 1 ]
[]
[]
[ "gcc", "python" ]
stackoverflow_0003500638_gcc_python.txt
Q: Using web2py on Eclipse I am trying to use the steps I found on the net to make web2py work on Eclipse, but I must have something setup wrong because Eclipse gives me error on the imports. For instance the instructions say to do this at the top of controllers: if 0: from gluon.globals import * ...
Using web2py on Eclipse
I am trying to use the steps I found on the net to make web2py work on Eclipse, but I must have something setup wrong because Eclipse gives me error on the imports. For instance the instructions say to do this at the top of controllers: if 0: from gluon.globals import * from gluon.html import * ...
[ "Do these steps first.\nThen do what I have above. Urghhh\n" ]
[ 1 ]
[]
[]
[ "eclipse", "python", "web2py" ]
stackoverflow_0003467546_eclipse_python_web2py.txt
Q: python beautifulsoup adding extra end tags I'm using Beautifulsoup to parse a website request = urllib2.Request(url) response = urllib2.urlopen(request) soup = BeautifulSoup.BeautifulSoup(response) I am using it to traverse a table. The problem I am running into is that BS is adding an extra end tag for t...
python beautifulsoup adding extra end tags
I'm using Beautifulsoup to parse a website request = urllib2.Request(url) response = urllib2.urlopen(request) soup = BeautifulSoup.BeautifulSoup(response) I am using it to traverse a table. The problem I am running into is that BS is adding an extra end tag for the table into the html which doesn't exist, whic...
[ "How about searching directly for each tag instead of trying to traverse into the table?\n for td in soup.find(\"td\"):\n ...\n\nits not unusual to find the tbody tag nested within a table automatically when its not in the code. Either you can code for it or just jump straight to the tr or td tag.\n" ]
[ 1 ]
[]
[]
[ "beautifulsoup", "html_parsing", "python" ]
stackoverflow_0003505003_beautifulsoup_html_parsing_python.txt
Q: best way to parse a language that's ALMOST Python? I'm working on a domain-specific language implemented on top of Python. The grammar is so close to Python's that until now we've just been making a few trivial string transformations and then feeding it into ast. For example, indentation is replaced by #endfor/#en...
best way to parse a language that's ALMOST Python?
I'm working on a domain-specific language implemented on top of Python. The grammar is so close to Python's that until now we've just been making a few trivial string transformations and then feeding it into ast. For example, indentation is replaced by #endfor/#endwhile/#endif statements, so we normalize the indentatio...
[ "PLY works. It's odd because it mimics lex/yacc in a way that's not terribly pythonic. \nBoth lex and yacc have an implicit interface that makes it possible to run the output from lex as a stand-alone program. This \"feature\" is carefully preserved. Similarly for the yacc-like features of PLY. The \"feature\"...
[ 1 ]
[]
[]
[ "parsing", "python" ]
stackoverflow_0003504677_parsing_python.txt
Q: wxPython: centering an image in a panel I have a GridSizer with StaticBitmap images in it. I want to put each of the images in their own panels so I can change the background color to highlight an image if it has been selected. When I try to do this, however, the images are not centered in their panels and the hig...
wxPython: centering an image in a panel
I have a GridSizer with StaticBitmap images in it. I want to put each of the images in their own panels so I can change the background color to highlight an image if it has been selected. When I try to do this, however, the images are not centered in their panels and the highlighted background color is only present on ...
[ "You need to add your image to a boxSizer with a border.\nYou could write an imagePanel class to implement this.\nYou should then be able to call SetBackgroundColour on your ImgPanels to change the borders (panels) colour when ever you need to.\nHere's a very rough example for an ImgPanel class\nclass ImgPanel(wx....
[ 6 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0003502772_python_wxpython.txt
Q: Extending the code of Python - adding language features I have been programming in python exclusively for 4 years and have never really looked under the hood at the C code in which python is written. I have recently been looking into a problem that would involve modifying python at that level. The code seems pret...
Extending the code of Python - adding language features
I have been programming in python exclusively for 4 years and have never really looked under the hood at the C code in which python is written. I have recently been looking into a problem that would involve modifying python at that level. The code seems pretty consistent, and thus relatively easily understood. Howeve...
[ "This article may help you get started. It takes a lot of information from the excellent PEP 339 - Design of the CPython Compiler.\n", "http://docs.python.org/extending/index.html - Custom modules/extensions\nhttp://docs.python.org/c-api/index.html - C API, under the hood\n", "There's not too much written lore ...
[ 3, 1, 1 ]
[]
[]
[ "c", "core", "python" ]
stackoverflow_0003505029_c_core_python.txt
Q: Django maximum recursion depth exceeded I'm building a small web project using Django that has one model (Image) that contains an ImageField. When I try to upload an image using the admin interface I am presented with this problem (personally identifying information removed): RuntimeError at /admin/main/image/add/...
Django maximum recursion depth exceeded
I'm building a small web project using Django that has one model (Image) that contains an ImageField. When I try to upload an image using the admin interface I am presented with this problem (personally identifying information removed): RuntimeError at /admin/main/image/add/ maximum recursion depth exceeded Request M...
[ "You need return self.printTag() not return self.printTag(self)\n" ]
[ 4 ]
[]
[]
[ "apache", "django", "python", "recursion" ]
stackoverflow_0003505467_apache_django_python_recursion.txt
Q: Python : Text to ASCII & ASCII to text converter program i am a newbie to python 2.7 , trying to create a simple program, which takes an input string from the user, converts all the characters into their ascii values, adds 2 to all the ascii values and then converts the new values into text. So for example, if the...
Python : Text to ASCII & ASCII to text converter program
i am a newbie to python 2.7 , trying to create a simple program, which takes an input string from the user, converts all the characters into their ascii values, adds 2 to all the ascii values and then converts the new values into text. So for example, if the user input is "test" , the output should be "vguv". This is t...
[ "message2 = ord(ch) + 2 makes message2 an integer, and so of course you cannot then call split on it -- it's a single int representing a single character, why ever would you want to split it?! Plus, you're resetting encodedmessage to the empty string each time through the loop, so once you've fixed the split weird...
[ 2, 1, 1 ]
[]
[]
[ "ascii", "python" ]
stackoverflow_0003505567_ascii_python.txt
Q: Dynamically adding checkboxes with PyQt4 I have a simple GUI built using python and PyQt4. After the user enters something into the program, the program should then add a certain number of checkboxes to the UI depending on what the user's input was. For testing purposes, I have one checkbox existing in the appli...
Dynamically adding checkboxes with PyQt4
I have a simple GUI built using python and PyQt4. After the user enters something into the program, the program should then add a certain number of checkboxes to the UI depending on what the user's input was. For testing purposes, I have one checkbox existing in the application from start, and that checkbox is nested...
[ "I think you're making life hard for yourself by copying QtCreator's output style. I think it's important to manually code some UIs to see how it works. I suspect you're not adding the check box to the layout. Try something this (Import * used for clarity here):\n\nimport sys\nfrom PyQt4.QtGui import *\nfrom PyQt4....
[ 2, 1 ]
[]
[]
[ "checkbox", "dynamic", "pyqt4", "python", "user_interface" ]
stackoverflow_0003496220_checkbox_dynamic_pyqt4_python_user_interface.txt
Q: files getting wrongly cached by the web server while using standard python file operations (Django) I have a Django app, which populates content from a text file, and populates them using the initial option in a standard form. The file gets updated on the server, but when the form gets refreshed, it picks up conte...
files getting wrongly cached by the web server while using standard python file operations (Django)
I have a Django app, which populates content from a text file, and populates them using the initial option in a standard form. The file gets updated on the server, but when the form gets refreshed, it picks up content from the a previously saved version, or the version before the Apache WebServer was reloaded. This mea...
[ "The issue is simply that all the parameters to fields are evaluated at form definition time. So, the initial value for domains is set to whatever the return value is from spamsource() at the time the form is defined, ie usually when the server is started.\nOne way of fixing this would be to override the form's __i...
[ 3, 0 ]
[]
[]
[ "caching", "django", "file", "python" ]
stackoverflow_0003431124_caching_django_file_python.txt
Q: PyQt4 Threading: Sending data back to a thread I'm writing a program, with a PyQt frontend. To ensure that the UI doesn't freeze up, I use QThreads to emit signals back to the parent. Now, I have reached a point where I need my thread to stop running, emit a signal back to the parent, then wait on the parent to ...
PyQt4 Threading: Sending data back to a thread
I'm writing a program, with a PyQt frontend. To ensure that the UI doesn't freeze up, I use QThreads to emit signals back to the parent. Now, I have reached a point where I need my thread to stop running, emit a signal back to the parent, then wait on the parent to return an approval for the thread to continue (after...
[ "One approach is using a condition variable.\nIn my code, however, I prefer using Python's built-in Queue objects to synchronize data between threads. While I'm at it, I use Python's threads as opposed to PyQt threads, mainly because it allows me to reuse the non-GUI part of the code without an actual GUI.\n" ]
[ 1 ]
[]
[]
[ "multithreading", "pyqt4", "python", "signals", "user_interface" ]
stackoverflow_0003505982_multithreading_pyqt4_python_signals_user_interface.txt
Q: Django: Managing Session Variables to manage the browser back button I am creating a web based Mock test paper, which needs to be fairly secure. The needs are Each question can be attempted and answered just once. All are multiple Choice questions Once a question is answered and the submit pressed, then that ses...
Django: Managing Session Variables to manage the browser back button
I am creating a web based Mock test paper, which needs to be fairly secure. The needs are Each question can be attempted and answered just once. All are multiple Choice questions Once a question is answered and the submit pressed, then that session must expire, and the same question must not appear either through bac...
[ "\nAnd how do you ensure that by pressing the back button, you are not able to access a question attempted and answered?\n\nPost-Redirect-Get. http://en.wikipedia.org/wiki/Post/Redirect/Get\n\nHow do you automatically kill the session, once the submit button is pressed?\n\nDoesn't really make sense. You don't nee...
[ 3 ]
[]
[]
[ "django", "django_sessions", "python", "session" ]
stackoverflow_0003506112_django_django_sessions_python_session.txt
Q: Static class members python So I'm using static class members so I can share data between class methods and static methods of the same class (there will only be 1 instantiation of the class). I understand this fine, but I'm just wondering when the static members get initialized? Is it on import? On the first use o...
Static class members python
So I'm using static class members so I can share data between class methods and static methods of the same class (there will only be 1 instantiation of the class). I understand this fine, but I'm just wondering when the static members get initialized? Is it on import? On the first use of the class? Because I'm going to...
[ "They will be initialized at class definition time, which will happen at import time if you are importing the class as part of a module. This assuming a \"static\" class member definition style like this:\nclass Foo:\n bar = 1\n\nprint Foo.bar # prints '1'\n\nNote that, this being a static class member, there i...
[ 16 ]
[]
[]
[ "python", "static", "static_variables" ]
stackoverflow_0003506150_python_static_static_variables.txt
Q: What is the best way to sort items on one of the items values I have two instances of an object in a list class Thing(): timeTo = 0 timeFrom = 0 name = "" o1 = Thing() o1.name = "One" o1.timeFrom = 2 o2 = Thing() o2.timeTo = 20 o2.name = "Two" myList = [o1, o2] biggestIndex = (myList[0].timeFrom...
What is the best way to sort items on one of the items values
I have two instances of an object in a list class Thing(): timeTo = 0 timeFrom = 0 name = "" o1 = Thing() o1.name = "One" o1.timeFrom = 2 o2 = Thing() o2.timeTo = 20 o2.name = "Two" myList = [o1, o2] biggestIndex = (myList[0].timeFrom < myList[1].timeTo) & 1 bigger = myList.pop(biggestIndex) lesser...
[ "The best solution is to make Thing instances sortable. You do this by implementing __lt__:\nclass Thing():\n timeTo = 0\n timeFrom = 0\n name = \"\"\n\n def __lt__(self, other):\n return self.timeFrom < other.timeTo\n\n\nlesser, bigger = sorted(myList)\n\nPython2 has lesser, bigger = sorted...
[ 2, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003503859_python.txt
Q: Special type of combination using itertools I am almost finished with a task someone gave me that at first involved easy use of the product() function from itertools. However, the person asked that it should also do something a bit different like: li = [[1, 2, 3], [4, 5, 6]] A regular product() would give someth...
Special type of combination using itertools
I am almost finished with a task someone gave me that at first involved easy use of the product() function from itertools. However, the person asked that it should also do something a bit different like: li = [[1, 2, 3], [4, 5, 6]] A regular product() would give something like: [1, 4], [1, 5], [1, 6], [2, 4], [2, 5],...
[ "I wondering what is the magical computations you performing, but it look's like that's your formula:\nk = int(raw_input('From What row items should be appeared again at the end?'))\nres = [l for l in product(*(li+[li[k]])) if l[k]<l[len(li)] ]\n\n", "Generalized for more than two sublist (map function would be t...
[ 1, 1 ]
[]
[]
[ "python", "python_itertools" ]
stackoverflow_0003506210_python_python_itertools.txt
Q: how to make a 3d effect on bars in matplotlib? I have a very simple basic bar's graphic like this one but i want to display the bars with some 3d effect, like this I just want the bars to have that 3d effect...my code is: fig = Figure(figsize=(4.6,4)) ax1 = fig.add_subplot(111,ylabel="Valeur",xlabel="Code",auto...
how to make a 3d effect on bars in matplotlib?
I have a very simple basic bar's graphic like this one but i want to display the bars with some 3d effect, like this I just want the bars to have that 3d effect...my code is: fig = Figure(figsize=(4.6,4)) ax1 = fig.add_subplot(111,ylabel="Valeur",xlabel="Code",autoscale_on=True) width = 0.35 ind = np.arange(len(val...
[ "I certainly understand your reason for needing a 3d bar plot; i suspect that's why they were created. \nThe libraries ('toolkits') in Matplotlib required to create 3D plots are not third-party libraries, etc., rather they are included in the base Matplotlib installation. \n(This is true for the current stable vers...
[ 11, 1 ]
[]
[]
[ "3d", "bar_chart", "matplotlib", "python" ]
stackoverflow_0003501771_3d_bar_chart_matplotlib_python.txt
Q: How is memcache.incr() affected by App Engine maintenance periods? I'm working on an application that will run on Google App Engine. I would like it to respond gracefully to App Engine maintenance periods. According to the documentation, memcache will simply not store or retrieve data during maintenance periods: ...
How is memcache.incr() affected by App Engine maintenance periods?
I'm working on an application that will run on Google App Engine. I would like it to respond gracefully to App Engine maintenance periods. According to the documentation, memcache will simply not store or retrieve data during maintenance periods: During a read-only maintenance period, calls to the memcache API will ...
[ "The documentation for incr() states:\n\nThe return value is a new long integer value, or None if key was not in the cache or could not be incremented for any other reason.\n\nAs the documentation also makes clear that you're unable to set or get data during maintenance, and incr() is really just a helper function ...
[ 3 ]
[]
[]
[ "google_app_engine", "maintenance_mode", "memcached", "python" ]
stackoverflow_0003506503_google_app_engine_maintenance_mode_memcached_python.txt
Q: Using RSA in Python I am using RSA to encrypt/decrypt my session keys in Python. I am using Pycrypto library. After generating the keypair, I want to extract the private key and public key from that generated key and store them in different files. How can I do this? I can see the has Private method which can tell ...
Using RSA in Python
I am using RSA to encrypt/decrypt my session keys in Python. I am using Pycrypto library. After generating the keypair, I want to extract the private key and public key from that generated key and store them in different files. How can I do this? I can see the has Private method which can tell that the generated keypai...
[ "If you want to get the different parts from the key, there is key attribute for that:\n>>> from Crypto.PublicKey import RSA\n>>> RSAkey = RSA.generate(1024)\n>>> getattr(RSAkey.key, 'n')\n13773...L\n>>> getattr(RSAkey.key, 'p')\n11731...L\n>>> getattr(RSAkey.key, 'q')\n11740...L\n\nAvailable components are 'n', 'e...
[ 41 ]
[]
[]
[ "pycrypto", "python", "rsa" ]
stackoverflow_0003504955_pycrypto_python_rsa.txt
Q: How to align the text in a wx.ListBox using wxPython? I want the text of the ListBox to be centered, is that possible? A: No, the default ListBox won't work for that. Try the VListBox instead.
How to align the text in a wx.ListBox using wxPython?
I want the text of the ListBox to be centered, is that possible?
[ "No, the default ListBox won't work for that. Try the VListBox instead.\n" ]
[ 1 ]
[]
[]
[ "alignment", "center", "listbox", "python", "wxpython" ]
stackoverflow_0003483179_alignment_center_listbox_python_wxpython.txt
Q: What are the most interesting projects surrounding python? There are many neat projects around that are extending the usefulness of python inside and outside the core language and standard library. Some that come to mind are: pypy stackless twisted unladen swallow web frameworks numpy function annotations other ...
What are the most interesting projects surrounding python?
There are many neat projects around that are extending the usefulness of python inside and outside the core language and standard library. Some that come to mind are: pypy stackless twisted unladen swallow web frameworks numpy function annotations other interesting ideas What are some of the projects that get you ex...
[ "My favorites:\n\nFull-featured web frameworks like Django - making basic web development really easy.\nPyQt - binding the full power of the Qt framework to Python\nPygame - easy and fun game development\nmatplotlib - publication-quality scientific plots for any purpose\n\n", "Sage: \"Sage is a free open-source ...
[ 4, 1, 1, 0, 0, 0 ]
[]
[]
[ "projects", "python" ]
stackoverflow_0003504842_projects_python.txt
Q: mongodb union $or problems I have a collection which is an action log between two users. It has a src_id and a dest_id. I'm a looking to fetch all the records that are actions between id1 and a list of ids - "ids = [id2, id3, id4]". The following two statements work properly: act_obs = self.db.action_log.find( ...
mongodb union $or problems
I have a collection which is an action log between two users. It has a src_id and a dest_id. I'm a looking to fetch all the records that are actions between id1 and a list of ids - "ids = [id2, id3, id4]". The following two statements work properly: act_obs = self.db.action_log.find( {'src_id': id1, 'dest_id':...
[ "I don't think that you can use $or like that. You will have to perform the union client side.\n", "The $or operator is available in MongoDB 1.5.3 and later. \nAn alternative is to use a Javascript function, something like...\nfind = self.db.action_log.find()\nfind.where(pymongo.code.Code('this.dest_id==1 || this...
[ 0, 0 ]
[]
[]
[ "mongodb", "pymongo", "python" ]
stackoverflow_0003436386_mongodb_pymongo_python.txt
Q: Enthought Python, Sage, or others (in Unix clusters) I have access to a cluster of Unix machines, but they don't have the software I need (numpy, scipy, matplotlib, etc), so I have to install them by myself (I don't have root permissions, either, so commands like apt-get or yast don't work). In the worst case, I w...
Enthought Python, Sage, or others (in Unix clusters)
I have access to a cluster of Unix machines, but they don't have the software I need (numpy, scipy, matplotlib, etc), so I have to install them by myself (I don't have root permissions, either, so commands like apt-get or yast don't work). In the worst case, I will have to compile them all from source. Is there any bet...
[ "EPD (Enthought Python Distribution) is great, but even for academics, you can only get the 32-bit version free of charge. If you intend to do anything ram-intensive, it's not really an option.\nEdit: This has since changed, and the 64-bit version is freely available for academic/educational use.\nOn the other han...
[ 9, 6, 3, 3, 3, 1, 1 ]
[]
[]
[ "numpy", "python", "scipy", "unix" ]
stackoverflow_0002751058_numpy_python_scipy_unix.txt
Q: Python RTF Multi Column layout Can anybody reccomend a way of generating a multi column RTF document with python, i was going to use PyRTF but i cant find any documentation on how to set up columns. i think i might need to edit the modules source any reccomendations? A: Managed to patch it up quite easily after ...
Python RTF Multi Column layout
Can anybody reccomend a way of generating a multi column RTF document with python, i was going to use PyRTF but i cant find any documentation on how to set up columns. i think i might need to edit the modules source any reccomendations?
[ "Managed to patch it up quite easily after a few technical difficulties\nhttp://www.importsoul.net/python/pyrtf/\n", "PyRTF is abandonware and doesn't realy have anything in the way of documentation other than the examples. I don't know about columns, but it does support tables so you might be able to achieve the...
[ 2, 1 ]
[]
[]
[ "python", "rtf" ]
stackoverflow_0003501068_python_rtf.txt
Q: Add one to a function call in python What does the last line, return 1 + .... do ? How can you return 1 plus a function call? Below is the assignments text: These functions recursively count the number of instances of the key in the target string def countSubStringMatchRecursive(target, key): currentPositio...
Add one to a function call in python
What does the last line, return 1 + .... do ? How can you return 1 plus a function call? Below is the assignments text: These functions recursively count the number of instances of the key in the target string def countSubStringMatchRecursive(target, key): currentPosition = find(target, key) if find(target, ...
[ "The last line isn't returning \"1 plus a function call\", it is returning 1 + the return value of the function, which is either 0 or 1 depending on whether the condition has been met.\nIt is recursive, in that the return value from the function call will be 1 + the return value of another function call -- again, a...
[ 2, 1, 1 ]
[]
[]
[ "function", "python" ]
stackoverflow_0003507525_function_python.txt
Q: How can I discover classes in a specific package in python? I have a package of plug-in style modules. It looks like this: /Plugins /Plugins/__init__.py /Plugins/Plugin1.py /Plugins/Plugin2.py etc... Each .py file contains a class that derives from PluginBaseClass. So I need to list every module in the Plugi...
How can I discover classes in a specific package in python?
I have a package of plug-in style modules. It looks like this: /Plugins /Plugins/__init__.py /Plugins/Plugin1.py /Plugins/Plugin2.py etc... Each .py file contains a class that derives from PluginBaseClass. So I need to list every module in the Plugins package and then search for any classes that implement PluginB...
[ "Edit: here's a revised solution. I realised I was making a mistake while testing my previous one, and it doesn't really work the way you would expect. So here is a more complete solution:\nimport os\nfrom imp import find_module\nfrom types import ModuleType, ClassType\n\ndef iter_plugins(package):\n \"\"\"Recei...
[ 7, 6, 2, 1 ]
[]
[]
[ "python", "reflection" ]
stackoverflow_0003507125_python_reflection.txt
Q: Python and C++ integration. Python prints string as multiple lines I'm trying to write a program in python to run a program in C++. It wasn't working right, so I made the most basic version of each I could. The C++ program merely takes in a string from stdin, and then prints it out. The Python code is written as ...
Python and C++ integration. Python prints string as multiple lines
I'm trying to write a program in python to run a program in C++. It wasn't working right, so I made the most basic version of each I could. The C++ program merely takes in a string from stdin, and then prints it out. The Python code is written as follows: import popen2, string, StringIO fin, fout = popen2.popen2("PyT...
[ "In C++, std::cin >> mystring uses spaces as separators. Use std::getline instead if you want to gobble up a whole line at a time.\n" ]
[ 2 ]
[]
[]
[ "popen", "python", "stdio", "string", "whitespace" ]
stackoverflow_0003506850_popen_python_stdio_string_whitespace.txt
Q: Are there frameworks for Jython or JRuby, or is it you can run a py or ruby app on the JVM? Are there specific frameworks for Jython or JRuby, or is it you can run a py or ruby app on the JVM? i.e. you take your python django app, and you can run in on tomcat using jython? Sorry little confused. A: JRuby 1.5.X ...
Are there frameworks for Jython or JRuby, or is it you can run a py or ruby app on the JVM?
Are there specific frameworks for Jython or JRuby, or is it you can run a py or ruby app on the JVM? i.e. you take your python django app, and you can run in on tomcat using jython? Sorry little confused.
[ "JRuby 1.5.X is compatible with Ruby 1.8.7, and pretty much anything you write in Ruby will work in JRuby. This includes applications written in frameworks such as Ruby on Rails, which can be converted to a war file and deployed to Tomcat. In fact the NetBeans IDE comes with Ruby on Rails support and by default you...
[ 2, 1 ]
[]
[]
[ "java", "jruby", "jvm", "jython", "python" ]
stackoverflow_0003322164_java_jruby_jvm_jython_python.txt
Q: Controlling the instantiation of python object My question does not really have much to do with sqlalchemy but rather with pure python. I'd like to control the instantiation of sqlalchemy Model instances. This is a snippet from my code: class Tag(db.Model): __tablename__ = 'tags' query_class = TagQuery ...
Controlling the instantiation of python object
My question does not really have much to do with sqlalchemy but rather with pure python. I'd like to control the instantiation of sqlalchemy Model instances. This is a snippet from my code: class Tag(db.Model): __tablename__ = 'tags' query_class = TagQuery id = db.Column(db.Integer, primary_key=True) n...
[ "I use class method for that.\nclass Tag(Declarative):\n ...\n @classmethod\n def get(cls, tag_name):\n tag = cls.query.filter(cls.name == tag_name).first()\n if not tag:\n tag = cls(tag_name)\n return tag\n\nAnd then \ndef _set_tags(self, taglist):\n self._tags = []\n ...
[ 3, 2, 1 ]
[]
[]
[ "metaprogramming", "python", "sqlalchemy" ]
stackoverflow_0003506498_metaprogramming_python_sqlalchemy.txt
Q: Paragraph translation in Python/Django I translated a site using django i18n, I have no problems for menus, little paragraph, etc.. The thing I dont understand is for translating big paragraph. On my site, the admin can write some news by administration page, but he wants them in differents languages. I can imagin...
Paragraph translation in Python/Django
I translated a site using django i18n, I have no problems for menus, little paragraph, etc.. The thing I dont understand is for translating big paragraph. On my site, the admin can write some news by administration page, but he wants them in differents languages. I can imagine some methods to do that : one field per l...
[ "I'm not 100% sure what you're asking for, but it sounds like you have a model called News that you want to be multilingual aware.\nThere is a page on the Django wiki that covers some differing approaches to the problem of storing multilingual content in models, including the one you describe of having a field for ...
[ 0 ]
[]
[]
[ "django", "internationalization", "python" ]
stackoverflow_0003507526_django_internationalization_python.txt
Q: Trouble Updating Label Text Environment: Built interface using Glade3. Backend is written in Python using the GTK+ Builder library. - Although I know the method I need to use to update a label's text (label.set_text("string")), I'm having trouble obtaining the label object in the python code. Here's what my cod...
Trouble Updating Label Text
Environment: Built interface using Glade3. Backend is written in Python using the GTK+ Builder library. - Although I know the method I need to use to update a label's text (label.set_text("string")), I'm having trouble obtaining the label object in the python code. Here's what my code looks like: #!/usr/bin/python #...
[ "The widget parameter to on_button1_clicked is a gtk.Button, not a gtk.Label. gtk.Button has a convenience api method called set_label().\nThis only works if the child of Gtk.Button is a gtk.Label. This is the default when creating a new button in Glade-3, but if you've changed the contents of the button, this will...
[ 3 ]
[]
[]
[ "gtk", "pygtk", "python", "user_interface" ]
stackoverflow_0003508075_gtk_pygtk_python_user_interface.txt
Q: I have a series of python modules I would like to put into a package, how can I do this? I have a series of python modules I would like to put into a package. I would like to set it up such that anyone interested can just download it and install it (on unix). How can I do this? A: You should use distutils/setupt...
I have a series of python modules I would like to put into a package, how can I do this?
I have a series of python modules I would like to put into a package. I would like to set it up such that anyone interested can just download it and install it (on unix). How can I do this?
[ "You should use distutils/setuptools to create egg and PyPI to distribute your package.\nSee according tutorials on packaging and uploading to PyPI:\nhttp://diveintopython3.org/packaging.html\nhttp://wiki.python.org/moin/CheeseShopTutorial\n" ]
[ 1 ]
[]
[]
[ "module", "package", "python" ]
stackoverflow_0003508103_module_package_python.txt
Q: How can I know if the user is connected to the local machine via ssh in my python script? How can I know if the user is connected to the local machine via ssh in my python script? A: You can use the os module to check for the existence of the environment variable SSH_CONNECTION. >>> import os >>> using_ssh = 'SS...
How can I know if the user is connected to the local machine via ssh in my python script?
How can I know if the user is connected to the local machine via ssh in my python script?
[ "You can use the os module to check for the existence of the environment variable SSH_CONNECTION.\n>>> import os\n>>> using_ssh = 'SSH_CONNECTION' in os.environ\n\n", "Am I correct in assuming you're running your script on some sort of UNIX/Linux system? If so, you can just type \"users\" on the command-line, an...
[ 6, 0, 0 ]
[]
[]
[ "python", "ssh" ]
stackoverflow_0003507980_python_ssh.txt
Q: Recommended language for multithreaded data work Right now, I use a combination of Python and R for all of my data processing needs. However, some of my datasets are incredibly large and would benefit strongly from multithreaded processing. For example, if there are two steps that each have to performed on a set ...
Recommended language for multithreaded data work
Right now, I use a combination of Python and R for all of my data processing needs. However, some of my datasets are incredibly large and would benefit strongly from multithreaded processing. For example, if there are two steps that each have to performed on a set of several millions of data points, I would like to be...
[ "It is possible to do this in Python using the multiprocessing module -- this spawns multiple processes instead of threads, which bypasses the GIL and hence allows true concurrency.\nThat is not to say that Python is the 'best' language for this job; that's a subjective point which can be argued over. But it is cer...
[ 6, 5, 3, 1, 0, 0 ]
[]
[]
[ "multithreading", "python", "r" ]
stackoverflow_0003507451_multithreading_python_r.txt
Q: Break/Decompose complex and compound sentences in nltk Is there a way to decompose complex sentences into simple sentences in nltk or other natural language processing libraries? For example: The park is so wonderful when the sun is setting and a cool breeze is blowing ==> The sun is setting. a cool breeze is blow...
Break/Decompose complex and compound sentences in nltk
Is there a way to decompose complex sentences into simple sentences in nltk or other natural language processing libraries? For example: The park is so wonderful when the sun is setting and a cool breeze is blowing ==> The sun is setting. a cool breeze is blowing. The park is so wonderful.
[ "This is much more complicated than it seems, so you're unlikely to find a perfectly clean method.\nHowever, using the English parser in OpenNLP, I can take your example sentence and get a following grammar tree:\n (S\n (NP (DT The) (NN park))\n (VP\n (VBZ is)\n (ADJP (RB so) (JJ wonderful))\n ...
[ 12 ]
[]
[]
[ "nlp", "nltk", "python" ]
stackoverflow_0003501436_nlp_nltk_python.txt
Q: Start a script on a remote machine through ssh with python - but in reverse? Here's what I need to do: The user is on a remote machine and connects to a server via ssh. He runs a python script on the server. The script running on the server starts a script on the user's remote machine as a subprocess and opens a...
Start a script on a remote machine through ssh with python - but in reverse?
Here's what I need to do: The user is on a remote machine and connects to a server via ssh. He runs a python script on the server. The script running on the server starts a script on the user's remote machine as a subprocess and opens a pipe to it for communication. First, is this at all possible? Second, is this pos...
[ "\nFirst, is this at all possible?\n\nWith simple user --SSH--> server - no, its not.\n\nis this possible in such a way that the user does not need to do anything fancy\n\nUser will have to run sshd on his machine, add a user for your server and somehow let you to connect to it, bypassing NAT if any. So no, there i...
[ 4 ]
[]
[]
[ "python", "ssh", "subprocess" ]
stackoverflow_0003508164_python_ssh_subprocess.txt
Q: How do I find only whole words using re.search? I have a list of words built from different HTML pages. Instead of writing rule after rule to strip out different elements, I am trying to go through the list and say if it's not a full word with only alpha characters, just move on. This is not working. for w in word...
How do I find only whole words using re.search?
I have a list of words built from different HTML pages. Instead of writing rule after rule to strip out different elements, I am trying to go through the list and say if it's not a full word with only alpha characters, just move on. This is not working. for w in words: if re.search('\b[a-zA-Z]\b', w) == None: ...
[ "You're almost there. You just have to tell your search to match an entire string of 1 or more characters.\nfor w in words:\n if re.search('^[a-zA-Z]+$', w) == None:\n continue\n\nAnother solution (for this specific case atleast) would be to use isalpha();\nfor w in words:\n if not w.isalpha():\n ...
[ 3 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003508283_python_regex.txt
Q: XMPP chat: accessing contacts' status messages with xmppPy's Roster I'm trying to access my google talk contacts' custom status messages with xmpppy. I'm made it this far: import xmpp import sys userID = 'myname@gmail.com' password = 'mypassword' ressource = 'Script' jid = xmpp.protocol.JID(userID) jabber =...
XMPP chat: accessing contacts' status messages with xmppPy's Roster
I'm trying to access my google talk contacts' custom status messages with xmpppy. I'm made it this far: import xmpp import sys userID = 'myname@gmail.com' password = 'mypassword' ressource = 'Script' jid = xmpp.protocol.JID(userID) jabber = xmpp.Client(jid.getDomain(), debug=[]) connection = jabber.connect(('ta...
[ "Here's one thing I've found, which was not clear to me when I first started working with xmpp. Friending is two-way. \nUsing presence stanzas\n(a) You can \"subscribe\" to your friend, and your friend can return \"subscribed\".\n(b) Your friend can \"subscribe\" to you, and you can return \"subscribed\".\nYour fri...
[ 3, 2 ]
[]
[]
[ "chat", "google_talk", "python", "xmpp" ]
stackoverflow_0002381597_chat_google_talk_python_xmpp.txt
Q: PyGTK TreeColumns all exact duplicates I wrote a simple PyGTK script to show some basic process information in a TreeView: import gtk import os import pwd import grp class ProcParser: """ Parses the status file of a particular process """ def __init__(self, fname): self.lines = map(lambda ...
PyGTK TreeColumns all exact duplicates
I wrote a simple PyGTK script to show some basic process information in a TreeView: import gtk import os import pwd import grp class ProcParser: """ Parses the status file of a particular process """ def __init__(self, fname): self.lines = map(lambda x: x[:-1], open(fname).readlines()) def...
[ "for append on treview you should do\n rendererText = gtk.CellRendererText()\n tvcols = [\"Name\", \"Pid\", \"User\", \"Group\"]\n\n for num, name in enumerate(tvcols):\n column_name = gtk.TreeViewColumn(name ,rendererText, text=num)\n self.tree.append_column(column_name)\n\n" ]
[ 4 ]
[]
[]
[ "gtktreeview", "pygtk", "python" ]
stackoverflow_0003505171_gtktreeview_pygtk_python.txt
Q: Regular Expression 'Split' function I'm new to this site, and new to Python. So I'm learning about Regular Expressions and I was working through Google's expamples here. I was doing one of the 'Search' examples but I changed the 'Search' to 'Split' and changed the search pattern a bit just to play with it, here's ...
Regular Expression 'Split' function
I'm new to this site, and new to Python. So I'm learning about Regular Expressions and I was working through Google's expamples here. I was doing one of the 'Search' examples but I changed the 'Search' to 'Split' and changed the search pattern a bit just to play with it, here's the line print re.split(r'i', 'piiig') ...
[ "Your example might make more sense if you replace i with ,:\nprint re.split(r',', 'p,,,g')\n\nIn this case, there are four fields found by splitting on the comma, a 'p', a 'g', and two empty ones '' in the middle.\n", "split removes the instance it finds. The two blank strings are are the two empty strings betwe...
[ 6, 2, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003508898_python_regex.txt
Q: Python one-liner I want a one-liner solution in Python of the following code, but how? total = 0 for ob in self.oblist: total += sum(v.amount for v in ob.anoutherob) It returns the total value. I want it in a one-liner. How can I do it? A: There isn't any need to double up on the sum() calls: total = sum(v....
Python one-liner
I want a one-liner solution in Python of the following code, but how? total = 0 for ob in self.oblist: total += sum(v.amount for v in ob.anoutherob) It returns the total value. I want it in a one-liner. How can I do it?
[ "There isn't any need to double up on the sum() calls:\ntotal = sum(v.amount for ob in self.oblist for v in ob.anotherob)\n\n", "You can just collapse the for loop into another level of comprehension:\ntotal = sum(sum(v.amount for v in ob.anotherob) for ob in self.oblist)\n\n" ]
[ 38, 7 ]
[]
[]
[ "python", "sum" ]
stackoverflow_0003508766_python_sum.txt
Q: Console colors (Windows) Is it possible to print out things in different colors in Python for Windows? I already enabled ANSI.sys, but this does not seam to work. I want to be able to print one line in red, and the next in green, etc. A: The WConio module should be all you need to accomplish this. WConio.textba...
Console colors (Windows)
Is it possible to print out things in different colors in Python for Windows? I already enabled ANSI.sys, but this does not seam to work. I want to be able to print one line in red, and the next in green, etc.
[ "The WConio module should be all you need to accomplish this.\n\nWConio.textbackground(color) sets the background color without changing the foreground. See below for the color constants.\nWConio.textcolor(color) sets the foreground color without changing the background. See below for the color constants.\n\nThe co...
[ 2 ]
[]
[]
[ "ansi_escape", "ansicon", "colors", "python", "windows" ]
stackoverflow_0003508906_ansi_escape_ansicon_colors_python_windows.txt
Q: handling python string or list dynamically numberofrow, its value is dynamically set in form field. now since numberofrow is in multiple tables, when i receive that variable from form, if only one numerofrow, its a String, for ex. numberofrow = 01 if more than one numberofrow, its a list, for ex. numberofrow = ...
handling python string or list dynamically
numberofrow, its value is dynamically set in form field. now since numberofrow is in multiple tables, when i receive that variable from form, if only one numerofrow, its a String, for ex. numberofrow = 01 if more than one numberofrow, its a list, for ex. numberofrow = [01, 02, 04] Now how do i differentiate if its a...
[ "For this purpose there is a build-in called isinstance. You can use it to check if an object is an instance of that class (and compared to your solution also super classes are considered in this test).\nif isinstance(numberofrow, list):\n # do this\nelse:\n # do that\n\nIt's quite common to do something like...
[ 6, 4, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003509150_python.txt
Q: Can deleting a django Model with a ManyToManyField create orphaned database rows? If I have two classes A and B with a many to many relationship and I want to delete an instance of A, do I need to remove all of its related Bs first or will Django sort that out for me? I obviously don't want to leave orphaned rows ...
Can deleting a django Model with a ManyToManyField create orphaned database rows?
If I have two classes A and B with a many to many relationship and I want to delete an instance of A, do I need to remove all of its related Bs first or will Django sort that out for me? I obviously don't want to leave orphaned rows in the join table. Does it make any difference if the ManyToMany field is declared on c...
[ "\nIf I have two classes A and B with a many to many relationship and I want to delete an instance of A, do I need to remove all of its related Bs first or will Django sort that out for me?\n\nShort answer: Django will sort that out for you.\n\nDoes it make any difference if the ManyToMany field is declared on clas...
[ 2 ]
[]
[]
[ "django", "django_models", "many_to_many", "python" ]
stackoverflow_0003509275_django_django_models_many_to_many_python.txt
Q: Edit Windows 7 Registry in Python? I have run into another problem with my current project. The program needs to values and keys periodically while running. Each time I attempt to edit the value, I get a code 5, Access Denied. How would I go about doing this so the values can be editied, but the user doesn't have ...
Edit Windows 7 Registry in Python?
I have run into another problem with my current project. The program needs to values and keys periodically while running. Each time I attempt to edit the value, I get a code 5, Access Denied. How would I go about doing this so the values can be editied, but the user doesn't have to enter admin credentials to run the ap...
[ "If you want to edit something that is writable only with administrative privileges, you just have to run under admin privileges. Everything else would be a giant security hole.\n" ]
[ 1 ]
[]
[]
[ "access_denied", "editing", "python", "registry", "windows_7" ]
stackoverflow_0003509471_access_denied_editing_python_registry_windows_7.txt
Q: Python socket client-server application I wrote two applictions which comunicate by socket. This is the code: Server: import socket server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.bind(("",9999)) server_socket.listen(5) video = True power = True print "TCPServer Waiting for clien...
Python socket client-server application
I wrote two applictions which comunicate by socket. This is the code: Server: import socket server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.bind(("",9999)) server_socket.listen(5) video = True power = True print "TCPServer Waiting for client on port 9999" while 1: client_socket,a...
[ "You don't send anything. I presume the line data = \"Please vc or pc: is meant to get input from the user, but it just assigns the string to data. Then when you check if data == 'pc' | data == 'vc' the check fails so it prints \"bad data\".\nAlso do not use | in boolean expressions - use or and and. | and & wil...
[ 2 ]
[]
[]
[ "python", "sockets" ]
stackoverflow_0003509539_python_sockets.txt
Q: Converting a list with many items into single item lines in python I want to convert lines in a text file from this: animal cat, mouse, dog, horse numbers 22,45,124,87 to this: animal cat animal mouse animal dog animal horse numbers 22 numbers 45 numbers 124 numbers 8...
Converting a list with many items into single item lines in python
I want to convert lines in a text file from this: animal cat, mouse, dog, horse numbers 22,45,124,87 to this: animal cat animal mouse animal dog animal horse numbers 22 numbers 45 numbers 124 numbers 87 How would I do this conversion in python? Thanks
[ "with open('thefile.txt') as fin:\n with open('result.txt') as fou:\n for line in fin:\n key, values = line.split(None, 1)\n vs = [x.strip() for x in values.split(',')]\n for v in vs:\n fou.write('%s %s\\n' % (key, v))\n\n", "Use a collections.defaultdict.\nYou might want to searc...
[ 4, 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0003508051_list_python.txt
Q: how can I put a process in background using django? I tried os.system, os.spwanl, etc.. but it doesn't work well I need to execute some background process from django application. A: Try to use celery. It was originally created for this purpose and also supports scheduling tasks. A: The subprocess module give...
how can I put a process in background using django?
I tried os.system, os.spwanl, etc.. but it doesn't work well I need to execute some background process from django application.
[ "Try to use celery. It was originally created for this purpose and also supports scheduling tasks.\n", "The subprocess module gives you much finer-grained control over spawning processes than afforded by os.system.\n", "I have used subprocess to spawn background processes from Django before. It may depend on yo...
[ 15, 0, 0, 0 ]
[]
[]
[ "django", "process", "python", "system" ]
stackoverflow_0002872605_django_process_python_system.txt
Q: Read 40 bytes of binary data as ascii text I have some binary data, in hex editor it looks like: s.o.m.e.d.a.t.a with all these dots in between each letter when I read with filehandle.read(40) it shows these dots I know that the dots aren't supposed to be there, is there a way to unpack some ascii data that is 40 ...
Read 40 bytes of binary data as ascii text
I have some binary data, in hex editor it looks like: s.o.m.e.d.a.t.a with all these dots in between each letter when I read with filehandle.read(40) it shows these dots I know that the dots aren't supposed to be there, is there a way to unpack some ascii data that is 40 bytes long with struct? I tried '40s' and 's' b...
[ "If your first byte is an ASCII character (as indicated by your example) and your second byte is '\\x00', then you probably have data encoded as UTF-16LE. \nHowever it would be a good idea if you showed us unequivocably exactly what's in the first few bytes of your file. Please do this:\npython -c \"print(repr(open...
[ 4, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003507925_python.txt
Q: Pure Python in Xcode Is there a way to program using pure python in Xcode? I want something like the c++ command line utility except for python, I found a tutorial that did not work for me: (after playing around with which active architecture finally decided on i386) when trying to print "Hello, World!" I get the ...
Pure Python in Xcode
Is there a way to program using pure python in Xcode? I want something like the c++ command line utility except for python, I found a tutorial that did not work for me: (after playing around with which active architecture finally decided on i386) when trying to print "Hello, World!" I get the following error "Data Form...
[ "/Library/Frameworks/Python.framework/Versions/2.6/bin/python is typically the path to the python.org installer Python (or possibly other non-Apple Python) which, indeed, includes only 32-bit architectures (ppc and i386). It also is built using the OS X 10.4u SDK (an optional install with Xcode on 10.6). The Appl...
[ 2 ]
[]
[]
[ "macos", "python", "xcode" ]
stackoverflow_0003498839_macos_python_xcode.txt
Q: Dynamically loading Python application code from database under Google App Engine I need to store python code in a database and load it in some kind of bootstrap.py application for execution. I cannot use filesystem because I'm using GAE, so this is my only choice. However I'm not a python experienced user. I alre...
Dynamically loading Python application code from database under Google App Engine
I need to store python code in a database and load it in some kind of bootstrap.py application for execution. I cannot use filesystem because I'm using GAE, so this is my only choice. However I'm not a python experienced user. I already was able to load 1 line of code and run it using eval, however a piece of code with...
[ "I was able to do what I intent after reading more about Python dynamic code loading.\nHere is the sample code. I removed headers to be lighter:\nThanks anyway!\n=============\nclass DynCode(db.Model):\n name = db.StringProperty()\n code = db.TextProperty(default=None)\n\n=============\nclass MainHandler(weba...
[ 4, 3, 2 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0003505357_google_app_engine_google_cloud_datastore_python.txt
Q: Python: How to check if a unicode string contains a cased character? I'm doing a filter wherein I check if a unicode (utf-8 encoding) string contains no uppercase characters (in all languages). It's fine with me if the string doesn't contain any cased character at all. For example: 'Hello!' will not pass the filt...
Python: How to check if a unicode string contains a cased character?
I'm doing a filter wherein I check if a unicode (utf-8 encoding) string contains no uppercase characters (in all languages). It's fine with me if the string doesn't contain any cased character at all. For example: 'Hello!' will not pass the filter, but "!" should pass the filter, since "!" is not a cased character. I ...
[ "import unicodedata as ud\n\ndef contains_cased(u):\n return any(ud.category(c)[0] == 'L' for c in u)\n\n", "Here is the full scoop on Unicode character categories.\nLetter categories include:\nLl -- lowercase\nLu -- uppercase\nLt -- titlecase\nLm -- modifier\nLo -- other\n\nNote that Ll <-> islower(); similarly...
[ 8, 8, 1 ]
[]
[]
[ "lowercase", "python", "unicode", "uppercase" ]
stackoverflow_0003508490_lowercase_python_unicode_uppercase.txt
Q: Getting list of all strings from a Django app Eclipse has a function called Externalise all Strings, which will move all strings to an properties file. Is there such a solution available for Django/Python? Basically I have a large project with number of views/models/templates, and going through all of them, and pu...
Getting list of all strings from a Django app
Eclipse has a function called Externalise all Strings, which will move all strings to an properties file. Is there such a solution available for Django/Python? Basically I have a large project with number of views/models/templates, and going through all of them, and putting string -> _("string") etc is a big pain, so i...
[ "It is automated in Django and has been for a long time. But the docs are a bit hard to find ;)\nYou can use the makemessages management command, or if you run an older version of django run django/bin/make-messages.py.\nLink to the docs: http://docs.djangoproject.com/en/dev/ref/django-admin/#makemessages\nExample:...
[ 1 ]
[]
[]
[ "django", "internationalization", "python" ]
stackoverflow_0003509512_django_internationalization_python.txt
Q: Use (Python) Gstreamer to decode audio (to PCM data) I'm writing an application that uses the Python Gstreamer bindings to play audio, but I'm now trying to also just decode audio -- that is, I'd like to read data using a decodebin and receive a raw PCM buffer. Specifically, I want to read chunks of the file incre...
Use (Python) Gstreamer to decode audio (to PCM data)
I'm writing an application that uses the Python Gstreamer bindings to play audio, but I'm now trying to also just decode audio -- that is, I'd like to read data using a decodebin and receive a raw PCM buffer. Specifically, I want to read chunks of the file incrementally rather than reading the whole file into memory. S...
[ "To get the data back in your application, the recommended way is appsink.\nBased on a simple audio player like this one (and replace the oggdemux/vorbisdec by decodebin & capsfilter with caps = \"audio/x-raw-int\"), change autoaudiosink to appsink, and connect \"new-buffer\" signal to a python function + set \"emi...
[ 5 ]
[]
[]
[ "audio", "decode", "gstreamer", "pcm", "python" ]
stackoverflow_0003507746_audio_decode_gstreamer_pcm_python.txt
Q: Passing subclasses to imported library I have library which returns collections of some semi-abstract objects. class Item1(object): pass class Item2(object): pass class Collection1(object): pass class Provider(object): def retrieve_collection(self): col = Collection1() col.add(Ite...
Passing subclasses to imported library
I have library which returns collections of some semi-abstract objects. class Item1(object): pass class Item2(object): pass class Collection1(object): pass class Provider(object): def retrieve_collection(self): col = Collection1() col.add(Item1()) col.add(Item2()) retur...
[ "mylib.py\nclass Item1(object):\n def __repr__(self):\n return \"Base Item1\"\nclass Item2(object):\n def __repr__(self):\n return \"Base Item2\"\nclass Collection1(set):\n pass \n\nclass Provider(object):\n Item1=Item1\n Item2=Item2\n def retrieve_collection(self):\n col = Co...
[ 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003509961_python.txt
Q: Why does python libs (eg imaplib) does not use logging but use sys.stderr.write? I'm not sure if it's because sys.stderr.write is faster. A: imaplib is much older (it was in Python1.5.2) than the logging module (Python2.3), so perhaps noone has needed to update it to use logging yet
Why does python libs (eg imaplib) does not use logging but use sys.stderr.write?
I'm not sure if it's because sys.stderr.write is faster.
[ "imaplib is much older (it was in Python1.5.2) than the logging module (Python2.3), so perhaps noone has needed to update it to use logging yet\n" ]
[ 6 ]
[]
[]
[ "logging", "python" ]
stackoverflow_0003510747_logging_python.txt
Q: Looking For: A “demo” web web-based application that uses web services Greetings – I am experimenting with various software techniques to capture and analyze the messages being exchanged between web services, web services that together would form a cloud hosted web application. One of the initial steps is locating...
Looking For: A “demo” web web-based application that uses web services
Greetings – I am experimenting with various software techniques to capture and analyze the messages being exchanged between web services, web services that together would form a cloud hosted web application. One of the initial steps is locating a “demo” application to actually experiment against, one that actually cons...
[ "The piston add-in for Django is nice. It has sample RESTful web services applications you can run.\nhttp://bitbucket.org/jespern/django-piston/wiki/Home\nYou might want to use the demo app from the presentation.\nhttp://bitbucket.org/Josh/django-piston-presentation/wiki/Home\n", "I recall using an add-on for tu...
[ 1, 0, 0 ]
[]
[]
[ "python", "web_applications", "web_services" ]
stackoverflow_0003508878_python_web_applications_web_services.txt
Q: Python: Slice a 2d array into tiles I have a raw data file which I read into a byte buffer (a python string). Each data value represents an 8bit pixel of a 2d array representing an image. I know the width and height of this image. I would like to split the image into tiles so that each tiles area must be larger th...
Python: Slice a 2d array into tiles
I have a raw data file which I read into a byte buffer (a python string). Each data value represents an 8bit pixel of a 2d array representing an image. I know the width and height of this image. I would like to split the image into tiles so that each tiles area must be larger than a 'min tile area' (eg 1024 bytes) and ...
[ "As you give no indication of the meaning of \"best\", I will suppose that it means \"with the less cluttered code\".\nLet's say you have the following data:\nfrom collections import Sequence\nimport operator\n\nassert(type(MIN_AREA) is int)\nassert(type(MAX_AREA) is int)\nassert(type(width) is int)\nassert(type(he...
[ 2, 1 ]
[]
[]
[ "python", "slice" ]
stackoverflow_0003510057_python_slice.txt
Q: Python yield returns characters instead of string from single-element tuple I'm using yield to process each element of a list. However, if the tuple only has a single string element, yield returns the characters of the string, instead of the whole string: self.commands = ("command1") ... for command in self.comman...
Python yield returns characters instead of string from single-element tuple
I'm using yield to process each element of a list. However, if the tuple only has a single string element, yield returns the characters of the string, instead of the whole string: self.commands = ("command1") ... for command in self.commands: yield command # returns 'c' not 'command1' how can i fix ...
[ "A tuple having only 1 element should be written with a trailing comma.\nself.commands = (\"command1\",)\n\n", "self.commands = [\"command1\"]\n\nYou never told the loop that you had a list, so it's treating the string as the sequence.\nedit: or you could just fix the tuple, as recommended ... I assumed you'd wan...
[ 6, 0 ]
[]
[]
[ "python", "yield" ]
stackoverflow_0003511292_python_yield.txt
Q: Factory pattern in Python I'm currently implementing the Factory design pattern in Python and I have a few questions. Is there any way to prevent the direct instantiation of the actual concrete classes? For example, if I have a VehicleFactory that spawns Vehicles, I want users to just use that factory, and preven...
Factory pattern in Python
I'm currently implementing the Factory design pattern in Python and I have a few questions. Is there any way to prevent the direct instantiation of the actual concrete classes? For example, if I have a VehicleFactory that spawns Vehicles, I want users to just use that factory, and prevent anyone from accidentally inst...
[ "Be Pythonic. Don't overcomplicate your code with \"enterprise\" language (like Java) solutions that add unnecessary levels of abstraction.\nYour code should be simple, and intuitive. You shouldn't need to delegate to another class to instantiate another.\n", "\nDon't expose the class (for example make it private...
[ 23, 12, 6 ]
[]
[]
[ "design_patterns", "factory", "factory_pattern", "python" ]
stackoverflow_0003511027_design_patterns_factory_factory_pattern_python.txt
Q: How to remove list of words from a list of strings Sorry if the question is bit confusing. This is similar to this question I think this the above question is close to what I want, but in Clojure. There is another question I need something like this but instead of '[br]' in that question, there is a list of stri...
How to remove list of words from a list of strings
Sorry if the question is bit confusing. This is similar to this question I think this the above question is close to what I want, but in Clojure. There is another question I need something like this but instead of '[br]' in that question, there is a list of strings that need to be searched and removed. Hope I made my...
[ "Without regexp you could do like this:\nplaces = ['of New York', 'of the New York']\n\nnoise_words_set = {'of', 'the', 'at', 'for', 'in'}\nstuff = [' '.join(w for w in place.split() if w.lower() not in noise_words_set)\n for place in places\n ]\nprint stuff\n\n", "Here is my stab at it. This uses...
[ 15, 11, 4, 1 ]
[]
[]
[ "list_comprehension", "python", "regex", "stop_words" ]
stackoverflow_0003510846_list_comprehension_python_regex_stop_words.txt
Q: Is there any generic binary protocol codec library for python? There is nice one for java - MINA. Once I've heard that there is something similar for python. But can't remind. EDIT: to be more specific, I would like to have a tool which would help me to create a coded for some binary stream. EDIT2: I'd like to lis...
Is there any generic binary protocol codec library for python?
There is nice one for java - MINA. Once I've heard that there is something similar for python. But can't remind. EDIT: to be more specific, I would like to have a tool which would help me to create a coded for some binary stream. EDIT2: I'd like to list solutions here (thanks Scott for related topics) Listed in order i...
[ "python has pack/unpack in the standard lib that can be used to interpret binary data and map them to structs \nsee \"11.3. Working with Binary Data Record Layouts\" here http://docs.python.org/tutorial/stdlib2.html\nor here http://docs.python.org/library/struct.html\n", "Have you tried the bitstring module? (Ful...
[ 5, 5 ]
[]
[]
[ "binary", "protocols", "python" ]
stackoverflow_0003511217_binary_protocols_python.txt
Q: rewrite small piece of python code I have lots of small pieces of code that look like: for it in <iterable>: if <condition>: return True/False Is there a way I can rewrite this piece of code with a lambda expression ? I know I can factor it out in a small method/function, but I am looking for some lambda t...
rewrite small piece of python code
I have lots of small pieces of code that look like: for it in <iterable>: if <condition>: return True/False Is there a way I can rewrite this piece of code with a lambda expression ? I know I can factor it out in a small method/function, but I am looking for some lambda thing if it can be done.
[ "Use the built-in any function.\ne.g. \nany(<condition> for it in <iterable>) # return True on <condition>\n\n", "In addition to what everyone else has said, for the reverse case:\nfor it in <iterable>:\n if <condition>:\n return False\nreturn True\n\nuse all():\nb = all(<condition> for it in <iterable...
[ 6, 1, 0, 0 ]
[]
[]
[ "python", "refactoring" ]
stackoverflow_0003511115_python_refactoring.txt
Q: Country-based Super User Access, and modifiying Django Auth I'm looking to give super user access to users of a program I'm devving. All the entities have a country id value, so i'm just lookign to hook up my user model to have a country ID Looking at Django Auth, It should be nice and easy to add a super_user_cou...
Country-based Super User Access, and modifiying Django Auth
I'm looking to give super user access to users of a program I'm devving. All the entities have a country id value, so i'm just lookign to hook up my user model to have a country ID Looking at Django Auth, It should be nice and easy to add a super_user_country_id field. However, how frowned upon is it to modify the core...
[ "At the moment, the recommended way is to create a Profile model and link it to the User model with a OneToOneField or a ForeignKey (depending on your requirements). Here's a good tutorial on the topic.\nThe Django devs have repeatedly expressed their intent to make extending the User model more straightforward, bu...
[ 1, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003511620_django_python.txt
Q: Auto-adjusting size for Tkinter frame I'm working on a gui and I'd like to know how to adjust the size of the menus of a frame in order to have them take all the horizontal space of the frame. The problem has changed : now the menu buttons are ok when the window is in normal size but when I resize it the menu but...
Auto-adjusting size for Tkinter frame
I'm working on a gui and I'd like to know how to adjust the size of the menus of a frame in order to have them take all the horizontal space of the frame. The problem has changed : now the menu buttons are ok when the window is in normal size but when I resize it the menu buttons drop in the middle of the window. How ...
[ "Your question lacks enough detail to give you a good answer. Are you creating a menubar by putting menu buttons in a frame? If so, that's the wrong way to do it. Create a menu widget and assign it to the menu property of the main window and you'll end up with standard menus that behave normally. \nHere's a simple ...
[ 0 ]
[]
[]
[ "menu", "python", "tkinter" ]
stackoverflow_0003511791_menu_python_tkinter.txt
Q: What does %d mean in struct.pack? I was reading though a library of python code, and I'm stumped by this statement: struct.pack( "<ii%ds"%len(value), ParameterTypes.String, len(value), value.encode("UTF8") ) I understand everything but%d, and I'm not sure why the length of value is being packed in twice. As I und...
What does %d mean in struct.pack?
I was reading though a library of python code, and I'm stumped by this statement: struct.pack( "<ii%ds"%len(value), ParameterTypes.String, len(value), value.encode("UTF8") ) I understand everything but%d, and I'm not sure why the length of value is being packed in twice. As I understand it, the structure will have lit...
[ "Aarrrgh the mind boggles ....\n@S.Lott: \"\"\"I don't think the number is particularly important, since Python will tend to pack correctly without it.\"\"\" -1. Don't think; investigate. Without a number means merely that the number defaults to 1. Tends to pack correctly??? Perhaps you think that struct.pack(\"s\...
[ 2, 1, 1, 0, 0 ]
[]
[]
[ "python", "struct" ]
stackoverflow_0003510814_python_struct.txt
Q: Does this PyList_Append(list, Py_BuildValue(...)) leak? Does this leak?: static PyObject* foo(PyObject* self, PyObject* args){ PyObject* list = PyList_New(0); for(int i = 0; i < 100; i++) // leak? does PyList_Append increment ref of the temporary? PyList_Append(list, Py_BuildValue("i", 42))...
Does this PyList_Append(list, Py_BuildValue(...)) leak?
Does this leak?: static PyObject* foo(PyObject* self, PyObject* args){ PyObject* list = PyList_New(0); for(int i = 0; i < 100; i++) // leak? does PyList_Append increment ref of the temporary? PyList_Append(list, Py_BuildValue("i", 42)); return list; } Though, I suppose it's better to do th...
[ "PyList_Append does indeed increment the reference counter, so, yes, the first example will leak. PyList_SetItem does not, making it a weird exception.\nThe second option will be slightly more efficient because the list will be allocated to excatly the right size and Python does have to dynamically resize it as it...
[ 29 ]
[]
[]
[ "c", "python" ]
stackoverflow_0003512414_c_python.txt
Q: How to get read-only objects from database? I'd like to query the database and get read-only objects with session object. I need to save the objects in my server and use them through the user session. If I use a object outside of the function that calls the database, I get this error: "DetachedInstanceError: Paren...
How to get read-only objects from database?
I'd like to query the database and get read-only objects with session object. I need to save the objects in my server and use them through the user session. If I use a object outside of the function that calls the database, I get this error: "DetachedInstanceError: Parent instance is not bound to a Session; lazy load o...
[ "You must load the parent object again.\n" ]
[ 0 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0003513433_python_sqlalchemy.txt
Q: What possibilities exist to build an installer for a windows application on Linux (install target=windows, build environment=Linux) After playing around with NSIS (Nullsoft Scriptable Installation System) for a few days, I really feel the pain it's use brings me. No wonder, the authors claim it's scripting impleme...
What possibilities exist to build an installer for a windows application on Linux (install target=windows, build environment=Linux)
After playing around with NSIS (Nullsoft Scriptable Installation System) for a few days, I really feel the pain it's use brings me. No wonder, the authors claim it's scripting implementation is a "mixture of PHP and Assembly". So, I hope there is something better to write installation procedures to get Windows programs...
[ "You may be interested by BitRock\n", "You might try looking at InstallAnywhere, but it may require Java.\n", "Try running InnoSetup under Wine. It should work unless you have some very specific needs. InnoSetup is open source, BTW.\n", "It seems that pyinstaller might do the trick. I'm also looking for somet...
[ 2, 0, 0, 0 ]
[]
[]
[ "installation", "linux", "python", "windows" ]
stackoverflow_0001562999_installation_linux_python_windows.txt
Q: (Unintentionally) skipping items when iterating over a list I have a list and I want to remove from it the items that don't appear in another list. I've tried the following: for w in common: for i in range(1,n): if not w in words[i]: common.remove(w) However, this fails to r...
(Unintentionally) skipping items when iterating over a list
I have a list and I want to remove from it the items that don't appear in another list. I've tried the following: for w in common: for i in range(1,n): if not w in words[i]: common.remove(w) However, this fails to remove some of the items. Adding print statements for w in common:...
[ "I think you can simplify your statement with something like this:\nfiltered = filter(lambda x: x in words, common)\n\nThat's checking each element in common for it's presence in words and removing based on it. You may need to try x not in words depending on what you're desired result is, but I think that should c...
[ 8, 3, 3, 2, 2 ]
[]
[]
[ "list", "python" ]
stackoverflow_0003513531_list_python.txt