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: configuring connection-pool size with Andy McCurdy's python-for-redis library I have a python loader using Andy McCurdy's python library that opens multiple Redis DB connections and sets millions of keys looping through files of lines each containing an integer that is the redis-db number for that record. Alltoget...
configuring connection-pool size with Andy McCurdy's python-for-redis library
I have a python loader using Andy McCurdy's python library that opens multiple Redis DB connections and sets millions of keys looping through files of lines each containing an integer that is the redis-db number for that record. Alltogether, only 20 databases are open at the present time, but eventually there may be as...
[ "\nSo I'm guessing this is about the connection pooling support built into the python library. Am I correct in that guess?\n\nYes.\n\nIf so the real question is is there a way to increase the pool size\n\nNot needed, it will increase connections up to 2**31 per default (andys lib). So your connections are idle anyw...
[ 1 ]
[]
[]
[ "configuration", "connection_pooling", "python", "redis" ]
stackoverflow_0006628953_configuration_connection_pooling_python_redis.txt
Q: How do I connect to link-local IPv6 with WMI/COM? I'm trying to do some v4 network configuration of host A, from host B. Because using WMI over v4 would be a catch-22, I want to use link-local v6 to make my connection. COM has, apparently, supported IPv6 since at least 2003. It seems that link-local was forgotten....
How do I connect to link-local IPv6 with WMI/COM?
I'm trying to do some v4 network configuration of host A, from host B. Because using WMI over v4 would be a catch-22, I want to use link-local v6 to make my connection. COM has, apparently, supported IPv6 since at least 2003. It seems that link-local was forgotten. The confusing thing is this: if host A has working IPv...
[ "It turns out whatever weird callback mechanism WMI does to get two-way communication going, cannot cope with link-local addressing. I'm escalating to Microsoft support.\nUPDATE: I have discussed the issue with MS Support. As it turns out, the default settings for Windows Firewall block link-local name resolution, ...
[ 1 ]
[]
[]
[ "python", "winapi", "wmi" ]
stackoverflow_0006693194_python_winapi_wmi.txt
Q: Is there an easy way to write this in Python? if(i-words < 0): start_point = 0 else: start_point = i - words Or is this the easiest way using min/max? This is for lists splicing. I want start_point to always be 0 or above. A: Better is to make the limiting more obvious s...
Is there an easy way to write this in Python?
if(i-words < 0): start_point = 0 else: start_point = i - words Or is this the easiest way using min/max? This is for lists splicing. I want start_point to always be 0 or above.
[ "Better is to make the limiting more obvious\nstart_point = max(i - words, 0)\n\nThis way, anyone reading can see that you're limiting a value.\nUsing any form of if has the disadvantage that you compute twice i - words. Using a temporary for this will make more code bloat. \nSo, use max and min in these cases.\n",...
[ 10, 1 ]
[]
[]
[ "max", "min", "numbers", "python" ]
stackoverflow_0006703993_max_min_numbers_python.txt
Q: Python ZeroMQ PUSH/PULL -- Lost Messages? I am trying to use python with zeroMQ in PUSH / PULL mode, sending messages of size 4[MB] every few seconds. For some reason, while it looks like all the messages are sent, ONLY SOME of them appear to have been received by the server. What am I missing here? Here's the co...
Python ZeroMQ PUSH/PULL -- Lost Messages?
I am trying to use python with zeroMQ in PUSH / PULL mode, sending messages of size 4[MB] every few seconds. For some reason, while it looks like all the messages are sent, ONLY SOME of them appear to have been received by the server. What am I missing here? Here's the code for the client -- client.py import zmq impor...
[ "The problem is that when the program exits, the socket gets closed immediately and garbage collected with an effective LINGER of 0 (i.e. it throws any unsent messages away). This is a problem for larger messages because they take longer to send than it takes for the socket to be garbage collected.\nYou can avoid t...
[ 16, 1 ]
[]
[]
[ "python", "zeromq" ]
stackoverflow_0006702187_python_zeromq.txt
Q: Equivalent to (.*) in negative look behind assertion Regex Python I am writing a negative lookbehind assertion expression in Python which performs the following function to parse a plain text file: Does not match anything followed after http://********** ; but will match the pattern when it is not inside a http:...
Equivalent to (.*) in negative look behind assertion Regex Python
I am writing a negative lookbehind assertion expression in Python which performs the following function to parse a plain text file: Does not match anything followed after http://********** ; but will match the pattern when it is not inside a http://* link Example: http://www.test.com/aa4 cd6 bx2 vq9 yu9 http://ww...
[ "Problem: Lookbehind does not allow pattern whose length is not fixed.\nQuick hack: Perhaps the following regexp does the job?\nr'(?<![./])[a-z][a-z][0-9]'\n\nIt works like this: \n>>> str = \"\"\"http://www.test.com/aa4\n... bx2 vq9 \n... http://www.bh9.com/cj3\n... \"\"\"\n>>> re.findall(r'(?<![./])[a-z][a-z][0-9...
[ 2, 1 ]
[]
[]
[ "negative_lookbehind", "python", "regex" ]
stackoverflow_0006704130_negative_lookbehind_python_regex.txt
Q: Get list of visible voxels in a grid I'm working on a Minecraft-style game, and I need a way to reduce the amount of the world rendered. Currently, I'm using a naive, render-everything approach, which is having obvious scaling problems. I need a way to take an array of blocks, and in some way find out which ones a...
Get list of visible voxels in a grid
I'm working on a Minecraft-style game, and I need a way to reduce the amount of the world rendered. Currently, I'm using a naive, render-everything approach, which is having obvious scaling problems. I need a way to take an array of blocks, and in some way find out which ones are touching air, water, or any other trans...
[ "If you only need to do this once, performance should not be an issue. If you also incrementally update the .isBoundary property of blocks whenever the world is changed, you will never have to do it again.\nHowever you still run into issues if your world is too large or full of holes and caverns and transparent-int...
[ 4, 2 ]
[]
[]
[ "python", "voxels" ]
stackoverflow_0006703523_python_voxels.txt
Q: How to retrieve the list of models for model A which contains a foreign key to B? class Member( models.Model ): id = models.AutoField(unique=True, primary_key=True) ... class Address( models.Model ): member = models.ForeignKey( Member ) I have the pk for a Member & can retrieve a Member; but I want t...
How to retrieve the list of models for model A which contains a foreign key to B?
class Member( models.Model ): id = models.AutoField(unique=True, primary_key=True) ... class Address( models.Model ): member = models.ForeignKey( Member ) I have the pk for a Member & can retrieve a Member; but I want to retrieve the possibly more than one Address(es) that point to that Member. How do I a...
[ "Address.objects.filter(member=somemember)\n\nor\nAddress.objects.filter(member_id=somemember_pk)\n\n", "class Address( models.Model ):\n member = models.ForeignKey(Member, related_name=\"addresses\")\n\nThen use member.addresses.\n" ]
[ 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006703290_django_python.txt
Q: Python dictionary storage Possible Duplicate: Ordering in Python (2.4) dictionary I tried to copy a dict to another but in a sorted way. I got the follwing problem. mydict = {'carl':40, 'alan':2, 'bob':1, 'danny':3} d1={} for key in sorted(mydict): ...
Python dictionary storage
Possible Duplicate: Ordering in Python (2.4) dictionary I tried to copy a dict to another but in a sorted way. I got the follwing problem. mydict = {'carl':40, 'alan':2, 'bob':1, 'danny':3} d1={} for key in sorted(mydict): d1[key]=mydict[key] When I...
[ "Dicts have no order.\nYou have to use a OrderedDict.\n", "Python dictionaries are not sorted. Use collections.OrderedDict\n", "Because dict doesn't remember the order that keys were first inserted. You need OrderedDict.\n" ]
[ 5, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006704429_python.txt
Q: Writing an email sending program in Python I want to write an email sending script in Python. Most email programs have to connect to existing servers, like Gmail or Hotmail. I want my script to work independantly of those servers and just be able to send email itself (without having to logon anywhere else). The re...
Writing an email sending program in Python
I want to write an email sending script in Python. Most email programs have to connect to existing servers, like Gmail or Hotmail. I want my script to work independantly of those servers and just be able to send email itself (without having to logon anywhere else). The reason for this is because most email servers (lik...
[ "You need an MTA (a.k.a. mail transfer agent), whether it's local or remote. SMTP servers talk to each other to deliver the mail through — if you don't want to connect to the remote one, you need to run a local one. Look into Postfix or exim — just be careful not to allow random people to connect to it. Go to Serve...
[ 4, 0, 0 ]
[]
[]
[ "email", "python" ]
stackoverflow_0006704343_email_python.txt
Q: Ambiguous pywintypes.error when calling win32gui.GetPixel() So here's the line of code triggering the error: win32gui.GetPixel(win32gui.GetDC(self._hwndGame), x, y) Here's the error: pywintypes.error: (0, 'GetPixel', 'No error message is available') I'm not sure how to interpret this error or where to begin reso...
Ambiguous pywintypes.error when calling win32gui.GetPixel()
So here's the line of code triggering the error: win32gui.GetPixel(win32gui.GetDC(self._hwndGame), x, y) Here's the error: pywintypes.error: (0, 'GetPixel', 'No error message is available') I'm not sure how to interpret this error or where to begin resolving it. Any ideas at all would be greatly appreciated.
[ "I may have accidentally solved my problem. It seems the error (in this case) is thrown when trying to GetPixel() for a device that doesn't support \"color management.\" Either that or I was trying to GetPixel() outside the bounds of the window's dimensions. Both cases seemed to cause this error. This is just a hun...
[ 1 ]
[]
[]
[ "ambiguous", "getpixel", "python", "win32gui" ]
stackoverflow_0006701087_ambiguous_getpixel_python_win32gui.txt
Q: get(self) takes exactly 1 argument, 2 supplied - NOT I am having a very odd error occurring in the following: class ServeHandler(blobstore_handlers.BlobstoreDownloadHandler): def get(self, resource): iconKey = str(urllib.unquote(resource)) if iconKey: blob_info = blobstore.get(iconKey) if...
get(self) takes exactly 1 argument, 2 supplied - NOT
I am having a very odd error occurring in the following: class ServeHandler(blobstore_handlers.BlobstoreDownloadHandler): def get(self, resource): iconKey = str(urllib.unquote(resource)) if iconKey: blob_info = blobstore.get(iconKey) if blob_info: url = images.get_serving_url(blob_...
[ "You are probably not matching any resource group parameter in your URL regex configuration.\nBe sure to have a rule like this in your main:\n application = webapp.WSGIApplication(\n [(r'/files/(.*)', ServeHandler)], debug=True)\n run_wsgi_app(application)\n\nThis will pass to the get() resource paramet...
[ 1, 0 ]
[]
[]
[ "blobstore", "google_app_engine", "python" ]
stackoverflow_0006703230_blobstore_google_app_engine_python.txt
Q: python installation path I've tried making a package for my python project, and this has an sh script that does some post install python setup.py install for some dependencies/subprojects. But turns out that MacOS installer creates it's own context and screws up some paths so going simply: python setup.py instal...
python installation path
I've tried making a package for my python project, and this has an sh script that does some post install python setup.py install for some dependencies/subprojects. But turns out that MacOS installer creates it's own context and screws up some paths so going simply: python setup.py install - won't work One solution t...
[ "You most certainly can not assume that python is installed there. If python is properly installed, it should be in the $PATH, otherewise you just can't know. I could have installed it at /whatever/snake-program/, if it wasn't in the path, how could you guess?\nEDIT: What do you mean $PATH contains a lot more by th...
[ 0 ]
[]
[]
[ "path", "python" ]
stackoverflow_0006705360_path_python.txt
Q: List users in IRC channel using Twisted Python IRC framework I am trying to write a function that will print the lists of nicks in an IRC channel to the channel using Twisted Python. How do I do this? I have read the API documentation and I have only seen one question similar to mine on this site, but it doesn't...
List users in IRC channel using Twisted Python IRC framework
I am trying to write a function that will print the lists of nicks in an IRC channel to the channel using Twisted Python. How do I do this? I have read the API documentation and I have only seen one question similar to mine on this site, but it doesn't really answer my question. If I knew how to get the userlist (or...
[ "The linked example you seem to think is the same, uses WHO, different command, different purpose. The correct way is to use NAMES.\nExtended IRCClient to support a names command.\nfrom twisted.words.protocols import irc\nfrom twisted.internet import defer\n\nclass NamesIRCClient(irc.IRCClient):\n def __init__(s...
[ 6 ]
[]
[]
[ "irc", "python", "twisted" ]
stackoverflow_0006671620_irc_python_twisted.txt
Q: Easy Deploying of Python and application in one Bundle , For Linux I Develop Fairly large python application on server side , with all database connect , files extraction , parsing , command line calls. It becomes a nightmare for deploying as i used many third party modules outside of standard python lib. And i lo...
Easy Deploying of Python and application in one Bundle , For Linux
I Develop Fairly large python application on server side , with all database connect , files extraction , parsing , command line calls. It becomes a nightmare for deploying as i used many third party modules outside of standard python lib. And i lost track of them . Especially Differnt Linux OS uses different version o...
[ "Most Python packages can be deployed by creating a lib or similar directory in your deployment, and adding it to sys.path in Python, or PYTHONPATH outside, then copying the package directory (usually inside the directory you unzipped) into that directory. This lets you keep the package with your deployed code, say...
[ 5, 1, 0 ]
[ "There's no reason for Super Simple Server Side Setup.\nDon't waste time on that.\nHow many server installations will happen? Not many. \nSys admins expect a certain level of complexity in server-based applications.\nYou have a list of 3rd party packages; they follow that list and do the installs.\nThen -- after ...
[ -4 ]
[ "deployment", "linux", "portability", "portable_applications", "python" ]
stackoverflow_0006705193_deployment_linux_portability_portable_applications_python.txt
Q: How to make an application not portable? I am trying to make an application that should not portable between computers or between users of the same computer. Which is the best way to do this? edit: By not portable I meant, the application should not be usable without installing it. ie) moving the installed folder ...
How to make an application not portable?
I am trying to make an application that should not portable between computers or between users of the same computer. Which is the best way to do this? edit: By not portable I meant, the application should not be usable without installing it. ie) moving the installed folder to a different computer or different user logi...
[ "Almost no matter what mechanism you implement, the other user will always be able to decompile the program and route around what prevents running it with relative ease. Two exceptions:\n\nMove key functionality + authentication into c modules. This makes circumvention harder, but not impossible\nMove key functiona...
[ 1, 0, 0 ]
[]
[]
[ "cross_platform", "portability", "python" ]
stackoverflow_0006705521_cross_platform_portability_python.txt
Q: Login and registration form on one page with Django I have been stuck on this for a while. I am trying to put both the login and registration forms on the same page, however I have been getting multiple errors depending on which approach I try. The page is actually able to load fine, however neither of the form fi...
Login and registration form on one page with Django
I have been stuck on this for a while. I am trying to put both the login and registration forms on the same page, however I have been getting multiple errors depending on which approach I try. The page is actually able to load fine, however neither of the form fields will load. And then when I hit the register or login...
[ "I think it might be csrf token not found error.If you are using django 1.3 with csrf middleware you have to put csrf token {% csrf_token %} tag with each form posting data like this:\n{% extends \"admin/base.html\" %}\n{% load i18n %}\n\n{% block content %}\n<form method=\"post\" action=\".\">{% csrf_token %}\n\n ...
[ 0 ]
[]
[]
[ "django", "django_authentication", "django_forms", "python" ]
stackoverflow_0006705709_django_django_authentication_django_forms_python.txt
Q: directory listing in python I am getting trouble with directory listing.Suppose, I have a directory with some subdirectory(named as a-z, 0-9, %, -).In each subdirectory, I have some related xml files. So, I have to read each lines of this files.I have tried with the following code. def listFilesMain(dirpath): ...
directory listing in python
I am getting trouble with directory listing.Suppose, I have a directory with some subdirectory(named as a-z, 0-9, %, -).In each subdirectory, I have some related xml files. So, I have to read each lines of this files.I have tried with the following code. def listFilesMain(dirpath): for dirname, dirnames, filenames ...
[ "How about this:\ndef list_files(dirpath):\n files = []\n for dirname, dirnames, filenames in os.walk(dirpath):\n files += [os.path.join(dirname, filename) for filename in filenames]\n return files\n\nYou could also do this as a generator, so the list isn't stored in its entirety:\ndef list_files(di...
[ 2, 1 ]
[]
[]
[ "directory", "python" ]
stackoverflow_0006706122_directory_python.txt
Q: datetime in defining database using sqlalchemy Should I use () with datetime.now in defining tables? What code wrong 1 or 2? 1: Base = declarative_base() class T(Base): __tablename__ = 't' created = Column(DateTime, default=datetime.now) 2: Base = declarative_base() class T(Base): __tablename__ = 't'...
datetime in defining database using sqlalchemy
Should I use () with datetime.now in defining tables? What code wrong 1 or 2? 1: Base = declarative_base() class T(Base): __tablename__ = 't' created = Column(DateTime, default=datetime.now) 2: Base = declarative_base() class T(Base): __tablename__ = 't' created = Column(DateTime, default=datetime.no...
[ "You want the first case. What you're doing is telling SqlAlchemy than whenever a row is inserted, run this function (callable) to get the default value. That can be any callable function or a string value. \nThis way the function is called exactly at insert time and you get the correct date that it was inserted. \...
[ 20 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0006706161_python_sqlalchemy.txt
Q: Class/self problem Here's my code: class Pop(object): def holder(self): self.boobs = 16 self.sent = "pop" def together(self): print "%s : %i" % (self.sent, self.boobs) pop = Pop() pop.together() Shouldn't this print "pop : 16"? Sorry for the odd variable names :P Also, I'm new to...
Class/self problem
Here's my code: class Pop(object): def holder(self): self.boobs = 16 self.sent = "pop" def together(self): print "%s : %i" % (self.sent, self.boobs) pop = Pop() pop.together() Shouldn't this print "pop : 16"? Sorry for the odd variable names :P Also, I'm new to self. Thanks.
[ "In your example, you should first call holder, because that sets the variable to 16.\nI think you meant to do this:\nclass Pop(object):\n def __init__(self):\n self.boobs = 16\n self.sent = \"pop\"\n def together(self):\n print \"%s : %i\" % (self.sent, self.boobs)\n\npop = Pop()\n\npop....
[ 10 ]
[]
[]
[ "python", "self" ]
stackoverflow_0006706715_python_self.txt
Q: Optimize graph for path finding and getting nodes at specific coordinates I'm building a graph class represented as a dict. The graph class is used to perform path finding on a large 2D grid matrix. The nodes are stored as keys and the neighbour nodes are stored as values. This works nice for fast path searches bu...
Optimize graph for path finding and getting nodes at specific coordinates
I'm building a graph class represented as a dict. The graph class is used to perform path finding on a large 2D grid matrix. The nodes are stored as keys and the neighbour nodes are stored as values. This works nice for fast path searches but I also need to get specific nodes out of the dict determined by their x and y...
[ "add an index to Graph which would look like {(x,y):node}. this would require implementing __setitem__ to add the Node to the index, and remove it if another Node already exists and __delitem__ would also remove the Node from the index. this would allow get_node_at(self, x, y) to just do return self.index[(x,y)].\n...
[ 1 ]
[]
[]
[ "graph", "path_finding", "python" ]
stackoverflow_0006706489_graph_path_finding_python.txt
Q: Do i always need to start the new site in django by "django-admin" When i need to start new django i use django-admin startproject site1 and it then create skeltion files. Then use syncdb i want to know if just copy the files from previous site e,g site1 and then rename it to different folder and make necessary...
Do i always need to start the new site in django by "django-admin"
When i need to start new django i use django-admin startproject site1 and it then create skeltion files. Then use syncdb i want to know if just copy the files from previous site e,g site1 and then rename it to different folder and make necessary chnages in settings and URL and then use syncdb . Will my site work or ...
[ "No you don't need to use startproject. You can copy files from another project or write the skeleton files yourself. You probably want to have a unique SECRET_KEY setting though.\n", "Sure. You can definitely copy (or clone with mercurial, git, you name it) your project and make necessary changes and you are d...
[ 3, 1 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0006706765_django_django_admin_python.txt
Q: How to users.set_current_user? How to create a custom login system with google-app-engine's User class? I'm making my own login system. I have tried os.environ['USER_EMAIL'] = 'john.doe@example.com', but it doesn't work. I guess the information is not saved in a session, so if I visit another page then users.get_c...
How to users.set_current_user?
How to create a custom login system with google-app-engine's User class? I'm making my own login system. I have tried os.environ['USER_EMAIL'] = 'john.doe@example.com', but it doesn't work. I guess the information is not saved in a session, so if I visit another page then users.get_current_user() has no memory of what ...
[ "You can't - the Users API only supports signing in with methods supported by that API. If you want to implement your own signin, you will need to use a third-party session library and keep track of logged in users the 'regular' way.\n" ]
[ 3 ]
[]
[]
[ "authentication", "google_app_engine", "python" ]
stackoverflow_0006706678_authentication_google_app_engine_python.txt
Q: Python multiprocessing not deterministic (Manager)? I am trying to share a dict via the Manager interface and it seems the results vary! Sometimes it is {1: 8, 2: 3, 3: 2, 4: 1} and other times {1: 6, 2: 3, 3: 2, 4: 1}, {1: 7, 2: 3, 3: 2, 4: 1}, etc. This is just counting the divisors and should work deterministic...
Python multiprocessing not deterministic (Manager)?
I am trying to share a dict via the Manager interface and it seems the results vary! Sometimes it is {1: 8, 2: 3, 3: 2, 4: 1} and other times {1: 6, 2: 3, 3: 2, 4: 1}, {1: 7, 2: 3, 3: 2, 4: 1}, etc. This is just counting the divisors and should work deterministically... The code is here: from multiprocessing import Pr...
[ "There is a race condition in your code, right here:\n try:\n d[i] += 1\n except:\n d[i] = 1\n\nConsider what happens if d[i] does not yet exist and if two processes reach d[i] += 1 at about the same time. Bo...
[ 4 ]
[]
[]
[ "multiprocessing", "python" ]
stackoverflow_0006706861_multiprocessing_python.txt
Q: Django: want to create an app that can upload and display images I want to create a django app that can upload and display images. However I am having some trouble doing this as it is not working properly. What happens is when I try to upload the image from my form, it does not get displayed in my list. So I seem ...
Django: want to create an app that can upload and display images
I want to create a django app that can upload and display images. However I am having some trouble doing this as it is not working properly. What happens is when I try to upload the image from my form, it does not get displayed in my list. So I seem to be having problems displaying my images. Here is what I have done s...
[ "First, your urls string should contain only slash \"/\" symbol instead of \"\\\"\nSecondly, you may use a local path for your upload_to parameter as:\nupload_to='upload/'\n\nAnd then set properly the MEDIA_ROOT value in settings.py, see the docs.\nin your case, it would be:\nMEDIA_ROOT = 'C:/Users/AQUIL/Desktop/my...
[ 1, 0 ]
[]
[]
[ "django", "forms", "image", "python", "upload" ]
stackoverflow_0006706825_django_forms_image_python_upload.txt
Q: Converting a string to datetime in python Possible Duplicate: Parse date and format it using python? i have a date string like 2011-07-15 13:00:00+00:00 . Any way to convert this string to a datetime object in python ? Thank You A: You can handle the time zone appropriately, and have the format recognized auto...
Converting a string to datetime in python
Possible Duplicate: Parse date and format it using python? i have a date string like 2011-07-15 13:00:00+00:00 . Any way to convert this string to a datetime object in python ? Thank You
[ "You can handle the time zone appropriately, and have the format recognized automatically, if you use dateutil.parser, as described here:\nfrom dateutil import parser\ndt = parser.parse(\"2011-07-15 13:00:00+00:00\")\n\n", "You can use the strptime function in the datetime module. http://docs.python.org/library/d...
[ 10, 4 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0006707061_datetime_python.txt
Q: Python - using subprocess to call sed? I wish to call sed from python using subprocess. The script I tried using is below. however, this pipes the sed output to the standard terminal. It seems that the '>' operator is not recognised from within my subprocess.call statement. Any suggestions? import sys import o...
Python - using subprocess to call sed?
I wish to call sed from python using subprocess. The script I tried using is below. however, this pipes the sed output to the standard terminal. It seems that the '>' operator is not recognised from within my subprocess.call statement. Any suggestions? import sys import os import subprocess files = os.listdir(sys...
[ "Use\nout_file = open(outp, \"w\")\nsub = subprocess.call(['sed', 's/\\\"//g', inp], stdout=out_file )\n\n", "It would be much faster to skip running all the sed processes and just do the work in Python.\nimport os\nimport sys\nfiles = os.listdir(sys.argv[1])\n\nfor count, f in enumerate(files):\n with open(os...
[ 14, 9 ]
[]
[]
[ "python", "sed", "subprocess" ]
stackoverflow_0006706953_python_sed_subprocess.txt
Q: 2D slice series of 3D array in numpy I have a 3D array that represents density values over cartesian space. To get a 2D image I just sum over one of the axes using sum(array,2) and then use the matplotlib function imshow(array2D) to obtain the 2D image. What I want to do is use imshow() to display only one slice o...
2D slice series of 3D array in numpy
I have a 3D array that represents density values over cartesian space. To get a 2D image I just sum over one of the axes using sum(array,2) and then use the matplotlib function imshow(array2D) to obtain the 2D image. What I want to do is use imshow() to display only one slice of the 3D array at a time so that I can 'pa...
[ "I actually wrote code to do exactly what I think you are looking for, see if this helps:\nimport numpy as np\nimport pylab\n\nclass plotter:\n def __init__(self, im, i=0):\n self.im = im\n self.i = i\n self.vmin = im.min()\n self.vmax = im.max()\n self.fig = pylab.figure()\n ...
[ 3 ]
[]
[]
[ "image", "matplotlib", "numpy", "python", "slice" ]
stackoverflow_0006620979_image_matplotlib_numpy_python_slice.txt
Q: obtaining named attributes of self according to my understanding of concatenation this code should work: aList = ["first", "second", "last"] for i in aList: print self.i My class defines the bindings self.first=something as well as self.second and self.last. When I write print self.first the code works but pr...
obtaining named attributes of self
according to my understanding of concatenation this code should work: aList = ["first", "second", "last"] for i in aList: print self.i My class defines the bindings self.first=something as well as self.second and self.last. When I write print self.first the code works but print self.i raises an exception. What am ...
[ "In your code, \"i\" is a string, you need to do that:\naList = [\"first\", \"second\", \"last\"]\nfor i in aList:\n print getattr(self, i, None)\n\nhttp://docs.python.org/library/functions.html#getattr\n\ngetattr(object, name[, default])\n Return the value of the named attribute of object. name must be a s...
[ 9, 1 ]
[]
[]
[ "python" ]
stackoverflow_0006707285_python.txt
Q: Changing a unix timestamp to a different timezone I retrieve a unix timestamp from a web service in a Python program. This timestamp is in a USA timezone. In order to insert it in a MySQL database with other objects, localized in France, I would like to convert this timestamp to the French timezone. I could do it ...
Changing a unix timestamp to a different timezone
I retrieve a unix timestamp from a web service in a Python program. This timestamp is in a USA timezone. In order to insert it in a MySQL database with other objects, localized in France, I would like to convert this timestamp to the French timezone. I could do it with mathematical functions, but there is the issue of ...
[ "If it's really a unix timestamp, then it's UTC based. Just interpret it correctly for your use case. Apply the timezone translation only when you have to print this date as text.\nIf you're storing it as timestamp on your side too, keep it exactly as it is.\n", "I had a similar problem in the past when the times...
[ 8, 6, 1 ]
[]
[]
[ "date", "datetime", "python", "timezone" ]
stackoverflow_0006706808_date_datetime_python_timezone.txt
Q: Python __new__ metaclass behavior with inheritance I have two questions regarding the behavior of running the below code. Why is __new__ even being called without instantiating an object? I thought __new__ controlled the creation of a new instance. Next, why does delattr raise an AttributeError when hasattr return...
Python __new__ metaclass behavior with inheritance
I have two questions regarding the behavior of running the below code. Why is __new__ even being called without instantiating an object? I thought __new__ controlled the creation of a new instance. Next, why does delattr raise an AttributeError when hasattr returns True for size? class ShapeBase(type): def __new__(c...
[ "__new__ of a metaclass controls the instantiation of a new class, not a new instance of that class. So, when you create the class Shape with ShapeBase as the metaclass, ShapeBase.__new__ is invoked.\n", "For the second question delattr(rv, 'size') (and del rv.size) is failing because the attribute size is a clas...
[ 4, 3 ]
[]
[]
[ "inheritance", "metaprogramming", "python" ]
stackoverflow_0006707558_inheritance_metaprogramming_python.txt
Q: Python regular expression question - sub string but not prepended with :) I'm trying to sub foo to bar, but only if it's not prepended with ie. /. So... foobar should change to barbar, but /foobar not. I've tried to add [^/] at beginning of my re, but that doesn't work if foo is at beginning of string. I hate regu...
Python regular expression question - sub string but not prepended with
:) I'm trying to sub foo to bar, but only if it's not prepended with ie. /. So... foobar should change to barbar, but /foobar not. I've tried to add [^/] at beginning of my re, but that doesn't work if foo is at beginning of string. I hate regular expressions! :P
[ "Use a negative lookbehind assertion.\n>>> re.search('(?<!/)foo', 'foo')\n<_sre.SRE_Match object at 0x7f44891518b8>\n>>> re.search('(?<!/)foo', '/foo')\n>>> re.search('(?<!/)foo', 'barfoo')\n<_sre.SRE_Match object at 0x7f4489151850>\n\n", "try using\n \\bfoo\\b\n\\b is a word boundary, it deals with a lot of c...
[ 1, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0006707601_python_regex.txt
Q: How to use alphanum.py? The Alphanum algorithm (python implementation) "sorts strings containing a mix of letters and numbers. Given strings of mixed characters and numbers, it sorts the numbers in value order, while sorting the non-numbers in ASCII order. The end result is a natural sorting order." My attempt in ...
How to use alphanum.py?
The Alphanum algorithm (python implementation) "sorts strings containing a mix of letters and numbers. Given strings of mixed characters and numbers, it sorts the numbers in value order, while sorting the non-numbers in ASCII order. The end result is a natural sorting order." My attempt in python2.7 is below. >>> impor...
[ "I am just a beginner, but I don't remember a alphanum in the standard library of python. \nIf alphanum.py is something you wrote or downloaded try from alphanum.py import *.\nI seem to remember having a similar issue with a module I built that was corrected using that instead of just import.\n", "Thanks to the a...
[ 1, 0 ]
[]
[]
[ "alphanumeric", "python", "sorting" ]
stackoverflow_0006695343_alphanumeric_python_sorting.txt
Q: Why it has got two different result with the same "inputs" I don't understand why it has two difference result. Please help me, to explain these results. This is my codesorce: # coding: iso-8859-2 class Satelite: def __init__(self, name, mass=100, speed=0): self.name, self.mass, self.speed= name, mass...
Why it has got two different result with the same "inputs"
I don't understand why it has two difference result. Please help me, to explain these results. This is my codesorce: # coding: iso-8859-2 class Satelite: def __init__(self, name, mass=100, speed=0): self.name, self.mass, self.speed= name, mass, speed def lokes(self, power, time): self.speed=se...
[ "The lokes() method mutates the object, meaning that you don't have the same input each time.\n", "That's because you're modifying a state variable in the middle.\ndef lokes(self, power, time):\n # this reassigns speed, so next time the function is called, \n # it will be higher.\n self.speed=self.speed+...
[ 4, 3, 1 ]
[]
[]
[ "algorithm", "object", "python" ]
stackoverflow_0006707800_algorithm_object_python.txt
Q: Show only python function def in PyDev Eclipse/Aptana Is there a way in a huge python file , you just see the function def you are interested in ? I remember Eclipse has an option to do this in Java and it was pretty helpful.How about for Python in PyDev/Aptana Studio 3? A: Look in Window > Preferences > PyDev >...
Show only python function def in PyDev Eclipse/Aptana
Is there a way in a huge python file , you just see the function def you are interested in ? I remember Eclipse has an option to do this in Java and it was pretty helpful.How about for Python in PyDev/Aptana Studio 3?
[ "Look in Window > Preferences > PyDev > Editor > Code Folding. Enable Folding for Function Definitions. Then hit Ctrl-9 and Ctrl-0 to fold and unfold your code.\nEdit: You can also use Ctrl-- (minus) and Ctrl-= to fold and unfold single levels.\n", "What you can do is use the regular outline (Alt+Shift+Q O) with ...
[ 2, 0 ]
[]
[]
[ "aptana", "eclipse", "outline_view", "pydev", "python" ]
stackoverflow_0006700416_aptana_eclipse_outline_view_pydev_python.txt
Q: xml missing element in python System uses dom parser in python 2.7.2. The goal is to extract the .db file and use it on sql server.I currently have no problem with sqlite3 library. I have read the similar questions/answers about how to handle a missing element while parsing xml files.But still I couldn't figure ou...
xml missing element in python
System uses dom parser in python 2.7.2. The goal is to extract the .db file and use it on sql server.I currently have no problem with sqlite3 library. I have read the similar questions/answers about how to handle a missing element while parsing xml files.But still I couldn't figure out the solution. xml has 15000+ elem...
[ "Instead of parsing the entire xml and then inserting, parse each vlancard the retrieve it's id/value/name and then insert them into the DB.\n" ]
[ 2 ]
[]
[]
[ "minidom", "python", "sqlite", "xml" ]
stackoverflow_0006707925_minidom_python_sqlite_xml.txt
Q: Mathtext markers in matplotlib As I need to plot many curves in a single figure, I need many different types of markers. Sometimes the number of the default markers are not enough, so it would be nice if the user could customize the marker types. According to the document page (http://matplotlib.sourceforge.net/ap...
Mathtext markers in matplotlib
As I need to plot many curves in a single figure, I need many different types of markers. Sometimes the number of the default markers are not enough, so it would be nice if the user could customize the marker types. According to the document page (http://matplotlib.sourceforge.net/api/artist_api.html#matplotlib.lines.L...
[ "Have you set text.usetex in your matplotrc file? You also need to use the right output backend, such as Postscript or PDF.\n" ]
[ 0 ]
[]
[]
[ "marker", "matplotlib", "python" ]
stackoverflow_0006707964_marker_matplotlib_python.txt
Q: PyDev cannot find modules in the project source folder Okay, so this is not the first time I've had this problem, but it really has driven me to the edge this time. The problem is this. I am developing something on Linux and Windows, sharing the workspace via dropbox and switching between interpreters. Occasionall...
PyDev cannot find modules in the project source folder
Okay, so this is not the first time I've had this problem, but it really has driven me to the edge this time. The problem is this. I am developing something on Linux and Windows, sharing the workspace via dropbox and switching between interpreters. Occasionally, the project stops being executable. The error I get is: T...
[ "Please upgrade to the latest PyDev (2.2.1 at this time), as it should 'fix' that for you. If you still have the issue, please post a screenshot of your PyDev package explorer for this project.\n" ]
[ 2 ]
[]
[]
[ "import", "module", "pydev", "python", "pythonpath" ]
stackoverflow_0006705259_import_module_pydev_python_pythonpath.txt
Q: Google app engine: Queries I have a table Foo where my foos are stored and if I log in via browser and list all my foos there is one Foo with ID=12. Then I have this code: logging.info(fid) q = db.GqlQuery("SELECT * FROM Foo WHERE ID = :1", fid) logging.info(list(q)) which prints 12 [] If I do q.fetch(4) it stil...
Google app engine: Queries
I have a table Foo where my foos are stored and if I log in via browser and list all my foos there is one Foo with ID=12. Then I have this code: logging.info(fid) q = db.GqlQuery("SELECT * FROM Foo WHERE ID = :1", fid) logging.info(list(q)) which prints 12 [] If I do q.fetch(4) it still gives me index out of range. W...
[ "Read the doc. You can't query with a raw ID, you need to create a Key object.\n", "get_by_id\n\nis what I was looking for!\n" ]
[ 3, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0006707931_google_app_engine_python.txt
Q: How to call a python class function from another file I have this class in my parser.py file class HostInfo(object): def __init__(self, host_id): self.osclass = [] self.osmatch = [] self.osfingerprint = [] self.portused = [] self.ports = [] self.extraports = [] self.tcpsequence = {} ...
How to call a python class function from another file
I have this class in my parser.py file class HostInfo(object): def __init__(self, host_id): self.osclass = [] self.osmatch = [] self.osfingerprint = [] self.portused = [] self.ports = [] self.extraports = [] self.tcpsequence = {} self.hostnames = [] self.tcptssequence = {} self.i...
[ "from parser import HostInfo\n\nobj = HostInfo(<whatever host_id you need here>)\nobj.get_id\n\nthis is the way, how are you actually doing it?\n" ]
[ 10 ]
[]
[]
[ "python" ]
stackoverflow_0006708125_python.txt
Q: Sending Emails with Python, Google AppEngine Possible Duplicate: sending email with GAE copies sender — how to stop? I'm using Python with Google's App Engine and I am working on sending emails to users. I have it so users can respond to posts by emailing them. However, it also, by default, sends a copy of the e...
Sending Emails with Python, Google AppEngine
Possible Duplicate: sending email with GAE copies sender — how to stop? I'm using Python with Google's App Engine and I am working on sending emails to users. I have it so users can respond to posts by emailing them. However, it also, by default, sends a copy of the email to the user. Is it possible to disable this?...
[ "From Wooble's duplicate:\n\nYou can't - App Engine automatically BCCs the sender. If you don't want to receive them, you could use one of your app's incoming email addresses as the sender address.\n\n" ]
[ 0 ]
[]
[]
[ "django", "email", "google_app_engine", "python" ]
stackoverflow_0006698589_django_email_google_app_engine_python.txt
Q: Most efficient Django query to get the objects and their related I have this model: class Institution(models.Model): name = models.CharField(max_length=128, db_index=True) aliases = models.ManyToManyField('self', blank=True) I would like to make the most efficient query that return all Institution where n...
Most efficient Django query to get the objects and their related
I have this model: class Institution(models.Model): name = models.CharField(max_length=128, db_index=True) aliases = models.ManyToManyField('self', blank=True) I would like to make the most efficient query that return all Institution where name contains the search term AND their aliases Institution. I came wit...
[ "Union queries -- like this -- are difficult.\nIt's important to review the use cases to be sure you really need to conflate two separate collections (by name and by alias) like this. Sometimes the web page can be presented with two collections, removing the need for a union.\nUsing Q objects to build \"or\" condi...
[ 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006708690_django_python.txt
Q: What db backend to use for ~60,000 static records i am not an expert programmer :D well i had built an application an year ago in vb which usually deals with querying the data, process it and display in a list box. Initially i did not have any idea on databases, so i had done it with files :) After few months i al...
What db backend to use for ~60,000 static records
i am not an expert programmer :D well i had built an application an year ago in vb which usually deals with querying the data, process it and display in a list box. Initially i did not have any idea on databases, so i had done it with files :) After few months i altered it(uses ms access database) well thats story abou...
[ "Take a look at sqlite. It is an embedded database that could be a good solution for your problem.\n", "I'd go with a SQL database, they're easy to set up and JDBC is very easy to use. XML would be really bad for that amount of data.\n", "It all depends how much money you want to despend in your project. \nJava...
[ 2, 1, 1, 0 ]
[]
[]
[ "java", "python", "rdbms", "xml" ]
stackoverflow_0006708835_java_python_rdbms_xml.txt
Q: Help with error message There's an error message I can't understand since I don't see where my code calls it. It appears when using the User object with Google app engine with dev_appserver. Can you tell me what it means? ERROR 2011-07-15 15:01:07,664 __init__.py:463] 'User' object has no attribute '_User__emai...
Help with error message
There's an error message I can't understand since I don't see where my code calls it. It appears when using the User object with Google app engine with dev_appserver. Can you tell me what it means? ERROR 2011-07-15 15:01:07,664 __init__.py:463] 'User' object has no attribute '_User__email' Traceback (most recent cal...
[ "I would guess your error is at import-time of some module:\nERROR 2011-07-15 15:01:07,664 __init__.py:463] 'User' object has no attribute '_User__email'\n\n__init__.py is the file that define a directory as being a package of modules.\nYou could either look for a line #463 with a User object on it, or selective...
[ 1 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0006709185_django_google_app_engine_python.txt
Q: python: can I use a string formatting operator with a class's getter methods? I want to do something like this: class Foo(object): def __init__(self, name): self._name = name self._count = 0 def getName(self): return self._name name = property(getName) def getCount(self): ...
python: can I use a string formatting operator with a class's getter methods?
I want to do something like this: class Foo(object): def __init__(self, name): self._name = name self._count = 0 def getName(self): return self._name name = property(getName) def getCount(self): c = self._count self._count += 1 return c count = propert...
[ "Just change it to not use self.__dict__. You have to access name and count as properties instead of trying to access them by the names that their properties are bound to:\nclass Foo(object):\n def __init__(self, name):\n self._name = name\n self._count = 0\n def getName(self):\n return ...
[ 2 ]
[]
[]
[ "class", "dictionary", "format", "properties", "python" ]
stackoverflow_0006709133_class_dictionary_format_properties_python.txt
Q: Unzip -l in python Is there a way to list all files within a zipped archive in Python? Under bash I usually use unzip -l myzip.zip thanks for any hints A: import zipfile with zipfile.ZipFile(path) as f: for name in f.namelist(): print name A: Iterate through the list returned by ZipFile.infolist().
Unzip -l in python
Is there a way to list all files within a zipped archive in Python? Under bash I usually use unzip -l myzip.zip thanks for any hints
[ "import zipfile\n\nwith zipfile.ZipFile(path) as f:\n for name in f.namelist():\n print name\n\n", "Iterate through the list returned by ZipFile.infolist().\n" ]
[ 2, 1 ]
[]
[]
[ "python", "unzip" ]
stackoverflow_0006709299_python_unzip.txt
Q: Python - capturing subprocess exceptions I'm using os.popen(cmd) to connect to a database with isql. This is in Unix, Python version 2.3.4. I'm trying to implement error handling, and I'm wondering if there's an efficient way to capture errors/exceptions raised by called subprocesses such as this, without dealing ...
Python - capturing subprocess exceptions
I'm using os.popen(cmd) to connect to a database with isql. This is in Unix, Python version 2.3.4. I'm trying to implement error handling, and I'm wondering if there's an efficient way to capture errors/exceptions raised by called subprocesses such as this, without dealing with stderr, etc. Thanks, Dan
[ "If you are using subprocess in the following way you should be able to do it like this \nsql_stdout_stderr = subprocess.Popen(sql_command, stdout=subprocess.PIPE)\n#communicate returns a tuple\nstdout, stderr = sql_stdout_stderr.communicate()\n\nThis will allow you to return the stdout and error. If the stderr con...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006709310_python.txt
Q: Non-Virtual Inheritance in Python Is non-virtual inheritance possible in Python, or do I have to use composition? I would like to call methods against an individual instance of the base class for each subclass rather than a single one for all subclasses. Update Example: Class A has an list in it. Class B and C ar...
Non-Virtual Inheritance in Python
Is non-virtual inheritance possible in Python, or do I have to use composition? I would like to call methods against an individual instance of the base class for each subclass rather than a single one for all subclasses. Update Example: Class A has an list in it. Class B and C are sublasses of A B and C add things to ...
[ "In Python, there is no separate instance of a base class if the base class is inherited multiple times. I don't believe it's possible to achieve what you're asking using inheritance. Composition should work fine though.\nP.S. Your question is phrased in a rather cryptic manner (using C++ terminology for a purely P...
[ 2, 1, 1 ]
[]
[]
[ "composition", "inheritance", "python" ]
stackoverflow_0006709153_composition_inheritance_python.txt
Q: error is raised when I try to remove elements (pydot objects) from a python list I am writing an algorithm to represent regression trees, using pydot module (an interface to Graphviz's Dot language). In the algorithm, lists of Edges and Nodes are made, and then they are represented - that is working fine. But in s...
error is raised when I try to remove elements (pydot objects) from a python list
I am writing an algorithm to represent regression trees, using pydot module (an interface to Graphviz's Dot language). In the algorithm, lists of Edges and Nodes are made, and then they are represented - that is working fine. But in some specific situations, I need to remove some of the Edges and Nodes, and that's wher...
[ "At the surface, it seems that the problem is in Edges or Nodes without parent graph. So, the overall solution would be: do not allow nodes and edges hang around, always attach them to graph,and then remove from graph as needed.\n" ]
[ 1 ]
[]
[]
[ "list", "pydot", "python" ]
stackoverflow_0006709780_list_pydot_python.txt
Q: Selenium script can't find function when opening new page I have a problem with my selenium-python script when opening another page in separate function. In function test2_points() selenium can't find functionselect and Products_4. This is my script: from selenium import selenium import unittest, time, re import s...
Selenium script can't find function when opening new page
I have a problem with my selenium-python script when opening another page in separate function. In function test2_points() selenium can't find functionselect and Products_4. This is my script: from selenium import selenium import unittest, time, re import socket import sys class discount_reward(unittest.TestCase): ...
[ "You're almost certainly executing that sel.select() before the page is finished loading. Any time you perform an action that causes a page transition (e.g., open(), click() on a link or button), you should follow it with a wait_for_page_to_load(timeout_in_milliseconds). The wait will end when the page is fully l...
[ 1 ]
[]
[]
[ "python", "selenium_rc" ]
stackoverflow_0006659246_python_selenium_rc.txt
Q: Checking if a date string is in UTC format I have a date string like "2011-11-06 14:00:00+00:00". Is there a way to check if this is in UTC format or not ?. I tried to convert the above string to a datetime object using utc = datetime.strptime('2011-11-06 14:00:00+00:00','%Y-%m-%d %H:%M%S+%z) so that i can compare...
Checking if a date string is in UTC format
I have a date string like "2011-11-06 14:00:00+00:00". Is there a way to check if this is in UTC format or not ?. I tried to convert the above string to a datetime object using utc = datetime.strptime('2011-11-06 14:00:00+00:00','%Y-%m-%d %H:%M%S+%z) so that i can compare it with pytz.utc, but i get 'ValueError: 'z' is...
[ "A simple regular expression will do:\n>>> import re\n>>> RE = re.compile(r'^\\d{4}-\\d{2}-\\d{2}[ T]\\d{2}:\\d{2}:\\d{2}[+-]\\d{2}:\\d{2}$')\n>>> bool(RE.search('2011-11-06 14:00:00+00:00'))\nTrue\n\n", "The problem with your format string is that strptime just passes the job of parsing time strings on to c's st...
[ 5, 2, 2 ]
[]
[]
[ "datetime", "python", "pytz" ]
stackoverflow_0006709315_datetime_python_pytz.txt
Q: Converting from PST/PDT (Facebook timestamp) to UTC Facebook API (using FQL) gives me timestamps based on Pacific timezone. It represents the number of second since 1st January 1970. I am located in France and France time is GMT+2 in summer and GMT+1 in winter. This "summer time change" is well handled by all date...
Converting from PST/PDT (Facebook timestamp) to UTC
Facebook API (using FQL) gives me timestamps based on Pacific timezone. It represents the number of second since 1st January 1970. I am located in France and France time is GMT+2 in summer and GMT+1 in winter. This "summer time change" is well handled by all datetime / time functions based on local. As you have already...
[ "I have to use pytz\nfrom datetime import *\nfrom pytz import timezone\nimport pytz\n\n[...]\n\nif (not isinstance(pacificTime, int)):\n pacificTime = int(pacificTime)\noriginalTimeZone = \"America/Los_Angeles\"\nprint datetime.fromtimestamp(pacificTime, pytz.timezone(originalTimeZone))\n\nThis solution comes fr...
[ 2, 1 ]
[]
[]
[ "datetime", "facebook", "python", "timezone" ]
stackoverflow_0006709216_datetime_facebook_python_timezone.txt
Q: Remove one column for a numpy array I have a numpy array of dimension (48, 366, 3) and I want to remove the last column from the array to make it (48, 365, 3). What is the best way to do that? (All the entries are integers. I'm using Python v2.6) A: You could try numpy.delete: http://docs.scipy.org/doc/numpy/ref...
Remove one column for a numpy array
I have a numpy array of dimension (48, 366, 3) and I want to remove the last column from the array to make it (48, 365, 3). What is the best way to do that? (All the entries are integers. I'm using Python v2.6)
[ "You could try numpy.delete:\nhttp://docs.scipy.org/doc/numpy/reference/generated/numpy.delete.html\nor just get the slice of the array you want and write it to a new array.\nFor example:\na = np.random.randint(0,2, size=(48,366,3))\nb = np.delete(a, np.s_[-1:], axis=1)\nprint b.shape # <--- (48,365,3)\n\nor equiva...
[ 54, 5 ]
[]
[]
[ "arrays", "numpy", "python" ]
stackoverflow_0006710684_arrays_numpy_python.txt
Q: Python: Waiting for a file to reach a size limit in a CPU friendly manner I am monitoring a file in Python and triggering an action when it reaches a certain size. Right now I am sleeping and polling but I'm sure there is a more elegant way to do this: POLLING_PERIOD = 10 SIZE_LIMIT = 1 * 1024 * 1024 while True: ...
Python: Waiting for a file to reach a size limit in a CPU friendly manner
I am monitoring a file in Python and triggering an action when it reaches a certain size. Right now I am sleeping and polling but I'm sure there is a more elegant way to do this: POLLING_PERIOD = 10 SIZE_LIMIT = 1 * 1024 * 1024 while True: sleep(POLLING_PERIOD) if stat(file).st_size >= SIZE_LIMIT: # do ...
[ "Linux Solution\nYou want to look at using pyinotify it is a Python binding for inotify.\nHere is an example on watching for close events, it isn't a big jump to listening for size changes.\n#!/usr/bin/env python\n\nimport os, sys\nfrom pyinotify import WatchManager, Notifier, ProcessEvent, EventsCodes\n\ndef Monit...
[ 4, 2, 1, 0 ]
[]
[]
[ "multithreading", "polling", "python", "sleep" ]
stackoverflow_0006710676_multithreading_polling_python_sleep.txt
Q: HTML inside node using ElementTree I am using ElementTree to parse a XML file. In some fields, there will be HTML data. For example, consider a declaration as follows: <Course> <Description>Line 1<br />Line 2</Description> </Course> Now, supposing _course is an Element variable which hold this Couse element. ...
HTML inside node using ElementTree
I am using ElementTree to parse a XML file. In some fields, there will be HTML data. For example, consider a declaration as follows: <Course> <Description>Line 1<br />Line 2</Description> </Course> Now, supposing _course is an Element variable which hold this Couse element. I want to access this course's descripti...
[ "Do you have any control over the creation of the xml file? The contents of xml tags which contain xml tags (or similar), or markup chars ('<', etc) should be encoded to avoid this problem. You can do this with either:\n\na CDATA section\nBase64 or some other encoding (which doesn't include xml reserved characters)...
[ 3, 3, 1, 1 ]
[]
[]
[ "elementtree", "html", "python", "xml" ]
stackoverflow_0001088476_elementtree_html_python_xml.txt
Q: Celery monitoring not working with database broker I'm using django-celery using the database as both broker and results store. The events are getting processed, but the monitoring (celerycam or celeryev) is not working. My settings.py includes import djcelery djcelery.setup_loader() BROKER_BACKEND = "django" ...
Celery monitoring not working with database broker
I'm using django-celery using the database as both broker and results store. The events are getting processed, but the monitoring (celerycam or celeryev) is not working. My settings.py includes import djcelery djcelery.setup_loader() BROKER_BACKEND = "django" CELERY_IMPORTS = ( "cbridge.tasks", ) I...
[ "I think your answer might be here...\nDjango Celery: Admin interface showing zero tasks/workers\n\"The event snapshots doesn't currently work with the Django ORM transport.\"\n" ]
[ 3 ]
[]
[]
[ "celery", "configuration", "django", "django_celery", "python" ]
stackoverflow_0006701633_celery_configuration_django_django_celery_python.txt
Q: Get Request Using PyCurl after logging into website After doing a post to log into my website, I try to do a get on my the site and I get a bunch of garbage "�0������`&)��붋...." instead of the data from my site. Why is that? How do I fix that? A: Obviously a dead thread, but if anyone else stumbles across this,...
Get Request Using PyCurl after logging into website
After doing a post to log into my website, I try to do a get on my the site and I get a bunch of garbage "�0������`&)��붋...." instead of the data from my site. Why is that? How do I fix that?
[ "Obviously a dead thread, but if anyone else stumbles across this, funky data like that is most likely compressed with zlib or gzip. If you are using pycurl, this should do the trick:\nimport pycurl\n\nch = pycurl.Curl()\nch.setopt(pycurl.URL, 'http://example.com')\nch.setopt(pycurl.ENCODING, '')\nch.perform()\n\n...
[ 4 ]
[]
[]
[ "pycurl", "python" ]
stackoverflow_0003225012_pycurl_python.txt
Q: python - same instruction, different outcome Could someone help me understand what is going on in the following Python code (python 3.2)? I'm really clueless here. import sys u = sys.stdin.readline() # try entering the string "1 2 3" r = map(lambda t: int(t.strip()),u.split()) print(sum(r)) # prints 6 print(su...
python - same instruction, different outcome
Could someone help me understand what is going on in the following Python code (python 3.2)? I'm really clueless here. import sys u = sys.stdin.readline() # try entering the string "1 2 3" r = map(lambda t: int(t.strip()),u.split()) print(sum(r)) # prints 6 print(sum(r)) # prints 0 ? Thank you.
[ "map() in Python 3.x returns an iterator, not a list. Putting it through sum() the first time consumes it, leaving nothing for the second time.\n" ]
[ 14 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0006711311_python_python_3.x.txt
Q: Python + MIDI + Ableton Live, How? I write app with SL4A on Android. I want to send midi signals to Ableton Live. Tell me, HOW :> What library will be good for that ? A: I would use OSC, rather an midi. "Open Sound Control (OSC) is a protocol for communication among computers, sound synthesizers, and other mult...
Python + MIDI + Ableton Live, How?
I write app with SL4A on Android. I want to send midi signals to Ableton Live. Tell me, HOW :> What library will be good for that ?
[ "I would use OSC, rather an midi.\n\"Open Sound Control (OSC) is a protocol for communication among computers, sound synthesizers, and other multimedia devices that is optimized for modern networking technology. Bringing the benefits of modern networking technology to the world of electronic musical instruments, OS...
[ 4 ]
[]
[]
[ "ableton_live", "android", "midi", "python" ]
stackoverflow_0004169771_ableton_live_android_midi_python.txt
Q: how to copy python modules into python lib directory I have some python modules to copy into my Linux computer. I found out that I need to copy them into one of the directory that python searches or else show a new path for it. 1. when I tried to copy files into /usr/bin/..../python2.6 .. its not allowing me. h...
how to copy python modules into python lib directory
I have some python modules to copy into my Linux computer. I found out that I need to copy them into one of the directory that python searches or else show a new path for it. 1. when I tried to copy files into /usr/bin/..../python2.6 .. its not allowing me. how do I make it. 2. Also do tell me how do I add a new sea...
[ "Make it a proper Python package on top of setuptools and register your command-line frontends using the 'console_scripts' entry-point.\n" ]
[ 2 ]
[]
[]
[ "copy", "linux", "module", "python" ]
stackoverflow_0006711365_copy_linux_module_python.txt
Q: Scientific Problems for Python Coding Dojos We are organizing a Coding Dojo of scientific applications in the Brazilian Python Community, the main goals are: improve our skills in Numpy (and some others scientific libs); improve the use of TDD in this kind of applications; and better understand of limitations of t...
Scientific Problems for Python Coding Dojos
We are organizing a Coding Dojo of scientific applications in the Brazilian Python Community, the main goals are: improve our skills in Numpy (and some others scientific libs); improve the use of TDD in this kind of applications; and better understand of limitations of these APIs. I'm looking for problems that fit thes...
[ "Software Carpentry, a set of educational materials for scientific computing, is mostly in Python and has a number of well thought out example problems.\n", "You sold take a look on this lecture of the MIT. Back in the days I learned some new stuff and also learned how to deal with python. They have some simple e...
[ 3, 3, 2, 1 ]
[]
[]
[ "numpy", "python", "scientific_computing", "tdd" ]
stackoverflow_0006702288_numpy_python_scientific_computing_tdd.txt
Q: Installing Python Imaging Library on my iPhone's Python interpreter I've been learning python for some time now. Recently I needed to install in my Mac the Image module for Python, and after a while I achieve this running a mpkg installer specially for my OS, so far everything was ok and I could run my script. No...
Installing Python Imaging Library on my iPhone's Python interpreter
I've been learning python for some time now. Recently I needed to install in my Mac the Image module for Python, and after a while I achieve this running a mpkg installer specially for my OS, so far everything was ok and I could run my script. Now I'm in the needing of running my script in my jailbroken iPhone, which ...
[ "I found out how\nI downloaded the PIL 1.1.7 source from http://www.pythonware.com/products/pil/ and untared the Imaging-1.1.7.tar.gz file, then I made the following commands:\ncd Imaging-1.1.7/\npython setup.py install\n\nYou can also follow the instructions on the README file in Imaging-1.1.7/ for building the pa...
[ 2 ]
[]
[]
[ "iphone", "python" ]
stackoverflow_0006703113_iphone_python.txt
Q: python lines that start with @ Possible Duplicate: Understanding Python decorators I was reading a django app source code where I find this @login_required def activities(request = None,\ project_id = 0,\ task_id = 0,\ ... What does the line that start with @ mean? A: It's ...
python lines that start with @
Possible Duplicate: Understanding Python decorators I was reading a django app source code where I find this @login_required def activities(request = None,\ project_id = 0,\ task_id = 0,\ ... What does the line that start with @ mean?
[ "It's a decorator. What it does is basically wrap the function. It is equivalent with this code:\ndef activities(request = None,\\\n project_id = 0,\\\n task_id = 0,\\\n ...\nactivities = login_required(activities)\n\nIt is used for checking function arguments (in this case request....
[ 5, 4, 3, 0 ]
[]
[]
[ "decorator", "python", "python_decorators" ]
stackoverflow_0006711762_decorator_python_python_decorators.txt
Q: Is it bad to use vars() I have a string expression that I need to do eval on. This expression may have key names from a given dictionary and values for those keys may or may not be strings. For my eval to be able to evaluate those names, I am creating variables with the key names that appear in that dict and assig...
Is it bad to use vars()
I have a string expression that I need to do eval on. This expression may have key names from a given dictionary and values for those keys may or may not be strings. For my eval to be able to evaluate those names, I am creating variables with the key names that appear in that dict and assign it the value from the dict ...
[ "Why not do this:\n>>> eval('x+y', {'x':1, 'y':2})\n3\n\n", "There is a better way to do what you're trying to do: the optional globals and locals arguments to eval.\ndef test(e1, d1):\n return eval(e1, globals(), d1)\n\ndoes the same thing as your code but without needing to muck with vars. If you can get aw...
[ 2, 2, 1 ]
[]
[]
[ "python", "variables" ]
stackoverflow_0006711749_python_variables.txt
Q: Optimizing Sqlite3 for 20,000+ Updates I have lists of about 20,000 items that I want to insert into a table (with about 50,000 rows in it). Most of these items update certain fields in existing rows and a minority will insert entirely new rows. I am accessing the database twice for each item. First is a select qu...
Optimizing Sqlite3 for 20,000+ Updates
I have lists of about 20,000 items that I want to insert into a table (with about 50,000 rows in it). Most of these items update certain fields in existing rows and a minority will insert entirely new rows. I am accessing the database twice for each item. First is a select query that checks whether the row exists. Next...
[ "I think your bottleneck is that you commit with/avec each insert/update:\n\nI commit each transaction right after the update/insert.\n\nEither stop doing that, or at least switch to WAL journaling; see this answer of mine for why:\nSQL Server CE 4.0 performance comparison\nIf you have a primary key you can optimiz...
[ 5, 2 ]
[]
[]
[ "optimization", "performance", "python", "sqlite" ]
stackoverflow_0006711357_optimization_performance_python_sqlite.txt
Q: Accessing POST request data from CGIHTTPServer (python) I have a very simple CGI webserver running using python CGIHTTPServer class. This class spawns and executes a cgi-php script. If the webpage sends POST request, how can I access the POST request data in the php script? A: When you say your Python process "s...
Accessing POST request data from CGIHTTPServer (python)
I have a very simple CGI webserver running using python CGIHTTPServer class. This class spawns and executes a cgi-php script. If the webpage sends POST request, how can I access the POST request data in the php script?
[ "When you say your Python process \"spawns and executes\" a cgi-php script, I believe what you mean is \"it calls my PHP script by executing the PHP CLI executable, passing it the name of my script.\"\nUsing the PHP CLI executable, HTTP-specific superglobals and environment values will not be set automatically. Yo...
[ 1 ]
[]
[]
[ "cgi", "cgihttprequesthandler", "php", "python", "webserver" ]
stackoverflow_0006712092_cgi_cgihttprequesthandler_php_python_webserver.txt
Q: running a python script indefinitely (as a process, pretty much) i have tests that i ran which can take up to 15m at a time. during these 15m, a log file is periodically written to. however, most of the content is useless. in response to this i have a python script that parses out the useless text and displays th...
running a python script indefinitely (as a process, pretty much)
i have tests that i ran which can take up to 15m at a time. during these 15m, a log file is periodically written to. however, most of the content is useless. in response to this i have a python script that parses out the useless text and displays the relevant data. what i'm trying to achieve is similar to what tail -...
[ "looks like you need something like \"pytailer\":\nhttp://code.google.com/p/pytailer/\nWhile I never used it myself, last example looks like what you want.\n", "You could just have the script filter standard input, and pipe tail -f through it. When you're waiting on stdin, your script will sleep, so it's plenty e...
[ 3, 3, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006712282_python.txt
Q: what's the alternative to nested classes in Python I read a post stating that 'nested classes wasn't pythonic' what's the alternative please forgive me, this isn't the best example but it's the basic concept. a nested class for performing a task. I'm basically having to connect to a service in multiple threads. ...
what's the alternative to nested classes in Python
I read a post stating that 'nested classes wasn't pythonic' what's the alternative please forgive me, this isn't the best example but it's the basic concept. a nested class for performing a task. I'm basically having to connect to a service in multiple threads. import threading, imporedlib class Mother(threading.Thr...
[ "You want to use composition:\nimport threading, importedlib\n\nclass Child:\n def __init__(self, parent):\n self.parent=parent\n\n def run(self):\n importedlib.runajob(parent.VAL1, parent.VAL2)\n\n\n\nclass Mother(threading.Thread):\n def __init__(self,val1,val2):\n self.VAL1 = val1\n...
[ 7 ]
[]
[]
[ "multithreading", "nested_class", "python" ]
stackoverflow_0006712442_multithreading_nested_class_python.txt
Q: how to insert a string to pdf using pypdf? sorry,.. i'am a noob in python.. I need to create a pdf file, without using an existing pdf files.. (pure create a new one) i have googling, and lot of them is merge 2 pdf or create a new file copies from a particular page in another file... what i want to achieve is ma...
how to insert a string to pdf using pypdf?
sorry,.. i'am a noob in python.. I need to create a pdf file, without using an existing pdf files.. (pure create a new one) i have googling, and lot of them is merge 2 pdf or create a new file copies from a particular page in another file... what i want to achieve is make a report page (in chart), but for first step ...
[ "You want \"pisa\" or \"reportlab\" for generating arbitrary PDF documents, not \"pypdf\".\nhttp://www.xhtml2pdf.com/doc/pisa-en.html\nhttp://www.reportlab.org\n", "Also check out the pyfpdf library. I've used the php port of this library for a few years and it's quite flexible, allowing you to work with flowable...
[ 7, 2 ]
[]
[]
[ "pypdf", "python" ]
stackoverflow_0006119484_pypdf_python.txt
Q: Python encoding problem (unicode) Before throwing tomatoes, let me explain my problem (I have read the python unicode doc first). I use json module to parse a json-format result into dictionaries. This, gives me unicode encoded strings (ex : u"My string t\xf4t"). Then I use Mysqldb to store this string in my Mysql...
Python encoding problem (unicode)
Before throwing tomatoes, let me explain my problem (I have read the python unicode doc first). I use json module to parse a json-format result into dictionaries. This, gives me unicode encoded strings (ex : u"My string t\xf4t"). Then I use Mysqldb to store this string in my Mysql database. I precise that these databas...
[ "u\"My string t\\xf4t\" is a Unicode string (its type is unicode), but \"My string t\\xf4t\" is a bytestring (its type is str).\nunicode(storedInDB, \"utf_8\") tries to decode the bytestring as UTF-8, but \"My string t\\xf4t\" isn't valid UTF-8.\n", "It appears that although you configured MySql for UTF-8, you di...
[ 1, 1, 1 ]
[]
[]
[ "character_encoding", "encoding", "python", "unicode" ]
stackoverflow_0006711516_character_encoding_encoding_python_unicode.txt
Q: Need to pass two arguments to Python script from OBJ-C iOS App Im new at writing code in general and I need some help converting a Python Script to OBJ-C for an iOS App. I have a python script running an XMLRPC server on a Network Bridge. I have an iOS App written in Xcode4 that needs to make a call to the python...
Need to pass two arguments to Python script from OBJ-C iOS App
Im new at writing code in general and I need some help converting a Python Script to OBJ-C for an iOS App. I have a python script running an XMLRPC server on a Network Bridge. I have an iOS App written in Xcode4 that needs to make a call to the python script running on the Network Bridge when a button is pressed. I a...
[ "You cannot invoke a script on the iOS device. You can in OS X, but not in an (app store approved) iOS app.\n", "My guess is that you need to create an array containing your arguments:\nNSArray *args = [NSArray arrayWithObjects:ourAddr, dev, nil];\n\nand then pass that to your XMLRPCRequest:\n[waitOnEvent setMet...
[ 0, 0 ]
[]
[]
[ "ios", "objective_c", "python" ]
stackoverflow_0006712499_ios_objective_c_python.txt
Q: Python name of class in class body Is it possible to get the class name within the body of a class definition? For example, class Foo(): x = magic() # x should now be 'Foo' I know that I can do this statically outside of the class body using a class method: class Bar(): @classmethod def magic(cls): ...
Python name of class in class body
Is it possible to get the class name within the body of a class definition? For example, class Foo(): x = magic() # x should now be 'Foo' I know that I can do this statically outside of the class body using a class method: class Bar(): @classmethod def magic(cls): print cls.__name__ Bar.magic() H...
[ "Ok - got one more solution - this one is actually not that complex!\nimport traceback\n\ndef magic():\n return traceback.extract_stack()[-2][2]\n\nclass Something(object):\n print magic()\n\nIt will print out \"Something\". I'm not sure if extracted stack format is standardised in any way, but it works for pyt...
[ 7, 4, 1, 1 ]
[ "class Bar():\n\n @classmethod\n def magic(cls):\n return cls.__name__\n\n @property\n def x(self):\n return self.magic()\n\n def y(self):\n return self.x\n\n>>> a = Bar()\n>>> a.x\n'Bar'\n>>> a.y()\n'Bar'\n\nThis way you can use x as an attribute, at least within any instance an...
[ -2 ]
[ "metaprogramming", "python", "python_2.x" ]
stackoverflow_0006710904_metaprogramming_python_python_2.x.txt
Q: substitute values in email via python substitute values in email via python I am NEW to python and trying to write a script that will send an email (In HTML) to a group of people. This python script will execute a perl script that will read an excel file and save it in a .txt file, once the file is created the pyt...
substitute values in email via python
substitute values in email via python I am NEW to python and trying to write a script that will send an email (In HTML) to a group of people. This python script will execute a perl script that will read an excel file and save it in a .txt file, once the file is created the python script will open the txtFile and create...
[ "Allow me to direct your attention to the format string function\nhtml = \"\"\"\\\n<html>\n Message\n Hi {0:}, (Need to be updated from Array[1])\n starting on {1:} (Should ready from date = time.strftime(\"%m-%d-%y\"))\n\n {2:} (Should be replaced with Array[2]) is the 3LS lead for this week.\\n\n\n Let me...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006712735_python.txt
Q: Eclipse pydev project PYTHONPATH with macports python 2.6 I'm using Pydev with Eclipse on Mac. My python interpeter is macports python 2.6. Right now the python package i'm working on is in my eclipse workspace, but the only way I can get my scripts to run is if I first install it into the macports 2.6 python s...
Eclipse pydev project PYTHONPATH with macports python 2.6
I'm using Pydev with Eclipse on Mac. My python interpeter is macports python 2.6. Right now the python package i'm working on is in my eclipse workspace, but the only way I can get my scripts to run is if I first install it into the macports 2.6 python site_packages folder. This means each time I make a code change...
[ "Go to Window > Preferences > PyDev > Interpreter - Python. You should have an interpreter set up. If not, click New and browse to it.\nUnder Libraries, click New Folder and browse to the directory you want to include. Click Apply, let it build, and try again.\nEdit: That is if you want to run the scripts THROUGH E...
[ 2 ]
[]
[]
[ "eclipse", "macos", "python" ]
stackoverflow_0006712824_eclipse_macos_python.txt
Q: Two very close regexes with lookahead assertions in Python - why does re.split() behave differently? I was trying to anser this question where the OP has the following string: "path:bte00250 Alanine, aspartate and glutamate metabolism path:bte00330 Arginine and proline metabolism" and wants to split it to obtain ...
Two very close regexes with lookahead assertions in Python - why does re.split() behave differently?
I was trying to anser this question where the OP has the following string: "path:bte00250 Alanine, aspartate and glutamate metabolism path:bte00330 Arginine and proline metabolism" and wants to split it to obtain the following list: ['path:bte00250 Alanine, aspartate and glutamate metabolism', 'path:bte00330 Arginine ...
[ "Python's re.split() has a documented limitation: It can't split on zero-length matches. Therefore the split only worked with the added space.\n" ]
[ 5 ]
[]
[]
[ "lookahead", "python", "regex" ]
stackoverflow_0006712855_lookahead_python_regex.txt
Q: Why does python 2.7.2 pygtk segfault parsing a glade GtkButtonBox? Here are the steps to reproduce my problem: I designed a UI in glade 3.10.0 including a GtkButtonBox containing 4 buttons: <object class="GtkButtonBox" id="i_bbox"> <property name="visible">True</property> [...] some children (buttons) The glade f...
Why does python 2.7.2 pygtk segfault parsing a glade GtkButtonBox?
Here are the steps to reproduce my problem: I designed a UI in glade 3.10.0 including a GtkButtonBox containing 4 buttons: <object class="GtkButtonBox" id="i_bbox"> <property name="visible">True</property> [...] some children (buttons) The glade file gets loaded into the python script: builder_fname = "example_layout....
[ "The warning seems to hint that you need to use GtkHButtonBox or GtkVButtonBox versus GtkButtonBox ... do those segfault?\n" ]
[ 1 ]
[]
[]
[ "glade", "gtk", "pygtk", "python", "segmentation_fault" ]
stackoverflow_0006712865_glade_gtk_pygtk_python_segmentation_fault.txt
Q: Python problems with FancyURLopener, 401, and "Connection: close" I'm new to Python, so forgive me if I am missing something obvious. I am using urllib.FancyURLopener to retrieve a web document. It works fine when authentication is disabled on the web server, but fails when authentication is enabled. My guess is ...
Python problems with FancyURLopener, 401, and "Connection: close"
I'm new to Python, so forgive me if I am missing something obvious. I am using urllib.FancyURLopener to retrieve a web document. It works fine when authentication is disabled on the web server, but fails when authentication is enabled. My guess is that I need to subclass urllib.FancyURLopener to override the get_user_...
[ "I just tried your code on my webserver (nginx) and it works as expected:\n\nGet from urllib client\nHTTP/1.1 401 Unauthorized from server with Headers\nConnection: close\nWWW-Authenticate: Basic realm=\"Restricted\"\n\nclient tries again with Authorization header\nAuthorization: Basic <Base64encoded credentials>\n...
[ 0 ]
[]
[]
[ "http_status_code_401", "python", "urllib" ]
stackoverflow_0002382338_http_status_code_401_python_urllib.txt
Q: Python web framework suited for creating games I'm looking for a Python web framework that is suited for creating text-based web games. Django seems to be the most popular choice but after doing some research it seems to be suited for newspaper and other content-based websites. It also seems to be a bit too "autom...
Python web framework suited for creating games
I'm looking for a Python web framework that is suited for creating text-based web games. Django seems to be the most popular choice but after doing some research it seems to be suited for newspaper and other content-based websites. It also seems to be a bit too "automagical" for my taste - I want to know what's going o...
[ "One of the most modern ones is pyramid. Couple it with gevent for high performance, and you'll be on top of the problem.\nPros:\n\nyou can choose the components you want, for instance you are not forced to use a specific ORM, although sqlalchemy is the de facto\nfriendly community\ngood documentation; pyramid stan...
[ 3, 1 ]
[ "Django originated from a newspaper, but it is capable of handling any type of site. Checkout:\nhttps://www.djangoproject.com/weblog/2007/may/25/curse/\nNow granted Curse is a site about gaming, not a gaming site itself, but since your game is going to be purely-text-based (and since I doubt, initially at least, t...
[ -1 ]
[ "python", "web_frameworks" ]
stackoverflow_0006712736_python_web_frameworks.txt
Q: Automatically generating code from a text or xml file and then compiling? I would like to know how I could generate code from a text file in a particular format into a VB.net or C# source file. For instance: I would like my code generating program to read text file having the following format: <category1> <s...
Automatically generating code from a text or xml file and then compiling?
I would like to know how I could generate code from a text file in a particular format into a VB.net or C# source file. For instance: I would like my code generating program to read text file having the following format: <category1> <subcategory> entry1 entry2 </subcategory> </Category1> An...
[ "I'm not really convinced this is a python question, despite the tags and penultimate sentence in the question, but here's a python answer.\n>>> from xml.etree import ElementTree as etree\n>>> corpus = '''<category1>\n... <subcategory>\n... entry1\n... entry2\n... </subcategory>\n... </c...
[ 1, 0, 0, 0 ]
[]
[]
[ "c#", "code_generation", "python", "vb.net" ]
stackoverflow_0006712984_c#_code_generation_python_vb.net.txt
Q: How do you test a function using which retrieves data by urllib2? I am getting into testing in python and I asked myself how to test this method. def get_response(self, url, params): encoded_params = urllib.urlencode(params) request = urllib2.Request(BASE_URL, headers=HEADERS) response = urllib2.urlope...
How do you test a function using which retrieves data by urllib2?
I am getting into testing in python and I asked myself how to test this method. def get_response(self, url, params): encoded_params = urllib.urlencode(params) request = urllib2.Request(BASE_URL, headers=HEADERS) response = urllib2.urlopen(request, encoded_params) return response Using doctest or unitte...
[ "This is a good case for using fake objects:\n# my_module\nget_url = urllib2.urlopen\n\ndef get_response(self, url, params):\n encoded_params = urllib.urlencode(params)\n request = urllib2.Request(BASE_URL, headers=HEADERS)\n response = get_url(request, encoded_params)\n return response\n\n# test_my_mod...
[ 5, 3 ]
[]
[]
[ "doctest", "python", "unit_testing", "urllib2" ]
stackoverflow_0006712983_doctest_python_unit_testing_urllib2.txt
Q: Mapping a list of tuples using a dictionary Given the following list of tuples: y = [(1, 2), (3, 5)] and the following dictionary: d = {1: 'a', 2: 'c', 3: 'n', 4: 'y', 5: 'u'} is there a simple way of mapping y onto [('a', 'c'), ('n', 'u')]? A: How about this: >>> y = [(1, 2), (3, 5)] >>> d = {1: 'a', 2: 'c', ...
Mapping a list of tuples using a dictionary
Given the following list of tuples: y = [(1, 2), (3, 5)] and the following dictionary: d = {1: 'a', 2: 'c', 3: 'n', 4: 'y', 5: 'u'} is there a simple way of mapping y onto [('a', 'c'), ('n', 'u')]?
[ "How about this:\n>>> y = [(1, 2), (3, 5)]\n>>> d = {1: 'a', 2: 'c', 3: 'n', 4: 'y', 5: 'u'}\n>>>\n>>> [(d[k], d[v]) for k,v in y]\n[('a', 'c'), ('n', 'u')]\n>>>\n\n", "If the elements of y are not guaranteed to be 2-tuples, you can use:\n>>> d = {1: 'a', 2: 'c', 3: 'n', 4: 'y', 5: 'u'}\n>>> y = [(1, 2), (3, 5, 4...
[ 11, 2 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0006712816_dictionary_python.txt
Q: How to match regex with multiple overlapping patterns? The context I have a string made of mixed mp3 information that I must try to match against a pattern made of arbitrary strings and tokens. It works like that : The program shows the user a given string the Beatles_Abbey_Road-SomeWord-1969 User enter a patte...
How to match regex with multiple overlapping patterns?
The context I have a string made of mixed mp3 information that I must try to match against a pattern made of arbitrary strings and tokens. It works like that : The program shows the user a given string the Beatles_Abbey_Road-SomeWord-1969 User enter a pattern to help program parse the string the %Artist_%Album-S...
[ "This solution seems to work. In addition to the regex you will need a list of tuples to describe the pattern, where each element corresponds to one capturing group of the regex.\nFor your Beatles example, it would look like this:\npattern = r\"the (.+_.+)-SomeWord-(.+)\"\ngroups = [((\"Artist\", \"Album\"), \"_\"...
[ 1, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0006705206_python_regex.txt
Q: Ironpython: Function works in CPython, mysterious null pointer exception in IronPython I'm trying to do something that seems very simple, and falls within the range of standard python. The following function takes a collection of sets, and returns all of the items that are contained in two or more sets. To do this...
Ironpython: Function works in CPython, mysterious null pointer exception in IronPython
I'm trying to do something that seems very simple, and falls within the range of standard python. The following function takes a collection of sets, and returns all of the items that are contained in two or more sets. To do this, while the collection of sets is not empty, it simply pops one set out of the collection, i...
[ "It's a bug. It will be fixed in 2.7.1, but I don't think the fix is in the 2.7.1 Beta 1 release.\n", "This is a bug still present in the 2.7.1 Beta 1 release. \nIt has been fixed in master, and the fix will be included in the next release.\nIronPython 3.0 (3.0.0.0) on .NET 4.0.30319.235\nType \"help\", \"copyrig...
[ 3, 1 ]
[]
[]
[ "cpython", "ironpython", "nullreferenceexception", "python" ]
stackoverflow_0006712051_cpython_ironpython_nullreferenceexception_python.txt
Q: Algorithm to allocate 'skills' effectively across 'businesses' - stable marriage problem The game Tiny Tower has various 'Bitizens' which are skilled 0-9 in different attributes: Michael: a) retail: 9 b) creative: 2 c) service: 7 d) recreational: 4 e) food: 6 And it then has business in which three Bitizen...
Algorithm to allocate 'skills' effectively across 'businesses' - stable marriage problem
The game Tiny Tower has various 'Bitizens' which are skilled 0-9 in different attributes: Michael: a) retail: 9 b) creative: 2 c) service: 7 d) recreational: 4 e) food: 6 And it then has business in which three Bitizens can work at. Each business falls into one of the categories retail, creative, service, recre...
[ "Let's assume an extra \"point\" is equally valuable no matter where you put it. For example, if you have two businesses, creative and food, we assume it is always better to have a total of 20 in creative and 3 in food than to have 11 in each.\nIn that case, your problem is an example of the Assignment problem. T...
[ 4, 0 ]
[]
[]
[ "algorithm", "python", "stable_marriage" ]
stackoverflow_0006713152_algorithm_python_stable_marriage.txt
Q: Converting from a C double transferred in two hex strings my very first day with Python. I like to filter on a trace file generated by C. Each double from C is formatted in the file by two hex strings representing 32 bit of the 64 double. e.g. 1234567890.3 (C double) inside file: 0xb4933333 0x41d26580 How can I p...
Converting from a C double transferred in two hex strings
my very first day with Python. I like to filter on a trace file generated by C. Each double from C is formatted in the file by two hex strings representing 32 bit of the 64 double. e.g. 1234567890.3 (C double) inside file: 0xb4933333 0x41d26580 How can I parse and combine it to further work with a Python float? Thanks...
[ "You can use struct, using the 'd' modifier for 'double':\n>>> import struct\n>>> num1 = '0xb4933333'\n>>> num2 = '0x41d26580'\n>>> struct.unpack('!d', (num2[2:]+num1[2:]).decode('hex'))[0]\n1234567890.3\n\nBe careful what order you append the doubles in, the above assumes a big-endian machine. Also, I stripped 0x ...
[ 9, 0 ]
[]
[]
[ "double", "floating_point", "hex", "python", "string" ]
stackoverflow_0006713569_double_floating_point_hex_python_string.txt
Q: Problems loading pygtk on Ubuntu 11.04 I'm trying to use pygtk in Python but when I try running my code I get this error: Traceback (most recent call last): File "application.py", line 3, in <module> pygtk.require(2.0) File "/usr/lib/python2.7/dist-packages/pygtk.py", line 85, in require "required vers...
Problems loading pygtk on Ubuntu 11.04
I'm trying to use pygtk in Python but when I try running my code I get this error: Traceback (most recent call last): File "application.py", line 3, in <module> pygtk.require(2.0) File "/usr/lib/python2.7/dist-packages/pygtk.py", line 85, in require "required version '%s' not found on system" % version Asse...
[ "The 3rd line in your file should read: \npygtk.require('2.0')\n\nBecause 2.0 is a string in this case, not a float.\n" ]
[ 1 ]
[]
[]
[ "pygtk", "python", "ubuntu" ]
stackoverflow_0006713620_pygtk_python_ubuntu.txt
Q: Intepretering Special Characters in XLSX Documents I am using the xlsx Python library to read an XLSX document, but some column data contains special characters like _x000D_. How can this be converted to its original form? A: If _x000D_ is supposed to represent a unicode character with a hex code point, you coul...
Intepretering Special Characters in XLSX Documents
I am using the xlsx Python library to read an XLSX document, but some column data contains special characters like _x000D_. How can this be converted to its original form?
[ "If _x000D_ is supposed to represent a unicode character with a hex code point, you could use a regular expression expression to find them and a callback function to convert them to the appropriate value.\nimport re\n\ninput_string = \"H_x00E9_llo W_x00D8_rld!\"\n\ndef parse_escaped_character_match(match):\n ret...
[ 4 ]
[]
[]
[ "python", "unicode", "xlsx" ]
stackoverflow_0006710761_python_unicode_xlsx.txt
Q: How come Python's dict doesn't have .iter()? def complicated_dot(v, w): dot = 0 for (v_i, w_i) in zip(v, w): for x in v_i.iter(): if x in w_i: dot += v_i[x] + w_i[x] return float(dot) I'm getting an error that says: AttributeError: 'dict' obj...
How come Python's dict doesn't have .iter()?
def complicated_dot(v, w): dot = 0 for (v_i, w_i) in zip(v, w): for x in v_i.iter(): if x in w_i: dot += v_i[x] + w_i[x] return float(dot) I'm getting an error that says: AttributeError: 'dict' object has no attribute 'iter'
[ "Considering the following dict:\n>>> d\n{'a': 1, 'c': 3, 'b': 2}\n\nYou can just iterate over the keys like so:\n>>> for k in d:\n... print(k, d[k])\n... \n('a', 1)\n('c', 3)\n('b', 2)\n\nThis implicitly calls the special method __iter__(), but remember:\n\nExplicit is better than implicit.\n\nPython 2.x\nWhat...
[ 16, 13, 8 ]
[]
[]
[ "python" ]
stackoverflow_0006706318_python.txt
Q: Django comments I have a Django application with two models: the first one is django.contrib.auth.User and the second one is Product, created by me. For every product I would add the comments, so every User registered can insert a comment for every product. I've see there's django.contrib.comments, but probably it...
Django comments
I have a Django application with two models: the first one is django.contrib.auth.User and the second one is Product, created by me. For every product I would add the comments, so every User registered can insert a comment for every product. I've see there's django.contrib.comments, but probably it's for the blog-like ...
[ "What you've described sounds extremely simple, and perfect for Django's in-built comment app. Just because it allows anonymous users to comment doesn't mean that's a requirement, you can easily prevent anonymous users from commenting by simply not displaying the comment form for non-authenticated users.\nYou shoul...
[ 5, 0 ]
[]
[]
[ "django", "django_apps", "django_comments", "python" ]
stackoverflow_0006713990_django_django_apps_django_comments_python.txt
Q: Python and Django IDE with remote editing? I'm looking for an IDE that will allow me to edit remote Python projects and also has decent Django support, remote command execution, and maybe remote debugging. I've tried PyCharm and Aptana with PyDev but I'm not having much luck configuring them for remote editing. T...
Python and Django IDE with remote editing?
I'm looking for an IDE that will allow me to edit remote Python projects and also has decent Django support, remote command execution, and maybe remote debugging. I've tried PyCharm and Aptana with PyDev but I'm not having much luck configuring them for remote editing. Thanks for your help!
[ "I have Pycharm setup on a Ubuntu 10.10. The key is to use \"sshfs\" - it maps to my web-host - via ssh. Those are the pre-reqs : ssh access, sshfs. (unless you can figure out a way to map ssh to a windows shared drive).\nSo once ssh, sshfs are setup, I create a linux mount locally - so my webhost's directory appe...
[ 6, 2, 0 ]
[]
[]
[ "django", "ide", "python" ]
stackoverflow_0006435000_django_ide_python.txt
Q: Numpy/IPython equivalent to Matlab's assignin I'm in the process of moving some of our internal data visualization/analysis tools from Matlab to IPython/Numpy/Scipy/PyLab. The tools I refer to are Matlab GUIs which do only simple kinds of analysis. Occasionally, I want to do more sophisticated analysis in which ...
Numpy/IPython equivalent to Matlab's assignin
I'm in the process of moving some of our internal data visualization/analysis tools from Matlab to IPython/Numpy/Scipy/PyLab. The tools I refer to are Matlab GUIs which do only simple kinds of analysis. Occasionally, I want to do more sophisticated analysis in which case I press a button in the GUI which executes Mat...
[ "Take a look at the global namespace. Practically, I'd use something like following code, depending on whether your variable has a static name or the name can change dynamically.\ndef staticAssignInBase():\n global x\n x = 'someValue'\n\ndef dynamicAssignInBase():\n g = globals()\n g['someVarName'] = 's...
[ 3 ]
[]
[]
[ "ipython", "matlab", "matplotlib", "numpy", "python" ]
stackoverflow_0006709387_ipython_matlab_matplotlib_numpy_python.txt
Q: Custom wrapper for indexing python list starting at 1 I'd like to write a simple wrapper for the python list type that forces it to start indexing at 1 instead of 0. I've got a a fairly complex program based on some discrete probability distributions of duration data, with integer-length buckets, but I don't have ...
Custom wrapper for indexing python list starting at 1
I'd like to write a simple wrapper for the python list type that forces it to start indexing at 1 instead of 0. I've got a a fairly complex program based on some discrete probability distributions of duration data, with integer-length buckets, but I don't have any durations of less than 1. Anyway, it would greatly simp...
[ "Here's a complete (I think) implementation of a 1-based list, correctly handling slicing (including extended slices), indexing, popping, etc. It's slightly more tricky to get this right than you might think, especially the slicing and the negative indexes. In fact I'm still not 100% sure it works exactly as it sh...
[ 3, 1, 1 ]
[]
[]
[ "list", "operator_overloading", "python", "types", "wrapper" ]
stackoverflow_0006713463_list_operator_overloading_python_types_wrapper.txt
Q: Unable to open a connection to PostgreSQL from Python3 I'm running into a weird problem where I'm unable to connect to PostgreSQL from a Python 3.2 install. I'm running Fedora 15 and have installed Python3 and PostgerSQL9 from the Fedora repositories using yum. Does anyone have any ideas on why I'm seeing this p...
Unable to open a connection to PostgreSQL from Python3
I'm running into a weird problem where I'm unable to connect to PostgreSQL from a Python 3.2 install. I'm running Fedora 15 and have installed Python3 and PostgerSQL9 from the Fedora repositories using yum. Does anyone have any ideas on why I'm seeing this problem and how to correct it? Google searches haven't been ...
[ "I think that probably is some bug in python3-postgresql package, but it looks like it works after little change. Edit this file (probably /usr/lib64 for 64 bit installations):\n/usr/lib/python3.2/site-packages/postgresql/protocol/client3.py\n\nChange (line 514):\nelement.Startup(**startup), password\n\nto:\nelemen...
[ 4, 0, 0 ]
[]
[]
[ "postgresql", "py_postgresql", "python", "python_3.x" ]
stackoverflow_0006685277_postgresql_py_postgresql_python_python_3.x.txt
Q: pylint warning on 'except Exception:' For a block like this: try: #some stuff except Exception: pass pylint raises warning W0703 'Catch "Exception"'. Why? A: It's considered good practice to not normally catch the root Exception object, instead of catching more specific ones - for example IOException. C...
pylint warning on 'except Exception:'
For a block like this: try: #some stuff except Exception: pass pylint raises warning W0703 'Catch "Exception"'. Why?
[ "It's considered good practice to not normally catch the root Exception object, instead of catching more specific ones - for example IOException.\nConsider if an out of memory exception occurred - simply using \"pass\" isn't going to leave your programme in a good state.\nPretty much the only time you should catch ...
[ 35, 19, 3, 1, 1 ]
[ "Catching Exception (without re-raising) has 2 really bad side effects: errors get eaten, so you lose the stack trace, but also that ctrl-c (or whatever the break key is on your operating system) also gets handled here.\nThe typical behavior of programs like this is that either they can't be stopped, or that ctrl-c...
[ -1 ]
[ "pylint", "python" ]
stackoverflow_0000756180_pylint_python.txt
Q: how do you inherit Queue in Python when I inherit Queue i get an error: super(domainQueue,self).__init__() TypeError: must be type, not classobj and when I read up on it, something about classic classes etc. How do I initialize the base Queue class? A: Queue.Queue is an old-style class, and as such it doesn't s...
how do you inherit Queue in Python
when I inherit Queue i get an error: super(domainQueue,self).__init__() TypeError: must be type, not classobj and when I read up on it, something about classic classes etc. How do I initialize the base Queue class?
[ "Queue.Queue is an old-style class, and as such it doesn't support many of the features of new-style classes (such as super). You have two choices, to call Queue.Queue explicitly as suggested in TorelTwiddler's answer, or to add object to the bases:\nclass myQueue(Queue.Queue, object):\n def __init__(self):\n ...
[ 5, 1 ]
[]
[]
[ "python", "python_2.7", "queue" ]
stackoverflow_0006714040_python_python_2.7_queue.txt
Q: setuptools: data files included with `bdist` but not with `sdist` I've got a setup.py file which looks like this: #!/usr/bin/env python from setuptools import setup, find_packages setup( name="foo", version="1.0", packages=find_packages(), include_package_data=True, package_data={ "": ...
setuptools: data files included with `bdist` but not with `sdist`
I've got a setup.py file which looks like this: #!/usr/bin/env python from setuptools import setup, find_packages setup( name="foo", version="1.0", packages=find_packages(), include_package_data=True, package_data={ "": ["*"], }, ) And a package foo which looks like this: foo/__init__....
[ "There are different sources for selecting those files. The package_data is used for installing from the source tree. The build a source package you also need a MANIFEST.in file. It should contain something like recursive-include *.txt, or whatever you need. \n" ]
[ 12 ]
[]
[]
[ "python", "setup.py", "setuptools" ]
stackoverflow_0006714145_python_setup.py_setuptools.txt
Q: Python script to test for most recently modified file - inconsistent results I found this post on stackoverflow which was exactly what I wanted to integrate into a larger script I am writing: Find the newest folder in a directory in Python I want to check for the newest file or folder so modified the script for t...
Python script to test for most recently modified file - inconsistent results
I found this post on stackoverflow which was exactly what I wanted to integrate into a larger script I am writing: Find the newest folder in a directory in Python I want to check for the newest file or folder so modified the script for testing as follows: #!/usr/bin/env python3.1 import os def allFilesIn(b='.'): ...
[ "Your function allFilesIn only returns the last file returned by os.listdir because you append the results outside of the for loop. You probably meant this:\ndef allFilesIn(b='.'):\n result = []\n for d in os.listdir(b):\n bd = os.path.join(b, d)\n result.append(bd)\n return result\n\nAs an a...
[ 1 ]
[]
[]
[ "directory", "file", "python", "testing" ]
stackoverflow_0006714491_directory_file_python_testing.txt
Q: django-comments questions I've just implemented django-comments. settings.py INSTALLED_APPS = ( ... 'django.contrib.comments', ) product_detail.html {% get_comment_count for product as comment_count %} <p>This event has {{ comment_count }} comments.</p> {% render_comment_list for product %} {% render_com...
django-comments questions
I've just implemented django-comments. settings.py INSTALLED_APPS = ( ... 'django.contrib.comments', ) product_detail.html {% get_comment_count for product as comment_count %} <p>This event has {{ comment_count }} comments.</p> {% render_comment_list for product %} {% render_comment_form for product %} templ...
[ "Line 4 seems ok? I see no problem at least ;) But of course always test your code :)\nThe removal is a bit hackish, but that is also because the templatinglanguage is a bit limited. If you have a recent version you can probably use the in operator though: https://docs.djangoproject.com/en/dev/ref/templates/builtin...
[ 2 ]
[]
[]
[ "django", "django_comments", "django_contrib", "python" ]
stackoverflow_0006714497_django_django_comments_django_contrib_python.txt
Q: convert list to string then back it to list [ Python] I got a problem, it's about converting from List to String to edit it I have file text content these name Roby Bucky johan Then I want to add beside each one OK:1 so i do this code Names='a.txt' # here is the names O=open(Names,'r') # we open the file content...
convert list to string then back it to list [ Python]
I got a problem, it's about converting from List to String to edit it I have file text content these name Roby Bucky johan Then I want to add beside each one OK:1 so i do this code Names='a.txt' # here is the names O=open(Names,'r') # we open the file content the names iamList=O.readlines() # read the name it would b...
[ "You don't need to convert it to a string to add Ok:1 at the end of each element.\nYou could do it with a list comprehension like this:\niamNewList = [e.rstrip() + 'Ok:1' for e in iamList]\n\nAlternatively, to be less fancy, you could do this:\niamNewList = []\nfor e in iamList:\n iamNewList.append(e.rstrip() + ...
[ 2, 1, 0, 0 ]
[]
[]
[ "edit", "python", "strip" ]
stackoverflow_0006714472_edit_python_strip.txt
Q: How do I run a function in a Python module using only the Windows command line? To clarify, the Python module I'm writing is a self-written .py file (named converter), not one that comes standard with the Python libraries. Anyways, I want to somehow overload my function such that typing in converter file_name wi...
How do I run a function in a Python module using only the Windows command line?
To clarify, the Python module I'm writing is a self-written .py file (named converter), not one that comes standard with the Python libraries. Anyways, I want to somehow overload my function such that typing in converter file_name will send the file's name to def converter(file_name): # do something I've been e...
[ "You can use something like PyInstaller to create a exe out of your py-file.\nTo use the argument in python:\nimport sys\n\nif __name__ == \"__main__\":\n converter(sys.argv[1])\n\n", "You can type in the windows shell:\npython converter.py file_name.txt\n\nto give the arguments to the sys.argv list within pyt...
[ 2, 1, 0, 0 ]
[]
[]
[ "command_line", "python" ]
stackoverflow_0006714151_command_line_python.txt
Q: This takes a long time...how do I speed this dictionary up? (python) meta_map = {} results = db.meta.find({'corpus_id':id, 'method':method}) #this Mongo query only takes 3ms print results.explain() #result is mongo queryset of 2000 documents count = 0 for r in results: count += 1 ...
This takes a long time...how do I speed this dictionary up? (python)
meta_map = {} results = db.meta.find({'corpus_id':id, 'method':method}) #this Mongo query only takes 3ms print results.explain() #result is mongo queryset of 2000 documents count = 0 for r in results: count += 1 print count word = r.get('word') data = r.get('data...
[ "Instead of\nif not meta_map.has_key(word):\n\nyou should use\nif word not in meta_map:\n\nThere is no point in doing data = r.get('data',{}) if you are not going to use it.\nIt's not obvious why you are doing word = r.get('word') ... if 'word' always exists in r, you should just use word = r['word']; otherwise you...
[ 3, 2 ]
[ "If your problem really is the dictionary, maybe using setdefault() instead of first looking the key up and then setting it can help.\n" ]
[ -1 ]
[ "database", "mongodb", "python" ]
stackoverflow_0006714438_database_mongodb_python.txt