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: Transferring variables between classes I have 2 classes that operate on the same variables but do the inverse of each other. Is there a way to transfer the variables between them without hard coding every exchange or combining all the values into one array? Combining the classes is not an option. #pseudocode clas...
Transferring variables between classes
I have 2 classes that operate on the same variables but do the inverse of each other. Is there a way to transfer the variables between them without hard coding every exchange or combining all the values into one array? Combining the classes is not an option. #pseudocode class class1: def __init___(self): # co...
[ "Put the shared data into a third object and reference it from both classes.\n", "I think this is much easier than you think. Here is some examples of \"sending\" data between two classes.\nclass class2(object):\n def __init__(self, other):\n self.other = other\n\n def set_color(self, color):\n ...
[ 2, 2 ]
[]
[]
[ "class", "class_variables", "python", "variables" ]
stackoverflow_0004571590_class_class_variables_python_variables.txt
Q: Ruby or Python for heavy import script? I have an application I wrote in PHP (on symfony) that imports large CSV files (up to 100,000 lines). It has a real memory usage problem. Once it gets through about 15,000 rows, it grinds to a halt. I know there are measures I could take within PHP but I'm kind of done with ...
Ruby or Python for heavy import script?
I have an application I wrote in PHP (on symfony) that imports large CSV files (up to 100,000 lines). It has a real memory usage problem. Once it gets through about 15,000 rows, it grinds to a halt. I know there are measures I could take within PHP but I'm kind of done with PHP, anyway. If I wanted to write an app that...
[ "What are you importing the CSV file into? Couldn't you parse the CSV file in a way that doesn't load the whole thing into memory at once (i.e. work with one line at a time)?\nIf so, then you can use Ruby's standard CSV library to do something like the following\"\nCSV.open('csvfile.csv', 'r') do |row|\n #executes...
[ 10, 9, 3, 1 ]
[]
[]
[ "import", "lisp", "php", "python", "ruby" ]
stackoverflow_0004571119_import_lisp_php_python_ruby.txt
Q: Is there a standard set of libraries for dynamic strings, lists, and dictionaries in C? I'm interested in getting into C to get close to the metal performance, but would like to write in a Pythonic style and don't want to roll my own dynamic strings, lists, and dictionaries. Cython is pretty good, but would like t...
Is there a standard set of libraries for dynamic strings, lists, and dictionaries in C?
I'm interested in getting into C to get close to the metal performance, but would like to write in a Pythonic style and don't want to roll my own dynamic strings, lists, and dictionaries. Cython is pretty good, but would like to know how to use dynamic variables in straight C if possible. With C++ there is of course t...
[ "glib is pretty good and widely used:\n\nGLib provides the core application\n building blocks for libraries and\n applications written in C. It provides\n the core object system used in GNOME,\n the main loop implementation, and a\n large set of utility functions for\n strings and common data structures.\n\nI...
[ 4, 3 ]
[]
[]
[ "c", "c++", "cython", "python" ]
stackoverflow_0004571807_c_c++_cython_python.txt
Q: passing blob parameter to django I keep my images in the DB as blobs: class MyClass(db.Model): icon=db.BlobProperty() Now, I want to send the blob to my HTML like this : lets say I have myClass as an instance of MyClass result = """<div img_attr=%s> Bla Bla </div>""" % (myClass.icon) Some how it doesn't work...
passing blob parameter to django
I keep my images in the DB as blobs: class MyClass(db.Model): icon=db.BlobProperty() Now, I want to send the blob to my HTML like this : lets say I have myClass as an instance of MyClass result = """<div img_attr=%s> Bla Bla </div>""" % (myClass.icon) Some how it doesn't work. Do you have any idea?
[ "You cannot just dump raw image data into your html page. You need to do this in two pieces:\nIn your html, you need to refer to an image file:\nresult = \"<div>\"\n \"<img src='{0}' />\"\n \"</div>\"\n .format(MYSITE + MYIMAGEDIR + myClass.name)\n\nYour browser reads the html page, finds ou...
[ 1, 0, 0 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0004571348_django_google_app_engine_python.txt
Q: Python dict to JSON via json.loads: I have troubleshooting some code that uses HTTP POST to send data and should return a JSON result whose contents are a dictionary. I am using an XML-RPC wrapper to expose this service. When the wrapper receives the dict information from the http response variable, the dict conte...
Python dict to JSON via json.loads:
I have troubleshooting some code that uses HTTP POST to send data and should return a JSON result whose contents are a dictionary. I am using an XML-RPC wrapper to expose this service. When the wrapper receives the dict information from the http response variable, the dict contents are in a string in this form: {'creat...
[ "You are trying to use the wrong method. json.loads is for loading JSON to Python. If you want to convert Python to JSON, you need json.dumps.\nresult = json.dumps(response[1])\n\n", "That dict is in Python dict literal format, not JSON. You can do:\nimport ast\nresult = ast.literal_eval(response[1])\n\nto read i...
[ 36, 5, 3 ]
[]
[]
[ "django", "http_post", "json", "python" ]
stackoverflow_0004571684_django_http_post_json_python.txt
Q: how can I used the “pefile.py” to get file(.exe) version I want to used python to get the executed file version, and i know the pefile.py how to used it to do this? notes: the executed file may be not completely. A: This is the best answer I think you can find: import pefile pe = pefile.PE("/path/to/something.ex...
how can I used the “pefile.py” to get file(.exe) version
I want to used python to get the executed file version, and i know the pefile.py how to used it to do this? notes: the executed file may be not completely.
[ "This is the best answer I think you can find:\nimport pefile\npe = pefile.PE(\"/path/to/something.exe\")\n\nprint hex(pe.VS_VERSIONINFO.Length)\nprint hex(pe.VS_VERSIONINFO.Type)\nprint hex(pe.VS_VERSIONINFO.ValueLength)\nprint hex(pe.VS_FIXEDFILEINFO.Signature)\nprint hex(pe.VS_FIXEDFILEINFO.FileFlags)\nprint hex...
[ 6, 2 ]
[]
[]
[ "python" ]
stackoverflow_0001265078_python.txt
Q: Designing an open source OCR engine specifically for rendered text (screenshots) So my current personal project is to be able to automatically grab screenshots out of a game, OCR the text, and count the number of occurrences of given words. Having spent all evening looking around at different OCR solutions, I've c...
Designing an open source OCR engine specifically for rendered text (screenshots)
So my current personal project is to be able to automatically grab screenshots out of a game, OCR the text, and count the number of occurrences of given words. Having spent all evening looking around at different OCR solutions, I've come to realize that the majority of OCR packages out there are designed for scanned te...
[ "So I've been thinking about it and I feel that the best approach will be to count the number of pixels in each blob/glyph/character. This should really cut down on the number of tests I need to do to differentiate between glyphs.\nRegretfully, I'll have to be very specific about fonts. The software will only be ...
[ 2, 1, 0 ]
[]
[]
[ "ocr", "python", "screen_scraping" ]
stackoverflow_0004536763_ocr_python_screen_scraping.txt
Q: Is there someway I can get specific details about an AttributeError exception in Python? I'm trying to call a function. One of the parameters is a variable with attributes (which I know because of the AttributeError exception I got). I don't know the exact attributes this variable is supposed to have, so I was w...
Is there someway I can get specific details about an AttributeError exception in Python?
I'm trying to call a function. One of the parameters is a variable with attributes (which I know because of the AttributeError exception I got). I don't know the exact attributes this variable is supposed to have, so I was wondering if there was some way I can see some extra details about the exception, for example, ...
[ "AttributeError typically identifies the missing attribute. e.g.:\nclass Foo:\n def __init__(self):\n self.a = 1\n\nf = Foo()\nprint(f.a)\nprint(f.b)\n\nWhen I run that, I see:\n$ python foo.py\n1\nTraceback (most recent call last):\n File \"foo.py\", line 10, in <module>\n print(f.b)\nAttributeError:...
[ 16, 3, 0 ]
[]
[]
[ "attributes", "error_handling", "exception", "python" ]
stackoverflow_0004572362_attributes_error_handling_exception_python.txt
Q: arbitrary operation on list ["add",["subtract",["multiply",2,["add",1,3]], 4 ] , 5 ] how can I do these operation when prog see "add" it adds 1 and 3 and return 4 new list became ["add",["subtract",["multiply",2, 4 ], 4 ] , 5 ] when prog see "multiply" it does 2*4 nd return 8 new list became ["add",["subtract...
arbitrary operation on list
["add",["subtract",["multiply",2,["add",1,3]], 4 ] , 5 ] how can I do these operation when prog see "add" it adds 1 and 3 and return 4 new list became ["add",["subtract",["multiply",2, 4 ], 4 ] , 5 ] when prog see "multiply" it does 2*4 nd return 8 new list became ["add",["subtract",8, 4 ] , 5 ] after one recursi...
[ "You should write a recursive function that goes through the lists and do the operations.\nIt's actually fairly trivial, but I don't want to just hand you the answer, especially since it sounds like homework. :) So update your question with what you tried to do, and we'll tell you where you are going wrong.\n", "...
[ 1, 1, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0004569302_list_python.txt
Q: CollapsiblePane do not expand/collapse by mouse or respond to mouse I tried to use CollapsiblePane component of wxPython toolkit. I add 2 checkboxes directly in panel and 2 checkboxes under a CollapsiblePane which is placed in panel. My problem is that collapsible pane and components under it do not respond to mou...
CollapsiblePane do not expand/collapse by mouse or respond to mouse
I tried to use CollapsiblePane component of wxPython toolkit. I add 2 checkboxes directly in panel and 2 checkboxes under a CollapsiblePane which is placed in panel. My problem is that collapsible pane and components under it do not respond to mouse events, i.e. i cannot expand/collapse the pane or interact with compon...
[ "You created a self.panel object, but created your collapsible pane as a child of your frame.\nYou need to change how your window updates. First the sizer must layout then you must fit your panel, and then fit your window. Code is posted below. I changed the size of the frame so that you can see the expanding an...
[ 0 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0004548944_python_wxpython.txt
Q: Postgres 8.4.4 + psycopg2 + python 2.6.5 + Win7 instability You can see the combination of software components I'm using in the title of the question. I have a simple 10-table database running on a Postgres server (Win 7 Pro). I have client apps (python using psycopg to connect to Postgres) who connect to the d...
Postgres 8.4.4 + psycopg2 + python 2.6.5 + Win7 instability
You can see the combination of software components I'm using in the title of the question. I have a simple 10-table database running on a Postgres server (Win 7 Pro). I have client apps (python using psycopg to connect to Postgres) who connect to the database at random intervals to conduct relatively light transacti...
[ "If you're having problems with postgresql acting up like this, you should read this page:\nhttp://wiki.postgresql.org/wiki/Guide_to_reporting_problems\nFor an example of a real bug, and how to ask a question that gets action and answers, read this thread.\nhttp://archives.postgresql.org/pgsql-general/2010-12/msg01...
[ 1 ]
[]
[]
[ "database_connection", "postgresql", "psycopg2", "python" ]
stackoverflow_0004571280_database_connection_postgresql_psycopg2_python.txt
Q: realtime collaborative editing: mobwrite on windows7 x64 I have set up Mobwrite on my Win7 development machine using the daemon and q.py listener. The client test suite passes, but when I run the server test suite, everything fails with this sort of response: Question: U:user10259538167863824 f:0:unittest1025953...
realtime collaborative editing: mobwrite on windows7 x64
I have set up Mobwrite on my Win7 development machine using the daemon and q.py listener. The client test suite passes, but when I run the server test suite, everything fails with this sort of response: Question: U:user10259538167863824 f:0:unittest10259538167863824 R:0:Hello world Expected: u:user10259538167863824 ...
[ "The MobWrite support group would probably be the best place to ask this:\nhttp://groups.google.com/group/mobwrite\nI agree that the unit tests are probably failing due to line endings. MobWrite always uses \\n for its line endings. If the unit tests (an XML file) were transferred using ASCII to a Windows box, th...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004508419_python.txt
Q: Feedback on implementation of function which compares integer signs in Python I've made a small function which, given a tuple, compares if all elements in this tuple is of the same sign. E.g., tuple = [-1, -4, -6, -8] is good, while [-1, -4, 12, -8] is bad. I am not sure I've made the smartest implementation, so I...
Feedback on implementation of function which compares integer signs in Python
I've made a small function which, given a tuple, compares if all elements in this tuple is of the same sign. E.g., tuple = [-1, -4, -6, -8] is good, while [-1, -4, 12, -8] is bad. I am not sure I've made the smartest implementation, so I know this is the place to ask. def check_consistent_categories(queryset): try:...
[ "This might help you:\ndef all_same_sign(ints):\n return all(x < 0 for x in ints) or all(x > 0 for x in ints)\n\nYou may want to change < and > to <= and >= depending on how you want to treat 0.\n", "After @EOL's solution, but works without list indexing or iterating multiple times.\ndef all_same_sign(sequence...
[ 14, 3, 1, 1, 1, 1, 1, 0, 0 ]
[]
[]
[ "python", "sign" ]
stackoverflow_0004558326_python_sign.txt
Q: translate by replacing words inside existing text What are common approaches for translating certain words (or expressions) inside a given text, when the text must be reconstructed (with punctuations and everythin.) ? The translation comes from a lookup table, and covers words, collocations, and emoticons like L33...
translate by replacing words inside existing text
What are common approaches for translating certain words (or expressions) inside a given text, when the text must be reconstructed (with punctuations and everythin.) ? The translation comes from a lookup table, and covers words, collocations, and emoticons like L33t, CUL8R, :-), etc. Simple string search-and-replace is...
[ "The reason your smiley example doesn't work with regex is the \\b refers to a word boundary. Since there are no \"word\" characters in the smiley, there is no word boundary, so your expression doesn't match. You could use lookaheads/lookbehinds to see if you are bounded by spaces, but to check against punctuatio...
[ 1, 0, 0, 0 ]
[]
[]
[ "language_agnostic", "nlp", "python", "regex", "string" ]
stackoverflow_0002224915_language_agnostic_nlp_python_regex_string.txt
Q: Strange PYTHONPATH problem I recently updated my python installation to 2.7 (previously 2.5), and I've noticed a strange problem where I cannot import certain modules that I created. I had no problem before. Normally, I edit the PYTHONPATH and add the directory I want to import modules. For some strange reason,...
Strange PYTHONPATH problem
I recently updated my python installation to 2.7 (previously 2.5), and I've noticed a strange problem where I cannot import certain modules that I created. I had no problem before. Normally, I edit the PYTHONPATH and add the directory I want to import modules. For some strange reason, I can no longer import. I chec...
[ "Think I found the problem. Somehow I had added the some of the python standard libraries into PYTHONPATH. Once I removed those, everything works fine.\n" ]
[ 1 ]
[]
[]
[ "import", "importerror", "python" ]
stackoverflow_0004572880_import_importerror_python.txt
Q: running python script in bash slower than running code in IDLE I have written a python script to draw the sierpinski gasket using Tkinter and when run from the python IDLE the program takes about half the time it takes to run when run from bash. I timed the script using them time module in python. Any ideas as to ...
running python script in bash slower than running code in IDLE
I have written a python script to draw the sierpinski gasket using Tkinter and when run from the python IDLE the program takes about half the time it takes to run when run from bash. I timed the script using them time module in python. Any ideas as to why this is happening will be appreciated. thanks
[ "It's because of the way you're passing it. Based on your comment on the other answer, you're using python -c, and in IDLE you're using the Run command (or something similar). I'm not aware of any performance issues with python -c, but using Run in IDLE to run somescript.py is equivalent to python somescript.py.\nY...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004573094_python.txt
Q: Django Keyword Search Not Working I bought this book and Im busy working through it. Now what I found is that someone has already come across this same problem and posted here on this URL: "Practical django Projects, 2nd ed., source code Im having the exact same problem as above except that while it shows on the b...
Django Keyword Search Not Working
I bought this book and Im busy working through it. Now what I found is that someone has already come across this same problem and posted here on this URL: "Practical django Projects, 2nd ed., source code Im having the exact same problem as above except that while it shows on the backend when I perform a search for a pa...
[ "I have posted there this answer, I am reposting it here, maybe it will help you.\nDo you have:\nfrom django.contrib import admin\nadmin.autodiscover()\n\nin your urls.py? And also something like this:\nurlpatterns = patterns('',\n ...\n (r'^admin/', include(admin.site.urls)),\n)\n\nAnd also have you turned o...
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004572984_django_python.txt
Q: Using Tornado with Pika for Asynchronous Queue Monitoring I have an AMQP server (RabbitMQ) that I would like to both publish and read from in a Tornado web server. To do this, I figured I would use an asynchronous amqp python library; in particular Pika (a variation of it that supposedly supports Tornado). I have ...
Using Tornado with Pika for Asynchronous Queue Monitoring
I have an AMQP server (RabbitMQ) that I would like to both publish and read from in a Tornado web server. To do this, I figured I would use an asynchronous amqp python library; in particular Pika (a variation of it that supposedly supports Tornado). I have written code that appears to successfully read from the queue, ...
[ "It would help to see some source code, but I use this same tornado-supporting pika module without issue in more than one production project. \nYou don't want to create a connection per request. Create a class that wraps all of your AMQP operations, and instantiate it as a singleton at the tornado Application level...
[ 8, 0 ]
[]
[]
[ "amqp", "asynchronous", "python", "rabbitmq", "tornado" ]
stackoverflow_0004483440_amqp_asynchronous_python_rabbitmq_tornado.txt
Q: CeleryCAM not working... - Django/Celery celery works wonderfully! :) e.g. results are returned with no problems! Unfortunately celerycam does not: This is what my panel looks like, celeryev looks the same. NB: all those tasks have been completed succesfully, they are just not showing as completed, and the names ...
CeleryCAM not working... - Django/Celery
celery works wonderfully! :) e.g. results are returned with no problems! Unfortunately celerycam does not: This is what my panel looks like, celeryev looks the same. NB: all those tasks have been completed succesfully, they are just not showing as completed, and the names are not showing either. I'm usingthe followi...
[ "You can only run one monitor at a time (this is changing in the next version, 2.2). Make sure you don't have any left over celerycam/celeryev processes running, or upgrade to the development version (it is in freeze now, and is already well tested).\n" ]
[ 3 ]
[]
[]
[ "celery", "django", "python", "ubuntu" ]
stackoverflow_0004558271_celery_django_python_ubuntu.txt
Q: Self Modifying Python? How can I redirect all print statements within a function without touching sys.stdout? I have a situation where I am attempting to port some big, complex python routines to a threaded environment. I want to be able to, on a per-call basis, redirect the output from the function's print statem...
Self Modifying Python? How can I redirect all print statements within a function without touching sys.stdout?
I have a situation where I am attempting to port some big, complex python routines to a threaded environment. I want to be able to, on a per-call basis, redirect the output from the function's print statement somewhere else (a logging.Logger to be specific). I really don't want to modify the source for the code I am co...
[ "In Python2.6 (and 2.7), you can use\nfrom __future__ import print_function\n\nThen you can change the code to use the print() function as you would for Python3\nThis allows you to create a module global or local function called print which will be used in preference to the builtin function\neg.\nfrom __future__ im...
[ 6, 3, 2 ]
[]
[]
[ "python", "python_2.6" ]
stackoverflow_0004573727_python_python_2.6.txt
Q: Python: Get index of dictionary item in list I have a list li: [ {name: "Tom", age: 10}, {name: "Mark", age: 5}, {name: "Pam", age: 7} ] I want to get the index of the item that has a certain name. For example, if I ask for "Tom" it should give me: 0. "Pam" should give me 2. A: >>> from operator import itemgett...
Python: Get index of dictionary item in list
I have a list li: [ {name: "Tom", age: 10}, {name: "Mark", age: 5}, {name: "Pam", age: 7} ] I want to get the index of the item that has a certain name. For example, if I ask for "Tom" it should give me: 0. "Pam" should give me 2.
[ ">>> from operator import itemgetter\n>>> map(itemgetter('name'), li).index('Tom')\n0\n>>> map(itemgetter('name'), li).index('Pam')\n2\n\nIf you need to look up a lot of these from the same list, creating a dict as done in Satoru.Logic's answer, is going to be a lot more efficent\n", "You may index the dicts by n...
[ 28, 16 ]
[]
[]
[ "dictionary", "indexing", "list", "python" ]
stackoverflow_0004573875_dictionary_indexing_list_python.txt
Q: Python: Errors saving and loading objects with pickle module I am trying to load and save objects with this piece of code I get it from a question I asked a week ago: Python: saving and loading objects and using pickle. The piece of code is this: class Fruits: pass banana = Fruits() banana.color = 'yellow' ...
Python: Errors saving and loading objects with pickle module
I am trying to load and save objects with this piece of code I get it from a question I asked a week ago: Python: saving and loading objects and using pickle. The piece of code is this: class Fruits: pass banana = Fruits() banana.color = 'yellow' banana.value = 30 import pickle filehandler = open("Fruits.ob...
[ "Python does not pickle whole classes. Only the names. Therefore you must have the module that contains them saved to a file and importable at the time they are unpickled. Python will then re-import them. \nIf you run into problems, you may need to define special helper methods, __getstate__ and __setstate__ that a...
[ 4 ]
[]
[]
[ "object", "pickle", "python" ]
stackoverflow_0004573976_object_pickle_python.txt
Q: Python: saving and loading a class definition I am interested in saving and load objects using the pickle module as you can read in a question I asked before: Python: Errors saving and loading objects with pickle module Someone commment: 1, In an other way: the error is raise because pickle wanted to load an inst...
Python: saving and loading a class definition
I am interested in saving and load objects using the pickle module as you can read in a question I asked before: Python: Errors saving and loading objects with pickle module Someone commment: 1, In an other way: the error is raise because pickle wanted to load an instance of the class Fruits and search for the class d...
[ "The pickle module saves and loads the objects internal state. The code is not a part of the internal state, not even for classes, so therefore it gets tricky.\nThe obvious way is to make the whole class definition in a string, pickle that string, and then load it, and exec() that string. Another option that may or...
[ 10 ]
[]
[]
[ "class", "pickle", "python" ]
stackoverflow_0004574053_class_pickle_python.txt
Q: List updates in two places In python you can create a list like so: [[0,0]]*n This creates a list such as this: [[0, 0], [0, 0], [0, 0]] The issue is when you update the list such as: li[0][0]=10 [[10, 0], [10, 0], [10, 0]] Is there anyway to create lists of a certain size with this method but not encountering ...
List updates in two places
In python you can create a list like so: [[0,0]]*n This creates a list such as this: [[0, 0], [0, 0], [0, 0]] The issue is when you update the list such as: li[0][0]=10 [[10, 0], [10, 0], [10, 0]] Is there anyway to create lists of a certain size with this method but not encountering this problem? I created this wor...
[ "li = [[0,0] for i in range(players)]\n\n" ]
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0004574159_python.txt
Q: What is good practice for writing web applications that control daemons (and their config files) Can someone suggest some basic advice on dealing with web applications that interact with configuration files like httpd.conf, bind zone files, etc. I understand that it's bad practice, in fact very dangerous to allow ...
What is good practice for writing web applications that control daemons (and their config files)
Can someone suggest some basic advice on dealing with web applications that interact with configuration files like httpd.conf, bind zone files, etc. I understand that it's bad practice, in fact very dangerous to allow arbitrary execution of code without fully validating it and so on. But say you are tasked to write a s...
[ "I'm not a Unix security guru, but some basic things to think of:\n\nMake sure your web app runs as a specific user, and make sure that user has privileged rights only to those files which it is supposed to modify.\nDo not allow arbitrary inputs to be added to the files, have strict forms where each field is valida...
[ 1, 0 ]
[]
[]
[ "database_administration", "php", "python", "ruby_on_rails", "system_administration" ]
stackoverflow_0004573468_database_administration_php_python_ruby_on_rails_system_administration.txt
Q: What is the difference between self and object parameters in __repr__ method? I already know the difference between old-style class (class Foo()...) and new-style class (class Foo(object)...). But, what is the difference between that : class Foo(object): def __repr__(self): return 'foo' and class Foo(object...
What is the difference between self and object parameters in __repr__ method?
I already know the difference between old-style class (class Foo()...) and new-style class (class Foo(object)...). But, what is the difference between that : class Foo(object): def __repr__(self): return 'foo' and class Foo(object): def __repr__(object): return 'foo' Thanks.
[ "The difference is that in one case you called the variable that holds the instance self and in another case you called it object. That's the only difference.\nThe self variable is explicit in Python, and you can call it whatever you want. self is just the convention everyone uses for readability.\nFor example, thi...
[ 7, 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0004574296_python.txt
Q: Python: pynotify network problem I am using pynotify and this is the code I am trying to get to work: #! /usr/bin/python try: import pynotify if pynotify.init("Telebrama Alert"): n = pynotify.Notification('Message','This is test message') n.set_urgency(pynotify.URGENCY_CRITICAL) n.s...
Python: pynotify network problem
I am using pynotify and this is the code I am trying to get to work: #! /usr/bin/python try: import pynotify if pynotify.init("Telebrama Alert"): n = pynotify.Notification('Message','This is test message') n.set_urgency(pynotify.URGENCY_CRITICAL) n.show() else: print 'There w...
[ "pynotify is just an X client. To connect non-local X server you have to set DISPLAY environment variable. Note, that X server you are going to connect to should be configured to accept remote connections (see man pages for xhost and xauth).\n", "Well you should understand pynotify is not about network.\npynotify...
[ 2, 1, 0 ]
[]
[]
[ "pynotify", "python" ]
stackoverflow_0001768918_pynotify_python.txt
Q: SocketServer doesn't work on Linux I wrote a simple python script using the SocketServer, it works well on Windows, but when I execute it on a remote Linux machine(Ubuntu), it doesn't work at all.. The script is like below: #-*-coding:utf-8-*- import SocketServer class MyHandler(SocketServer.BaseRequestHandler):...
SocketServer doesn't work on Linux
I wrote a simple python script using the SocketServer, it works well on Windows, but when I execute it on a remote Linux machine(Ubuntu), it doesn't work at all.. The script is like below: #-*-coding:utf-8-*- import SocketServer class MyHandler(SocketServer.BaseRequestHandler): def handle(self): data_rcv...
[ "You are binding the server to 127.0.0.1, the IP address for localhost. This means the server will only accept connections originating from the same machine; it won't recognize ones coming from another machine.\nYou need to either bind to your external IP address, or bind to a wildcard address (i.e. don't bind to a...
[ 6, 2, 0 ]
[]
[]
[ "linux", "python", "python_2.7", "sockets" ]
stackoverflow_0004574605_linux_python_python_2.7_sockets.txt
Q: python web app in prod I am considering to use python serving json based web services, my priorities are, in order: maintainability easy of coding high availability performance Apache->AJP->Flup->Python seems ok to me, would you recommend another setup or is this ok ? A: What would AJP do in that setup? The on...
python web app in prod
I am considering to use python serving json based web services, my priorities are, in order: maintainability easy of coding high availability performance Apache->AJP->Flup->Python seems ok to me, would you recommend another setup or is this ok ?
[ "What would AJP do in that setup? The only \"flup\" I can find is a package with a \"Random assortment of WSGI servers\", which doesn't seem very helpful.\nI'd recommend you to look at Pyramid and Django. Two Python web frameworks with different philosophies that both fulfill your requirements. Then pick the one th...
[ 1, 1, 1, 0 ]
[]
[]
[ "ajp", "apache", "flup", "python" ]
stackoverflow_0004573980_ajp_apache_flup_python.txt
Q: Ignore folders with certain filetypes I'm trying in vain to rewrite my old Powershell script found here - "$_.extension -eq" not working as intended? - for Python.I have no Python experience or knowledge and my 'script' is a mess but it mostly works. The only thing missing is that I would like to be able to ignore...
Ignore folders with certain filetypes
I'm trying in vain to rewrite my old Powershell script found here - "$_.extension -eq" not working as intended? - for Python.I have no Python experience or knowledge and my 'script' is a mess but it mostly works. The only thing missing is that I would like to be able to ignore folders which don't contain 'mp3s', or whi...
[ "If I understand correctly, your core problem is that this script is creating a lot of empty pls.m3u files. That's because you're calling open before you've even checked whether you have anything you want to write.\nA simple fix would be to change this:\ntarget = open(\"pls.m3u\", 'w')\nj = os.path.abspath(os.getcw...
[ 2, 0 ]
[]
[]
[ "powershell", "python" ]
stackoverflow_0004574716_powershell_python.txt
Q: What are some decent IDEs that i can use to code python? Possible Duplicate: What IDE to use for Python? I really don't like the python gui, so im looking for an IDE to use. Open source. A: I've used Wing in the past. I like it. A: I would suggest bluefish. It's a very powerful IDE that i've used a lot and i...
What are some decent IDEs that i can use to code python?
Possible Duplicate: What IDE to use for Python? I really don't like the python gui, so im looking for an IDE to use. Open source.
[ "I've used Wing in the past. I like it.\n", "I would suggest bluefish. It's a very powerful IDE that i've used a lot and i definately suggest it.\n", "I use NetBeans with Python plugin. I like it because it integrates well with several Python versions I have installed, and it has some cool features (like unlock...
[ 1, 0, 0 ]
[]
[]
[ "ide", "open_source", "python" ]
stackoverflow_0004574960_ide_open_source_python.txt
Q: Prevent method calls for n seconds, show message of the remaining time I'm working on simple GUI but I'm stuck. This is the basic flow: Show text text and: save time in time_pressed start the progressbar and update it until time_notallow expires. If a user presses <Next> see if seconds specified in time_notall...
Prevent method calls for n seconds, show message of the remaining time
I'm working on simple GUI but I'm stuck. This is the basic flow: Show text text and: save time in time_pressed start the progressbar and update it until time_notallow expires. If a user presses <Next> see if seconds specified in time_notallow have passed, and if not, don't allow the display of the next text. Basic...
[ "You don't need threads or timers to solve this problem. All you need is a procedure that takes a number of seconds to wait, and have it call itself once a second until the number gets down to zero. \nIt would look something like this (off the top of my head, untested):\ndef __init__(...):\n ...\n self.locked...
[ 2, 0, 0 ]
[]
[]
[ "bind", "events", "python", "time", "tkinter" ]
stackoverflow_0004574447_bind_events_python_time_tkinter.txt
Q: In Python, can I specify a function argument's default in terms of other arguments? Suppose I have a python function that takes two arguments, but I want the second arg to be optional, with the default being whatever was passed as the first argument. So, I want to do something like this: def myfunc(arg1, arg2=arg1...
In Python, can I specify a function argument's default in terms of other arguments?
Suppose I have a python function that takes two arguments, but I want the second arg to be optional, with the default being whatever was passed as the first argument. So, I want to do something like this: def myfunc(arg1, arg2=arg1): print (arg1, arg2) Except that doesn't work. The only workaround I can think of i...
[ "As @Ignacio says, you can't do this. In your latter example, you might have a situation where None is a valid value for arg2. If this is the case, you can use a sentinel value:\nsentinel = object()\ndef myfunc(arg1, arg2=sentinel):\n if arg2 is sentinel:\n arg2 = arg1\n print (arg1, arg2)\n\nmyfunc(\"...
[ 30, 8, 4 ]
[]
[]
[ "arguments", "default_value", "function", "python" ]
stackoverflow_0004575326_arguments_default_value_function_python.txt
Q: invalid request when URL rewriting in web2py I'm learning web2py and I'm very happy with this framework, but I have a problem setting up nice urls. I want to transform: http://127.0.0.1:8000/computers/default/computer/this-is-a-test into: http://127.0.0.1:8000/computer/this-is-a-test I have put this in routes.py...
invalid request when URL rewriting in web2py
I'm learning web2py and I'm very happy with this framework, but I have a problem setting up nice urls. I want to transform: http://127.0.0.1:8000/computers/default/computer/this-is-a-test into: http://127.0.0.1:8000/computer/this-is-a-test I have put this in routes.py but I get an invalid request: default_application...
[ "I use autoroutes, take a look at autoroutes on web2py scripts folder\nhttp://snipt.net/rochacbruno/routesconf/ and /routespy/\n", "Change your $1's to $a's.\nThese are treated specially by web2py's rewrite parser, but must be alpha.\n" ]
[ 2, 1 ]
[]
[]
[ "python", "url_rewriting", "web2py" ]
stackoverflow_0004571779_python_url_rewriting_web2py.txt
Q: How can I setup a consistent python/django/virtualenv environment on my localhost, using my production settings? On my production server I have python 2.5.2 and django 1.1 installed in a virtualenv directory. I use pip as well. My production server runs on Debian. On my local pc I run ubuntu and I'd like to have c...
How can I setup a consistent python/django/virtualenv environment on my localhost, using my production settings?
On my production server I have python 2.5.2 and django 1.1 installed in a virtualenv directory. I use pip as well. My production server runs on Debian. On my local pc I run ubuntu and I'd like to have consistent packaging. I have wanted to play with fabric so I now want to setup the same exact environment locally. I do...
[ "Create a virtual instance mimicing your production environment. This will enable you to have a sandbox setup exactly like your production environment. Try VirtualBox :-)\n", "zc.buildout is a good tool for this, but it's not useful \"after the fact\". But for future projects you might want to consider using it. ...
[ 2, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004575545_django_python.txt
Q: Different standard deviation for same input from Wolfram and numpy I am currently working on reimplementing some algorithm written in Java in Python. One step is to calculate the standard deviation of a list of values. The original implementation uses DescriptiveStatistics.getStandardDeviation from the Apache Math...
Different standard deviation for same input from Wolfram and numpy
I am currently working on reimplementing some algorithm written in Java in Python. One step is to calculate the standard deviation of a list of values. The original implementation uses DescriptiveStatistics.getStandardDeviation from the Apache Math 1.1 library for this. I use the standard deviation of numpy 1.5. The pr...
[ "Apache and Wolfram divide by N-1 rather than N. This is a degrees of freedom adjustment, since you estimate μ. By dividing by N-1 you obtain an unbiased estimate of the population standard deviation. You can change NumPy's behavior using the ddof option.\nThis is described in the NumPy documentation:\n\nThe aver...
[ 24 ]
[]
[]
[ "java", "numpy", "python", "statistics" ]
stackoverflow_0004575645_java_numpy_python_statistics.txt
Q: Beautiful soup how print a tag while iterating over it My xml looks like this, I want to get the locations. <?xml version="1.0" encoding="UTF-8"?> <playlist version="1" xmlns="http://xspf.org/ns/0/"> <trackList> <track> <location>file:///home/ashu/Music/Collections/randomPicks/ipod%20on%20sep%2009/Coldplay-...
Beautiful soup how print a tag while iterating over it
My xml looks like this, I want to get the locations. <?xml version="1.0" encoding="UTF-8"?> <playlist version="1" xmlns="http://xspf.org/ns/0/"> <trackList> <track> <location>file:///home/ashu/Music/Collections/randomPicks/ipod%20on%20sep%2009/Coldplay-Sparks.mp3</location> <title>Coldplay-Sparks</title> </...
[ "Use lxml, it's faster and supports xpath:\n>>> doc = lxml.etree.fromstring(yourxml)\n>>> doc.xpath('//n:location/text()', namespaces={'n': 'http://xspf.org/ns/0/'})\n['file:///home/ashu/Music/Collections/randomPicks/ipod%20on%20sep%2009/Coldplay-Sparks.mp3',\n'file:///home/ashu/Music/Collections/randomPicks/gud%20...
[ 1, 0 ]
[]
[]
[ "beautifulsoup", "python", "xml" ]
stackoverflow_0004575622_beautifulsoup_python_xml.txt
Q: Python list comprehension overriding value have a look at the following piece of code, which shows a list comprehension.. >>> i = 6 >>> s = [i * i for i in range(100)] >>> print(i) When you execute the code example in Python 2.6 it prints 99, but when you execute it in Python 3.x it prints 6. What were the reaso...
Python list comprehension overriding value
have a look at the following piece of code, which shows a list comprehension.. >>> i = 6 >>> s = [i * i for i in range(100)] >>> print(i) When you execute the code example in Python 2.6 it prints 99, but when you execute it in Python 3.x it prints 6. What were the reason for changing the behaviour and why is the outp...
[ "The old behaviour was a mistake but couldn't easily be fixed as some code relied on it.\nThe variable i inside the list comprehension should be a different i from the one at the top level. Logically it should have its own scope which does not extend outside the comprehension as its value only makes sense inside th...
[ 33, 7, 5, 0 ]
[]
[]
[ "closures", "list_comprehension", "python" ]
stackoverflow_0004575698_closures_list_comprehension_python.txt
Q: python conditional list creation from 2D lists Say I've got a list of lists. Say the inner list of three elements in size and looks like this: ['apple', 'fruit', 1.23] The outer list looks like this data = [['apple', 'fruit', 1.23], ['pear', 'fruit', 2.34], ['lettuce', 'vegetable', 3.45]] I want ...
python conditional list creation from 2D lists
Say I've got a list of lists. Say the inner list of three elements in size and looks like this: ['apple', 'fruit', 1.23] The outer list looks like this data = [['apple', 'fruit', 1.23], ['pear', 'fruit', 2.34], ['lettuce', 'vegetable', 3.45]] I want to iterate through the outer list and cull data for ...
[ "[(i, k) for i, j, k in data if j == 'fruit']\n\n", "List comprehensions, using tuple indexing or slicing\ntempList = [(i[0], i[2]) for i in data if i[1] == 'fruit']\ntempList = [i[:1]+i[2:] for i in data if i[1] == 'fruit']\n\nAlso, generator expressions if you don't need a list, just the sequence.\n(here with t...
[ 5, 3, 3, 1, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0004575973_list_python.txt
Q: Clarification needed about Python CSV file format parsing Format is like: CHINA;2002-06-25 00:00:00.000;5,60 CHINA;2002-06-26 00:00:00.000;5,32 CHINA;2002-06-27 00:00:00.000;5,31 and I try to use Python's CSV tools to parse it but cannot understand the paragraph, source: And while the module doesn’t directly supp...
Clarification needed about Python CSV file format parsing
Format is like: CHINA;2002-06-25 00:00:00.000;5,60 CHINA;2002-06-26 00:00:00.000;5,32 CHINA;2002-06-27 00:00:00.000;5,31 and I try to use Python's CSV tools to parse it but cannot understand the paragraph, source: And while the module doesn’t directly support parsing strings, it can easily be done: import csv for row ...
[ "The docs you quote are talking about the difference between parsing csv data stored in a file, and csv data stored in a string. It doesn't have to do with the format of the data.\nYou should be able to read your data with something like:\nimport csv\ncsv_reader = csv.reader(open('data.csv', 'rb'), delimiter=';')\...
[ 3 ]
[]
[]
[ "csv", "parsing", "python" ]
stackoverflow_0004576163_csv_parsing_python.txt
Q: most widely used python web app deployment style I wonder which option is more stable (leaving performance aside) and is more widely used (I assume the widely used one is the most stable): apache -> mod_wsgi apache -> mod_fcgid apache -> mod_proxy_ajp apache -> mod_proxy_http for a project that will serve REST...
most widely used python web app deployment style
I wonder which option is more stable (leaving performance aside) and is more widely used (I assume the widely used one is the most stable): apache -> mod_wsgi apache -> mod_fcgid apache -> mod_proxy_ajp apache -> mod_proxy_http for a project that will serve REST services with small json formatted input and output m...
[ "apache -> mod-wsgi is currently the \"recommended\" solution. But it also depends on your needs quite a bit.\nThere is quite a difference between running 1 heavy application versus 1 light aplication or many light applications.\nPersonally my preferred setup is still nginx -> apache -> mod_wsgi with multiple apach...
[ 2, 0 ]
[]
[]
[ "apache", "fastcgi", "nginx", "python", "wsgi" ]
stackoverflow_0004575709_apache_fastcgi_nginx_python_wsgi.txt
Q: simple python file writing question I'm learning Python, and have run into a bit of a problem. On my OSX install of Python 3.1, this happens in the console: >>> filename = "test" >>> reader = open(filename, 'r') >>> writer = open(filename, 'w') >>> reader.read() '' >>> writer.write("hello world\n") 12 >>> reader.r...
simple python file writing question
I'm learning Python, and have run into a bit of a problem. On my OSX install of Python 3.1, this happens in the console: >>> filename = "test" >>> reader = open(filename, 'r') >>> writer = open(filename, 'w') >>> reader.read() '' >>> writer.write("hello world\n") 12 >>> reader.read() '' And calling more test in BASH c...
[ "There are two potential reasons why you are seeing this behaviour.\nWhen you open a file for writing (with the \"w\" open mode in Python), the OS removes the original file and creates a totally new one. So by opening the file for reading first and then writing, the original reading handle refers to a file that no ...
[ 3, 1, 0, 0 ]
[]
[]
[ "file", "python" ]
stackoverflow_0004576346_file_python.txt
Q: How to remove %20 from the file path? file:///home/ashu/Music/Collections/randomPicks/ipod%20on%20sep%2009/Coldplay-Sparks.mp3 How can I convert a string like the above to get the normal file path which I can pass to open() function? A: Have a look at url2pathname: import urllib2 path = urllib2.url2pathname("f...
How to remove %20 from the file path?
file:///home/ashu/Music/Collections/randomPicks/ipod%20on%20sep%2009/Coldplay-Sparks.mp3 How can I convert a string like the above to get the normal file path which I can pass to open() function?
[ "Have a look at url2pathname:\nimport urllib2\n\npath = urllib2.url2pathname(\"file:///home/ashu/Music/Collections/randomPicks/ipod%20on%20sep%2009/Coldplay-Sparks.mp3\")\n\n", "This is called unquote. Avaiable from urllib.\nimport urllib\nurllib.unquote('%20')\n\n" ]
[ 16, 10 ]
[]
[]
[ "filepath", "python" ]
stackoverflow_0004577120_filepath_python.txt
Q: Making a somehow complex application: Ruby vs Python I want to create a somehow complex application: It is a game level editor. You can put in tiles and other objects for a level. Then "compress" the level data into a file. With another application, it will read the file's data and play the game. The application i...
Making a somehow complex application: Ruby vs Python
I want to create a somehow complex application: It is a game level editor. You can put in tiles and other objects for a level. Then "compress" the level data into a file. With another application, it will read the file's data and play the game. The application is for Windows mainly. Other platforms are yet to be consid...
[ "Python + PyGame. Hands down. You will benefit from:\n\nGood docs for both the language and PyGame\nGUI, sprites, and audio all in one, again with PyGame\nBetter Windows support than Ruby (you can install both Python and PyGame from .exes)\n\nDesktop applications (esp. for Windows) aren't really Ruby's sweet spot. ...
[ 4, 1 ]
[]
[]
[ "python", "ruby", "user_interface" ]
stackoverflow_0004577156_python_ruby_user_interface.txt
Q: Restricted Assignment in Python's List Comprehensions? The example is stolen from here but my goal has a restriction so that output is [8,12,-54]. How can you do it with list comprehensions? I need to somehow refer to the index like x_{i}*y_{i}, I am hesitant to add a loop there, is there some elegant solution? >>...
Restricted Assignment in Python's List Comprehensions?
The example is stolen from here but my goal has a restriction so that output is [8,12,-54]. How can you do it with list comprehensions? I need to somehow refer to the index like x_{i}*y_{i}, I am hesitant to add a loop there, is there some elegant solution? >>> vec1 = [2, 4, 6] >>> vec2 = [4, 3, -9] >>> [x*y for x in v...
[ "[x * y for x, y in zip(vec1, vec2)]\n\n" ]
[ 10 ]
[]
[]
[ "list_comprehension", "python" ]
stackoverflow_0004577481_list_comprehension_python.txt
Q: urllib2 performs different between windows and *nix platform? This simple script performs auto login action. It can run on my Linux box (Python 2.7) and laptop (Mac OSX Python2.5), but I encounter problems on windows xp (both Python 2.6/2.7) Traceback (most recent call last): File "E:\workspace\python\login_baid...
urllib2 performs different between windows and *nix platform?
This simple script performs auto login action. It can run on my Linux box (Python 2.7) and laptop (Mac OSX Python2.5), but I encounter problems on windows xp (both Python 2.6/2.7) Traceback (most recent call last): File "E:\workspace\python\login_baidu.py", line 22, in <module> h=auto_login_hi(url,name,password) ...
[ "It isn't a Nix vs. Windows issue... your code fails on both platforms :)\nthis line is wrong:\nopener=urllib2.build_opener(request,cj)\n\ntry this instead:\nopener = urllib2.build_opener(cj)\n\nyou are calling build_opener() wrong. see the python docs.\nalso, you have an extra import for httplib that you don't nee...
[ 2, 0 ]
[]
[]
[ "python", "urllib2" ]
stackoverflow_0004577239_python_urllib2.txt
Q: Django book question: Database config problem. Getting Operational Error I am on chapter 5 of the django book and trying to proceed, but I'm stuck on one part: Link to exact chapter: http://www.djangobook.com/en/2.0/chapter05/ Problem: testing database configurations When I: Run python manage.py shell form withi...
Django book question: Database config problem. Getting Operational Error
I am on chapter 5 of the django book and trying to proceed, but I'm stuck on one part: Link to exact chapter: http://www.djangobook.com/en/2.0/chapter05/ Problem: testing database configurations When I: Run python manage.py shell form within the mysite project directory Then in the shell type these commands to test...
[ "My first guess is permissions error. What are the permissions on the Python27 directory, and do they correspond to the permissions from which you are running the python manage command.\nI typically put the database in the project directory, not the python directory.\n", "You're using sqlite, which creates a dat...
[ 0, 0 ]
[]
[]
[ "database", "django", "python" ]
stackoverflow_0004576940_database_django_python.txt
Q: MongoDB Map/Reduce raise exception: failed: db assertion failure I created map/reduce functions to group tasks results in one result object. I wrote in in python with using pymongo library: m = Code("""function() { data = {}; res = '' if(this.result_id) { res={'objectid':thi...
MongoDB Map/Reduce raise exception: failed: db assertion failure
I created map/reduce functions to group tasks results in one result object. I wrote in in python with using pymongo library: m = Code("""function() { data = {}; res = '' if(this.result_id) { res={'objectid':this.result_id.toString()}; } else { res=this.result;...
[ "I found my problem. As was said by one of developers, we can't use sorting without indexes. So if you use sorting, first of all you must create an index for that sorting.\n" ]
[ 2 ]
[]
[]
[ "mapreduce", "mongodb", "pymongo", "python" ]
stackoverflow_0004469693_mapreduce_mongodb_pymongo_python.txt
Q: Create function in python to find the highest of all function arguments, and return the "tag" of the value Consider the following: p1=1; p2=5; p3=7; highest=max(p1,p2,p3). The max function would return 7. I am looking to create a similar function, which would return "p3". I have created a small function (by simpl...
Create function in python to find the highest of all function arguments, and return the "tag" of the value
Consider the following: p1=1; p2=5; p3=7; highest=max(p1,p2,p3). The max function would return 7. I am looking to create a similar function, which would return "p3". I have created a small function (by simple comparisons) for the above example, shown below. however I am having trouble when the number of arguments go u...
[ "There is no way to get the name of the variable that had the highest value in the caller (because it might be a number or a complex expression), but by using keyword arguments exclusively, you can get the name of the parameter. Something like this:\ndef argmax(**kwargs):\n mx = -1e+400 # overflows to -Inf\n ...
[ 5, 5, 0, 0 ]
[]
[]
[ "function", "highest", "python" ]
stackoverflow_0004577345_function_highest_python.txt
Q: What web programming languages are capable of making this web app? I'm exploring many technologies, but I would like your input on which web framework would make this the easiest/ most possible. I'm currently looking to JSP/JSF/Primefaces, but I'm not sure if that is capable of this app. Here's a basic descriptio...
What web programming languages are capable of making this web app?
I'm exploring many technologies, but I would like your input on which web framework would make this the easiest/ most possible. I'm currently looking to JSP/JSF/Primefaces, but I'm not sure if that is capable of this app. Here's a basic description of the app: Users log in with their username and password (maybe I ca...
[ "The best approach is whatever is best for you. If Python isn't your strength but Java is, then use Java. If you're a Python expert and know little Java, use Python. \nThere are so many resources on the Internet supporting so many platforms that the decision really comes down to what works best for you.\n", "Fo...
[ 4, 2, 1 ]
[]
[]
[ "jsf", "jsf_2", "primefaces", "python", "web_applications" ]
stackoverflow_0004577414_jsf_jsf_2_primefaces_python_web_applications.txt
Q: Python regex string for keyword and keyword options How do I match a keyword in a string and if found look for options related to the keyword? These are the keywords and options that I need to find: Standard Snow <start date> <end date> Example: <24/12/2010> <9/1/2011> Rain <all day> or <start time> <end time> E...
Python regex string for keyword and keyword options
How do I match a keyword in a string and if found look for options related to the keyword? These are the keywords and options that I need to find: Standard Snow <start date> <end date> Example: <24/12/2010> <9/1/2011> Rain <all day> or <start time> <end time> Example: <8:30> <10:45> or <10:30> <13:00> Wind <all day>...
[ "You can try the following regex, it's more restrictive/specific and I think it should work:\nRegex = re.compile(r'''\n^(Rain|Snow|Wind|Standard) <(\\d+:\\d+|\\d+/\\d+/\\d+)>\n''', re.VERBOSE)\n\nEssentially it matches one of the types, followed by <somevaliddata>. Then you can take the second match group and split...
[ 1 ]
[]
[]
[ "python", "regex", "string" ]
stackoverflow_0004578527_python_regex_string.txt
Q: Python programming - Windows focus and program process I'm working on a python program that will automatically combine sets of files based on their names. Being a newbie, I wasn't quite sure how to go about it, so I decided to just brute force it with the win32api. So I'm attempting to do everything with virtual...
Python programming - Windows focus and program process
I'm working on a python program that will automatically combine sets of files based on their names. Being a newbie, I wasn't quite sure how to go about it, so I decided to just brute force it with the win32api. So I'm attempting to do everything with virtual keys. So I run the script, it selects the top file (after a...
[ "I would suggest using a command-line tool like pdftk http://www.pdflabs.com/tools/pdftk-the-pdf-toolkit/ - it does exactly what you want, it's cross-platform, it's free, and it's a small download.\nYou can easily call it from python with (for example) subprocess.Popen\nEdit: sample code as below:\nimport subproces...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0004577121_python.txt
Q: Should I log before or after an operation? I'm thinking about where to write the log record around an operation. Here are two different styles. The first one, write log before the operation. Before: log.info("Perform operation XXX") operation() And here is a different style, write the log after the operation. Aft...
Should I log before or after an operation?
I'm thinking about where to write the log record around an operation. Here are two different styles. The first one, write log before the operation. Before: log.info("Perform operation XXX") operation() And here is a different style, write the log after the operation. After: operation() log.info("Operation XXX is done....
[ "I'd typically use two different log levels.\nThe first one I put on a \"debug\" level, and the second one on an \"info\" level. That way typical production machines would only log what's being done, but I can turn on the debug logging and see what it tries to do before it errors out.\n", "It all depends what you...
[ 32, 1, 1 ]
[ "There's another style that I've seen used in Linux boot scripts and in strace. It's got the advantages of your combined style with less verbosity, but you've got to make sure that your logging facility isn't doing any buffering. I don't know log.info, so here's a rough example with print:\nprint \"Doing XXX... \...
[ -3 ]
[ "coding_style", "logging", "python" ]
stackoverflow_0004577376_coding_style_logging_python.txt
Q: Having a problem installing zeormq for python I'm a beginner on unix so I'm sorry if I post something easy. Also I have to admit that I do not master all the process. I need to install zeromq on my ubuntu. I have python 2.6.6 installed I followed the instructions on the website for UNIX systems : http://www.zeromq...
Having a problem installing zeormq for python
I'm a beginner on unix so I'm sorry if I post something easy. Also I have to admit that I do not master all the process. I need to install zeromq on my ubuntu. I have python 2.6.6 installed I followed the instructions on the website for UNIX systems : http://www.zeromq.org/intro:get-the-software and after http://www.ze...
[ "All the error you gave us is saying that gcc failed. Most likely gcc also gave you a long error message telling you why it failed. That is more helpful.\nIf I'm going to guess, some sort of development headers is missing. Probably the Python development headers, which you can install with \nsudo apt-get install py...
[ 12 ]
[]
[]
[ "python", "zeromq" ]
stackoverflow_0004578672_python_zeromq.txt
Q: Connecting slots and signals in PyQt4 in a loop Im trying to build a calculator with PyQt4 and connecting the 'clicked()' signals from the buttons doesn't work as expected. Im creating my buttons for the numbers inside a for loop where i try to connect them afterwards. def __init__(self): for i in range(0,10):...
Connecting slots and signals in PyQt4 in a loop
Im trying to build a calculator with PyQt4 and connecting the 'clicked()' signals from the buttons doesn't work as expected. Im creating my buttons for the numbers inside a for loop where i try to connect them afterwards. def __init__(self): for i in range(0,10): self._numberButtons += [QPushButton(str(i), ...
[ "This is just, how scoping, name lookup and closures are defined in Python.\nPython only introduces new bindings in namespace through assignment and through parameter lists of functions. i is therefore not actually defined in the namespace of the lambda, but in the namespace of __init__(). The name lookup for i i...
[ 18, 4, 0 ]
[]
[]
[ "pyqt4", "python", "signals_slots" ]
stackoverflow_0004578861_pyqt4_python_signals_slots.txt
Q: Django signals as IPC So I have written a websocket application in Twisted. The application is a basic game between a number of users, but trying to use the web socket for setup and record saving is painful, so I was looking into using Django based rendering for the supplementary information (as in standings, gam...
Django signals as IPC
So I have written a websocket application in Twisted. The application is a basic game between a number of users, but trying to use the web socket for setup and record saving is painful, so I was looking into using Django based rendering for the supplementary information (as in standings, game setup, lobby list, etc) a...
[ "No. Django signals are restricted to a single Python interpreter. You'll need to put together something else (sockets, JSON-RPC, XMPP, etc.) in order to perform IPC.\n" ]
[ 2 ]
[]
[]
[ "django", "ipc", "python", "twisted" ]
stackoverflow_0004579051_django_ipc_python_twisted.txt
Q: Tokenizing a string with unequal number of spaces between fields I am tryint to tokenize entries from a file. However I am not able to use the line.split("") option because of unequal number of spaces between files. I am copying a few lines from my file below: "08-09-2010 21:21:46 00:22:7f:a6:9b:69 ...
Tokenizing a string with unequal number of spaces between fields
I am tryint to tokenize entries from a file. However I am not able to use the line.split("") option because of unequal number of spaces between files. I am copying a few lines from my file below: "08-09-2010 21:21:46 00:22:7f:a6:9b:69 -79" "08-09-2010 21:21:46 04:4f:aa:b4:49:49...
[ "The columns look fixed-width, in which case you can use string slicing followed by a possible .strip() to remove trailing whitespace:\n>>> for line in data.split('\\n'):\n... print (line[1:25].strip(), line[26:45].strip(), line[46:69].strip(), line[70:-1].strip())\n... \n('08-09-2010 21:21:46', '00:22:7f:a6:9b...
[ 7, 1, 0, 0 ]
[]
[]
[ "python", "split", "tokenize" ]
stackoverflow_0004576391_python_split_tokenize.txt
Q: How to resume a Selenium RC test after a computer sleep? When I put my Mac to sleep while an interactive Python session with a selenium instance and corresponding browser is running, after waking up the browser (or selenium server?) are no longer responding to any commands from the Python shell. This forces me to ...
How to resume a Selenium RC test after a computer sleep?
When I put my Mac to sleep while an interactive Python session with a selenium instance and corresponding browser is running, after waking up the browser (or selenium server?) are no longer responding to any commands from the Python shell. This forces me to restart the browser, losing the state of my test. Is there a w...
[ "You might be able to make this work by setting ridiculously large timeout values on your Selenium commands. But, you may still run into a problem where MacOS X kills the network connection when it goes to sleep. Once the connection is severed, you're only real option would be to grab the test session ID and try ...
[ 0 ]
[]
[]
[ "macos", "python", "selenium", "selenium_rc" ]
stackoverflow_0003293788_macos_python_selenium_selenium_rc.txt
Q: How to write "Hello World" RESTful API using Python and then consume it I am totally new to Python. Can anybody guide me how to write and then consume a simple "Hello World" RESTful API in Python. A: I recommend using a WSGI “microframework” such as Bottle or web.py. Here's hello world with Bottle, taken directl...
How to write "Hello World" RESTful API using Python and then consume it
I am totally new to Python. Can anybody guide me how to write and then consume a simple "Hello World" RESTful API in Python.
[ "I recommend using a WSGI “microframework” such as Bottle or web.py.\nHere's hello world with Bottle, taken directly from its home page:\nfrom bottle import route, run\n\n@route('/:name')\ndef index(name='World'):\n return '<b>Hello %s!</b>' % name\n\nrun(host='localhost', port=8080)\n\n", "In general, I would...
[ 2, 1 ]
[]
[]
[ "python", "rest" ]
stackoverflow_0003061307_python_rest.txt
Q: Can Django Test Client Be Used for API Calls in Production? I'm building a Django app with an API built on Piston. For the sake of keeping everything as DRY as possible and the API complete, I'd like my internal applications to call the API rather than the models (kind of a proxy-view-controller a la https://githu...
Can Django Test Client Be Used for API Calls in Production?
I'm building a Django app with an API built on Piston. For the sake of keeping everything as DRY as possible and the API complete, I'd like my internal applications to call the API rather than the models (kind of a proxy-view-controller a la https://github.com/raganwald/homoiconic/blob/master/2010/10/vc_without_m.md bu...
[ "After reviewing the code for TestClient, it doesn't appear to have any additional overhead related to testing. Rather, it just functions as a basic client for internal requests. I'll be using the test client as the internal client, and using Piston's DjangoEmitter to get model objects back from the API.\nOnly test...
[ 10 ]
[]
[]
[ "api", "django", "django_testing", "python" ]
stackoverflow_0004576290_api_django_django_testing_python.txt
Q: What is the best way to parse python script file in C/C++ code I am embedding python in C/C++ program. What I am trying to do is to parse the python script file from the C/C++ program, break the file to "blocks" so that each "block" is an a valid command in python code. Each block I need to put into std::string. F...
What is the best way to parse python script file in C/C++ code
I am embedding python in C/C++ program. What I am trying to do is to parse the python script file from the C/C++ program, break the file to "blocks" so that each "block" is an a valid command in python code. Each block I need to put into std::string. For example: #PythonScript.py import math print "Hello Python" i = ...
[ "I've no idea why you want to do this, but the safest way is to let Python itself do the parsing work. If you're using Python earlier than 2.6, you can use the compiler module. For 2.6 and later, use the built-in compile function and the ast module. In 3.x you have to use these, as the compiler module has been remo...
[ 4, 1, 1, 0, 0 ]
[]
[]
[ "c", "c++", "parsing", "python" ]
stackoverflow_0004578253_c_c++_parsing_python.txt
Q: Splitting '12213123_mul_32432532' in Python Regex I hav Got HTTP Request Like GET /1213123_mul_32424324.html HTTP/1.1 User-Agent: ..... etc...etc... I need to send the multiplication of Integers 1213123 and 32424324... So I have created a Python ccript for this. I used the req.find() method to fetch integer. but ...
Splitting '12213123_mul_32432532' in Python Regex
I hav Got HTTP Request Like GET /1213123_mul_32424324.html HTTP/1.1 User-Agent: ..... etc...etc... I need to send the multiplication of Integers 1213123 and 32424324... So I have created a Python ccript for this. I used the req.find() method to fetch integer. but there should be a better way, like using regex. Whats t...
[ "This is a case where a regex is applicable:\n>>> re.search(r'^GET /(\\d+)_mul_(\\d+)\\.html', 'GET /1213123_mul_32424324.html HTTP/1.1').groups()\n('1213123', '32424324')\n\nCast the values using int(), multiply them and do what you want with the result.\nTo compare, this is how you could do it with .split(). I do...
[ 4 ]
[]
[]
[ "http", "python", "regex", "string" ]
stackoverflow_0004579395_http_python_regex_string.txt
Q: Problems POST-ing with pyCurl i'm trying to POST a file to a webservice using CURL (that's what I need to use so I can't take twisted or something else). The problem is that when using pyCurl the webservice doesn't receive the file i'm sending, as in the case commented at the bottom of the file. What am I doing wr...
Problems POST-ing with pyCurl
i'm trying to POST a file to a webservice using CURL (that's what I need to use so I can't take twisted or something else). The problem is that when using pyCurl the webservice doesn't receive the file i'm sending, as in the case commented at the bottom of the file. What am I doing wrong in my pyCurl script? Any ideeas...
[ "PyCurl seems to be an orphaned project. It hasn't been updated in two years. I just call command line curl as a subprocess.\nimport subprocess\n\ndef curl(*args):\n curl_path = '/usr/bin/curl'\n curl_list = [curl_path]\n for arg in args:\n # loop just in case we want to filter args in future.\n ...
[ 8, 1, 0 ]
[]
[]
[ "pycurl", "python", "webservice_client" ]
stackoverflow_0004154306_pycurl_python_webservice_client.txt
Q: Can't get Beaker cache working I'm trying to use Beaker's caching library but I can't get it working. Here's my test code. class IndexHandler(): @cache.cache('search_func', expire=300) def get_results(self, query): results = get_results(query) return results def get(self, query): ...
Can't get Beaker cache working
I'm trying to use Beaker's caching library but I can't get it working. Here's my test code. class IndexHandler(): @cache.cache('search_func', expire=300) def get_results(self, query): results = get_results(query) return results def get(self, query): results = self.get_results(query)...
[ "If you configure beaker to save to the filesystem, you can easily see that each argument is being pickled as well. Example:\ntp3\nsS'tags <myapp.controllers.tags.TagsController object at 0x103363c10> <MySQLdb.cursors.Cursor object at 0x103363dd0> apple'\np4\n\nNotice that the cache \"key\" contains more than just ...
[ 3, 1, 1 ]
[]
[]
[ "beaker", "python" ]
stackoverflow_0003170882_beaker_python.txt
Q: Interacting with web based game I would like to create a script, that will play for me a facebook game and I would like to write it in Python. Could you point me to some tutorial about how can I achieve that? A: The Reddit thread on "Making a game bot using Python" has some good replies relevant to this.
Interacting with web based game
I would like to create a script, that will play for me a facebook game and I would like to write it in Python. Could you point me to some tutorial about how can I achieve that?
[ "The Reddit thread on \"Making a game bot using Python\" has some good replies relevant to this.\n" ]
[ 1 ]
[]
[]
[ "facebook", "http", "python" ]
stackoverflow_0004579529_facebook_http_python.txt
Q: Why does simplejson work in Terminal and not TextMate? I'm using simplejson to get data from the New York Time API. It works when I run the file through the terminal with the command "python test.py" but not when I run through TextMate using command + R. I'm running the exact same file. Why is this? I am running S...
Why does simplejson work in Terminal and not TextMate?
I'm using simplejson to get data from the New York Time API. It works when I run the file through the terminal with the command "python test.py" but not when I run through TextMate using command + R. I'm running the exact same file. Why is this? I am running Snow Leopard 10.6.4, TextMate 1.5.10, and Python 2.6.4. Edit:...
[ "What doesn't work? You should provide more information like error messages and what-not. However, I assume that the version of python is different, and simplejson isn't on your PYTHONPATH when launched from textmate.\n", "Just so you know, simplejson was incorporated into the Python 2.6 distribution's standard l...
[ 1, 0 ]
[]
[]
[ "python", "simplejson", "textmate" ]
stackoverflow_0004235821_python_simplejson_textmate.txt
Q: What causes Python "Interpreter not Initialized (version mismatch?)" error? I'm now on my third full day this week of trying to get OpenCV to work with Python. (I have been trying on and off for the past 6 months). I get this error Python 2.7.1 (r271:86882M, Nov 30 2010, 10:35:34) [GCC 4.2.1 (Apple Inc. build 566...
What causes Python "Interpreter not Initialized (version mismatch?)" error?
I'm now on my third full day this week of trying to get OpenCV to work with Python. (I have been trying on and off for the past 6 months). I get this error Python 2.7.1 (r271:86882M, Nov 30 2010, 10:35:34) [GCC 4.2.1 (Apple Inc. build 5664)] on darwin Type "help", "copyright", "credits" or "license" for more informati...
[ "Every time I've tried to compile OpenCV on OS X, it will claim to find my custom installed Python but then link against the system Pyton (2.6) instead.\nThis is what is happening here, if you view the full compiler output for OpenCV it actually linked itself against 2.6 and will be unusable in your custom 2.7.\nIf...
[ 3 ]
[]
[]
[ "opencv", "osx_snow_leopard", "python", "python_2.7" ]
stackoverflow_0004579603_opencv_osx_snow_leopard_python_python_2.7.txt
Q: Can I instantiate a new object without using function notation? Why? If I make a simple class like this: class Foo: i = 1 j = 2 Can I instantiate a new object by simply using Foo on the right-hand side ( as opposed to saying Foo() )? I would guess not, but I just tried the following and it worked: finst = Foo...
Can I instantiate a new object without using function notation? Why?
If I make a simple class like this: class Foo: i = 1 j = 2 Can I instantiate a new object by simply using Foo on the right-hand side ( as opposed to saying Foo() )? I would guess not, but I just tried the following and it worked: finst = Foo print finst.i
[ "It works, because i is not a property of the object (or instance) but of the class. You are not creating a new instance.\nTry:\nclass Foo:\n def bar(self):\n print 42\n\nfinst = Foo\nfinst.bar()\n\n\nTraceback (most recent call last):\n File \"\", line 1, in \n TypeError: unbound method bar() must be calle...
[ 4, 1, 1, 1 ]
[]
[]
[ "class", "function", "python" ]
stackoverflow_0004579932_class_function_python.txt
Q: Installing python-mysql with wamp's mysql (I'm not sure if this should be asked here or SU.. but seeing this question on SO, I am asking it here...) I have wamp (mysql-5.1.33) server setup on my vista machine, and I am trying to install python-mysql 1.2.3c1 to use the mysql version provided by wamp. At first, when...
Installing python-mysql with wamp's mysql
(I'm not sure if this should be asked here or SU.. but seeing this question on SO, I am asking it here...) I have wamp (mysql-5.1.33) server setup on my vista machine, and I am trying to install python-mysql 1.2.3c1 to use the mysql version provided by wamp. At first, when I ran python setup.py install, I got an error ...
[ "The reason is msvc9compiler.py in Python26\\Lib\\distutils don't analyse VC version properly. You can check find_vcvarsall(version) in msvc9compiler.py yourself: it always turns version = 9, means VC9(2008) will work, but never VC8(2005). The awkward way to compile something using setup.py with VC8 is make version...
[ 1, 0, 0 ]
[]
[]
[ "mysql", "mysql_python", "python" ]
stackoverflow_0001581431_mysql_mysql_python_python.txt
Q: Update Facebook Page's status using pyfacebook I am attempting to add functionality to my Django app: when a new post is approved, I want to update the corresponding Facebook Page's status with a message and a link to the post automatically. Basic status update. I have downloaded and installed pyfacebook - and I ...
Update Facebook Page's status using pyfacebook
I am attempting to add functionality to my Django app: when a new post is approved, I want to update the corresponding Facebook Page's status with a message and a link to the post automatically. Basic status update. I have downloaded and installed pyfacebook - and I have read through the tutorial from Facebook. I hav...
[ "In the definition of login, particularly in the docstring, it appears as though the intended behavior is to open up a browser in order to have you log in that way.\ndef login(self, popup=False):\n \"\"\"Open a web browser telling the user to login to Facebook.\"\"\"\n import webbrowser\n webbrowser.open(...
[ 2, 0 ]
[]
[]
[ "django", "facebook", "pyfacebook", "python" ]
stackoverflow_0001907662_django_facebook_pyfacebook_python.txt
Q: Replace all accented characters by their LaTeX equivalent Given a Unicode string, I want to replace non-ASCII characters by LaTeX code producing them (for example, having é become \'e, and œ become \oe). I'm incorporating this into a Python code. This should rely on a translation table, and I have come up with the...
Replace all accented characters by their LaTeX equivalent
Given a Unicode string, I want to replace non-ASCII characters by LaTeX code producing them (for example, having é become \'e, and œ become \oe). I'm incorporating this into a Python code. This should rely on a translation table, and I have come up with the following code, which is simple and seems to work nicely: acce...
[ "OK, so here's the table I've built up for now. Please feel free to edit to add to it! (or comment if you don't have enough reputation to edit)\n################################################################\n# LaTeX accents replacement\nlatexAccents = [\n [ u\"à\", \"\\\\`a\" ], # Grave accent\n [ u\"è\", \"\\...
[ 12, 11, 3, 1 ]
[]
[]
[ "diacritics", "latex", "python", "unicode" ]
stackoverflow_0004578912_diacritics_latex_python_unicode.txt
Q: how to crop image in web based python application? I'm searching for a way to crop image on a web based python application such as appengine application , can i do that ?? if yes which lib i have to use ?? A: In Google Appengine you have google.appengine.api.images.crop which does that for you. If you are using ...
how to crop image in web based python application?
I'm searching for a way to crop image on a web based python application such as appengine application , can i do that ?? if yes which lib i have to use ??
[ "In Google Appengine you have google.appengine.api.images.crop which does that for you.\nIf you are using another service, you need to use PIL.Image.crop\n(The crop functions are a bit down on the pages, look them up with search)\n", "Google App Engine does not allow one to upload binary modules along with the Py...
[ 2, 2 ]
[]
[]
[ "google_app_engine", "image_processing", "python" ]
stackoverflow_0004580080_google_app_engine_image_processing_python.txt
Q: Google Data API on Symbian I want to use Google Data API on a Symbian device with pys60 but I couldn't find any doc. Is there any way to install Google Data APIs Python Client Library on Symbian ? A: According to the Google Data API protocol documentation, even the client libraries are basically just sending XML...
Google Data API on Symbian
I want to use Google Data API on a Symbian device with pys60 but I couldn't find any doc. Is there any way to install Google Data APIs Python Client Library on Symbian ?
[ "According to the Google Data API protocol documentation, even the client libraries are basically just sending XML data over HTTP, so it should be possible (in theory, at least) to send the same data from your own PyS60 application by grokking the code of the Python client. If memory serves me right, ElementTree is...
[ 1, 0 ]
[]
[]
[ "google_data_api", "pys60", "python", "symbian" ]
stackoverflow_0002815041_google_data_api_pys60_python_symbian.txt
Q: AppEngine Features and Tricks What are your favourite AppEngine features/tricks to make your development faster and easier? I don't expect one answer of course, but I would appreciate every AppEngine developer to have a share in this question. You can share anything including: Methods to make debugging easier. Me...
AppEngine Features and Tricks
What are your favourite AppEngine features/tricks to make your development faster and easier? I don't expect one answer of course, but I would appreciate every AppEngine developer to have a share in this question. You can share anything including: Methods to make debugging easier. Methods for avoiding AppEngine data s...
[ "Have a look to Google App Engine Tools and Tips here; it summarizes many useful tools and resources for working in App Engine\n", "I added appengine_admin which makes administrating entities easy.\n", "I would say the following things make my developement easier:\n\nUseing a freamewokr: Django or Tipfy \n\nIf ...
[ 1, 1, 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0004578481_google_app_engine_python.txt
Q: Customizing debug print format with PyDev Is it possible to see ints (and ints that are parts of dicts, lists, and tuples, etc.) as hex values when debugging with PyDev? More broadly, is it possible to make any given data type show up the way you want in the variable display tab? A: The PyDev Debugger simply u...
Customizing debug print format with PyDev
Is it possible to see ints (and ints that are parts of dicts, lists, and tuples, etc.) as hex values when debugging with PyDev? More broadly, is it possible to make any given data type show up the way you want in the variable display tab?
[ "The PyDev Debugger simply uses the repr() function to show the values. So if overwrite the __repr__() function than you can change how the values are printed.\nI don't think there are any other options of changing the way your variables show, although you might (not sure about that) be able to get away with overwr...
[ 2 ]
[]
[]
[ "eclipse", "pydev", "python" ]
stackoverflow_0004580174_eclipse_pydev_python.txt
Q: python library for splitting video I need to split big video file into smaller pieces by time. Give me your suggestions, please, and if you can some tips for library usage. Thanks. A: OpenCV has Python wrappers. As you're interested in video IO, have a look at QueryFrame and its related functions there. In the e...
python library for splitting video
I need to split big video file into smaller pieces by time. Give me your suggestions, please, and if you can some tips for library usage. Thanks.
[ "OpenCV has Python wrappers.\nAs you're interested in video IO, have a look at QueryFrame and its related functions there.\nIn the end, your code will look something like this (completely untested):\nimport cv\n\ncapture = cv.CaptureFromFile(filename)\nwhile Condition1:\n # Need a frame to get the output video d...
[ 7, 1 ]
[]
[]
[ "python", "video" ]
stackoverflow_0004580576_python_video.txt
Q: create missing directories in path Is there a clean way of taking a path like this: /foo/bar/faz/baz/ where foo and bar exist, but faz and baz don't, and create create faz and baz while leaving foo and bar alone? (Of course, this should work for something like exists/exists/exists/doesnt_exist/doesnt_exit/doesnt_...
create missing directories in path
Is there a clean way of taking a path like this: /foo/bar/faz/baz/ where foo and bar exist, but faz and baz don't, and create create faz and baz while leaving foo and bar alone? (Of course, this should work for something like exists/exists/exists/doesnt_exist/doesnt_exit/doesnt_exist/doesnt_exist or whatever (number o...
[ "os.makedirs does exactly that.\n" ]
[ 11 ]
[]
[]
[ "python" ]
stackoverflow_0004580641_python.txt
Q: Getting 401 on Twitter OAuth POST requests I am trying to use Twitter OAuth and my POST requests are failing with a 401 (Invalid OAuth Request) error. For example, if I want to post a new status update, I am sending a HTTP POST request to https://twitter.com/statuses/update.json with the following parameters - st...
Getting 401 on Twitter OAuth POST requests
I am trying to use Twitter OAuth and my POST requests are failing with a 401 (Invalid OAuth Request) error. For example, if I want to post a new status update, I am sending a HTTP POST request to https://twitter.com/statuses/update.json with the following parameters - status=Testing&oauth_version=1.0&oauth_token=xxx& ...
[ "I just finished implementing twitter OAuth API from scratch using Java. Get and post requests work OK. You can use this page http://www.hueniverse.com/hueniverse/2008/10/beginners-gui-1.html to check signature and HTTP headers. Just enter your keys and tokens and check output. It seems twitter works exactly as des...
[ 4, 3, 3, 2, 0, -8 ]
[]
[]
[ "oauth", "python", "rest", "twitter", "web_services" ]
stackoverflow_0000688766_oauth_python_rest_twitter_web_services.txt
Q: One-to-One relation classes I want to have a class named ProjectDirectory and a class named MetaDirectory. Each project has a MetaDirectory which contains some meta data. Is it the good way to write the classes like this: class ProjectDirectory(object): def __init__(self, directory=None): self.director...
One-to-One relation classes
I want to have a class named ProjectDirectory and a class named MetaDirectory. Each project has a MetaDirectory which contains some meta data. Is it the good way to write the classes like this: class ProjectDirectory(object): def __init__(self, directory=None): self.directory = directory self.meta_d...
[ "That's perfectly fine, but since there is now a one to one connection between the classes, you could actually merge them. If you have many types of Directories beside ProjectDirectory, you could inherit from MetaDirectory instead.\nBut if for some reason you don't want to, the design above is fine. There isn't any...
[ 2, 0, 0 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0004579262_oop_python.txt
Q: Why am I getting this error in my Mongo query? Exception Type: OperationFailure at / Exception Value: database error: point not in range My code is this: user_center = [ user_utm[1], user_utm[2] ] user_radius = tools.milesToMeters(request.session['browser_distance']) results = db.datasets.find({"test_set":"g2", ...
Why am I getting this error in my Mongo query?
Exception Type: OperationFailure at / Exception Value: database error: point not in range My code is this: user_center = [ user_utm[1], user_utm[2] ] user_radius = tools.milesToMeters(request.session['browser_distance']) results = db.datasets.find({"test_set":"g2", "loc_utm": {"$within": {"$center" : [ user_center, u...
[ "If you run Mongodb Version 1.4.0/1.5.0 you should upgrade to 1.5.2 where that kind of issue has been fixed.\n" ]
[ 6 ]
[]
[]
[ "database", "mongodb", "python" ]
stackoverflow_0004572563_database_mongodb_python.txt
Q: Shuffling an array in c++ Possible Duplicate: How exactly should I implement a shuffle or random-number algorithm for an array to display quotes in random order? I have a small array that I need the values to be randomly shuffled around within the array. I can do this in python using random.shuffle(), but I can ...
Shuffling an array in c++
Possible Duplicate: How exactly should I implement a shuffle or random-number algorithm for an array to display quotes in random order? I have a small array that I need the values to be randomly shuffled around within the array. I can do this in python using random.shuffle(), but I can seem to figure out how to do i...
[ "You can use std::random_shuffle from <algorithm>.\nHere's a basic example from the page:\n#include <algorithm> \n#include <vector> ...
[ 15 ]
[]
[]
[ "c++", "python" ]
stackoverflow_0004581584_c++_python.txt
Q: How do I register global system keyboard hotkeys on Mac OS X in wxPython/Python 2.7? I'm writing a GUI-based app in Python 2.7 using wxPython 2.8. I'm trying to run everything on a Mac, and unfortunately it seems that wxPython's wx.Window.RegisterHotKey() method only works on Windows. I would like to be able to ...
How do I register global system keyboard hotkeys on Mac OS X in wxPython/Python 2.7?
I'm writing a GUI-based app in Python 2.7 using wxPython 2.8. I'm trying to run everything on a Mac, and unfortunately it seems that wxPython's wx.Window.RegisterHotKey() method only works on Windows. I would like to be able to set a global hotkey or key combination while the application is running, and have that key...
[ "When the app has focus, you should be able to use wxPython's AcceleratorTable:\nhttp://www.blog.pythonlibrary.org/2008/07/02/wxpython-working-with-menus-toolbars-and-accelerators/\nhttp://www.blog.pythonlibrary.org/2010/12/02/wxpython-keyboard-shortcuts-accelerators/\nI don't have a Mac, so for you'll have to try ...
[ 0, 0 ]
[]
[]
[ "macos", "python", "wxpython", "wxwidgets" ]
stackoverflow_0004530028_macos_python_wxpython_wxwidgets.txt
Q: Get parts of html code as a new string in python I was wondering how I could get a value, between some html tags, from some html code using python. Say I wanted to get the price of a product in an amazon page: I've got up to: url = raw_input("Enter the url:\n") sock = urllib.urlopen(url) htmlsource = sock.read() s...
Get parts of html code as a new string in python
I was wondering how I could get a value, between some html tags, from some html code using python. Say I wanted to get the price of a product in an amazon page: I've got up to: url = raw_input("Enter the url:\n") sock = urllib.urlopen(url) htmlsource = sock.read() sock.close() so now I got the html source as a string ...
[ "You need to use a HTML Parsing Library. It provides better features than using standard regexs, where you can go wrong easily and it is hard to maintain. Python Standard Library comes with html.parse in py3k and HTMLParser in python2.x series which would help you parse the HTML file and get the values of the tags....
[ 4, 2, 0 ]
[]
[]
[ "html", "python", "regex", "search", "variables" ]
stackoverflow_0004581620_html_python_regex_search_variables.txt
Q: Is there a way to get the largest integer one can use in Python? Is there some pre-defined constant like INT_MAX? A: Python has arbitrary precision integers so there is no true fixed maximum. You're only limited by available memory. In Python 2, there are two types, int and long. ints use a C type, while longs...
Is there a way to get the largest integer one can use in Python?
Is there some pre-defined constant like INT_MAX?
[ "Python has arbitrary precision integers so there is no true fixed maximum. You're only limited by available memory.\nIn Python 2, there are two types, int and long. ints use a C type, while longs are arbitrary precision. You can use sys.maxint to find the maximum int. But ints are automatically promoted to lon...
[ 134 ]
[]
[]
[ "integer", "python" ]
stackoverflow_0004581842_integer_python.txt
Q: Why is there a difference between calcsize("!BHB") and calcsize("BHB")? Using the struct module in python 2.4.3 why is there a difference between calcsize("!BHB") and calcsize("BHB")? whereby; when from struct import * calcsize("!BHB") == 4 calcsize("BHB") == 5 I understand the big endian and little endian concep...
Why is there a difference between calcsize("!BHB") and calcsize("BHB")?
Using the struct module in python 2.4.3 why is there a difference between calcsize("!BHB") and calcsize("BHB")? whereby; when from struct import * calcsize("!BHB") == 4 calcsize("BHB") == 5 I understand the big endian and little endian concept, but don't really get it in terms of bytes placement for the above formats....
[ "The reason for that is explained in the Python Docs and it is due to padding issue when you are using a mixed structure members (BHB)\n\nPadding is only automatically added between successive structure members. \nNo padding is added at the beginning or the end of the encoded struct.\nNo padding is added when using...
[ 5 ]
[]
[]
[ "python", "struct" ]
stackoverflow_0004582003_python_struct.txt
Q: Django - subclassing UserAdmin to create dynamic templates? I'm not quite sure how to phrase the question that I want to ask. Let's say that you have two profile objects that could possibly be associated with a User. Only one of them will be associate (there's a one to one mapping) but it could be one of two pos...
Django - subclassing UserAdmin to create dynamic templates?
I'm not quite sure how to phrase the question that I want to ask. Let's say that you have two profile objects that could possibly be associated with a User. Only one of them will be associate (there's a one to one mapping) but it could be one of two possible profile objects. My admin code looks like this: admin.site...
[ "This is one way to do it. Keep in mind, this is a hack. I based this code off of the ModelAdmin code in django.contrib.admin.options.\nadmin.site.unregister(User)\n\nclass AProfileInline(admin.StackedInline):\n model = UserProfileA\n\nclass BProfileInline(admin.StackedInline):\n model = UserProfileB\n\ncla...
[ 0 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0004581723_django_django_admin_python.txt
Q: Python Game Programming Where can i find a decent resource to learn game programming in python? A: PyGame. It's also a framework designed specifically for creating games in Python. Invent Your Own Computer Games with Python is a great online book on the subject. A: The pygame wiki has a page with tutorials: h...
Python Game Programming
Where can i find a decent resource to learn game programming in python?
[ "PyGame. It's also a framework designed specifically for creating games in Python.\nInvent Your Own Computer Games with Python is a great online book on the subject. \n", "\nThe pygame wiki has a page with tutorials:\nhttp://www.pygame.org/wiki/tutorials\n\nI've made a game after sorta paging through tutorials an...
[ 4, 1 ]
[]
[]
[ "opengl", "python" ]
stackoverflow_0004582168_opengl_python.txt
Q: Is there a better way to feed different parameters into a function with if-statements? I've been teaching myself Python for a little while now, and I've never programmed before. I just wrote a basic backup program that writes out the progress of each individual file while it is copying. I wrote a function that det...
Is there a better way to feed different parameters into a function with if-statements?
I've been teaching myself Python for a little while now, and I've never programmed before. I just wrote a basic backup program that writes out the progress of each individual file while it is copying. I wrote a function that determines buffer size so that smaller files are copied with a smaller buffer, and bigger files...
[ "I believe that you are on the right track. One solution to your problem is saving the parameters in variables.\ndef smartcopy(filestocopy, dest_path, show_progress = False):\n \"\"\"Determines what buffer size to use with copy()\n Setting show_progress to True calls back display_progress()\"\"\"\n #fil...
[ 2, 1, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004581945_python.txt
Q: Unexpected end of archive Hey there, I'm pretty new to programming and I've got a problem with the Python Challenge; and I've removed the exact url in hopes avoiding any heavy spoilers. Anyway, my problem is that I'm trying to open the file I've created, in WinRAR after I've ran the following code, and it tells me...
Unexpected end of archive
Hey there, I'm pretty new to programming and I've got a problem with the Python Challenge; and I've removed the exact url in hopes avoiding any heavy spoilers. Anyway, my problem is that I'm trying to open the file I've created, in WinRAR after I've ran the following code, and it tells me the file has an "unexpected of...
[ "I'm guessing you're on a Windows machine. (Mostly due to \"WinRAR\")\nnewfile = open(url.split('/')[-1],'w')\n\nThe 'w' opens the file for writing, but in \"text\" mode. In text mode, some OSs (like Windows) convert '\\n' to something else ('\\r\\n' in Window's case.). To avoid this translation, open the file in b...
[ 3 ]
[]
[]
[ "python", "urllib", "zip" ]
stackoverflow_0004582470_python_urllib_zip.txt
Q: Simplejson dump and load not returning valid dictionary I'm trying to store a json result in the GAE datastore, so that I can read it later. I'm dumping it to a String, then storing it, then reading it and loading it back into a dict. But I can no longer read it as a dict after loading. result = freebase.mqlread...
Simplejson dump and load not returning valid dictionary
I'm trying to store a json result in the GAE datastore, so that I can read it later. I'm dumping it to a String, then storing it, then reading it and loading it back into a dict. But I can no longer read it as a dict after loading. result = freebase.mqlready(query) Print result: [{u'mid': u'/m/095hd', u'name': u'S...
[ "Uh, looks like you're accessing the collection rather than the inner object:\nSurely you meant: \nfor j in json:\n name = j['name']\n\n", "Ordinary dictionary doesn't transform attribute access into item lookup:\n>>> d = {'name': 'Joe'}\n>>> d.name\nTraceback (most recent call last):\n File \"<input>\", line...
[ 9, 2, 1 ]
[]
[]
[ "google_app_engine", "json", "python", "simplejson" ]
stackoverflow_0004582636_google_app_engine_json_python_simplejson.txt
Q: Is there a Django template filter that turns a datetime into "5 hours ago" or "12 days ago"? Let's say I have a datetime. I do this: Submitted on {{ post.date|date:"D. M d, P" }} This actually prints the date. However, what if I want it to say, "4 hours ago" or "55 days ago" or "2 months ago"? A: Try the temp...
Is there a Django template filter that turns a datetime into "5 hours ago" or "12 days ago"?
Let's say I have a datetime. I do this: Submitted on {{ post.date|date:"D. M d, P" }} This actually prints the date. However, what if I want it to say, "4 hours ago" or "55 days ago" or "2 months ago"?
[ "Try the template filter timesince.\nUse it like this:\n{{ mytemplatevar|timesince }}\n\n", "UPDATED:\nWe can assume that you have a post_date attribute saved in your model capturing the time you save the post. present.time is the current time that is loaded freshly onto the template when one visits the post. Thi...
[ 18, 4, 1 ]
[]
[]
[ "css", "django", "filter", "python", "templates" ]
stackoverflow_0004582507_css_django_filter_python_templates.txt
Q: file walking in python So, I've got a working solution, but it's ugly and seems un-idiomatic. The problem is this: For a directory tree, where every directory is set up to have: 1 .xc file at least 1 .x file any number of directories which follow the same format and nothing else. I'd like to, given the root path...
file walking in python
So, I've got a working solution, but it's ugly and seems un-idiomatic. The problem is this: For a directory tree, where every directory is set up to have: 1 .xc file at least 1 .x file any number of directories which follow the same format and nothing else. I'd like to, given the root path and walk the tree applying ...
[ "The function os.walk recursively walks through a directory tree, returning all file and subdirectory names.\nSo all you have to do is detect the .x and .xc extensions from the filenames and apply your functions when they do (untested code follows):\nimport os\n\nfor dirpath, dnames, fnames in os.walk(\"./\"):\n ...
[ 32, 6, 1 ]
[ "You could use a dict to hold an extension -> function mapping:\nfuncMap = {\".xc\" : xc,\n \".x\" : x}\n\nThen you create a recursive function that takes a single directory, gets the list of files n that directory, and determines the extension of each file:\ndef iterateDir(s):\n\n l = dir.list(s) # N...
[ -2 ]
[ "python" ]
stackoverflow_0004582550_python.txt
Q: Creating Plots in Excel from a Python script Is it possible to write a Python script that will create and save a chart in Excel? A: This is what I read here http://python-excel.googlegroups.com/web/python-excel.pdf?gda=xZW5Y0IAAAAK26IHZlH6sZ8eLgsep540qvBo1o93MWeCIftQ3v-jMNXEtWX7y7b6ByPnawQ3OxpV4u3aa4iAIyYQIqbG...
Creating Plots in Excel from a Python script
Is it possible to write a Python script that will create and save a chart in Excel?
[ "This is what I read here \nhttp://python-excel.googlegroups.com/web/python-excel.pdf?gda=xZW5Y0IAAAAK26IHZlH6sZ8eLgsep540qvBo1o93MWeCIftQ3v-jMNXEtWX7y7b6ByPnawQ3OxpV4u3aa4iAIyYQIqbG9naPgh6o8ccLBvP6Chud5KMzIQ\nThere are still reasons why automating an Excel instance via COM is necessary:\n• manipulation of graphs \...
[ 2 ]
[]
[]
[ "charts", "excel", "python" ]
stackoverflow_0004583036_charts_excel_python.txt
Q: Django: Changing the url of an optional ImageField Via signals I check if my model belongs to a category. If it is, I want to change my optional ImageField to a specific url. How can this be achieved? Code below doesnt work, I get "cannot set attribute" error as it is an optional field and it was blank as I saved ...
Django: Changing the url of an optional ImageField
Via signals I check if my model belongs to a category. If it is, I want to change my optional ImageField to a specific url. How can this be achieved? Code below doesnt work, I get "cannot set attribute" error as it is an optional field and it was blank as I saved it. Here is my sample model class Foo(models.Model): ...
[ "You don't say what problem you're having (does that code work?), so there are two problems in your code. Firstly, you probably don't want to be saving in a post-save signal (infinite loop, anyone?). Secondly, you've got an indentation issue (you need to indent after the if).\nThe way you probably want to do this i...
[ 1 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0004583090_django_django_models_python.txt
Q: Structured programming and Python generators? Update: What I really wanted all along were greenlets. Note: This question mutated a bit as people answered and forced me to "raise the stakes", as my trivial examples had trivial simplifications; rather than continue to mutate it here, I will repose the question when...
Structured programming and Python generators?
Update: What I really wanted all along were greenlets. Note: This question mutated a bit as people answered and forced me to "raise the stakes", as my trivial examples had trivial simplifications; rather than continue to mutate it here, I will repose the question when I have it clearer in my head, as per Alex's sugges...
[ "\nHowever, I'd like to make my\n reusability criteria one notch harder:\n what if I need a control structure\n around my repeated generation?\n\nitertools often helps even there - you need to provide concrete examples where you think it doesn't.\n\nFor\n instance, I might want to call a\n subgenerator forever...
[ 11, 6, 6, 3, 3, 2, 1, 0 ]
[]
[]
[ "generator", "python" ]
stackoverflow_0001745333_generator_python.txt
Q: PyGTK: Trouble with size of ScrolledWindow I am using PyGTK and the gtk.Assistant. On one page I have placed a treeview (one column, just strings) in a gtk.ScrolledWindow (I wanted the vertical scrollbar, since the list contains about 35 items). Everything is working fine; the only thing that bugs me is that I hav...
PyGTK: Trouble with size of ScrolledWindow
I am using PyGTK and the gtk.Assistant. On one page I have placed a treeview (one column, just strings) in a gtk.ScrolledWindow (I wanted the vertical scrollbar, since the list contains about 35 items). Everything is working fine; the only thing that bugs me is that I have not been able to figure out from the documenta...
[ "I've been very, very stupid, it was merely a packing issue >_<\nThis line\nself.page7.pack_start(scrolled_win, False, False, 0)\n\nshould read\nself.page7.pack_start(scrolled_win, True, True, 0)\n\ninstead!\nNow everything's looking the way I want it to look.\n" ]
[ 2 ]
[]
[]
[ "gtkscrolledwindow", "gtktreeview", "pygtk", "python" ]
stackoverflow_0004579401_gtkscrolledwindow_gtktreeview_pygtk_python.txt
Q: Is it possible to pickle python "units" units? I'm using the Python "units" package (http://pypi.python.org/pypi/units/) and I've run into some trouble when trying to pickle them. I've tried to boil it down to the simplest possible to case to try and figure out what's going on. Here's my simple test: from units im...
Is it possible to pickle python "units" units?
I'm using the Python "units" package (http://pypi.python.org/pypi/units/) and I've run into some trouble when trying to pickle them. I've tried to boil it down to the simplest possible to case to try and figure out what's going on. Here's my simple test: from units import unit, named_unit from units.predefined import d...
[ "It seems that the problem is not that Unit instances are not pickable since your case shows otherwise but rather than the de-serialized instance does not compare equal to the original instance hence they're treated as incompatible units even though they're equivlent.\nI have never used unit before but after skimmi...
[ 2, 0 ]
[]
[]
[ "google_app_engine", "pickle", "python", "units_of_measurement" ]
stackoverflow_0004582557_google_app_engine_pickle_python_units_of_measurement.txt
Q: How can I change processname of my python script on OpenBSD4.8 I tried py-setproctitle and setproctitle. Both of them didn't work on OpenBSD. A: The problem is here In setup.py it tests if setproctitle is defined in unistd.h, although it is defined in stdlib.h on OpenBSD. By checking in stdlib.h too (which is i...
How can I change processname of my python script on OpenBSD4.8
I tried py-setproctitle and setproctitle. Both of them didn't work on OpenBSD.
[ "The problem is here\nIn setup.py it tests if setproctitle is defined in unistd.h, although it is defined in stdlib.h on OpenBSD.\nBy checking in stdlib.h too (which is included later on - So no worries), everything works as expected.\nDiff below:\n--- setup.py~ Mon Jan 3 12:05:39 2011\n+++ setup.py Mon Jan ...
[ 4 ]
[]
[]
[ "openbsd", "python", "python_2.5" ]
stackoverflow_0004584102_openbsd_python_python_2.5.txt
Q: python thread error obj = functioning() from threading import Thread Thread(target=obj.runCron(cronDetails)).start() print "new thread started..." I am runnning this, this should run as new thread for runCron function and should print new thread started. but this is not printing new thread started and not creati...
python thread error
obj = functioning() from threading import Thread Thread(target=obj.runCron(cronDetails)).start() print "new thread started..." I am runnning this, this should run as new thread for runCron function and should print new thread started. but this is not printing new thread started and not creating new thread
[ "You question is missing some details, e.g. what error message you are getting, etc. – below is a working example mimicked after your code.\n#!/usr/bin/env python\n\nimport time\n\nclass Obj(object):\n def runCron(self, cronDetails):\n time.sleep(1)\n print cronDetails\n\nobj = Obj()\ncronDetails =...
[ 2, 1 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0004584530_multithreading_python.txt
Q: replacement functionality for imp.load_module() in Google App Engine? The imp module in Google App Engine is empty. Therefore, is there another way to do what the imp.load_module() function does -- namely, to return a module object from a file object? (or even more generally -- even a way to generate a module obj...
replacement functionality for imp.load_module() in Google App Engine?
The imp module in Google App Engine is empty. Therefore, is there another way to do what the imp.load_module() function does -- namely, to return a module object from a file object? (or even more generally -- even a way to generate a module object from any random piece of code (sent to exec() or something)?)
[ "Well, you can try:\n>>> import types\n>>> foo = types.ModuleType('foo')\n\nBut it will obviously be empty, and you'll have to \"fill\" it some other way, including \n>>> exec('bar=2', foo.__dict__)\n>>> foo.bar\n2\n\nThe big question is why you would want that. Executing a \"random piece of code\" is generally a v...
[ 1, 0 ]
[]
[]
[ "google_app_engine", "import", "python" ]
stackoverflow_0004583120_google_app_engine_import_python.txt