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: Where do I put common code for if and elif? For the example below: if a == 100: # Five lines of code elif a == 200: # Five lines of code Five lines of code is common and repeating how can I avoid it? I know about putting it a function or if a == 100 or a == 200: # Five lines of code if a == 1...
Where do I put common code for if and elif?
For the example below: if a == 100: # Five lines of code elif a == 200: # Five lines of code Five lines of code is common and repeating how can I avoid it? I know about putting it a function or if a == 100 or a == 200: # Five lines of code if a == 100: # Do something elif a == 200: ...
[ "Alternative (1): put your 5 lines in a function, and just call it\nAlternative (2)\nif a in (100, 200):\n # five lines of code\n if a == 100:\n # ...\n else:\n # ...\n\nA little less verbose than your code\n", "def five_lines(arg):\n ...\n\nif a in [100,200]:\n five_lines(i)\n\n", "Remember...
[ 4, 1, 1 ]
[]
[]
[ "conditional", "python" ]
stackoverflow_0002605425_conditional_python.txt
Q: 'NoneType' object has no attribute 'get' error using SQLAlchemy I've been trying to map an object to a database using SQLAlchemy but have run into a snag. Edit: Basically changed a whole bunch of stuff. Version info if handy: [OS: Mac OSX 10.5.8 | Python: 2.6.4 | SQLAlchemy: 0.5.8] The class I'm going to map: c...
'NoneType' object has no attribute 'get' error using SQLAlchemy
I've been trying to map an object to a database using SQLAlchemy but have run into a snag. Edit: Basically changed a whole bunch of stuff. Version info if handy: [OS: Mac OSX 10.5.8 | Python: 2.6.4 | SQLAlchemy: 0.5.8] The class I'm going to map: class Student(object): def __init__(self, id, name): self....
[ "You are creating Student instances before mapping class which modifies class to SQLAlchemy needs. So your instance is not properly initialized. Just put the lines creating Student instances after calling mapper(Student, students_table) and everything will work as expected.\n", "It looks like you might have a nam...
[ 2, 0 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0002605205_python_sqlalchemy.txt
Q: functional-style datatypes in Python For anyone who's spent some time with sml, ocaml, haskell, etc. when you go back to using C, Python, Java, etc. you start to notice things you never knew were missing. I'm doing some stuff in Python and I realized what I really want is a functional-style datatype like (for exam...
functional-style datatypes in Python
For anyone who's spent some time with sml, ocaml, haskell, etc. when you go back to using C, Python, Java, etc. you start to notice things you never knew were missing. I'm doing some stuff in Python and I realized what I really want is a functional-style datatype like (for example) datatype phoneme = Vowel of string | ...
[ "For the simple enumerations like voice, place and manner you could use a class like this:\nclass Enum(object):\n def __init__(self, *values):\n self._values = set(values)\n for value in values:\n setattr(self, value, value)\n def __iter__(self):\n return iter(self._values)\n\nplace = Enu...
[ 1, 1, 0 ]
[]
[]
[ "functional_programming", "python", "types" ]
stackoverflow_0002604666_functional_programming_python_types.txt
Q: Scraping a page from a secure URL which is possibly using a session ID How to scrape a page like this: https://www.procom.ca/JobList.aspx?keywords=&Cities=&reference=&JobType=0 It is secure, and looks like it requires a referrer. I can't get anything using wget or httplib2. If you go through this page, you get a l...
Scraping a page from a secure URL which is possibly using a session ID
How to scrape a page like this: https://www.procom.ca/JobList.aspx?keywords=&Cities=&reference=&JobType=0 It is secure, and looks like it requires a referrer. I can't get anything using wget or httplib2. If you go through this page, you get a list and it works on a browser but not the command line. https://www.procom.c...
[ "As you suspect, it requires a referer. This works:\n import urllib2\n urlopen = urllib2.urlopen\n Request = urllib2.Request\n url = 'https://www.procom.ca/JobList.aspx?keywords=&Cities=&reference=&JobType=0'\n headers = {'Referer' : 'http://www.stackoverflow.com'}\n req = Request(url, None, headers)\n...
[ 3, 0 ]
[]
[]
[ "mechanize", "python", "referrer", "scrapy", "screen_scraping" ]
stackoverflow_0002604914_mechanize_python_referrer_scrapy_screen_scraping.txt
Q: Reading path in templates is there any way to read the path to the current page? For example, I am at www.example.com/foo/bar/ - and I want to read '/foo/bar/'. I have to do this in the template file without modifying views, and I have too many view files to edit each one. Cheers. A: If you add django.core.conte...
Reading path in templates
is there any way to read the path to the current page? For example, I am at www.example.com/foo/bar/ - and I want to read '/foo/bar/'. I have to do this in the template file without modifying views, and I have too many view files to edit each one. Cheers.
[ "If you add django.core.context_processors.request to your TEMPLATE_CONTEXT_PROCESSORS setting, it will add the request variable to every template-rendering that uses a RequestContext (which is most of the built-in ones). This is the HTTPRequest object for the current request, the path attribute of which is the req...
[ 3, 2, 2 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0002127937_django_django_templates_python.txt
Q: How do you determine an acceptable response time for App Engine DB requests? According to this discussion of Google App Engine on Hacker News, A DB (read) request takes over 100ms on the datastore. That's insane and unusable for about 90% of applications. How do you determine what is an acceptable response ...
How do you determine an acceptable response time for App Engine DB requests?
According to this discussion of Google App Engine on Hacker News, A DB (read) request takes over 100ms on the datastore. That's insane and unusable for about 90% of applications. How do you determine what is an acceptable response time for a DB read request? I have been using App Engine without noticing any issu...
[ "You can measure precisely how much each RPC call (datastore or otherwise) is taking, thanks to Guido van Rossum's AppStats relatively-new component (it's part of the standard SDK since 1.3.1). See here for more. 100 milliseconds is fine for most well-designed apps -- if you need to make two or three queries to s...
[ 3, 2, 2, 1, 1 ]
[]
[]
[ "database", "google_app_engine", "java", "python", "response_time" ]
stackoverflow_0002602527_database_google_app_engine_java_python_response_time.txt
Q: Run Python CGI Script on Windows XP I have a Windows XP machine that has Apache installed via a VisualSVNServer installation. I am . trying to get a simple python cgi script to run in my browser e.g. http://build.procepts.com.au:8080/hg/cgi-bin/test.cgi. However despite trying all the recommended approaches the ...
Run Python CGI Script on Windows XP
I have a Windows XP machine that has Apache installed via a VisualSVNServer installation. I am . trying to get a simple python cgi script to run in my browser e.g. http://build.procepts.com.au:8080/hg/cgi-bin/test.cgi. However despite trying all the recommended approaches the browser only ever displays the plain text...
[ "The apache server that comes with VisualSVNServer is a minimal build supporting just enough to serve SVN repositories. It does not include cgi support.\nThat said, it's pretty easy to add cgi support (or any other module for that matter). \nFor CGI support specifically, you'll need to obtain \"mod_cgi.so\" built...
[ 1, 0 ]
[]
[]
[ "apache", "cgi", "python", "scripting" ]
stackoverflow_0002605270_apache_cgi_python_scripting.txt
Q: Change process name of Python script Windows Task Manager lists all running processes in the "Processes" tab. The image name of Python scripts is always python.exe, or pythonw.exe, or the name of the Python interpreter. Is there a nice way to change the image name of a Python script, other than changing the name o...
Change process name of Python script
Windows Task Manager lists all running processes in the "Processes" tab. The image name of Python scripts is always python.exe, or pythonw.exe, or the name of the Python interpreter. Is there a nice way to change the image name of a Python script, other than changing the name of the Python interpreter?
[ "You could use py2exe to turn your Python program into a self-contained executable with whatever name that you choose to give it.\n", "There's no nice way that I've found to change the name of a running process in Windows, but you can create small .exe stubs with ExeMaker rather than resorting to py2exe packaging...
[ 1, 1 ]
[]
[]
[ "process", "python", "windows" ]
stackoverflow_0002155042_process_python_windows.txt
Q: assigning a list in python pt=[2] pt[0]=raw_input() when i do this , and give an input suppose 1011 , it says list indexing error- " list assignment index out of range" . may i know why? i think i am not able to assign a list properly . how to assign an array of 2 elements in python then? A: Try this: pt = list...
assigning a list in python
pt=[2] pt[0]=raw_input() when i do this , and give an input suppose 1011 , it says list indexing error- " list assignment index out of range" . may i know why? i think i am not able to assign a list properly . how to assign an array of 2 elements in python then?
[ "Try this:\npt = list()\npt.append(raw_input())\npt.append(raw_input())\nprint pt\n\nYou now have two elements in your list. Once you are more familiar with python syntax, you might write this as:\npt = [raw_input(), raw_input()]\n\nAlso, note that lists are not to be confused with arrays in Java or C: Lists grow d...
[ 4, 3 ]
[]
[]
[ "python" ]
stackoverflow_0002606303_python.txt
Q: Problem's running unittest test suite OO I have a test suite to perform smoke tests. I have all my script stored in various classes but when I try and run the test suite I can't seem to get it working if it is in a class. The code is below: (a class to call the tests) from alltests import SmokeTests class CallTes...
Problem's running unittest test suite OO
I have a test suite to perform smoke tests. I have all my script stored in various classes but when I try and run the test suite I can't seem to get it working if it is in a class. The code is below: (a class to call the tests) from alltests import SmokeTests class CallTests(SmokeTests): def integration(self): ...
[ "I know this is not the answer, but I'd suggest using library that can use test discovery, like nose or unittest capability from Python 2.7+.\nPossibility to do\nnosetests module.submodule\n\nor\nnosetests module.submodule:TestCase.test_method\n\nis priceless :)\n", "This can't work:\nclass SmokeTests():\n\n d...
[ 3, 1 ]
[]
[]
[ "class", "python", "unit_testing" ]
stackoverflow_0002606515_class_python_unit_testing.txt
Q: How to use the validation rules on both client-side and server-side? I'm using jQuery validation system for client-side validation. The backend works with django. jQuery use an interesting set of rules in JSON format. Does exists something to use the same rules on django side or I need to code it myself? A: No...
How to use the validation rules on both client-side and server-side?
I'm using jQuery validation system for client-side validation. The backend works with django. jQuery use an interesting set of rules in JSON format. Does exists something to use the same rules on django side or I need to code it myself?
[ "No, no such thing exists.\nYes, you need to code it yourself.\nHowever, I imagine you could possibly create widgets which are able to deliver generic validation js routines based on the modelFields. Such as \"This should be chars not more than max_length\". However they could not trivially generate client-side c...
[ 2, 2, 0 ]
[]
[]
[ "django", "jquery", "python", "validation" ]
stackoverflow_0002606283_django_jquery_python_validation.txt
Q: how to define an array in python? i want to define an array in python . how would i do that ? do i have to use list? A: Normally you would use a list. If you really want an array you can import array: import array a = array.array('i', [5, 6]) # array of signed ints If you want to work with multidimensional arra...
how to define an array in python?
i want to define an array in python . how would i do that ? do i have to use list?
[ "Normally you would use a list. If you really want an array you can import array:\nimport array\na = array.array('i', [5, 6]) # array of signed ints\n\nIf you want to work with multidimensional arrays, you could try numpy.\n", "List is better, but you can use array like this :\narray('l')\narray('c', 'hello world...
[ 5, 4, 4, 3, 1 ]
[]
[]
[ "arrays", "python" ]
stackoverflow_0002606793_arrays_python.txt
Q: How do I find out if the variable is declared in Python? I want to use a module as a singleton referenced in other modules. It looks something like this (that's not actually a code I'm working on, but I simplified it to throw away all unrelated stuff): main.py import singleton import printer def main(): single...
How do I find out if the variable is declared in Python?
I want to use a module as a singleton referenced in other modules. It looks something like this (that's not actually a code I'm working on, but I simplified it to throw away all unrelated stuff): main.py import singleton import printer def main(): singleton.Init(1,2) printer.Print() if __name__ == '__main__': ...
[ "The assignment inside Init is forcing the variables to be treated as locals. Use the global keyword to fix this:\nvariable1 = ''\nvariable2 = ''\n\ndef Init(var1, var2)\n global variable1, variable2\n variable1 = var1\n variable2 = var2\n\n", "You can use de dictionaries vars and globals:\nvars().has_key('...
[ 7, 2 ]
[]
[]
[ "declaration", "python", "singleton", "variables" ]
stackoverflow_0002607037_declaration_python_singleton_variables.txt
Q: Python ctypes and dynamic linking I'm writing some libraries in C which contain functions that I want to call from Python via ctypes. I've done this successfully another library, but that library had only very vanilla dependencies (namely fstream, math, malloc, stdio, stdlib). The other library I'm working on has ...
Python ctypes and dynamic linking
I'm writing some libraries in C which contain functions that I want to call from Python via ctypes. I've done this successfully another library, but that library had only very vanilla dependencies (namely fstream, math, malloc, stdio, stdlib). The other library I'm working on has more complicated dependencies. For exam...
[ "OK, thanks for your help.\nto get this to work I had to include the dependencies when linking (duh). I had tried this before but got an error, so solve this I had to recompile fftw with '-fpic' as a CPP flag. all works now.\nicpc -Wall -fPIC -c waveprop.cpp -o libwaveprop.o $std_link\nicpc -shared -Wl,-soname,libw...
[ 4, 0 ]
[]
[]
[ "ctypes", "dynamic_linking", "python" ]
stackoverflow_0002606450_ctypes_dynamic_linking_python.txt
Q: Django vs. Pylons I've recently become a little frustrated with Django as a whole. It seems like I can't get full control over anything. I love Python to death, but I want to be able (and free) to do something as simple as adding a css class to an auto-generated form. One MVC framework that I have really been enj...
Django vs. Pylons
I've recently become a little frustrated with Django as a whole. It seems like I can't get full control over anything. I love Python to death, but I want to be able (and free) to do something as simple as adding a css class to an auto-generated form. One MVC framework that I have really been enjoying working with is G...
[ "I'm using Pylons right now. The flexibility is great. It's all about best-of-breed rather than The Django Way. It's more oriented toward custom application development, as opposed to content-based web sites. You can certainly do content sites in it; it's just not specifically designed for them.\nOn the other hand,...
[ 20, 5, 1, 1 ]
[]
[]
[ "django", "grails", "pylons", "python" ]
stackoverflow_0001344824_django_grails_pylons_python.txt
Q: Help with python list-comprehension A simplified version of my problem: I have a list comprehension that i use to set bitflags on a two dimensional list so: s = FLAG1 | FLAG2 | FLAG3 [[c.set_state(s) for c in row] for row in self.__map] All set_state does is: self.state |= f This works fine but I have to have th...
Help with python list-comprehension
A simplified version of my problem: I have a list comprehension that i use to set bitflags on a two dimensional list so: s = FLAG1 | FLAG2 | FLAG3 [[c.set_state(s) for c in row] for row in self.__map] All set_state does is: self.state |= f This works fine but I have to have this function "set_state" in every cell in ...
[ "List comprehensions are for creating lists. You don't seem to care about the actual lists you are making, so you should just use a for statement, like so:\nfor row in self.__map:\n for c in row:\n c.state |= s\n\n", "Yes, you're using the wrong tool. A list comprehension returns a completely new value,...
[ 4, 3, 1, 0, 0 ]
[]
[]
[ "lambda", "list_comprehension", "python" ]
stackoverflow_0002607488_lambda_list_comprehension_python.txt
Q: Access to content of Lotus Notes database without Lotus Notes software installed I am looking for a programatic way to access content in a Lotus Notes database (.nsf file) without having Lotus Notes software installed. Python would be preferred but I'm also willing to look at other languages e.g. C/C++ or other me...
Access to content of Lotus Notes database without Lotus Notes software installed
I am looking for a programatic way to access content in a Lotus Notes database (.nsf file) without having Lotus Notes software installed. Python would be preferred but I'm also willing to look at other languages e.g. C/C++ or other means e.g. SQL From what I have read, all of the methods e.g. Python COM access, pyodbc ...
[ "The short answer is, unfortunately you will need the Notes client installed. There are a few ways to access data from an NSF such as NotesSQL, COM, C/C++, but all rely on the Lotus C API at the core, and you'll need a notes client and a notes ID file to gain access via that API. \n", "If this is a one-time nee...
[ 3, 1, 0 ]
[]
[]
[ "lotus", "lotus_notes", "python" ]
stackoverflow_0002541702_lotus_lotus_notes_python.txt
Q: Django syncdb error: One or more models did not validate /mysite/project4 class notes(models.Model): created_by = models.ForeignKey(User) detail = models.ForeignKey(Details) Details and User are in the same module i.e,/mysite/project1 In project1 models i have defined class User(): ...... cla...
Django syncdb error: One or more models did not validate
/mysite/project4 class notes(models.Model): created_by = models.ForeignKey(User) detail = models.ForeignKey(Details) Details and User are in the same module i.e,/mysite/project1 In project1 models i have defined class User(): ...... class Details(): ...... When DB i synced there is an error...
[ "Gee we just had this one; and I answered...\nYou have a number of foreign keys which django is unable to generate unique names for.\nYou can help out by adding \"related_name\" arguments to the foreignkey field definitions in your models. Eg:\n class notes(models.Model):\n created_by = models.ForeignKey(User, r...
[ 8 ]
[]
[]
[ "django", "django_models", "django_views", "python" ]
stackoverflow_0002608017_django_django_models_django_views_python.txt
Q: Best option for Google App Engine Datastore and external database? I need to get an App Engine app talking to and sharing data with an external database, The best option i can come up with is outputting the external database data to an xml file and then processing this in my app engine app and storing it inside th...
Best option for Google App Engine Datastore and external database?
I need to get an App Engine app talking to and sharing data with an external database, The best option i can come up with is outputting the external database data to an xml file and then processing this in my app engine app and storing it inside the datastore, although the data being shared is sensitive data such as lo...
[ "Google Apps' Secure Data Connector (SDC) is designed for this kind of tasks -- indeed, it even works when the \"other database\" lives behind a firewall (a common case for enterprise data), and for other Google Apps (Docs, Spreadsheets, ...) as well as App Engine.\nAs the docs summarize things, the flow is:\n\nGoo...
[ 6, 3 ]
[]
[]
[ "django", "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0002606707_django_google_app_engine_google_cloud_datastore_python.txt
Q: What's the right way to use idlestartup on python 2.6.5? Idlestartup is analogous to pythonstartup variable, but for IDLE, instead of command line. But it seems not to work properly. I'm using python 2.6.5 on Windows. I have the following script assigned to it: from pprint import pprint import sys newPath = 'C:\\P...
What's the right way to use idlestartup on python 2.6.5?
Idlestartup is analogous to pythonstartup variable, but for IDLE, instead of command line. But it seems not to work properly. I'm using python 2.6.5 on Windows. I have the following script assigned to it: from pprint import pprint import sys newPath = 'C:\\Python26\test') sys.path.append(newPath) print "initial config ...
[ "sys.stdout may not be in its final state at the time idlestartup's getting loaded - so it's quite possible that a print to it tries to go to the \"original\" standard-output, and then immediately the standard output is redirected to idle's command window and so the effects of the print are never seen. In other wo...
[ 4 ]
[]
[]
[ "python", "startup" ]
stackoverflow_0002608092_python_startup.txt
Q: Problems with umlauts in python appdata environvent variable I can't find a correct way to get the environment variable for the appdata path in python. The problem is that my user name includes special characters (the german ae and ue). I made a workaround wit PyQt for Vista and Windows 7 but it doesn't work for X...
Problems with umlauts in python appdata environvent variable
I can't find a correct way to get the environment variable for the appdata path in python. The problem is that my user name includes special characters (the german ae and ue). I made a workaround wit PyQt for Vista and Windows 7 but it doesn't work for XP Systems. Does anybody know the correct encoding of these environ...
[ "As Mike says, you can get the system codepage from getfilesystemencoding. This encoding is used to convert Windows's native Unicode strings into bytes for all C stdio functions used by Python, including the filesystem calls that use byte string filepaths, and os.environ.\nWhat this means is that you will be able t...
[ 10 ]
[]
[]
[ "appdata", "encoding", "environment", "python", "variables" ]
stackoverflow_0002608200_appdata_encoding_environment_python_variables.txt
Q: Getting the attribute name that the created object will be given Before I ask this, do note: I want this for debugging purposes. I know that this is going to be some bad black magic, but I want to use it just during debugging so I could identify my objects more easily. It's like this. I have some object from class...
Getting the attribute name that the created object will be given
Before I ask this, do note: I want this for debugging purposes. I know that this is going to be some bad black magic, but I want to use it just during debugging so I could identify my objects more easily. It's like this. I have some object from class A that creates a few B instances as attributes: class A(object): ...
[ "You can use sys._getframe to get the line number where B() is called, then you can use inspect.getsourcelines to get the actual line of code. From there you can parse the line of code to get the thing to which B() is being assigned:\nimport sys\nimport inspect\n\nclass A(object):\n def __init__(self):\n ...
[ 2, 0, 0 ]
[ "Not very magical, but:\nclass A(object):\n def __init__(self)\n self.vanilla_b = B(self)\n self.chocolate_b = B(self)\n\nand:\nclass B(object):\n def __init__(self, a):\n for i in dir(a):\n if getattr(a, i) == self:\n pass # store it somewhere now\n\nEDIT: Sorry...
[ -1 ]
[ "debugging", "introspection", "magic_methods", "python" ]
stackoverflow_0002608645_debugging_introspection_magic_methods_python.txt
Q: GUI freezes when executing def function. Use threads? I've made a small program which has 2 buttons and each does certain thing. Here's a simplified version of the code. Thing is it works fine except that the button freezes and stays in a clicked position and whole GUI freezes until the command is completed. As fa...
GUI freezes when executing def function. Use threads?
I've made a small program which has 2 buttons and each does certain thing. Here's a simplified version of the code. Thing is it works fine except that the button freezes and stays in a clicked position and whole GUI freezes until the command is completed. As far as I know threads would be best to use in this situation,...
[ "pyGTK has a whole section of there FAQ devoted to threading. \n20.6 seems like a good minimal example.\n" ]
[ 0 ]
[]
[]
[ "glade", "pygtk", "python" ]
stackoverflow_0002608922_glade_pygtk_python.txt
Q: Splitting tuples in Python - best practice? I have a method in my Python code that returns a tuple - a row from a SQL query. Let's say it has three fields: (jobId, label, username) For ease of passing it around between functions, I've been passing the entire tuple as a variable called 'job'. Eventually, however, I...
Splitting tuples in Python - best practice?
I have a method in my Python code that returns a tuple - a row from a SQL query. Let's say it has three fields: (jobId, label, username) For ease of passing it around between functions, I've been passing the entire tuple as a variable called 'job'. Eventually, however, I want to get at the bits, so I've been using code...
[ "@Staale\nThere is a better way:\njob = dict(zip(keys, values))\n\n", "I'd say that a dictionary is definitely the best way to do it. It's easily extensible, allows you to give each value a sensible name, and Python has a lot of built-in language features for using and manipulating dictionaries. If you need to ...
[ 14, 13, 5, 3, 2, 2, 0, 0 ]
[ "How about this:\nclass TypedTuple:\n def __init__(self, fieldlist, items):\n self.fieldlist = fieldlist\n self.items = items\n def __getattr__(self, field):\n return self.items[self.fieldlist.index(field)]\n\nYou could then do:\nj = TypedTuple([\"jobid\", \"label\", \"username\"], job)\npri...
[ -2 ]
[ "python", "tuples" ]
stackoverflow_0000041701_python_tuples.txt
Q: Python: needs more than 1 value to unpack What am I doing wrong to get this error? replacements = {} replacements["**"] = ("<strong>", "</strong>") replacements["__"] = ("<em>", "</em>") replacements["--"] = ("<blink>", "</blink>") replacements["=="] = ("<marquee>", "</marquee>") replacemen...
Python: needs more than 1 value to unpack
What am I doing wrong to get this error? replacements = {} replacements["**"] = ("<strong>", "</strong>") replacements["__"] = ("<em>", "</em>") replacements["--"] = ("<blink>", "</blink>") replacements["=="] = ("<marquee>", "</marquee>") replacements["@@"] = ("<code>", "</code>") for delim...
[ "It should be:\nfor delimiter, (open_tag, close_tag) in replacements.iteritems(): # or .items() in py3k\n\n", "I think you need to call .items() like the third example in this link\nfor delimiter, (open_tag, close_tag) in replacements.items(): # error here\n message = self.replaceFormatting(delimiter, message,...
[ 10, 3 ]
[]
[]
[ "python", "syntax" ]
stackoverflow_0002609136_python_syntax.txt
Q: Problem with literal arguments in the PATTERN string for a python 2to3 fixer I'm writing a fixer for the 2to3 tool in python. In my pattern string, I have a section where I'd like to match an empty string as an argument, or an empty unicode string. The relevant chunk of my pattern looks like: (args='""' | args='u"...
Problem with literal arguments in the PATTERN string for a python 2to3 fixer
I'm writing a fixer for the 2to3 tool in python. In my pattern string, I have a section where I'd like to match an empty string as an argument, or an empty unicode string. The relevant chunk of my pattern looks like: (args='""' | args='u""') My issue is the second option never matches. Even if it's alone, it won't mat...
[ "Because 2to3 pattern matching is designed to match tokens not literals, there is no way to do this directly.\nInstead you could match (args=STRING) and then determine the value of the string argument inside the transformation function and handle it appropriately.\n" ]
[ 1 ]
[]
[]
[ "pattern_matching", "python", "python_2to3", "special_characters", "unicode" ]
stackoverflow_0002588286_pattern_matching_python_python_2to3_special_characters_unicode.txt
Q: Converting string with UTC offset to a datetime object Given this string: "Fri, 09 Apr 2010 14:10:50 +0000" how does one convert it to a datetime object? After doing some reading I feel like this should work, but it doesn't... >>> from datetime import datetime >>> >>> str = 'Fri, 09 Apr 2010 14:10:50 +0000' >>> fm...
Converting string with UTC offset to a datetime object
Given this string: "Fri, 09 Apr 2010 14:10:50 +0000" how does one convert it to a datetime object? After doing some reading I feel like this should work, but it doesn't... >>> from datetime import datetime >>> >>> str = 'Fri, 09 Apr 2010 14:10:50 +0000' >>> fmt = '%a, %d %b %Y %H:%M:%S %z' >>> datetime.strptime(str, fm...
[ "It looks as if strptime doesn't always support %z. Python appears to just call the C function, and strptime doesn't support %z on your platform.\nNote: from Python 3.2 onwards it will always work.\n" ]
[ 40 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0002609259_datetime_python.txt
Q: Running a python script on all the files in a directory I have a Python script that reads through a text csv file and creates a playlist file. However I can only do one at a time, like: python playlist.py foo.csv foolist.txt However, I have a directory of files that need to be made into a playlist, with different...
Running a python script on all the files in a directory
I have a Python script that reads through a text csv file and creates a playlist file. However I can only do one at a time, like: python playlist.py foo.csv foolist.txt However, I have a directory of files that need to be made into a playlist, with different names, and sometimes a different number of files. So far I h...
[ "for f in *.csv; do\n python playlist.py \"$f\" \"${f%.csv}list.txt\"\ndone\n\nWill that do the trick? This will put foo.csv in foolist.txt and abc.csv in abclist.txt.\nOr do you want them all in the same file?\n", "Just use a for loop with the asterisk glob, making sure you quote things appropriately for spaces...
[ 11, 6, 4, 2 ]
[]
[]
[ "command_line", "python", "scripting" ]
stackoverflow_0002609159_command_line_python_scripting.txt
Q: How to correctly relay TCP traffic between sockets? I'm trying to write some Python code that will establish an invisible relay between two TCP sockets. My current technique is to set up two threads, each one reading and subsequently writing 1kb of data at a time in a particular direction (i.e. 1 thread for A to B...
How to correctly relay TCP traffic between sockets?
I'm trying to write some Python code that will establish an invisible relay between two TCP sockets. My current technique is to set up two threads, each one reading and subsequently writing 1kb of data at a time in a particular direction (i.e. 1 thread for A to B, 1 thread for B to A). This works for some applications ...
[ "\nIs it possible to only read from\n socket A when we know that B is ready\n to receive data?\n\nSure: use select.select on both sockets A and B (if it returns saying only one of them is ready, use it on the other one), and only read from A and write to B when you know they're both ready. E.g.:\nimport select\n...
[ 5, 1, 1 ]
[]
[]
[ "portforwarding", "python", "sockets", "tcp" ]
stackoverflow_0002604740_portforwarding_python_sockets_tcp.txt
Q: Python Mindstorms RCX I've got 30 unopened Lego Mindstorms kits that I'd love to use in my intro programming class to do some simple robotics stuff at the end of the year. We're using Python in the class, so I'd prefer there to be a way for the kids to write the programs in Python. Unfortunately, these are old kit...
Python Mindstorms RCX
I've got 30 unopened Lego Mindstorms kits that I'd love to use in my intro programming class to do some simple robotics stuff at the end of the year. We're using Python in the class, so I'd prefer there to be a way for the kids to write the programs in Python. Unfortunately, these are old kits with RCX bricks - not the...
[ "Running Python on the brick itself is probably hard (for the reason others already stated - size of the interpreter, available RAM on the brick for example) but this might be of interest:\nAccording to this thread you should be able to use pylnp (remote) combined with BrickOS (on the brick; formerly legOS).\n", ...
[ 3, 2 ]
[]
[]
[ "lego_mindstorms", "python" ]
stackoverflow_0002596929_lego_mindstorms_python.txt
Q: "cannot concatenate 'str' and 'list' objects" keeps coming up :( I'm writing a python program. The program calculates Latin Squares using two numbers the user enters on a previous page. But but an error keeps coming up, "cannot concatenate 'str' and 'list' objects" here is the program: #!/usr/bin/env python # -*- ...
"cannot concatenate 'str' and 'list' objects" keeps coming up :(
I'm writing a python program. The program calculates Latin Squares using two numbers the user enters on a previous page. But but an error keeps coming up, "cannot concatenate 'str' and 'list' objects" here is the program: #!/usr/bin/env python # -*- coding: UTF-8 -*- # enable debugging import cgi import cgitb cgitb.en...
[ "range returns a list object, so when you say \nline = calc_range(first_line_num, int1)\n\nYou are assigning a list to line. This is why out_str += line throws the error.\nYou can use str() to convert a list to a string, or you can build up a string a different way to get the results you are looking for.\n", "By ...
[ 4, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002609460_python.txt
Q: What are the differences among sqlite3 from python2.5, pysqlite and apsw I would like to know the differences among sqlite3 from python2.5, pysqlite and apsw? I have a bumpy run when trying to install pysqlite on windows vista with python2.5, see following: download sqlite from http://sqlite.org/download.html an...
What are the differences among sqlite3 from python2.5, pysqlite and apsw
I would like to know the differences among sqlite3 from python2.5, pysqlite and apsw? I have a bumpy run when trying to install pysqlite on windows vista with python2.5, see following: download sqlite from http://sqlite.org/download.html and unzip them into windows/system32 folder and put sqlite3.dll into c:/python25...
[ "pysqlite is the same as sqlite3 (which is built in to the windows binary package for python 2.5)\n", "Still, the pysqlite site-package includes more patches. It is version 2.6.0 whereas the built-in module is version 2.3.2. The error when importing pysqlite2.test may occur if you are in the pysqlite package dire...
[ 3, 2 ]
[]
[]
[ "pysqlite", "python", "sqlite" ]
stackoverflow_0002608958_pysqlite_python_sqlite.txt
Q: smtp text message code not sending I have a python code to send a text message to your cellphone using SMTP. when I run it I don't get any errors, but it doesn't send the text message. My code isn't finished, right now I am just getting the basics down. Any help on making it send would be appreciated. #infile = op...
smtp text message code not sending
I have a python code to send a text message to your cellphone using SMTP. when I run it I don't get any errors, but it doesn't send the text message. My code isn't finished, right now I am just getting the basics down. Any help on making it send would be appreciated. #infile = open('companyname.txt', 'r') import sys i...
[ "Start with the basics, enable debugging for the smtp object and see what you get.\nsmtpObj = smtplib.SMTP('smtp.comcast.net') \nsmtpObj.set_debuglevel(10)\nsmtpObj.sendmail(sender,reciever , message)\n\nYou can read about the set_debuglevel call here.\n", "Change\nsmtpObj.sendmail(sender,reciever , messa...
[ 1, 1 ]
[]
[]
[ "message", "python", "smtp", "text" ]
stackoverflow_0002609879_message_python_smtp_text.txt
Q: Dumping one class type with Django dumpdata I use dumpdata to output all my apps's classes. One of my app has one class that never get's outputted and I don't know where to start looking to know what's wrong. The class is used regularly, every other classes in the app are dumped fine and dumpdata doesn't throw any...
Dumping one class type with Django dumpdata
I use dumpdata to output all my apps's classes. One of my app has one class that never get's outputted and I don't know where to start looking to know what's wrong. The class is used regularly, every other classes in the app are dumped fine and dumpdata doesn't throw any error. Any clue ?
[ "You might try serializing it to json and see if you get any errors there -- maybe there's a subtle inconsistency that's messing up the serialization.\n>>> from django.core import serializers\n>>> from myapp.mymodels import mymodel\n>>> serializers.serialize('json', mymodel.objects.all())\n[...]\n\nThis might be wo...
[ 1 ]
[]
[]
[ "django", "dump", "python" ]
stackoverflow_0002603427_django_dump_python.txt
Q: Fast math operations on an array in python I have a fairly simple math operation I'd like to perform on a array. Let me write out the example: A = numpy.ndarray((255, 255, 3), dtype=numpy.single) # .. for i in range(A.shape[0]): for j in range(A.shape[1]): x = simple_func1(i) y = simple_func2(j...
Fast math operations on an array in python
I have a fairly simple math operation I'd like to perform on a array. Let me write out the example: A = numpy.ndarray((255, 255, 3), dtype=numpy.single) # .. for i in range(A.shape[0]): for j in range(A.shape[1]): x = simple_func1(i) y = simple_func2(j) A[i, j] = (alpha * x * y + beta * x**2...
[ "Here is the vectorized version:\ni = arange(255)\nj = arange(255)\nx = simple_func1(i)\ny = simple_func2(j)\ny = y.reshape(-1,1) \n\nA = alpha * x * y + beta * x**2 + gamma * y**2 # broadcasting is your friend here\n\nIf you want to fill the last coordinates with 1 and 0:\nB = empty(A.shape+(3,))\nB[:,:,0] = A\...
[ 3, 1 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0002610184_numpy_python.txt
Q: Python Script to check website for a tag I'm trying to figure out how to go about writing a website monitoring script (cron job in the end) to open up a given URL, check to see if a tag exists, and if the tag does not exist, or doesn't contain the expected data, then to write some to a log file, or to send an e-ma...
Python Script to check website for a tag
I'm trying to figure out how to go about writing a website monitoring script (cron job in the end) to open up a given URL, check to see if a tag exists, and if the tag does not exist, or doesn't contain the expected data, then to write some to a log file, or to send an e-mail. The tag would be something like or someth...
[ "Your best bet imo is to check out BeautifulSoup. Something like so:\nimport urllib2\nfrom BeautifulSoup import BeautifulSoup\n\npage = urllib2.urlopen(\"http://yoursite.com\")\nsoup = BeautifulSoup(page)\n\n# See the docs on how to search through the soup. I'm not sure what\n# you're looking for so my example stop...
[ 5, 2, 1 ]
[]
[]
[ "crontab", "html", "linux", "python", "scripting" ]
stackoverflow_0002610395_crontab_html_linux_python_scripting.txt
Q: Hide deprecated methods from tab completion I would like to control which methods appear when a user uses tab-completion on a custom object in ipython - in particular, I want to hide functions that I have deprecated. I still want these methods to be callable, but I don't want users to see them and start using them...
Hide deprecated methods from tab completion
I would like to control which methods appear when a user uses tab-completion on a custom object in ipython - in particular, I want to hide functions that I have deprecated. I still want these methods to be callable, but I don't want users to see them and start using them if they are inspecting the object. Is this somet...
[ "Partial answer for you. I'll post the example code and then explain why its only a partial answer.\nCode:\nclass hidden(object): # or whatever its parent class is\n def __init__(self):\n self.value = 4\n def show(self):\n return self.value\n def change(self,n):\n self.value = n\n ...
[ 4, 1, 0, 0 ]
[]
[]
[ "ipython", "python" ]
stackoverflow_0002531479_ipython_python.txt
Q: Python: Get items at depth? (set library?) I have a nested list something like this: PLACES = ( ('CA', 'Canada', ( ('AB', 'Alberta'), ('BC', 'British Columbia' ( ('van', 'Vancouver'), ), ... )), ('US', 'United States', ( ('AL', 'Alabama'), ('A...
Python: Get items at depth? (set library?)
I have a nested list something like this: PLACES = ( ('CA', 'Canada', ( ('AB', 'Alberta'), ('BC', 'British Columbia' ( ('van', 'Vancouver'), ), ... )), ('US', 'United States', ( ('AL', 'Alabama'), ('AK', 'Alaska'), ... I need to retrieve s...
[ "Here is a solution which will work for any depth:\ndef depthGenerator(seq, depth):\n if depth==0:\n for x in seq:\n yield x[:2] #strip subsequences\n return\n\n for x in seq:\n if len(x)==3: #has subsequence?\n for y in depthGenerator(x[2], depth-1):\n ...
[ 5, 1, 1 ]
[]
[]
[ "algorithm", "list", "python", "set" ]
stackoverflow_0002610588_algorithm_list_python_set.txt
Q: A better python property decorator I've inherited some python code that contains a rather cryptic decorator. This decorator sets properties in classes all over the project. The problem is that this I have traced my debugging problems to this decorator. Seems it "fubars" all debuggers I've tried and trying to speed...
A better python property decorator
I've inherited some python code that contains a rather cryptic decorator. This decorator sets properties in classes all over the project. The problem is that this I have traced my debugging problems to this decorator. Seems it "fubars" all debuggers I've tried and trying to speed up the code with psyco breaks everthing...
[ "The same thing? No. You can't do what that decorator does without magic like sys.settrace. (It technically doesn't have to be sys.settrace, but using something else -- like bytecode rewriting -- wouldn't be an improvement.) You can make it a lot simpler by doing, for example:\ndef Property(f): \n fget, fset, ...
[ 8, 2 ]
[]
[]
[ "debugging", "decorator", "properties", "python" ]
stackoverflow_0002610621_debugging_decorator_properties_python.txt
Q: How to compare 2 lists and merge them in Python/MySQL? I want to merge data. Following are my MySQL tables. I want to use Python to traverse though a list of both Lists (one with dupe = 'x' and other with null dupes). This is sample data. Actual data is humongous. For instance : a b c d e f key dupe --------------...
How to compare 2 lists and merge them in Python/MySQL?
I want to merge data. Following are my MySQL tables. I want to use Python to traverse though a list of both Lists (one with dupe = 'x' and other with null dupes). This is sample data. Actual data is humongous. For instance : a b c d e f key dupe -------------------- 1 d c f k l 1 x 2 g h j 1 3 i h u u 2 4 u...
[ "OK, let's have some fun...\nmysql> create table so (a int, b char, c char, d char, e char, f char, `key` int, dupe char);\nQuery OK, 0 rows affected (0.05 sec)\n\nmysql> insert into so values (1, 'd', 'c', 'f', 'k', 'l', 1, 'x'), (2, 'g', null, 'h', null, 'j', 1, null), (3, 'i', null, 'h', 'u', 'u', 2, null), (4, ...
[ 2 ]
[]
[]
[ "duplicate_data", "duplicates", "merge", "mysql", "python" ]
stackoverflow_0002610443_duplicate_data_duplicates_merge_mysql_python.txt
Q: Django project models.py versus app models.py I am learning Django and I am trying to understand the use of models.py in the project versus the application. It seems from the tutorial examples that I include a model definition in the app, but when I went to apply that knowledge to my own existing database I got s...
Django project models.py versus app models.py
I am learning Django and I am trying to understand the use of models.py in the project versus the application. It seems from the tutorial examples that I include a model definition in the app, but when I went to apply that knowledge to my own existing database I got stuck. I took a database that I use (a copy of cours...
[ "There shouldn't be any reason to have \"project level models\" (or \"project level views\" for that matter). You just need to split the functionality into separate apps.\nLet's say you are designing an intranet website for a school. You would have one app that deals with students' accounts, and another app generat...
[ 27, 9, 6 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0002610727_django_django_models_python.txt
Q: Can zlib.crc32 or zlib.adler32 be safely used to mask primary keys in URLs? In Django Design Patterns, the author recommends using zlib.crc32 to mask primary keys in URLs. After some quick testing, I noticed that crc32 produces negative integers about half the time, which seems undesirable for use in a URL. zlib.a...
Can zlib.crc32 or zlib.adler32 be safely used to mask primary keys in URLs?
In Django Design Patterns, the author recommends using zlib.crc32 to mask primary keys in URLs. After some quick testing, I noticed that crc32 produces negative integers about half the time, which seems undesirable for use in a URL. zlib.adler32 does not appear to produce negatives, but is described as "weaker" than CR...
[ "You can interpret the 32 bit CRC value as an unsigned integer.\n", "Upon further investigation, this seems like a really bad idea:\nIn [11]: s = set([zlib.crc32(str(x)) for x in xrange(20000000)])\nIn [12]: len(s)\nOut[12]: 19989760\nIn [13]: 20000000 - len(s)\nOut[13]: 10240\n\nThat's 10,240 collisions in 20,00...
[ 1, 1, 1 ]
[]
[]
[ "crc", "primary_key", "python", "url", "zlib" ]
stackoverflow_0002610677_crc_primary_key_python_url_zlib.txt
Q: Python-daemon doesn't kill its kids When using python-daemon, I'm creating subprocesses likeso: import multiprocessing class Worker(multiprocessing.Process): def __init__(self, queue): self.queue = queue # we wait for things from this in Worker.run() ... q = multiprocessing.Queue() with daemon.Daem...
Python-daemon doesn't kill its kids
When using python-daemon, I'm creating subprocesses likeso: import multiprocessing class Worker(multiprocessing.Process): def __init__(self, queue): self.queue = queue # we wait for things from this in Worker.run() ... q = multiprocessing.Queue() with daemon.DaemonContext(): for i in xrange(3): ...
[ "Your options are a bit limited. If doing self.daemon = True in the constructor for the Worker class does not solve your problem and trying to catch signals in the Parent (ie, SIGTERM, SIGINT) doesn't work, you may have to try the opposite solution - instead of having the parent kill the children, you can have the ...
[ 32, 4, 2 ]
[]
[]
[ "children", "daemon", "multiprocessing", "python", "zombie_process" ]
stackoverflow_0002542610_children_daemon_multiprocessing_python_zombie_process.txt
Q: Making all variables accessible to namespace Say I have a simple function: def myfunc(): a = 4.2 b = 5.5 ... many similar variables ... I use this function one time only and I am wondering what is the easiest way to make all the variables inside the function accessible to my main name-space. Do I hav...
Making all variables accessible to namespace
Say I have a simple function: def myfunc(): a = 4.2 b = 5.5 ... many similar variables ... I use this function one time only and I am wondering what is the easiest way to make all the variables inside the function accessible to my main name-space. Do I have to declare global for each item? or any other su...
[ "Best way, in my biased opinion, is to wrap the dictionary into a nice object where the \"variables\" are accessed as attributes -- the pattern I named Bunch when I introduced it many years ago, and a great example of the last item in the Zen of Python (if you don't know what that is, import this at an interpreter ...
[ 8, 5, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002610931_python.txt
Q: Installing Python Script, Maintaining Reference to Python 2.6 I am trying to distribute my Python program. The program relies on version 2.6. I went through the distribution documentation: http://docs.python.org/distutils/index.html and what I have figured out so far is that I basically need to write a setup.py sc...
Installing Python Script, Maintaining Reference to Python 2.6
I am trying to distribute my Python program. The program relies on version 2.6. I went through the distribution documentation: http://docs.python.org/distutils/index.html and what I have figured out so far is that I basically need to write a setup.py script. Something like: setup(name='Distutils', version='1.0', de...
[ "One option is to specify the specific version of the Python interpreter using the hash bang:\n\n#! /usr/bin/env python2.6\n\nAnother option is to check sys.version_info, for example:\n\nif (sys.version_info[0] != 2) or (sys.version_info[1]<6):\n if sys.version_info[0] > 2:\n print(\"Version 2.6+, and not...
[ 1, 0 ]
[]
[]
[ "distribution", "programming_languages", "python" ]
stackoverflow_0002611430_distribution_programming_languages_python.txt
Q: Any tips on moving from ActionScript 3 to Python? I've been developing stuff using ActionScript since AS2,and when AS3 was released i had a bit of a hard time to understand its concepts. Then i realized i had to learn some OOP. I started studying OOP and now i feel i need to take a step further, that's why i chose...
Any tips on moving from ActionScript 3 to Python?
I've been developing stuff using ActionScript since AS2,and when AS3 was released i had a bit of a hard time to understand its concepts. Then i realized i had to learn some OOP. I started studying OOP and now i feel i need to take a step further, that's why i chose Python. Are there any tips/advices/hints or whatever l...
[ "I can tell you that I started to understand ActionScript much better after reading Learning Python and Python Tutorial in the meantime\n" ]
[ 0 ]
[]
[]
[ "actionscript", "migration", "oop", "python" ]
stackoverflow_0002611045_actionscript_migration_oop_python.txt
Q: Deploying Pylons with uWSGI We're trying to move our intranet to Pylons. My boss is trying to set up Pylons to use uWSGI behind Apache so he can set up multiple, independent applications. However, he's having a difficult time getting it set up, with some apparent code problems in the C source code for uWSGI. Does ...
Deploying Pylons with uWSGI
We're trying to move our intranet to Pylons. My boss is trying to set up Pylons to use uWSGI behind Apache so he can set up multiple, independent applications. However, he's having a difficult time getting it set up, with some apparent code problems in the C source code for uWSGI. Does anyone have any suggestions for h...
[ "Here is how I did it:\nhttp://tonylandis.com/python/deployment-howt-pylons-nginx-and-uwsgi/\n", "You can directly use paste for deploying pylons on uWSGI: \nhttp://projects.unbit.it/uwsgi/wiki/UsePaste\n", "The Pylons documentation contains very detailed instructions about deployment. \nIs there anything speci...
[ 6, 3, 0 ]
[]
[]
[ "apache", "deployment", "pylons", "python", "uwsgi" ]
stackoverflow_0002217679_apache_deployment_pylons_python_uwsgi.txt
Q: Loading Files in AppEngine I've got a tiny bit of code to display a file in app.yaml - url: /(.*\.(gif|png|jpg)) static_files: static/\1 upload: static/(.*\.(gif|png|jpg)) in main.py ... class ShowImage(webapp.RequestHandler): def get(self): rootpath = os.path.dirname(__file__) file = rootpath +...
Loading Files in AppEngine
I've got a tiny bit of code to display a file in app.yaml - url: /(.*\.(gif|png|jpg)) static_files: static/\1 upload: static/(.*\.(gif|png|jpg)) in main.py ... class ShowImage(webapp.RequestHandler): def get(self): rootpath = os.path.dirname(__file__) file = rootpath + "/static/tracker.gif"; fh...
[ "Removed \n- url: /(.*\\.(gif|png|jpg))\n static_files: static/\\1\n upload: static/(.*\\.(gif|png|jpg))\n\nfrom app.yaml apparently you cant serve content from folders you daftly marked as static\nAs from Deployment of static directory contents to google app engine\n", "To spell out what Chris M. is referring ...
[ 3, 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0002607063_google_app_engine_python.txt
Q: How to use the _Qt python module? There is a python module called "_Qt". PyQt is not what I want. I was wondering if there was any documentation for the _Qt module installed with python as a standard module. I have a mac. A: That's QuickTime, nothing to do with Qt. In your question it's not really clear if you i...
How to use the _Qt python module?
There is a python module called "_Qt". PyQt is not what I want. I was wondering if there was any documentation for the _Qt module installed with python as a standard module. I have a mac.
[ "That's QuickTime, nothing to do with Qt.\nIn your question it's not really clear if you intended to use Qt or QuickTime.\n" ]
[ 0 ]
[]
[]
[ "module", "python", "qt" ]
stackoverflow_0002611593_module_python_qt.txt
Q: How to rotate the text of a wx.StaticText? I want to write a Static Text with an upside down ^ How can I do it? A: There are a couple of approaches. 1) If you actually want to do the rotation, you can do it by drawing the text to a wx.GraphicsContext and then rotation it there, write this to a bitmap, and displa...
How to rotate the text of a wx.StaticText?
I want to write a Static Text with an upside down ^ How can I do it?
[ "There are a couple of approaches.\n1) If you actually want to do the rotation, you can do it by drawing the text to a wx.GraphicsContext and then rotation it there, write this to a bitmap, and display that.\n2) It might be easier to find the right unicode symbol. Having spent way too much of my time lately lookin...
[ 3, 0 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0002610494_python_wxpython.txt
Q: Python Comet Server I am building a web application that has a real-time feed (similar to Facebook's newsfeed) that I want to update via a long-polling mechanism. I understand that with Python, my choices are pretty much to either use Stackless (building from their Comet wsgi example) or Cometd + Twisted. Unfortun...
Python Comet Server
I am building a web application that has a real-time feed (similar to Facebook's newsfeed) that I want to update via a long-polling mechanism. I understand that with Python, my choices are pretty much to either use Stackless (building from their Comet wsgi example) or Cometd + Twisted. Unfortunately there is very littl...
[ "Orbited seems as a nice solution. Haven't tried it though.\n\nUpdate: things have changed in the last 2.5 years.\nWe now have websockets in all major browsers, except IE (naturally) and a couple of very good abstractions over it, that provide many methods of emulating real-time communication.\n\nsocket.io along wi...
[ 13, 9, 6, 4, 2, 1, 1 ]
[]
[]
[ "cometd", "python", "python_stackless" ]
stackoverflow_0000960969_cometd_python_python_stackless.txt
Q: Create thumbnail images for jpegs with python As the title says i am looking for a way convert a huge number of images into thumbnails of different sizes , How do i go about doing this in python A: See: http://www.pythonware.com/products/pil/index.htm import os, sys import Image size = 128, 128 for infile in ...
Create thumbnail images for jpegs with python
As the title says i am looking for a way convert a huge number of images into thumbnails of different sizes , How do i go about doing this in python
[ "See: http://www.pythonware.com/products/pil/index.htm\nimport os, sys\nimport Image\n\nsize = 128, 128\n\nfor infile in sys.argv[1:]:\n outfile = os.path.splitext(infile)[0] + \".thumbnail\"\n if infile != outfile:\n try:\n im = Image.open(infile)\n im.thumbnail(size)\n ...
[ 22 ]
[]
[]
[ "image_processing", "python" ]
stackoverflow_0002612436_image_processing_python.txt
Q: How to create make .so files from code written in C or C++ that are usable from Python Looking at Python modules and at code in the "lib-dnyload" directory in the Python framework, I noticed whenever code is creating some kind of GUI or graphic it imports a non-Python file with a .so extension. And there are tons ...
How to create make .so files from code written in C or C++ that are usable from Python
Looking at Python modules and at code in the "lib-dnyload" directory in the Python framework, I noticed whenever code is creating some kind of GUI or graphic it imports a non-Python file with a .so extension. And there are tons .so files in "lib-dnyload". From googling things I found that these files are called shared...
[ "Official python documentation starts with simple example. It's good enough for start.\n", "In my opinion the easiest way is to use Cython. Cython will generate some C code for you, compile it to make a \".so\" library that you can load from python. This is easy and painless. I suggest you to follow the tutorial ...
[ 4, 2, 2, 0, 0 ]
[]
[]
[ "distutils", "gcc", "macos", "python", "shared_objects" ]
stackoverflow_0002610421_distutils_gcc_macos_python_shared_objects.txt
Q: Including a pyd directly in a setup.py file I have a complex build process to generate a couple of python extension modules (.pyd). I want to include these in my setup.py for use with distutils. The distutils page talks in length about how to add extension modules from source, but I'd want to simply package these ...
Including a pyd directly in a setup.py file
I have a complex build process to generate a couple of python extension modules (.pyd). I want to include these in my setup.py for use with distutils. The distutils page talks in length about how to add extension modules from source, but I'd want to simply package these precompiled .pyd. What is the best practice to do...
[ "You could add your extension name to 'includes' \noptions={\n 'py2exe':{'includes':['yourextensionname_without_pyd']}\n}\n\nHere is the list of options from py2exe site\n" ]
[ 1 ]
[]
[]
[ "distutils", "python" ]
stackoverflow_0002612518_distutils_python.txt
Q: python lists error A=s.append(s[i]+A+B) A=s.append(s[i]+A+B) TypeError: unsupported operand type(s) for +: 'long' and 'str' What does this error mean ? A and B are strings and s is a list A: s may be a list, but the element - s[i] - is not - it's a long, as indicated by the error. In addition, append() operates...
python lists error
A=s.append(s[i]+A+B) A=s.append(s[i]+A+B) TypeError: unsupported operand type(s) for +: 'long' and 'str' What does this error mean ? A and B are strings and s is a list
[ "s may be a list, but the element - s[i] - is not - it's a long, as indicated by the error.\nIn addition, append() operates on the list directly - it returns None, so you're actually setting A to be None - probably not what you wanted!\nThere are two things you can do to help avoid this type of error in the future....
[ 4, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002612507_python.txt
Q: indexing error in list in python B=l.append((l[i]+A+B)) l is a list here and i am trying to append into it more value for it to act as an array . But its still giving me error like list index out of range . How to get rid of it ? A: List index out of range means that i is greater than len(l) - 1 (since Python,...
indexing error in list in python
B=l.append((l[i]+A+B)) l is a list here and i am trying to append into it more value for it to act as an array . But its still giving me error like list index out of range . How to get rid of it ?
[ "List index out of range means that i is greater than len(l) - 1 (since Python, and many other programming languages, use indexing that starts at 0 instead of 1, the last item in the list has index len(l) - 1, not just len(l).\nTry debugging like so:\ntry:\n B = l.append((l[i] + A + B))\nexcept IndexError:\n ...
[ 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002612461_python.txt
Q: How do you construct an array suitable for numpy sorting? I need to sort two arrays simultaneously, or rather I need to sort one of the arrays and bring the corresponding element of its associated array with it as I sort. That is if the array is [(5, 33), (4, 44), (3, 55)] and I sort by the first axis (labeled be...
How do you construct an array suitable for numpy sorting?
I need to sort two arrays simultaneously, or rather I need to sort one of the arrays and bring the corresponding element of its associated array with it as I sort. That is if the array is [(5, 33), (4, 44), (3, 55)] and I sort by the first axis (labeled below dtype='alpha') then I want: [(3.0, 55.0) (4.0, 44.0) (5.0, ...
[ "I think what you want is the zip function. If you have \nx = [1,2,3]\ny = [4,5,6]\n\nthen zip(x,y) == [(1,4),(2,5),(3,6)]\nSo your array could be constructed using\na = numpy.array(zip(x,y), dtype=dtype)\n\n", "for your bonus question -- zip actually unzips too:\nIn [1]: a = range(10)\nIn [2]: b = range(10, 20)...
[ 6, 3, 3, 3, 2, 1 ]
[]
[]
[ "algorithm", "arrays", "numpy", "python" ]
stackoverflow_0000560283_algorithm_arrays_numpy_python.txt
Q: struct.error: unpack requires a string argument of length 4 Python says I need 4 bytes for a format code of "BH": struct.error: unpack requires a string argument of length 4 Here is the code, I am putting in 3 bytes as I think is needed: major, minor = struct.unpack("BH", self.fp.read(3)) "B" Unsigned char (1 by...
struct.error: unpack requires a string argument of length 4
Python says I need 4 bytes for a format code of "BH": struct.error: unpack requires a string argument of length 4 Here is the code, I am putting in 3 bytes as I think is needed: major, minor = struct.unpack("BH", self.fp.read(3)) "B" Unsigned char (1 byte) + "H" Unsigned short (2 bytes) = 3 bytes (!?) struct.calcsize...
[ "The struct module mimics C structures. It takes more CPU cycles for a processor to read a 16-bit word on an odd address or a 32-bit dword on an address not divisible by 4, so structures add \"pad bytes\" to make structure members fall on natural boundaries. Consider:\nstruct { 11\n char a; ...
[ 28, 8 ]
[]
[]
[ "python", "struct" ]
stackoverflow_0002611858_python_struct.txt
Q: error in python d not defined. I am learning python and have this error . I can figure out where\what the error is in the code. File "<string>", line 1, in <module>. Name = "" Desc = "" Gender = "" Race = "" # Prompt user for user-defined information Name = input('What is your Name? ') Desc = input('Describe yours...
error in python d not defined.
I am learning python and have this error . I can figure out where\what the error is in the code. File "<string>", line 1, in <module>. Name = "" Desc = "" Gender = "" Race = "" # Prompt user for user-defined information Name = input('What is your Name? ') Desc = input('Describe yourself: ') When i run the program it ...
[ "In Python 2.x, input() expects something which is a Python expression, which means that if you type d it interprets that as a variable named d. If you typed \"d\", then it would be fine.\nWhat you probably actually want for 2.x is raw_input(), which returns the entered value as a raw string instead of evaluating i...
[ 21, 4, 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0002612948_python_python_3.x.txt
Q: What Can A 'TreeDict' (Or Treemap) Be Used For In Practice? I'm developing a 'TreeDict' class in Python. This is a basically a dict that allows you to retrieve its key-value pairs in sorted order, just like the Treemap collection class in Java. I've implemented some functionality based on the way unique indexes i...
What Can A 'TreeDict' (Or Treemap) Be Used For In Practice?
I'm developing a 'TreeDict' class in Python. This is a basically a dict that allows you to retrieve its key-value pairs in sorted order, just like the Treemap collection class in Java. I've implemented some functionality based on the way unique indexes in relational databases can be used, e.g. functions to let you ret...
[ "I've seen several answers pointing to the \"walk in ordered sequence\" feature, which is indeed important, but none highlighting the other big feature, which is \"find first entry with a key >= this\". This has many uses even when there's no real need to \"walk\" from there.\nFor example (this came up in a recent ...
[ 6, 2, 2, 1, 1, 1, 0 ]
[]
[]
[ "collections", "dictionary", "python", "treemap", "uses" ]
stackoverflow_0001014247_collections_dictionary_python_treemap_uses.txt
Q: Python: Is there a way to reflectivly list all attributes of a class Given a class such as class MyClass: text = "hello" number = 123 Is there a way in python to inspect MyClass an determine that it has the two attributes text and number. I can not use something like inspect.getSource(object) because the ...
Python: Is there a way to reflectivly list all attributes of a class
Given a class such as class MyClass: text = "hello" number = 123 Is there a way in python to inspect MyClass an determine that it has the two attributes text and number. I can not use something like inspect.getSource(object) because the class I am to get it's attributes for are generate using SWIG (so they are...
[ "I usually just use dir(MyClass). Works on instantiated objects too.\nedit:\nI should mention this is a shorthand function I use for figuring out if my objects are getting created correctly. You might want to look more carefully into the reflection API's if you're doing this programmatically. \nAlso it may not work...
[ 8, 0 ]
[ "Please write actual, executable code snippets; don't expect people answering your question to first fix your code.\nclass MyClass(object):\n text = \"hello\"\n number = 123\n\nfor a in dir(MyClass):\n print a\n\n" ]
[ -1 ]
[ "python", "reflection", "swig" ]
stackoverflow_0002612257_python_reflection_swig.txt
Q: SQLAlchemy unsupported type error - and table design issues? back again with some more SQLAlchemy shenanigans. Let me step through this. My table is now set up as so: engine = create_engine('sqlite:///:memory:', echo=False) metadata = MetaData() students_table = Table('studs', metadata, Column('sid', Integer...
SQLAlchemy unsupported type error - and table design issues?
back again with some more SQLAlchemy shenanigans. Let me step through this. My table is now set up as so: engine = create_engine('sqlite:///:memory:', echo=False) metadata = MetaData() students_table = Table('studs', metadata, Column('sid', Integer, primary_key=True), Column('name', String), Column('prefe...
[ "Do you expect that SQLAlchemy magically convert your object and collection of objects to integer value? It's impossible. SQLAlchemy can store related objects in separate tables or serialized, but it doesn't have telepathic algorithms to read your mind. So you have to describe your choice explicitly.\nAnswers to yo...
[ 4 ]
[]
[]
[ "database_design", "python", "sqlalchemy" ]
stackoverflow_0002609719_database_design_python_sqlalchemy.txt
Q: beautifulsoup and mechanize to get ajax call result hi im building a scraper using python 2.5 and beautifulsoup but im stuble upon a problem ... part of the web page is generating after user click on some button, whitch start an ajax request by calling specific javacsript function using proper parameters is there ...
beautifulsoup and mechanize to get ajax call result
hi im building a scraper using python 2.5 and beautifulsoup but im stuble upon a problem ... part of the web page is generating after user click on some button, whitch start an ajax request by calling specific javacsript function using proper parameters is there a way to simulate user interaction and get this result? i...
[ "ok so i have figured it out ... it was quite simple after i realised that i could use combination of urllib, ulrlib2 and beautifulsoup\nimport urllib, urllib2\nfrom BeautifulSoup import BeautifulSoup as bs_parse\n\ndata = urllib.urlencode(values)\nreq = urllib2.Request(url, data)\nres = urllib2.urlopen(req)\npag...
[ 6, 3 ]
[]
[]
[ "ajax", "beautifulsoup", "mechanize", "python", "scraper" ]
stackoverflow_0002610112_ajax_beautifulsoup_mechanize_python_scraper.txt
Q: How hard is it to modify the Django Models? I am doing geolocation, and Django does not have a PointField. So, I am forced to writing in RAW SQL. GeoDjango, the Django library, does not support the following query for MYSQL databases (can someone verify that for me?) cursor.execute("SELECT id FROM l_tag WHERE\ ...
How hard is it to modify the Django Models?
I am doing geolocation, and Django does not have a PointField. So, I am forced to writing in RAW SQL. GeoDjango, the Django library, does not support the following query for MYSQL databases (can someone verify that for me?) cursor.execute("SELECT id FROM l_tag WHERE\ (GLength(LineStringFromWKB(LineStri...
[ "Why don't you just extend a class that's already there? Just curious and wish I could help you specifically.\n", "GeoDjango does have a PointField. \nIt looks like you're trying to do a dwithin field lookup, which does not work on MySQL (as of April 2010), but does in Postgres:\nclass Tag(Model):\n point = P...
[ 0, 0 ]
[]
[]
[ "database", "django", "geodjango", "mysql", "python" ]
stackoverflow_0002548791_database_django_geodjango_mysql_python.txt
Q: Eclipse PyDev doesn't shut down interpreter when you click the little red button Seems that even after unchecking the option in the PyDev/Debug preferenecs pane to launch in the background, once it's launched I have to go to task manager to kill the python process. A: This often happens when you're using somethi...
Eclipse PyDev doesn't shut down interpreter when you click the little red button
Seems that even after unchecking the option in the PyDev/Debug preferenecs pane to launch in the background, once it's launched I have to go to task manager to kill the python process.
[ "This often happens when you're using something like cherrypy/django and the process restarts after you've changed a python file while it's running. When this happens, I think the process is different but still using the same output console and thus won't be killed when you press the red button. \nI'm not sure ther...
[ 1, 1 ]
[]
[]
[ "eclipse", "eclipse_plugin", "pydev", "python" ]
stackoverflow_0002613672_eclipse_eclipse_plugin_pydev_python.txt
Q: ISBNs are used as primary key, now I want to add non-book things to the DB - should I migrate to EAN? I built an inventory database where ISBN numbers are the primary keys for the items. This worked great for a while as the items were books. Now I want to add non-books. some of the non-books have EANs or ISSNs, so...
ISBNs are used as primary key, now I want to add non-book things to the DB - should I migrate to EAN?
I built an inventory database where ISBN numbers are the primary keys for the items. This worked great for a while as the items were books. Now I want to add non-books. some of the non-books have EANs or ISSNs, some do not. It's in PostgreSQL with django apps for the frontend and JSON api, plus a few supporting python ...
[ "I don't know postgres but normally ISBM would be a unique index key but not the primary. It's better to have an integer as primary/foreign key. That way you only need to add a new field EAN/ISSN as nullable.\n", "I agree with the_lotus, not least because ISBN is a poor choice for primary key\nData wise, it may n...
[ 3, 3, 2, 2 ]
[]
[]
[ "django", "isbn", "postgresql", "python" ]
stackoverflow_0002610000_django_isbn_postgresql_python.txt
Q: beautifulsoup: find the n-th element's sibling I have a complex html DOM tree of the following nature: <table> ... <tr> <td> ... </td> <td> <table> <tr> <td> <!-- inner most table --> ...
beautifulsoup: find the n-th element's sibling
I have a complex html DOM tree of the following nature: <table> ... <tr> <td> ... </td> <td> <table> <tr> <td> <!-- inner most table --> <table> ... ...
[ "If tag is the innermost table, then\ntag.findNextSibling('h2')\n\nwill be\n<h2>This is hell!</h2>\n\nTo literally get the next sibling, you could use tag.nextSibling,\nwhich in this case, is u'\\n'. \nIf you want the next sibling that is not a NavigableString (such as u'\\n'), then you could use\ntag.findNextSibli...
[ 10, 1 ]
[]
[]
[ "beautifulsoup", "find", "python", "siblings" ]
stackoverflow_0002613527_beautifulsoup_find_python_siblings.txt
Q: Added tagging to existing model, now how does its admin work? I wanted to add a StackOverflow-style tag input to a blog model of mine. This is a model that has a lot of data already in it. class BlogPost(models.Model): # my blog fields try: tagging.register(BlogPost) except tagging.AlreadyRegistered: ...
Added tagging to existing model, now how does its admin work?
I wanted to add a StackOverflow-style tag input to a blog model of mine. This is a model that has a lot of data already in it. class BlogPost(models.Model): # my blog fields try: tagging.register(BlogPost) except tagging.AlreadyRegistered: pass I thought that was all I needed so I went through my old data...
[ "Did you try using TagField() in the model instead of registering the model?\nfrom tagging.fields import TagField\n\nclass BlogPost(models.Model):\n # ...\n tags = TagField()\n\n", "Like istruble said (sorry I can't comment above):\nDid you try using TagField() in the model instead of registering the model?...
[ 2, 0 ]
[]
[]
[ "django", "django_admin", "django_tagging", "python" ]
stackoverflow_0002560240_django_django_admin_django_tagging_python.txt
Q: Python 2.5 module allowing implementation of javascript under windows hi im looking for some modules for python 2.5 whitch allows to run and executes javascript ... any ideas? A: pyv8 definitely supports Windows, but I'm not sure that it supports Python 2.5 out of the box (the pre-built binary packages definitel...
Python 2.5 module allowing implementation of javascript under windows
hi im looking for some modules for python 2.5 whitch allows to run and executes javascript ... any ideas?
[ "pyv8 definitely supports Windows, but I'm not sure that it supports Python 2.5 out of the box (the pre-built binary packages definitely require Python 2.6; I think that you can build from sources with 2.5, but you might need to tweak said sources for the purpose, and I think you will also need a suitable C compile...
[ 1, 0 ]
[]
[]
[ "javascript", "python", "windows" ]
stackoverflow_0002613100_javascript_python_windows.txt
Q: Pylons custom authorizer with Authkit? How do i setup authkit for more authorizers? I want to give certain users admin rights, but only for their own page. A: http://pylonsbook.com/en/1.1/authentication-and-authorization.html#authkit What do you mean by 'admin rights, but only for their own page'? You mean that...
Pylons custom authorizer with Authkit?
How do i setup authkit for more authorizers? I want to give certain users admin rights, but only for their own page.
[ "http://pylonsbook.com/en/1.1/authentication-and-authorization.html#authkit\nWhat do you mean by 'admin rights, but only for their own page'? You mean that user could, for example view other user profiles and edit his own profile?\nIn this case you should check what information should be shown to user and what acti...
[ 1 ]
[]
[]
[ "authentication", "authkit", "pylons", "python" ]
stackoverflow_0002611325_authentication_authkit_pylons_python.txt
Q: How to enter decimal/binary numbers when creating byte objects in python? I'm using python 3.1.1. I know that I can create byte objects using the byte literal in the form of b'...'. In these byte objects, each byte can be represented as a character(in ascii code if I'm not wrong) or as a hexadecimal/octal number. ...
How to enter decimal/binary numbers when creating byte objects in python?
I'm using python 3.1.1. I know that I can create byte objects using the byte literal in the form of b'...'. In these byte objects, each byte can be represented as a character(in ascii code if I'm not wrong) or as a hexadecimal/octal number. Hexadecimal and octal numbers can be entered using an escape of \x for hexadeci...
[ "You can use the built-in bytes constructor to turn a sequence of integers into a byte string:\n>>> bytes((7,8,9,10,11))\nb'\\x07\\x08\\t\\n\\x0b'\n>>> bytes(range(7,12))\nb'\\x07\\x08\\t\\n\\x0b'\n>>> bytes((0b1,0b0,0b1))\nb'\\x01\\x00\\x01'\n\n", "You could use binary literals for integers\n>>> b = bytearray(b'...
[ 4, 2 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0002614406_python_python_3.x.txt
Q: Problem with Classes in Python Ok guys, I'm really new at python (and programming itself) so sorry for my ignorance, but I really needed to ask this. So im doing a wxPython project where I added several tabs for a notebook (each tab of the notebook = a class) and there is one tab where I added a checkbox (in a ta...
Problem with Classes in Python
Ok guys, I'm really new at python (and programming itself) so sorry for my ignorance, but I really needed to ask this. So im doing a wxPython project where I added several tabs for a notebook (each tab of the notebook = a class) and there is one tab where I added a checkbox (in a tab, lets call it for example Tab1), a...
[ "This sounds more like a wxpython question than a classes question. Normally, in python, tab1 would need a handle to tab2 in order to hide the button in tab2. Or it would need a handle to some shared resource, like a parent class or shared model class, that would allow tab1 to affect settings in tab2 (like the hi...
[ 6, 5 ]
[]
[]
[ "class", "python", "wxpython" ]
stackoverflow_0002614225_class_python_wxpython.txt
Q: how to create a string which can be used as an array in python? i want to create a string S , which can be used as an array , as in each element can be used separately by accesing them as an array. A: That's how Python strings already work: >>> a = "abcd" >>> a[0] 'a' >>> a[2] 'c' But keep in mind that this is ...
how to create a string which can be used as an array in python?
i want to create a string S , which can be used as an array , as in each element can be used separately by accesing them as an array.
[ "That's how Python strings already work:\n>>> a = \"abcd\"\n>>> a[0]\n'a'\n>>> a[2]\n'c'\n\nBut keep in mind that this is read only access.\n", "You can convert a string to a list of characters by using list, and to go the other way use join:\n>>> s = 'Hello, world!'\n>>> l = list(s)\n>>> l[7] = 'f'\n>>> ''.join(...
[ 5, 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002612583_python.txt
Q: Python script, runs well, but not perfectly, debugging help What it does (sort of)... or is meant to, the script reads from a csv file that contains information on sound files and create a play list exactly 60 minutes long. An example csv, contains: their title, duration (in seconds), minium total time to be playe...
Python script, runs well, but not perfectly, debugging help
What it does (sort of)... or is meant to, the script reads from a csv file that contains information on sound files and create a play list exactly 60 minutes long. An example csv, contains: their title, duration (in seconds), minium total time to be played (in minutes) An example is: Soundfoo,120,10 Soundbar,30,6 Soun...
[ "I ran your code several times and I got always the same result indicated below. I can not replicate your problem. \nedit: sorry, yes now I see the problem.\nThe problem is in the first while loop\nI would take away everything in this loop. The code is too convoluted and thus a call for bug. It can be done simpler...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002610543_python.txt
Q: Python (windows) will open files from command line, but not from a script launched from eclipse I'm pretty new to writing python for windows (linux is no problem), and am having problems getting python to recognize files when running scripts, though it behaves fine in the command line What am I doing wrong here? d...
Python (windows) will open files from command line, but not from a script launched from eclipse
I'm pretty new to writing python for windows (linux is no problem), and am having problems getting python to recognize files when running scripts, though it behaves fine in the command line What am I doing wrong here? def verifyFile(x): # return os.path.isfile(x) This will return true (with a valid file, of cour...
[ "There is not really enough information here to debug your issue, but I have a suspicion.\nTry adding the line \nprint sys.argv\n\nto the start of your code, and see what the actual arguments that are being passed in to your program. I have a feeling that you will find the the filename D:\\Documents and Settings\\...
[ 1 ]
[]
[]
[ "file", "python", "windows" ]
stackoverflow_0002614749_file_python_windows.txt
Q: Copy string - Python Ok guys I imagine this is easy but I can't seem to find how to copy a string. Simply COPY to the system like CTRL+C on a text. Basically I want to copy a string so I can for example, lets say, paste(ctrl+v). Sorry for such a trivial question, haha. A: For Windows, you use win32clipboard. Yo...
Copy string - Python
Ok guys I imagine this is easy but I can't seem to find how to copy a string. Simply COPY to the system like CTRL+C on a text. Basically I want to copy a string so I can for example, lets say, paste(ctrl+v). Sorry for such a trivial question, haha.
[ "For Windows, you use win32clipboard. You will need pywin32.\nFor GTK (at least on GNU/Linux), you can use pygtk.\nEDIT: Since you mentioned (a bit late) you're using wxPython, they actually have a module for this too, wx.Clipboard.\n", "This depends a lot on the OS. On Linux, due to X's bizarre selection model...
[ 4, 2, 2, 2 ]
[]
[]
[ "clipboard", "copy", "python", "string" ]
stackoverflow_0002614975_clipboard_copy_python_string.txt
Q: Multi-Threaded data insertion in MySQL using python I am working on a project involving insertion a lot of data in to the database. I am wondering if anybody knows how to fill 2 or 3 tables in the database at the same time.An example or psueodecode would be helpful. Thanks A: If you have a lot of data to insert ...
Multi-Threaded data insertion in MySQL using python
I am working on a project involving insertion a lot of data in to the database. I am wondering if anybody knows how to fill 2 or 3 tables in the database at the same time.An example or psueodecode would be helpful. Thanks
[ "If you have a lot of data to insert into the database all at once, then you probably are interested in bulk loading data. The ideal tool for that is the bulk loader that likely comes with your database -- Oracle, Microsoft SQL Server, Sybase SQL Server, and MySQL (to name the ones that come to mind) all have bulk ...
[ 3 ]
[]
[]
[ "database", "multithreading", "mysql", "python" ]
stackoverflow_0002613105_database_multithreading_mysql_python.txt
Q: Decoding tcp packets using python I am trying to decode data received over a tcp connection. The packets are small, no more than 100 bytes. However when there is a lot of them I receive some of the the packets joined together. Is there a way to prevent this. I am using python I have tried to separate the packets, ...
Decoding tcp packets using python
I am trying to decode data received over a tcp connection. The packets are small, no more than 100 bytes. However when there is a lot of them I receive some of the the packets joined together. Is there a way to prevent this. I am using python I have tried to separate the packets, my source is below. The packets start w...
[ "I would create a class that is responsible for decoding the packets from a stream, like this:\nclass PacketDecoder(object):\n\n STX = ...\n ETX = ...\n\n def __init__(self):\n self._stream = ''\n\n def feed(self, buffer):\n self._stream += buffer\n\n def decode(self):\n '''\n ...
[ 5, 4, 3, 0, 0 ]
[]
[]
[ "decoding", "packets", "python", "string", "tcp" ]
stackoverflow_0002184181_decoding_packets_python_string_tcp.txt
Q: Python NameError when attempting to use a user-defined class I'm getting a weird instance of a NameError when attempting to use a class I wrote. In a directory, I have the following file structure: dir/ ReutersParser.py test.py reut-xxx.sgm Where my custom class is defined in ReutersParser.py and I have a ...
Python NameError when attempting to use a user-defined class
I'm getting a weird instance of a NameError when attempting to use a class I wrote. In a directory, I have the following file structure: dir/ ReutersParser.py test.py reut-xxx.sgm Where my custom class is defined in ReutersParser.py and I have a test script defined in test.py. The ReutersParser looks somethin...
[ "Your problem is not your code, but what you run it in. If you read the error and the code it displays closely:\n File \"D:\\Projects\\Reuters\\ReutersParser.py\", line 38, in __init__\n SGMLParser.__init__(self, verbose)\nNameError: global name 'sgmllib' is not defined\n\nyou'll notice there's no reference to ...
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0002615059_python.txt
Q: Scrapy domain_name for spider From the Scrapy tutorial: domain_name: identifies the Spider. It must be unique, that is, you can’t set the same domain name for different Spiders. Does this mean that domain_name must be a valid domain name, like domain_name = 'example.com' Or can I name domain_name = 'ex1' Th...
Scrapy domain_name for spider
From the Scrapy tutorial: domain_name: identifies the Spider. It must be unique, that is, you can’t set the same domain name for different Spiders. Does this mean that domain_name must be a valid domain name, like domain_name = 'example.com' Or can I name domain_name = 'ex1' The problem is I had a spider that wo...
[ "To answer my own question:\n\ndomain_name = 'wc2'\n\nworks.\n", "As you have found out yourself, domain_name shouldn't be real. It's used when calling the spider to crawl.\n" ]
[ 1, 0 ]
[]
[]
[ "python", "scrapy" ]
stackoverflow_0001804694_python_scrapy.txt
Q: Simple pygtk and threads example please Can someone give me a simple example involving threads in this manner, please. Problem with my code is that when I click button One, GUI freezes until its finished. I want buttons to stay responsive when def is being executed. How can i fix that? class fun: wTree = ...
Simple pygtk and threads example please
Can someone give me a simple example involving threads in this manner, please. Problem with my code is that when I click button One, GUI freezes until its finished. I want buttons to stay responsive when def is being executed. How can i fix that? class fun: wTree = None def __init__( self ): ...
[ "Use Python Threads: http://docs.python.org/library/threading.html\nSomething like:\nclass SoneThread(threading.Thread):\n def __init__(self):\n threading.Thread.__init__(self)\n self.start() # invoke the run method\n\n def run(self):\n time.sleep(1)\n print \"1\"\n time.sleep(...
[ 4, 1 ]
[]
[]
[ "pygtk", "python" ]
stackoverflow_0002615124_pygtk_python.txt
Q: how to transfer a python object between two requests? i want to process a python dict object in batches between two requests. i was wondering what's the best way to do it. i want to do that because my dict is big and i couldn't do the whole processing in 30s. thanks A: You can serialize your object (perhaps with...
how to transfer a python object between two requests?
i want to process a python dict object in batches between two requests. i was wondering what's the best way to do it. i want to do that because my dict is big and i couldn't do the whole processing in 30s. thanks
[ "You can serialize your object (perhaps with pickle, though there may be more efficient and specific ways if your object's nature is well-constrained) and save the serialized byte string to the datastore and to memcache (I don't recommend using just memcache, because it just might occasionally happen that the cache...
[ 4 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0002615050_google_app_engine_python.txt
Q: Rationale behind Python's preferred for syntax What is the rationale behind the advocated use of the for i in xrange(...)-style looping constructs in Python? For simple integer looping, the difference in overheads is substantial. I conducted a simple test using two pieces of code: File idiomatic.py: #!/usr/bin/env...
Rationale behind Python's preferred for syntax
What is the rationale behind the advocated use of the for i in xrange(...)-style looping constructs in Python? For simple integer looping, the difference in overheads is substantial. I conducted a simple test using two pieces of code: File idiomatic.py: #!/usr/bin/env python M = 10000 N = 10000 if __name__ == "__main...
[ "Here's the proper comparison, e.g. in loop.py:\nM = 10000\nN = 10000\n\ndef thegoodone():\n for x in xrange(N):\n for y in xrange(M):\n pass\n\ndef thebadone():\n x = 0\n while x < N:\n y = 0\n while y < M:\n y += 1\n x += 1\n\nAll substantial code should alw...
[ 22, 11, 3, 1, 0 ]
[]
[]
[ "performance", "python" ]
stackoverflow_0002611867_performance_python.txt
Q: (Python) Why do I always have to type absolute paths in file functions? For instance, if I have: C:\42\main.py and C:\42\info.txt and I want to read info.txt from main.py, I have to input "C:\42\info.txt" instad of just "info.txt". Is it supposed to be like that? If not, how can I fix it? A: You can specify path...
(Python) Why do I always have to type absolute paths in file functions?
For instance, if I have: C:\42\main.py and C:\42\info.txt and I want to read info.txt from main.py, I have to input "C:\42\info.txt" instad of just "info.txt". Is it supposed to be like that? If not, how can I fix it?
[ "You can specify paths relative to where your script is. I do it all the time when writing unittests.\nEvery python file has a special attribute -- __file__ -- that stores the path to that file. \npy_file= os.path.abspath(__file__) # path to main.py\npy_dir = os.path.dirname(py_file) # path to the parent dir of m...
[ 10, 5, 1 ]
[]
[]
[ "absolute_path", "python" ]
stackoverflow_0002615526_absolute_path_python.txt
Q: Why can't I download a whole image file with urllib2.urlopen() When I run the following code, it only seems to be downloading the first little bit of the file and then exiting. Occassionally, I will get a 10054 error, but usually it just exits without getting the whole file. My internet connection is crappy wirele...
Why can't I download a whole image file with urllib2.urlopen()
When I run the following code, it only seems to be downloading the first little bit of the file and then exiting. Occassionally, I will get a 10054 error, but usually it just exits without getting the whole file. My internet connection is crappy wireless, and I often get broken downloads on larger files in firefox, but...
[ "To write a binary file on Windows you need to explicitly open it as binary, i.e.:\nxkcdpicfile=open(\"C:\\\\Documents and Settings\\\\John Gann\\\\Desktop\\\\xkcd.png\",\n \"wb\")\n\nnote the extra b in the options: \"wb\", not just \"w\"!\nI would also recommend losing the print chunk which may se...
[ 10 ]
[]
[]
[ "download", "image", "python" ]
stackoverflow_0002615593_download_image_python.txt
Q: Help calling def from class Noob question... class msgbox: def __init__(self, lbl_msg = '', dlg_title = ''): self.wTree = gtk.glade.XML('msgbox.glade') self.wTree.get_widget('dialog1').set_title(dlg_title) self.wTree.get_widget('label1').set_text(lbl_msg) ...
Help calling def from class
Noob question... class msgbox: def __init__(self, lbl_msg = '', dlg_title = ''): self.wTree = gtk.glade.XML('msgbox.glade') self.wTree.get_widget('dialog1').set_title(dlg_title) self.wTree.get_widget('label1').set_text(lbl_msg) self.wTree.signal_autoconnect( {'...
[ "It looks like you want\nself.msg.done()\n\nto close the existing \"Please wait...\" message box. msgbox().done() creates a new message box, then calls done on this new instance.\nAs for the extra parameter, you aren't using it, so remove it from the definition of done:\ndef done(self):\n self.wTree.get_widget('...
[ 1, 1 ]
[]
[]
[ "pygtk", "python" ]
stackoverflow_0002615610_pygtk_python.txt
Q: Trace/BPT trap when running feedparser inside a Thread object I am trying to run a Thread to parse a list of links using the universal feed parser, but when I start the thread I get a Trace/BPT trap. Here's the code I am using: class parseRssFiles(Thread): def __init__ (self,rssLinks): Thread.__init__(sel...
Trace/BPT trap when running feedparser inside a Thread object
I am trying to run a Thread to parse a list of links using the universal feed parser, but when I start the thread I get a Trace/BPT trap. Here's the code I am using: class parseRssFiles(Thread): def __init__ (self,rssLinks): Thread.__init__(self) self.rssLinks = rssLinks def run(self): self.rssC...
[ "Without a working test case, it is hard to know for sure but I suspect you are running into the problem documented in Python tracker issue 7144, namely, trying to initialize the CoreFoundation framework on other than the main thread. That problem is fixed in Python 2.6.5 which you could install from python.org or...
[ 1 ]
[]
[]
[ "feedparser", "multithreading", "python" ]
stackoverflow_0002614910_feedparser_multithreading_python.txt
Q: Storing Data from both POST variables and GET parameters I want my python script to simultaneously accept POST variables and query string variables from the web address. The script has code : form = cgi.FieldStorage() print form However, this only captures the post variables and no query variables from the web ad...
Storing Data from both POST variables and GET parameters
I want my python script to simultaneously accept POST variables and query string variables from the web address. The script has code : form = cgi.FieldStorage() print form However, this only captures the post variables and no query variables from the web address. Is there a way to do this? Thanks, Ali
[ "cgi.parse_qsl (in any Python 2.*; urlparse.parse_qsl in 2.6 or better) take a query string and return a list of name, value pairs. Use os.environ['QUERY_STRING'] to get the query string part of the URL your CGI script was reached at (everything after the ? in the URL, if any).\n" ]
[ 1 ]
[]
[]
[ "cgi", "forms", "get", "post", "python" ]
stackoverflow_0002616001_cgi_forms_get_post_python.txt
Q: How to create Fibonacci Sequence in Java I really suck at math. I mean, I REALLY suck at math. I'm trying to make a simple fibonacci sequence class for an algorithm I'll be using. I have seen the python example which looks something like this: a = 0 b = 1 while b < 10: print b a, b = b, b+a The problem i...
How to create Fibonacci Sequence in Java
I really suck at math. I mean, I REALLY suck at math. I'm trying to make a simple fibonacci sequence class for an algorithm I'll be using. I have seen the python example which looks something like this: a = 0 b = 1 while b < 10: print b a, b = b, b+a The problem is that I can't really make this work in any ot...
[ "I'd do it this way:\npublic class FibonacciAlgorithm {\n\n private int a = 0;\n\n private int b = 1;\n\n public FibonacciAlgorithm() {\n\n }\n\n public int increment() {\n int temp = b;\n b = a + b;\n a = temp;\n return value;\n }\n\n public int getValue() {\n ...
[ 7, 4, 2, 1, 0, 0, 0, 0, 0 ]
[ "public Integer increment() {\n a = b;\n b = a + b;\n return value;\n }\nIs certainly wrong. I think switching the first two lines should do the trick\n" ]
[ -1 ]
[ "java", "python" ]
stackoverflow_0001045151_java_python.txt
Q: Python: what package contains the installation metadata? e.g., how can I find out that the executable has been installed in "/usr/bin/python" and the library files in "/usr/lib/python2.6"? A: You want the sys module: >>> print sys.executable /usr/bin/python >>> print sys.path ['', '/System/Library/Frameworks/Pyt...
Python: what package contains the installation metadata?
e.g., how can I find out that the executable has been installed in "/usr/bin/python" and the library files in "/usr/lib/python2.6"?
[ "You want the sys module:\n>>> print sys.executable\n/usr/bin/python\n>>> print sys.path\n['', '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python26.zip',\n '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6', \n'/System/Library/Frameworks/Python.framework/Versions/2.6/lib/pyth...
[ 1, 1 ]
[]
[]
[ "installation", "metadata", "python" ]
stackoverflow_0002616190_installation_metadata_python.txt
Q: Real-time data on webpage with jQuery I would like a webpage that constantly updates a graph with new data as it arrives. Regularly, all the data you have is passed to the page at the beginning of the request. However, I need the page to be able to update itself with fresh information every few seconds to redraw t...
Real-time data on webpage with jQuery
I would like a webpage that constantly updates a graph with new data as it arrives. Regularly, all the data you have is passed to the page at the beginning of the request. However, I need the page to be able to update itself with fresh information every few seconds to redraw the graph. Background The webpage will be si...
[ "So the page must perform periodic jQuery.ajax calls with a url parameter set to a server's URL where the latest up-to-data information (possibly just as an incremental delta from the last instant for which the client has info -- the client can send that instant as a query parameter in the Ajax call) is served, ide...
[ 6, 0 ]
[]
[]
[ "django", "jquery", "python" ]
stackoverflow_0002615719_django_jquery_python.txt
Q: Python: eliminating stack traces into library code? When I get a runtime exception from the standard library, it's almost always a problem in my code and not in the library code. Is there a way to truncate the exception stack trace so that it doesn't show the guts of the library package? For example, I would like...
Python: eliminating stack traces into library code?
When I get a runtime exception from the standard library, it's almost always a problem in my code and not in the library code. Is there a way to truncate the exception stack trace so that it doesn't show the guts of the library package? For example, I would like to get this: Traceback (most recent call last): File "...
[ "The traceback module in Python's standard library lets you emit error tracebacks in a way that accords to your liking, while an exception is propagating. You can use this power either in the except leg of a try/except statement, or in a function you've installed as sys.excepthook, which gets called if and when an...
[ 11, 3, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002615414_python.txt
Q: How to simulate tuples and sets in C#? I want to use some features of python like as Tuples and Sets in c#. should I implement them? or there are already implemented? could anybody knows a library of dynamic data structures for .net languages? A: .NET 3.5 has HashSet. .NET 4.0 will have a Tuple class. As noted i...
How to simulate tuples and sets in C#?
I want to use some features of python like as Tuples and Sets in c#. should I implement them? or there are already implemented? could anybody knows a library of dynamic data structures for .net languages?
[ ".NET 3.5 has HashSet.\n.NET 4.0 will have a Tuple class. As noted in the article, earlier version of .NET do contain KeyValuePair< TKey, TValue > which is similar to a Tuple< T1, T2 >, with the main difference being that KeyValuePair requires that TKey is unique. \n", "For Sets, HashSets (a .NET 3.5 feature) do ...
[ 14, 3, 1 ]
[]
[]
[ "c#", "data_structures", "python", "set", "tuples" ]
stackoverflow_0002616255_c#_data_structures_python_set_tuples.txt
Q: Is it possible to detect when the system is recording a sound and then perform some action on Python? I began learning Python a few days ago, and i was wondering about a practical use for a program. Then i came up with the following: if my brother is in his room recording himself playing guitar, a led plugged to t...
Is it possible to detect when the system is recording a sound and then perform some action on Python?
I began learning Python a few days ago, and i was wondering about a practical use for a program. Then i came up with the following: if my brother is in his room recording himself playing guitar, a led plugged to the usb and wired so it's outside his door lights up, and then i'll know he's recording and i'll take care n...
[ "to interact with USB, you can read this related question.\nto detect recording, you will have to tell us on which operating system your program is intented to run (but i am not sure it is possible to detect that another application is recording)\n" ]
[ 0 ]
[]
[]
[ "audio_recording", "detection", "led", "python", "usb" ]
stackoverflow_0002616252_audio_recording_detection_led_python_usb.txt
Q: How can I learn to set up a build process? What I was taught at school is all about programming languages, software design, but hardly anything about how to automatically build a software, probably with something like unit testing integrated. Please tell me how do one start learning to set up a build process for h...
How can I learn to set up a build process?
What I was taught at school is all about programming languages, software design, but hardly anything about how to automatically build a software, probably with something like unit testing integrated. Please tell me how do one start learning to set up a build process for his project. If this is too abstract to make any ...
[ "I like a couple of Pragmatic Programmers' books on this subject, Ship it! and Release it!. Together, they teach a lot of real-world, pragmatic stuff about such things as build systems and how to design well-deployable programs.\n", "If you're doing this in Java, you can check out Maven. There are a host of tuto...
[ 4, 2, 2, 1, 0 ]
[]
[]
[ "ci_server", "python" ]
stackoverflow_0002615923_ci_server_python.txt
Q: Unknown reason for code executing the way it does in python I am a beginner programmer, using python on Mac. I created a function as a part of a game which receives the player's input for the main character's name. The code is: import time def newGameStep2(): print ' *************************************...
Unknown reason for code executing the way it does in python
I am a beginner programmer, using python on Mac. I created a function as a part of a game which receives the player's input for the main character's name. The code is: import time def newGameStep2(): print ' ****************************************** ' print '\nStep2\t\t\t\tCharacter Name' pr...
[ "Your recursive call to newGameStep2() isn't returning, so when the second call finishes, control flow continues in the first call after the if/else block, and return newStep2Choice returns the first read value. You need to change the recursive call to:\nreturn newGameStep2()\n\n" ]
[ 8 ]
[]
[]
[ "macos", "python" ]
stackoverflow_0002616468_macos_python.txt
Q: Pythonic reading from config files I have a python class which reads a config file using ConfigParser: Config file: [geography] Xmin=6.6 Xmax=18.6 Ymin=36.6 YMax=47.1 Python code: class Slicer: def __init__(self, config_file_name): config = ConfigParser.ConfigParser() config.read(config_file_n...
Pythonic reading from config files
I have a python class which reads a config file using ConfigParser: Config file: [geography] Xmin=6.6 Xmax=18.6 Ymin=36.6 YMax=47.1 Python code: class Slicer: def __init__(self, config_file_name): config = ConfigParser.ConfigParser() config.read(config_file_name) # Rad the lines from the fi...
[ "I usually try to avoid external interactions in a constructor - makes it hard to test the code. Better pass a config parser instance or a fp-like object instead of a filename.\n", "for line in ['x_min', 'x_max', 'y_min', 'y_max']:\n\n setattr(self, line, config.getfloat('geography', line.replace('_', '')))\n\n...
[ 5, 3, 1 ]
[]
[]
[ "coding_style", "configparser", "dry", "python" ]
stackoverflow_0002616574_coding_style_configparser_dry_python.txt
Q: Port C's fread(&struct,....) to Python Hey, I'm really struggling with this one. I'am trying to port a small piece of someone else's code to Python and this is what I have: typedef struct { uint8_t Y[LUMA_HEIGHT][LUMA_WIDTH]; uint8_t Cb[CHROMA_HEIGHT][CHROMA_WIDTH]; uint8_t Cr[CHROMA_HEIGHT][CHROMA_WIDTH]; }...
Port C's fread(&struct,....) to Python
Hey, I'm really struggling with this one. I'am trying to port a small piece of someone else's code to Python and this is what I have: typedef struct { uint8_t Y[LUMA_HEIGHT][LUMA_WIDTH]; uint8_t Cb[CHROMA_HEIGHT][CHROMA_WIDTH]; uint8_t Cr[CHROMA_HEIGHT][CHROMA_WIDTH]; } __attribute__((__packed__)) frame_t; frame...
[ "You have to use struct python standard module.\nFrom its documentation (emphasys added):\n\nThis module performs conversions\n between Python values and C structs\n represented as Python strings. It uses\n format strings (explained below) as\n compact descriptions of the lay-out of\n the C structs and the int...
[ 6 ]
[]
[]
[ "c", "porting", "python", "struct" ]
stackoverflow_0002616680_c_porting_python_struct.txt
Q: Retrieving information with Python's urllib from a page that is done via __doPostBack()? I'm trying to parse a page that has different sections that are loaded with a Javascript __doPostBack() function. An example of a link is: javascript:__doPostBack('ctl00$cphMain$ucOemSchPicker$dlSch$ctl03$btnSch','') As soon ...
Retrieving information with Python's urllib from a page that is done via __doPostBack()?
I'm trying to parse a page that has different sections that are loaded with a Javascript __doPostBack() function. An example of a link is: javascript:__doPostBack('ctl00$cphMain$ucOemSchPicker$dlSch$ctl03$btnSch','') As soon as this is clicked, the browser doesn't fetch a new URL but a section of webpage is updated to...
[ "javascript:__doPostBack('...\n\n(Urgh. That's a sad and nasty approach.)\nA simple general-purpose approach for finding URLs whose logic is buried in JavaScript is to run the page normally, with a network debugger on (eg. Firebug's ‘Net’ tab, or Fiddler). By monitoring the request made when you click, you can see ...
[ 1 ]
[]
[]
[ "asp.net", "javascript", "parsing", "python", "urllib" ]
stackoverflow_0002616783_asp.net_javascript_parsing_python_urllib.txt
Q: fade out in Image module Python I want to take a BMP or JPG and duplicate it so the new image will darker (or brighrt) what function can I use? Ariel A: You can use ImageEnhance module of PIL: import Image import ImageEnhance image = Image.open(r'c:\temp\20090809210.jpg') enhancer = ImageEnhance.Brightness(imag...
fade out in Image module Python
I want to take a BMP or JPG and duplicate it so the new image will darker (or brighrt) what function can I use? Ariel
[ "You can use ImageEnhance module of PIL:\nimport Image\nimport ImageEnhance\n\nimage = Image.open(r'c:\\temp\\20090809210.jpg')\nenhancer = ImageEnhance.Brightness(image)\nbrighter_image = enhancer.enhance(2)\ndarker_image = enhancer.enhance(0.5)\n\nLook at PIL and ImageEnhance documentation for more details.\nNote...
[ 7, 1 ]
[]
[]
[ "fadeout", "image", "python" ]
stackoverflow_0002616645_fadeout_image_python.txt