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: Python: Is it possible to set the clientport with xmlrpclib? Is it possible to set the clientport for the xmlrpc-connection? I want to say: Client should make a ServerProxy-object to over a specific client port or pseudocode something like this: serv = xmlrpclib.ServerProxy("server:port","overSpecificClientPo...
Python: Is it possible to set the clientport with xmlrpclib?
Is it possible to set the clientport for the xmlrpc-connection? I want to say: Client should make a ServerProxy-object to over a specific client port or pseudocode something like this: serv = xmlrpclib.ServerProxy("server:port","overSpecificClientPort").
[ "Try to define a custom transport. This should be something like that:\nimport xmlrpclib, httplib\n\nclass sourcedTransport(xmlrpclib.Transport):\n def setSource(self, src):\n self.src = src\n def make_connection(self, host):\n h = httplib.HTTPConnection(host, source_address= self.src)\n ...
[ 1 ]
[ "There is no option for this in module xmlrpclib, but you can create your own by modifying the original version. Assuming you use Linux, fetch /usr/lib/python2.7/xmlrpclib.py. Modify the method make_connection accordingly.\nProviding a parameter source_address to HTTPConnection is supported by httplib not before Py...
[ -2 ]
[ "python", "xml_rpc", "xmlrpclib" ]
stackoverflow_0007269849_python_xml_rpc_xmlrpclib.txt
Q: Django - ModelAdmin media definition I'm trying to include some CSS and JS files into the change form of an object like specified in the doc. Here are me files: admin.py #... class ScribPartAdmin(admin.ModelAdmin): class Media: css = { 'all': ('mymarkup.css',) } js = ('mymarkup.js',) admin.sit...
Django - ModelAdmin media definition
I'm trying to include some CSS and JS files into the change form of an object like specified in the doc. Here are me files: admin.py #... class ScribPartAdmin(admin.ModelAdmin): class Media: css = { 'all': ('mymarkup.css',) } js = ('mymarkup.js',) admin.site.register(ScribPart, ScribPartAdmin) #......
[ "Because I was not pointing to the good locations:\n#...\nclass ScribPartAdmin(admin.ModelAdmin):\n class Media:\n css = {\n 'all': ('css/mymarkup.css',)\n }\n js = ('javascript/mymarkup.js',)\n\nadmin.site.register(ScribPart, ScribPartAdmin)\n#...\n\nis better.\nApparently Django includes medias tha...
[ 5 ]
[]
[]
[ "django", "django_modeladmin", "media", "python" ]
stackoverflow_0007270558_django_django_modeladmin_media_python.txt
Q: How to retrieve a subset of embedded documents in MongoDB? I have a User document, which has an array of embedded log event documents, of which have dates and times as well as other info. Is there any way I can retrieve the User document and ONLY a subset of the embedded log events, based on date? A: It's not po...
How to retrieve a subset of embedded documents in MongoDB?
I have a User document, which has an array of embedded log event documents, of which have dates and times as well as other info. Is there any way I can retrieve the User document and ONLY a subset of the embedded log events, based on date?
[ "It's not possible at the moment.\nAs of 1.5.1, you can use the $slice operator to do something similar, but only if your log objects are already ordered by date (which theoretically should be the case because you generally don't log something in the past):\n> db.User.findOne({}, {\"logs\":{$slice: -2}}) // last tw...
[ 0 ]
[]
[]
[ "mongodb", "pymongo", "python" ]
stackoverflow_0007264542_mongodb_pymongo_python.txt
Q: GTK+ Dock Panel like visual component I'm developing a small desktop application using python. I want it to be multi platform, and have a GUI similar (but simpler) to Eclipse. I know that the component that works just like eclipse layout are called DockPanel in Microsoft .NET. Can someone help me out? Since eclips...
GTK+ Dock Panel like visual component
I'm developing a small desktop application using python. I want it to be multi platform, and have a GUI similar (but simpler) to Eclipse. I know that the component that works just like eclipse layout are called DockPanel in Microsoft .NET. Can someone help me out? Since eclipse is developed in GTK+ I guess I need only ...
[ "In GTK+ there is a docking library called gdl which is used by Anjuta IDE for example. However, this would not be a very cooperative solution for cross-platform use. I think MonoDevelop built there docking library based on this, but I could be wrong about that.\nI've personally used this application in a PyGTK (GT...
[ 1, 0, 0 ]
[]
[]
[ "desktop", "dockpanel", "gtk", "python", "qt" ]
stackoverflow_0007208401_desktop_dockpanel_gtk_python_qt.txt
Q: read data from file, store in a python dict and search for values in python I had a text file with some information like this: A , 12 B , 34 A , 54 F , 60 I want to read the file, and store the information in a python dictionary, like this: {'A':['12','54',...], B:['34',....]...} and so on. But I am stuck with ho...
read data from file, store in a python dict and search for values in python
I had a text file with some information like this: A , 12 B , 34 A , 54 F , 60 I want to read the file, and store the information in a python dictionary, like this: {'A':['12','54',...], B:['34',....]...} and so on. But I am stuck with how to search every A in lines. This is my tried: repo = {} infile = open('...
[ "There is not such a data structure like {A:{12,54,...}, B:{34,....}. However:\nrepo = {}\ninfile = open('test10.log','r')\nlines = infile.readlines()[2:-1]\nfor i in lines:\n module, time = [a.strip() for a in i.split(',')]\n repo.setdefault(module, []).append(int(time))\n\nwill give you a dict of lists:\n{'...
[ 3, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0007266747_dictionary_python.txt
Q: How to pass variables to a form before it is processed I have the following template form, containing several variables. <form action="https://me.s3.amazonaws.com/" method="post" enctype='multipart/form-data' class="upload-form"> <input type="hidden" name="key" value="videos/{{filename}}"> <input type="hid...
How to pass variables to a form before it is processed
I have the following template form, containing several variables. <form action="https://me.s3.amazonaws.com/" method="post" enctype='multipart/form-data' class="upload-form"> <input type="hidden" name="key" value="videos/{{filename}}"> <input type="hidden" name="AWSAccessKeyId" value="{{access_key}}"> <inp...
[ "You should change your form's action to your django view and in your view you can re-post to https://me.s3.amazonaws.com/:\nIn your template\n<form action=\"http://mywebsite/upload\" method=\"post\" ...\n\nIn your view.py:\ndef upload(request):\n # Your treatment here.\n # Post the data to amazon S3.\n ur...
[ 2, 0 ]
[]
[]
[ "amazon_s3", "django", "forms", "http_headers", "python" ]
stackoverflow_0007270895_amazon_s3_django_forms_http_headers_python.txt
Q: How to clear stdout in Python subprocess? this snippet will ping an ip address in windows and get output line each 2 seconds, however, I found there's a very slowly memory increasement of ping.exe process after run it, if I deploy it to ping 1000 ip parallel, soon it will cause server hang, I think it may because ...
How to clear stdout in Python subprocess?
this snippet will ping an ip address in windows and get output line each 2 seconds, however, I found there's a very slowly memory increasement of ping.exe process after run it, if I deploy it to ping 1000 ip parallel, soon it will cause server hang, I think it may because of stdout buffer, may I know how to clear the s...
[ "ping is producing many more lines than you're reading due to the 2 second timeout between reads. I'd move the os.kill call into another thread, and use the main thread to read every line from proc.stdout:\nimport sys, os\nimport subprocess\nimport threading\nimport signal\nimport time\n\n#Use ctrl-c and ctrl-break...
[ 1, 0 ]
[]
[]
[ "memory", "ping", "python" ]
stackoverflow_0007268960_memory_ping_python.txt
Q: Python Class Initialization and Memory Model Behavior I know this has been documented somewhere on Stack Overflow, but I can't for the life of me find it... I'll be happy to accept any relevant links. I have the following code: class A: def __init__(self, x=[]): x += [1] print id(x), x print "...
Python Class Initialization and Memory Model Behavior
I know this has been documented somewhere on Stack Overflow, but I can't for the life of me find it... I'll be happy to accept any relevant links. I have the following code: class A: def __init__(self, x=[]): x += [1] print id(x), x print "Try with default:" a = A() b = A() c = A() d = A() print "...
[ "@agf came up with the link that answers the question: \"Least Astonishment\" and the Mutable Default Argument\nThe accepted response for that link points to the following useful explanation: http://effbot.org/zone/default-values.htm\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0007270761_python.txt
Q: Problem with Vim omnicomplete and system Python I have Vim set up, with +python (:version says it's ok). My .vimrc contains filetype plugin on set ofu=syntaxcomplete#Complete autocmd FileType python setlocal omnifunc=pythoncomplete#Complete When some .py file is open, and I type i.e. pri and press Ctrl-X, Ctrl-O,...
Problem with Vim omnicomplete and system Python
I have Vim set up, with +python (:version says it's ok). My .vimrc contains filetype plugin on set ofu=syntaxcomplete#Complete autocmd FileType python setlocal omnifunc=pythoncomplete#Complete When some .py file is open, and I type i.e. pri and press Ctrl-X, Ctrl-O, it says no pattern was found? Am I missing something...
[ "Rather than syntaxcomplete#Complete, use pythoncomplete#Complete:\n# ~/.vim/ftplugin/python.vim\nsetlocal omnifunc=pythoncomplete#Complete\n\n# Or by autocmd\nautocmd FileType python setlocal omnifunc=pythoncomplete#Complete\n\n\n" ]
[ 3 ]
[]
[]
[ "omnicomplete", "python", "vim" ]
stackoverflow_0007271129_omnicomplete_python_vim.txt
Q: Python transform while-loop into a generator function I want to replace and optimize an extensively used while-loop that generates list values from an input list. How can this be accomplished with iter, itertools, a generator function or something else? The following example code is for illustration only: thisli...
Python transform while-loop into a generator function
I want to replace and optimize an extensively used while-loop that generates list values from an input list. How can this be accomplished with iter, itertools, a generator function or something else? The following example code is for illustration only: thislist = [2, 8, 17, 5, 41, 77, 3, 11] newlist = [] index = 0 ...
[ "You can do it with a generator. It yields the next value every time you call \"next\" on it.\ndef my_gen(data):\n for index in range(0, len(data)-1):\n value = data[index]\n value += 2 * value\n #etc\n yield value\n\nmy_list = [2, 8, 17, 5, 41, 77, 3, 11]\nx = my_gen(my_list)\nprint ...
[ 0 ]
[]
[]
[ "generator", "list", "optimization", "python", "while_loop" ]
stackoverflow_0007271362_generator_list_optimization_python_while_loop.txt
Q: How to call Python script from Android Is it possible in Android to call Python script? I have already some scripts in Python 2.7 and I want to call that from Android(that script create file and fills with data). To be more specific I am trying to execute Python script on phone, that script connects to some site, ...
How to call Python script from Android
Is it possible in Android to call Python script? I have already some scripts in Python 2.7 and I want to call that from Android(that script create file and fills with data). To be more specific I am trying to execute Python script on phone, that script connects to some site, download data and do some intelligence and t...
[ "With googles SL4A-project, it's possible to have Python-scripts execute on your Android phone.\nParts of the Android API are wrapped for Python (but not all of it)\nYou can embed Python-scripts in your application (sounds like your approach).\n" ]
[ 5 ]
[]
[]
[ "android", "python" ]
stackoverflow_0007271299_android_python.txt
Q: Python based SVM library Is there a Python based library providing an SVM implementation with a GPL or any other opensource license? I have come across a few that provide an SVM wrapper for the SVM logic encoded in C, but none that are coded entirely in Python. Regards, Mandar A: libsvm has Python bindings. Edi...
Python based SVM library
Is there a Python based library providing an SVM implementation with a GPL or any other opensource license? I have come across a few that provide an SVM wrapper for the SVM logic encoded in C, but none that are coded entirely in Python. Regards, Mandar
[ "libsvm has Python bindings.\nEdit\nGoogling found PyML, but I haven't used it.\n", "You might want to check out this link, it has a big collection of machine learning software, it lists 50+ libraries that have been written in Python:\nhttp://mloss.org/software/language/python/\n" ]
[ 2, 1 ]
[]
[]
[ "machine_learning", "python", "svm" ]
stackoverflow_0007253668_machine_learning_python_svm.txt
Q: Django - Include a media into a specific admin page If I have this kind of modelAdmin: admin.py #... class ScribPartAdmin(admin.ModelAdmin): class Media: css = { 'all': ('css/mymarkup.css',) } admin.site.register(ScribPart, ScribPartAdmin) #... mymarkup.css is actually included in all the pages c...
Django - Include a media into a specific admin page
If I have this kind of modelAdmin: admin.py #... class ScribPartAdmin(admin.ModelAdmin): class Media: css = { 'all': ('css/mymarkup.css',) } admin.site.register(ScribPart, ScribPartAdmin) #... mymarkup.css is actually included in all the pages concerning the object ScribPart. How can I specify in whic...
[ "To the best of my knowledge, you would need to override the template files for these views. You can inherit from the default template files, and just add your custom CSS in the extrahead block.\n", "You can load a .js file wich load a specific css file for each page.\n" ]
[ 3, 0 ]
[]
[]
[ "django", "django_modeladmin", "media", "python" ]
stackoverflow_0007270963_django_django_modeladmin_media_python.txt
Q: Python generator's 'yield' in separate function I'm implementing a utility library which is a sort-of task manager intended to run within the distributed environment of Google App Engine cloud computing service. (It uses a combination of task queues and memcache to execute background processing). I plan to use gen...
Python generator's 'yield' in separate function
I'm implementing a utility library which is a sort-of task manager intended to run within the distributed environment of Google App Engine cloud computing service. (It uses a combination of task queues and memcache to execute background processing). I plan to use generators to control the execution of tasks, essentiall...
[ "You seem to be missing the obvious:\nclass EntityWorker(Worker):\n def setup(self):\n self.entity_query = Entity.all()\n\n def run(self):\n for e in self.entity_query:\n do_something_with(e)\n yield self.sleep(timedelta(seconds=1))\n\n def sleep(self, wait):\n re...
[ 3, 2, 1 ]
[]
[]
[ "generator", "google_app_engine", "python" ]
stackoverflow_0007269613_generator_google_app_engine_python.txt
Q: eclipse+pydev how to rename module? I'm using eclipse + pydev. I want to refactor and change the name of my module. I clicked on my module in the package explorer, but no refactoring (other than 'rename') in the context menu. Similarly, the refactoring on the top navigation menu is greyed out. So how do i change m...
eclipse+pydev how to rename module?
I'm using eclipse + pydev. I want to refactor and change the name of my module. I clicked on my module in the package explorer, but no refactoring (other than 'rename') in the context menu. Similarly, the refactoring on the top navigation menu is greyed out. So how do i change my module name and have it reflected acros...
[ "This feature is still not properly integrated in the pydev package explorer, so, for now, you have to find a place that uses the module you want in the code and rename that reference in the editor (you don't need to report that as a bug as that's already known and should be fixed soon).\n", "Did you try rename? ...
[ 2, 1 ]
[]
[]
[ "eclipse", "pydev", "python" ]
stackoverflow_0007268426_eclipse_pydev_python.txt
Q: py2app setup.py usage question Ok so I'm trying to use py2app to generate a distribution for my project. I'm still not sure I get the hang of it tho. So my setup.py looks like this: """ This is a setup.py script generated by py2applet Usage: python setup.py py2app """ from setuptools import setup import setu...
py2app setup.py usage question
Ok so I'm trying to use py2app to generate a distribution for my project. I'm still not sure I get the hang of it tho. So my setup.py looks like this: """ This is a setup.py script generated by py2applet Usage: python setup.py py2app """ from setuptools import setup import setuptools PACKAGES = ['sqlalchemy.dial...
[ "Well seems I got the whole thing wrong. \n'includes' : ['sqlalchemy.dialects.sqlite']\n\nInstead of packages, and that seems to have done the trick.\n" ]
[ 3 ]
[]
[]
[ "py2app", "python" ]
stackoverflow_0007270554_py2app_python.txt
Q: How to get the difference in Localtime and GMT time python? I get the server date and I need to get the difference of this date from GMT I get Datetime = "2011-04-27 2:17:45" I would like to get the result like Datetime = "2011-04-27 2:17:45 +0500" A: Try this: import datetime, pytz now = datetime.datetime.now...
How to get the difference in Localtime and GMT time python?
I get the server date and I need to get the difference of this date from GMT I get Datetime = "2011-04-27 2:17:45" I would like to get the result like Datetime = "2011-04-27 2:17:45 +0500"
[ "Try this:\nimport datetime, pytz\nnow = datetime.datetime.now(pytz.timezone('Asia/Kolkata'))\n\nprint now.strftime('%Y-%m-%d %H:%M:%S %z')\n\n# prints: '2011-04-27 13:56:09 +0530'\n\n", "From the example you have given, it looks to me that what you are looking for is datetime.isoformat. The example in the page s...
[ 3, 0, 0, 0, 0, 0 ]
[]
[]
[ "datetime", "python", "timezone" ]
stackoverflow_0005800924_datetime_python_timezone.txt
Q: Read Non Blocking error while using pxssh (ssh module for python) I am trying to do ssh on a remote machine using a python script using pxssh moudule. Here are the lines of code that I use for the same : s = pxssh.pxssh() s.login (hostip,'root',auto_prompt_reset=False) But this gives me the following TIME...
Read Non Blocking error while using pxssh (ssh module for python)
I am trying to do ssh on a remote machine using a python script using pxssh moudule. Here are the lines of code that I use for the same : s = pxssh.pxssh() s.login (hostip,'root',auto_prompt_reset=False) But this gives me the following TIMEOUT error. Traceback (most recent call last): File "<stdin>", line ...
[ "I have changed the python library and instead using paramiko which is much more stable and doesn't give the above error.\n", "I had the same problem. This post ( http://bytes.com/topic/python/answers/760027-read_nonblocking-error-pxssh ) had the solution. \n\"I just added a self.sendline() and a time.sleep(0.5) ...
[ 3, 2 ]
[]
[]
[ "python", "ssh" ]
stackoverflow_0006012665_python_ssh.txt
Q: python string replace is deleting whitespace incorrectly I have a method def strip_searchname(self, original_name): taboo = {" and ", " of ", " at ", " in ", ":", "-", ",", " the ", " "} searchname = original_name for word in taboo: print(searchname) searchname = searchname.replace(word...
python string replace is deleting whitespace incorrectly
I have a method def strip_searchname(self, original_name): taboo = {" and ", " of ", " at ", " in ", ":", "-", ",", " the ", " "} searchname = original_name for word in taboo: print(searchname) searchname = searchname.replace(word, "") searchname = re.sub('[^a-zA-Z]', "", searchname) ...
[ "\nWhat I DON'T understand is why it seems to be executing the \" \"\n replace BEFORE the \" of \" replace, for example, when the \" of \"\n replace comes before the space in the list.\n\nIt's not a list. \ntaboo = {\" and \", \" of \", \" at \", \" in \", \":\", \"-\", \",\", \" the \", \" \"}\n\nis a set liter...
[ 10, 0, 0 ]
[]
[]
[ "python", "replace", "string", "whitespace" ]
stackoverflow_0007272758_python_replace_string_whitespace.txt
Q: Increase each list element in all possible ways I have a list: test = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] Need to increase each list element in all possible ways using Python standard library. It's a puzzle, and I've already done this: test = [elem + 1 for elem in test] for i in range(len(test)): test[i] += 1 test = ...
Increase each list element in all possible ways
I have a list: test = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] Need to increase each list element in all possible ways using Python standard library. It's a puzzle, and I've already done this: test = [elem + 1 for elem in test] for i in range(len(test)): test[i] += 1 test = map(lambda x : x + 1, test) test = [sum(elem) for el...
[ "You could use recursion, (and you could use True and False instead of 1 and 0, but that's just crazy talk):\ndef recurseadd(test):\n if test:\n return [test[False] + True] + recurseadd(test[True:])\n else:\n return test\n\nInstead of that + you could use [test[0] + 1].extend(recurseadd(test[1:]...
[ 3, 2, 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0007272643_list_python.txt
Q: How to map a function to a triple nested list and keep the triple nested list intact? I've have been building an analysis workflow for my PhD and have been using a triple nested list to represent my data structure because I want it to be able to expand to an arbitrary amount of data in its second and third levels....
How to map a function to a triple nested list and keep the triple nested list intact?
I've have been building an analysis workflow for my PhD and have been using a triple nested list to represent my data structure because I want it to be able to expand to an arbitrary amount of data in its second and third levels. The first level is the whole dataset, the second level is each subject in the dataset and ...
[ "Rather than doing it in place, make a new list\n dataset = [[[float(value) for value in measure] \n for measure in subject] \n for subject in dataset] \n\n", "return [[map(float, measure) for measure in subject] for subject in dataset]\nYou can return a list in...
[ 14, 3, 2, 2 ]
[]
[]
[ "list", "nested", "python" ]
stackoverflow_0007273164_list_nested_python.txt
Q: In a GQL query what ANCESTOR IS :1 exactly means? I have come across with GQL queries containing ANCESTOR IS :1. So, what the ancestor is and what :1 stands for? query = db.GqlQuery("SELECT * " "FROM my_db " "WHERE ANCESTOR IS :1 AND answer > :3 AND ch = :4 " ...
In a GQL query what ANCESTOR IS :1 exactly means?
I have come across with GQL queries containing ANCESTOR IS :1. So, what the ancestor is and what :1 stands for? query = db.GqlQuery("SELECT * " "FROM my_db " "WHERE ANCESTOR IS :1 AND answer > :3 AND ch = :4 " "ORDER BY answer", my_db_k...
[ "An ancestor query returns descendants of the given ancestor entity; that is, entities that list the ancestor as their parent, or whose parent does, etc.\n:1, :2, etc. are placeholders that are replaced by the following parameters to GqlQuery().\n" ]
[ 3 ]
[]
[]
[ "google_app_engine", "gql", "python" ]
stackoverflow_0007273215_google_app_engine_gql_python.txt
Q: Python clean way to wrap individual statements in a try except block I'm currently doing some Python automation of Excel with com. It's fully functional, and does what I want, but I've discovered something surprising. Sometimes, some of the Excel commands I use will fail with an exception for no apparent reason. O...
Python clean way to wrap individual statements in a try except block
I'm currently doing some Python automation of Excel with com. It's fully functional, and does what I want, but I've discovered something surprising. Sometimes, some of the Excel commands I use will fail with an exception for no apparent reason. Other times, they will work. In the VB equivalent code for what I'm doing,...
[ "Consider abstracting away the suppression. And to Aaron's point, do not swallow exceptions generally.\nclass Suppressor:\n def __init__(self, exception_type):\n self._exception_type = exception_type\n\n def __call__(self, expression):\n try:\n exec expression\n except self._ex...
[ 14, 10, 4, 0 ]
[]
[]
[ "com", "excel", "python", "try_catch", "vba" ]
stackoverflow_0007271245_com_excel_python_try_catch_vba.txt
Q: How to use filter in Python with a function which belongs to an object which is an element on the list being filtered? To be specific in my case, the class Job has a number of Task objects on which it operates. import tasker class Job(object): _name = None _tasks = [] _result = None def _...
How to use filter in Python with a function which belongs to an object which is an element on the list being filtered?
To be specific in my case, the class Job has a number of Task objects on which it operates. import tasker class Job(object): _name = None _tasks = [] _result = None def __init__(self, Name): self._name = Name def ReadTasks(self): # read from a Json file and create a list...
[ "You can use a generator expression with sum:\nfailTaskCnt = sum(1 for task in self._tasks if task.IsTaskFail())\n\n" ]
[ 4 ]
[]
[]
[ "filter", "python" ]
stackoverflow_0007273719_filter_python.txt
Q: How to mock the Django Model.save() function in python? I'm using the mock library and I want to be able to mock the save() function of my model class in the following way: Twice the original function should be invoked (and succeed in actually saving the model), and the third time it should throw an exception. Thi...
How to mock the Django Model.save() function in python?
I'm using the mock library and I want to be able to mock the save() function of my model class in the following way: Twice the original function should be invoked (and succeed in actually saving the model), and the third time it should throw an exception. This is for a unit test of a function that calls save three time...
[ "Based on http://pypi.python.org/pypi/mock documentation.\n>>> values = [1, 2]\n>>> def side_effect():\n... return values.pop()\n...\n>>> real = SomeModelClass()\n>>> real.save = Mock(side_effect=side_effect)\n\nShould work twice, then fail with an IndexError every time after that.\nI have no clue what that can...
[ 1 ]
[]
[]
[ "django", "mocking", "python", "unit_testing" ]
stackoverflow_0007261848_django_mocking_python_unit_testing.txt
Q: Converting String Date to Timestamp and back python Hello I am trying to take a date input from jquery UI and process it into the database as a timestamp as well as read it back. I know I probably need to use strftime but cannot figure out how to do it. the date comes in as MM/DD/YYYY I would like to convert it in...
Converting String Date to Timestamp and back python
Hello I am trying to take a date input from jquery UI and process it into the database as a timestamp as well as read it back. I know I probably need to use strftime but cannot figure out how to do it. the date comes in as MM/DD/YYYY I would like to convert it into a timestamp and also after the select queries return i...
[ "To parse the string into a datetime.datetime object:\nIn [23]: import datetime\nIn [29]: datetime.datetime.strptime('9/1/2011','%m/%d/%Y')\nOut[29]: datetime.datetime(2011, 9, 1, 0, 0)\n\nHere is a little diagram describing how datetime/timetuple/timestamp conversions are done in Python:\n o------------o\n...
[ 7 ]
[]
[]
[ "datetime", "jquery_ui", "python" ]
stackoverflow_0007273841_datetime_jquery_ui_python.txt
Q: Testing for reference equality in Python Say I have a class in Python that has an eq method defined for comparing attributes for equality: class Foo(object): # init code... def __eq__(self, other): # usual eq code here.... How can I then compare two instances of Foo for reference equality (that i...
Testing for reference equality in Python
Say I have a class in Python that has an eq method defined for comparing attributes for equality: class Foo(object): # init code... def __eq__(self, other): # usual eq code here.... How can I then compare two instances of Foo for reference equality (that is test if they are the same instance)? If I d...
[ "Thats the is operator\nprint f1 is f2\n\n", "f1 is f2 checks if two references are to the same object. Under the hood, this compares the results of id(f1) == id(f2) using the id builtin function, which returns a integer that's guaranteed unique to the object (but only within the object's lifetime). \nUnder CPyth...
[ 75, 7, 5 ]
[]
[]
[ "equality", "python", "reference" ]
stackoverflow_0007274097_equality_python_reference.txt
Q: python read-only class properties Is there a way to make read-only class properties in Python? Ex. in Unity3d you can do this: transform.position = Vector3.zero Vector3.zero returns an instance of the Vector3 class where x, y, and z are 0. This is basically the same as: transform.position = Vector3(0, 0, 0) I've...
python read-only class properties
Is there a way to make read-only class properties in Python? Ex. in Unity3d you can do this: transform.position = Vector3.zero Vector3.zero returns an instance of the Vector3 class where x, y, and z are 0. This is basically the same as: transform.position = Vector3(0, 0, 0) I've tried doing something like this: class...
[ "The most obvious way might be to alter the class object after the fact:\nclass Vector3(object):\n # ...\nVector3.zero = Vector3(0, 0, 0)\n\nThe main problem with this is that there's then only one zero object, and if it's mutable you can cause accidental damage all over the place. It may be easier (and feel les...
[ 10, 8, 6, 2, 1, 0 ]
[ "As for the read-only part, this is a good resource.\ntemplate = property(lambda self: self.__template)\n\n" ]
[ -1 ]
[ "properties", "python" ]
stackoverflow_0007273293_properties_python.txt
Q: Finding empty files in Python What's the best way in Python to find all empty (zero byte) files, recursively, from a given directory? I could use os.walk and stat each file, but that seems very inefficient. Thanks. A: I'm not sure how you'd get more efficient than os.walk and stat since that's fundamentally wh...
Finding empty files in Python
What's the best way in Python to find all empty (zero byte) files, recursively, from a given directory? I could use os.walk and stat each file, but that seems very inefficient. Thanks.
[ "I'm not sure how you'd get more efficient than os.walk and stat since that's fundamentally what you're doing. You could use some external command/service through Python's subprocess.Popen but then that's hardly \"in python\".\n", "First, you should make it work, then figure out how to make it faster. You shoul...
[ 2, 0 ]
[]
[]
[ "filesystems", "python" ]
stackoverflow_0007273954_filesystems_python.txt
Q: remove values from a python dict I had a python dict like this: {'1' : {'1': {'A' : 34, 'B' : 23, 'C' : nan, 'D': inf, ...} ....} ....} For each "letter" key I had to calculate something, but I obtained values like inf or nan and I need to remove them. How could I do that? My first tried was to "cut" such values,...
remove values from a python dict
I had a python dict like this: {'1' : {'1': {'A' : 34, 'B' : 23, 'C' : nan, 'D': inf, ...} ....} ....} For each "letter" key I had to calculate something, but I obtained values like inf or nan and I need to remove them. How could I do that? My first tried was to "cut" such values, i.e., to return just values between 0...
[ "You should be able to use the del statement to delete the dictionary item. For example:\ndel dct['1']['1']['C']\n\n", "I'm taking a shot in the dark here, but you can probably do it in a couple of different ways. One method would be to calculate the value and then decide whether or not you actually want to kee...
[ 1, 0 ]
[]
[]
[ "dictionary", "nan", "python" ]
stackoverflow_0007274058_dictionary_nan_python.txt
Q: python process wrapper I need to write a process wrapper in python that will launch an application and restart it if it fails. This will be logged to an specified log location passed in from command line. Is this possible? A: Use the subprocess module. Use Popen to start it and get a Popen objet. Use Popen.poll(...
python process wrapper
I need to write a process wrapper in python that will launch an application and restart it if it fails. This will be logged to an specified log location passed in from command line. Is this possible?
[ "Use the subprocess module. Use Popen to start it and get a Popen objet. Use Popen.poll() or wait to get process status depending of what you want. Do it in a loop, and log using the logging module.\nmy 2 cents\n", ">>> from subprocess import Popen\n>>> def spawner(cmd_list):\n... while True:\n... pri...
[ 1, 1 ]
[]
[]
[ "process", "python" ]
stackoverflow_0007273744_process_python.txt
Q: Attempting to run Selenium IDE Python scripts as test suite I have a couple of problems with running more than one Python test script exported by Selenium IDE Python Remote Control plugin formatter. 1) After a python script is completed the browser window automatically closes. I am running tests in Firefox, for ...
Attempting to run Selenium IDE Python scripts as test suite
I have a couple of problems with running more than one Python test script exported by Selenium IDE Python Remote Control plugin formatter. 1) After a python script is completed the browser window automatically closes. I am running tests in Firefox, for my example. 2) Selenium can't export it's test suites in python. ...
[ "The reason firefox gets restarted every time is because setUp is getting called before each unit test function is called (and similarly, tearDown, after). So the unit test simply creates a new selenium browser instance for each test. It's not necessarily a bad thing though, but it might be faster to re-use the sam...
[ 1, 0 ]
[]
[]
[ "api", "python", "selenium", "test_suite", "testcase" ]
stackoverflow_0007233138_api_python_selenium_test_suite_testcase.txt
Q: Error installing eggs with packages for different python version with virtualenv I'm not able to install packages with a virtualenv set to a different python version. Here's my $: $ sudo apt-get install python-setuptools python-dev build-essential $ sudo easy_install -U pip $ sudo virtualenv --no-site-packages --...
Error installing eggs with packages for different python version with virtualenv
I'm not able to install packages with a virtualenv set to a different python version. Here's my $: $ sudo apt-get install python-setuptools python-dev build-essential $ sudo easy_install -U pip $ sudo virtualenv --no-site-packages --distribute --python=/usr/bin/python2.6 pootle $ cd pootle $ sudo pip install mysql-pyt...
[ "$ sudo apt-get install python2.6-dev\n" ]
[ 2 ]
[]
[]
[ "mysql_python", "pip", "python", "virtualenv" ]
stackoverflow_0007268339_mysql_python_pip_python_virtualenv.txt
Q: Python using exceptions for control flow considered bad? All right, I've seen this multiple times in the past, but most recently with my question here. So, I'm curious why this is the case, in python because generators use exceptions to indicate the end of the data. If this is so bad for everyone using python, why...
Python using exceptions for control flow considered bad?
All right, I've seen this multiple times in the past, but most recently with my question here. So, I'm curious why this is the case, in python because generators use exceptions to indicate the end of the data. If this is so bad for everyone using python, why does the language include it in what are considered fundament...
[ "Because ending the generator is not a common event (I know it will always happen, but it only happens once). Throwing the exception is considered expensive. If an event is going to succeed 99% of the time and fail 1%, using try/except can be much faster than checking if it's okay to access that data (it's easier t...
[ 16, 1, 0 ]
[]
[]
[ "generator", "python", "try_catch" ]
stackoverflow_0007274310_generator_python_try_catch.txt
Q: django 1.3 validate form field that are programmatically created I have a form in which I programmatically generate the fields on runtime. In the clean method inside my form, when i print cleaned_data i get nothing. Is it possible to access the data of the field that was generated at runtime? wizard.py for...
django 1.3 validate form field that are programmatically created
I have a form in which I programmatically generate the fields on runtime. In the clean method inside my form, when i print cleaned_data i get nothing. Is it possible to access the data of the field that was generated at runtime? wizard.py for i in lobj: form.fields['list[%s]' % i.id] = forms.CharFie...
[ "mudhusudan brought my attention to the fact that I missed to place clean method in the super call. Below code is the fix\nclass SelectList_Form(forms.Form):\n\n param = forms.CharField(widget=forms.HiddenInput, required=False)\n\n def clean(self):\n super(SelectList_Form, self).clean()\n cleane...
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007272059_django_python.txt
Q: Introspect calling object How do I introspect A's instance from within b.func() (i.e. A's instance's self): class A(): def go(self): b=B() b.func() class B(): def func(self): # Introspect to find the calling A instance here A: In general we don't want that func to have access bac...
Introspect calling object
How do I introspect A's instance from within b.func() (i.e. A's instance's self): class A(): def go(self): b=B() b.func() class B(): def func(self): # Introspect to find the calling A instance here
[ "In general we don't want that func to have access back to the calling instance of A because this breaks encapsulation. Inside of b.func you should have access to any args and kwargs passed, the state/attributes of the instance b (via self here), and any globals hanging around.\nIf you want to know about a calling...
[ 40, 5, 1, 0 ]
[]
[]
[ "introspection", "python" ]
stackoverflow_0007272326_introspection_python.txt
Q: Why do Python unicode strings require special treatment for UTF-8 BOM? For some reason, Python seems to be having issues with BOM when reading unicode strings from a UTF-8 file. Consider the following: with open('test.py') as f: for line in f: print unicode(line, 'utf-8') Seems straightforward, doesn't i...
Why do Python unicode strings require special treatment for UTF-8 BOM?
For some reason, Python seems to be having issues with BOM when reading unicode strings from a UTF-8 file. Consider the following: with open('test.py') as f: for line in f: print unicode(line, 'utf-8') Seems straightforward, doesn't it? That's what I thought until I ran it from command line and got: UnicodeE...
[ "The 'utf-8-sig' encoding will consume the BOM signature on your behalf.\n", "You wrote:\n\n UnicodeEncodeError: 'charmap' codec can't encode character u'\\ufeff' in position 0: character maps to <undefined>\n\n\nWhen you specify the \"utf-8\" encoding in Python, it takes you at your word. UTF-8 files aren’t supp...
[ 28, 12 ]
[]
[]
[ "character_encoding", "io", "python", "unicode", "utf_8" ]
stackoverflow_0007274478_character_encoding_io_python_unicode_utf_8.txt
Q: Set up Scrapy framework to run on Python 2.7 Is it possible to select which version of Python is used by Scrapy? I am running Scrapy on Ubuntu 10.04 which ships with Python 2.6. I have Python 2.7 installed on my machine and would like to take advantage of some of the features of this later version but do not kno...
Set up Scrapy framework to run on Python 2.7
Is it possible to select which version of Python is used by Scrapy? I am running Scrapy on Ubuntu 10.04 which ships with Python 2.6. I have Python 2.7 installed on my machine and would like to take advantage of some of the features of this later version but do not know how to set Scrapy to run on 2.7. When I type "p...
[ "The right way to do this is to organize things so that your special Python is in its own subdirectory that has a bin and lib subdirectory. Then you put that subdirectory in the PATH environment variable before the system binary directories.\nFor instance, lets say you have a /python directory and you put the pytho...
[ 1, 0 ]
[]
[]
[ "frameworks", "python", "python_2.7", "scrapy", "ubuntu" ]
stackoverflow_0007266050_frameworks_python_python_2.7_scrapy_ubuntu.txt
Q: Behavior of Python's time.sleep(0) under linux - Does it cause a context switch? This pattern comes up a lot but I can't find a straight answer. An non-critical, un-friendly program might do while(True): # do some work Using other technologies and platforms, if you want to allow this program to run hot (use a...
Behavior of Python's time.sleep(0) under linux - Does it cause a context switch?
This pattern comes up a lot but I can't find a straight answer. An non-critical, un-friendly program might do while(True): # do some work Using other technologies and platforms, if you want to allow this program to run hot (use as much CPU cycles as possible) but be polite - allow other programs who are running ho...
[ "I'd never thought about this, so I wrote this script:\nimport time\n\nwhile True:\n print \"loop\"\n time.sleep(0.5)\n\nJust as a test. Running this with strace -o isacontextswitch.strace -s512 python test.py gives you this output on the loop:\nwrite(1, \"loop\\n\", 5) = 5\nselect(0, NULL, ...
[ 35, 17, 9 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0007273474_multithreading_python.txt
Q: how do i turn for loop iterator into a neat pythonic one line for loop I really love shrinking my code into as few lines as possible. I have the code below and I been trying to get it into one line, if anyone can advise, i would appreciate it. list_choices = {} if_changed = '' for i in obj:...
how do i turn for loop iterator into a neat pythonic one line for loop
I really love shrinking my code into as few lines as possible. I have the code below and I been trying to get it into one line, if anyone can advise, i would appreciate it. list_choices = {} if_changed = '' for i in obj: if if_changed!=i.area.region.id: if_changed = i...
[ "list_choices = {}\nfor i in obj:\n list_choices.setdefault(i.area.region.id, []).append([i.id, i.name])\n\nor, using list_choices = collections.defaultdict(list) the last line will be:\nlist_choices[i.area.region.id].append([i.id, i.name])\n\n", "Not very clear what you want to do, so I'm guessing you want to...
[ 4, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007274521_python.txt
Q: Python If Condition with two conditions dependent on a tuple I have only recently begun programming in Python (with previous Ruby experience). I am trying to set up an if condition with two conditions: if not previous[1] and previous[0][0] == 5: print "hello world" However, I keep getting this error: ...
Python If Condition with two conditions dependent on a tuple
I have only recently begun programming in Python (with previous Ruby experience). I am trying to set up an if condition with two conditions: if not previous[1] and previous[0][0] == 5: print "hello world" However, I keep getting this error: <type 'exceptions.IndexError'>: tuple index out of range Print ...
[ "((5, 1, 9, 23),), then this is a length-1 tuple. It's only element--with index 0--is the tuple (5, 1, 9, 23). It doesn't have a second element to have the index 1, so that_tuple[1] raises IndexError.\nWhat did you hope previous[1] would give you?\n", "There is only a single element in 'previous'. That is why you...
[ 6, 0, 0 ]
[]
[]
[ "conditional", "python", "python_2.7", "ruby", "tuples" ]
stackoverflow_0007275128_conditional_python_python_2.7_ruby_tuples.txt
Q: python webservice execution problem I have a python web service. My problem is when I changed my web service classes. I can't see the changes on the browser and I see last version of web service on the browser all the time. I used Bottle framework and cgi. A: This is from my experience of using Django with Apac...
python webservice execution problem
I have a python web service. My problem is when I changed my web service classes. I can't see the changes on the browser and I see last version of web service on the browser all the time. I used Bottle framework and cgi.
[ "This is from my experience of using Django with Apache, but have you tried restarting your web server? Sometimes the web server will hold a copy of the code in memory to speed up execution, but restarting your web server will make it reload all *.py files.\nProviding more information about the technology stack yo...
[ 0, 0 ]
[]
[]
[ "python", "web_services" ]
stackoverflow_0005319088_python_web_services.txt
Q: Creating versioned libraries in python We're setting up new branches at work which all will share the same libraries. The problem with this is if we update one library you might break all apps that aren't updated. Therefore we would like to version our libraries. The way I was planning on doing this is either like...
Creating versioned libraries in python
We're setting up new branches at work which all will share the same libraries. The problem with this is if we update one library you might break all apps that aren't updated. Therefore we would like to version our libraries. The way I was planning on doing this is either like this loader.load(name='mylib', version='1.0...
[ "Typically the way this is done is by incrementing the module name. You could design a more robust method, but this is the easiest to understand/implement.\nimport package.modv2\nimport package.modv3\n\nCreate a new module version each time the API has changed. \nIt could also be done at the function level to min...
[ 3, 2, 1 ]
[]
[]
[ "python", "versioning" ]
stackoverflow_0007274468_python_versioning.txt
Q: Temporary file association for single cmd.exe session I need to set association for .py files to be executed with specific python version. But I need to make this association only for single cmd.exe session (parallel sessions should not be affected). Does Windows allow this? I suspect the answer is no, but I'd lik...
Temporary file association for single cmd.exe session
I need to set association for .py files to be executed with specific python version. But I need to make this association only for single cmd.exe session (parallel sessions should not be affected). Does Windows allow this? I suspect the answer is no, but I'd like to see some proof before throwing out the idea to get suc...
[ "Sure you can. You were very close to answer in your comment to Jakob's answer - \n\nIf it is possible to change file association with environment\n variables - it will help, but it doesn't seem possible.\n\nIt is possible. All you have to do is to use REG_EXPAND_SZ type of registry key and environment variable in...
[ 8, 3, 1, 0 ]
[]
[]
[ "file_association", "python", "windows" ]
stackoverflow_0005583024_file_association_python_windows.txt
Q: South migration default value from other column? I have a model that has one column right now, description, that populates an area on a few different pages of the site. The client wants this split up into a couple different columns, so they can populate different values in certain parts of the site. So I have to ...
South migration default value from other column?
I have a model that has one column right now, description, that populates an area on a few different pages of the site. The client wants this split up into a couple different columns, so they can populate different values in certain parts of the site. So I have to change that description column to frontpage_descriptio...
[ "This is exactly a three-step: schema migration to add the columns, a data migration to set them, and another schema migration to delete the original description column. 90% of that is done for you from the ./manage command, so it's not as if this is tragically more work.\n" ]
[ 1 ]
[]
[]
[ "django", "django_south", "python" ]
stackoverflow_0007274871_django_django_south_python.txt
Q: Extract string from Python re How do you extract the original 'raw' string from a Python regex. For example, I have the following simple regex: import re test_line_re = re.compile(r'Test \d+ Result: \s+') I want to be able to print: Test \d+ Result \s+ A: You can use the pattern attribute: print test_line_re.p...
Extract string from Python re
How do you extract the original 'raw' string from a Python regex. For example, I have the following simple regex: import re test_line_re = re.compile(r'Test \d+ Result: \s+') I want to be able to print: Test \d+ Result \s+
[ "You can use the pattern attribute:\nprint test_line_re.pattern\n\nYou should always search through the documentation when you have questions like this.\n", ">>> re.compile(r'Test \\d+ Result: \\s+').pattern\n'Test \\\\d+ Result: \\\\s+'\n\n", "Is there any reason you can't store the string before compiling the...
[ 3, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007265713_python.txt
Q: Python: Overriding a Unknown class Consider this example: x = a.some_class_instance x.foo() I want to decorate x.foo() something along the lines of @x.foo() def dec() print 'decorator' x.foo() Is there anyway to do this? Thanks :) A: The easy way is to do this: x.foo = dec(x.foo) Another way i...
Python: Overriding a Unknown class
Consider this example: x = a.some_class_instance x.foo() I want to decorate x.foo() something along the lines of @x.foo() def dec() print 'decorator' x.foo() Is there anyway to do this? Thanks :)
[ "The easy way is to do this:\nx.foo = dec(x.foo)\n\nAnother way is to extend the instance's class\nx = a.some_class_instance\nclass Extended(x.__class__):\n @dec\n def foo(...):\n ...\n\nBut I can't see any good reason to do that.\n", "The following code\n@decorator\ndef decoratee():\n pass\n\nis ...
[ 1, 0 ]
[]
[]
[ "decorator", "overriding", "python" ]
stackoverflow_0007275902_decorator_overriding_python.txt
Q: Inheritance of from_ in Python Edit: There was some confusion, but I want to ask a general question about object oriented design in Python. Consider a class that lets you map data values to counts or frequencies: class DataMap(dict): pass Now consider a subclass that allows you to construct a histogram from a...
Inheritance of from_ in Python
Edit: There was some confusion, but I want to ask a general question about object oriented design in Python. Consider a class that lets you map data values to counts or frequencies: class DataMap(dict): pass Now consider a subclass that allows you to construct a histogram from a list of data: class Histogram(DataM...
[ "To start with, if you think you want @staticmethod, you almost always don't. Either the function is not part of the class, in which case it should just be a free function, or it is part of the class, but not tied to an instance, and it should be a @classmethod. Your named constructor is a good candidate for a @c...
[ 3 ]
[]
[]
[ "constructor", "inheritance", "overloading", "python" ]
stackoverflow_0007276057_constructor_inheritance_overloading_python.txt
Q: Using Python to Create MIDI's Essentially, I'm trying to create MIDI's from scratch and put them online. I'm open to different languages, but prefer to use Python (one of the 2's, if that makes any difference.) and was wondering what library I should use. Thanks in advance! A: Looks like this is what you are loo...
Using Python to Create MIDI's
Essentially, I'm trying to create MIDI's from scratch and put them online. I'm open to different languages, but prefer to use Python (one of the 2's, if that makes any difference.) and was wondering what library I should use. Thanks in advance!
[ "Looks like this is what you are looking for:\nSimple, Cross Platform MIDI Library for Python\nMidiUtil can create MIDI files in python.\n" ]
[ 9 ]
[ "Perl has the module MIDI::Simple. I remember an article about it in the now extinct The Perl Journal:\nhttp://www.foo.be/docs/tpj/issues/vol4_1/tpj0401-0018.html\n" ]
[ -1 ]
[ "python" ]
stackoverflow_0007276139_python.txt
Q: How to work with multiple JSON formats? I'm playing with a python script to pull, parse and format Twitter trend JSON. The location specific format nests the trends inside of an array: [ { "created_at": "2010-07-15T22:31:11Z", "trends": [ { "name": "trendy", "url": "http://search.t...
How to work with multiple JSON formats?
I'm playing with a python script to pull, parse and format Twitter trend JSON. The location specific format nests the trends inside of an array: [ { "created_at": "2010-07-15T22:31:11Z", "trends": [ { "name": "trendy", "url": "http://search.twitter.com/search?q=trendy", "query":...
[ "The more generic case is the one with the list.\nSince you need only the first element, if the parsed object is a list, you extract the first value.\nIn your code, you can simply replace:\nfor x in trends_all[0]['trends']:\n ...\n\nwith\nif isinstance(trends_all, list):\n trends_all = trends_all[0]\nfor x in...
[ 0 ]
[]
[]
[ "json", "python", "twitter" ]
stackoverflow_0007276276_json_python_twitter.txt
Q: How to inherit a class' methods and have them access self member variables in python I'm kind of new to Python, and I have been trying to figure out the best way to migrate a bunch of messy class methods (which access member variables) into a separate Utils.py type module to clean things up. The method names still...
How to inherit a class' methods and have them access self member variables in python
I'm kind of new to Python, and I have been trying to figure out the best way to migrate a bunch of messy class methods (which access member variables) into a separate Utils.py type module to clean things up. The method names still need to be inherited by the base class, but they need to also have access to the parnet c...
[ "The solution to this is to define variables in the __init__() method of the class, and to make sure to initialize the inherited object.\n__init__() is a 'magic' class method which is called when a new object is created from the class definition.\n# Inherit object for new-style Python classes (recommended)\nclass G...
[ 4 ]
[]
[]
[ "class", "inheritance", "python" ]
stackoverflow_0007276232_class_inheritance_python.txt
Q: Are there dictionary comprehensions in Python? (Problem with function returning dict) I know about list comprehensions, what about dictionary comprehensions? Expected Output: >>> countChar('google') {'e': 1, 'g': 2, 'l': 1, 'o': 2} >>> countLetters('apple') {'a': 1, 'e': 1, 'l': 1, 'p': 2} >>> coun...
Are there dictionary comprehensions in Python? (Problem with function returning dict)
I know about list comprehensions, what about dictionary comprehensions? Expected Output: >>> countChar('google') {'e': 1, 'g': 2, 'l': 1, 'o': 2} >>> countLetters('apple') {'a': 1, 'e': 1, 'l': 1, 'p': 2} >>> countLetters('') {} Code (I'm a beginner): def countChar(word): l = [] #get a list...
[ "If you're on Python 2.7 or newer:\n{item: word.count(item) for item in set(word)}\n\nworks fine. You don't need to sort the list before you set it. You also don't need to turn the word into a list. Also, you're on a new enough Python to use collections.Counter(word) instead.\nIf you're on an older version of Pytho...
[ 67, 33 ]
[]
[]
[ "dictionary", "python", "python_2.x" ]
stackoverflow_0007276511_dictionary_python_python_2.x.txt
Q: Dictionary and array as class vs. instance variables This is an easy way to earn some points. Please explain the following: class C: a = {} b = 0 c = [] def __init__(self): self.x = {} def d(self, k, v): self.x[k] = v self.a[k] = v; self.b = v self.c.ap...
Dictionary and array as class vs. instance variables
This is an easy way to earn some points. Please explain the following: class C: a = {} b = 0 c = [] def __init__(self): self.x = {} def d(self, k, v): self.x[k] = v self.a[k] = v; self.b = v self.c.append(v) def out(self, k): print(self.x[k], se...
[ "First of all, [] is not an array, it's a list. The issue here is how the attribute resolution and mutable variables work. Let's start with\nclass Foo(object):\n a = {}\n b = 0\n c = []\n\nThis creates a class with three attributes — those are available either through class itself (Foo.a, for example), or ...
[ 5, 2 ]
[]
[]
[ "python" ]
stackoverflow_0007277094_python.txt
Q: list reverse, list multiple by -1 Expected Result: >>> createLists(5) ([1, 2, 3, 4, 5], [5, 4, 3, 2, 1], [ -5, -4, -3, -2, -1], [-1, -2, -3, -4, -5]) My code: # Write a function that returns 4 lists given a postive number. def createLists(num): ls = [item for item in range(num)] return s...
list reverse, list multiple by -1
Expected Result: >>> createLists(5) ([1, 2, 3, 4, 5], [5, 4, 3, 2, 1], [ -5, -4, -3, -2, -1], [-1, -2, -3, -4, -5]) My code: # Write a function that returns 4 lists given a postive number. def createLists(num): ls = [item for item in range(num)] return set(ls, ls.reverse(), ls.reverse()*(-1),...
[ "def createLists(num): \n ls = range(1, num+1)\n return (ls, ls[::-1], [-n for n in ls][::-1], [-n for n in ls])\n\nprint createLists(5)\n\nhttp://ideone.com/B0ixx\n", "The two problems you are running into are: \n1. reverse() reverses the list in place and returns nothing, so set(ls, ls.reverse()) is like ...
[ 6, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007277177_python.txt
Q: Python equivalent to echo -e? Is there a python equivalent to echo -e? In other words, is there a built-in function to convert r"\x50\x79\x74\x68\x6f\x6e" to "Python" in Python? Edit I added the 'r' prefix, to make sure everyone understands that I do not want the python interpreter to convert this. Rather, I want ...
Python equivalent to echo -e?
Is there a python equivalent to echo -e? In other words, is there a built-in function to convert r"\x50\x79\x74\x68\x6f\x6e" to "Python" in Python? Edit I added the 'r' prefix, to make sure everyone understands that I do not want the python interpreter to convert this. Rather, I want to convert that 24-character string...
[ "The correct way to do this, which I just found is\n>>> a = r\"\\x50\\x79\\x74\\x68\\x6f\\x6e\"\n>>> print a\n\\x50\\x79\\x74\\x68\\x6f\\x6e\n>>> a.decode('string_escape')\n'Python'\n\nMake sure you are escaping the backslashes (or using the raw 'r' prefix) when testing this!\nReferences:\n\nhttp://docs.python.org/...
[ 10, 3 ]
[]
[]
[ "python" ]
stackoverflow_0007277225_python.txt
Q: local python simple http erver sends wrong mime type in windows but not in linux for.svg i have a created a simple http server in python (i haven't touched the do_GET function) in linux (ubuntu) everything works fine but in windows when i want to open the .svg file in firefox (so http://localhost:8000/editor.svg )...
local python simple http erver sends wrong mime type in windows but not in linux for.svg
i have a created a simple http server in python (i haven't touched the do_GET function) in linux (ubuntu) everything works fine but in windows when i want to open the .svg file in firefox (so http://localhost:8000/editor.svg ) it asks me if i want to download it or save it. it has been determined in a previous question...
[ "You want mimetypes.add_type().\nhttp://docs.python.org/library/mimetypes.html\nLinux provides system-wide mimetypes configuration with up-to-date entries. Apparently Windows does not.\n" ]
[ 3 ]
[]
[]
[ "firefox", "python", "svg", "windows" ]
stackoverflow_0007276767_firefox_python_svg_windows.txt
Q: Why is this code so CPU and memory intensive? Why does this code takes 0.32 CPU hours and has an avreage memory of 24.6 MBytes? The page refreshes about 30 times until it stops because there are no more datastore entities. class MainHandler(webapp.RequestHandler): def get(self): found = False q...
Why is this code so CPU and memory intensive?
Why does this code takes 0.32 CPU hours and has an avreage memory of 24.6 MBytes? The page refreshes about 30 times until it stops because there are no more datastore entities. class MainHandler(webapp.RequestHandler): def get(self): found = False q = MyModel.all(keys_only=True).fetch(1000) ...
[ "Seconding task queues. Using mapreduce to delete entities is a common practice. It'll manage the tasks for you.\nA micro optimization is to make one webapp.WSGIApplication and reuse it from a class variable, rather than creating a new one every time main() is invoked.\n", "I found out by testing that I can lower...
[ 0, 0 ]
[]
[]
[ "google_app_engine", "optimization", "python" ]
stackoverflow_0007269433_google_app_engine_optimization_python.txt
Q: Whats is going on? Python skipping over lines in function When I run the following program in Python, the function takes the variables in, but completely skips over the rest and re-shows the main menu for the program without doing anything. Plus, it skips the qualifying "if" statements and asks for all the variabl...
Whats is going on? Python skipping over lines in function
When I run the following program in Python, the function takes the variables in, but completely skips over the rest and re-shows the main menu for the program without doing anything. Plus, it skips the qualifying "if" statements and asks for all the variables even if the first or second options are chosen (which don't ...
[ "Your function is defined as counting (x, y, z, countingSubmenu, q), but when you're calling it, you're argument list is counting(countingSubmenu, x, y, z, q). \n", "It seems to be working in python 2.7 (see Chris Phillips answer)\nAnyway few improvements you can do\n\ntake out function counting out of the loop\n...
[ 5, 3, 3, 1 ]
[]
[]
[ "function", "if_statement", "python", "skip" ]
stackoverflow_0007277463_function_if_statement_python_skip.txt
Q: String building: Hiding string length? I'm modifying python code and I came across this statement and have no idea what it means nor can I find anything on the interent about it. Sorry that its so out of context.. conn.queue.put('%x\r\n%s\r\n' % (len(chunk), chunk) if chunke...
String building: Hiding string length?
I'm modifying python code and I came across this statement and have no idea what it means nor can I find anything on the interent about it. Sorry that its so out of context.. conn.queue.put('%x\r\n%s\r\n' % (len(chunk), chunk) if chunked else chunk) The code is putting a chunk i...
[ "It's not an if statement with no body, it's a conditional expression. A if condition else B evaluates to A if condition is true, otherwise it evaluates to B. So in this case:\n'%x\\r\\n%s\\r\\n' % (len(chunk), chunk)\n if chunked else chunk\n\nWill either be:\n'%x\\r\\n%s\\r\\n' ...
[ 2 ]
[]
[]
[ "python", "string" ]
stackoverflow_0007277545_python_string.txt
Q: Where does port put its installs in osx? I have installed scipy with port on my mac. it says all is fine: $ sudo port install py-scipy Password: ---> Computing dependencies for py-scipy ---> Cleaning py-scipy but when i pull up python, it doesn't see it: $ python2.6 Python 2.6.7 (r267:88850, Jul 27 2011, 11:54...
Where does port put its installs in osx?
I have installed scipy with port on my mac. it says all is fine: $ sudo port install py-scipy Password: ---> Computing dependencies for py-scipy ---> Cleaning py-scipy but when i pull up python, it doesn't see it: $ python2.6 Python 2.6.7 (r267:88850, Jul 27 2011, 11:54:59) [GCC 4.2.1 (Apple Inc. build 5666) (dot ...
[ "To change your current version of Python to the one installed with MacPorts:\nsudo port select python python26\nThis should let you use the MacPorts version of Python that has scipy installed.\n", "For more information search for macports.conf, you will have all the information there. You can also man macports.c...
[ 3, 0, 0 ]
[]
[]
[ "classpath", "macos", "port", "python" ]
stackoverflow_0007021657_classpath_macos_port_python.txt
Q: Passing a JSON document in Python I am trying to pass a policy document to be encoded into base64. The policy document is located at ~/policy_document >>> policy = base64.b64encode(policy_document) What do I need to do here to get policy_document to pass it to base64? Thank you. A: # First open the file # Then ...
Passing a JSON document in Python
I am trying to pass a policy document to be encoded into base64. The policy document is located at ~/policy_document >>> policy = base64.b64encode(policy_document) What do I need to do here to get policy_document to pass it to base64? Thank you.
[ "# First open the file\n# Then read the entire contents into memory\n>>> policy_document = open(\"/absolute/path/to/policy_document\", \"r\").read()\n\n# Then base64 encode the contents.\n>>> policy = base64.b64encode(policy_document)\n\n# If you are using Python 2.7 you can use the with statement\n# to ensure file...
[ 4, 0 ]
[]
[]
[ "json", "python" ]
stackoverflow_0007277666_json_python.txt
Q: Libraries act differently depending on if they are installed or not I have a Python library I wrote which has been acting up on me. I have a set of variables which change the way the library works. In testing it all worked fine, but when I python lib.py install the variables have no effect on the library. I broke ...
Libraries act differently depending on if they are installed or not
I have a Python library I wrote which has been acting up on me. I have a set of variables which change the way the library works. In testing it all worked fine, but when I python lib.py install the variables have no effect on the library. I broke this down to the simplest example possible: Library: ##lib.py con...
[ "What you describe would be inconsistent with how Python works (read, if you like, \"I don't believe you did precisely that and got precisely that result\").\nIf you go importing lib from different places or in different ways, though, you could be ending up with two copies of it, either two copies of one of the mod...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0007277673_python.txt
Q: How to simulate ZipFile.open in Python 2.5? I want to extract a file from a zip to a specific path, ignoring the file path in the archive. This is very easy in Python 2.6 (my docstring is longer than the code) import shutil import zipfile def extract_from_zip(name, dest_path, zip_file): """Similar to zipfile....
How to simulate ZipFile.open in Python 2.5?
I want to extract a file from a zip to a specific path, ignoring the file path in the archive. This is very easy in Python 2.6 (my docstring is longer than the code) import shutil import zipfile def extract_from_zip(name, dest_path, zip_file): """Similar to zipfile.ZipFile.extract but extracts the file given by na...
[ "Haven't tested this bit, but I use something extremely similar in Python 2.4\nimport zipfile\n\ndef extract_from_zip(name, dest_path, zip_file):\n dest_file = open(dest_path, 'wb')\n dest_file.write(zip_file.read(name))\n dest_file.close()\n\nextract_from_zip('path/to/file/in/archive.dat', \n 'outp...
[ 4, 1, 0 ]
[]
[]
[ "python", "python_2.5", "zip" ]
stackoverflow_0003781261_python_python_2.5_zip.txt
Q: What exactly are Django Apps I want to switch from Rails to Django, to broaden my mind, and a question has bobbed up in my mind. My Rails app is quite a mess, since my hobby-based development approach is a patch-and-glue one. I have seen very early that Django divied between a project and an app. According to thei...
What exactly are Django Apps
I want to switch from Rails to Django, to broaden my mind, and a question has bobbed up in my mind. My Rails app is quite a mess, since my hobby-based development approach is a patch-and-glue one. I have seen very early that Django divied between a project and an app. According to their site, a project is made of many ...
[ "A django App is a fancy name for a python package. Really, that's it. The only thing that would distinguish a django app from other python packages is that it makes sense for it to appear in the INSTALLED_APPS list in settings.py, because it contains things like templates, models, or other features that can be a...
[ 6, 1, 0, 0 ]
[]
[]
[ "django", "django_apps", "python" ]
stackoverflow_0007276011_django_django_apps_python.txt
Q: Capitalization of all characters string in a double loop in Python I have the following Python code, that cycles thru the string and capitalizes each character: str = 'abcd' l = list(str) for i in range(len(l)): rl = list(str) cap_char = l[i].capitalize() rl[i] = cap_char str1 = ''.join(rl) pr...
Capitalization of all characters string in a double loop in Python
I have the following Python code, that cycles thru the string and capitalizes each character: str = 'abcd' l = list(str) for i in range(len(l)): rl = list(str) cap_char = l[i].capitalize() rl[i] = cap_char str1 = ''.join(rl) print str1 Which produces: Abcd aBcd abCd abcD I would like to enhance ...
[ "import itertools\nx = 'abcd'\nn = len(x)\nfor i in xrange(1,n):\n combinations = itertools.combinations(range(n), i)\n for c in combinations:\n print ''.join([k if m not in c else k.upper() for m,k in enumerate(x)]),\n print ' >> - {0} char(s) capitalized'.format(i)\n\nOutput:\nAbcd aBcd abCd abcD >> ...
[ 3, 2, 2 ]
[]
[]
[ "capitalization", "list", "python" ]
stackoverflow_0007278092_capitalization_list_python.txt
Q: Sanitizing inputs to MongoDB I'm writing a REST interface to a MongoDB database program, and I'm trying to implement search functionality. I'd like to expose the entire MongoDB interface. I have two questions, really, but they're related so I'm putting them in one post: Is it safe to decode untrusted JSON with th...
Sanitizing inputs to MongoDB
I'm writing a REST interface to a MongoDB database program, and I'm trying to implement search functionality. I'd like to expose the entire MongoDB interface. I have two questions, really, but they're related so I'm putting them in one post: Is it safe to decode untrusted JSON with the Python json module, or is it lik...
[ "Python's JSON module should be safe to use with untrusted input, at least in its default configuration (i.e. you haven't supplied any of the custom decoders, which could potentially have exploits within them).\nHowever, we cannot say with certainty that the results of json.loads() are safe to pass to pymongo's fin...
[ 6 ]
[]
[]
[ "code_injection", "json", "mongodb", "pymongo", "python" ]
stackoverflow_0007278238_code_injection_json_mongodb_pymongo_python.txt
Q: Use underscore builtin in script In an interactive console (in Python) I can do this; k = 5 def generateur(i): i += 1 yield i for j in generateur(k): j print _ Where the _ variable take latest value. This could be very useful for me, when I loop through a generator and would like raise an exception ...
Use underscore builtin in script
In an interactive console (in Python) I can do this; k = 5 def generateur(i): i += 1 yield i for j in generateur(k): j print _ Where the _ variable take latest value. This could be very useful for me, when I loop through a generator and would like raise an exception and print the wrong statement by examp...
[ "In a script, you can simply write:\nfor j in generateur(k):\n j\n\nprint(j)\n\n", "_ is a special variable that only exists in interactive sessions. However, because of Python's scoping rules, the variable j continues to exist when the for loop terminates. Therefore, you can simply do:\nfor j in generateur(k)...
[ 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007276672_python.txt
Q: Endless Syntax Errors for sqlite in terminal I'm trying to lean sqlite3 and create databases, but I'm having trouble getting started. I go to the Terminal and start things off by typing sqlite3. I get the following prompt: sqlite> I installed sqlAcademy and am trying to work through the tutorial, but with example...
Endless Syntax Errors for sqlite in terminal
I'm trying to lean sqlite3 and create databases, but I'm having trouble getting started. I go to the Terminal and start things off by typing sqlite3. I get the following prompt: sqlite> I installed sqlAcademy and am trying to work through the tutorial, but with examples like: >>> import sqlalchemy >>> sqlalchemy.__ver...
[ "That's because you're running in sqlite terminal. The sample code should be run from python's terminal.\n", "To further expand on Demian's answer:\nIn the terminal type:\n$ python\n\nyou will get (or similar depending on which version of python you have installed)\nPython 2.7.1+ (r271:86832, Apr 11 2011, 18:13:5...
[ 6, 1 ]
[]
[]
[ "python", "sqlalchemy", "sqlite", "terminal" ]
stackoverflow_0007278383_python_sqlalchemy_sqlite_terminal.txt
Q: Why does takewhile() skip the first line? I have a file like this: 1 2 3 TAB 1 2 3 TAB I want to read the lines between TAB as blocks. import itertools def block_generator(file): with open(file) as lines: for line in lines: block = list(itertools.takewhile(lambda x: x.rstrip('\n') != '\t'...
Why does takewhile() skip the first line?
I have a file like this: 1 2 3 TAB 1 2 3 TAB I want to read the lines between TAB as blocks. import itertools def block_generator(file): with open(file) as lines: for line in lines: block = list(itertools.takewhile(lambda x: x.rstrip('\n') != '\t', ...
[ "Here is another approach using groupby\nfrom itertools import groupby\ndef block_generator(filename):\n with open(filename) as lines:\n for pred,block in groupby(lines, \"\\t\\n\".__ne__):\n if pred:\n yield block\n\n", "Here you go, tested code. Uses while True: to loop, and...
[ 4, 2, 1, 1 ]
[]
[]
[ "generator", "io", "python" ]
stackoverflow_0007278327_generator_io_python.txt
Q: Run all Tests in Directory Using Nose I need to be able to run all tests in the current directory by typing one line in the Linux shell. In some directories, this works fine. But in others, when I type "nosetests" no tests are run. The tests will run if I call for them individually but I need them to all run autom...
Run all Tests in Directory Using Nose
I need to be able to run all tests in the current directory by typing one line in the Linux shell. In some directories, this works fine. But in others, when I type "nosetests" no tests are run. The tests will run if I call for them individually but I need them to all run automatically. Here is one of the directories th...
[ "From Python Testing: Beginner's Guide by Daniel Arbuckle:\n\nNose looks for tests in directories and modules whose names start with test and Test, or contain a '_', '.', or '-' followed by test or Test. That's the default, but it's not actually the whole story.\n\nAn Extended Introduction to the nose Unit Testing ...
[ 56, 15 ]
[]
[]
[ "nose", "python" ]
stackoverflow_0006333495_nose_python.txt
Q: Making Gradient Images Quickly with C++ I'm currently working with Python to create images of gradients. However, for my uses I'm afraid that Python may just be too slow. I know that Python can be extended with C++ with relative ease. So what are some quick ways to produce images of gradients in C++? A: Writin...
Making Gradient Images Quickly with C++
I'm currently working with Python to create images of gradients. However, for my uses I'm afraid that Python may just be too slow. I know that Python can be extended with C++ with relative ease. So what are some quick ways to produce images of gradients in C++?
[ "Writing a bitmap manually is quite easy. For a Windows Bitmap you need a 54 byte header and then an array of colour values. (.bmp file specs)\nSo, create a file, write the header, supply the pixel array. For a gradient generating the colour values should be fairly simple.\n.pgm/.ppm files are even easier as they h...
[ 2 ]
[]
[]
[ "c++", "gradient", "image", "python" ]
stackoverflow_0007278662_c++_gradient_image_python.txt
Q: Using Urllib instead of action in post form I need to allow users to upload content directly to Amazon S3. This form works: <form action="https://me.s3.amazonaws.com/" method="post" enctype='multipart/form-data' class="upload-form">{% csrf_token %} <input type="hidden" name="key" value="videos/test.jpg"> <...
Using Urllib instead of action in post form
I need to allow users to upload content directly to Amazon S3. This form works: <form action="https://me.s3.amazonaws.com/" method="post" enctype='multipart/form-data' class="upload-form">{% csrf_token %} <input type="hidden" name="key" value="videos/test.jpg"> <input type="hidden" name="AWSAccessKeyId" value="...
[ "I recommend watching the form do its work with Firebug, enabled and set to the Net tab.\nAfter completing the POST, click its [+] icon to expand, study the Headers, POST, Response tabs to see what you are missing and/or doing wrong.\nNext separate this script from Django and put into a standalone file. Add one th...
[ 1 ]
[]
[]
[ "amazon_s3", "python", "urllib2" ]
stackoverflow_0007278010_amazon_s3_python_urllib2.txt
Q: getting the full UserProfile profile I am doing this through django $ python manage.py shell from django.contrib.auth.models import User a = User(username='zoro') a.get_profile().? what do i type after get_profile. to get the full profile instead of typing in one thing like a.get_profile().Location to get just th...
getting the full UserProfile profile
I am doing this through django $ python manage.py shell from django.contrib.auth.models import User a = User(username='zoro') a.get_profile().? what do i type after get_profile. to get the full profile instead of typing in one thing like a.get_profile().Location to get just the location.
[ "a.get_profile() is the full profile (its an instance object of your user profile model). So you can save it in a variable and and use it.\nThough if you want to get everything as a python dict you could try a.get_profile().__dict__.\n" ]
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007278947_django_python.txt
Q: How to implement "import" in a Python-like interpreter? I am just writing an python interpreter for fun to see how some language features can be implemented. Now comes to the point of implement "import"....... Do you guys have some ideas about how to do that? What are some potential problems? A: Try this - Impo...
How to implement "import" in a Python-like interpreter?
I am just writing an python interpreter for fun to see how some language features can be implemented. Now comes to the point of implement "import"....... Do you guys have some ideas about how to do that? What are some potential problems?
[ "Try this - \nImporting Python Modules\nPython modules - How do they work\nHow does import keyword in python actually work?\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0007279178_python.txt
Q: Designing an async API in Python (Note: this question is strictly about the design of the API, not about how to implement it; i.e. I only care about what the client of my API sees here, not what I have to do to make it work.) In simple terms: I want to know the established pattern - if any - for explicit futures (...
Designing an async API in Python
(Note: this question is strictly about the design of the API, not about how to implement it; i.e. I only care about what the client of my API sees here, not what I have to do to make it work.) In simple terms: I want to know the established pattern - if any - for explicit futures (aka promises, aka deferreds, aka tasks...
[ "Okay, so I have found PEP-3148, which does have a Future class. I cannot quite use it as is, so far as I can see, because proper instances are only created by Executor, and that is a class to convert existing synchronous APIs to asynchrony by e.g. moving the synchronous call to a background thread. However, I can ...
[ 6, 1, 0 ]
[]
[]
[ "api_design", "asynchronous", "future", "promise", "python" ]
stackoverflow_0007278588_api_design_asynchronous_future_promise_python.txt
Q: Test framework with automated email notification for python I'm looking for a test framework for Python that will automatically email me if a test fails, with the name of the broken test and the broken test output. I understand it's fairly trivial to wrap a testing library in a try/catch block, but I was surprised...
Test framework with automated email notification for python
I'm looking for a test framework for Python that will automatically email me if a test fails, with the name of the broken test and the broken test output. I understand it's fairly trivial to wrap a testing library in a try/catch block, but I was surprised that I couldn't find frameworks that support this out of the box...
[ "If I understand correctly that you want your tests run automatically and have the emails sent to you because you aren't there to run them, buildbot is the tool: it can run tests whenever you commit to the repository, and on failure can alert you via email, IRC message, etc.\n" ]
[ 2 ]
[]
[]
[ "automation", "email", "python", "testing" ]
stackoverflow_0007279548_automation_email_python_testing.txt
Q: Problem in python using readline data into an array so here my code arr = [] inp = open ("test.txt","r") for line in inp.readlines(): for i in line.split(): arr.append(i) print arr and the output for arr is [] and if i try to print arr[0] or anything it says the index is out of range im trying to tak...
Problem in python using readline data into an array
so here my code arr = [] inp = open ("test.txt","r") for line in inp.readlines(): for i in line.split(): arr.append(i) print arr and the output for arr is [] and if i try to print arr[0] or anything it says the index is out of range im trying to take the data out of the text and put it into array for use ...
[ "There is no need to call .readlines(). The open() function returns a file handle that works as an iterator, and it will return one line at a time. Also, if you are using a modern Python you have with and it is best practice to use it for this sort of thing. So:\narr = []\nwith open(\"test.txt\", \"r\") as inp:\...
[ 2, 1, 0 ]
[]
[]
[ "arrays", "list", "python" ]
stackoverflow_0007279461_arrays_list_python.txt
Q: Running a python script from another script I wish to a run a python script which takes options and arguments from another python script. For example run C:\\code\\old_start_training_generic_depth.py -i 10 -l 2 from C:\\code\\start.py A: You can do that using subprocess.Popen, which can be used to run any exte...
Running a python script from another script
I wish to a run a python script which takes options and arguments from another python script. For example run C:\\code\\old_start_training_generic_depth.py -i 10 -l 2 from C:\\code\\start.py
[ "You can do that using subprocess.Popen, which can be used to run any external process from your Python code (including other Python programs). \nThat said, I would do it otherwise. Since both programs are in Python, I would package the one you want to call as a module which can be invoked programmatically (i.e. im...
[ 7, 3, 2, 1 ]
[ "# once upon a time somewhere in the start.py\nos.system(\"python C:\\\\code\\\\old_start_training_generic_depth.py -i 10 -l 2\")\n\n" ]
[ -1 ]
[ "python" ]
stackoverflow_0006015482_python.txt
Q: Access files from web.py urls I'm using web.py for a small project and I have files I want the user to be able to access in /files directory on the server. I can't seem to find how to return a file on a GET request so I can't work how to do this. Exactly want to do essentially is: urls = ('/files/+', 'files') cla...
Access files from web.py urls
I'm using web.py for a small project and I have files I want the user to be able to access in /files directory on the server. I can't seem to find how to return a file on a GET request so I can't work how to do this. Exactly want to do essentially is: urls = ('/files/+', 'files') class files: def GET(self) #RE...
[ "Playing around I came up with this webpy GET method:\ndef GET(self):\n request = web.input( path=None )\n getPath = request.path\n if os.path.exists( getPath ):\n getFile = file( getPath, 'rb' )\n web.header('Content-type','application/octet-stream')\n web.header('Content-transfer-enc...
[ 3, 0, 0 ]
[]
[]
[ "python", "web.py", "web_applications", "web_services" ]
stackoverflow_0004908765_python_web.py_web_applications_web_services.txt
Q: Question on python text file read write using Win32com I am reading a text file a.txt which has so many columns and i need the data in 5 columns. I fetched it by reading and get data of 5 columns,but my question is how can I import these 5 columns data into one excel file having same column as in text file. A: ...
Question on python text file read write using Win32com
I am reading a text file a.txt which has so many columns and i need the data in 5 columns. I fetched it by reading and get data of 5 columns,but my question is how can I import these 5 columns data into one excel file having same column as in text file.
[ "Here is an example explaining how to generate an excel file with the xlwt python lib.\nUsing win32 would be ok but i personnaly prefer to use xlwt because it doesn't require excel to be installed on the machine.\nimport xlwt\nwb = xlwt.Workbook()\nws = wb.add_sheet(\"My sheet\")\nfor line in xrange(10):\n for c...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0007279324_python.txt
Q: Using pygame on a mac? I was trying to get pygame on my mac to work. I got it running in terminal. But I run into issues when trying to use it with netbeans or trying to run the file. It gives me the error from pygame.locals import * ImportError: No module named locals any help? Thanks! A: If you still want ...
Using pygame on a mac?
I was trying to get pygame on my mac to work. I got it running in terminal. But I run into issues when trying to use it with netbeans or trying to run the file. It gives me the error from pygame.locals import * ImportError: No module named locals any help? Thanks!
[ "If you still want to use netbeans, I think you should take a look at ActivePython\nActivepython basically lets you install different pythons on your machine and be able to select between them (there's a lot more features I'm sure).\nMy advice would be to go to the console and type \n>python \n>>> from pygame.local...
[ 1 ]
[]
[]
[ "macos", "netbeans", "pygame", "python" ]
stackoverflow_0006449121_macos_netbeans_pygame_python.txt
Q: Interpreting python segment I'm new to python and came across this segment of code. Can someone help me with the syntax here? Maybe provide some comments on each line to how it's working? xs is a list that contains dates. data = {} for title, d in tmpdata.items(): data[title] = [x in d and d[x][s...
Interpreting python segment
I'm new to python and came across this segment of code. Can someone help me with the syntax here? Maybe provide some comments on each line to how it's working? xs is a list that contains dates. data = {} for title, d in tmpdata.items(): data[title] = [x in d and d[x][statid] or 0 for x in xs] ...
[ "If I had to guess, I'd say the most perplexing line to someone new to Python must be:\ndata[title] = [x in d and d[x][statid] or 0 for x in xs]\n\nThere is a lot going on here, and some of it uses a style that, although safe in this instance, is no longer recommended. Here is a more verbose form:\ndata[title] = [...
[ 4, 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007280033_python.txt
Q: Twisted, Deferred Callbacks chain After reading the documentation and a few use cases. The question arose how to use a chain of Callbacks. More precisely how to transfer data between Callbacks Here is the code: d = defer.Deferred() d.addCallback(self.min_active_stack) d.addCallback(self.min_normalization) d.addCal...
Twisted, Deferred Callbacks chain
After reading the documentation and a few use cases. The question arose how to use a chain of Callbacks. More precisely how to transfer data between Callbacks Here is the code: d = defer.Deferred() d.addCallback(self.min_active_stack) d.addCallback(self.min_normalization) d.addCallback(self.insert_db) d.callback(0) de...
[ "I actually don't understand the problem. Why you can't just pass result from min_active_stack() through stack_shift() into min_normalization()?\ndef stack_shift(res):\n # do something usefull\n return res\n\nOr since it looks like you want to do something asynchronous in stack_shift, the Deferred equivalent:...
[ 2 ]
[]
[]
[ "callback", "deferred", "python", "twisted" ]
stackoverflow_0007278797_callback_deferred_python_twisted.txt
Q: Calculation star position in the sky, PyEphem I have difficulties with finding current coordinates (RA, DEC) for star in sky. In net I have found only this one tutorial, how to use ephem library: http://asimpleweblog.wordpress.com/2010/07/04/astrometry-in-python-with-pyephem/ As I understood I need to: create ob...
Calculation star position in the sky, PyEphem
I have difficulties with finding current coordinates (RA, DEC) for star in sky. In net I have found only this one tutorial, how to use ephem library: http://asimpleweblog.wordpress.com/2010/07/04/astrometry-in-python-with-pyephem/ As I understood I need to: create observer telescope = ephem.Observer() telescope.lon...
[ "I guess you're looking for FixedBody?\ntelescope = ephem.Observer()\ntelescope.long = ephem.degrees('10')\ntelescope.lat = ephem.degrees('60')\ntelescope.elevation = 200\nstar = ephem.FixedBody()\nstar._ra = 123.123\nstar._dec = 45.45\nstar.compute(telescope)\nprint star.alt, star.az\n\nI don't know about the acc...
[ 6, 3 ]
[]
[]
[ "astronomy", "pyephem", "python" ]
stackoverflow_0006870743_astronomy_pyephem_python.txt
Q: Fully qualified class name in Jython Supposing some.module.MyClass is a Java class, if it is imported in Jython 2.1, its fully qualified class name can be got like this: from some.module import MyClass print MyClass.__name__ then "some.module.MyClass" was printed. Now, the same code in Jython 2.5 prints "MyClass"...
Fully qualified class name in Jython
Supposing some.module.MyClass is a Java class, if it is imported in Jython 2.1, its fully qualified class name can be got like this: from some.module import MyClass print MyClass.__name__ then "some.module.MyClass" was printed. Now, the same code in Jython 2.5 prints "MyClass" only. To get the complete name in Jython ...
[ "The following works:\nprint MyClass.canonicalName\n\nIt would print \"some.module.MyClass\" as expected.\nIn this case, java.lang.Class.getCanonicalName is called.\nIt is less likely that an arbitrary class will have a method called getCanonicalName() than getName(), so in principle it is more reliable than\nprint...
[ 0 ]
[]
[]
[ "classname", "jython", "python" ]
stackoverflow_0007270022_classname_jython_python.txt
Q: Emacs Python.el, Syntax Highlighting Quirks I'm using python.el version 0.23.1 for Emacs right now. The syntax highlighting seems to be a bit off -- any variable name containing an underscore followed by a keyword will result in the keyword being highlighted. Example, "foo_list" will result in "list" being highl...
Emacs Python.el, Syntax Highlighting Quirks
I'm using python.el version 0.23.1 for Emacs right now. The syntax highlighting seems to be a bit off -- any variable name containing an underscore followed by a keyword will result in the keyword being highlighted. Example, "foo_list" will result in "list" being highlighted. More for my own understanding of Emacs-Li...
[ "When you say you're using python-mode 0.23.1, do you mean the one that comes bundled with Emacs or this one: http://launchpad.net/python-mode ? (which seems to be on version 6.something)\nThe reason I'm asking is that I can't reproduce what you're seeing. In an empty python buffer, I inserted\ndef x ():\n a_lis...
[ 3 ]
[]
[]
[ "emacs", "python", "syntax_highlighting" ]
stackoverflow_0007279031_emacs_python_syntax_highlighting.txt
Q: Is it possible, in python, to update or initialize a dictionary key with a single command? For instance, say I want to build an histogram, I would go like that: hist = {} for entry in data: if entry["location"] in hist: hist[entry["location"]] += 1 else: hist[entry["location"]] = 1 Is ther...
Is it possible, in python, to update or initialize a dictionary key with a single command?
For instance, say I want to build an histogram, I would go like that: hist = {} for entry in data: if entry["location"] in hist: hist[entry["location"]] += 1 else: hist[entry["location"]] = 1 Is there a way to avoid the existence check and initialize or update the key depending on its existence...
[ "What you want here is a defaultdict:\nfrom collections import defaultdict\nhist = defaultdict(int)\nfor entry in data:\n hist[entry[\"location\"]] += 1\n\ndefaultdict default-constructs any entry that doesn't already exist in the dict, so for ints they start out at 0 and you just add one for every item.\n", "...
[ 22, 11, 8, 1 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0007280644_dictionary_python.txt
Q: user authentication problem in django I am new in python and django.I am trying for a secure user authentication using django framework.I create a login.html page in [templates/user].And if login success user leads to user/ContactSuccess.html. ContactSuccess.html : <html> ---------{{request.user.username }}----...
user authentication problem in django
I am new in python and django.I am trying for a secure user authentication using django framework.I create a login.html page in [templates/user].And if login success user leads to user/ContactSuccess.html. ContactSuccess.html : <html> ---------{{request.user.username }}------------ {% if request.user.is_authentic...
[ "The problem is that the values which determine whether a user has been authenticated are determined by the browser -- HTTP authentication keeps the username and password stored and then more or less prepends it to every request. In order to stop the login from working, you need to tell the browser to stop.\nThere ...
[ 2 ]
[]
[]
[ "django", "django_1.3", "python" ]
stackoverflow_0007280838_django_django_1.3_python.txt
Q: How to group items in an iterable object based on the first character of the item? Starting with a sorted iterable object I need to group the items by their first character (say a group for every letter from a to z and a group for numbers and symbols). For a more concrete example, let's say I have this list: L = [...
How to group items in an iterable object based on the first character of the item?
Starting with a sorted iterable object I need to group the items by their first character (say a group for every letter from a to z and a group for numbers and symbols). For a more concrete example, let's say I have this list: L = ['aa', 'ab', 'ac', 'ba', 'bb', 'bc', 'ca', 'cb', 'cc', '10', '%a', ' b', ...] And I need ...
[ "import itertools as it\n\nL = ['aa', 'ab', 'ac', 'ba', 'bb', 'bc', 'ca', 'cb', 'cc', '10', '%a', ' b']\n\nsorter = lambda x: x[0].lower() if x and x[0].isalpha() else '}'\nGL = [list(v) for k, v in it.groupby(sorted(L, key=sorter), key=sorter)]\n\nreturns:\n[['aa', 'ab', 'ac'],\n ['ba', 'bb', 'bc'],\n ['ca', 'cb',...
[ 9 ]
[]
[]
[ "python" ]
stackoverflow_0007280969_python.txt
Q: List from string of digits I'm getting a string from input() which consists of digits separated by spaces (1 5 6 3). First I'm trying to check that the input only consists of digits with the isdigit() function but because of the spaces I can't get it to work. Then I convert the string to a list using the split() f...
List from string of digits
I'm getting a string from input() which consists of digits separated by spaces (1 5 6 3). First I'm trying to check that the input only consists of digits with the isdigit() function but because of the spaces I can't get it to work. Then I convert the string to a list using the split() function. What I need is to make ...
[ "What you're describing is a look before you leap approach, i.e. checking first whether the input is conforming, and then parsing it. It's more pythonic to use a Easier to ask for forgiveness than permission approach, i.e. just do it and handle exceptions:\ns = raw_input() # input() in Python 3\ntry:\n numbers = m...
[ 6, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007281257_python.txt
Q: Python dynamic class names Possible Duplicate: Dynamic loading of python modules python: How to add property to a class dynamically? I have a dictionary with the filename and class names how can I import this class names and how can I create this classes? Example: classNames = { 'MCTest':MCTestClass} I want to...
Python dynamic class names
Possible Duplicate: Dynamic loading of python modules python: How to add property to a class dynamically? I have a dictionary with the filename and class names how can I import this class names and how can I create this classes? Example: classNames = { 'MCTest':MCTestClass} I want to import the MCTest and create t...
[ "You have to use the __import__ function:\nhttp://docs.python.org/library/functions.html#import\nExample from doc page:\n>>> import sys\n>>> name = 'foo.bar.baz'\n>>> __import__(name)\n<module 'foo' from ...>\n>>> baz = sys.modules[name]\n>>> baz\n<module 'foo.bar.baz' from ...>\n\nTo instantiate a class from baz y...
[ 6, 1 ]
[]
[]
[ "dynamic", "python" ]
stackoverflow_0007281110_dynamic_python.txt
Q: Python: are objects more memory-hungry than dictionaries? Python 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. # RAM usage: 2100 >>> class Test: ... def __init__(self, i): ... self.one = i ... ...
Python: are objects more memory-hungry than dictionaries?
Python 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. # RAM usage: 2100 >>> class Test: ... def __init__(self, i): ... self.one = i ... self.hundred = 100*i ... # RAM usage: 2108 >>> list1 ...
[ "If you define a class in Python (as opposed to writing it as C extension) then by default it will use a dictionary to store all of its attributes. This is why it's impossible for it to be smaller than a dictionary, and why you can assign arbitrary attributes to most Python objects.\nIf you know know in advance whi...
[ 10, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007281305_python.txt
Q: How can I update a plone page via a script? I have a large amount of automatically generated html files that I would like to push to my Plone website with a script. I currently generate the files, log into Plone, click edit on each individual page and copy and paste the html into the editor. I'd like to automate t...
How can I update a plone page via a script?
I have a large amount of automatically generated html files that I would like to push to my Plone website with a script. I currently generate the files, log into Plone, click edit on each individual page and copy and paste the html into the editor. I'd like to automate this. It would be nice to retain the plone version...
[ "You can script anything in Plone via the following methods:\n\nThrough-the-web via API calls (e.g. XML-RPC, wsapi, etc.)\nThe bin/instance run script provided by plone.recipe.zope2instance (See charm for an example of this).\n\nYou can also use a migration framework like:\n\ncollective.transmogrifier\n\nwhich allo...
[ 5, 2, 2, 0 ]
[]
[]
[ "plone", "python" ]
stackoverflow_0007274968_plone_python.txt
Q: How to remove line from the file in python Possible Duplicate: Deleting a specific line in a file (python) I need to delete the line contains number '2' from the file f= 2 3 5 6 7 2 4 5 A: When you want to edit a file, you make a new file with the correct data and then rename the new file as the old file. This...
How to remove line from the file in python
Possible Duplicate: Deleting a specific line in a file (python) I need to delete the line contains number '2' from the file f= 2 3 5 6 7 2 4 5
[ "When you want to edit a file, you make a new file with the correct data and then rename the new file as the old file. This is what serious programs like your text editor probably do. (Some text editors actually do even weirder stuff, but there's no use going into that.) This is because in many filesystems the rena...
[ 4, 2 ]
[ "import fileinput\nfor line in fileinput.input('f',inplace =1):\n line = line.strip()\n if not '2' in line:\n print line \n\n" ]
[ -1 ]
[ "python" ]
stackoverflow_0007276454_python.txt
Q: How is http://shell.appspot.com/ executing code online? I'm building a website which allows you to write python code online just like http://shell.appspot.com/ or http://ideone.com. Can someone please provide me some help how I can achieve this? A: First of all you can browse their source code. The main file is ...
How is http://shell.appspot.com/ executing code online?
I'm building a website which allows you to write python code online just like http://shell.appspot.com/ or http://ideone.com. Can someone please provide me some help how I can achieve this?
[ "First of all you can browse their source code. The main file is only 321 lines !\nBasically it keeps a separate global dict for each user session, then uses compile and exec to run the code and return the result.\n# log and compile the statement up front\ntry:\n logging.info('Compiling and evaluating:\\n%s' % sta...
[ 6, 2 ]
[]
[]
[ "python" ]
stackoverflow_0007281348_python.txt
Q: What's the difference between assertEqual and assertIs (assertIs was introduced in Python 2.7)? Reference - http://docs.python.org/library/unittest.html#assert-methods assertEqual(a, b) # checks that a == b assertIs(a, b) # checks that a is b <---- whatever that means???? A: Using assertEqual the two objects...
What's the difference between assertEqual and assertIs (assertIs was introduced in Python 2.7)?
Reference - http://docs.python.org/library/unittest.html#assert-methods assertEqual(a, b) # checks that a == b assertIs(a, b) # checks that a is b <---- whatever that means????
[ "Using assertEqual the two objects need not be of the same type, they merely need to be the same value. In comparison, using assertIs the two objects need to be the same object.\nassertEqual tests for equality like the == operator:\n\nThe operators <, >, ==, >=, <=, and != compare the values of two objects. The obj...
[ 24 ]
[]
[]
[ "python", "unit_testing" ]
stackoverflow_0007281774_python_unit_testing.txt
Q: How come a returned string can be interpreted as a function in python? I was skimming through Learn python the hard way and I have come across a code snippet like below. But I did not understand what's behind it, a function basically returns a string that which it's class has a function of the same name. And it c...
How come a returned string can be interpreted as a function in python?
I was skimming through Learn python the hard way and I have come across a code snippet like below. But I did not understand what's behind it, a function basically returns a string that which it's class has a function of the same name. And it can call the function properly. Well, you will get what I mean when you look ...
[ "What you see is the result of the getattr() builtin. Python is a high level language and what's more, an interpreted one. Since all objects in python are basically constructed in memory in forms of hash-tables Python has a rather vast Reflection mechanism.\nThis means that Python can inspect and modify its own cla...
[ 5, 4 ]
[]
[]
[ "function", "python", "string" ]
stackoverflow_0007282005_function_python_string.txt
Q: Python urllib post with different content type than urlencoded It is my understanding that, I need to use url encoded content for posting with urllib. Is it possible to use application/json content type when posting with urllib? A: Not with urllib, as you'd need to set the Content-type header, and urllib does n...
Python urllib post with different content type than urlencoded
It is my understanding that, I need to use url encoded content for posting with urllib. Is it possible to use application/json content type when posting with urllib?
[ "Not with urllib, as you'd need to set the Content-type header, and urllib does not provide a way to do so. You can do it however with urllib2 (but also not with urlopen() wich is more meant to \"open files with a url\" rather than submitting data):\nimport urllib2\nreq = urllib2.Request('http://www.example.com/', ...
[ 5 ]
[]
[]
[ "curl", "python", "urllib2" ]
stackoverflow_0007282187_curl_python_urllib2.txt
Q: Working with strings in python produces strange quotation marks currently I am working with scrapy, which is a web crawling framework based on python. The data is extracted from html using XPATH . (I am new to python) To wrap the data scrapy uses items, e.g. item = MyItem() item['id'] = obj.select('div[@class="id...
Working with strings in python produces strange quotation marks
currently I am working with scrapy, which is a web crawling framework based on python. The data is extracted from html using XPATH . (I am new to python) To wrap the data scrapy uses items, e.g. item = MyItem() item['id'] = obj.select('div[@class="id"]').extract() When the id is printed like print item['id'] I get fo...
[ "python can use both single ' and double \" quotes as quotation marks. when it prints something out it chooses single quotes normally, but will switch to double quotes if the text it is printing contains single quotes (to avoid having to escape the quote in the string):\nso normally, it is printing [u'....'] but s...
[ 4 ]
[]
[]
[ "python", "xpath" ]
stackoverflow_0007274592_python_xpath.txt
Q: Optimizing performance when reading a satellite image file in python I have a multiband satellite image stored in the band interleaved pixel (BIP) format along with a separate header file. The header file provides the details such as the number of rows and columns in the image, and the number of bands (can be more...
Optimizing performance when reading a satellite image file in python
I have a multiband satellite image stored in the band interleaved pixel (BIP) format along with a separate header file. The header file provides the details such as the number of rows and columns in the image, and the number of bands (can be more than the standard 3). The image itself is stored like this (assume a 5 ba...
[ "If you can find a fast function to load the binary data in a big python list (or numpy array), you can de-interleave the data using the slicing notation:\nband0 = biglist[::nbands]\nband1 = biglist[1::nbands]\n....\n\nDoes that help?\n", "Standard PIL\nTo load an image from a file, use the open function in the I...
[ 4, 1, 1 ]
[]
[]
[ "file_io", "image_processing", "python", "python_imaging_library", "satellite_image" ]
stackoverflow_0007279409_file_io_image_processing_python_python_imaging_library_satellite_image.txt