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: Assigning IDs to instances of a class (Pythonic) I want to have each instance of some class have a unique integer identifier based on the order that I create them, starting with (say) 0. In Java, I could do this with a static class variable. I know I can emulate the same sort of behavior with Python, but what woul...
Assigning IDs to instances of a class (Pythonic)
I want to have each instance of some class have a unique integer identifier based on the order that I create them, starting with (say) 0. In Java, I could do this with a static class variable. I know I can emulate the same sort of behavior with Python, but what would be the most 'Pythonic' way to do this? Thanks
[ "The following approach would be relatively pythonic (for my subjective judgement of pythonic - explicit, yet concise):\nclass CounterExample(object):\n\n instances_created = 0\n\n def __init__(self):\n CounterExample.instances_created += 1\n\n def __del__(self):\n \"\"\" If you want to trac...
[ 3, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002989870_python.txt
Q: Help with copy and deepcopy in Python I think I tried to ask for far too much in my previous question so apologies for that. Let me lay out my situation in as simple a manner as I can this time. Basically, I've got a bunch of dictionaries that reference my objects, which are in turn mapped using SQLAlchemy. All fi...
Help with copy and deepcopy in Python
I think I tried to ask for far too much in my previous question so apologies for that. Let me lay out my situation in as simple a manner as I can this time. Basically, I've got a bunch of dictionaries that reference my objects, which are in turn mapped using SQLAlchemy. All fine with me. However, I want to make iterati...
[ "Here is another option, but I'm not sure it's applicable to your problem:\n\nRetrieve objects from database along with all needed relations. You can either pass lazy='joined' or lazy='subquery' to relations, or call options(eagerload(relation_property) method of query, or just access required properties to trigger...
[ 2, 1 ]
[]
[]
[ "copy", "python", "sqlalchemy" ]
stackoverflow_0002983275_copy_python_sqlalchemy.txt
Q: cPickle class with data save to file I've big class in Python it's "DataBase-like" class. I want to save it to file - all including data. This is input(example to show the issue, in script database is like 10000 records): import cPickle # DataBase-like class class DataBase: class Arrays: pass class Zones: ...
cPickle class with data save to file
I've big class in Python it's "DataBase-like" class. I want to save it to file - all including data. This is input(example to show the issue, in script database is like 10000 records): import cPickle # DataBase-like class class DataBase: class Arrays: pass class Zones: pass class Nodes: class CR: p...
[ "You are pickling \"DataBase\" which is a class definition. You need to instantiate an object of class DataBase then pickle that.\nobjDataBase = DataBase()\nobjDataBase.Arrays.Data = etc....\n\nfilename='D:/results/file.lft'\nfile=open(filename,'w')\ncPickle.dump(objDataBase, file, protocol=2)\nfile.close()\n\n" ]
[ 4 ]
[]
[]
[ "object_persistence", "pickle", "python", "serialization" ]
stackoverflow_0002991557_object_persistence_pickle_python_serialization.txt
Q: What are alternatives to Asterisq's Constellation Framework for actionscript? i would like to present data in something like Constellation Framework... but without flash what other options are out there? python, html5, javascript would be great, but i have no preference other than no flash (i don't own CS) EDIT: i...
What are alternatives to Asterisq's Constellation Framework for actionscript?
i would like to present data in something like Constellation Framework... but without flash what other options are out there? python, html5, javascript would be great, but i have no preference other than no flash (i don't own CS) EDIT: i have found a handful of html5 examples without much source code and infoVis.
[ "I know of two good options which will work in Javascript:\n\nProtovis\nThe JavaScript InfoVis Toolkit\n\nIn Java, I would recommend Prefuse. I don't know off hand of Python Network libraries, but I'm sure there are some.\n" ]
[ 0 ]
[]
[]
[ "actionscript", "flash", "html", "python", "visualization" ]
stackoverflow_0002981723_actionscript_flash_html_python_visualization.txt
Q: Is there an alternative to Pidgin, but with less restrictive licensing? Recently came across pidgin. Its great, and does what I want, but I am not too keen on the GPL license. Other any alternatives, with less restrictive licenses? I would prefer the library to be C or C++, as I am most familiar with those languag...
Is there an alternative to Pidgin, but with less restrictive licensing?
Recently came across pidgin. Its great, and does what I want, but I am not too keen on the GPL license. Other any alternatives, with less restrictive licenses? I would prefer the library to be C or C++, as I am most familiar with those languages, but a an IM library implemented in python would be interesting too.
[ "Take a look at kde's kopete. The chat client itself is still GPL but it's underlying library libkopete is LGPL. So you could link with it pretty freely.\n", "Twisted Words\n" ]
[ 4, 1 ]
[]
[]
[ "c", "c++", "pidgin", "python" ]
stackoverflow_0002991867_c_c++_pidgin_python.txt
Q: how to implement a really efficient bitvector sorting in python Actually this is an interesting topic from programming pearls, sorting 10 digits telephone numbers in a limited memory with an efficient algorithm. You can find the whole story here What I am interested in is just how fast the implementation could be ...
how to implement a really efficient bitvector sorting in python
Actually this is an interesting topic from programming pearls, sorting 10 digits telephone numbers in a limited memory with an efficient algorithm. You can find the whole story here What I am interested in is just how fast the implementation could be in python. I have done a naive implementation with the module bitvect...
[ "As Niki pointed out, you are comparing a very fast C routine with a Python one. Using psyco speeds it up a little bit for me, but you can really speed it up by using a bit vector module written in C. I used bitarray and then the bit sorting method surpasses the built-in sort for an array size of about 250,000 usin...
[ 3, 1 ]
[]
[]
[ "algorithm", "bitvector", "python", "sorting" ]
stackoverflow_0002991663_algorithm_bitvector_python_sorting.txt
Q: Can't get custom slot working in PyQT4 with QT4 designer I am new to PyQT4. After some tuts I decided to make a simple GUI in which I will enter text in first line and on clicking of Reverse button ,it will show reversed string on second line. I made a custom slot for this,by defining the function in my class.But ...
Can't get custom slot working in PyQT4 with QT4 designer
I am new to PyQT4. After some tuts I decided to make a simple GUI in which I will enter text in first line and on clicking of Reverse button ,it will show reversed string on second line. I made a custom slot for this,by defining the function in my class.But when I click reverse nothing happens. I have used in-bilt slot...
[ "Try using QtCore.SIGNAL(\"clicked()\") instead of QtCore.SIGNAL(\"Click()\").\n" ]
[ 0 ]
[]
[]
[ "pyqt4", "python", "qt4" ]
stackoverflow_0002991945_pyqt4_python_qt4.txt
Q: How Similar are Java, C#, and Python? I know it is a kind of broad question but any answer are appreciated. A: All: Require some form of runtime on your system (JVM/.net/Python runtime) All can probably be compiled to executables without the runtime (this is iffy and situational, none of them are designed to wo...
How Similar are Java, C#, and Python?
I know it is a kind of broad question but any answer are appreciated.
[ "All:\n\nRequire some form of runtime on your system (JVM/.net/Python runtime)\nAll can probably be compiled to executables without the runtime (this is iffy and situational, none of them are designed to work this way)\nAre good languages\nAll have specific areas where they are much more appropriate than the other ...
[ 15, 11, 7, 2, 1, 1, 1, 1 ]
[ "Python was made to be simpler, more readable, flexible and object oriented than what existed before - i.e. Java, Perl etc. It's actually closer to Java than it is to Ruby. Ruby is more like Smalltalk. Think of Python as Java without the stuff that mostly gets in your way, makes things awkward to do, slows you d...
[ -1, -2 ]
[ "c#", "java", "python" ]
stackoverflow_0002991554_c#_java_python.txt
Q: networking application and GUI in python I'm writing an application that sends files over network, I want to develop a custom protocol to not limit myself in term on feature richness (http wouldn't be appropriate, the nearest thing is the bittorrent protocol maybe). I've tried with twisted, I've built a good app ...
networking application and GUI in python
I'm writing an application that sends files over network, I want to develop a custom protocol to not limit myself in term on feature richness (http wouldn't be appropriate, the nearest thing is the bittorrent protocol maybe). I've tried with twisted, I've built a good app but there's a bug in twisted that makes my GUI...
[ "Two threads: one for the GUI, one for sending/receiving data. Tkinter would be a perfectly fine toolkit for this. You don't need twisted or any other external libraries or toolkits -- what comes out of the box is sufficient to get the job done. \n", "Disclaimer: I have little experience with network application...
[ 1, 1, 1, 1 ]
[]
[]
[ "networking", "python" ]
stackoverflow_0002991852_networking_python.txt
Q: Ubuntu quickly (python/gtk) - how to monitor stdin? I'm starting to work with Ubuntu's "quickly" framework, which is python/gtk based. I want to write a gui wrapper for a textmode C state-machine that uses stdin/stdout. I'm new to gtk. I can see that the python print command will write to the terminal window, so ...
Ubuntu quickly (python/gtk) - how to monitor stdin?
I'm starting to work with Ubuntu's "quickly" framework, which is python/gtk based. I want to write a gui wrapper for a textmode C state-machine that uses stdin/stdout. I'm new to gtk. I can see that the python print command will write to the terminal window, so I assume I could redirect that to my C program's stdin. B...
[ "The gtk version of select, is glib.io_add_watch, you may want to redirect the stdin/stdout of the process to/from the GUI, you can check an article I've written time ago:\nhttp://pygabriel.wordpress.com/2009/07/27/redirecting-the-stdout-on-a-gtk-textview/\n", "I'm not sure about the quickly framework, but in Pyt...
[ 4, 2 ]
[]
[]
[ "canonical_quickly", "gtk", "pygtk", "python" ]
stackoverflow_0002992458_canonical_quickly_gtk_pygtk_python.txt
Q: Python-based password tracker (or dictionary) Where we work we need to remember about 10 long passwords which need to change every so often. I would like to create a utility which can potentially save these passwords in an encrypted file so that we can keep track of them. I can think of some sort of dictionary pas...
Python-based password tracker (or dictionary)
Where we work we need to remember about 10 long passwords which need to change every so often. I would like to create a utility which can potentially save these passwords in an encrypted file so that we can keep track of them. I can think of some sort of dictionary passwd = {'host1':'pass1', 'host2':'pass2'}, etc, but ...
[ "Answers to your questions:\n\nYes. Take a look at KeePass.\nI wouldn't program a utility like this in Python, because there are available open source tools already. Furthermore, I would have concerns about protecting the unencrypted passwords as they were processed by a Python program.\n\nHope that helps.\n", ...
[ 4, 3, 0, 0 ]
[]
[]
[ "encryption", "passwords", "python" ]
stackoverflow_0002992057_encryption_passwords_python.txt
Q: computing z-scores for 2D matrices in scipy/numpy in Python How can I compute the z-score for matrices in Python? Suppose I have the array: a = array([[ 1, 2, 3], [ 30, 35, 36], [2000, 6000, 8000]]) and I want to compute the z-score for each row. The solution I came up with is:...
computing z-scores for 2D matrices in scipy/numpy in Python
How can I compute the z-score for matrices in Python? Suppose I have the array: a = array([[ 1, 2, 3], [ 30, 35, 36], [2000, 6000, 8000]]) and I want to compute the z-score for each row. The solution I came up with is: array([zs(item) for item in a]) where zs is in scipy.stats.stat...
[ "scipy.stats.stats.zs is defined like this:\ndef zs(a):\n mu = mean(a,None)\n sigma = samplestd(a)\n return (array(a)-mu)/sigma\n\nSo to extend it to work on a given axis of an ndarray, you could do this:\nimport numpy as np\nimport scipy.stats.stats as sss\ndef my_zs(a,axis=-1):\n b=np.array(a).swapaxe...
[ 3, 2 ]
[]
[]
[ "cluster_analysis", "machine_learning", "numpy", "python", "scipy" ]
stackoverflow_0002985135_cluster_analysis_machine_learning_numpy_python_scipy.txt
Q: in pylongs, is there a way to loop through all the controllers and actions? in pylons, is it possible to loop through all the controllers and their actions? I want to create a javascript object that has all the controllers and their actions A: I'm writing this under the assumption that you're trying to do a "tab...
in pylongs, is there a way to loop through all the controllers and actions?
in pylons, is it possible to loop through all the controllers and their actions? I want to create a javascript object that has all the controllers and their actions
[ "I'm writing this under the assumption that you're trying to do a \"table of contents\" thing. If this is not the case and the below information is not helpful, my apologies.\n\nIf you know the controllers you want the actions for before-hand (that is to say, before runtime), you could write\ndef contents(self):\n ...
[ 1 ]
[]
[]
[ "pylons", "python" ]
stackoverflow_0002981110_pylons_python.txt
Q: How to ignore GUI as much as possible without rendering APP less GUI developer friendly The substance of an app is more important to me than its apperance, yet GUI always seems to dominate a disproportionate percentage of programmer time, development and target resource requirements/constraints. Ideally I'd like ...
How to ignore GUI as much as possible without rendering APP less GUI developer friendly
The substance of an app is more important to me than its apperance, yet GUI always seems to dominate a disproportionate percentage of programmer time, development and target resource requirements/constraints. Ideally I'd like an application architecture that will permit me to develop an app using a lightweight referen...
[ "Write a core library that handles the functionality and provides hooks for progress notification. Then write the interfaces as separate applications or libraries that use the core library.\n", "The answer you seek is MVC - Model/View/Controller. \n" ]
[ 3, 1 ]
[]
[]
[ "portability", "python", "user_interface" ]
stackoverflow_0002991910_portability_python_user_interface.txt
Q: HttpError 502 with Google Wave Active Robot API fetch_wavelet() I am trying to use the Google Wave Active Robot API fetch_wavelet() and I get an HTTP 502 error example: from waveapi import robot import passwords robot = robot.Robot('gae-run', 'http://images.com/fake-image.jpg') robot.setup_oauth(p...
HttpError 502 with Google Wave Active Robot API fetch_wavelet()
I am trying to use the Google Wave Active Robot API fetch_wavelet() and I get an HTTP 502 error example: from waveapi import robot import passwords robot = robot.Robot('gae-run', 'http://images.com/fake-image.jpg') robot.setup_oauth(passwords.CONSUMER_KEY, passwords.CONSUMER_SECRET, server_rpc_base='ht...
[ "Joe Gregorio answered my question on the Google Wave API Google group\n\nDid you make any changes to the\n wavelet before submitting it? I think\n there was an old bug where sending in\n an empty change would cause a 502,\n this might be a regression in that\n behavior.\n\nIf I removed the robot.submit(wav...
[ 0 ]
[]
[]
[ "google_app_engine", "google_wave", "python" ]
stackoverflow_0002982956_google_app_engine_google_wave_python.txt
Q: Python - how to check if weak reference is still available I am passing some weakrefs from Python into C++ class, but C++ destructors are actively trying to access the ref when the real object is already dead, obviously it crashes... Is there any Python C/API approach to find out if Python reference is still alive...
Python - how to check if weak reference is still available
I am passing some weakrefs from Python into C++ class, but C++ destructors are actively trying to access the ref when the real object is already dead, obviously it crashes... Is there any Python C/API approach to find out if Python reference is still alive or any other known workaround for this ? Thanks
[ "From Python C API documentation:\n\nPyObject* PyWeakref_GetObject(PyObject *ref)\n Return value: Borrowed reference.\n Return the referenced object from a weak reference, ref. If the referent\n is no longer live, returns None. New in version 2.2. \n\n", "If you call PyWeakref_GetObject on the wea...
[ 4, 3 ]
[]
[]
[ "c++", "python", "reference", "weak" ]
stackoverflow_0002993393_c++_python_reference_weak.txt
Q: Python import error: Symbol not found, but the symbol is *is not* present in the file I get this error when I try to import ssrc.spread: ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/ssrc/_spread.so, 2): Symbol not found: __ZN17ssrcspread_v1_0_67Mailbox11ZeroTime...
Python import error: Symbol not found, but the symbol is *is not* present in the file
I get this error when I try to import ssrc.spread: ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/ssrc/_spread.so, 2): Symbol not found: __ZN17ssrcspread_v1_0_67Mailbox11ZeroTimeoutE The file in question (_spread.so) includes the symbol: $ nm _spread.so | grep _ZN17ssr...
[ "$ nm _spread.so | grep _ZN17ssrcspread_v1_0_67Mailbox11ZeroTimeoutE\n U __ZN17ssrcspread_v1_0_67Mailbox11ZeroTimeoutE\n U __ZN17ssrcspread_v1_0_67Mailbox11ZeroTimeoutE\n\nThe _spread.so file does not include the symbol, it is depending on it. The U means undefined.\nI feel like there may be a version misma...
[ 2 ]
[]
[]
[ "macos", "python" ]
stackoverflow_0002989233_macos_python.txt
Q: Django snippet with logic is there a way to create a Django snippet that has logic? I think about something like contact template tag: {% contact_form %} with template: <form action="send_contact_form" method="POST">...</form> with logic: def send_contact_form(): ... I want to be able to use it anywhere in ...
Django snippet with logic
is there a way to create a Django snippet that has logic? I think about something like contact template tag: {% contact_form %} with template: <form action="send_contact_form" method="POST">...</form> with logic: def send_contact_form(): ... I want to be able to use it anywhere in my projects. It should work onl...
[ "Custom template tags.\n" ]
[ 1 ]
[]
[]
[ "django", "django_forms", "django_templates", "python" ]
stackoverflow_0002993191_django_django_forms_django_templates_python.txt
Q: Fast method call scheduling in Python For some part of my project I need a process-local scheduling system that will allow me to delay method execution on few seconds. I have thousands of “clients” of this system, so using threading.Timer for each delay is a bad idea because I will quickly reach OS thread limit. I...
Fast method call scheduling in Python
For some part of my project I need a process-local scheduling system that will allow me to delay method execution on few seconds. I have thousands of “clients” of this system, so using threading.Timer for each delay is a bad idea because I will quickly reach OS thread limit. I've implemented a system that use only one ...
[ "An alternative implementation you could use is to use the time.time() method to calculate the absolute time each queued function should be executed. Place this time and your function-to-be-called in an object wrapper that overrides the comparison operator using the execution time to determine order. Then use the h...
[ 2, 2, 0 ]
[]
[]
[ "linux", "multithreading", "python", "scheduling", "timer" ]
stackoverflow_0002990088_linux_multithreading_python_scheduling_timer.txt
Q: how to set a pop up menu on a particular table view item i have a QTableView , and i need to show a popup menu that shows the item properties . i need to set the context menu to apear only when you right click over a particular items in that tableview. but coudln't find a way to do it . i can set the context menu ...
how to set a pop up menu on a particular table view item
i have a QTableView , and i need to show a popup menu that shows the item properties . i need to set the context menu to apear only when you right click over a particular items in that tableview. but coudln't find a way to do it . i can set the context menu to appear when your over the table . i cant have it for each ...
[ "Assuming you're in control of when the menu pops up, then you'll want to use the indexAt(QPoint) member function in order to determine what item the mouse is over.\nIf you're not currently in control of when the menu shows up, you'll need to set the view's contextMenuPolicy to something that will give you control ...
[ 2 ]
[]
[]
[ "pyqt", "pyqt4", "python", "qt", "qt4" ]
stackoverflow_0002993426_pyqt_pyqt4_python_qt_qt4.txt
Q: how to create a theme with QT im looking for a way to make my pyqt interface look nicer by adding a theme to it. im new to Qt and i still have no idea how to add a custom theme for widgets.. so how is that possible ? and is it possible through qt designer ? sorry for my bad english , its my third language. i h...
how to create a theme with QT
im looking for a way to make my pyqt interface look nicer by adding a theme to it. im new to Qt and i still have no idea how to add a custom theme for widgets.. so how is that possible ? and is it possible through qt designer ? sorry for my bad english , its my third language. i hope the idea is clear enough . plea...
[ "The most easily implemented method is via Qt's style sheets that are quite similar to CSS. Take a look at the style reference if you need anything more complicated. Qt Designer does give you access to the styleSheet property, although I'd recommend using a separate file for it if you're doing anything non-trivial....
[ 3 ]
[]
[]
[ "pyqt", "pyqt4", "python", "qt", "qt4" ]
stackoverflow_0002993375_pyqt_pyqt4_python_qt_qt4.txt
Q: Spawning and waiting for child processes in Python The relevant part of the code looks like this: pids = [] for size in SIZES: pids.append(os.spawnv(os.P_NOWAIT, RESIZECMD, [RESIZECMD, lotsOfOptions])) # Wait for all spawned imagemagick processes to finish while pids: (pid, status) = os.waitpid(0, 0) ...
Spawning and waiting for child processes in Python
The relevant part of the code looks like this: pids = [] for size in SIZES: pids.append(os.spawnv(os.P_NOWAIT, RESIZECMD, [RESIZECMD, lotsOfOptions])) # Wait for all spawned imagemagick processes to finish while pids: (pid, status) = os.waitpid(0, 0) if pid: pids.remove(pid) What this should be d...
[ "The recommended way to start subprocess is to use the subprocess module.\npipe = Popen([\"program\", \"arg1\", \"arg2\"])\npipe.wait()\n\n", "I would recommend you install python-subprocess32 -- a robust backport of Python 3's version of the subprocess standard library module, suitable for Python 2.4 to 2.7, and...
[ 5, 3 ]
[]
[]
[ "cygwin", "linux", "process", "python" ]
stackoverflow_0002993487_cygwin_linux_process_python.txt
Q: Searching for duplicate records within a text file where the duplicate is determined by only two fields First, Python Newbie; be patient/kind. Next, once a month I receive a large text file (think 7 Million records) to test for duplicate values. This is catalog information. I get 7 fields, but the two I'm intere...
Searching for duplicate records within a text file where the duplicate is determined by only two fields
First, Python Newbie; be patient/kind. Next, once a month I receive a large text file (think 7 Million records) to test for duplicate values. This is catalog information. I get 7 fields, but the two I'm interested in are a supplier code and a full orderable part number. To determine if the record is dupliacted, I co...
[ "Maybe you could consider building a dictionary mapping (supplier_number, compressed_part_number) tuples to data structures (nested lists perhaps, or instances of a custom class for improved readability & maintainability) holding information on line numbers for the lines the records matching the key tuple appear in...
[ 1, 0, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002991967_python.txt
Q: Display constantly updating information in-place in command-line window using python? I am essentially building a timer. I have a python script that monitors for an event and then prints out the seconds that have elapsed since that event. Instead of an ugly stream of numbers printed to the command line, I would l...
Display constantly updating information in-place in command-line window using python?
I am essentially building a timer. I have a python script that monitors for an event and then prints out the seconds that have elapsed since that event. Instead of an ugly stream of numbers printed to the command line, I would like to display only the current elapsed time "in-place"-- so that only one number is visibl...
[ "I use this: http://newcenturycomputers.net/projects/wconio.html\n", "Outputting \\b will move the output cursor left 1 cell, and outputting \\r will return it to column 0. Make sure to flush the output often though.\n" ]
[ 3, 3 ]
[]
[]
[ "command_line", "python" ]
stackoverflow_0002993805_command_line_python.txt
Q: wxPython TreeCtrl without showing root while still showing arrows I am making a python tree visualizer using wxPython. It would be used like so: show_tree([ 'A node with no children', ('A node with children', 'A child node', ('A child node with children', 'Another child')) ]) It worked fine but it shows a root wi...
wxPython TreeCtrl without showing root while still showing arrows
I am making a python tree visualizer using wxPython. It would be used like so: show_tree([ 'A node with no children', ('A node with children', 'A child node', ('A child node with children', 'Another child')) ]) It worked fine but it shows a root with a value of "Tree". I made it so that it would create multiple roots ...
[ "Note: When I posted this I did not realize you were able to apply multiple styles to trees.\nAfter trying everything, I realized that it was a combination of TR_HIDE_ROOT and TR_HAS_BUTTONS that does the trick of hiding the root while still showing arrows on the left side that allow you to collapse and hide nodes ...
[ 9, 1 ]
[]
[]
[ "python", "root_node", "tree", "treecontrol", "wxwidgets" ]
stackoverflow_0002925971_python_root_node_tree_treecontrol_wxwidgets.txt
Q: Python + PostgreSQL + strange ascii = UTF8 encoding error I have ascii strings which contain the character "\x80" to represent the euro symbol: >>> print "\x80" € When inserting string data containing this character into my database, I get: psycopg2.DataError: invalid byte sequence for encoding "UTF8": 0x80 HINT:...
Python + PostgreSQL + strange ascii = UTF8 encoding error
I have ascii strings which contain the character "\x80" to represent the euro symbol: >>> print "\x80" € When inserting string data containing this character into my database, I get: psycopg2.DataError: invalid byte sequence for encoding "UTF8": 0x80 HINT: This error can also happen if the byte sequence does not matc...
[ "The question starts with a false premise:\n\nI have ascii strings which contain the character \"\\x80\" to represent the euro symbol.\n\nASCII characters are in the range \"\\x00\" to \"\\x7F\" inclusive.\nThe previously-accepted now-deleted answer operated under two gross misapprehensions (1) that locale == encod...
[ 12 ]
[]
[]
[ "encoding", "postgresql", "python", "unicode", "utf_8" ]
stackoverflow_0002991660_encoding_postgresql_python_unicode_utf_8.txt
Q: Read -> change -> save. Thread safe This code should automatically connect players when they enter a game. But the problem is when two users try to connect at the same time - in this case 2nd user can easily overwrite changes made by 1st user ('room_1' variable). How could I make it thread safe? def join(userId):...
Read -> change -> save. Thread safe
This code should automatically connect players when they enter a game. But the problem is when two users try to connect at the same time - in this case 2nd user can easily overwrite changes made by 1st user ('room_1' variable). How could I make it thread safe? def join(userId): users = memcache.get('room_1') ...
[ "Something like this may work.\nclass Room(db.Model):\n users = db.StringListProperty()\n\ndef join(userId):\n def _transaction():\n room = Room.get_by_key_name('room_1')\n if room is None:\n room = Room(key_name = 'room_1', users = [])\n room.users.append(userId)\n room...
[ 2, 1, 0, 0 ]
[]
[]
[ "google_app_engine", "python", "thread_safety" ]
stackoverflow_0002987429_google_app_engine_python_thread_safety.txt
Q: Python - help on custom wx.Python (pyDev) class I have been hitting a dead end with this program. I am trying to build a class that will let me control the BIP's of a button when it is in use. so far this is what i have (see following.) It keeps running this weird error TypeError: 'module' object is not callable -...
Python - help on custom wx.Python (pyDev) class
I have been hitting a dead end with this program. I am trying to build a class that will let me control the BIP's of a button when it is in use. so far this is what i have (see following.) It keeps running this weird error TypeError: 'module' object is not callable - I, coming from C++ and C# (for some reason the #incl...
[ "Commented out this whole thing and the error went away and a window popped up:\n self.Button1 = Custom_Button(self, parent, -1, \n \"D:/Documents/Python/Normal.bmp\", \n \"D:/Documents/Python/Clicked.bmp\",\n \"D:/Documents/Pyth...
[ 2, 1 ]
[]
[]
[ "class_design", "custom_controls", "pydev", "python", "wxpython" ]
stackoverflow_0002994289_class_design_custom_controls_pydev_python_wxpython.txt
Q: Extracting Information from Images What are some fast and somewhat reliable ways to extract information about images? I've been tinkering with OpenCV and this seems so far to be the best route plus it has Python bindings. So to be more specific I'd like to determine what I can about what's in an image. So for ex...
Extracting Information from Images
What are some fast and somewhat reliable ways to extract information about images? I've been tinkering with OpenCV and this seems so far to be the best route plus it has Python bindings. So to be more specific I'd like to determine what I can about what's in an image. So for example the haar face detection and full b...
[ "Your question is difficult to answer without more clarification about the types of images you are analyzing and your purpose.\nThe tone of the post seems that you are interested in tinkering -- that's fine. If you want to tinker, one example application might be iris identification using wavelet analysis. You can ...
[ 2 ]
[]
[]
[ "identification", "image", "opencv", "python" ]
stackoverflow_0002994398_identification_image_opencv_python.txt
Q: Network Communication program in python Basically what I'm trying to achieve is a program which allow users to connect to a each other over a network in, essentially, a chat room. What I'm currently struggling with is writing the code so that the users can connect to each other without knowing the IP-address of th...
Network Communication program in python
Basically what I'm trying to achieve is a program which allow users to connect to a each other over a network in, essentially, a chat room. What I'm currently struggling with is writing the code so that the users can connect to each other without knowing the IP-address of the computer that the other users are using or ...
[ "I can give you two suggestions. First of all, UDP packets to the broadcast address of your network will be received by everybody. Secondly, there is a protocol for programs offering certain services to find each other on a local network. That protocol is called mDNS, ZeroConf, or Bonjour.\nUsing broadcast UDP i...
[ 6 ]
[]
[]
[ "client_server", "networking", "p2p", "python" ]
stackoverflow_0002994430_client_server_networking_p2p_python.txt
Q: Using classes for the first time,help in debugging here is post my code:this is no the entire code but enough to explain my doubt.please discard any code line which u find irrelavent enter code here saving_tree={} isLeaf=False class tree: global saving_tree rootNode=None lispTree=None def __init...
Using classes for the first time,help in debugging
here is post my code:this is no the entire code but enough to explain my doubt.please discard any code line which u find irrelavent enter code here saving_tree={} isLeaf=False class tree: global saving_tree rootNode=None lispTree=None def __init__(self,x): file=x string=file.readlines...
[ "saving_tree is not global in the __init__ method (which is a different scope than the class body). You could fix that by adding global saving_tree as the first statement in the method (and remove that in the body which plays no role).\nA better approach would be to forget about global and use a class attribute in...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0002994655_python.txt
Q: IronPython For Unit Testing over C# We know that Python provides a lot of productivity over any compiled languages. We have programming in C# & need to write the unit test cases in C# itself. If we see the amount of code we write for unit test is approximately ten times more than the original code. Is it ideal c...
IronPython For Unit Testing over C#
We know that Python provides a lot of productivity over any compiled languages. We have programming in C# & need to write the unit test cases in C# itself. If we see the amount of code we write for unit test is approximately ten times more than the original code. Is it ideal choice to write unit test cases in IronPyt...
[ "Python is excellent for UnitTesting C# code. Our app is 75% in Python and 25% C#(Python.Net), and our unit tests are 100% python. \nI find that it's much easier to make use of stubs and mocks in Python which is probably one of the most critical components that enable one to write effective unittests.\n", "Will...
[ 6, 4, 3, 3, 2, 1, 0, 0 ]
[]
[]
[ "c#", "ironpython", "python", "unit_testing" ]
stackoverflow_0000340128_c#_ironpython_python_unit_testing.txt
Q: Monitor web sites visited using Internet Explorer, Opera, Chrome, Firefox and Safari in Python I am working on a project for work and have seemed to run into a small problem. The project is a similar program to Web Nanny, but branded to my client's company. It will have features such as website blocking by URL, ke...
Monitor web sites visited using Internet Explorer, Opera, Chrome, Firefox and Safari in Python
I am working on a project for work and have seemed to run into a small problem. The project is a similar program to Web Nanny, but branded to my client's company. It will have features such as website blocking by URL, keyword and web activity logs. I would also need it to be able to "pause" downloads until an acceptabl...
[ "I would recommend looking into a nice web proxy. If the machines are all on the same network you can implement a transparent caching web proxy and put filtering rules on it. They tend to be high speed and can do lots of cool things.\nI have had some luck with Squid. Would this solve your situation?\n", "You need...
[ 2, 0 ]
[]
[]
[ "google_chrome", "internet_explorer", "opera", "python", "safari" ]
stackoverflow_0002994486_google_chrome_internet_explorer_opera_python_safari.txt
Q: django auth : strange error with authenticate() I am using authenticate() to authenticating users manually. Using admin interface I can see that there is no 'last_login' attribute for Users Debug traceback is : Environment: Request Method: GET Request URL: https://localhost/login/ Django Version: 1.1.1 Python Ver...
django auth : strange error with authenticate()
I am using authenticate() to authenticating users manually. Using admin interface I can see that there is no 'last_login' attribute for Users Debug traceback is : Environment: Request Method: GET Request URL: https://localhost/login/ Django Version: 1.1.1 Python Version: 2.6.5 Installed Applications: ['django.contrib....
[ "The problem isn't with authenticate(), it seems to be with login() which you appear to be passing a unicode into, rather than a django.contrib.auth.models.User object.\nYou should probably be getting that User object from authenticate()\nuser = authenticate(username=username, password=password)\n...\nlogin(request...
[ 2, 0 ]
[]
[]
[ "django", "django_authentication", "python" ]
stackoverflow_0002995736_django_django_authentication_python.txt
Q: Efficient and accurate way to compact and compare Python lists? I'm trying to a somewhat sophisticated diff between individual rows in two CSV files. I need to ensure that a row from one file does not appear in the other file, but I am given no guarantee of the order of the rows in either file. As a starting point...
Efficient and accurate way to compact and compare Python lists?
I'm trying to a somewhat sophisticated diff between individual rows in two CSV files. I need to ensure that a row from one file does not appear in the other file, but I am given no guarantee of the order of the rows in either file. As a starting point, I've been trying to compare the hashes of the string representation...
[ "It's hard to give a great answer without knowing more about your constraints, but if you can store a hash for each line of each file then you should be ok. At the very least you'll need to be able to store the hash list for one file, which you then would sort and write to disk, then you can march through the two ...
[ 4, 2, 1, 1, 0, 0, 0 ]
[]
[]
[ "comparison", "hash", "list", "python" ]
stackoverflow_0002994159_comparison_hash_list_python.txt
Q: How to poll a file in /sys I am stuck reading a file in /sys/ which contains the light intensity in Lux of the ambient light sensor on my Nokia N900 phone. See thread on talk.maemo.org here I tried to use pyinotify to poll the file but this looks some kind of wrong to me since the file is alway "process_IN_OPEN", ...
How to poll a file in /sys
I am stuck reading a file in /sys/ which contains the light intensity in Lux of the ambient light sensor on my Nokia N900 phone. See thread on talk.maemo.org here I tried to use pyinotify to poll the file but this looks some kind of wrong to me since the file is alway "process_IN_OPEN", "process_IN_ACCESS" and "process...
[ "Since the /sys/file is a pseudo-file which just presents a view on an underlying, volatile operating system value, it makes sense that there would never be a modify event raised. Since the file is \"modified\" from below it doesn't follow regular file-system semantics.\nIf a modify event is never raised, using a p...
[ 1, 0 ]
[]
[]
[ "maemo", "pyinotify", "python", "sys" ]
stackoverflow_0002995664_maemo_pyinotify_python_sys.txt
Q: Why doesn't Python require exactly four spaces per indentation level? Whitespace is signification in Python in that code blocks are defined by their indentation. Furthermore, Guido van Rossum recommends using four spaces per indentation level (see PEP 8: Style Guide for Python Code). What was the reasoning behind ...
Why doesn't Python require exactly four spaces per indentation level?
Whitespace is signification in Python in that code blocks are defined by their indentation. Furthermore, Guido van Rossum recommends using four spaces per indentation level (see PEP 8: Style Guide for Python Code). What was the reasoning behind not requiring exactly four spaces per indentation level as well? Are there ...
[ "There are no technical reasons. It would not be too hard to modify the Python interpreter to require exactly four spaces per indentation level.\nHere is one use case for other indentation levels: when typing into the interactive interpreter, it's very handy to use one-space indentations. It saves on typing, it's...
[ 30, 11, 8, 6, 5, 1, 1, 1, 1, 0, 0 ]
[]
[]
[ "indentation", "python" ]
stackoverflow_0002966285_indentation_python.txt
Q: What is the difference between a module and a script in Python? Think the title summarizes the question :-) A: A script is generally a directly executable piece of code, run by itself. A module is generally a library, imported by other pieces of code. Note that there's no internal distinction -- both are execut...
What is the difference between a module and a script in Python?
Think the title summarizes the question :-)
[ "A script is generally a directly executable piece of code, run by itself. A module is generally a library, imported by other pieces of code.\nNote that there's no internal distinction -- both are executable and importable, although library code often won't do anything (or will just run its unit tests) when execut...
[ 62, 31 ]
[]
[]
[ "module", "python", "scripting" ]
stackoverflow_0002996110_module_python_scripting.txt
Q: Elegant ways to print out a bunch of instance attributes in python 2.6? First some background. I'm parsing a simple file format, and wish to re-use the results in python code later, so I made a very simple class hierarchy and wrote the parser to construct objects from the original records in the text files I'm wor...
Elegant ways to print out a bunch of instance attributes in python 2.6?
First some background. I'm parsing a simple file format, and wish to re-use the results in python code later, so I made a very simple class hierarchy and wrote the parser to construct objects from the original records in the text files I'm working from. At the same time I'd like to load the data into a legacy database,...
[ "class MyRecord:\n #.... \n def __getitem__(self, key):\n return getattr(self, key)\n\n", "If you make attr1's length a property or attribute of the record class (so you're really just printing instance attributes as the title implies), you could just do this.\nattrs = ['id', 'attr1', 'attr1_len', ....
[ 2, 2 ]
[]
[]
[ "oop", "output_formatting", "python" ]
stackoverflow_0002997010_oop_output_formatting_python.txt
Q: importing classes python Just wondering why import sys exit(0) gives me this error: Traceback (most recent call last): File "<pyshell#1>", line 1, in ? exit(0) TypeError: 'str' object is not callable but from sys import exit exit(0) works fine? A: Python imports only the chosen names into the namespace...
importing classes python
Just wondering why import sys exit(0) gives me this error: Traceback (most recent call last): File "<pyshell#1>", line 1, in ? exit(0) TypeError: 'str' object is not callable but from sys import exit exit(0) works fine?
[ "Python imports only the chosen names into the namespace.\nYour equivalent first solution should be\nsys.exit(0)\n\nsince import sys imports only the sys keyword into the current namespace.\n", "See http://effbot.org/zone/import-confusion.htm for all the different ways to use import in Python.\nimport sys\nThis i...
[ 8, 6, 0 ]
[]
[]
[ "import", "python" ]
stackoverflow_0002997105_import_python.txt
Q: Datastore performance, my code or the datastore latency I had for the last month a bit of a problem with a quite basic datastore query. It involves 2 db.Models with one referring to the other with a db.ReferenceProperty. The problem is that according to the admin logs the request takes about 2-4 seconds to complet...
Datastore performance, my code or the datastore latency
I had for the last month a bit of a problem with a quite basic datastore query. It involves 2 db.Models with one referring to the other with a db.ReferenceProperty. The problem is that according to the admin logs the request takes about 2-4 seconds to complete. I strip it down to a bare form and a list to display the r...
[ "There's certainly things you can do to optimize your code. For example, you're iterating over a query, which is less efficient than fetching the query and iterating over the results.\nI'd recommend using Appstats to profile your app, and check out the Patterns of Doom series of posts.\n", "Don't just try things....
[ 3, 0 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "optimization", "python" ]
stackoverflow_0002995981_google_app_engine_google_cloud_datastore_optimization_python.txt
Q: 404 when getting private YouTube video even when logged in with the owner's account using gdata-python-client If a YouTube video is set as private and I try to fetch it using the gdata Python API a 404 RequestError is raised, even though I have done a programmatic login with the account that owns that video: from ...
404 when getting private YouTube video even when logged in with the owner's account using gdata-python-client
If a YouTube video is set as private and I try to fetch it using the gdata Python API a 404 RequestError is raised, even though I have done a programmatic login with the account that owns that video: from gdata.youtube import service yt_service = service.YouTubeService(email=my_email, ...
[ "Apparently the YouTube Data API doesn't allow this (yet), so to workaround this I use the GetYouTubeUserFeed method of a YouTubeService instance to obtain a list of all the video entries I need (whether they are private or public):\nfrom gdata.youtube import service\nVIDEO_ID = 'IcVqemzfyYs'\nyt_service = service....
[ 0 ]
[]
[]
[ "gdata_api", "python", "youtube_api" ]
stackoverflow_0002991636_gdata_api_python_youtube_api.txt
Q: Using upload_data on Google AppEngine doesn't let me update entities with id based keys This seems so basic - I must be missing something. I am trying to download my entities, update a few properties, and upload the entities. I'm using the Django nonrel & appengine projects, so all the entities are stored as id r...
Using upload_data on Google AppEngine doesn't let me update entities with id based keys
This seems so basic - I must be missing something. I am trying to download my entities, update a few properties, and upload the entities. I'm using the Django nonrel & appengine projects, so all the entities are stored as id rather than name. I can download the entities to csv fine, but when I upload (via appcfg.py up...
[ "As the error message indicates, overwriting entities with numeric IDs isn't currently supported. You may be able to work around it by providing a post-upload function that recreates the entity with the relevant key, but I'd suggest stepping back and analyzing why you're doing this - why not just update the entitie...
[ 0 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0002992107_django_google_app_engine_python.txt
Q: Copy call signature to decorator If I do the following def mydecorator(f): def wrapper(*args, **kwargs): f(*args, **kwargs) wrapper.__doc__ = f.__doc__ wrapper.__name__ = f.__name__ return wrapper @mydecorator def myfunction(a,b,c): '''My docstring''' pass And then type help myfun...
Copy call signature to decorator
If I do the following def mydecorator(f): def wrapper(*args, **kwargs): f(*args, **kwargs) wrapper.__doc__ = f.__doc__ wrapper.__name__ = f.__name__ return wrapper @mydecorator def myfunction(a,b,c): '''My docstring''' pass And then type help myfunction, I get: Help on function myfunct...
[ "Here is an example using Michele Simionato's decorator module to fix the signature:\nimport decorator\n\n@decorator.decorator\ndef mydecorator(f,*args, **kwargs):\n return f(*args, **kwargs)\n\n@mydecorator\ndef myfunction(a,b,c):\n '''My docstring'''\n pass\n\nhelp(myfunction)\n# Help on function myfunct...
[ 9, 3, 1 ]
[]
[]
[ "decorator", "python" ]
stackoverflow_0002982974_decorator_python.txt
Q: Django: Filtering datetime field by *only* the year value? I'm trying to spit out a django page which lists all entries by the year they were created. So, for example: 2010: Note 4 Note 5 Note 6 2009: Note 1 Note 2 Note 3 It's proving more difficult than I would have expected. The model from which the data com...
Django: Filtering datetime field by *only* the year value?
I'm trying to spit out a django page which lists all entries by the year they were created. So, for example: 2010: Note 4 Note 5 Note 6 2009: Note 1 Note 2 Note 3 It's proving more difficult than I would have expected. The model from which the data comes is below: class Note(models.Model): business = models.For...
[ "Either construct custom SQL or use\ndate_list = Note.objects.all().dates('created', 'year')\n\nfor years in date_list:\n Note.objects.filter(created__year = years.year)\n\nThis is the way it is done in date based generic views. \n", "You can use django.views.generic.date_based.archive_year or use year field l...
[ 43, 3 ]
[]
[]
[ "django", "django_models", "django_queryset", "group_by", "python" ]
stackoverflow_0002997433_django_django_models_django_queryset_group_by_python.txt
Q: XML library similar to simplejson/json? - Python is there a similar library to simplejson, which would enable quick serialization of data to and from XML. e.g. json.loads('{vol:'III', title:'Magical Unicorn'}') e.g. json.dumps([1,2,3,4,5]) Any ideas? A: You're not going to find anything for xml as consistent a...
XML library similar to simplejson/json? - Python
is there a similar library to simplejson, which would enable quick serialization of data to and from XML. e.g. json.loads('{vol:'III', title:'Magical Unicorn'}') e.g. json.dumps([1,2,3,4,5]) Any ideas?
[ "You're not going to find anything for xml as consistent as json, because xml doesn't know about data types. It depends on you to follow conventions or enforce adherence to an xml schema file.\nThat being said, if you're willing to accept the XML-RPC data structure mapping and a few limitations, check out the xmlr...
[ 3, 3, 2, 2, 1 ]
[]
[]
[ "json", "python", "simplejson", "xml" ]
stackoverflow_0002996678_json_python_simplejson_xml.txt
Q: Matching a+ in a regex This should be easy, but I've managed to stump 2 people so far at work & I've been at it for over 3 hours now, so here goes. I need to replace a+ with aplus (along with a few other cases) with the Python re module. eg. "I passed my a+ exam." needs to become "I passed my aplus exam." Just us...
Matching a+ in a regex
This should be easy, but I've managed to stump 2 people so far at work & I've been at it for over 3 hours now, so here goes. I need to replace a+ with aplus (along with a few other cases) with the Python re module. eg. "I passed my a+ exam." needs to become "I passed my aplus exam." Just using \ba+ works fine most of ...
[ "Turn that \\W into an assertion.\n\\ba\\+(?=\\W)\n\nor, better,\n\\ba\\+(?!\\w)\n\nsince the negative assertion allows matching the a+ at end of string too.\n", ">>> re.sub(r'\\ba\\+\\s', 'aplus ', 'I passed my a+ exam.')\n'I passed my aplus exam.'\n>>> re.sub(r'\\ba\\+\\s', 'aplus ', 'a+b')\n'a+b'\n\n", "You ...
[ 8, 1, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002997869_python_regex.txt
Q: Python Threading I'm trying to make a simple program that continually displays and updates a label that displays the CPU usage, while having other unrelated things going on. I've done enough research to know that threading is likely going to be involved. However, I'm having trouble applying what I've seen in simp...
Python Threading
I'm trying to make a simple program that continually displays and updates a label that displays the CPU usage, while having other unrelated things going on. I've done enough research to know that threading is likely going to be involved. However, I'm having trouble applying what I've seen in simple examples of threadi...
[ "You should never attempt to alter a UI element from a thread that isn't the main thread. \nWhat you probably want is after(delay_ms, callback, args). Some information can be over at http://www.pythonware.com/library/tkinter/introduction/x9507-alarm-handlers-and-other.htm.\nAs a sample, here's a quick script to sho...
[ 4, 2 ]
[]
[]
[ "multithreading", "python", "tkinter" ]
stackoverflow_0002987913_multithreading_python_tkinter.txt
Q: Avoid 404 page override I 'm using django-lfs with default django-app.Its appear django-lfs override 404 default template. How to avoid this process A: Within the templates folder, there is should be a 404.html. Remove that, and django defaults to the standard 404 page!
Avoid 404 page override
I 'm using django-lfs with default django-app.Its appear django-lfs override 404 default template. How to avoid this process
[ "Within the templates folder, there is should be a 404.html. Remove that, and django defaults to the standard 404 page!\n" ]
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002997764_django_python.txt
Q: Importing Python modules without installing - Sybase ASE I need to use the Sybase Python module but our SA's won't install because it's not in the repo's. I've downloaded it and placed it on the box and would just like to 'import' or 'include' the module without installing it first. - Is this possible? From the lo...
Importing Python modules without installing - Sybase ASE
I need to use the Sybase Python module but our SA's won't install because it's not in the repo's. I've downloaded it and placed it on the box and would just like to 'import' or 'include' the module without installing it first. - Is this possible? From the looks of it (Sybase ASE) it needs some type of compilation befor...
[ "If you can get Sybase to use a virtual environment (I know nothing about Sybase, sorry), perhaps you could install the module using virtualenv, which generally doesn't require root access or SA approval.\n", "From the sybase documentation it looks like compilation is required, and Google tells me that it's not a...
[ 1, 1, 0 ]
[]
[]
[ "module", "python", "sap_ase" ]
stackoverflow_0002997697_module_python_sap_ase.txt
Q: deleting all the file of certain size i have bunch of log files and I have to delete the files of some small sizes, which were erroneous files that got created. ( 63bytes ). I have to copy only those files which have data in it . A: Shell (linux); find . -type f -size 63c -delete Will traverse subdirectories (u...
deleting all the file of certain size
i have bunch of log files and I have to delete the files of some small sizes, which were erroneous files that got created. ( 63bytes ). I have to copy only those files which have data in it .
[ "Shell (linux);\nfind . -type f -size 63c -delete\n\nWill traverse subdirectories (unless you tell it otherwise)\n", "Since you tagged your question with \"python\" here is how you could do this in that language:\ntarget_size = 63\nimport os\nfor dirpath, dirs, files in os.walk('.'):\n for file in files: \n ...
[ 18, 10, 6 ]
[]
[]
[ "perl", "python", "shell" ]
stackoverflow_0002994035_perl_python_shell.txt
Q: How to make every Class Method call a specified method before execution? I want to make my Python Class behave in such a way that when any Class method is called a default method is executed first without explicitly specifying this in the called Class. An example may help :) Class animals: def _internalMethod(...
How to make every Class Method call a specified method before execution?
I want to make my Python Class behave in such a way that when any Class method is called a default method is executed first without explicitly specifying this in the called Class. An example may help :) Class animals: def _internalMethod(): self.respires = True def cat(): self._internalMethod()...
[ "You could use a metaclass and getattribute to decorate all methods dynamically (if you are using Python 2, be sure to subclass from object!).\nAnother option is just to have a fixup on the class, like:\ndef add_method_call(func, method_name):\n def replacement(self, *args, **kw):\n getattr(self, method_n...
[ 5 ]
[]
[]
[ "python" ]
stackoverflow_0002998969_python.txt
Q: Is there a Python library that eases the creation of CLI utilities like Django management commands? I want to create a set of command-line utilities in python that would be used like so: python utility.py command1 -option arg Very similar to django management commands. Is there any library that eases the creation...
Is there a Python library that eases the creation of CLI utilities like Django management commands?
I want to create a set of command-line utilities in python that would be used like so: python utility.py command1 -option arg Very similar to django management commands. Is there any library that eases the creation of such commands?
[ "Baker is rather nice I think. Optfunc maybe also.\n", "Optparse is the way to go\n", "Take a look at plac. I haven't used it as I stumbled to it just recently. It looks simple enough, though.\n", "You just want to create a two-level command? You should use argparse -- it's simple enough, is similar to optpa...
[ 5, 2, 2, 2 ]
[]
[]
[ "command_line", "django", "python" ]
stackoverflow_0002995894_command_line_django_python.txt
Q: Passing values into regex match function In python (it's a Django filter), I'm doing this: lReturn = re.sub(r'\[usecase:([ \w]+)]', r'EXTEND WITH <a href="/usecase/%s/\1/">\1</a>' % pCurrentProjectName, lReturn) I'd like to use a function instead of a string (so I can check that the usercase is a valid name), so ...
Passing values into regex match function
In python (it's a Django filter), I'm doing this: lReturn = re.sub(r'\[usecase:([ \w]+)]', r'EXTEND WITH <a href="/usecase/%s/\1/">\1</a>' % pCurrentProjectName, lReturn) I'd like to use a function instead of a string (so I can check that the usercase is a valid name), so it would change to this: def _match_function(m...
[ "You could create a function that returns a function (a closure):\ndef _match_function(name):\n def f(matchobj):\n lMatch = matchobj.group(1)\n return \"EXTEND WITH <a href='/usecase/%s/%s/'>%s</a>\" % (name, lMatch, lMatch)\n return f\n\nlReturn = re.sub(r'\\[usecase:([ \\w]+)]', _match_functio...
[ 4 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002999205_python_regex.txt
Q: Trying to use py2exe, but python is not recognized I am following the the tutorial at http://www.py2exe.org/index.cgi/Tutorial to figure out how to use py2exe. I get down to step 3 where you are supposed to run the command: python setup.py py2exe I do that and then I get this error: 'python' is not recognized as ...
Trying to use py2exe, but python is not recognized
I am following the the tutorial at http://www.py2exe.org/index.cgi/Tutorial to figure out how to use py2exe. I get down to step 3 where you are supposed to run the command: python setup.py py2exe I do that and then I get this error: 'python' is not recognized as an internal or external command, operable program or bat...
[ "Python just isn't on your path. If you indeed have Python 2.4, it should be C:\\Python24\\python.exe with the default installer.\nWherever the file is located, if you don't set Python's folder in your path, you will write the command as\nC:\\Python24\\python.exe setup.py py2exe\n\n(or whatever the correct path is...
[ 2, 0 ]
[]
[]
[ "py2exe", "python" ]
stackoverflow_0002999427_py2exe_python.txt
Q: Python: split files using multiple split delimiters I have multiple CSV files which I need to parse in a loop to gather information. The problem is that while they are the same format, some are delimited by '\t' and others by ','. After this, I want to remove the double-quote from around the string. Can python spl...
Python: split files using multiple split delimiters
I have multiple CSV files which I need to parse in a loop to gather information. The problem is that while they are the same format, some are delimited by '\t' and others by ','. After this, I want to remove the double-quote from around the string. Can python split via multiple possible delimiters? At the minute, I can...
[ "Splitting the file like that is not a good idea: It will fail if there is a comma within one of the fields. For example (for a tab-delimited file): The line \"field1\"\\t\"Hello, world\"\\t\"field3\" will be split into 4 fields instead of 3.\nInstead, you should use the csv module. It contains the helpful Sniffer ...
[ 14, 2 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0002999373_csv_python.txt
Q: Parsing timestamp with Python2.4 I want to parse a timestamp from a log file that has been written via datetime.datetime.now().strftime('%Y%m%d%H%M%S') and then compute the number of seconds that have passed since this timestamp. I know I could do it with datetime.datetime.strptime to get back a datetime object an...
Parsing timestamp with Python2.4
I want to parse a timestamp from a log file that has been written via datetime.datetime.now().strftime('%Y%m%d%H%M%S') and then compute the number of seconds that have passed since this timestamp. I know I could do it with datetime.datetime.strptime to get back a datetime object and then compute a timedelta. Problem is...
[ ">>> ts = time.mktime(time.strptime('20040412234551', '%Y%m%d%H%M%S'))\n>>> ts\n1081809951.0\n>>> datetime.datetime.fromtimestamp(ts)\ndatetime.datetime(2004, 4, 12, 23, 45, 51)\n\n", "now = datetime.datetime.now()\nthen = datetime.datetime(*time.strptime('20080227034510' ,'%Y%m%d%H%M%S')[0:6])\ndifference = now ...
[ 5, 1, 0, 0 ]
[]
[]
[ "datetime", "parsing", "python", "python_2.4" ]
stackoverflow_0002997777_datetime_parsing_python_python_2.4.txt
Q: Getting youtube links from embedded youtube video on pages? Is there a regex to get youtube video links or ids from embedded youtube videos on webpages? A: To find: "<object(.*)youtube.com/v/(.*)\"(.*)</object>" To convert to a link: replace("<object(.*)youtube.com/v/(.*)\"(.*)</object>", '<a href="http://www.yo...
Getting youtube links from embedded youtube video on pages?
Is there a regex to get youtube video links or ids from embedded youtube videos on webpages?
[ "To find:\n\"<object(.*)youtube.com/v/(.*)\\\"(.*)</object>\"\nTo convert to a link:\nreplace(\"<object(.*)youtube.com/v/(.*)\\\"(.*)</object>\", '<a href=\"http://www.youtube.com/watch?v=\\\\2\">click here</a>', $str) \nsource\n" ]
[ 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002998517_python_regex.txt
Q: Specifying the Python interpreter for vim's :python command (Mac)Vim seems to be picking up /usr/bin/python instead of the one that's at the front of my path (/Library/Frameworks/Python.framework/Versions/2.6/bin/python) when I use the :python command. Is this entirely a compile-time thing or can I somehow overrid...
Specifying the Python interpreter for vim's :python command
(Mac)Vim seems to be picking up /usr/bin/python instead of the one that's at the front of my path (/Library/Frameworks/Python.framework/Versions/2.6/bin/python) when I use the :python command. Is this entirely a compile-time thing or can I somehow override it?
[ "Seems like it is an entirely compile-time thing:\n$ ldd /usr/bin/vim | grep python\nlibpython2.5.so.1.0 => /usr/lib/libpython2.5.so.1.0 (0xb6bcc000)\n\nmy vim --version also reports being built against a specific python.\n$ vim --version | tr '-' '\\n' | grep python\n+python +quickfix +reltime +rightleft +ruby +sc...
[ 14 ]
[]
[]
[ "environment_variables", "python", "vim" ]
stackoverflow_0002999315_environment_variables_python_vim.txt
Q: How to access GMail (IMAP Email) from my Shell/Python script to download a zip file attached to an email and process it? I have to process a file everyday. This file is sent to my Email once everyday. If I can get to this email once every day and download the attachment, that had be awesome. Is it even remotely po...
How to access GMail (IMAP Email) from my Shell/Python script to download a zip file attached to an email and process it?
I have to process a file everyday. This file is sent to my Email once everyday. If I can get to this email once every day and download the attachment, that had be awesome. Is it even remotely possible to do such a thing? Thanks!
[ "Please see How can I download all emails with attachments from Gmail? for a practical example.\n", "This is certainly possible. Check out imaplib in Python's standard library; with it doing what you want should be quite straightforward. Also, you can process zip files directly in Python using the zipfile library...
[ 6, 1, 1 ]
[]
[]
[ "download", "gmail", "imap", "python", "shell" ]
stackoverflow_0003000014_download_gmail_imap_python_shell.txt
Q: How do you redirect a standard stream of a C++ routine wrapped with SWIG and exposed to Python? Is it possible to control the standard streams of C++ code in python? The code is wrapped with SWIG and then exposed to Python where I call one of its functions. I am getting all kinds of unwanted messages coming from C...
How do you redirect a standard stream of a C++ routine wrapped with SWIG and exposed to Python?
Is it possible to control the standard streams of C++ code in python? The code is wrapped with SWIG and then exposed to Python where I call one of its functions. I am getting all kinds of unwanted messages coming from C++ code and I want to suppress them either by not using the output stream or by redirecting it to a b...
[ "I think the best way is to implement a simple function/method in C or C++ of your extension to redirect the stdout output, see dup for example, I think it will work fine.\n" ]
[ 1 ]
[]
[]
[ "c++", "outputstream", "python", "standards", "swig" ]
stackoverflow_0002942284_c++_outputstream_python_standards_swig.txt
Q: Utilizing multiple python projects I have a python app, that I'm developing. There is a need to use another library, that resides in different directory. The file layout looks like this: dir X has two project dirs: current-project xLibrary I'd like to use xLibrary in currentProject. I've been trying writting...
Utilizing multiple python projects
I have a python app, that I'm developing. There is a need to use another library, that resides in different directory. The file layout looks like this: dir X has two project dirs: current-project xLibrary I'd like to use xLibrary in currentProject. I've been trying writting code as if all the sources resided in t...
[ "It's generally a good programming practice to isolate packages into actual packages and treat them as such. If you're sure you'd like to continue with that approach though you can modify the search path from within python via:\nimport sys\nsys.path.append( \"<path_containing_the_other_python_files>\" )\n\nTo avoid...
[ 2, 2, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003000921_python.txt
Q: C++ Swig Python (Embedded Python in C++) works in Release but not in Debug Platform: Windows 7, 64 bit (x64), Visual Studio 2008 I chose Python & Swig binding as the scripting environment of the application. As a prototype, created a simple VS solution with main() which initializes Python (Py_Initalize, Py_setPyH...
C++ Swig Python (Embedded Python in C++) works in Release but not in Debug
Platform: Windows 7, 64 bit (x64), Visual Studio 2008 I chose Python & Swig binding as the scripting environment of the application. As a prototype, created a simple VS solution with main() which initializes Python (Py_Initalize, Py_setPyHome, etc) & executes test.py. In the same solution created another project which...
[ "Alright - found it. The debug output dll has to be named xxx_d.pyd!! In above case it would be _MyClasses_d.pyd\n" ]
[ 1 ]
[]
[]
[ "debugging", "python", "swig" ]
stackoverflow_0003000612_debugging_python_swig.txt
Q: Unwanted behaviour from dict.fromkeys I'd like to initialise a dictionary of sets (in Python 2.6) using dict.fromkeys, but the resulting structure behaves strangely. More specifically: >>>> x = {}.fromkeys(range(10), set([])) >>>> x {0: set([]), 1: set([]), 2: set([]), 3: set([]), 4: set([]), 5: set([]), 6: set([]...
Unwanted behaviour from dict.fromkeys
I'd like to initialise a dictionary of sets (in Python 2.6) using dict.fromkeys, but the resulting structure behaves strangely. More specifically: >>>> x = {}.fromkeys(range(10), set([])) >>>> x {0: set([]), 1: set([]), 2: set([]), 3: set([]), 4: set([]), 5: set([]), 6: set([]), 7: set([]), 8: set([]), 9: set([])} >>>>...
[ "The second argument to dict.fromkeys is just a value. You've created a dictionary that has the same set as the value for every key. Presumably you understand the way this works:\n>>> a = set()\n>>> b = a\n>>> b.add(1)\n>>> b\nset([1])\n>>> a\nset([1])\n\nyou're seeing the same behavior there; in your case, x[0],...
[ 19, 18, 3, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003000468_python.txt
Q: How do I make a python window always be on bottom? How do I make a python window always be on bottom? A: If you're talking about Tkinter, you can use: window.geometry('300x200-5+40') Where the 300x200 is the size, and -5+40 is the positioning offsets.
How do I make a python window always be on bottom?
How do I make a python window always be on bottom?
[ "If you're talking about Tkinter, you can use:\n window.geometry('300x200-5+40')\n\nWhere the 300x200 is the size, and -5+40 is the positioning offsets.\n" ]
[ 0 ]
[]
[]
[ "python", "tkinter", "windows" ]
stackoverflow_0003000447_python_tkinter_windows.txt
Q: PHP CURL sending POST to Django app issue This code in PHP sends a HTTP POST to a Django app using CURL lib. I need that this code sends POST but redirect to the page in the same submit. Like a simple form does. The PHP Code: $c = curl_init(); curl_setopt($c, CURLOPT_FOLLOWLOCATION, true); curl_setopt($c, CURLOPT_...
PHP CURL sending POST to Django app issue
This code in PHP sends a HTTP POST to a Django app using CURL lib. I need that this code sends POST but redirect to the page in the same submit. Like a simple form does. The PHP Code: $c = curl_init(); curl_setopt($c, CURLOPT_FOLLOWLOCATION, true); curl_setopt($c, CURLOPT_URL, "http://www.xxx.com"); curl_setopt($c, CUR...
[ "Your code does a server-side POST request to the page. You can't \"redirect\" the user to the same \"instance\" of the page.\nIf you need to do it in one step, print out a form with method=\"POST\" and hidden fields and then add JavaScript which automatically submits it.\n" ]
[ 1 ]
[]
[]
[ "curl", "django", "php", "python" ]
stackoverflow_0003001122_curl_django_php_python.txt
Q: Define a global in a Python module from a C API I am developing a module for Python using a C API. How can I create a variable that is seen as global from Python? For example, if my module is module, I want to create a variable g that does this job: import module print module.g In particular, g is an integer. So...
Define a global in a Python module from a C API
I am developing a module for Python using a C API. How can I create a variable that is seen as global from Python? For example, if my module is module, I want to create a variable g that does this job: import module print module.g In particular, g is an integer. Solution from Alex Martelli PyObject *m = Py_InitModule...
[ "You can use PyObject_SetAttrString in your module's initialization routine, with first argument o being (the cast to (PyObject*) of) your module, second argument attr_name being \"g\", third argument v being a variable\nPyObject *v = PyLong_FromLong((long) 23);\n\n(or whatever other value of course, 23 is just an ...
[ 4 ]
[]
[]
[ "c", "global_variables", "python", "python_c_api", "python_module" ]
stackoverflow_0003001239_c_global_variables_python_python_c_api_python_module.txt
Q: What good open source programs exist for fuzzing popular image file types? I am looking for a free, open source, portable fuzzing tool for popular image file types that is written in either Java, Python, or Jython. Ideally, it would accept specifications for the fuzzable fields using some kind of declarative const...
What good open source programs exist for fuzzing popular image file types?
I am looking for a free, open source, portable fuzzing tool for popular image file types that is written in either Java, Python, or Jython. Ideally, it would accept specifications for the fuzzable fields using some kind of declarative constraints. Non-procedural grammar for specifying constraints are greatly preferred...
[ "Peach has a file fuzzing module. Here is an excellent quick start tutorial for using the file fuzzing module to attack mplayer using a sound file: http://peachfuzzer.com/TutorialFileFuzzing \nI recommend focusing on the file's header.\n", "Not exactly what you are asking for, but for getting quick up and running...
[ 3, 2, 0, 0 ]
[]
[]
[ "fuzzer", "generator", "image", "java", "python" ]
stackoverflow_0002210303_fuzzer_generator_image_java_python.txt
Q: Return an object after parsing xml with SAX I have some large XML files to parse and have created an object class to contain my relevant data. Unfortunately, I am unsure how to return the object for later processing. Right now I pickle my data and moments later depickle the object for access. This seems wastefu...
Return an object after parsing xml with SAX
I have some large XML files to parse and have created an object class to contain my relevant data. Unfortunately, I am unsure how to return the object for later processing. Right now I pickle my data and moments later depickle the object for access. This seems wasteful, and there surely must be a way of grabbing my ...
[ "Bah, sat and thought about it for a second and the answer was obvious. Return quit the method, and then just pull out the data field from the ContentHandler object I had created.\n" ]
[ 1 ]
[]
[]
[ "python", "sax", "xml" ]
stackoverflow_0003001350_python_sax_xml.txt
Q: Passing arguments to a python service I need some help with a python service. I have a service written in Python. What I need to do is to pass it some arguments. Let me give you an example to explain it a bit better. Lets say I have a service, that does nothing but writes something to a log. I'd like to write the ...
Passing arguments to a python service
I need some help with a python service. I have a service written in Python. What I need to do is to pass it some arguments. Let me give you an example to explain it a bit better. Lets say I have a service, that does nothing but writes something to a log. I'd like to write the same thing into the log several times, so I...
[ "Sorry, not enough info to answer your question. This seem an application-specific thing.\nThe only thing I can think is to review the code of win32serviceutil.HandleCommandLine method and WinService class to determine which one writes to the log. Then, you have to make a subclass and override the method responsibl...
[ 0, 0 ]
[]
[]
[ "python", "service" ]
stackoverflow_0003000476_python_service.txt
Q: Python "string_escape" vs "unicode_escape" According to the docs, the builtin string encoding string_escape: Produce[s] a string that is suitable as string literal in Python source code ...while the unicode_escape: Produce[s] a string that is suitable as Unicode literal in Python source code So, they should ha...
Python "string_escape" vs "unicode_escape"
According to the docs, the builtin string encoding string_escape: Produce[s] a string that is suitable as string literal in Python source code ...while the unicode_escape: Produce[s] a string that is suitable as Unicode literal in Python source code So, they should have roughly the same behaviour. BUT, they appear ...
[ "According to my interpretation of the implementation of unicode-escape and the unicode repr in the CPython 2.6.5 source, yes; the only difference between repr(unicode_string) and unicode_string.encode('unicode-escape') is the inclusion of wrapping quotes and escaping whichever quote was used.\nThey are both driven...
[ 26, 14 ]
[]
[]
[ "encoding", "escaping", "python", "python_2.x", "quotes" ]
stackoverflow_0002969044_encoding_escaping_python_python_2.x_quotes.txt
Q: compressed archive with quick access to individual file I need to come up with a file format for new application I am writing. This file will need to hold a bunch other text files which are mostly text but can be other formats as well. Naturally, a compressed tar file seems to fit the bill. The problem is that I w...
compressed archive with quick access to individual file
I need to come up with a file format for new application I am writing. This file will need to hold a bunch other text files which are mostly text but can be other formats as well. Naturally, a compressed tar file seems to fit the bill. The problem is that I want to be able to retrieve some data from the file very quick...
[ "ZIP seems to be appropriate for your situation. Files are compressed individually, which means you access them without streaming through everything before.\nIn Python, you can use zipfile.\n" ]
[ 3 ]
[]
[]
[ "archive", "file_format", "python", "tar" ]
stackoverflow_0003002196_archive_file_format_python_tar.txt
Q: Split a key that is a string of numbers into single digit keys in Python I would like to turn the following dictionary: dictionary = { 4388464: ['getting'] 827862 : ['Taruma', 'Varuna'] ... } into: dictionary = { 4: {3: {8: {8: {4: {6: {4: {'words': ['getting']}}}}}}} 8: {2: {7: {8: {6: {2: {'...
Split a key that is a string of numbers into single digit keys in Python
I would like to turn the following dictionary: dictionary = { 4388464: ['getting'] 827862 : ['Taruma', 'Varuna'] ... } into: dictionary = { 4: {3: {8: {8: {4: {6: {4: {'words': ['getting']}}}}}}} 8: {2: {7: {8: {6: {2: {'words': ['Taruma', 'Varuna']}}}}}} ... } This will then allow me to use t...
[ "import pprint\n\ndictionary = {\n 4388464: ['getting'],\n 43881: ['got'],\n 827862 : ['Taruma', 'Varuna'],\n}\n\nd2 = {}\n\ndef add_it(d, k, words):\n knum = int(k[0])\n if len(k) == 1:\n d[knum] = {'words': words}\n else:\n dsub = d.setdefault(knum, {})\n add_it(dsub, k[1:],...
[ 5, 0, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0002997279_dictionary_python.txt
Q: blank lines in file after sorting content of a text file in python I have this small script that sorts the content of a text file # The built-in function `open` opens a file and returns a file object. # Read mode opens a file for reading only. try: f = open("tracks.txt", "r") try: # Read the enti...
blank lines in file after sorting content of a text file in python
I have this small script that sorts the content of a text file # The built-in function `open` opens a file and returns a file object. # Read mode opens a file for reading only. try: f = open("tracks.txt", "r") try: # Read the entire contents of a file at once. # string = f.read() # OR...
[ "An \"empty\" line read from a text file is represented in Python by a string containing only a newline (\"\\n\"). You may also want to avoid lines whose \"data\" consists only of spaces, tabs, etc (\"whitespace\"). The str.strip() method lets you detect both cases (a newline is whitespace).\nf = open(\"tracks.txt\...
[ 24, 6, 4 ]
[]
[]
[ "python" ]
stackoverflow_0003002392_python.txt
Q: does BeautifulSoup strips inline CSS and javascript content hey guys does beautifulSoup strips css and javascript content? after using content3 = ''.join(BeautifulSoup(content).findAll(text=True)) i still have them lingering around. A: What exactly do you want to strip, all script and style elements? It shoul...
does BeautifulSoup strips inline CSS and javascript content
hey guys does beautifulSoup strips css and javascript content? after using content3 = ''.join(BeautifulSoup(content).findAll(text=True)) i still have them lingering around.
[ "What exactly do you want to strip, all script and style elements? It should be something like:\n''.join(BeautifulSoup(content).findAll(text=lambda text: \ntext.parent.name != \"script\" and \ntext.parent.name != \"style\"))\n\n" ]
[ 0 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0003002534_beautifulsoup_python.txt
Q: Iterating dictionary indexes in django templates I have a dictionary with embedded objects, which looks something like this: notes = { 2009: [<Note: Test note>, <Note: Another test note>], 2010: [<Note: Third test note>, <Note: Fourth test note>], } I'm trying to access each of the note objects inside a d...
Iterating dictionary indexes in django templates
I have a dictionary with embedded objects, which looks something like this: notes = { 2009: [<Note: Test note>, <Note: Another test note>], 2010: [<Note: Third test note>, <Note: Fourth test note>], } I'm trying to access each of the note objects inside a django template, and having a helluva time navigating t...
[ "Try: \n<h3>Notes</h3>\n{% for year, notes in notes.items %}\n {{ year }}\n {% for note in notes %}\n {{ note }}\n {% endfor %}\n{% endfor %}\n\n" ]
[ 8 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0003002728_django_django_templates_python.txt
Q: SQL get data out of BEGIN; ...; END; block in python I want to run many select queries at once by putting them between BEGIN; END;. I tried the following: cur = connection.cursor() cur.execute(""" BEGIN; SELECT ...; END;""") res = cur.fetchall() However, I get the error: psycopg2.ProgrammingError: no results to f...
SQL get data out of BEGIN; ...; END; block in python
I want to run many select queries at once by putting them between BEGIN; END;. I tried the following: cur = connection.cursor() cur.execute(""" BEGIN; SELECT ...; END;""") res = cur.fetchall() However, I get the error: psycopg2.ProgrammingError: no results to fetch How can I actually get data this way? Likewise, if ...
[ "Postgresql doesn't actually support returning multiple result sets from a single command. If you pass this input to psql:\nBEGIN;\nSELECT ...;\nEND;\n\nit will split this up client-side and actually execute three statements, only the second of which returns a result set.\n\"BEGIN\" and \"END\" are SQL-level comman...
[ 4, 0 ]
[]
[]
[ "postgresql", "python", "sql", "sqlobject" ]
stackoverflow_0003002033_postgresql_python_sql_sqlobject.txt
Q: Does Python work in larger teams? I read this post last night and it got me thinking. I like python and "batteries", pypi and such. But I've only done python solo. Never tried it in a team. Are the points that Ted mentions valid? If they are how do teams cope with them? Does Python work in teams or even large team...
Does Python work in larger teams?
I read this post last night and it got me thinking. I like python and "batteries", pypi and such. But I've only done python solo. Never tried it in a team. Are the points that Ted mentions valid? If they are how do teams cope with them? Does Python work in teams or even large teams? Or it kills productivity? I personal...
[ "Python works fine in teams. Whether a language works in large teams is largely a factor of how well the team works together, and has little to do with the language.\n", "I currently work on a large Django app, and in my previous job I worked on a large Java project (desktop app, not web, but still appropriate to...
[ 13, 7, 1, 0 ]
[]
[]
[ "collaboration", "python" ]
stackoverflow_0002999160_collaboration_python.txt
Q: Calling Python app/script from C# I'm building an ASP.NET MVC (C#) site where I want to implement STV (Single Transferable Vote) voting. I've used OpenSTV for voting scenarios before, with great success, but I've never used it programmatically. The OpenSTV Google Code project offers a Python script that allows usa...
Calling Python app/script from C#
I'm building an ASP.NET MVC (C#) site where I want to implement STV (Single Transferable Vote) voting. I've used OpenSTV for voting scenarios before, with great success, but I've never used it programmatically. The OpenSTV Google Code project offers a Python script that allows usage of OpenSTV from other applications: ...
[ "Here is a good example on how to call IronPython from C#, including passing arguments and returning results; of course you'll have to make that code into a function, with ballotFname and reportFname as its arguments.\n", "The best way is probably to use IronPython. See this answer for a starting point.\n" ]
[ 4, 3 ]
[]
[]
[ "asp.net", "asp.net_mvc", "c#", "openstv", "python" ]
stackoverflow_0003002402_asp.net_asp.net_mvc_c#_openstv_python.txt
Q: sql select from a large number of IDs I have a table, Foo. I run a query on Foo to get the ids from a subset of Foo. I then want to run a more complicated set of queries, but only on those IDs. Is there an efficient way to do this? The best I can think of is creating a query such as: SELECT ... --complicated stuff...
sql select from a large number of IDs
I have a table, Foo. I run a query on Foo to get the ids from a subset of Foo. I then want to run a more complicated set of queries, but only on those IDs. Is there an efficient way to do this? The best I can think of is creating a query such as: SELECT ... --complicated stuff WHERE ... --more stuff AND id IN (1, 2, ...
[ "One technique I've used in the past is to put the IDs into a temp table, and then use that to drive a sequence of queries. Something like:\nBEGIN;\nCREATE TEMP TABLE search_result ON COMMIT DROP AS\n SELECT entity_id\n FROM entity /* long complicated search joins and conditions ... */;\n-- Fetch primary entities...
[ 6, 1, 0, 0 ]
[]
[]
[ "postgresql", "python", "sql", "sqlobject" ]
stackoverflow_0003001786_postgresql_python_sql_sqlobject.txt
Q: what is the recommended way of running a embedded web server within a desktop app (say wsgi server with pyqt) The desktop app should start the web server on launch and should shut it down on close. Assuming that the desktop is the only client allowed to connect to the web server, what is the best way to write thi...
what is the recommended way of running a embedded web server within a desktop app (say wsgi server with pyqt)
The desktop app should start the web server on launch and should shut it down on close. Assuming that the desktop is the only client allowed to connect to the web server, what is the best way to write this? Both the web server and the desktop run in a blocking loop of their own. So, should I be using threads or multip...
[ "Use something like CherryPy or paste.httpserver. You can use wsgiref's server, and it generally works okay locally, but if you are doing Ajax the single-threaded nature of wsgiref can cause some odd results, or if you ever do a subrequest you'll get a race condition. But for most cases it'll be fine. It might b...
[ 6, 2, 1 ]
[]
[]
[ "desktop", "pyqt", "python", "user_interface", "wsgi" ]
stackoverflow_0003001185_desktop_pyqt_python_user_interface_wsgi.txt
Q: Python: Access dictionary value inside of tuple and sort quickly by dict value I know that wasn't clear. Here's what I'm doing specifically. I have my list of dictionaries here: dict = [{int=0, value=A}, {int=1, value=B}, ... n] and I want to take them in combinations, so I used itertools and it gave me a tuple (...
Python: Access dictionary value inside of tuple and sort quickly by dict value
I know that wasn't clear. Here's what I'm doing specifically. I have my list of dictionaries here: dict = [{int=0, value=A}, {int=1, value=B}, ... n] and I want to take them in combinations, so I used itertools and it gave me a tuple (Well, okay it gave me a memory object that I then used enumerate on so I could loop ...
[ "for (index, tuple) in enumerate(combinations(dict, 2)):\n thesmall = min(tuple, key=lambda d: d['int'])\n thelarge = max(tuple, key=lambda d: d['int'])\n\nIf you need more than just min and max, then\n inorder = sorted(tuple, key=lambda d: d['int'])\n\nand there you have all the dicts in order as required...
[ 2 ]
[]
[]
[ "dictionary", "python", "sorting", "tuples" ]
stackoverflow_0003003072_dictionary_python_sorting_tuples.txt
Q: sqlobject: No connection has been defined for this thread or process I'm using sqlobject in Python. I connect to the database with conn = connectionForURI(connStr) conn.makeConnection() This succeeds, and I can do queries on the connection: g_conn = conn.getConnection() cur = g_conn.cursor() cur.execute(query) r...
sqlobject: No connection has been defined for this thread or process
I'm using sqlobject in Python. I connect to the database with conn = connectionForURI(connStr) conn.makeConnection() This succeeds, and I can do queries on the connection: g_conn = conn.getConnection() cur = g_conn.cursor() cur.execute(query) res = cur.fetchall() This works as intended. However, I also defined some ...
[ "Do:\nfrom sqlobject import sqlhub, connectionForURI\n\nsqlhub.processConnection = connectionForURI(connStr)\n\n" ]
[ 3 ]
[]
[]
[ "python", "sql", "sqlobject" ]
stackoverflow_0003000908_python_sql_sqlobject.txt
Q: averaging matrix efficiently in Python, given an n x p matrix, e.g. 4 x 4, how can I return a matrix that's 4 x 2 that simply averages the first two columns and the last two columns for all 4 rows of the matrix? e.g. given: a = array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [1...
averaging matrix efficiently
in Python, given an n x p matrix, e.g. 4 x 4, how can I return a matrix that's 4 x 2 that simply averages the first two columns and the last two columns for all 4 rows of the matrix? e.g. given: a = array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]) return a matrix t...
[ "How about using some math? You can define a matrix M = [[0.5,0],[0.5,0],[0,0.5],[0,0.5]] so that A*M is what you want.\nfrom numpy import array, matrix\n\nA = array([[1, 2, 3, 4], \n [5, 6, 7, 8], \n [9, 10, 11, 12], \n [13, 14, 15, 16]])\nM = matrix([[0.5,0],\n [0.5,0],\n ...
[ 5, 4, 1, 1 ]
[]
[]
[ "numpy", "python", "scipy" ]
stackoverflow_0002978323_numpy_python_scipy.txt
Q: What is a more efficient way in Python to return list elements which are not in a second list? Is there a faster way to do this in python? [f for f in list_1 if not f in list_2] list_1 and list_2 both consist of about 120.000 strings. It takes about 4 minutes to generate the new list. A: If you put list_2 into ...
What is a more efficient way in Python to return list elements which are not in a second list?
Is there a faster way to do this in python? [f for f in list_1 if not f in list_2] list_1 and list_2 both consist of about 120.000 strings. It takes about 4 minutes to generate the new list.
[ "If you put list_2 into a set, it should make the containment checking a lot quicker:\ns = set(list_2)\n[f for f in list_1 if not f in s]\n\nThis is because x in list is an O(n) check, while x in set is constant-time. \nAnother way is to use set-difference:\nlist(set(list_1).difference(set(list_2)))\n\nHowever, thi...
[ 9, 4 ]
[]
[]
[ "python" ]
stackoverflow_0003003390_python.txt
Q: Specifying custom URL schema in appengine using app.yaml? I am trying to have a custom URL which looks like this: example.com/site/yahoo.com which would hit this script like this= example.com/details?domain=yahoo.com can this be done using app.yaml? the basic idea is to call "details" with the input "yahoo.com" ...
Specifying custom URL schema in appengine using app.yaml?
I am trying to have a custom URL which looks like this: example.com/site/yahoo.com which would hit this script like this= example.com/details?domain=yahoo.com can this be done using app.yaml? the basic idea is to call "details" with the input "yahoo.com"
[ "You can't really rewrite the URLs per se, but you can use regular expression groups to perform a similar kind of thing.\nIn your app.yaml file, try something like:\nhandlers:\n- url: /site/(.+)\n script: site.py\n\nAnd in your site.py:\nSiteHandler(webapp.RequestHandler):\n def get(self, site):\n # the ...
[ 4 ]
[]
[]
[ "google_app_engine", "python", "rewrite" ]
stackoverflow_0003003624_google_app_engine_python_rewrite.txt
Q: facing problem when trying to send an email using python I wrote the code like this import smtplib server=smtplib.SMTP('localhost') Then it raised an error like error: [Errno 10061] No connection could be made because the target machine actively refused it I am new to SMTP, can you tell what exactly the proble...
facing problem when trying to send an email using python
I wrote the code like this import smtplib server=smtplib.SMTP('localhost') Then it raised an error like error: [Errno 10061] No connection could be made because the target machine actively refused it I am new to SMTP, can you tell what exactly the problem is?
[ "It sounds like SMTP is not set up on the computer you are trying this from. Try using your ISP's mail server (often something like mail.example.com) or make sure you have an SMTP server installed locally.\n", "Rather than trying to install smtp library locally, you can setup a simple smtp server on a console.\nD...
[ 2, 2, 0 ]
[]
[]
[ "python", "smtp" ]
stackoverflow_0003004006_python_smtp.txt
Q: How to get progress bar to time Class exectution I am trying to use progress bar to show the progress of a script. I want it increase progress after every function in a class is executed. The code I have tried is below: import progressbar from time import sleep class hello(): def no(self): print 'hell...
How to get progress bar to time Class exectution
I am trying to use progress bar to show the progress of a script. I want it increase progress after every function in a class is executed. The code I have tried is below: import progressbar from time import sleep class hello(): def no(self): print 'hello!' def yes(self): print 'No!!!!!!' def...
[ "does this do what you want ?\nimport progressbar\nfrom time import sleep\n\nclass hello():\n def no(self):\n print 'hello!'\n\n def yes(self):\n print 'No!!!!!!'\n\n def __call__(self) :\n methods = [self.no, self.yes]\n return [ (x[0]*100/len(methods), x[1]) for x in enumerat...
[ 2 ]
[]
[]
[ "class", "progress_bar", "python" ]
stackoverflow_0003004533_class_progress_bar_python.txt
Q: KindError: Property r must be an instance of SecondModel, why? class FirstModel(db.Model): p = db.StringProperty() r=db.ReferenceProperty(SecondModel) class SecondModel(db.Model): r = db.ReferenceProperty(FirstModel) class sss(webapp.RequestHandler): def get(self): a=FirstModel() a.p='sss' ...
KindError: Property r must be an instance of SecondModel, why?
class FirstModel(db.Model): p = db.StringProperty() r=db.ReferenceProperty(SecondModel) class SecondModel(db.Model): r = db.ReferenceProperty(FirstModel) class sss(webapp.RequestHandler): def get(self): a=FirstModel() a.p='sss' a.put() b=SecondModel() b.r=a b.put() a.r=b ...
[ "The code you show shouldn't even compile - you can't instantiate a reference property with a class that isn't yet defined - unless you have another definition of SecondModel somewhere that you haven't included, in which case the issue is that FirstModel has a reference to the original SecondModel, but you're passi...
[ 0, -2 ]
[]
[]
[ "google_app_engine", "model", "properties", "python" ]
stackoverflow_0003003845_google_app_engine_model_properties_python.txt
Q: Encrypt and Decrypt information in a cookie I need to securely crypt and decrypt information about users ( name, surname and user_id ) in cookies. What is the best way to do this ? What encryption and decryption function do I need ? Thanks ^_^ A: It's generally a bad idea: an attacker can do chosen-text dictiona...
Encrypt and Decrypt information in a cookie
I need to securely crypt and decrypt information about users ( name, surname and user_id ) in cookies. What is the best way to do this ? What encryption and decryption function do I need ? Thanks ^_^
[ "It's generally a bad idea: an attacker can do chosen-text dictionary attacks if they can guess what you might be putting in the cookie, which is quite likely, and securing a universal key is harder than looking after a database containing confidential information, because there is not much in the way of an audit t...
[ 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003004551_django_python.txt
Q: Django admin urls return INVALID REQUEST! - Django my admin urls are sat behind a prefix by doing the following. 1# (r'^admin/', include(admin.site.urls)), is placed within urls_core.py 2# (r'^api/', include('project.urls_core')), is palced within urls.py All admin URLs work fine except app indexes. If I go to...
Django admin urls return INVALID REQUEST! - Django
my admin urls are sat behind a prefix by doing the following. 1# (r'^admin/', include(admin.site.urls)), is placed within urls_core.py 2# (r'^api/', include('project.urls_core')), is palced within urls.py All admin URLs work fine except app indexes. If I go to any URL such as: /api/admin/core/ /api/admin/registrat...
[ "I think some middleware, that strips the leading api/ from the url should help you:\nimport re\n\nclass URLPrefixMiddleware:\n def process_request(self, request):\n request.path = re.sub('^api/','',request.path)\n\nYou shouldn't need your additional URL configuration then anymore. Put it in middleware.py...
[ 1 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0003004736_django_django_admin_python.txt
Q: ANT doesn't get exit code return by a python script I'm currently using ant for building my java project on a Windows XP machine. I have different tasks defined in the build.xml and one of this is the exec of a Python script for analyzing the application output. I would like to make ANT failing when a particolar t...
ANT doesn't get exit code return by a python script
I'm currently using ant for building my java project on a Windows XP machine. I have different tasks defined in the build.xml and one of this is the exec of a Python script for analyzing the application output. I would like to make ANT failing when a particolar tag is discovered by script. I'm trying using: sys.exit(1)...
[ "Try this:\n<exec dir=\"${path}/scripts\" executable=\"python\" failonerror=\"true\">\n <arg line=\"log_analysis.py results.log\" />\n</exec>\n\nAnt does not stop the build process if the command exits with a return code signaling failure by default; you have to set failonerror=\"true\" to do that.\n" ]
[ 17 ]
[]
[]
[ "ant", "build", "python", "scripting" ]
stackoverflow_0003004057_ant_build_python_scripting.txt
Q: Is there a way to set a fixed width for the characters in HTML? Is there a way to set a fix size for the characters in HTML? That means, say … First row, 8th character is “Z” Second row’s 8th character is “A” I want to print out , when printed the “Z” has to be exactly on top of “A” *Note: I'm using the insertHtml...
Is there a way to set a fixed width for the characters in HTML?
Is there a way to set a fix size for the characters in HTML? That means, say … First row, 8th character is “Z” Second row’s 8th character is “A” I want to print out , when printed the “Z” has to be exactly on top of “A” *Note: I'm using the insertHtml method in QTextEdit()
[ "What you're asking for is called a fixed-width font. As James Hopkin remarked, HTML text in <tt> or <pre> tags is rendered with a fixed-width font. \nHowever, what you describe sounds like a table. HTML has direct support for that, with <table>, <tr> (row) and <td> (data/cell). Don't bother with fixed-width fonts;...
[ 3, 0 ]
[]
[]
[ "pyqt4", "python", "qtextedit" ]
stackoverflow_0003005063_pyqt4_python_qtextedit.txt
Q: encrypting passwords in a python conf file on a windows platform I have a script running on a remote machine. db info is stored in a configuration file. I want to be able to encrypt the password in the conf text so that no one can just read the file and gain access to the database. This is my current set up: My co...
encrypting passwords in a python conf file on a windows platform
I have a script running on a remote machine. db info is stored in a configuration file. I want to be able to encrypt the password in the conf text so that no one can just read the file and gain access to the database. This is my current set up: My conf file sensitive info is encoded with base64 module. The main script ...
[ "If you want to be able to get back the password (instead you should hash it), you could always salt it for extra measures. But that wouldn't be much help if the user can get the salt out of the executable. \nReally the best way would be to not let them access the database at all. Use a web service or a server on y...
[ 0, 0 ]
[]
[]
[ "encryption", "passwords", "python", "windows" ]
stackoverflow_0003005632_encryption_passwords_python_windows.txt
Q: Problem with TCP server in Twisted I'm trying to make a simple TCP server using Twisted ,which can do some interaction between diffirent client connections.The main code is as below: #!/usr/bin/env python from twisted.internet import protocol, reactor from time import ctime #global variables PORT = 22334 connlist...
Problem with TCP server in Twisted
I'm trying to make a simple TCP server using Twisted ,which can do some interaction between diffirent client connections.The main code is as below: #!/usr/bin/env python from twisted.internet import protocol, reactor from time import ctime #global variables PORT = 22334 connlist = {} #store all the connections ids ...
[ "Each time a TCP connection is made, Twisted will create a unique instance of TSServerProtocol to handle that connection. So, you'll only ever see 1 connection in TSServerProtocol. Normally, this is what you want but Factories can be extended to do the connection tracking you're attempting to do here. Specifically,...
[ 3 ]
[]
[]
[ "python", "tcp", "twisted" ]
stackoverflow_0003004227_python_tcp_twisted.txt
Q: Are there any builds of Unladen Swallow available? I realise there aren't any official ones, but I was hoping I could grab an unofficial one from somewhere? I'm running 32-bit Windows XP on x86 hardware (Core 2 Duo). A: For the time being, there are no official Windows binaries, so you have to build them on your...
Are there any builds of Unladen Swallow available?
I realise there aren't any official ones, but I was hoping I could grab an unofficial one from somewhere? I'm running 32-bit Windows XP on x86 hardware (Core 2 Duo).
[ "For the time being, there are no official Windows binaries, so you have to build them on your own.\nDownload a release from here, and the instructions for building are here: BuildingOnWindows.\nA quick Google search suggests that there aren't any others who've followed this procedure and published the results.\n" ...
[ 1 ]
[]
[]
[ "python", "unladen_swallow" ]
stackoverflow_0002818899_python_unladen_swallow.txt
Q: Correct way to protect a private API Key when versioning a python application on a public git repo I would like to open-source a python project on Github but it contains an API key that should not be distributed. I guess there's something better than removing the key each time a "push" is committed to the repo. Im...
Correct way to protect a private API Key when versioning a python application on a public git repo
I would like to open-source a python project on Github but it contains an API key that should not be distributed. I guess there's something better than removing the key each time a "push" is committed to the repo. Imagine a simplified foomodule.py : import urllib2 API_KEY = 'XXXXXXXXX' urllib2.urlopen("http://example.c...
[ "One way would be to make it an explicit part of the interface. Make it an argument for your object constructors, for example. Or require the client to extend your class and provide a method, returning the key.\nIt sucks when one needs to edit your module before she can use it.\n", "have a versioned template key_...
[ 1, 1 ]
[]
[]
[ "configuration", "python", "version_control" ]
stackoverflow_0003006132_configuration_python_version_control.txt
Q: Django message doesn't expire My code in the view: from django.contrib import messages messages.add_message(request, messages.INFO, 'Hello world.') I don't want to show this code to the user the second time if he/she refreshes again. How do I go about doing that? Messages don't seem to have any sort of expi...
Django message doesn't expire
My code in the view: from django.contrib import messages messages.add_message(request, messages.INFO, 'Hello world.') I don't want to show this code to the user the second time if he/she refreshes again. How do I go about doing that? Messages don't seem to have any sort of expiry setting. There is documentation ...
[ "Messages are cleared as soon as you iterate messages (which should be available from RequestContext).\nSo step one is making sure you're displaying messages! If you want to hold-off on displaying messages for a certain page, you'll perhaps want to investigate punching things into session but it's getting a bit mes...
[ 5 ]
[]
[]
[ "django", "frameworks", "messages", "python", "session" ]
stackoverflow_0003006041_django_frameworks_messages_python_session.txt
Q: Random Loss of precision in Python ReadLine() We have a process which takes a very large csv (1.6GB) and breaks it down into pieces (in this case 3). This runs nightly and normally doesn't give us any problems. When it ran last night, however, the first of the output files had lost precision on the numeric fiel...
Random Loss of precision in Python ReadLine()
We have a process which takes a very large csv (1.6GB) and breaks it down into pieces (in this case 3). This runs nightly and normally doesn't give us any problems. When it ran last night, however, the first of the output files had lost precision on the numeric fields in the data. The active ingredient in the scri...
[ ".readline() doesn't do anything with the content of the line, certainly not with numbers, so it's definitely not the culprit. \nThanks for giving more info, but this still looks very mysterious to me as neither function should be causing such a change. You didn't open the output in Excel, by any chance? Sometimes ...
[ 1 ]
[]
[]
[ "file_io", "python" ]
stackoverflow_0003006378_file_io_python.txt
Q: Python class decorator and maximum recursion depth exceeded I try define class decorator. I have problem with __init__ method in decorated class. If __init__ method invokes super the RuntimeError maximum recursion depth exceeded is raised. Code example: def decorate(cls): class NewClass(cls): pass return ...
Python class decorator and maximum recursion depth exceeded
I try define class decorator. I have problem with __init__ method in decorated class. If __init__ method invokes super the RuntimeError maximum recursion depth exceeded is raised. Code example: def decorate(cls): class NewClass(cls): pass return NewClass @decorate class Foo(object): def __init__(self, *ar...
[ "Remember that a decorator is simply syntactic sugar for:\n>>> Foo = decorate(Foo)\n\nSo in this case the name Foo actually refers to the NewClass class. Within the Foo.__init__ method you are in fact asking for the super __init__ of NewClass, which is Foo.__init__ (which is what is currently running).\nThus, your ...
[ 5, 5 ]
[]
[]
[ "class", "decorator", "python" ]
stackoverflow_0003005945_class_decorator_python.txt