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: HTTP GET script based on httplib I need a tool, which can download some part of data from web server, and after that i want connection not be closed. Therfore, i thought about a script in python, which can do: 1) send request 2) read some part of response 3) will freeze - server should think that connection exist,...
HTTP GET script based on httplib
I need a tool, which can download some part of data from web server, and after that i want connection not be closed. Therfore, i thought about a script in python, which can do: 1) send request 2) read some part of response 3) will freeze - server should think that connection exist, and should not close it is it possilb...
[ "httplib doesn't support that. Use another library, like httplib2. Here's example.\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0003636703_python.txt
Q: Projects using py.test I am looking for (list of) projects that use py.test. I am new to testing, and want to use py.test. I need examples from projects, so i can use py.test extensively. The documentation is good for py.test but is too fragmented to get a good grasp. I have a vague idea of how it works. I saw the...
Projects using py.test
I am looking for (list of) projects that use py.test. I am new to testing, and want to use py.test. I need examples from projects, so i can use py.test extensively. The documentation is good for py.test but is too fragmented to get a good grasp. I have a vague idea of how it works. I saw the py.test video(3hrs) from py...
[ "There is MoinMoin, Pida, PyPy and a host of other projects using py.test. In terms of examples you might also look into py.test's own test suite which naturally uses a lot of its features. Checkout http://bitbucket.org/hpk42/py-trunk and the \"testing\" sub directory and maybe file an issue on the tracker that y...
[ 3 ]
[]
[]
[ "pytest", "python", "testing" ]
stackoverflow_0003486194_pytest_python_testing.txt
Q: Executing modules as scripts I am learn python now, and today, i met a problem in http://docs.python.org/release/2.5.4/tut/node8.html 6.1.1 Executing modules as scripts When you run a Python module with python fibo.py <arguments> the code in the module will be executed, just as if you imported it, but with the ...
Executing modules as scripts
I am learn python now, and today, i met a problem in http://docs.python.org/release/2.5.4/tut/node8.html 6.1.1 Executing modules as scripts When you run a Python module with python fibo.py <arguments> the code in the module will be executed, just as if you imported it, but with the __name__ set to "__main__". That...
[ "What exactly did you do in the shell? What is the code you are running?\nIt sounds like you made a mistake in your script - perhaps missing the colon or getting the indentation wrong. Without seeing the file you are running it is impossible to say more.\nedit:\nI have figured out what is going wrong. You are tr...
[ 13 ]
[]
[]
[ "python", "windows" ]
stackoverflow_0003636798_python_windows.txt
Q: Matrix multiplication with Numpy Assume that I have an affinity matrix A and a diagonal matrix D. How can I compute the Laplacian matrix in Python with nympy? L = D^(-1/2) A D^(1/2) Currently, I use L = D**(-1/2) * A * D**(1/2). Is this a right way? Thank you. A: Please note that it is recommended to use numpy's...
Matrix multiplication with Numpy
Assume that I have an affinity matrix A and a diagonal matrix D. How can I compute the Laplacian matrix in Python with nympy? L = D^(-1/2) A D^(1/2) Currently, I use L = D**(-1/2) * A * D**(1/2). Is this a right way? Thank you.
[ "Please note that it is recommended to use numpy's array instead of matrix: see this paragraph in the user guide. The confusion in some of the responses is an example of what can go wrong... In particular, D**0.5 and the products are elementwise if applied to numpy arrays, which would give you a wrong answer. For e...
[ 4, 3, 1, 0 ]
[]
[]
[ "matrix_multiplication", "numpy", "python" ]
stackoverflow_0003580632_matrix_multiplication_numpy_python.txt
Q: serial port: have to send \n [edit] Initially I thought this was a pyserial problem but it's not. Basically it's a system problem: Sending anything over the serial port (/dev/ttyS0) would need a "\n" or "\r" or else it'll just be buffered. Below is the original question. Is it a limitation of Linux driver or is th...
serial port: have to send \n
[edit] Initially I thought this was a pyserial problem but it's not. Basically it's a system problem: Sending anything over the serial port (/dev/ttyS0) would need a "\n" or "\r" or else it'll just be buffered. Below is the original question. Is it a limitation of Linux driver or is there some settings I can change? He...
[ "from the documentation for pyserial http://pyserial.sourceforge.net/pyserial_api.html that does not seem to be the case. which version are you using?\nto clarify, which pySerial and which python seem to be relevant.\n" ]
[ 1 ]
[]
[]
[ "pyserial", "python", "serial_port" ]
stackoverflow_0003636910_pyserial_python_serial_port.txt
Q: Long programs using python -c switch I would like to use python for things I've been doing using bash. Is it possible to use the -c switch for long programs, e.g. a for loop with two statements? This would let me use python directly from command line, just like bash or php. Thanks. EDIT: Don't know how I missed it...
Long programs using python -c switch
I would like to use python for things I've been doing using bash. Is it possible to use the -c switch for long programs, e.g. a for loop with two statements? This would let me use python directly from command line, just like bash or php. Thanks. EDIT: Don't know how I missed it, simply doing a python -c ' and then pres...
[ "No problem if your underlying shell is bash, since you can continue an argument across multiple lines if an opened ' (quote) is not yet closed -- e.g.:\n$ python -c'for x in range(3):\n> if x!=1:\n> print x'\n0\n2\n$\n\nThe > is bash's default PS2, the \"multi-line continuation prompt\", as distinguished fro...
[ 8, 5, 3, 1 ]
[]
[]
[ "command_line", "python" ]
stackoverflow_0003637020_command_line_python.txt
Q: Python Twisted: "wait" for a variable to be filled by another event I know that twisted will not "wait"... I am working with an XMPP client to exchange data with an external process. I send an request and need to fetch the corresponding answer. I use a sendMessage to send my request to the server. When the server ...
Python Twisted: "wait" for a variable to be filled by another event
I know that twisted will not "wait"... I am working with an XMPP client to exchange data with an external process. I send an request and need to fetch the corresponding answer. I use a sendMessage to send my request to the server. When the server answers a onMessage method will receive it and check if it an answer to a...
[ "you can't return the results to sendRequest, because sendRequest can't wait.\nmake sendRequest return a Deferred instead, and fire it when the result arrives.\nSo the code calling sendRequest can just add a callback to the deferred and it will be called when there's a response.\nSomething like this (pseudo-code):\...
[ 3 ]
[]
[]
[ "asynchronous", "python", "twisted" ]
stackoverflow_0003636890_asynchronous_python_twisted.txt
Q: python -> multiprocessing module Here's what I am trying to accomplish - I have about a million files which I need to parse & append the parsed content to a single file. Since a single process takes ages, this option is out. Not using threads in Python as it essentially comes to running a single process (due to ...
python -> multiprocessing module
Here's what I am trying to accomplish - I have about a million files which I need to parse & append the parsed content to a single file. Since a single process takes ages, this option is out. Not using threads in Python as it essentially comes to running a single process (due to GIL). Hence using multiprocessing modu...
[ "Although the discussion with Eric was fruitful, later on I found a better way of doing this. Within the multiprocessing module there is a method called 'Pool' which is perfect for my needs. \nIt's optimizes itself to the number of cores my system has. i.e. only as many processes are spawned as the no. of cores. Of...
[ 4, 3 ]
[]
[]
[ "multiprocessing", "python", "queue" ]
stackoverflow_0003586723_multiprocessing_python_queue.txt
Q: Decompressing a .bz2 file in Python So, this is a seemingly simple question, but I'm apparently very very dull. I have a little script that downloads all the .bz2 files from a webpage, but for some reason the decompressing of that file is giving me a MAJOR headache. I'm quite a Python newbie, so the answer is prob...
Decompressing a .bz2 file in Python
So, this is a seemingly simple question, but I'm apparently very very dull. I have a little script that downloads all the .bz2 files from a webpage, but for some reason the decompressing of that file is giving me a MAJOR headache. I'm quite a Python newbie, so the answer is probably quite obvious, please help me. In th...
[ "You're opening and reading the compressed file as if it was a textfile made up of lines. DON'T! It's NOT.\nuncompressedData = bz2.BZ2File(zipFile).read()\n\nseems to be closer to what you're angling for.\nEdit: the OP has shown a few more things he's tried (though I don't see any notes about having tried the bes...
[ 16, 9, 6 ]
[]
[]
[ "compression", "python" ]
stackoverflow_0001250688_compression_python.txt
Q: Python URL download The code below returns none. How can I fix it? I'm using Python 2.6. import urllib URL = "http://download.finance.yahoo.com/d/quotes.csv?s=%s&f=sl1t1v&e=.csv" symbols = ('GGP', 'JPM', 'AIG', 'AMZN','GGP', 'JPM', 'AIG', 'AMZN') #symbols = ('GGP') def fetch_quote(symbols): url = URL % '+'.j...
Python URL download
The code below returns none. How can I fix it? I'm using Python 2.6. import urllib URL = "http://download.finance.yahoo.com/d/quotes.csv?s=%s&f=sl1t1v&e=.csv" symbols = ('GGP', 'JPM', 'AIG', 'AMZN','GGP', 'JPM', 'AIG', 'AMZN') #symbols = ('GGP') def fetch_quote(symbols): url = URL % '+'.join(symbols) fp = url...
[ "You have to explicitly return the data from fetch_quote function. Something like this:\ndef fetch_quote(symbols):\n url = URL % '+'.join(symbols)\n fp = urllib.urlopen(url)\n try:\n data = fp.read()\n finally:\n fp.close()\n return data # <======== Return\n\nIn the absence of an explic...
[ 4, 2 ]
[]
[]
[ "python", "url" ]
stackoverflow_0003637553_python_url.txt
Q: Python change data into sequence The "idata" I pulled from this URL needs to be turned into a sequence, how do i turn it into a sequence import urllib, csv URL = "http://download.finance.yahoo.com/d/quotes.csv?s=%s&f=sl1vt1&e=.csv" symbols = ('GGP', 'JPM', 'AIG', 'AMZN','GGP', 'JPM', 'AIG', 'AMZN') #symbols = ('G...
Python change data into sequence
The "idata" I pulled from this URL needs to be turned into a sequence, how do i turn it into a sequence import urllib, csv URL = "http://download.finance.yahoo.com/d/quotes.csv?s=%s&f=sl1vt1&e=.csv" symbols = ('GGP', 'JPM', 'AIG', 'AMZN','GGP', 'JPM', 'AIG', 'AMZN') #symbols = ('GGP',) def fetch_quote(symbols): u...
[ "I would guess based on the URL that you are downloading data in CSV format. As such, you probably want to parse it with a CSV reader. \n", "What do you mean by \"a sequence\"? You could turn it into a dictionary as follows. Just place this code after you produce idata.\nstocks = {}\nfor line in idata.split(\"\\r...
[ 1, 1 ]
[]
[]
[ "python", "url" ]
stackoverflow_0003637986_python_url.txt
Q: sqlalchemy: turn off declarative polymorphic join? Is there a way in sqlalchemy to turn off declarative's polymorphic join loading, in a single query? Most of the time it's nice, but I have: class A(Base) : discriminator = Column('type', mysql.INTEGER(1), index=True, nullable=False) __mapper_args__ = { 'pol...
sqlalchemy: turn off declarative polymorphic join?
Is there a way in sqlalchemy to turn off declarative's polymorphic join loading, in a single query? Most of the time it's nice, but I have: class A(Base) : discriminator = Column('type', mysql.INTEGER(1), index=True, nullable=False) __mapper_args__ = { 'polymorphic_on' : discriminator } id = Column(Integer, p...
[ "You should use with_polymorphic() instead of outerjoin(), which seems to return the expected results:\nsession.query(A).with_polymorphic(B).filter(B.x > 10).all()\n# BEGIN\n# SELECT \"A\".type AS \"A_type\", \"A\".id AS \"A_id\", \"A\".p AS \"A_p\", \"B\".id AS \"B_id\", \"B\".x AS \"B_x\" \n# FROM \"A\" LEFT OUTE...
[ 1, 1 ]
[]
[]
[ "declarative", "python", "sqlalchemy" ]
stackoverflow_0003630310_declarative_python_sqlalchemy.txt
Q: Multiple simultaneous tcp client connections for performace test i need to create multiple TCP connections simultaneously to some custom TCP-server application for its performance testing. I know a lot of such for Web (i.e. curl-loader based on libcurl), but I didn't found some general one. Scenario for client is ...
Multiple simultaneous tcp client connections for performace test
i need to create multiple TCP connections simultaneously to some custom TCP-server application for its performance testing. I know a lot of such for Web (i.e. curl-loader based on libcurl), but I didn't found some general one. Scenario for client is the simplest: create connection, send special data, read the answer an...
[ "My two cents:\n\nGo for Twisted, or any other asynchronous networking library.\nMake sure you can open enough file descriptors on the client and on the\nserver. On my Linux box, for instance, I can have no more than 1024 file\nfile descriptors by default:\ncarlos@marcelino:~$ ulimit -a\ncore file size (bl...
[ 1, 0 ]
[]
[]
[ "network_programming", "parallel_processing", "python", "tcpclient" ]
stackoverflow_0003636141_network_programming_parallel_processing_python_tcpclient.txt
Q: What is the difference between LIST.append(1) and LIST = LIST + [1] (Python) When I execute (I'm using the interactive shell) these statements I get this: L=[1,2,3] K=L L.append(4) L [1,2,3,4] K [1,2,3,4] But when I do exactly the same thing replacing L.append(4) with L=L+[4] I get: L [1,2,3,4] K [1,2,3] Is th...
What is the difference between LIST.append(1) and LIST = LIST + [1] (Python)
When I execute (I'm using the interactive shell) these statements I get this: L=[1,2,3] K=L L.append(4) L [1,2,3,4] K [1,2,3,4] But when I do exactly the same thing replacing L.append(4) with L=L+[4] I get: L [1,2,3,4] K [1,2,3] Is this some sort of reference thing? Why does this happen? Another funny thing I notic...
[ "L.append(4)\n\nThis adds an element on to the end of the existing list L.\nL += [4]\n\nThe += operator invokes the magic __iadd__() method. It turns out list overrides the __iadd__() method and makes it equivalent to extend() which, like append(), adds elements directly onto an existing list.\nL = L + [4]\n\nL + [...
[ 16, 2, 1, 0 ]
[]
[]
[ "append", "list", "python" ]
stackoverflow_0003638486_append_list_python.txt
Q: Active texturing with pygame (possible? what concepts to look into?) I have two images: I'd like to essentially 'cut out' the black shape from the texture tile so that I end up with something along these lines: Except transparent around the shape. Is this possible using pygame? This example I had to create in...
Active texturing with pygame (possible? what concepts to look into?)
I have two images: I'd like to essentially 'cut out' the black shape from the texture tile so that I end up with something along these lines: Except transparent around the shape. Is this possible using pygame? This example I had to create in GIMP. Additionally, would it be too performance-heavy to do this for e...
[ "I made a solution, however it is not the best either for speed either for beauty.\nYou can use double blitting with setting colorkeys for transparency. In that way the mask should have only two colors: black and white.\nNote that you can't use this for images with per pixel alpha (RGBA) only for RGB images.\nOther...
[ 8, 5 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0003580500_pygame_python.txt
Q: what is the max size of TextProperty on google app engine class JsTree_JsonData(db.Model): JsonData=db.TextProperty() i can;t find what is the TextProperty did you know ? thanks A: 1 megabyte. The archived page lists maximum entity size as 1 megabyte.
what is the max size of TextProperty on google app engine
class JsTree_JsonData(db.Model): JsonData=db.TextProperty() i can;t find what is the TextProperty did you know ? thanks
[ "1 megabyte.\nThe archived page lists maximum entity size as 1 megabyte.\n" ]
[ 6 ]
[]
[]
[ "google_app_engine", "max", "properties", "python" ]
stackoverflow_0003638577_google_app_engine_max_properties_python.txt
Q: Error Handling CRM 4 Webservice What is the best way to trap errors/exceptions with the CRM 4 Web service. Is there a way to get more detailed error messages from the web service? There is a custom application that creates orders and when the get a error message from the web service it is not very details or use...
Error Handling CRM 4 Webservice
What is the best way to trap errors/exceptions with the CRM 4 Web service. Is there a way to get more detailed error messages from the web service? There is a custom application that creates orders and when the get a error message from the web service it is not very details or useful. Is there a better way to get mo...
[ "Catch SoapException and take a look at Detail property. You'll find everything about the error in there.\n" ]
[ 1 ]
[]
[]
[ "dynamics_crm", "dynamics_crm_4", "python", "web_services" ]
stackoverflow_0003637579_dynamics_crm_dynamics_crm_4_python_web_services.txt
Q: Having trouble with Tkinter transparency I'm having problems making a top level widget fade in, in TKinter. For some reason the widget doesn't fade in at all, then it will show up in the taskbar, but only after clicking the button that runs this command twice (it's not supposed to be in the taskbar). The code resp...
Having trouble with Tkinter transparency
I'm having problems making a top level widget fade in, in TKinter. For some reason the widget doesn't fade in at all, then it will show up in the taskbar, but only after clicking the button that runs this command twice (it's not supposed to be in the taskbar). The code responsible for these problems. Alpha = 0.0 ...
[ "The problem is that your code never allows the window to redraw itself. Sleep causes the program to stop so the event loop isn't entered, and it's the event loop that causes the window to be drawn. \nInstead of sleeping, take advantage of the event loop and update the attributes every N milliseconds until you get ...
[ 6 ]
[]
[]
[ "fadein", "python", "tkinter", "transparency", "windows_7" ]
stackoverflow_0003399882_fadein_python_tkinter_transparency_windows_7.txt
Q: how do I set a field with a duplicate name of another field in mechanize? I am trying to submit a form with 2 fields with the same name but different type. I can identify the correct field I want by the field type or the number. Whats the best way of setting the correct field without iterating through all the fiel...
how do I set a field with a duplicate name of another field in mechanize?
I am trying to submit a form with 2 fields with the same name but different type. I can identify the correct field I want by the field type or the number. Whats the best way of setting the correct field without iterating through all the fields?
[ "Here is the signature of set_value() method of HTMLForm class.\nset_value(value, name=None, type=None, kind=None,\n id=None, nr=None,by_label=False,\n # by_label is deprecated \n label=None)\n\nAs you can see, you could specify type parameter, useful in this case to select the proper fie...
[ 0 ]
[]
[]
[ "duplicates", "forms", "mechanize", "python" ]
stackoverflow_0003639251_duplicates_forms_mechanize_python.txt
Q: Module name redefines built-in I'm making a game in Python, and it makes sense to have one of my modules named 'map'. My preferred way of importing is to do this: from mygame import map As pylint is telling me, however, this is redefining a built-in. What's the common way of dealing with this? Here are the cho...
Module name redefines built-in
I'm making a game in Python, and it makes sense to have one of my modules named 'map'. My preferred way of importing is to do this: from mygame import map As pylint is telling me, however, this is redefining a built-in. What's the common way of dealing with this? Here are the choices I can come up with: 1) Ignore t...
[ "This is subjective; there's no right answer.\nThat said, for me 3 is the only sensible option. Really really don't do 1; overwriting builtins is almost never a good idea and in this case it's especially confusing. 2 is better, but I think there is still an expectation that any function called map performs some ope...
[ 4, 2, 1 ]
[]
[]
[ "coding_style", "conventions", "naming_conventions", "python" ]
stackoverflow_0003639511_coding_style_conventions_naming_conventions_python.txt
Q: Design pattern for multiple consumers and a single data source I am designing a web interface to a certain hardware appliance that provides its own custom API. Said web interface can manage multiple appliances at once. The data is retrieved from appliance through polling with the custom API so it'd be preferable t...
Design pattern for multiple consumers and a single data source
I am designing a web interface to a certain hardware appliance that provides its own custom API. Said web interface can manage multiple appliances at once. The data is retrieved from appliance through polling with the custom API so it'd be preferable to make it asynchronous. The most obvious thing is to have a poller ...
[ "If you use Django and celery, you can create a Django project to be the web interface and a celery job to run in the background and poll. In that job, you can import your Django models so it can save the results of the polling very simply.\n" ]
[ 4 ]
[]
[]
[ "architecture", "cherrypy", "design_patterns", "python", "rpc" ]
stackoverflow_0003639607_architecture_cherrypy_design_patterns_python_rpc.txt
Q: Trouble with variable. [Python] I have this variable on the beginning of the code: enterActive = False and then, in the end of it, I have this part: def onKeyboardEvent(event): if event.KeyID == 113: # F2 doLogin() enterActive = True if event.KeyID == 13: # ENTER if enterActi...
Trouble with variable. [Python]
I have this variable on the beginning of the code: enterActive = False and then, in the end of it, I have this part: def onKeyboardEvent(event): if event.KeyID == 113: # F2 doLogin() enterActive = True if event.KeyID == 13: # ENTER if enterActive == True: m_lclick() ...
[ "See Global variables in Python. Inside onKeyboardEvent, enterActive currently refers to a local variable, not the (global) variable you have defined outside the function. You need to put\nglobal enterActive\n\nat the beginning of the function to make enterActive refer to the global variable.\n", "Approach 1: Use...
[ 6, 2, 1, 0, 0 ]
[]
[]
[ "python", "windows" ]
stackoverflow_0003639631_python_windows.txt
Q: Search by a property of a reference I have the following models: class Station(db.Model): code = db.StringProperty(required=True) name = db.StringProperty(required=True) class Schedule(db.Model): tripCode = db.StringProperty(required=True) station = db.ReferenceProperty(Station, required=True) ...
Search by a property of a reference
I have the following models: class Station(db.Model): code = db.StringProperty(required=True) name = db.StringProperty(required=True) class Schedule(db.Model): tripCode = db.StringProperty(required=True) station = db.ReferenceProperty(Station, required=True) arrivalTime = db.TimeProperty(requir...
[ "You will to de-normalize your models or sort the results in memory:\nSchedule.all().fetch(100).sort(key=lambda s: s.station.name)\n\n(code not tested)\n", "After use sort i think you need to fetch all entities:\nSchedule.all().fetch (100).sort(key=lambda s: s.station.name)\n\nMay be you can also use collection n...
[ 0, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003638691_google_app_engine_python.txt
Q: Break a text file into chunks based on line like the string split operation? I have text report files I need to "split()" like strings are split up into arrays. So the file is like: BOBO:12341234123412341234 1234123412341234123412341 123412341234 BOBO:12349087609812340-98 43690871234509875 45 BOBO:32498714235908...
Break a text file into chunks based on line like the string split operation?
I have text report files I need to "split()" like strings are split up into arrays. So the file is like: BOBO:12341234123412341234 1234123412341234123412341 123412341234 BOBO:12349087609812340-98 43690871234509875 45 BOBO:32498714235908713248 0987235 And I want to create 3 sub-files out of that splitting on lines th...
[ "Perhaps use itertools.groupby:\nimport itertools\n\ndef bobo(x): \n if x.startswith('BOBO:'):\n bobo.count+=1\n return bobo.count\nbobo.count=0\n\nwith open('a') as f:\n for key,grp in itertools.groupby(f,bobo):\n print(key,list(grp))\n\nyields:\n(1, ['BOBO:12341234123412341234\\n', '1234...
[ 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003639647_python.txt
Q: Does Lua support Decorators? I come from a Python background and really like the power of Python Decorators. Does Lua support Decorators? I've read the following link but it's unclear to me: http://lua-users.org/wiki/DecoratorsAndDocstrings UPDATE Would you also mind given an example how how to implement it in Lu...
Does Lua support Decorators?
I come from a Python background and really like the power of Python Decorators. Does Lua support Decorators? I've read the following link but it's unclear to me: http://lua-users.org/wiki/DecoratorsAndDocstrings UPDATE Would you also mind given an example how how to implement it in Lua if it's possible.
[ "The \"decorators\" documented at the page you quote (and used for example in this one to add type-checking) have little to do with Python's oddly-named \"decorator syntax\" for a specific way to apply a higher-order function (HOF) -- rather, the decorators described and used in Lua's wiki are a Lua idiom to suppor...
[ 10 ]
[]
[]
[ "decorator", "lua", "programming_languages", "python", "syntax" ]
stackoverflow_0003640536_decorator_lua_programming_languages_python_syntax.txt
Q: Python, ctypes and mmap I am wondering if it is possible for the ctypes package to interface with mmap. Currently, my module allocates a buffer (with create_string_buffer) and then passes that using byref to my libraries mylib.read function. This, as the name suggests, reads data into the buffer. I then call file....
Python, ctypes and mmap
I am wondering if it is possible for the ctypes package to interface with mmap. Currently, my module allocates a buffer (with create_string_buffer) and then passes that using byref to my libraries mylib.read function. This, as the name suggests, reads data into the buffer. I then call file.write(buf.raw) to write the d...
[ "An mmap object \"supports the writable buffer interface\", therefore you can use the from_buffer class method, which all ctypes classes have, with the mmap instance as the argument, to create a ctypes object just like you want, i.e., sharing the memory (and therefore the underlying file) that the mmap instance has...
[ 13, 1 ]
[]
[]
[ "ctypes", "python" ]
stackoverflow_0003640092_ctypes_python.txt
Q: Help with if statement I'm trying this part of my script and it work perfectly if win32gui.GetCursorInfo()[1] == 65567: but when I'm trying to add this win32gui.GetCursorInfo()[2] == categoriesScreenPos[1]: it stop working... why? The categoriesScreenPos[1] is the same value (17,242) of the position of the curso...
Help with if statement
I'm trying this part of my script and it work perfectly if win32gui.GetCursorInfo()[1] == 65567: but when I'm trying to add this win32gui.GetCursorInfo()[2] == categoriesScreenPos[1]: it stop working... why? The categoriesScreenPos[1] is the same value (17,242) of the position of the cursor, but the if doesn't work.....
[ "I think the m_move(*loginScreenPos[0]) causes the mouse coordinates to change (because it moves the mouse) and consequently so does win32gui.GetCursorInfo()[2] -- you say you printed it, but did you print it immediately after moving the mouse elsewhere?\n" ]
[ 1 ]
[]
[]
[ "if_statement", "python" ]
stackoverflow_0003640070_if_statement_python.txt
Q: django: trying to access my robots.txt: "TypeError at /robots.txt 'str' object is not callable" Exception Type: TypeError at /robots.txt Exception Value: 'str' object is not callable What gives? Views: ROBOTS_PATH = os.path.join(CURRENT_PATH, 'robots.txt') def robots(request): """ view for robots.txt file """ ret...
django: trying to access my robots.txt: "TypeError at /robots.txt 'str' object is not callable"
Exception Type: TypeError at /robots.txt Exception Value: 'str' object is not callable What gives? Views: ROBOTS_PATH = os.path.join(CURRENT_PATH, 'robots.txt') def robots(request): """ view for robots.txt file """ return HttpResponse(open(ROBOTS_PATH).read(), 'text/plain') Settings: CURRENT_PATH = os.path.abspath(o...
[ "Try: \nfrom appname.views import robots\n(r'^robots\\.txt$', robots), \n\nOr:\n(r'^robots\\.txt$', 'projectname.appname.views.robots'),\n\nDjango can't figure out where your 'robots' function is. \n" ]
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003640478_django_python.txt
Q: In my MapperExtension.create_instance, how can I extract individual row data by column name? I've got a query that returns a fair number of rows, and have found that We wind up throwing away most of the associated ORM instances; and building up those soon-to-be-thrown-away instances is pretty slow. So I'd like ...
In my MapperExtension.create_instance, how can I extract individual row data by column name?
I've got a query that returns a fair number of rows, and have found that We wind up throwing away most of the associated ORM instances; and building up those soon-to-be-thrown-away instances is pretty slow. So I'd like to build only the instances that I need! Unfortunately, I can't do this by simply restricting the ...
[ "The row accepts Column objects as indexes:\nrow[MyClass.some_element.__clause_element__()]\n\nbut that will only get you as far as the classes and aliased() constructs you have access to on the outside. Its very likely that would be all you'd need for that part of the issue (even though ultimately the idea won't...
[ 1 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0003571104_python_sqlalchemy.txt
Q: Alternative to Passing Global Variables Around to Classes and Functions I'm new to python, and I've been reading that using global to pass variables to other functions is considered noobie, as well as a bad practice. I would like to move away from using global variables, but I'm not sure what to do instead. Right ...
Alternative to Passing Global Variables Around to Classes and Functions
I'm new to python, and I've been reading that using global to pass variables to other functions is considered noobie, as well as a bad practice. I would like to move away from using global variables, but I'm not sure what to do instead. Right now I have a UI I've created in wxPython as its own separate class, and I hav...
[ "The alternatives to global variables are many -- mostly:\n\nexplicit arguments to functions, classes called to create one of their instance, etc (this is usually the clearest, since it makes the dependency most explicit, when feasible and not too repetitious);\ninstance variables of an object, when the functions t...
[ 5 ]
[]
[]
[ "python" ]
stackoverflow_0003640700_python.txt
Q: Computing greatest common denominator in python If you have a list of integers in python, say L = [4,8,12,24], how can you compute their greatest common denominator/divisor (4 in this case)? A: One way to do it is: import fractions def gcd(L): return reduce(fractions.gcd, L) print gcd([4,8,12,24])
Computing greatest common denominator in python
If you have a list of integers in python, say L = [4,8,12,24], how can you compute their greatest common denominator/divisor (4 in this case)?
[ "One way to do it is:\nimport fractions\n\ndef gcd(L):\n return reduce(fractions.gcd, L)\n\nprint gcd([4,8,12,24])\n\n" ]
[ 26 ]
[]
[]
[ "division", "integer", "python" ]
stackoverflow_0003640955_division_integer_python.txt
Q: How to write a common get_by_id() method for all kinds of models in Sqlalchemy? I'm using pylons with sqlalchemy. I have several models, and found myself wrote such code again and again: question = Session.query(Question).filter_by(id=question_id).one() answer = Session.query(Answer).fileter_by(id=answer_id).one()...
How to write a common get_by_id() method for all kinds of models in Sqlalchemy?
I'm using pylons with sqlalchemy. I have several models, and found myself wrote such code again and again: question = Session.query(Question).filter_by(id=question_id).one() answer = Session.query(Answer).fileter_by(id=answer_id).one() ... user = Session.query(User).filter_by(id=user_id).one() Since the models are all...
[ "If id is your primary key column, you just do:\nsession.query(Foo).get(id)\n\nwhich has the advantage of not querying the database if that instance is already in the session.\n", "Unfortunately, SQLAlchemy doesn't allow you to subclass Base without a corresponding table declaration. You could define a mixin clas...
[ 3, 2, 0 ]
[]
[]
[ "genericdao", "python", "sqlalchemy" ]
stackoverflow_0003638094_genericdao_python_sqlalchemy.txt
Q: Python: using downloaded modules I am new to Python and mostly used my own code. But so now I downloaded a package that I need for some problem I have. Example structure: root\ externals\ __init__.py cowfactory\ __init__.py cow.py milk.py kittens.py Now...
Python: using downloaded modules
I am new to Python and mostly used my own code. But so now I downloaded a package that I need for some problem I have. Example structure: root\ externals\ __init__.py cowfactory\ __init__.py cow.py milk.py kittens.py Now the cowfactory's __init__.py does fro...
[ "Inside the cowfactory package, relative imports should be used such as from . import cow. The __init__.py file in externals is not necessary. Assuming that your project lies in root\\ and cowfactory is the external package you downloaded, you can do it in two different ways:\n\nInstall the external module\nExterna...
[ 7, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003641322_python.txt
Q: What is necessary to use Win32 extensions with Portable Python I installed Portable Python in an USB drive and it is working but I cannot make it import Win32 extensions. A: Which version are you using? What is the error? If you are using PP 1.1 based on 2.6.1, there is a known bug that prevents import of python...
What is necessary to use Win32 extensions with Portable Python
I installed Portable Python in an USB drive and it is working but I cannot make it import Win32 extensions.
[ "Which version are you using? What is the error?\nIf you are using PP 1.1 based on 2.6.1, there is a known bug that prevents import of pythoncom and there is also a workaround to fix it:\nhttp://groups.google.com/group/portablepython/browse_frm/thread/acfacb783bc39cb7\n" ]
[ 1 ]
[]
[]
[ "portable_python", "python" ]
stackoverflow_0003639041_portable_python_python.txt
Q: Postfix hangs when sending email If I try to send an email as follows, the process hangs and nothing happens: >>> from django.core.management import setup_environ >>> from cube import settings >>> setup_environ(settings) 'cube' >>> from django.core.mail import send_mail >>> send_mail('Subject', 'Message', 'sender@...
Postfix hangs when sending email
If I try to send an email as follows, the process hangs and nothing happens: >>> from django.core.management import setup_environ >>> from cube import settings >>> setup_environ(settings) 'cube' >>> from django.core.mail import send_mail >>> send_mail('Subject', 'Message', 'sender@domain.com', ['recepient@domain.com'],...
[ "Your mail server isn't working fine. When you connect to it using telnet, you should see a welcome message along the lines of:\n220 your.server.name ESMTP Postfix\n\n(You can check the greeting that you should be seeing by running postconf smtpd_banner.)\nYou don't get that, so the mail server isn't running proper...
[ 11 ]
[]
[]
[ "django", "postfix_mta", "python", "smtp", "ubuntu_10.04" ]
stackoverflow_0003641936_django_postfix_mta_python_smtp_ubuntu_10.04.txt
Q: Automatic spam filtering or flagging for Django or Python? I'm working on a Django-based site that consists mostly of user- generated content: reviews, comments, tweet-like posts, etc. I'm concerned about spam. Are there any spam filters available for Django/Python? If not, what types of algorithms can be used ...
Automatic spam filtering or flagging for Django or Python?
I'm working on a Django-based site that consists mostly of user- generated content: reviews, comments, tweet-like posts, etc. I'm concerned about spam. Are there any spam filters available for Django/Python? If not, what types of algorithms can be used for automatic spam filtering or flagging? On a more general no...
[ "Take a look at SO question 915204. Jason Baker recommends using the Akismet Python API, which he states is what WordPress uses to stop spam. From the Akismet Python API website:\n\nAkismet is a web service for recognising spam comments.\n\nAlso, Patrick Beeson has a blog entry on how to use Akismet to stop spam on...
[ 2, 1 ]
[]
[]
[ "django", "python", "spam", "spam_prevention" ]
stackoverflow_0003641042_django_python_spam_spam_prevention.txt
Q: Django "for" loop and python dictionary problems I'm having a couple of issues getting django templating for loop tag to go through this dictionary: It is definitely being passed to the page ok as if I just do: {% for event in events %} {{ event }} {% endfor %} it writes 1,2,3 but when I try and do {{ event.s...
Django "for" loop and python dictionary problems
I'm having a couple of issues getting django templating for loop tag to go through this dictionary: It is definitely being passed to the page ok as if I just do: {% for event in events %} {{ event }} {% endfor %} it writes 1,2,3 but when I try and do {{ event.start }} it just doesn't output anything... evs = {...
[ "If you are just iterating over events you are just iterating over the dictonary's keys; you need to iterate over the dictionary's values: {% for event in events.values %}!\n", "Well, in your case, event is the always the key of one entry (which is a string), not the object itself, so event.start cannot work.\nHa...
[ 6, 5 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003642026_django_python.txt
Q: Is there a script to manage/search python snippets which understands python code like nullege.com? I have a folder full of python snippets and want to search it in a more intelligent way than grep. Is there already a script which parses python snippets to AST and lets you search it, like http://nullege.com? For ex...
Is there a script to manage/search python snippets which understands python code like nullege.com?
I have a folder full of python snippets and want to search it in a more intelligent way than grep. Is there already a script which parses python snippets to AST and lets you search it, like http://nullege.com? For example, if you have the following code: class InspectionFrame(wx.Frame): def SaveSettings(self, confi...
[ "To my knowledge, ctags is a classic tool for such a task. As of now, python support in exuberant ctags is lacking, but some work have been done last year: http://ctags.sourceforge.net/news.html.\nNow indexing of classes, functions, class members, variables and imports are supported.\n", "Your idea is awesome, I'...
[ 2, 1 ]
[]
[]
[ "code_snippets", "python", "search" ]
stackoverflow_0003599096_code_snippets_python_search.txt
Q: How to get byte offset in a file in python I am making a inverted index using hadoop and python. I want to know how can I include the byte offset of a line/word in python. I need something like this hello hello.txt@1124 I need the locations for making a full inverted index. Please help. A: Like this? file.tel...
How to get byte offset in a file in python
I am making a inverted index using hadoop and python. I want to know how can I include the byte offset of a line/word in python. I need something like this hello hello.txt@1124 I need the locations for making a full inverted index. Please help.
[ "Like this?\nfile.tell()\n\nReturn the file’s current position, like stdio's ftell().\nhttp://docs.python.org/library/stdtypes.html#file-objects\nUnfortunately tell() does not function since OP is using stdin instead of a file. But it is not hard to build a wrapper around it to give what you need.\nclass file_with_...
[ 12 ]
[]
[]
[ "inverted_index", "python" ]
stackoverflow_0003642088_inverted_index_python.txt
Q: Take first successful match from a batch of regexes I'm trying to extract set of data from a string that can match one of three patterns. I have a list of compiled regexes. I want to run through them (in order) and go with the first match. regexes = [ compiled_regex_1, compiled_regex_2, compiled_regex_...
Take first successful match from a batch of regexes
I'm trying to extract set of data from a string that can match one of three patterns. I have a list of compiled regexes. I want to run through them (in order) and go with the first match. regexes = [ compiled_regex_1, compiled_regex_2, compiled_regex_3, ] m = None for reg in regexes: m = reg.match(name...
[ "You can use the else clause of the for loop:\nfor reg in regexes:\n m = reg.match(name)\n if m: break\nelse:\n print 'ARGL NOTHING MATCHES THIS!!!'\n\n", "If you just want to know if any of the regex match then you could use the builtin any function:\nif any(reg.match(name) for reg in regexes):\n .....
[ 6, 2, 1, 1, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003642621_python_regex.txt
Q: Is this webpage-logging-in Python script correct? Is this Python script correct? import urllib, urllib2, cookielib username = 'myuser' password = 'mypassword' cj = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) login_data = urllib.urlencode({'username' : username, 'j_p...
Is this webpage-logging-in Python script correct?
Is this Python script correct? import urllib, urllib2, cookielib username = 'myuser' password = 'mypassword' cj = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) login_data = urllib.urlencode({'username' : username, 'j_password' : password}) opener.open('http://www.example....
[ "A simple \"view source\" on the login page whose URL you give reveals very easily the following detail about it... (just formatting the HTML minimally for readability):\n<span style=\"display:-moz-inline-stack\" class=\"unl\">\n <label for=\"userid\">User ID </label></span>\n<span><input size=\"27\" maxlength=\"...
[ 3 ]
[]
[]
[ "authentication", "built_in", "cookiecontainer", "cookies", "python" ]
stackoverflow_0003642569_authentication_built_in_cookiecontainer_cookies_python.txt
Q: Calculating if date is in start, future or present in Python I have two date/time strings: start_date = 10/2/2010 8:00:00 end_date = 10/2/2010 8:59:00 I need to write a function to calculate if the event is in the future, in the past or if it is happening right now - I've read a fair bit of documentation but j...
Calculating if date is in start, future or present in Python
I have two date/time strings: start_date = 10/2/2010 8:00:00 end_date = 10/2/2010 8:59:00 I need to write a function to calculate if the event is in the future, in the past or if it is happening right now - I've read a fair bit of documentation but just finding it quite hard to get this to work. I've not really don...
[ "from datetime import datetime\nstart_date = \"10/2/2010 8:00:00\"\nend_date = \"10/2/2010 8:59:00\"\n\n# format of date/time strings; assuming dd/mm/yyyy\ndate_format = \"%d/%m/%Y %H:%M:%S\"\n\n# create datetime objects from the strings\nstart = datetime.strptime(start_date, date_format)\nend = datetime.strptime(e...
[ 18 ]
[]
[]
[ "datetime", "django", "python", "time" ]
stackoverflow_0003642892_datetime_django_python_time.txt
Q: Adding a numpy array to a scipy.sparse.dok_matrix I have a scipy.sparse.dok_matrix (dimensions m x n), wanting to add a flat numpy-array with length m. for col in xrange(n): dense_array = ... dok_matrix[:,col] = dense_array However, this code raises an Exception in dok_matrix.__setitem__ when it tries to ...
Adding a numpy array to a scipy.sparse.dok_matrix
I have a scipy.sparse.dok_matrix (dimensions m x n), wanting to add a flat numpy-array with length m. for col in xrange(n): dense_array = ... dok_matrix[:,col] = dense_array However, this code raises an Exception in dok_matrix.__setitem__ when it tries to delete a non existing key (del self[(i,j)]). So, for no...
[ "I'm surprised that your unelegant way doesn't have the same problems as the slice way. This looks like a bug to me upon looking at the Scipy code. When you try to set a certain row and column in a dok_matrix to zero when it is already zero, there is be an error because it tries to delete the value at that row and ...
[ 2, 1 ]
[]
[]
[ "numpy", "python", "scipy", "sparse_matrix" ]
stackoverflow_0002674437_numpy_python_scipy_sparse_matrix.txt
Q: Amazon S3cmd crashes on some large uploads I routinely upload large bzipped sql files to S3 and have been noticing it crashing lately with this error. What might be causing this? Its always the same files that crash, but I am able to upload larger ones without a problem so it doesnt seem to be a size limit. !!!!!!...
Amazon S3cmd crashes on some large uploads
I routinely upload large bzipped sql files to S3 and have been noticing it crashing lately with this error. What might be causing this? Its always the same files that crash, but I am able to upload larger ones without a problem so it doesnt seem to be a size limit. !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! An unexp...
[ "S3 did not return an ETag [entity tag] in its response. Irrespective of what cause the ETag to be missing in the response, your version of s3cmd did not expect the ETag to be absent and aborted.\nAs far as I can tell, this should no longer be an issue in the latest version, 0.9.9.91, of s3cmd:\n## S3.py ##\n...\n...
[ 1 ]
[]
[]
[ "amazon_s3", "python" ]
stackoverflow_0003567080_amazon_s3_python.txt
Q: Google App Engine: Including external packages I understand that if you want to include external packages you have to include them in your project. So I was wondering how do you do this? Do people use one general script that auto imports them from a location. Maybe some kind of config file that lists all the exte...
Google App Engine: Including external packages
I understand that if you want to include external packages you have to include them in your project. So I was wondering how do you do this? Do people use one general script that auto imports them from a location. Maybe some kind of config file that lists all the external packages? Do you always zip the packages and us...
[ "Just place the package's folder in the root directory of your GAE application, easy!\n", "if you have modules or eggs in your scripts directory these can be imported like modules\nfor example if i wanted to use PyRTF on Google app engine i would copy the PyRTF folder from my computer into my projects root direct...
[ 2, 1, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003641538_google_app_engine_python.txt
Q: CherryPy How to respond with JSON? In my controller/request-handler, I have the following code: def monkey(self, **kwargs): cherrypy.response.headers['Content-Type'] = "application/json" message = {"message" : "Hello World!" } return message monkey.exposed = True And, in my view, I've got this javascript: ...
CherryPy How to respond with JSON?
In my controller/request-handler, I have the following code: def monkey(self, **kwargs): cherrypy.response.headers['Content-Type'] = "application/json" message = {"message" : "Hello World!" } return message monkey.exposed = True And, in my view, I've got this javascript: $(function() { var body = document.ge...
[ "Since CherryPy 3.2 there are tools to accept/return JSON:\n@cherrypy.expose\n@cherrypy.tools.json_out()\ndef monkey(self, **params):\n return {\"message\": \"Hello World!\"}\n\nUsing json_out serializes the output and sets the appropriate Content-Type header for you. \nSimilarly decorating with @cherrypy.tools...
[ 45, 14 ]
[]
[]
[ "cherrypy", "jquery", "json", "python" ]
stackoverflow_0003641007_cherrypy_jquery_json_python.txt
Q: storing file path using windows explorer browser in python I have written some encryption code in python that takes raw input message from user and then encrypts and decrypts it using AES. Now i want to enhance the working and i want that i can open the windows explorer from my code and browse to any file on my co...
storing file path using windows explorer browser in python
I have written some encryption code in python that takes raw input message from user and then encrypts and decrypts it using AES. Now i want to enhance the working and i want that i can open the windows explorer from my code and browse to any file on my computer, select it and when i press OK button the path to file is...
[ "That is because what you see when you open files in Windows is not actually an Explorer window, it is called a common dialog. I am assuming you are referering to this dialog:\n\nThere are different ways you can go about opening the common open dialog, among the most easiest is probably just using the Tkinter modul...
[ 6 ]
[]
[]
[ "explorer", "path", "python", "variables", "windows_explorer" ]
stackoverflow_0003643418_explorer_path_python_variables_windows_explorer.txt
Q: Delegates in python I've implemented this short example to try to demonstrate a simple delegation pattern. My question is. Does this look like I've understood delegation right? class Handler: def __init__(self, parent = None): self.parent = parent def Handle(self, event): handler = 'Handle_...
Delegates in python
I've implemented this short example to try to demonstrate a simple delegation pattern. My question is. Does this look like I've understood delegation right? class Handler: def __init__(self, parent = None): self.parent = parent def Handle(self, event): handler = 'Handle_' +event if hasat...
[ "One Python tip: you don't need to say:\nfunc = getattr(self.handler, 'Handle')\nfunc(event)\n\njust say:\nself.handler.Handle(event)\n\nI'm not sure what you are doing with your Handler class, it isn't used in your example.\nAnd in Python, methods with upper-case names are very very unusual, usually a result of po...
[ 17, 10 ]
[]
[]
[ "delegates", "design_patterns", "python" ]
stackoverflow_0003643538_delegates_design_patterns_python.txt
Q: Django / Python how to get the full request header? I've been looking over what I can find about this and found something about denying access to specific user-agents but couldn't find how I can actually get the full request header. I am trying to make a customized analytics app so would like access to the full he...
Django / Python how to get the full request header?
I've been looking over what I can find about this and found something about denying access to specific user-agents but couldn't find how I can actually get the full request header. I am trying to make a customized analytics app so would like access to the full headers.. any info is appreciated.
[ "All the headers are available in request.META. See the documentation.\n" ]
[ 12 ]
[]
[]
[ "django", "http_headers", "httprequest", "python" ]
stackoverflow_0003643766_django_http_headers_httprequest_python.txt
Q: python changing headers how do i change my headers and request so that i appear as firefox ... like when request to some servers import urllib f = urllib.urlopen("rss feed") they deny my request saying your client dosent have permission... i get reply but the reply contains " your client dosent have permission" s...
python changing headers
how do i change my headers and request so that i appear as firefox ... like when request to some servers import urllib f = urllib.urlopen("rss feed") they deny my request saying your client dosent have permission... i get reply but the reply contains " your client dosent have permission" so how do i get around this an...
[ "http://vsbabu.org/mt/archives/2003/05/27/urllib2_setting_http_headers.html\n", "If you want to use good old urllib instead of newer, fancier urllib2, then as urllib's docs say, and I quote,\nFor example, applications may want to specify a different User-Agent header than URLopener defines. This can be accomplish...
[ 2, 1 ]
[]
[]
[ "http_headers", "python" ]
stackoverflow_0003643775_http_headers_python.txt
Q: PythonWin saving session state I would like to be able to save my session state within the PythonWin editor (e.g. these three files are opened and positioned in these particular locations within the PythonWin window). I can get handles to each of the child windows within PythonWin using win32gui, as well as the t...
PythonWin saving session state
I would like to be able to save my session state within the PythonWin editor (e.g. these three files are opened and positioned in these particular locations within the PythonWin window). I can get handles to each of the child windows within PythonWin using win32gui, as well as the titles of each of the files and the p...
[ "I could be wrong, but isn't PythonWin written in Python?\nHave you tried reading the source to the \"Save\" command to figure out where it stores its full paths?\n(I'd take a look myself, but I haven't used Windows in half a decade)\n" ]
[ 0 ]
[]
[]
[ "python", "pywin32", "session", "win32gui" ]
stackoverflow_0003643696_python_pywin32_session_win32gui.txt
Q: Utf-8 with sqlalchemy on a database with init connect I am trying to use sqlalchemy to connect with mysql database. I have set up charset=utf-8$use_unicode=0. This worked with almost all databases, but not with a particular one. I believe it is because it has 'init-connect' variable set to 'SET NAMES latin2;' I ha...
Utf-8 with sqlalchemy on a database with init connect
I am trying to use sqlalchemy to connect with mysql database. I have set up charset=utf-8$use_unicode=0. This worked with almost all databases, but not with a particular one. I believe it is because it has 'init-connect' variable set to 'SET NAMES latin2;' I have no privileges to change that. It works for me if I send ...
[ "Sounds like what you want is a custom PoolListener. This SO answer explains how to write one in the context of SQLite's PRAGMA foreign_keys=ON\nSqlite / SQLAlchemy: how to enforce Foreign Keys?\n" ]
[ 1 ]
[]
[]
[ "mysql", "python", "sqlalchemy", "utf_8" ]
stackoverflow_0003617714_mysql_python_sqlalchemy_utf_8.txt
Q: Django url doesn't match even though it should In browser I get: Request URL: http://xxxxxx:8000/person/test/ Using the URLconf defined in person.urls, Django tried these URL patterns, in this order: ^person/ ^$ ^person/ ^person/(?P<slug>[-\w]+)/$ ^admin/ The current URL, person/test/, didn't match any of these...
Django url doesn't match even though it should
In browser I get: Request URL: http://xxxxxx:8000/person/test/ Using the URLconf defined in person.urls, Django tried these URL patterns, in this order: ^person/ ^$ ^person/ ^person/(?P<slug>[-\w]+)/$ ^admin/ The current URL, person/test/, didn't match any of these. In python shell I get: import re url = 'person/tes...
[ "It isn't matching against r'^person/(?P<slug>[-\\w]+)/$', the 404 page shows that it's matching against r'^person/person/(?P<slug>[-\\w]+)/$'\nYou've probably matched ^person/ in a urls.py, then imported another urls.py and put \"person\" in there also. Remove it from the second urls.py. After importing, a secon...
[ 5 ]
[]
[]
[ "django", "django_urls", "python" ]
stackoverflow_0003644095_django_django_urls_python.txt
Q: deploying python qt project can you tell me how do i deploy my project on qt designer. i am using windows and also how do i convert the .py files to standard .exe A: Converting ".py" to ".exe" would be like converting Java to ".exe" without using GCJ. Since the language doesn't compile to native code, you're ju...
deploying python qt project
can you tell me how do i deploy my project on qt designer. i am using windows and also how do i convert the .py files to standard .exe
[ "Converting \".py\" to \".exe\" would be like converting Java to \".exe\" without using GCJ. Since the language doesn't compile to native code, you're just bundling the interpreter and a packed set of .py files together using the same mechanism self-extracting .zip files use.\nThe main tools I know of for doing thi...
[ 4, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003511765_python.txt
Q: How to access comments using lxml I am trying to remove comments from a list of elements that were obtained by using lxml The best I have been able to do is: no_comments=[element for element in element_list if 'HtmlComment' not in str(type(each))] I am wondering if there is a more direct way? I am going to add so...
How to access comments using lxml
I am trying to remove comments from a list of elements that were obtained by using lxml The best I have been able to do is: no_comments=[element for element in element_list if 'HtmlComment' not in str(type(each))] I am wondering if there is a more direct way? I am going to add something based on Matthew's answer - he ...
[ "You can cut out the strings:\nfrom lxml.html import HtmlComment # or similar\nno_comments=[element for element in element_list if not isinstance(element, HtmlComment)]\n\n" ]
[ 1 ]
[]
[]
[ "html", "lxml", "parsing", "python" ]
stackoverflow_0003644186_html_lxml_parsing_python.txt
Q: Help with Windows Geometry in Python Why are the commands to change the window position before and after sleep(3.00) being ignored? if self.selectedM.get() == 'Bump': W1 = GetSystemMetrics(1) + 200 print W1 w1.wm_geometry("+100+" + str(W1)) w2.wm_geometry("+100+" + str(W1)) ...
Help with Windows Geometry in Python
Why are the commands to change the window position before and after sleep(3.00) being ignored? if self.selectedM.get() == 'Bump': W1 = GetSystemMetrics(1) + 200 print W1 w1.wm_geometry("+100+" + str(W1)) w2.wm_geometry("+100+" + str(W1)) w3.wm_geometry("+100+" + str(W1)) ...
[ "The answer to your question is that you don't give the system a chance to update the display. The display is updated by the event loop but you don't enter the event loop after either of the wm_geometry calls surrounding the sleep(3.00) call. They aren't being ignored, it's just that you're changing the geometry ag...
[ 1 ]
[]
[]
[ "algorithm", "python", "windows" ]
stackoverflow_0003327470_algorithm_python_windows.txt
Q: Reading data files in python 3.1 I am working on a project that is using data files from another program. My first attempt at reading the files was to open one of the files in binary mode, read the first 100 bytes and print the data to the terminal. I am not sure how to decipher the data that was displayed. The...
Reading data files in python 3.1
I am working on a project that is using data files from another program. My first attempt at reading the files was to open one of the files in binary mode, read the first 100 bytes and print the data to the terminal. I am not sure how to decipher the data that was displayed. The output that I got was: b'URES\x04\x00...
[ "Your best bet is to work upstream: find out more about the program that created these files. Find the person maintaining that program and ask them. Find other programs that consume this data.\nAt the very least, you're going to have to help us by telling us what you know about this data: what is it supposed to b...
[ 1, 0 ]
[]
[]
[ "linux", "python" ]
stackoverflow_0003644346_linux_python.txt
Q: Multiple values for key in dictionary in Python What I'm trying to do is get 3 values from a key into separate variables. Currently I'm doing it like this: for key in names: posX = names[key][0] posY = names[key][1] posZ = names[key][2] This doesn't seem very intuitive to me even though it works. I've al...
Multiple values for key in dictionary in Python
What I'm trying to do is get 3 values from a key into separate variables. Currently I'm doing it like this: for key in names: posX = names[key][0] posY = names[key][1] posZ = names[key][2] This doesn't seem very intuitive to me even though it works. I've also tried doing this: for key, value in names: loca...
[ "It's not unintuitive at all.\nThe only way to store \"multiple values\" for a given key in a dictionary is to store some sort of container object as the value, such as a list or tuple. You can access a list or tuple by subscripting it, as you do in your first example.\nThe only problem with your example is that it...
[ 11, 2, 2 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0003644409_dictionary_python.txt
Q: Default Python compilers on MacOS X I'm trying to install matplotlib for Python on MacOS X. If I use the system Python 2.6.1, the default compiler commands that matplotlib uses (presumably via distutils) are:: gcc-4.2 -DNDEBUG -g -fwrapv -Os -Wall -Wstrict-prototypes g++-4.2 -Wl,-F. -bundle -undefined dynamic_look...
Default Python compilers on MacOS X
I'm trying to install matplotlib for Python on MacOS X. If I use the system Python 2.6.1, the default compiler commands that matplotlib uses (presumably via distutils) are:: gcc-4.2 -DNDEBUG -g -fwrapv -Os -Wall -Wstrict-prototypes g++-4.2 -Wl,-F. -bundle -undefined dynamic_lookup However, if I simply add the python.o...
[ "The python.org release is designed to work just as well on MacOsX 10.5 as on 10.6, therefore of course it has to stick with a gcc release that is commonly available for both. Apple's system Python, of course, labors under no such constraint -- it supports only a very specific version of MacOsX and therefore can u...
[ 0 ]
[]
[]
[ "compiler_construction", "python" ]
stackoverflow_0003644399_compiler_construction_python.txt
Q: Language/GUI library to make map editor I'm designing a cross-platform map editor for an application I've developed, and I'm unsure what approach to take regarding language/gui library choice. Just for some basic info, the editor needs to parse and output xml files. I'm most comfortable with C++, Lua, and Perl, bu...
Language/GUI library to make map editor
I'm designing a cross-platform map editor for an application I've developed, and I'm unsure what approach to take regarding language/gui library choice. Just for some basic info, the editor needs to parse and output xml files. I'm most comfortable with C++, Lua, and Perl, but I'd also be willing to use Python (could us...
[ "My preference is always Gtk2 and Perl 5, but that combination works best on Linux. What OS are you going to run under?\nHere is an example Perl 5 script using Gtk2:\n#!/usr/bin/perl\n\nuse strict;\nuse warnings;\n\nuse Gtk2;\n\nGtk2->init;\n\nmy $window = Gtk2::Window->new;\nmy $vbox = Gtk2::VBox->new;\nmy $lab...
[ 4, 2, 2 ]
[]
[]
[ "c++", "lua", "perl", "python", "user_interface" ]
stackoverflow_0003644441_c++_lua_perl_python_user_interface.txt
Q: How do I get window attributes in Tkinter? self.attributes("-alpha", Alpha) How do I get window attributes in Tkinter? Currently I wan't my program to get the value of Alpha. A: In an earlier question you asked about transparency I gave an example that gets the alpha value for a window. See Having trouble with ...
How do I get window attributes in Tkinter?
self.attributes("-alpha", Alpha) How do I get window attributes in Tkinter? Currently I wan't my program to get the value of Alpha.
[ "In an earlier question you asked about transparency I gave an example that gets the alpha value for a window. See Having trouble with Tkinter transparency\n" ]
[ 2 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0003644515_python_tkinter.txt
Q: Python's getattr gets called twice? I am using this simple example to understand Python's getattr function: In [25]: class Foo: ....: def __getattr__(self, name): ....: print name ....: ....: In [26]: f = Foo() In [27]: f.bar bar bar Why is bar printed twice? Using Pyth...
Python's getattr gets called twice?
I am using this simple example to understand Python's getattr function: In [25]: class Foo: ....: def __getattr__(self, name): ....: print name ....: ....: In [26]: f = Foo() In [27]: f.bar bar bar Why is bar printed twice? Using Python 2.6.5.
[ "I think it's due to IPython.\nTo \"fix\" it, you have to disable autocall: %autocall 0\n\nIt's an inevitable side-effect of\n %autocall: since it has to analyze the\n object in the command line to see if\n it's callable, python triggers getattr\n calls on it.\n\nSource: http://mail.scipy.org/pipermail/ipython...
[ 9, 3 ]
[]
[]
[ "getattr", "python", "python_2.6", "reflection" ]
stackoverflow_0003644545_getattr_python_python_2.6_reflection.txt
Q: PyGTK treeview and row_activated callback I'm trying to retrieve the row data from a treemodel when the row_activated callback is fired. When row_activated is called, the 'path' variable it passes is a tuple. How do I easily use this tuple to retrieve an iter and ultimately the data itself? The treemodel class has...
PyGTK treeview and row_activated callback
I'm trying to retrieve the row data from a treemodel when the row_activated callback is fired. When row_activated is called, the 'path' variable it passes is a tuple. How do I easily use this tuple to retrieve an iter and ultimately the data itself? The treemodel class has a function to convert a string into an iter, b...
[ "Answering my own question, it makes sense after 45 minutes of googling I solve my own problem 30 seconds after posting on StackOverflow.\nI needed to use the get_iter function, not the get_iter_from_string function.\n" ]
[ 2 ]
[]
[]
[ "pygtk", "python" ]
stackoverflow_0003644777_pygtk_python.txt
Q: Setuptools not found I am switching from Linux to OSX and when I run our build's setup.py script, I get an error message that contains the text This script requires setuptools version 0.6c7. I have tried several times to install setuptools, and have verified that the setuptools egg exists in /Library/Python/2.6/...
Setuptools not found
I am switching from Linux to OSX and when I run our build's setup.py script, I get an error message that contains the text This script requires setuptools version 0.6c7. I have tried several times to install setuptools, and have verified that the setuptools egg exists in /Library/Python/2.6/site-packages. I have no i...
[ "It is very common to have multiple versions of Python on OS X systems. In recent releases of OS X, Apple has shipped two versions itself (in /usr/bin). You may have installed more recent versions using installers from python.org (which generally exist in /Library/Frameworks/Python.framework or using a package di...
[ 1, 0 ]
[]
[]
[ "macos", "python", "setup.py", "setuptools" ]
stackoverflow_0003644917_macos_python_setup.py_setuptools.txt
Q: How to parse a web use javascript to load .html by Python? I'm using Python to parse an auction site. If I use browser to open this site, it will go to a loading page, then jump to the search result page automatically. If I use urllib2 to open the webpage, the read() method only return the loading page. Is there a...
How to parse a web use javascript to load .html by Python?
I'm using Python to parse an auction site. If I use browser to open this site, it will go to a loading page, then jump to the search result page automatically. If I use urllib2 to open the webpage, the read() method only return the loading page. Is there any python package could wait until all contents are loaded then ...
[ "How does the search page work? If it loads anything using Ajax, you could do some basic reverse engineering and find the URLs involved using Firebug's Net panel or Wireshark and then use urllib2 to load those.\nIf it's more complicated than that, you could simulate the actions JS performs manually without loading ...
[ 0, 0 ]
[]
[]
[ "javascript", "python" ]
stackoverflow_0003637681_javascript_python.txt
Q: pkg_resources.VersionConflict when I try to start paster serve Im trying to use port 80. So when i use the command "sudo paster serve development.ini --reload" I get this error pkg_resources.VersionConflict: (Pylons 0.9.7 (/usr/lib/pymodules/python2.6), Requirement.parse('Pylons>=1.0')) I tried to do "easy_instal...
pkg_resources.VersionConflict when I try to start paster serve
Im trying to use port 80. So when i use the command "sudo paster serve development.ini --reload" I get this error pkg_resources.VersionConflict: (Pylons 0.9.7 (/usr/lib/pymodules/python2.6), Requirement.parse('Pylons>=1.0')) I tried to do "easy_install pylons" but I get "Pylons 1.0 is already the active version in ea...
[ "It sounds like Python is finding Pylons 0.9.7 before 1.0 in the module search path.\nIf that's the case, the simplest solution is probably to use your package manager to uninstall Pylons 0.9.7 and then use easy_install to restore anything that got removed as a side-effect.\nIf that doesn't do it, try also removing...
[ 3 ]
[]
[]
[ "pylons", "python" ]
stackoverflow_0003644921_pylons_python.txt
Q: Floats incorrect? - Python 2.6 I have a programming question, as follows, for which my solution does not produce the desired output This particle simulator operates in a universe with different laws of physics to ours. Each particle has a position (x, y), velocity (vx, vy) and an acceleration (ax, ay). Every part...
Floats incorrect? - Python 2.6
I have a programming question, as follows, for which my solution does not produce the desired output This particle simulator operates in a universe with different laws of physics to ours. Each particle has a position (x, y), velocity (vx, vy) and an acceleration (ax, ay). Every particle exerts an attractive force on e...
[ "You need to make a snapshot of the state and perform your calculations on the snapshot. If you move the particles around during the calculations as you are currently doing, you will get inconsistent results.\nSomething like this may work \nfrom copy import deepcopy\nfor iteration in range(times):\n i = 0\n ...
[ 5 ]
[]
[]
[ "floating_point", "python", "python_2.6" ]
stackoverflow_0003645185_floating_point_python_python_2.6.txt
Q: Why are mutable strings slower than immutable strings? Why are mutable strings slower than immutable strings? EDIT: >>> import UserString ... def test(): ... s = UserString.MutableString('Python') ... for i in range(3): ... s[0] = 'a' ... ... if __name__=='__main__': ... from timeit import Tim...
Why are mutable strings slower than immutable strings?
Why are mutable strings slower than immutable strings? EDIT: >>> import UserString ... def test(): ... s = UserString.MutableString('Python') ... for i in range(3): ... s[0] = 'a' ... ... if __name__=='__main__': ... from timeit import Timer ... t = Timer("test()", "from __main__ import test") ...
[ "In a hypothetical language that offers both mutable and immutable, otherwise equivalent, string types (I can't really think of one offhand -- e.g., Python and Java both have immutable strings only, and other ways to make one through mutation which add indirectness and therefore can of course slow things down a bit...
[ 26, 3, 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003644576_python.txt
Q: Ways to implement Flex [Bindable] in other languages As you may know, ActionScript allows you to mark a variable as [Bindable], causing any changes to that variable to have immediate effect all over your application. Pretty neat. How would you implement this feature in your favourite programming language? My first...
Ways to implement Flex [Bindable] in other languages
As you may know, ActionScript allows you to mark a variable as [Bindable], causing any changes to that variable to have immediate effect all over your application. Pretty neat. How would you implement this feature in your favourite programming language? My first guess was to use events or wrapper classes, but I couldn'...
[ "You'd use the Observer Pattern.\n" ]
[ 1 ]
[]
[]
[ "apache_flex", "bindable", "python" ]
stackoverflow_0003645598_apache_flex_bindable_python.txt
Q: In Google App Engine, how do I avoid creating duplicate entities with the same attribute? I am trying to add a transaction to keep from creating two entities with the same attribute. In my application, I am creating a new Player each time I see a new Google user logged in. My current implementation occasionally cr...
In Google App Engine, how do I avoid creating duplicate entities with the same attribute?
I am trying to add a transaction to keep from creating two entities with the same attribute. In my application, I am creating a new Player each time I see a new Google user logged in. My current implementation occasionally creates duplicate players when multiple json calls are made by a new Google user within a few mil...
[ "Use the username (or other identifier) as the key name, and use get_or_insert to transactionally create a new entity or return the existing one. Sahid's code won't work, because without a transaction, a race condition is still possible.\n", "Maybe you can use key name and get_by_key_name is better than filter.\n...
[ 4, 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003645582_google_app_engine_python.txt
Q: Simple RESTFUL client/server example in Python? Is there an online resource that shows how to write a simple (but robust) RESTFUL server/client (preferably with authentication), written in Python? The objective is to be able to write my own lightweight RESTFUL services without being encumbered by an entire web fra...
Simple RESTFUL client/server example in Python?
Is there an online resource that shows how to write a simple (but robust) RESTFUL server/client (preferably with authentication), written in Python? The objective is to be able to write my own lightweight RESTFUL services without being encumbered by an entire web framework. Having said that, if there is a way to do thi...
[ "Well, first of all you can use django-piston, as @Tudorizer already mentioned.\nBut then again, as I see it (and I might be wrong!), REST is more of a set of design guidelines, rather than a concrete API. What it essentially says is that the interaction with your service should not be based on 'things you can do' ...
[ 5, 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003645543_django_python.txt
Q: How to get the original value of changed fields? I'm using sqlalchemy as my orm, and use declarative as Base. Base = declarative_base() class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) name = Column(String) My question is, how do I know a user has been modified, and ho...
How to get the original value of changed fields?
I'm using sqlalchemy as my orm, and use declarative as Base. Base = declarative_base() class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) name = Column(String) My question is, how do I know a user has been modified, and how to get the original values without query database ag...
[ "\\To see if user has been modified you can check if user in session.dirty. If it is and you want to undo it, you can execute\nsession.rollback()\n\nbut be advised that this will rollback everything for the session to the last session.commit().\nIf you want to get the original values and memory serves me correctly,...
[ 13 ]
[]
[]
[ "insert_update", "python", "sqlalchemy" ]
stackoverflow_0003645802_insert_update_python_sqlalchemy.txt
Q: How to dynamically update values to arguments in Python loop? Python newbie here: I'm writing a market simulation in Python using Pysage, and want to generate an arbitrary number of agents (either buyers or sellers) using the mgr.register_actor() function, as follows: for name, maxValuation, endowment, id in xrang...
How to dynamically update values to arguments in Python loop?
Python newbie here: I'm writing a market simulation in Python using Pysage, and want to generate an arbitrary number of agents (either buyers or sellers) using the mgr.register_actor() function, as follows: for name, maxValuation, endowment, id in xrange(5): mgr.register_actor(Buyer(name="buyer001", maxValuation=10...
[ "You can prepare the names, maxValuations, and endowments as lists (or iterators), then use zip to group corresponding elements together:\nnames=['buyer{i:0>3d}'.format(i=i) for i in range(1,6)]\nmaxValuations=range(100,75,-5)\nendowments=range(500,250,-50)\nfor name, maxValuation, endowment in zip(names,maxValuati...
[ 4 ]
[]
[]
[ "for_loop", "python" ]
stackoverflow_0003646142_for_loop_python.txt
Q: Why would one use accelerators with fastcgi for PHP? I'm a newbie to web technology, and still on a learning curve. Heard that, fastcgi would keep the compiled(interpreted) php code in memory, so why would one has to use op-code caching (apc or eaccelerators) for PHP? But I never heard of any such accelerators fo...
Why would one use accelerators with fastcgi for PHP?
I'm a newbie to web technology, and still on a learning curve. Heard that, fastcgi would keep the compiled(interpreted) php code in memory, so why would one has to use op-code caching (apc or eaccelerators) for PHP? But I never heard of any such accelerators for Python. I'd expect as python and php are both interprete...
[ "Unlike PHP, (C)Python does not throw the bytecode away after running it. When module.py is imported and there is no module.pyc, it is bytecode-compiled and the result is copied to module.pyc; is it already exists, compilation is skipped and the ready-made module.pyc is used. One can do the same thing for the main ...
[ 2, 2, 0 ]
[]
[]
[ "fastcgi", "php", "python" ]
stackoverflow_0003646205_fastcgi_php_python.txt
Q: Python "ImportError: No module named" Problem I'm running Python 2.6.1 on Windows XP SP3. My IDE is PyCharm 1.0-Beta 2 build PY-96.1055. I'm storing my .py files in a directory named "src"; it has an __init__.py file that's empty except for an "__author__" attribute at the top. One of them is called Matrix.py: ...
Python "ImportError: No module named" Problem
I'm running Python 2.6.1 on Windows XP SP3. My IDE is PyCharm 1.0-Beta 2 build PY-96.1055. I'm storing my .py files in a directory named "src"; it has an __init__.py file that's empty except for an "__author__" attribute at the top. One of them is called Matrix.py: #!/usr/bin/env python """ "Core Python Programming"...
[ "This is a bit of a guess, but I think you need to \nchange your PYTHONPATH environment variable to include the src and test directories.\nRunning programs in the src directory may have been working, because Python automatically inserts the directory of the script it is currently running into sys.path. So importing...
[ 17, 1 ]
[]
[]
[ "pycharm", "python", "unit_testing" ]
stackoverflow_0003646307_pycharm_python_unit_testing.txt
Q: Is it Pythonic to mimic method overloading? Is it pythonic to mimic method overloading as found in statically typed languages? By that I mean writing a function that checks the types of its arguments and behaves differently based on those types. Here is an example: class EmployeeCollection(object): @staticmeth...
Is it Pythonic to mimic method overloading?
Is it pythonic to mimic method overloading as found in statically typed languages? By that I mean writing a function that checks the types of its arguments and behaves differently based on those types. Here is an example: class EmployeeCollection(object): @staticmethod def find(value): if isinstance(val...
[ "Not really, since you lose the ability to use types that are not-quite-that-but-close-enough. Create two separate methods (find_by_name() and find_by_number()) instead.\n", "Not very Pythonic, except perhaps, in 2.6 or better, if all the checks rely on the new abstract base classes, which are intended in part ex...
[ 13, 13, 5, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003642748_python.txt
Q: Neural Network, python I am trying to write a simple neural network that can come up with weights to for, say, the y=x function. Here's my code: http://codepad.org/rPdZ7fOz As you can see, the error level never really goes down much. I tried changing the momentum and learning rate but it did not help much. Is my ...
Neural Network, python
I am trying to write a simple neural network that can come up with weights to for, say, the y=x function. Here's my code: http://codepad.org/rPdZ7fOz As you can see, the error level never really goes down much. I tried changing the momentum and learning rate but it did not help much. Is my number of input, hidden and ...
[ "You're attempting to train the network to give output values 1,2,3,4 as far as I understood. Yet, at the output you use a sigmoid (math.tanh(..)) whose values are always between -1 and 1. \nSo the output of your Neural network is always between -1 and 1 and thus you always get a large error when trying to fit outp...
[ 2 ]
[]
[]
[ "backpropagation", "neural_network", "python" ]
stackoverflow_0003644795_backpropagation_neural_network_python.txt
Q: Abstract Django Application from "Project" I'm struggling to work out how best to do what I think I want to do - now it may be I don't have a correct understanding of what's best practice, so if not, feel free to howl at me etc. Basically, my question is, how do I abstract application functionality correctly, said...
Abstract Django Application from "Project"
I'm struggling to work out how best to do what I think I want to do - now it may be I don't have a correct understanding of what's best practice, so if not, feel free to howl at me etc. Basically, my question is, how do I abstract application functionality correctly, said functionality being found in an application tha...
[ "If I understand your problem correctly, then I would suggest doing a Custom Template Tag. In it you can do anything you want: use 0 or more args to the tag to get at and manipulate arbitrary objects, and then invoke the template engine \"by hand\" to get a snippet to return. E.g.\n[...]\nt = loader.get_template('s...
[ 1, 0, 0 ]
[]
[]
[ "django", "django_templates", "django_views", "python" ]
stackoverflow_0003646112_django_django_templates_django_views_python.txt
Q: When to use WSGI middleware? I write a router that takes the path of a request, match it against a regex and calls a WSGI handler, if the regex matches. The dict with the matching capturing groups is added to the envrion. Is it bad style to modify the environ with WSGI middleware? But is that what WSGI middleware ...
When to use WSGI middleware?
I write a router that takes the path of a request, match it against a regex and calls a WSGI handler, if the regex matches. The dict with the matching capturing groups is added to the envrion. Is it bad style to modify the environ with WSGI middleware? But is that what WSGI middleware was invented for? I've just read W...
[ "If you add things to the environ and then use those things in applications, without any fallbacks, then you have to some degree bound the application to the middleware.\nIn this particular case there is a convention for how to add those captured values to the environ: wsgiorg.routing_args. So while you would be p...
[ 5 ]
[]
[]
[ "python", "wsgi" ]
stackoverflow_0003646237_python_wsgi.txt
Q: Removing SOCKS 4/5 proxy This question is sort of the opposite of this: How can I use a SOCKS 4/5 proxy with urllib2? Let's say I use a SOCKS 5 proxy using the method accepted in that question. How would I revert it back to no proxy in the same process? i.e start process use proxy .. remove proxy ... Maybe there ...
Removing SOCKS 4/5 proxy
This question is sort of the opposite of this: How can I use a SOCKS 4/5 proxy with urllib2? Let's say I use a SOCKS 5 proxy using the method accepted in that question. How would I revert it back to no proxy in the same process? i.e start process use proxy .. remove proxy ... Maybe there is a better way to use the pro...
[ "Abra kadabra\nimport socks,socket,urllib2\nsocks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, \"127.0.0.1\", 8080)\ntemp = socket.socket\nsocket.socket = socks.socksocket \nprint urllib2.urlopen('http://www.google.com').read() // Proxy\nsocket.socket=temp\nprint urllib2.urlopen('http://www.google.com').read() // No p...
[ 11 ]
[]
[]
[ "proxy", "python", "sockets" ]
stackoverflow_0003632821_proxy_python_sockets.txt
Q: Best practice for a recursive console tool in Python What is the best practice (interface and implementation) for a command line tool that processes selected files in a directory tree? I give an example that comes to my mind, but I am looking for a 'best practice': flipcase foo.txt foo2.txt could process foo.txt ...
Best practice for a recursive console tool in Python
What is the best practice (interface and implementation) for a command line tool that processes selected files in a directory tree? I give an example that comes to my mind, but I am looking for a 'best practice': flipcase foo.txt foo2.txt could process foo.txt and save the result as foo2.txt. flipcase -rv *.txt coul...
[ "In my experience, the best starting point is to build a tool that follows basic Unix principles -- namely, to read from standard input and write to standard output. This allows people to use your tool in a flexible way:\nflipcase input.txt > output.txt\nothercommand | flipcase > output.txt\nflipcase | othercommand...
[ 2, 1, 1, 0 ]
[]
[]
[ "command_line", "python" ]
stackoverflow_0003646620_command_line_python.txt
Q: Why does Python (with twill) not want to log me in to a Yahoo mail box here? Can anyone, please, explain to me what's going on here. It seems that Python refuses to work (with twill) when I am trying to log in to my mailbox on Yahoo: Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit (Intel)] on w...
Why does Python (with twill) not want to log me in to a Yahoo mail box here?
Can anyone, please, explain to me what's going on here. It seems that Python refuses to work (with twill) when I am trying to log in to my mailbox on Yahoo: Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. *******...
[ "The problem lies in Mechanize. You need the newest version\nsu\ngit clone git://github.com/jjlee/mechanize.git\ncd mechanize\npython setup.py install\n\n" ]
[ 2 ]
[]
[]
[ "authentication", "python", "twill", "yahoo_mail" ]
stackoverflow_0003615355_authentication_python_twill_yahoo_mail.txt
Q: Python Software design I am starting to use python,more. Is there a good way to keep python disk access to a minimum. Seems to me that everytime a *.py file runs, it hits a hard disk. Is there way to avoid hitting the harddisk, and keep *.py file in memory and access it there. Would creating a small gui using ...
Python Software design
I am starting to use python,more. Is there a good way to keep python disk access to a minimum. Seems to me that everytime a *.py file runs, it hits a hard disk. Is there way to avoid hitting the harddisk, and keep *.py file in memory and access it there. Would creating a small gui using Wxframe, keep code in memory...
[ "If you run a .py file from the harddisk, the harddisk will be accessed.\nIn your GUI, just import your code and it will be loaded once and you can access it later.\n", "Modern operating systems cache file access pretty efficiently, as long as there is enough spare RAM available. You most likely won't notice any ...
[ 2, 2, 0 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0003647368_python_wxpython.txt
Q: How to control the size of the Windows shell window from within a python script? When launching a script-type python file from Windows you get a windows shell type window where the script runs. How can the script determine and also set/control the Window Size, Screen Buffer Size and Window Position of said window?...
How to control the size of the Windows shell window from within a python script?
When launching a script-type python file from Windows you get a windows shell type window where the script runs. How can the script determine and also set/control the Window Size, Screen Buffer Size and Window Position of said window?. I suspect this can be done with the pywin32 module but I can't find how.
[ "You can do this using the SetConsoleWindowInfo function from the win32 API. The following should work:\nfrom ctypes import windll, byref\nfrom ctypes.wintypes import SMALL_RECT\n\nSTDOUT = -11\n\nhdl = windll.kernel32.GetStdHandle(STDOUT)\nrect = wintypes.SMALL_RECT(0, 50, 50, 80) # (left, top, right, bottom)\nwi...
[ 12 ]
[]
[]
[ "python", "pywin32", "windows_shell" ]
stackoverflow_0003646362_python_pywin32_windows_shell.txt
Q: How to ignore pyc files in Netbeans project browser (regex question) I want to ignore .pyc files in the Netbeans project browser. I think I found a way: TOOLS -> MISCELLANEOUS -> FILES . Here is a section called: Files ignored by the IDE . The field there is waiting for a regex describing the file pattern . The de...
How to ignore pyc files in Netbeans project browser (regex question)
I want to ignore .pyc files in the Netbeans project browser. I think I found a way: TOOLS -> MISCELLANEOUS -> FILES . Here is a section called: Files ignored by the IDE . The field there is waiting for a regex describing the file pattern . The default value for that field is: ^(CVS|SCCS|vssver.?\.scc|#.*#|%.*%|_svn)$|~...
[ "Try this :\n^(CVS|SCCS|vssver.?\\.scc|#.*#|%.*%|_svn|.*\\.pyc)$|~$|^\\.(?!htaccess$).*$\n\nI just added the .*\\.pyc in the first group capture.\n" ]
[ 9 ]
[]
[]
[ "netbeans", "python", "regex" ]
stackoverflow_0003647771_netbeans_python_regex.txt
Q: Clear the screen in python Possible Duplicate: clear terminal in python How can I clear the window for all text, so that it looks like it has just been opened? I've heard os.system("clear") works, but it didn't. Using Python 2.6.5 on Windows 7 A: clear is for linux, I believe. cls should do the trick: os.syste...
Clear the screen in python
Possible Duplicate: clear terminal in python How can I clear the window for all text, so that it looks like it has just been opened? I've heard os.system("clear") works, but it didn't. Using Python 2.6.5 on Windows 7
[ "clear is for linux, I believe. cls should do the trick:\nos.system(\"cls\")\n", "os.system('cls')\nThat should work\n" ]
[ 1, 0 ]
[]
[]
[ "python", "windows" ]
stackoverflow_0003647175_python_windows.txt
Q: Is there a limit on the number of asynchronous urlfetch calls I can run simultaneously? I noticed what appears to be a limit on simultaneous asynchronous calls of urlfetch in the Java implementation (as noted here: http://code.google.com/appengine/docs/java/urlfetch/overview.html) but not in the python documentati...
Is there a limit on the number of asynchronous urlfetch calls I can run simultaneously?
I noticed what appears to be a limit on simultaneous asynchronous calls of urlfetch in the Java implementation (as noted here: http://code.google.com/appengine/docs/java/urlfetch/overview.html) but not in the python documentation: http://code.google.com/appengine/docs/python/urlfetch/asynchronousrequests.html So is it ...
[ "The limit for Python is just not documented in that page but in another one, which says (in the middle of the last paragraph of this section):\n\nThe app can have up to 10 simultaneous\n asynchronous URL Fetch calls.\n\nAs you see, that's the same limit as for Java.\n", "umm - that may be true for non-billable ...
[ 5, 1 ]
[]
[]
[ "google_app_engine", "python", "urlfetch" ]
stackoverflow_0003146349_google_app_engine_python_urlfetch.txt
Q: When is the `==` operator not equivalent to the `is` operator? (Python) I noticed I can use the == operator to compare all the native data types (integers, strings, booleans, floating point numbers etc) and also lists, tuples, sets and dictionaries which contain native data types. In these cases the == operator ch...
When is the `==` operator not equivalent to the `is` operator? (Python)
I noticed I can use the == operator to compare all the native data types (integers, strings, booleans, floating point numbers etc) and also lists, tuples, sets and dictionaries which contain native data types. In these cases the == operator checks if two objects are equal. But in some other cases (trying to compare ins...
[ "In Python, the == operator is implemented in terms of the magic method __eq__, which by default implements it by identity comparison. You can, however, override the method in order to provide your own concept of object equality. Note, that if you do so, you will usually also override at least __ne__ (which impleme...
[ 20, 18, 7, 4 ]
[]
[]
[ "comparison", "equality", "python" ]
stackoverflow_0003647692_comparison_equality_python.txt
Q: socket.error errno.EWOULDBLOCK i'm reading some code and i've come across this line socket.error errno.EWOULDBLOCK can anyone tell me what the conditions have to be to raise this error? A: From Python's socket module: http://docs.python.org/library/socket.html Initially all sockets are in blocking mode. In n...
socket.error errno.EWOULDBLOCK
i'm reading some code and i've come across this line socket.error errno.EWOULDBLOCK can anyone tell me what the conditions have to be to raise this error?
[ "From Python's socket module: http://docs.python.org/library/socket.html\n\nInitially all sockets are in blocking\n mode. In non-blocking mode, if a\n recv() call doesn’t find any data, or\n if a send() call can’t immediately\n dispose of the data, a error exception\n is raised.\n\nThe error exception it's ref...
[ 6, 3 ]
[]
[]
[ "networking", "python", "twisted" ]
stackoverflow_0003647539_networking_python_twisted.txt
Q: 'import feedparser' works via SSH, but fails when in browser I installed feedparser via SSH, using $ python setup.py install --home=~/httpdocs/python-libraries/feedparser-4.1/ I did that because I don't seem to have permission to properly run 'python setup.py install' I am running the following python code in 'te...
'import feedparser' works via SSH, but fails when in browser
I installed feedparser via SSH, using $ python setup.py install --home=~/httpdocs/python-libraries/feedparser-4.1/ I did that because I don't seem to have permission to properly run 'python setup.py install' I am running the following python code in 'test.py'. print "Content-type: text/html\n\n" try: import feedp...
[ "Maybe it's the problem with setting correct sys.path while running from shell vs from web server.\nMore about sys.path here: sys module.\nI'd recomend to try adding ~/httpdocs/python-libraries/feedparser-4.1/ (best using full path, without ~/) to your sys.path before the import. \nimport sys\nsys.path.append('/hom...
[ 7, 3, 0, 0 ]
[]
[]
[ "browser", "feedparser", "import", "python" ]
stackoverflow_0001755043_browser_feedparser_import_python.txt
Q: Python: how to pass a reference to a function IMO python is pass by value if the parameter is basic types, like number, boolean func_a(bool_value): bool_value = True Will not change the outside bool_value, right? So my question is how can I make the bool_value change takes effect in the outside one(pass by re...
Python: how to pass a reference to a function
IMO python is pass by value if the parameter is basic types, like number, boolean func_a(bool_value): bool_value = True Will not change the outside bool_value, right? So my question is how can I make the bool_value change takes effect in the outside one(pass by reference?
[ "You can use a list to enclose the inout variable:\ndef func(container):\n container[0] = True\n\n\ncontainer = [False]\nfunc(container)\nprint container[0]\n\nThe call-by-value/call-by-reference misnomer is an old debate. Python's semantics are more accurately described by CLU's call-by-sharing. See Fredrik L...
[ 6, 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0003648473_python.txt
Q: Python: Nested for loops or "next" statement I'm a rookie hobbyist and I nest for loops when I write python, like so: dict = { key1: {subkey/value1: value2} ... keyn: {subkeyn/valuen: valuen+1} } for key in dict: for subkey/value in key: do it to it I'm aware of a "next" keyword that...
Python: Nested for loops or "next" statement
I'm a rookie hobbyist and I nest for loops when I write python, like so: dict = { key1: {subkey/value1: value2} ... keyn: {subkeyn/valuen: valuen+1} } for key in dict: for subkey/value in key: do it to it I'm aware of a "next" keyword that would accomplish the same goal in one line (I ask...
[ "next is precious to advance an iterator when necessary, without that advancement controlling an explicit for loop. For example, if you want \"the first item in S that's greater than 100\", next(x for x in S if x > 100) will give it to you, no muss, no fuss, no unneeded work (as everything terminates as soon as a ...
[ 24 ]
[]
[]
[ "for_loop", "optimization", "python" ]
stackoverflow_0003648602_for_loop_optimization_python.txt
Q: Issue Replacing Already Existing Strings with ConfigParser I am using ConfigParser to save simple settings to a .ini file, and one of these settings is a directory. Whenever I replace a directory string such as D:/Documents/Data, with a shorter directory string such as D:/, the remaining characters are placed two...
Issue Replacing Already Existing Strings with ConfigParser
I am using ConfigParser to save simple settings to a .ini file, and one of these settings is a directory. Whenever I replace a directory string such as D:/Documents/Data, with a shorter directory string such as D:/, the remaining characters are placed two lines under the option. So the .ini file now looks like this: [...
[ "The r+ option (in the open in the with) is telling Python to keep the file's previous contents, just overwriting the specific bytes that will be written to it but leaving all others alone. Use w to open a file for complete overwriting, which seems to be what you should be doing here. Overwriting just selected by...
[ 1 ]
[]
[]
[ "configparser", "python" ]
stackoverflow_0003648612_configparser_python.txt
Q: python subclass access to class variable of parent I was surprised to to learn that a class variable of a subclass can't access a class variable of the parent without specifically indicating the class name of the parent: >>> class A(object): ... x = 0 ... >>> class B(A): ... y = x+1 ... Traceback (most r...
python subclass access to class variable of parent
I was surprised to to learn that a class variable of a subclass can't access a class variable of the parent without specifically indicating the class name of the parent: >>> class A(object): ... x = 0 ... >>> class B(A): ... y = x+1 ... Traceback (most recent call last): File "<stdin>", line 1, in <module> ...
[ "Python's scoping rules for barenames are very simple and straightforward: local namespace first, then (if any) outer functions in which the current one is nested, then globals, finally built-ins. That's all that ever happens when a barename is looked up, and there's no need to memorize or apply any complicated ru...
[ 51, 33 ]
[]
[]
[ "class_variables", "python", "subclass" ]
stackoverflow_0003648564_class_variables_python_subclass.txt
Q: Python Lxml - Append a existing xml with new data I am new to python/lxml After reading the lxml site and dive into python I could not find the solution to my n00b troubles. I have the below xml sample: --------------- <addressbook> <person> <name>Eric Idle</name> <phone type='fix'>999-999-999<...
Python Lxml - Append a existing xml with new data
I am new to python/lxml After reading the lxml site and dive into python I could not find the solution to my n00b troubles. I have the below xml sample: --------------- <addressbook> <person> <name>Eric Idle</name> <phone type='fix'>999-999-999</phone> <phone type='mobile'>555-555-555</phone...
[ "You could make a new tree by copying over all of the old one (not just the root tag!-), but it's much simpler to edit the existing tree in-place (and, why not?-)...:\ntree = etree.parse('addressbook.xml')\nroot = tree.getroot()\nNewSub = etree.SubElement ( root, 'CREATE_NEW_SUB' )\ntree.write ( 'addressbook1.xml' ...
[ 17 ]
[]
[]
[ "lxml", "python", "xml" ]
stackoverflow_0003648689_lxml_python_xml.txt
Q: how to crawl a 403 forbidden SNS i'm crawling an SNS with crawler written in python it works for a long time, but few days ago, the webpages got from my severs were ERROR 403 FORBIDDEN. i tried to change the cookie, change the browser, change the account, but all failed. and it seems that are the forbidden severs ...
how to crawl a 403 forbidden SNS
i'm crawling an SNS with crawler written in python it works for a long time, but few days ago, the webpages got from my severs were ERROR 403 FORBIDDEN. i tried to change the cookie, change the browser, change the account, but all failed. and it seems that are the forbidden severs are in the same network segment. what ...
[ "Looks like you've been blacklisted at the router level in that subnet, perhaps because you (or somebody else in the subnet) was violating terms of use, robots.txt, max crawling frequency as specified in a site-map, or something like that.\nThe solution is not technical, but social: contact the webmaster, be proper...
[ 1 ]
[]
[]
[ "http_status_code_403", "python", "web_crawler" ]
stackoverflow_0003648525_http_status_code_403_python_web_crawler.txt
Q: printing unicode through a QProcess I'm having some trouble handling unicode output from a QProcess. When I run the following example I get ?? instead of 中文. Can anyone tell me how to get the unicode output? from PyQt4.QtCore import * def on_ready_stdout(): byte_array = proc.readAllStandardOutput() prin...
printing unicode through a QProcess
I'm having some trouble handling unicode output from a QProcess. When I run the following example I get ?? instead of 中文. Can anyone tell me how to get the unicode output? from PyQt4.QtCore import * def on_ready_stdout(): byte_array = proc.readAllStandardOutput() print 'byte_array: ', byte_array print 'u...
[ "I've changed your code a little and got the expected output:\nbyte_array: hello 中文\n\nunicode: hello 中文\n\nmy changes were:\n\nI added # -- coding: utf-8 -- magic comment (details here)\nRemoved \"u\" string declaration from the proc.start call\n\nbelow is your code with my changes:\n# -*- coding: utf-8 -*-\nfro...
[ 0 ]
[]
[]
[ "pyqt", "python", "qprocess", "qt", "unicode" ]
stackoverflow_0003074969_pyqt_python_qprocess_qt_unicode.txt
Q: DB-API with Python I'm trying to insert some data into a local MySQL database by using MySQL Connector/Python -- apparently the only way to integrate MySQL into Python 3 without breaking out the C Compiler. I tried all the examples that come with the package; Those who execute can enter data just fine. Unfortunate...
DB-API with Python
I'm trying to insert some data into a local MySQL database by using MySQL Connector/Python -- apparently the only way to integrate MySQL into Python 3 without breaking out the C Compiler. I tried all the examples that come with the package; Those who execute can enter data just fine. Unfortunately my attempts to write ...
[ "You need to add a db.commit() to commit your changes before you db.close()!\n" ]
[ 5 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0003648861_mysql_python.txt
Q: C++ and python simultaneously. Is it doable I am totally new to programming as though I have my PhD as a molecular biologist for the last 10 years. Can someone please tell me: Would it be too hard to handle if I enrolled simultaneously in C++ and python? I am a full time employee too. Both courses start and finish...
C++ and python simultaneously. Is it doable
I am totally new to programming as though I have my PhD as a molecular biologist for the last 10 years. Can someone please tell me: Would it be too hard to handle if I enrolled simultaneously in C++ and python? I am a full time employee too. Both courses start and finish on the same dates and is for 3 months. For a var...
[ "You'll get holes in the head.\nPython's data structures and memory management are radically different from C++. \nWhichever language you \"get\" first, you'll love. The other you'll hate. Indeed, you'll be confused at the weird things one language lacks that the other has. One language will be reasonable, logi...
[ 7, 2, 1, 1, 0, 0, 0, 0 ]
[]
[]
[ "c++", "python" ]
stackoverflow_0003416342_c++_python.txt
Q: smart automatic C code generator with nested if in python I'm generating automatic C++ code from python, in particular I need to select some events for a list of events. I declare some selections: selectionA = Selection(name="selectionA", formula="A>10") selectionB = Selection(name="selectionB", formula="cobject->...
smart automatic C code generator with nested if in python
I'm generating automatic C++ code from python, in particular I need to select some events for a list of events. I declare some selections: selectionA = Selection(name="selectionA", formula="A>10") selectionB = Selection(name="selectionB", formula="cobject->f()>50") selectionC = selectionA * selectionB # * means AND th...
[ "It's unlikely that a compiler could optimize this code. Partly because cobject->f() might have side effects the compiler can't see.\nYou could help in a minor way by declaring your bools as const.\nOtherwise, it looks like you're already overloading operators to compose selections. So it shouldn't be too hard to...
[ 2, 1, 0, 0 ]
[]
[]
[ "c++", "code_generation", "compiler_construction", "python" ]
stackoverflow_0003595174_c++_code_generation_compiler_construction_python.txt