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: Nose / Nosegae: Import problems I have this problem and it's drivin' me nuts! So I am developing my first real Google App Engine application and I always like to discover things while writing tests. So I have the following setup: I have a virtualenv with nose, nosegae, webtest and gaetestbed. It's called porksvr. I activate my virtualenv like this: source porksvr/bin/activate To run nose I use the following command: nosetests --with-gae --gae-lib-root /home/fs/gae This gives me the following error DEBUG: Access to module file denied: /home/fs/work/gaecode/porksvr/lib/python2.6/site-packages/webtest So at first I thought "okay, nose is running the application in the 'context' of the dev_appserver so it doesn't know about webtest". But to be sure I created a new directory and added a small GAE application. It's just 3 files: -main.py -app.yaml -test_huh.py ( imports the webtest module. ) Now what really confused me is that this just works. I run the nosetests cmds and it's actually passing my tests. So I started digging in my application to find out what could be different but I really hit a wall. I first thought that it might be a permission problem since the error says 'access ...denied' but I couldn't really find anything special. Next I thought maybe it's because I created my application before the virtualenv but I couldn't really see how this can be a problem. So if anybody has a clue why this happens I would be really really grateful. A: Nose-GAE has some documented issues when you're using virtualenv. You might try using using nose's --without-sandbox flag. A: Great so after hours of trying I actually just solved my problem right after asking this question. What fixed it was to create the virtualenv with the following switch --no-site-packages. Apparently I had a copy of webtest in my system's Python that somehow gave problems with my virtualenv. I should have noticed it when I tried to pip install webtest in my virtualenv and it said it already existed. Still not 100% sure why some apps worked and others didn't.
Nose / Nosegae: Import problems
I have this problem and it's drivin' me nuts! So I am developing my first real Google App Engine application and I always like to discover things while writing tests. So I have the following setup: I have a virtualenv with nose, nosegae, webtest and gaetestbed. It's called porksvr. I activate my virtualenv like this: source porksvr/bin/activate To run nose I use the following command: nosetests --with-gae --gae-lib-root /home/fs/gae This gives me the following error DEBUG: Access to module file denied: /home/fs/work/gaecode/porksvr/lib/python2.6/site-packages/webtest So at first I thought "okay, nose is running the application in the 'context' of the dev_appserver so it doesn't know about webtest". But to be sure I created a new directory and added a small GAE application. It's just 3 files: -main.py -app.yaml -test_huh.py ( imports the webtest module. ) Now what really confused me is that this just works. I run the nosetests cmds and it's actually passing my tests. So I started digging in my application to find out what could be different but I really hit a wall. I first thought that it might be a permission problem since the error says 'access ...denied' but I couldn't really find anything special. Next I thought maybe it's because I created my application before the virtualenv but I couldn't really see how this can be a problem. So if anybody has a clue why this happens I would be really really grateful.
[ "Nose-GAE has some documented issues when you're using virtualenv.\nYou might try using using nose's --without-sandbox flag.\n", "Great so after hours of trying I actually just solved my problem right after asking this question.\nWhat fixed it was to create the virtualenv with the following switch --no-site-packa...
[ 6, 2 ]
[]
[]
[ "google_app_engine", "nose", "python" ]
stackoverflow_0003580134_google_app_engine_nose_python.txt
Q: How to send an e-mail from a Python script that is being run on "Google App Engine"? How could I send an e-mail from my Python script that is being run on "Google App Engines" to one of my mail boxes? I am just a beginner and I have never tried sending a message from a Python script. I have found this script (IN THIS TUTORIAL): Here is the same script as a quote: import sys, smtplib fromaddr = raw_input("From: ") toaddr = string.splitfields(raw_input("To: "), ',') print "Enter message, end with ^D:" msg = '' while 1: line = sys.stdin.readline() if not line: break msg = msg + line # The actual mail send server = smtplib.SMTP('localhost') server.sendmail(fromaddr, toaddrs, msg) server.quit() but I hardly understand how I could have this script run from "Google App Engine": 1) Firstly, I don't quite understand what e-mail address I need to place right after From: in this line: fromaddr = raw_input("From: ") Can I just place here any e-mail address of any e-mail boxes that I have? 2) Secondly, let's say I want to send a message to this e-mail address of mine brilliant@yahoo.com . Then the next line, I guess, must look this way: toaddr = string.splitfields(raw_input("To: brilliant@yahoo.com"), ',') Is this right? 3) Thirdly, let's say, the message that I want to send will be this sentence: Cats cannot fly! Then, I guess, the line that starts with msg = must look this way: msg = 'Cats cannot fly!' Is this correct? 4) If I upload this script as an application to "GAE", how often will it be sending this message to my mail box? Will it send this message to me only once or it will be sending it to me every second all the time until I delete the application? (This is why I haven't tried uploading this script so far) Thank You all in advance for Your time and patience. A: Sure - just use the Mail API as outlined in the docs: Python Java
How to send an e-mail from a Python script that is being run on "Google App Engine"?
How could I send an e-mail from my Python script that is being run on "Google App Engines" to one of my mail boxes? I am just a beginner and I have never tried sending a message from a Python script. I have found this script (IN THIS TUTORIAL): Here is the same script as a quote: import sys, smtplib fromaddr = raw_input("From: ") toaddr = string.splitfields(raw_input("To: "), ',') print "Enter message, end with ^D:" msg = '' while 1: line = sys.stdin.readline() if not line: break msg = msg + line # The actual mail send server = smtplib.SMTP('localhost') server.sendmail(fromaddr, toaddrs, msg) server.quit() but I hardly understand how I could have this script run from "Google App Engine": 1) Firstly, I don't quite understand what e-mail address I need to place right after From: in this line: fromaddr = raw_input("From: ") Can I just place here any e-mail address of any e-mail boxes that I have? 2) Secondly, let's say I want to send a message to this e-mail address of mine brilliant@yahoo.com . Then the next line, I guess, must look this way: toaddr = string.splitfields(raw_input("To: brilliant@yahoo.com"), ',') Is this right? 3) Thirdly, let's say, the message that I want to send will be this sentence: Cats cannot fly! Then, I guess, the line that starts with msg = must look this way: msg = 'Cats cannot fly!' Is this correct? 4) If I upload this script as an application to "GAE", how often will it be sending this message to my mail box? Will it send this message to me only once or it will be sending it to me every second all the time until I delete the application? (This is why I haven't tried uploading this script so far) Thank You all in advance for Your time and patience.
[ "Sure - just use the Mail API as outlined in the docs:\n\nPython\nJava\n\n" ]
[ 10 ]
[]
[]
[ "email", "google_app_engine", "python" ]
stackoverflow_0003595438_email_google_app_engine_python.txt
Q: is there a way to use im.putpixel rather than im.paste srcImage.paste(letters['H'], (10,15)) The above code will paste the letter H on the image (srcimage). letters is dict which contains the font images.. I cannot use paste in my assignment but i can use getpixel, load, putpixel, and save. I tried this but this is giving error: srcImage.putpixel((10,15),letters['H']) Error is: File "C:\Users\Naveen\Desktop\a1\a1_template.py", line 23, in doLOLImage srcImage.putpixel((10,15),letters['H']) File "C:\Python26\lib\site-packages\PIL\Image.py", line 1267, in putpixel return self.im.putpixel(xy, value) SystemError: new style getargs format but argument is not a tuple can you please provide me how to do this function of paste just using getpixel, putpixel, load, and save. A: I'm not familiar with PIL and the details of your assignment, so this will be pseudocode: for every pixel in letter['H']: putpixel (at position + position in letter['H']) Essentially, get every pixel and its position in the letter, and put that pixel into the image at the position you're currently at plus the position of the pixel in the letter. (thinking from the top left) – in other words, copy the image (letter['H']) pixel by pixel.
is there a way to use im.putpixel rather than im.paste
srcImage.paste(letters['H'], (10,15)) The above code will paste the letter H on the image (srcimage). letters is dict which contains the font images.. I cannot use paste in my assignment but i can use getpixel, load, putpixel, and save. I tried this but this is giving error: srcImage.putpixel((10,15),letters['H']) Error is: File "C:\Users\Naveen\Desktop\a1\a1_template.py", line 23, in doLOLImage srcImage.putpixel((10,15),letters['H']) File "C:\Python26\lib\site-packages\PIL\Image.py", line 1267, in putpixel return self.im.putpixel(xy, value) SystemError: new style getargs format but argument is not a tuple can you please provide me how to do this function of paste just using getpixel, putpixel, load, and save.
[ "I'm not familiar with PIL and the details of your assignment, so this will be pseudocode:\nfor every pixel in letter['H']:\n putpixel (at position + position in letter['H'])\n\nEssentially, get every pixel and its position in the letter, and put that pixel into the image at the position you're currently at plus...
[ 0 ]
[]
[]
[ "python", "python_imaging_library" ]
stackoverflow_0003568650_python_python_imaging_library.txt
Q: Is there a way to find the second longest word in a sentence in Python? I got stuck on this idea: how do I get the second longest word in a sentence ? I'm going to use it for an exit route in my code where the longest word might fail a test. Any ideas ? Thanks in advance. A: something like this: second_longest = sorted(sentence.split(), key=len)[-2] This is a pretty naive definition of word however, since it only splits on whitespace so any punctuation will be included as part of the words. You may want to filter the sentence to remove punctuation characters first.
Is there a way to find the second longest word in a sentence in Python?
I got stuck on this idea: how do I get the second longest word in a sentence ? I'm going to use it for an exit route in my code where the longest word might fail a test. Any ideas ? Thanks in advance.
[ "something like this:\nsecond_longest = sorted(sentence.split(), key=len)[-2]\n\nThis is a pretty naive definition of word however, since it only splits on whitespace so any punctuation will be included as part of the words. You may want to filter the sentence to remove punctuation characters first.\n" ]
[ 5 ]
[]
[]
[ "process", "python", "text", "word" ]
stackoverflow_0003595810_process_python_text_word.txt
Q: start python script as background process from within a python script My python script needs to start a background process and then continue processing to completion without waiting for a return. The background script will process for some time and will not generate any screen output. There is no inter-process data required. I have tried using various methods subprocess, multiprocessing but am clearly missing something. Does anyone have a simple example? TIA A: how about this: import subprocess from multiprocessing import Process Process(target=subprocess.call, args=(('ls', '-l', ), )).start() It's not all that elegant, but it fulfils all your requirements. A: Simple: subprocess.Popen(["background-process", "arguments"]) If you want to check later whether the background process completed its job, retain a reference to the Popen object and use it's poll() method. A: There is a nice writeup of the various pieces/parts on how to do it at Calling an external command in Python (per @lecodesportif). The gist of a quick answer is: retcode = subprocess.call(["ls", "-l"])
start python script as background process from within a python script
My python script needs to start a background process and then continue processing to completion without waiting for a return. The background script will process for some time and will not generate any screen output. There is no inter-process data required. I have tried using various methods subprocess, multiprocessing but am clearly missing something. Does anyone have a simple example? TIA
[ "how about this:\nimport subprocess\nfrom multiprocessing import Process\n\nProcess(target=subprocess.call, args=(('ls', '-l', ), )).start()\n\nIt's not all that elegant, but it fulfils all your requirements.\n", "Simple:\nsubprocess.Popen([\"background-process\", \"arguments\"])\n\nIf you want to check later whe...
[ 3, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003595685_python.txt
Q: How to put 2 lists into 1 Dictionary in Python? So this is the situation: I have 2 lists and want to put them in a dictionary. Content ['This is Sams Content', 'This is someone's else content'] Author ['Sam', 'Someone Else'] This is the dictionary I would like to create Reviews [{'content': 'This is Sams Content', 'author' : 'Sam'} , {'content': 'This is someone's else content', 'author' : 'Someone Else'} I hope you understand what the question is. Thanks for helping. A: You're looking for zip I believe. Something like this: reviews = [{'content': c, 'author': a} for c, a in zip(contentList, authorList)] A: content = ['This is Sams Content', 'This is someone\'s else content'] author = ['Sam', 'Someone Else'] reviews = [] for i in range(len(author)): d = { 'content': content[i], 'author': author[i] } reviews.append(d) for r in reviews: print "Author: %s, content: %s" % (r['author'], r['content']) EDIT for those who complained that range(len(...)) isn't sufficiently Pythonic (to which I say merely "seriously?"), here's the same solution using enumerate() as suggested: content = ['This is Sams Content', 'This is someone\'s else content'] author = ['Sam', 'Someone Else'] reviews = [] for i, elem in enumerate(author): d = { 'content': content[i], 'author': elem, } reviews.append(d) for r in reviews: print "Author: %s, content: %s" % (r['author'], r['content']) Personally I prefer the range(len(...)) solution over enumerate, because accessing both arrays in the same style when creating the hash aids readability. zip is still the most elegant solution though. A: reviews = [] authors = ['sam', 'dave'] content = ['content by sam', 'content by dave'] for a, c in zip(authors, content): reviews.append({'content':c, 'author':a}) print reviews A: Assuming Content and Author are arrays as defined in the question, and assuming you want a single resulting dict: d = {} for i in range(len(Content)): d[Content[i]] = Author[i]
How to put 2 lists into 1 Dictionary in Python?
So this is the situation: I have 2 lists and want to put them in a dictionary. Content ['This is Sams Content', 'This is someone's else content'] Author ['Sam', 'Someone Else'] This is the dictionary I would like to create Reviews [{'content': 'This is Sams Content', 'author' : 'Sam'} , {'content': 'This is someone's else content', 'author' : 'Someone Else'} I hope you understand what the question is. Thanks for helping.
[ "You're looking for zip I believe. Something like this:\nreviews = [{'content': c, 'author': a} for c, a in zip(contentList, authorList)]\n\n", "content = ['This is Sams Content', 'This is someone\\'s else content'] \nauthor = ['Sam', 'Someone Else']\n\nreviews = []\n\nfor i in range(len(author)):\n d = {\n ...
[ 7, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003595869_python.txt
Q: Problem building a list of class objects in python I'm still new to python, and been stuck playing around with this for a while and would appreciate someone pointing out where I'm going wrong. Basically I am trying to build a list that contains a number of different objects, with each object having several attributes. My attempt is simplified and shown below, basically I built a class for this object, containing several values, and then tried to build a list to contain the objects - it doesn't seem to be heading anywhere successful! Any suggestions would be greatly appreciated. class TagData(object): def __init__(self): self.tag = [] self.val = [] self.rel = [] self.database = [] self.description = [] tagvalue='xxx' tagList=[] tagList.append(TagData.tag(tagvalue)) tagList.append(TagData.val(val1)) Currently I am getting an error saying TagData has no attribute 'tag' Thanks, A: First, you need to create an instance of TagData, like this: TagData() This is why you are getting the AttributeError, because when you use TagData.tag(...), you are really trying to call the tag method of the TagData class object, instead of setting a property of a specific instance. Next, you need to assign to a property or create a method to set it. For example, you could add a method like this to your class: def addVal(self,value): self.val.append(value) And then: a=TagData() a.addVal('value') tagList.append(a) Or you could do this (if you don't wish to define getters/setters): a=TagData() a.val.append('text') tagList.append(a) Do not do all of that on one line, because when you call addVal, it will return None - and then you will append None to your list instead of your object. A: [] declares a list, so your member variables tag, val, rel etc are all list values, but it sounds like they really want to be scalars? So try this in your constructor: def __init__(self): self.tag = None self.val = None # etc Then you'd do something like this to create your objects: td = TagData() td.tag = tagvalue td.val = 'foo' tagList.append(td) If you want to be able to specify tag and val in the constructor call, you need to add constructor arguments. Here's one way: def __init__(self, tag=None, val=None): self.tag = tag self.val = val # etc Then: tagList.append(TagData(tag=tagvalue)) tagList.append(TagData(val='foo')) A: The immediate problem is that you are not instantiating TagData. The attributes inside __init__ are instance attributes (note the self. prefix used to set them for an instance) and not class attributes. Try the same code with an instance of TagData created thus: TagData() The broader problem is that I don't exactly understand what you are trying to do. Without that it is hard to answer your question better. Adding more context to your question would help.
Problem building a list of class objects in python
I'm still new to python, and been stuck playing around with this for a while and would appreciate someone pointing out where I'm going wrong. Basically I am trying to build a list that contains a number of different objects, with each object having several attributes. My attempt is simplified and shown below, basically I built a class for this object, containing several values, and then tried to build a list to contain the objects - it doesn't seem to be heading anywhere successful! Any suggestions would be greatly appreciated. class TagData(object): def __init__(self): self.tag = [] self.val = [] self.rel = [] self.database = [] self.description = [] tagvalue='xxx' tagList=[] tagList.append(TagData.tag(tagvalue)) tagList.append(TagData.val(val1)) Currently I am getting an error saying TagData has no attribute 'tag' Thanks,
[ "First, you need to create an instance of TagData, like this:\nTagData()\n\nThis is why you are getting the AttributeError, because when you use TagData.tag(...), you are really trying to call the tag method of the TagData class object, instead of setting a property of a specific instance.\nNext, you need to assign...
[ 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003595890_python.txt
Q: Good way to Django-based website, installing prerequisites if needed Consider a website build using python and django. In many cases it uses 3rd party modules beside standard python library - such as pytz, South, timezones or debug toolbar. What is standard or just convenient way to deploy such application to production hosting with all the prerequisites (timezones, etc) installed automatically? I'm new to python, and sorry if this question is lame. A: There are at least two options available. Jacob Kaplan-Moss, one of the co founders of Django has written about packaging an application using buildout and djangorecipe. There is also the versatile fabric. You should be able to tackle your problem using either of these alone or in combination with some custom scripts. A: Fabric is definitely a nice way to accomplish this. There is a fairly extensive blog write up on the process at http://www.caktusgroup.com/blog/2010/04/22/basic-django-deployment-with-virtualenv-fabric-pip-and-rsync/. The key to fabric is "fabfile.py" - there's an example of one that does a deployment at http://bitbucket.org/copelco/caktus-deployment/src/tip/example-django-project/caktus_website/fabfile.py. The variation of this that I've used to deploy to a Linode instance is http://gist.github.com/556508 A: You can either use a deployment solution like fabric (http://fabfile.org/) or you can try to package the entire thing up into a python egg with dependencies that will be automatically installed when you easy_install it. See http://mxm-mad-science.blogspot.com/2008/02/python-eggs-simple-introduction.html for a simple introduction to python eggs.
Good way to Django-based website, installing prerequisites if needed
Consider a website build using python and django. In many cases it uses 3rd party modules beside standard python library - such as pytz, South, timezones or debug toolbar. What is standard or just convenient way to deploy such application to production hosting with all the prerequisites (timezones, etc) installed automatically? I'm new to python, and sorry if this question is lame.
[ "There are at least two options available. Jacob Kaplan-Moss, one of the co founders of Django has written about packaging an application using buildout and djangorecipe. There is also the versatile fabric. You should be able to tackle your problem using either of these alone or in combination with some custom scri...
[ 3, 2, 1 ]
[]
[]
[ "dependencies", "deployment", "django", "installation", "python" ]
stackoverflow_0003595884_dependencies_deployment_django_installation_python.txt
Q: Place a Button in ListCtrl - wxPython Is is possible to place a button inside of a ListCtrl item with wxPython? Right now I have a ListCtrl that has data with a file name and size, and I want the user to be able to click a button, to download the file. If this isn't possible, is there a way to display an image in the ListCtrl, and then make it clickable so that I can bind an action to it? A: No. You will have to use "UltimateListControl", a generic list implementation that can attach any kind of widget to rows. Check its demo files for examples. You're probably best off grabbing the trunk code for bugfixes and other changes - I'm not sure how often Andrea updates the main zip on his site I've yet to use the control, but its demo is very impressive.
Place a Button in ListCtrl - wxPython
Is is possible to place a button inside of a ListCtrl item with wxPython? Right now I have a ListCtrl that has data with a file name and size, and I want the user to be able to click a button, to download the file. If this isn't possible, is there a way to display an image in the ListCtrl, and then make it clickable so that I can bind an action to it?
[ "No. You will have to use \"UltimateListControl\", a generic list implementation that can attach any kind of widget to rows. Check its demo files for examples. \nYou're probably best off grabbing the trunk code for bugfixes and other changes - I'm not sure how often Andrea updates the main zip on his site\nI've yet...
[ 4 ]
[]
[]
[ "python", "user_interface", "wxpython" ]
stackoverflow_0003595913_python_user_interface_wxpython.txt
Q: pyqt installation question Im planing to do some GUI development using pyqt4 pykde and python3.1 on Kubuntu 10.4. In the research I did I found out that most of the things are available as packages in repositories and some of the packages are preinstalled. Only thing is I'm not able to figure out what to install and what not to. Can someone please give me a list of packages that I need to install to do GUI development using python3.1 pyQt4 and pyKDE. A: The qt-designer is inside the new qtcreator (former package was qt-creator). install -doc packages as you like, also look for -examples, they are very helpful. for your convenience: aptitude install python31 python-qt4 python-qt4-doc pyqt4-dev-tools python-kde4 qtcreator For an IDE, look in question 1 or 2 A: I guess you need python-qt4 qt4-designer qt4-dev-tools.
pyqt installation question
Im planing to do some GUI development using pyqt4 pykde and python3.1 on Kubuntu 10.4. In the research I did I found out that most of the things are available as packages in repositories and some of the packages are preinstalled. Only thing is I'm not able to figure out what to install and what not to. Can someone please give me a list of packages that I need to install to do GUI development using python3.1 pyQt4 and pyKDE.
[ "The qt-designer is inside the new qtcreator (former package was qt-creator).\ninstall -doc packages as you like, also look for -examples, they are very helpful.\nfor your convenience:\naptitude install \n python31\n python-qt4 \n python-qt4-doc\n pyqt4-dev-tools\n python-kde4\n qtcreator\nFor an ...
[ 1, 0 ]
[]
[]
[ "linux", "pyqt4", "python", "ubuntu" ]
stackoverflow_0003385013_linux_pyqt4_python_ubuntu.txt
Q: Automating Excel macro using python I am using python in Linux to automate an excel. I have finished writing data into excel by using pyexcelerator package. Now comes the real challenge. I have to add another tab to the existing sheet and that tab should contain the macro run in the first tab. All these things should be automated. I Googled a lot and found win32come to do a job in macro, but that was only for windows. Anyone have any idea of how to do this, or can you guide me with few suggestions. A: Excel Macros are per sheets, so, I am afraid, you need to copy the macros explicitly if you created new sheet, instead of copying existing sheet to new one. A: You might find that Resolver One is better for what you want - it's a python-scriptable spreadsheet. A: Maybe manipulating your .xls with Openoffice and pyUno is a better way. Way more powerful.
Automating Excel macro using python
I am using python in Linux to automate an excel. I have finished writing data into excel by using pyexcelerator package. Now comes the real challenge. I have to add another tab to the existing sheet and that tab should contain the macro run in the first tab. All these things should be automated. I Googled a lot and found win32come to do a job in macro, but that was only for windows. Anyone have any idea of how to do this, or can you guide me with few suggestions.
[ "Excel Macros are per sheets, so, I am afraid, you need to copy the macros explicitly if you created new sheet, instead of copying existing sheet to new one.\n", "You might find that Resolver One is better for what you want - it's a python-scriptable spreadsheet.\n", "Maybe manipulating your .xls with Openoffic...
[ 0, 0, 0 ]
[]
[]
[ "automation", "excel", "linux", "python" ]
stackoverflow_0002697701_automation_excel_linux_python.txt
Q: django weighted questionnaire? I've been learning django off and on for a few years now and consider myself an advanced beginner, ha. I'm working on a "weighted questionnaire" (that's the best name I can give it anyway) for a client and have gone in circles about where to go with it. The client has come up with a series of yes or no questions and depending on the answer, certain weightings will be applied. At the end upon submission, I need to check for answers and add up the weightings than show a report with suggested products based on the weightings. The weightings are really just products with certain number values for each question. For example: "Do you smoke?" If answered "yes", then apply the following: Core(1), Alpha(4), Liver(2), Jade(1), Rejuve(4) I've setup initial models and admin but am kind of stumped with how to write the views. They'll be able to add questions with desired answers, then as many weightings (which are foreign keyed to products) and values per question as they want. Here are my models: from django.db import models from src.products.models import Product """ This app has 'yes' or 'no' questions. Each question has several 'weightings' atached to it which are tallied at the end to recommend specific products to the user doing the questionairre. """ class Question(models.Model): """Yes or no questions to gether enough info to recommend products via the weightings.""" ANSWER_CHOICES = ( ('y', 'Yes'), ('n', 'No'), ) GENDER_CHOICES = ( ('a', 'All'), ('m', 'Male'), ('f', 'Female'), ) question_text = models.CharField( help_text="The text to be displayed for the question", max_length=300 ) answer = models.CharField( help_text="Weightings will be applied based on the answer. <br> Ex: If 'Yes' is chosen for 'Do you smoke?', then weightings will be applied if the user answers 'Yes'", max_length=1, choices=ANSWER_CHOICES ) applies_to = models.CharField( help_text="Used to filter questions based on gender of user answering the questions.", max_length=1, choices=GENDER_CHOICES ) order = models.IntegerField( help_text="Used to determine the ordering of the questions. If left blank, the question will appear after those which are ordered.", blank=True, null=True, ) class Meta: verbose_name_plural = 'questions' ordering = ['order'] def __unicode__(self): return self.question_text class Weighting(models.Model): """References products with a specified weighting. Added up at end to recommend products.""" question = models.ForeignKey(Question) product = models.ForeignKey(Product) value = models.IntegerField() def __unicode__(self): return '%s %s %s' % (self.question, self.product, self.value) I'm manually creating the forms right now. I figure this is the best way. So, what'll be the best way to get the answers on post, then compare the answer with the desired answer and get the sum of the weightings across all questions? The last part with the sum seems the most difficult. Thoughts and suggestions? EDIT: Using for reference: http://questionnaire.corporatism.org/ A: What you are trying to do is basically setting up a many-to-many relationship between Question and Product and weighting this relation by adding a field to the relation (value); there's some documentation on that how to that in a django way! I guess you will need one more model to store the answers a user has given, it could be something like that: from django.contrib.auth.models import User class Answer(models.Model): user = models.ForeignKey(User) question = models.ForeignKey(Question) answer = models.CharField(choices=ANSWER_CHOICES, max_length=1) After you have stored the answers I guess the only way will be to iterate over one user's answers, answer by answer and sum up the values if the questions has the right answer! EDIT: This solution keeps the user's answer's persistent in the database, you have to think yourself what you want to do with them, otherwise you could just store them for a session eg. in a dictionary in request.session. EDIT: to get the questions in one form try something like: class QuestionForm(forms.Form): def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None, initial=None, error_class=ErrorList, label_suffix=':', empty_permitted=False): super(QuestionForm, self).__init__(data, files, auto_id, prefix, initial, error_class, label_suffix, empty_permitted) self.questions = Question.objects.all() if self.questions: for question in self.question: self.fields['question_%s' % question.pk] =\ forms.ChoiceField(label=question.question_text, choices=[(q.pk, q.answer) for q in question.answer_set.all()])
django weighted questionnaire?
I've been learning django off and on for a few years now and consider myself an advanced beginner, ha. I'm working on a "weighted questionnaire" (that's the best name I can give it anyway) for a client and have gone in circles about where to go with it. The client has come up with a series of yes or no questions and depending on the answer, certain weightings will be applied. At the end upon submission, I need to check for answers and add up the weightings than show a report with suggested products based on the weightings. The weightings are really just products with certain number values for each question. For example: "Do you smoke?" If answered "yes", then apply the following: Core(1), Alpha(4), Liver(2), Jade(1), Rejuve(4) I've setup initial models and admin but am kind of stumped with how to write the views. They'll be able to add questions with desired answers, then as many weightings (which are foreign keyed to products) and values per question as they want. Here are my models: from django.db import models from src.products.models import Product """ This app has 'yes' or 'no' questions. Each question has several 'weightings' atached to it which are tallied at the end to recommend specific products to the user doing the questionairre. """ class Question(models.Model): """Yes or no questions to gether enough info to recommend products via the weightings.""" ANSWER_CHOICES = ( ('y', 'Yes'), ('n', 'No'), ) GENDER_CHOICES = ( ('a', 'All'), ('m', 'Male'), ('f', 'Female'), ) question_text = models.CharField( help_text="The text to be displayed for the question", max_length=300 ) answer = models.CharField( help_text="Weightings will be applied based on the answer. <br> Ex: If 'Yes' is chosen for 'Do you smoke?', then weightings will be applied if the user answers 'Yes'", max_length=1, choices=ANSWER_CHOICES ) applies_to = models.CharField( help_text="Used to filter questions based on gender of user answering the questions.", max_length=1, choices=GENDER_CHOICES ) order = models.IntegerField( help_text="Used to determine the ordering of the questions. If left blank, the question will appear after those which are ordered.", blank=True, null=True, ) class Meta: verbose_name_plural = 'questions' ordering = ['order'] def __unicode__(self): return self.question_text class Weighting(models.Model): """References products with a specified weighting. Added up at end to recommend products.""" question = models.ForeignKey(Question) product = models.ForeignKey(Product) value = models.IntegerField() def __unicode__(self): return '%s %s %s' % (self.question, self.product, self.value) I'm manually creating the forms right now. I figure this is the best way. So, what'll be the best way to get the answers on post, then compare the answer with the desired answer and get the sum of the weightings across all questions? The last part with the sum seems the most difficult. Thoughts and suggestions? EDIT: Using for reference: http://questionnaire.corporatism.org/
[ "What you are trying to do is basically setting up a many-to-many relationship between Question and Product and weighting this relation by adding a field to the relation (value); there's some documentation on that how to that in a django way!\nI guess you will need one more model to store the answers a user has giv...
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003593756_django_python.txt
Q: How can I turn a list of words in a text file into a regex to filter out? I'm trying to filter out some text for certain keywords that are found in a text file. I was thinking about just parsing the file line by line, take each word and then merge them together with a pipe "|" then using that string inside re.sub. Any better more efficient ideas are welcome. A: Something like the following? import re with file('keywords.txt', 'r') as k: kwords = sorted(k.read().strip().split(), lambda x: (len(x), x)) searchstring = r'\s?\b(' + '|'.join(kwords) + r')\b' with file('textfile.txt', 'r') as t: text = t.read() newtext, _ = re.subn(searchstring, '', text).lstrip() A: Something like this without regexp? import string keyset = set(open('keywords.txt').read().splitlines()) for lineno,line in enumerate(open('textfile.txt')): result = [kw for kw in keyset for w in line.split() if kw in w and w.strip(string.punctuation) == kw] if result: print "%5s (%s): %s" % (lineno,', '.join(result), line),
How can I turn a list of words in a text file into a regex to filter out?
I'm trying to filter out some text for certain keywords that are found in a text file. I was thinking about just parsing the file line by line, take each word and then merge them together with a pipe "|" then using that string inside re.sub. Any better more efficient ideas are welcome.
[ "Something like the following?\nimport re\n\nwith file('keywords.txt', 'r') as k:\n kwords = sorted(k.read().strip().split(), lambda x: (len(x), x))\nsearchstring = r'\\s?\\b(' + '|'.join(kwords) + r')\\b'\nwith file('textfile.txt', 'r') as t:\n text = t.read()\nnewtext, _ = re.subn(searchstring, '', text).ls...
[ 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003595858_python_regex.txt
Q: python web service for massive usage I need to develp a real production webservice with python that will be used by another client application (with another progamming language ) . I mean in real production webservice that this webserivce is will be used on critical environment that failure of the webserivce could cause major problems. could someone provide /suggest which library to use in order to build such webservice with python ? I know that python has the built in simpleXMLRPCServer but i don't know its quality and if its apropriate for real production usage . A: Python has been used to develop production grade web services. There are numerous framework to do that. (Django, Twisted etc). You expect certain quality attributes from production grade servers like availability, scalability etc. For mission critical applications, availability becomes important. Your application architecture and development may influence these attributes more than the frameworks that you may use to develop them with. You can plan to provide extensive fault tolerance, redundant systems and various other strategies to improve availability. This applies to building application with Python framework too. Twisted is a very good framework to develop networking and web applications. There are other frameworks available in Python too, for example : Tornado etc You can go through certain twisted docs and also the following blog posts that can help understanding twisted better. Twisted in 60 seconds series A very good twisted introduction I have been exploring twisted basics and have posted a few notes at my blog Twisted docs: http://twistedmatrix.com/documents/10.1.0/web/howto/xmlrpc.html Python: deferToThread XMLRPC Server - Twisted - Cherrypy? http://nullege.com/codes/search/SimpleXMLRPCServer.SimpleXMLRPCDispatcher/all/1 http://code.activestate.com/recipes/526625-twisted-xml-rpc-server-with-basic-http-authenticat/ http://www.artima.com/weblogs/viewpost.jsp?thread=156396 Some projects along this line: http://freshmeat.net/projects/python-xmlrpc-server-w-ssl-authentication Django: https://launchpad.net/django-xmlrpc http://djangosnippets.org/snippets/2078/ http://www.drdobbs.com/184405364 http://www.davidfischer.name/2009/06/django-with-jsonrpc-and-xmlrpc/ Others: http://www.f4ntasmic.com/2009/03/simple-xmlrpc-server.html I hope this helps. :)
python web service for massive usage
I need to develp a real production webservice with python that will be used by another client application (with another progamming language ) . I mean in real production webservice that this webserivce is will be used on critical environment that failure of the webserivce could cause major problems. could someone provide /suggest which library to use in order to build such webservice with python ? I know that python has the built in simpleXMLRPCServer but i don't know its quality and if its apropriate for real production usage .
[ "Python has been used to develop production grade web services. There are numerous framework to do that. (Django, Twisted etc). \nYou expect certain quality attributes from production grade servers like availability, scalability etc. For mission critical applications, availability becomes important. Your applicati...
[ 6 ]
[]
[]
[ "python", "web_services" ]
stackoverflow_0003596094_python_web_services.txt
Q: python: reference "private" variables' names in an organized way Suppose I have a class, and I want to reference some elements in the ' __dict__ (for instance, I want to copy the dict and delete the attribute that cannot be pickled), from inside the class. Problem is, those attributes are "private" so my code ends up looking like so class MyClasss(object): def __init__(self): self.__prv=1 def __getstate__(self): ret=self.__dict__.copy() del ret['_MyClass__prv'] I reference the class name explicitly in the del statement, which looks a little ugly for me. Is there something nicer? something like MyClass.getPrivateString('prv') Of course I can implement one myself, but I would be surprised if there isn't a builtin to surpass this problem. A: Consider using only a single underscore for private attributes. These are still considered private but do not get name mangled. class MyClasss(object): def __init__(self): self._prv=1 def __getstate__(self): ret=self.__dict__.copy() del ret['_prv'] A: You might try to create a copy of the object, erase its private attributes and then return its __dict__, something like: class X: def __init__(self): self.__prv = 0 def del_privates(self): del self.__prv def __getstate__(self): other = X() other.__dict__ = self.__dict__.copy() other.del_privates() return other.__dict__ After calling __getstate__, the returned dict will not have the __prv member, since it gets erased when other.del_privates() is called. A: At the end, I used a variant of thieger's solution del ret["_%s__%s" % (MyClasss.__name__, "prv")] I think this is the most robust way I can write that piece of code, aside from giving up the mangling, which might be the right thing to do, but I was asking what to do in case you actually have mangling :) A: There is no shortcut, but if you just want to avoid naming the class explicitly, you can do something like: del ret["_%s__%s" % (self.__class__.__name__, "prv")]
python: reference "private" variables' names in an organized way
Suppose I have a class, and I want to reference some elements in the ' __dict__ (for instance, I want to copy the dict and delete the attribute that cannot be pickled), from inside the class. Problem is, those attributes are "private" so my code ends up looking like so class MyClasss(object): def __init__(self): self.__prv=1 def __getstate__(self): ret=self.__dict__.copy() del ret['_MyClass__prv'] I reference the class name explicitly in the del statement, which looks a little ugly for me. Is there something nicer? something like MyClass.getPrivateString('prv') Of course I can implement one myself, but I would be surprised if there isn't a builtin to surpass this problem.
[ "Consider using only a single underscore for private attributes. These are still considered private but do not get name mangled.\nclass MyClasss(object):\n def __init__(self):\n self._prv=1\n def __getstate__(self):\n ret=self.__dict__.copy()\n del ret['_prv']\n\n", "You might try...
[ 6, 1, 1, 0 ]
[ "Better to use your own naming convention for those attributes, such as _prv_x, _prv_y etc. then you can use a loop to selectively remove them\nclass MyClasss(object):\n def __init__(self):\n self._prv_x=1\n self._prv_y=1\n def __getstate__(self):\n return dict((k,v) for k,v in vars...
[ -1 ]
[ "obfuscation", "private", "python" ]
stackoverflow_0003579288_obfuscation_private_python.txt
Q: unsigned char* image to Python I was able to generate python bindings for a camera library using SWIG and I am able to capture and save image using the library's inbuilt functions. I am trying to obtain data from the camera into Python Image Library format, the library provides functions to return camera data as unsigned char* . Does anyone know how to convert unsigned char* image data into some data format that I can use in Python? Basically am trying to convert unsigned char* image data to Python Image Library format. Thank you. A: I believe you should use the fromstring method, as described here: How to read a raw image using PIL? Also, there's a good article on capturing data from the camera using python and opencv which is worth reading: http://www.jperla.com/blog/post/capturing-frames-from-a-webcam-on-linux A: Okay Guys, so finally after a long fight (maybe because am a newbie in python), I solved it. I wrote a data structure that could be understood by python and converted the unsigned char* image to that structure. After writing the interface for the custom data structure, I was able to get the image into Python Image Library image format. I wanted to paste the code here but it wont allow more tha 500 chars. Here's a link to my code http://www.optionsbender.com/technologybending/python/unsignedcharimagedatatopilimage I've also attached files so that you can use it. A: I'd assume those unsigned chars are the actual image bytes, so you could store those directly via: with open('filename', mode='wb') as file: file.write(image_bytes) (As long as you already have a file named filename in the current working directory.)
unsigned char* image to Python
I was able to generate python bindings for a camera library using SWIG and I am able to capture and save image using the library's inbuilt functions. I am trying to obtain data from the camera into Python Image Library format, the library provides functions to return camera data as unsigned char* . Does anyone know how to convert unsigned char* image data into some data format that I can use in Python? Basically am trying to convert unsigned char* image data to Python Image Library format. Thank you.
[ "I believe you should use the fromstring method, as described here:\nHow to read a raw image using PIL?\nAlso, there's a good article on capturing data from the camera using python and opencv which is worth reading: http://www.jperla.com/blog/post/capturing-frames-from-a-webcam-on-linux\n", "Okay Guys, so finally...
[ 1, 1, 0 ]
[]
[]
[ "c++", "pep3118", "python", "python_imaging_library", "unsigned_char" ]
stackoverflow_0003586003_c++_pep3118_python_python_imaging_library_unsigned_char.txt
Q: How do I manually add more cookies to a session which already has cookies set in mechanize? I have a python script which scrapes a page and receives a cookie. I want to append another cookie to the existing cookies that are being send to the server. So that on the next request I have the cookies from the original page plus ones I set manually. Anyway of doing this? I tried addheaders in mechanize but it was ignored. A: Use the set_cookie method: >>> import mechanize >>> br=mechanize.Browser() >>> br.set_cookie? Definition: br.set_cookie(self, cookie_string) Docstring: Request to set a cookie. Note that it is NOT necessary to call this method under ordinary circumstances: cookie handling is normally entirely automatic. The intended use case is rather to simulate the setting of a cookie by client script in a web page (e.g. JavaScript). In that case, use of this method is necessary because mechanize currently does not support JavaScript, VBScript, etc. The cookie is added in the same way as if it had arrived with the current response, as a result of the current request. This means that, for example, if it is not appropriate to set the cookie based on the current request, no cookie will be set. The cookie will be returned automatically with subsequent responses made by the Browser instance whenever that's appropriate. cookie_string should be a valid value of the Set-Cookie header. For example: browser.set_cookie( "sid=abcdef; expires=Wednesday, 09-Nov-06 23:12:40 GMT") Currently, this method does not allow for adding RFC 2986 cookies. This limitation will be lifted if anybody requests it.
How do I manually add more cookies to a session which already has cookies set in mechanize?
I have a python script which scrapes a page and receives a cookie. I want to append another cookie to the existing cookies that are being send to the server. So that on the next request I have the cookies from the original page plus ones I set manually. Anyway of doing this? I tried addheaders in mechanize but it was ignored.
[ "Use the set_cookie method:\n>>> import mechanize\n>>> br=mechanize.Browser()\n\n>>> br.set_cookie?\n\nDefinition: br.set_cookie(self, cookie_string)\nDocstring:\n Request to set a cookie.\n\n Note that it is NOT necessary to call this method under ordinary\n circumstances: cookie handling is normally enti...
[ 6 ]
[]
[]
[ "cookies", "mechanize", "python" ]
stackoverflow_0003596857_cookies_mechanize_python.txt
Q: Will Javascript V8 kill all the other server-side dynamic languages? Ruby, Python, PHP? That's all. It should be very nice to share the same libs on the client and on the server or not? Are JS VMs like HotRuby (http://hotruby.yukoba.jp/) a "real world" alternative or just a toy? PS: if I ask it is because I'd like know it, please don't close this question but just share your opinion. I'm not interested in programming language war. Put some benchmark if you know, or pros and cons I'm not comparing apples and pears https://stackoverflow.com/questions/3436335/could-node-js-replace-ruby-rails-completely-in-the-future I'm not a js fan A: Simply put: no. To use a bit longer explanation: Server-side javascript might put a big dent in currently used scripting languages, but it won't replace them for a few simple reasons: Legacy - there is a lot of code and libs out there already written for PHP, Python etc. Just like nobody is rushing to switch to Python3, nobody will be rushing to switch to server-side JavaScript. Brainfuck - JavaScript is, to most people, still a big brainfuck to code properly. People are used to imperative programming and 'normal' OOP. JavaScript is a strange mix between very weird OOP and functional programming. Not that this is bad, personally I love it, but it turns most mediocre programmers away. And let's face it, most programmers are mediocre. Price - while things running very fast is always nice. People are a lot more expensive these days than hardware is. Transforming everything to a new paradigm, or simply having people learn a whole new way of doing things is just ... expensive. Very expensive. Killer apps - this is related to point number 3. Until there is a very very very good reason to switch to server-side JavaScript people will not be willing to make the investment. Also, to top it all off, doing server-side stuff is so vastly different from doing browser-side stuff that there is almost no conceivable need for running the same code on both ends. Even the skills required to develop on each end are vastly different.
Will Javascript V8 kill all the other server-side dynamic languages? Ruby, Python, PHP?
That's all. It should be very nice to share the same libs on the client and on the server or not? Are JS VMs like HotRuby (http://hotruby.yukoba.jp/) a "real world" alternative or just a toy? PS: if I ask it is because I'd like know it, please don't close this question but just share your opinion. I'm not interested in programming language war. Put some benchmark if you know, or pros and cons I'm not comparing apples and pears https://stackoverflow.com/questions/3436335/could-node-js-replace-ruby-rails-completely-in-the-future I'm not a js fan
[ "Simply put: no.\nTo use a bit longer explanation: Server-side javascript might put a big dent in currently used scripting languages, but it won't replace them for a few simple reasons:\n\nLegacy - there is a lot of code and libs out there already written for PHP, Python etc. Just like nobody is rushing to switch t...
[ 12 ]
[]
[]
[ "javascript", "php", "python", "ruby" ]
stackoverflow_0003596875_javascript_php_python_ruby.txt
Q: Python: Get the redirect urls using cURL I am interested in getting the intermediate URLs in a redirect chain using pycURL. So, say I have a website, Site A, which redirects to Site B, which then redirects to Site C. Regularly I would only be able to see Site A (the starting URL) and Site C (the ending URL), however I am also interested in any sites that happen to reside in between the starting and ending site (in this case Site B). How would I go about doing this? A: Have a look to PyCurl Callbacks: ## Callback function invoked when header data is ready def header(buf): import sys sys.stdout.write(buf) # Returning None implies that all bytes were written c = pycurl.Curl() c.setopt(pycurl.URL, "http://www.siteA.com/") c.setopt(pycurl.HEADERFUNCTION, header) c.perform()
Python: Get the redirect urls using cURL
I am interested in getting the intermediate URLs in a redirect chain using pycURL. So, say I have a website, Site A, which redirects to Site B, which then redirects to Site C. Regularly I would only be able to see Site A (the starting URL) and Site C (the ending URL), however I am also interested in any sites that happen to reside in between the starting and ending site (in this case Site B). How would I go about doing this?
[ "Have a look to PyCurl Callbacks:\n## Callback function invoked when header data is ready\ndef header(buf):\n import sys\n sys.stdout.write(buf)\n # Returning None implies that all bytes were written\n\nc = pycurl.Curl()\nc.setopt(pycurl.URL, \"http://www.siteA.com/\")\nc.setopt(pycurl.HEADERFUNCTION, head...
[ 0 ]
[]
[]
[ "curl", "pycurl", "python" ]
stackoverflow_0003596968_curl_pycurl_python.txt
Q: WebTest: Testing with decorators + datastore calls I have a Google App Engine application and my request hadnler has a decorator that does authentication. With WebTest I found out yesterday how you can set a logged in user and administrator. Now today my authentication decorator got a little more complex. It's also checking if a user has a profile in the database and if he doesn't he'll get redirected to the 'new user' page. def authenticated(method): @functools.wraps(method) def wrapper(self, *args, **kwargs): user = users.get_current_user() if not user: self.redirect(users.create_login_url(self.request.uri)) return profile = Profile.get_by_key_name(str(user.user_id)) if not profile: self.redirect( '/newuser' ) return method(self, *args, **kwargs) return wrapper Now adding the profile part breaks my unit test that checks if a user is logged in and gets a status code 200(assertOK). def user_ok(self): os.environ['USER_EMAIL'] = 'info@example.com' os.environ['USER_IS_ADMIN'] = '' response = self.get( '/appindex' ) self.assertOK(response) So now I need to be able to somehow inject the profile functionality into the decorator so I can set it in my tests. Does anybody got an idea how to do this I've been trying to think of a way but I keep getting stuck. A: You should create a profile during the test, to be used by the decorator: def user_ok(self): key_name = 'info@example.com' new_user = Profile(key_name=key_name) new_user.put() os.environ['USER_EMAIL'] = key_name os.environ['USER_ID'] = key_name os.environ['USER_IS_ADMIN'] = '' response = self.get( '/appindex' ) self.assertOK(response) # Now let's reset it to check that the user will be redirected. new_user.delete() response = self.get( '/appindex' ) self.assertEqual(response.headers['Location'], 'http://localhost/newuser')
WebTest: Testing with decorators + datastore calls
I have a Google App Engine application and my request hadnler has a decorator that does authentication. With WebTest I found out yesterday how you can set a logged in user and administrator. Now today my authentication decorator got a little more complex. It's also checking if a user has a profile in the database and if he doesn't he'll get redirected to the 'new user' page. def authenticated(method): @functools.wraps(method) def wrapper(self, *args, **kwargs): user = users.get_current_user() if not user: self.redirect(users.create_login_url(self.request.uri)) return profile = Profile.get_by_key_name(str(user.user_id)) if not profile: self.redirect( '/newuser' ) return method(self, *args, **kwargs) return wrapper Now adding the profile part breaks my unit test that checks if a user is logged in and gets a status code 200(assertOK). def user_ok(self): os.environ['USER_EMAIL'] = 'info@example.com' os.environ['USER_IS_ADMIN'] = '' response = self.get( '/appindex' ) self.assertOK(response) So now I need to be able to somehow inject the profile functionality into the decorator so I can set it in my tests. Does anybody got an idea how to do this I've been trying to think of a way but I keep getting stuck.
[ "You should create a profile during the test, to be used by the decorator:\ndef user_ok(self):\n key_name = 'info@example.com'\n new_user = Profile(key_name=key_name)\n new_user.put()\n\n os.environ['USER_EMAIL'] = key_name\n os.environ['USER_ID'] = key_name\n os.environ['USER_IS_ADMIN'] = ''\n ...
[ 2 ]
[]
[]
[ "google_app_engine", "python", "unit_testing", "webtest", "wsgi" ]
stackoverflow_0003596958_google_app_engine_python_unit_testing_webtest_wsgi.txt
Q: GAE Datastore - Is there a next page / Are there x+1 entities? Currently, to determine whether or not there is a next page of entities I'm using the following code: q = Entity.all().fetch(10) cursor = q.cursor() extra = q.fetch(1) has_next_page = False if extra: has_next_page = True However, this is very expensive in terms of the time it takes to execute the 'extra' query. I need to extract the cursor after 10 results, but I need to fetch 11 to see if there is a succeeding page. Anyone have any better methods? A: If you fetch 11 items straight away you'll only have to fetch 1 extra item to know if there is a next page or not. And you can just display the first 10 results and use the 11th result only as a "next page" indicator.
GAE Datastore - Is there a next page / Are there x+1 entities?
Currently, to determine whether or not there is a next page of entities I'm using the following code: q = Entity.all().fetch(10) cursor = q.cursor() extra = q.fetch(1) has_next_page = False if extra: has_next_page = True However, this is very expensive in terms of the time it takes to execute the 'extra' query. I need to extract the cursor after 10 results, but I need to fetch 11 to see if there is a succeeding page. Anyone have any better methods?
[ "If you fetch 11 items straight away you'll only have to fetch 1 extra item to know if there is a next page or not. And you can just display the first 10 results and use the 11th result only as a \"next page\" indicator.\n" ]
[ 1 ]
[]
[]
[ "database", "google_app_engine", "google_cloud_datastore", "python", "scalability" ]
stackoverflow_0003597056_database_google_app_engine_google_cloud_datastore_python_scalability.txt
Q: How to use new Django 1.2 readonly_fields in ModelForm I'm trying to use the new readonly_fields in a ModelForm. class TrainingAddForm(forms.ModelForm): class Meta: model = TrainingTasks readonly_fields = ('trainee_signed','trainee_signed_date') But this does not work. Am I missing something or is this not possible? A: As per the documentation, this is a member of admin.ModelAdmin, not forms.ModelForm. Your admin form needs to inherit from admin.ModelAdmin in order for you to have access to the readonly_fields option. Edit: I mis-read the original question, I thought you were trying to use the field within Django's supplied admin app. However, as seen in my initial response, this option is only available for classes that inherit from admin.ModelAdmin — you will not be able to use it via forms.ModelForm. A: For doing it in a form, see In a Django form, how do I make a field readonly (or disabled) so that it cannot be edited?
How to use new Django 1.2 readonly_fields in ModelForm
I'm trying to use the new readonly_fields in a ModelForm. class TrainingAddForm(forms.ModelForm): class Meta: model = TrainingTasks readonly_fields = ('trainee_signed','trainee_signed_date') But this does not work. Am I missing something or is this not possible?
[ "As per the documentation, this is a member of admin.ModelAdmin, not forms.ModelForm. Your admin form needs to inherit from admin.ModelAdmin in order for you to have access to the readonly_fields option.\nEdit:\nI mis-read the original question, I thought you were trying to use the field within Django's supplied ad...
[ 0, 0 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0003597227_django_django_forms_python.txt
Q: sqlalchemy database table is locked I am trying to select all the records from a sqlite db I have with sqlalchemy, loop over each one and do an update on it. I am doing this because I need to reformat ever record in my name column. Here is the code I am using to do a simple test: def loadDb(name): sqlite3.connect(name) engine = create_engine('sqlite:///'+dbPath(), echo=False) metadata = MetaData(bind=engine) return metadata db = database("dealers.db") metadata = db.loadDb() dealers = Table('dealers', metadata, autoload=True) dealer = dealers.select().order_by(asc(dealers.c.id)).execute() for d in dealer: u = dealers.update(dealers.c.id==d.id) u.execute(name="hi") break I'm getting the error: sqlalchemy.exc.OperationalError: (OperationalError) database table is locked u'UPDATE dealers SET name=? WHERE dealers.id = ?' ('hi', 1) I'm very new to sqlalchemy and I'm not sure what this error means or how to fix it. This seems like it should be a really simple task, so I know I am doing something wrong. A: With SQLite, you can't update the database while you are still performing the select. You need to force the select query to finish and store all of the data, then perform your loop. I think this would do the job (untested): dealer = list(dealers.select().order_by(asc(dealers.c.id)).execute()) Another option would be to make a slightly more complicated SQL statement so that the loop executes inside the database instead of in Python. That will certainly give you a big performance boost.
sqlalchemy database table is locked
I am trying to select all the records from a sqlite db I have with sqlalchemy, loop over each one and do an update on it. I am doing this because I need to reformat ever record in my name column. Here is the code I am using to do a simple test: def loadDb(name): sqlite3.connect(name) engine = create_engine('sqlite:///'+dbPath(), echo=False) metadata = MetaData(bind=engine) return metadata db = database("dealers.db") metadata = db.loadDb() dealers = Table('dealers', metadata, autoload=True) dealer = dealers.select().order_by(asc(dealers.c.id)).execute() for d in dealer: u = dealers.update(dealers.c.id==d.id) u.execute(name="hi") break I'm getting the error: sqlalchemy.exc.OperationalError: (OperationalError) database table is locked u'UPDATE dealers SET name=? WHERE dealers.id = ?' ('hi', 1) I'm very new to sqlalchemy and I'm not sure what this error means or how to fix it. This seems like it should be a really simple task, so I know I am doing something wrong.
[ "With SQLite, you can't update the database while you are still performing the select. You need to force the select query to finish and store all of the data, then perform your loop. I think this would do the job (untested):\ndealer = list(dealers.select().order_by(asc(dealers.c.id)).execute())\n\nAnother option ...
[ 4 ]
[]
[]
[ "python", "sqlalchemy", "sqlite" ]
stackoverflow_0003596801_python_sqlalchemy_sqlite.txt
Q: Locating django app resources tl:dr How would a hosted django app correctly transform resource paths to match any hosted location (/ or /test or /testtest)? Full Description Let me try to explain what I am trying to do. I am trying to write a somewhat re-usable django app which I intend to use from within multiple projects. This app is called systemstatus. The systemstatus app provides a page under '$^' which provides a simple interface to query the system status. This page makes an ajax query back to the systemstatus app to determine the actual system status and report it on the UI. The systemstatus app provides a location '^service/$' which points to the ajax call handler. This page has to somehow figure out the correct URI for the ajax handler depending on where this app is hosted (e.g. under / or /status or /blahblah). I am wondering what an ideal way of doing this would be. I would say that this applies to other resources bundled inside the app too (stylesheets, images). Right now I am using request.path to determine what the target path should be. This path is then passed down as a parameter to the template. But this approach will soon become too cumbersome to handle. def system_status (request): queryPath = request.path + "service/" return render_to_response ('systemstatus.html', {'queryPath': queryPath}) My page template looks like this: function do_ajax () { $.getJSON ('{{ queryPath }}', function (data) { $("#status").html (data.status); }); } Thanks! A: You shouldn't hardcode your urls like that, but use reverse instead! Django also has a built-in template tag to reverse urls. So you could do something like function do_ajax () { $.getJSON ('{% url path.to.my_ajax_view %}', function (data) { $("#status").html (data.status); }); } directly in your template! You can also send the ajax request directly to your current page's url and check if it is an ajax request or not: def my_view(request): if request.is_ajax(): # generate response for your ajax script else: # generate the response for normal request # (render template of your page)
Locating django app resources
tl:dr How would a hosted django app correctly transform resource paths to match any hosted location (/ or /test or /testtest)? Full Description Let me try to explain what I am trying to do. I am trying to write a somewhat re-usable django app which I intend to use from within multiple projects. This app is called systemstatus. The systemstatus app provides a page under '$^' which provides a simple interface to query the system status. This page makes an ajax query back to the systemstatus app to determine the actual system status and report it on the UI. The systemstatus app provides a location '^service/$' which points to the ajax call handler. This page has to somehow figure out the correct URI for the ajax handler depending on where this app is hosted (e.g. under / or /status or /blahblah). I am wondering what an ideal way of doing this would be. I would say that this applies to other resources bundled inside the app too (stylesheets, images). Right now I am using request.path to determine what the target path should be. This path is then passed down as a parameter to the template. But this approach will soon become too cumbersome to handle. def system_status (request): queryPath = request.path + "service/" return render_to_response ('systemstatus.html', {'queryPath': queryPath}) My page template looks like this: function do_ajax () { $.getJSON ('{{ queryPath }}', function (data) { $("#status").html (data.status); }); } Thanks!
[ "You shouldn't hardcode your urls like that, but use reverse instead!\nDjango also has a built-in template tag to reverse urls. So you could do something like \nfunction do_ajax () {\n $.getJSON ('{% url path.to.my_ajax_view %}', function (data) {\n $(\"#status\").html (data.status);\n });\n}\n\ndirect...
[ 2 ]
[]
[]
[ "django", "django_urls", "python" ]
stackoverflow_0003597363_django_django_urls_python.txt
Q: create a tar file in a string using python I need to generate a tar file but as a string in memory rather than as an actual file. What I have as input is a single filename and a string containing the assosiated contents. I'm looking for a python lib I can use and avoid having to role my own. A little more work found these functions but using a memory steam object seems a little... inelegant. And making it accept input from strings looks like even more... inelegant. OTOH it works. I assume, as most of it is new to me. Anyone see any bugs in it? A: Use tarfile in conjunction with cStringIO: c = cStringIO.StringIO() t = tarfile.open(mode='w', fileobj=c) # here: do your work on t, then...: s = c.getvalue() # extract the bytestring you need
create a tar file in a string using python
I need to generate a tar file but as a string in memory rather than as an actual file. What I have as input is a single filename and a string containing the assosiated contents. I'm looking for a python lib I can use and avoid having to role my own. A little more work found these functions but using a memory steam object seems a little... inelegant. And making it accept input from strings looks like even more... inelegant. OTOH it works. I assume, as most of it is new to me. Anyone see any bugs in it?
[ "Use tarfile in conjunction with cStringIO:\nc = cStringIO.StringIO()\nt = tarfile.open(mode='w', fileobj=c)\n# here: do your work on t, then...:\ns = c.getvalue() # extract the bytestring you need\n\n" ]
[ 15 ]
[]
[]
[ "python", "tar" ]
stackoverflow_0003597382_python_tar.txt
Q: Is there a way to match a set of groups in any order in a regex? I looked through the related questions, there were quite a few but I don't think any answered this question. I am very new to Regex but I'm trying to get better so bear with me please. I am trying to match several groups in a string, but in any order. Is this something I should be using Regex for? If so, how? If it matters, I plan to use these in IronPython. EDIT: Someone asked me to be more specific, so here: I want to use re.match with a regex like: \[image\s*(?(@alt:(?<alt>.*?);).*(@title:(?<title>.*?);))*.*\](?<arg>.*?)\[\/image\] But it will only match the named groups when they are in the right order, and separated with a space. I would like to be able to match the named groups in any order, as long as they appear where they do now in the regex. A typical string that will be applied to this might look like: [image @alt:alien; @title:reddit alien;]http://www.reddit.com/alien.png[/image] But I should have no problem matching: [image @title:reddit alien; @alt:alien;]http://www.reddit.com/alien.png[/image] So the 'attributes' (things that come between '@' and ';' in the first 'tag') should be matched in any order, as long as they both appear. A: The answer to the question in your title is "no" -- to match N groups "in any order", the regex should have an "or" (the | feature in the regex pattern) among the N! (N factorial) possible permutations of the groups, the product of all integers from 1 to N. That's a number which grows extremely fast -- for N just equal 6, it's already 720, for 7, it's almost 5000, and so on at a dizzying pace -- so this approach is totally impractical for any N which isn't really tiny. The solutions may be many, depending on what you want the groups to be separated with. Let's say, for example, that you don't care (if you DO care, edit your question with better specs). In this case, if overlapping matches are impossible or are OK with you, make N separate regular expressions, one per group -- say these N compiled RE objects are in a list named grps, then mos = [g.search(thestring) for g in grps] is the list of match objects for the groups (None for a group which doesn't match). With the mos list you can do all sorts of checks and/or further manipulations, for example all(mos) is True if and only if all the groups matched, in which case [m.group() for m in mos] is the list of substrings that have been matched, and so on, and so forth. If you need non-overlapping matches, it's a bit more complicated -- you may extract the boundaries of all possible matches for each group, then seeing if there's a way to extract from these N lists a set of N intervals, one per lists, so that no two of them are pairwise intersecting. This is a somewhat subtle algorithm (if you want reasonable speed for a large N, of course), so I think it's worth a separate question, and in any case it's not worth discussing right here when the very issue of whether it's needed or not depends on so incredibly many factors that you have not specified. So, please edit your question with more precise specifications, first, and then things can perhaps be clarified to provide you with the code and/or algorithms you need. Edit: I see the OP has now clarified the issue at least of the extent of providing an example -- although, confusingly, he offers a RE pattern example and a string example that should not match, regardless of ordering (the RE specifies the presence of a substring @title which the example string does not have -- puzzling!). Anyway, if the number of groups in the example (two which appear to be interchangeable, one which appears to have to occur in a specific spot) is representative of the OP's actual problems, then the total number of permutations of interest is just two, so joining the "just two" permutations with a vertical bar | would of course be quite feasible. Is that the case in the OP's real problems, though...? Edit: if the number of permutations of interest is tiny, here's an example of one way to avoid the problem of repeated group names in the pattern (syntax requires Python 2.7 or better, but that's just for the final "dict comprehension" -- the same functionality is available in many previous version of Python, just with the less elegant dict(('a', ... syntax;-)...: >>> r = re.compile(r'(?P<a1>a.*?a).*?(?P<b1>b.*?b)|(?P<b2>b.*?b).*?(?P<a2>a.*?a)') >>> m = r.search('zzzakkkavvvbxxxbnnn') >>> g = m.groupdict() >>> d = {'a':(g.get('a1') or g.get('a2')), 'b':(g.get('b1') or g.get('b2'))} >>> d {'a': 'akkka', 'b': 'bxxxb'} A: This is very similar to one of the key problems with using regular expressions to parse HTML - there is no requirement that attributes always be specified in the same order, and many tags have surprising attributes (like <br clear="all">. So it seems you are working with a very similar markup syntax. Pyparsing addresses this problem in an indirect way - instead of trying to parse all different permutations, parse the general "@attrname:attribute value;" syntax, and keep track of the attributes keys and values in an attribute mapping data structure. The mapping makes it easy to get the "title" attribute, regardless of whether it came first or last in the image tag. This behavior is built into the pyparsing API methods, makeHTMLTags and makeXMLTags. Of course, this markup is not XML, but a similar approach gives some pretty easy to work with results: text = """[image @alt:alien; @title:reddit alien;]http://www.reddit.com/alien1.png[/image] But I should have no problem matching: [image @title:reddit alien; @alt:alien;]http://www.reddit.com/alien2.png[/image] """ from pyparsing import Suppress, Group, Word, alphas, SkipTo, Dict, ZeroOrMore LBRACK,RBRACK,COLON,SEMI,AT = map(Suppress,"[]:;@") tagAttribute = Group(AT + Word(alphas) + COLON + SkipTo(SEMI) + SEMI) imageTag = LBRACK + "image" + Dict(ZeroOrMore(tagAttribute)) + RBRACK imageLink = imageTag + SkipTo("[/image]")("text") for taginfo in imageLink.searchString(text): print taginfo.alt print taginfo.title print taginfo.text print Prints: alien reddit alien http://www.reddit.com/alien1.png alien reddit alien http://www.reddit.com/alien2.png
Is there a way to match a set of groups in any order in a regex?
I looked through the related questions, there were quite a few but I don't think any answered this question. I am very new to Regex but I'm trying to get better so bear with me please. I am trying to match several groups in a string, but in any order. Is this something I should be using Regex for? If so, how? If it matters, I plan to use these in IronPython. EDIT: Someone asked me to be more specific, so here: I want to use re.match with a regex like: \[image\s*(?(@alt:(?<alt>.*?);).*(@title:(?<title>.*?);))*.*\](?<arg>.*?)\[\/image\] But it will only match the named groups when they are in the right order, and separated with a space. I would like to be able to match the named groups in any order, as long as they appear where they do now in the regex. A typical string that will be applied to this might look like: [image @alt:alien; @title:reddit alien;]http://www.reddit.com/alien.png[/image] But I should have no problem matching: [image @title:reddit alien; @alt:alien;]http://www.reddit.com/alien.png[/image] So the 'attributes' (things that come between '@' and ';' in the first 'tag') should be matched in any order, as long as they both appear.
[ "The answer to the question in your title is \"no\" -- to match N groups \"in any order\", the regex should have an \"or\" (the | feature in the regex pattern) among the N! (N factorial) possible permutations of the groups, the product of all integers from 1 to N. That's a number which grows extremely fast -- for ...
[ 2, 0 ]
[]
[]
[ "c#", "python", "regex" ]
stackoverflow_0003597320_c#_python_regex.txt
Q: django-admin.py launches IDE I just went to create a new django project and I typed django-admin.py startproject my_project into the command prompt and it opened the django-admin.py file in my ide (komodo edit). This happens every time I run this command in any form, even if I just try django-admin.py. Any ideas what's going on and how I fix it? I'm on Win Xp with django 1.2.1 A: It sounds like you associated .py files with Komodo Edit instead of with python.exe. The simplest workaround is to type "python django-admin.py ..." to execute the admin. You can look in your Explorer options to change the association. There's a right-click menu option I think called "Open With..." that will let you change it.
django-admin.py launches IDE
I just went to create a new django project and I typed django-admin.py startproject my_project into the command prompt and it opened the django-admin.py file in my ide (komodo edit). This happens every time I run this command in any form, even if I just try django-admin.py. Any ideas what's going on and how I fix it? I'm on Win Xp with django 1.2.1
[ "It sounds like you associated .py files with Komodo Edit instead of with python.exe. The simplest workaround is to type \"python django-admin.py ...\" to execute the admin. \nYou can look in your Explorer options to change the association. There's a right-click menu option I think called \"Open With...\" that ...
[ 3 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0003597665_django_django_admin_python.txt
Q: hex <-> RGB <-> HSV Color space conversion with Python For this project I use Python's colorsys to convert RGB to HSV vice versa to be able to manipulate saturation and lightness, but I noticed that some colors yields bogus results. For example, if I take any primary colors there's no problem: However if I chose a random RGB color and convert it to HSV, I sometime gets bogus results. Sometimes these bogus results occurs when I increase or decrease the lightness or the saturation of a color. In this example lightness 10%, 20% and saturation 100% are bogus: I'm not quite sure why it happens nor how I should fix this .. A: The problem is in your dec2hex code: def dec2hex(d): """return a two character hexadecimal string representation of integer d""" r = "%X" % d return r if len(r) > 1 else r+r When your value is less than 16, you're duplicating it to get the value, in other words, multiplying it by 17. You want this: def dec2hex(d): """return a two character hexadecimal string representation of integer d""" return "%02X" % d
hex <-> RGB <-> HSV Color space conversion with Python
For this project I use Python's colorsys to convert RGB to HSV vice versa to be able to manipulate saturation and lightness, but I noticed that some colors yields bogus results. For example, if I take any primary colors there's no problem: However if I chose a random RGB color and convert it to HSV, I sometime gets bogus results. Sometimes these bogus results occurs when I increase or decrease the lightness or the saturation of a color. In this example lightness 10%, 20% and saturation 100% are bogus: I'm not quite sure why it happens nor how I should fix this ..
[ "The problem is in your dec2hex code:\ndef dec2hex(d):\n \"\"\"return a two character hexadecimal string representation of integer d\"\"\"\n r = \"%X\" % d\n return r if len(r) > 1 else r+r\n\nWhen your value is less than 16, you're duplicating it to get the value, in other words, multiplying it by 17. Yo...
[ 2 ]
[]
[]
[ "color_space", "colors", "python" ]
stackoverflow_0003597610_color_space_colors_python.txt
Q: avoid regex [python] I'd like to know if it's a good idea avoid regex. actually I have avoided it in any case and some peoples has been giving me advice that i shouldn't avoid it, since if you know what means every thing like: [] '|' \A \B \d \D \W \w \S \Z $ * ? ... it would be easy to read, right? but i fell like avoiding regex i would have a more readable code. it gets more unreadable when it's bigger, example: validators.py email_re = re.compile( r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*" # dot-atom r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-011\013\014\016-\177])*"' # quoted-string r')@(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+[A-Z]{2,6}\.?$', re.IGNORECASE) # domain so, I'd like to know a reason to not avoid regex? A: No, don't avoid regular expressions. They're actually quite a nifty little tool and will save you a lot of work if you use them wisely. What you do need to avoid is trying to use it for everything, a malaise that appears to strike those new to regular expressions before they become a little more tempered and a little less enamoured :-) For example, don't use it to validate email addresses. The way you validate an email address is to send an email to it with a link that the receiver has to click on to complete the "transaction". There are billions of valid email addresses (according to the RFCs) that have no physical email receiver behind them. The only way to be certain that there is a receiver is to send an email and wait for proof positive that it was received and acted upon. If I find myself writing a regular expression that's more than, let's say, 60 characters, I step back to see if there's a more readable way. Similarly, if I write a regular expression and come back a week later and can't instantly recognise what it does, I think about replacing it. This particular paragraph consists of my opinions of course, but they've served me well :-) A: Regular expressions are a tool. They are perfectly suited to some tasks and not to others. Like any tool, use them when they are the right tool for the job. Don't just avoid them because somebody said they were bad. Learn how to use them and then you can decide for yourself rather then depending on someone elses dogma. A: If you choose to use a more general parsing approach, like pyparsing or PLY, you will never require regular expressions (which can only match a small subset of the languages matchable with such general parsers). However, lexers such as the one in PLY are typically built around regular expressions (which are a perfect match for a lexer's needs!), so you will probably have to avoid that (as well as powerful tools such as BeautifulSoup when any "normal" user would be able to keep using and enjoying it by simply passing a regular expression object as the selector, since BeautifulSoup fully supports that) and will have to recode a lot of such existing parsers with your chosen general-purpose parsing package. Performance may suffer greatly, of course, by using extremely general tools in cases where simpler, highly optimized and concise ones would be a perfect solution -- and the size of your code may "blow up" to being very large in many common cases. But if you don't mind having programs twice as big and twice as slow, and are determined to avoid regular expressions at all costs, you can do that. On the other hand, if your main concern is with readability (quite an understandable and commendable concern, too), then the re.VERBOSE option, by allowing abundant use of whitespace and comments within the RE's pattern, can really do wonders for that goal without removing any of REs' advantages (except by diluting a sometimes-excessive conciseness;-). You WILL want to also keep at least one general-purpose parsing system under your belt, of course (rather than stretch REs to do tasks they're wrong for, as so many people unfortunately do!) -- but a minimal command of REs will serve you well in so many cases (including, for example, full use of BeautifulSoup and many other tools which can accept REs as parameters to apply them appropriately) that I think it's quite to be recommended. A: Just for some comparisions, here my version email format check not with regexp (with test cases) and one readable regexp offered to me as alternative (though sending email after it is accepted, is great idea): # -*- coding: utf8 -*- import string print("Valid letters in this computer are: "+string.letters) import re def validateEmail(a): sep=[x for x in a if not (x.isalpha() or x.isdigit() or x in r"!#$%&'*+-/=?^_`{|}~]") ] sepjoined=''.join(sep) ## sep joined must be ..@.... form if len(a)>255 or sepjoined.strip('.') != '@': return False end=a for i in sep: part,i,end=end.partition(i) if len(part)<2: return False return len(end)>1 def emailval(address): pattern = "[\.\w]{2,}[@]\w+[.]\w+" return re.match(pattern, address) if __name__ == '__main__': emails = [ "test.@web.com","test+john@web.museum", "test+john@web.m", "a@n.dk", "and.bun@webben.de","marjaliisa.hämäläinen@hel.fi", "marja-liisa.hämäläinen@hel.fi", "marjaliisah@hel.",'tony@localhost', '1234@23.45','me@somewhere'] print('\n\t'.join(["Valid emails are:"] + filter(validateEmail,emails))) print('\n\t'.join(["Regexp gives wrong answer:"] + filter(emailval,emails))) """ Output: Valid letters in this computer are: abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ Valid emails are: test+john@web.museum and.bun@webben.de tony@localhost 1234@23.45 me@somewhere Regexp gives wrong answer: test.@web.com and.bun@webben.de 1234@23.45 """ EDIT: cleaned up the regex filter function from this ancient code, edited for @detly link based more permissive version. Good enough for form filling first check for me before sending the confirmation email. Finaly put the 255 character length limit check mentioned in comments. This code by purpose does not accept the normal a@b as valid email address, but does accept me@somewhere. Another thing is that it depends of what isalpha returns. So this output, which is from Ideone.com has not accepted the scandinavian öä even they are valid nowadays. When run in my home computer, those are accepted. This is even when coding line is there. A: (Deleted a regular expression which purported to be an "official" one but is in fact not found in the RFC it claimed to be from.) This regex may be amusing as it is an attempt to precisely match the e-mail address grammar provided in an older version of the Internet mail standards.
avoid regex [python]
I'd like to know if it's a good idea avoid regex. actually I have avoided it in any case and some peoples has been giving me advice that i shouldn't avoid it, since if you know what means every thing like: [] '|' \A \B \d \D \W \w \S \Z $ * ? ... it would be easy to read, right? but i fell like avoiding regex i would have a more readable code. it gets more unreadable when it's bigger, example: validators.py email_re = re.compile( r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*" # dot-atom r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-011\013\014\016-\177])*"' # quoted-string r')@(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+[A-Z]{2,6}\.?$', re.IGNORECASE) # domain so, I'd like to know a reason to not avoid regex?
[ "No, don't avoid regular expressions. They're actually quite a nifty little tool and will save you a lot of work if you use them wisely.\nWhat you do need to avoid is trying to use it for everything, a malaise that appears to strike those new to regular expressions before they become a little more tempered and a li...
[ 19, 6, 3, 1, 0 ]
[ "Regular expressions are likely the right tool for extracting/validating email addresses...\nTo extract one or more email addresses from raw text:\nimport re\npat_e = re.compile(r'(?P<email>[\\w.+-]+@(?:[\\w-]+\\.)+[a-zA-Z]{2,})')\nemails = []\nfor r in pat_e.finditer(text):\n emails.append(r.group('email'))\nretu...
[ -2 ]
[ "python", "regex" ]
stackoverflow_0003597399_python_regex.txt
Q: How does Django's ORM manage to fetch Foreign objects when they are accessed Been trying to figure this out for a couple of hours now and have gotten nowhere. class other(models.Model): user = models.ForeignKey(User) others = other.objects.all() o = others[0] At this point the ORM has not asked for the o.user object, but if I do ANYTHING that touches that object, it loads it from the database. type(o.user) will cause a load from the database. What I want to understand is HOW they do this magic. What is the pythonic pixie dust that causes it to happen. Yes, I have looked at the source, I'm stumped. A: Django uses a metaclass (django.db.models.base.ModelBase) to customize the creation of model classes. For each object defined as a class attribute on the model (user is the one we care about here), Django first looks to see if it defines a contribute_to_class method. If the method is defined, Django calls it, allowing the object to customize the model class as it's being created. If the object doesn't define contribute_to_class, it is simply assigned to the class using setattr. Since ForeignKey is a Django model field, it defines contribute_to_class. When the ModelBase metaclass calls ForeignKey.contribute_to_class, the value assigned to ModelClass.user is an instance of django.db.models.fields.related.ReverseSingleRelatedObjectDescriptor. ReverseSingleRelatedObjectDescriptor is an object that implements Python's descriptor protocol in order to customize what happens when an instance of the class is accessed as an attribute of another class. In this case, the descriptor is used to lazily load and return the related model instance from the database the first time it is accessed. # make a user and an instance of our model >>> user = User(username="example") >>> my_instance = MyModel(user=user) # user is a ReverseSingleRelatedObjectDescriptor >>> MyModel.user <django.db.models.fields.related.ReverseSingleRelatedObjectDescriptor object> # user hasn't been loaded, yet >>> my_instance._user_cache AttributeError: 'MyModel' object has no attribute '_user_cache' # ReverseSingleRelatedObjectDescriptor.__get__ loads the user >>> my_instance.user <User: example> # now the user is cached and won't be looked up again >>> my_instance._user_cache <User: example> The ReverseSingleRelatedObjectDescriptor.__get__ method is called every time the user attribute is accessed on the model instance, but it's smart enough to only look up the related object once and then return a cached version on subsequent calls. A: This will not explain how exactly Django goes about it, but what you are seeing is Lazy Loading in action. Lazy Loading is a well known design pattern to defer the initialization of objects right up until the point they are needed. In your case until either of o = others[0] or type(o.user) is executed. This Wikipedia article may give you some insights into the process. A: Properties can be used to implement this behaviour. Basically, your class definition will generate a class similar to the following: class other(models.Model): def _get_user(self): ## o.users being accessed return User.objects.get(other_id=self.id) def _set_user(self, v): ## ... user = property(_get_user, _set_user) The query on User will not be performed until you access the .user of an 'other' instance.
How does Django's ORM manage to fetch Foreign objects when they are accessed
Been trying to figure this out for a couple of hours now and have gotten nowhere. class other(models.Model): user = models.ForeignKey(User) others = other.objects.all() o = others[0] At this point the ORM has not asked for the o.user object, but if I do ANYTHING that touches that object, it loads it from the database. type(o.user) will cause a load from the database. What I want to understand is HOW they do this magic. What is the pythonic pixie dust that causes it to happen. Yes, I have looked at the source, I'm stumped.
[ "Django uses a metaclass (django.db.models.base.ModelBase) to customize the creation of model classes. For each object defined as a class attribute on the model (user is the one we care about here), Django first looks to see if it defines a contribute_to_class method. If the method is defined, Django calls it, al...
[ 52, 1, 0 ]
[]
[]
[ "django", "orm", "python" ]
stackoverflow_0003597762_django_orm_python.txt
Q: Handling Password Authentication over a Network I'm writing a game which requires users to log in to their accounts in order to be able to play. What's the best way of transmitting passwords from client to server and storing them? I'm using Python and Twisted, if that's of any relevance. A: The best way is to authenticate via SSL/TLS. The best way of storing passwords is to store them hashed with some complex hash like sha1(sha1(password)+salt) with salt. A: If you want plug'n'play solution, use py-bcrypt for storing passwords (http://www.mindrot.org/projects/py-bcrypt/) and SSL/TLS to protect them in transit.
Handling Password Authentication over a Network
I'm writing a game which requires users to log in to their accounts in order to be able to play. What's the best way of transmitting passwords from client to server and storing them? I'm using Python and Twisted, if that's of any relevance.
[ "The best way is to authenticate via SSL/TLS. The best way of storing passwords is to store them hashed with some complex hash like sha1(sha1(password)+salt) with salt.\n", "If you want plug'n'play solution, use py-bcrypt for storing passwords (http://www.mindrot.org/projects/py-bcrypt/) and SSL/TLS to protect th...
[ 1, 0 ]
[]
[]
[ "network_programming", "passwords", "python", "security" ]
stackoverflow_0003595835_network_programming_passwords_python_security.txt
Q: loop in python ! can anyone help me with loop i want loop that code login_form_data = urllib.urlencode(login_form_seq) opener = urllib2.build_opener() site = opener.open(B, login_form_data).read() the code allow me to login to site but site have problem and the problem is: you can't login from first time that mean I have to press submit then when page reload press submit again... so i think loop will do that but How!? A: You need to handle cookies. Look at the cookielib module. A: If it is a cookie handling problem, use the "HTTPCookieProcessor" in urllib2. By applying it to your opener. cookieHandler = urllib2.HTTPCookieProcessor() # Needed for cookie handling # Apply the handler to an opener opener = urllib2.build_opener(cookieHandler) A: It seems that you are not accepting and saving the cookie(s) required by the page you are trying to access. This is not surprising given that urllib2 does not automatically do this for you. As others have said you'll have to explicitly write code to accept cookies. Something like this: import urllib2, cookielib cj = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) urllib2.install_opener(opener) login_form_data = urllib.urlencode(login_form_seq) site = opener.open(B, login_form_data).read() This would be a good time to read up about cookielib and HTTP state management in Python.
loop in python !
can anyone help me with loop i want loop that code login_form_data = urllib.urlencode(login_form_seq) opener = urllib2.build_opener() site = opener.open(B, login_form_data).read() the code allow me to login to site but site have problem and the problem is: you can't login from first time that mean I have to press submit then when page reload press submit again... so i think loop will do that but How!?
[ "You need to handle cookies. Look at the cookielib module.\n", "If it is a cookie handling problem, use the \"HTTPCookieProcessor\" in urllib2.\nBy applying it to your opener.\ncookieHandler = urllib2.HTTPCookieProcessor() # Needed for cookie handling\n\n# Apply the handler to an opener\nopener = urllib2.build_op...
[ 2, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003597644_python.txt
Q: Is it possible to compare the values of a csv and text file in python? i have a csv file and a text file. is it possible to compare the values in both files? or should i have the values of both in a csv file to make it easier? A: is it possible to compare the values in both files? Yes. You can open them both in binary mode an compare the bytes, or in text mode and compare the characters. Neither will be particularly useful, though. or should i have the values of both in a csv file to make it easier? Convert them both to list-of-lists format. For the CSV file, use a csv.reader. For the text file, use [line.split('\t') for line in open('filename.txt')] or whatever the equivalent is for your file format. A: Yes, you can compare values from any N sources. You have to extract the values from each and then compare them. If you make your question more specific (the format of the text file for instance), we might be able to help you more. A: csv itself is of course text as well. And that's basically the problem when "comparing", there's no "text file standard". Even csv isn't that strictly defined, and there's no normal form. For exmaple, should a header be included? Is column ordering relevant? How are fields separated in the textfile? Fixed width records? Newlines? Special markers (like csv)? , If you know the format of the textfile, you can read/parse it and compare the result with the csv file (which you will also need to read/parse of course), or generate csv from the textfile and compare that using diff.
Is it possible to compare the values of a csv and text file in python?
i have a csv file and a text file. is it possible to compare the values in both files? or should i have the values of both in a csv file to make it easier?
[ "\nis it possible to compare the values\n in both files?\n\nYes. You can open them both in binary mode an compare the bytes, or in text mode and compare the characters. Neither will be particularly useful, though.\n\nor should i have the values of both in\n a csv file to make it easier?\n\nConvert them both to ...
[ 3, 2, 2 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0003598205_csv_python.txt
Q: Python's list comprehensions and other better practices This relates to a project to convert a 2-way ANOVA program in SAS to Python. I pretty much started trying to learn the language Thursday, so I know I have a lot of room for improvement. If I'm missing something blatantly obvious, by all means, let me know. I haven't got Sage up and running yet, nor numpy, so right now, this is all quite vanilla Python 2.6.1. (portable) Primary query: Need a good set of list comprehensions that can extract the data in lists of samples in lists by factor A, by factor B, overall, and in groups of each level of factors A&B (AxB). After some work, the data is in the following form (3 layers of nested lists): response[a][b][n] (meaning [a1 [b1 [n1, ... ,nN] ...[bB [n1, ...nN]]], ... ,[aA [b1 [n1, ... ,nN] ...[bB [n1, ...nN]]] Hopefully that's clear.) Factor levels in my example case: A=3 (0-2), B=8 (0-7), N=8 (0-7) byA= [[a[i] for i in range(b)] for a[b] in response] (Can someone explain why this syntax works? I stumbled into it trying to see what the parser would accept. I haven't seen that syntax attached to that behavior elsewhere, but it's really nice. Any good links on sites or books on the topic would be appreciated. Edit: Persistence of variables between runs explained this oddity. It doesn't work.) byB=lstcrunch([[Bs[i] for i in range(len(Bs)) ]for Bs in response]) (It bears noting that zip(*response) almost does what I want. The above version isn't actually working, as I recall. I haven't run it through a careful test yet.) byAxB= [item for sublist in response for item in sublist] (Stolen from a response by Alex Martelli on this site. Again could someone explain why? List comprehension syntax is not very well explained in the texts I've been reading.) ByO= [item for sublist in byAxB for item in sublist] (Obviously, I simply reused the former comprehension here, 'cause it did what I need. Edit:) I'd like these to end up the same datatypes, at least when looped through by the factor in question, s.t. that same average/sum/SS/et cetera functions can be applied and used. This could easily be replaced by something cleaner: def lstcrunch(Dlist): """Returns a list containing the entire contents of whatever is imported, reduced by one level. If a rectangular array, it reduces a dimension by one. lstcrunch(DataSet[a][b]) -> DataOutput[a] [[1, 2], [[2, 3], [2, 4]]] -> [1, 2, [2, 3], [2, 4]] """ flat=[] if islist(Dlist):#1D top level list for i in Dlist: if islist(i): flat+= i else: flat.append(i) return flat else: return [Dlist] Oh, while I'm on the topic, what's the preferred way of identifying a variable as a list? I have been using: def islist(a): "Returns 'True' if input is a list and 'False' otherwise" return type(a)==type([]) Parting query: Is there a way to explicitly force a shallow copy to convert to a deep? copy? Or, similarly, when copying into a variable, is there a way of declaring that the assignment is supposed to replace the pointer, too, and not merely the value? (s.t.the assignment won't propagate to other shallow copies) Similarly, using that might be useful, as well, from time to time, so being able to control when it does or doesn't occur sounds really nice. (I really stepped all over myself when I prepared my table for inserting by calling: response=[[[0]*N]*B]*A ) Edit: Further investigation lead to most of this working fine. I've since made the class and tested it. it works fine. I'll leave the list comprehension forms intact for reference. def byB(array_a_b_c): y=range(len(array_a_b_c)) x=range(len(array_a_b_c[0])) return [[array_a_b_c[i][j][k] for k in range(len(array_a_b_c[0][0])) for i in y] for j in x] def byA(array_a_b_c): return [[repn for rowB in rowA for repn in rowB] for rowA in array_a_b_c] def byAxB(array_a_b_c): return [rowB for rowA in array_a_b_c for rowB in rowA] def byO(array_a_b_c): return [rep for rowA in array_a_b_c for rowB in rowA for rep in rowB] def gen3d(row, col, inner): """Produces a 3d nested array without any naughty shallow copies. [row[col[inner]] named s.t. the outer can be split on, per lprn for easy display""" return [[[k for k in range(inner)] for i in range(col)] for j in range(row)] def lprn(X): """This prints a list by lines. Not fancy, but works""" if isiterable(X): for line in X: print line else: print x def isiterable(a): return hasattr(a, "__iter__") Thanks to everyone who responded. Already see a noticeable improvement in code quality due to improvements in my gnosis. Further thoughts are still appreciated, of course. A: byAxB= [item for sublist in response for item in sublist] Again could someone explain why? I am sure A.M. will be able to give you a good explanation. Here is my stab at it while waiting for him to turn up. I would approach this from left to right. Take these four words: for sublist in response I hope you can see the resemblance to a regular for loop. These four words are doing the ground work for performing some action on each sublist in response. It appears that response is a list of lists. In that case sublist would be a list for each iteration through response. for item in sublist This is again another for loop in the making. Given that we first heard about sublist in the previous "loop" this would indicate that we are now traversing through sublist, one item at a time. If I were to write these loops out without comprehensions it would look like this: for sublist in response: for item in sublist: Next, we look at the remaining words. [, item and ]. This effectively means, collect items in a list and return the resulting list. Whenever you have trouble creating or understanding list iterations write the relevant for loops out and then compress them: result = [] for sublist in response: for item in sublist: result.append(item) This will compress to: [ item for sublist in response for item in sublist ] List comprehension syntax is not very well explained in the texts I've been reading Dive Into Python has a section dedicated to list comprehensions. There is also this nice tutorial to read through. Update I forgot to say something. List comprehensions are another way of achieving what has been traditionally done using map and filter. It would be a good idea to understand how map and filter work if you want to improve your comprehension-fu. A: For the copy part, look into the copy module, python simply uses references after the first object is created, so any change in other "copies" propagates back to the original, but the copy module makes real copies of objects and you can specify several copy modes A: It is sometimes kinky to produce right level of recursion in your data structure, however I think in your case it should be relatively simple. To test it out while we are doing we need one sample data, say: data = [ [a, [b, range(1,9)]] for b in range(8) for a in range(3)] print 'Origin' print(data) print 'Flat' ## from this we see how to produce the c data flat print([(a,b,c) for a,[b,c] in data]) print "Sum of data in third level = %f" % sum(point for point in c for a,[b,c] in data) print "Sum of all data = %f" % sum(a+b+sum(c) for a,[b,c] in data) for the type check, generally you should avoid it but if you must, as when you do not want to do recursion in string you can do it like this if not isinstance(data, basestring) : .... If you need to flatten structure you can find useful code in Python documentation (other way to express it is chain(*listOfLists)) and as list comprehension [ d for sublist in listOfLists for d in sublist ]: from itertools import flat.chain def flatten(listOfLists): "Flatten one level of nesting" return chain.from_iterable(listOfLists) This does not work though if you have data in different depths. For heavy weight flattener see: http://www.python.org/workshops/1994-11/flatten.py,
Python's list comprehensions and other better practices
This relates to a project to convert a 2-way ANOVA program in SAS to Python. I pretty much started trying to learn the language Thursday, so I know I have a lot of room for improvement. If I'm missing something blatantly obvious, by all means, let me know. I haven't got Sage up and running yet, nor numpy, so right now, this is all quite vanilla Python 2.6.1. (portable) Primary query: Need a good set of list comprehensions that can extract the data in lists of samples in lists by factor A, by factor B, overall, and in groups of each level of factors A&B (AxB). After some work, the data is in the following form (3 layers of nested lists): response[a][b][n] (meaning [a1 [b1 [n1, ... ,nN] ...[bB [n1, ...nN]]], ... ,[aA [b1 [n1, ... ,nN] ...[bB [n1, ...nN]]] Hopefully that's clear.) Factor levels in my example case: A=3 (0-2), B=8 (0-7), N=8 (0-7) byA= [[a[i] for i in range(b)] for a[b] in response] (Can someone explain why this syntax works? I stumbled into it trying to see what the parser would accept. I haven't seen that syntax attached to that behavior elsewhere, but it's really nice. Any good links on sites or books on the topic would be appreciated. Edit: Persistence of variables between runs explained this oddity. It doesn't work.) byB=lstcrunch([[Bs[i] for i in range(len(Bs)) ]for Bs in response]) (It bears noting that zip(*response) almost does what I want. The above version isn't actually working, as I recall. I haven't run it through a careful test yet.) byAxB= [item for sublist in response for item in sublist] (Stolen from a response by Alex Martelli on this site. Again could someone explain why? List comprehension syntax is not very well explained in the texts I've been reading.) ByO= [item for sublist in byAxB for item in sublist] (Obviously, I simply reused the former comprehension here, 'cause it did what I need. Edit:) I'd like these to end up the same datatypes, at least when looped through by the factor in question, s.t. that same average/sum/SS/et cetera functions can be applied and used. This could easily be replaced by something cleaner: def lstcrunch(Dlist): """Returns a list containing the entire contents of whatever is imported, reduced by one level. If a rectangular array, it reduces a dimension by one. lstcrunch(DataSet[a][b]) -> DataOutput[a] [[1, 2], [[2, 3], [2, 4]]] -> [1, 2, [2, 3], [2, 4]] """ flat=[] if islist(Dlist):#1D top level list for i in Dlist: if islist(i): flat+= i else: flat.append(i) return flat else: return [Dlist] Oh, while I'm on the topic, what's the preferred way of identifying a variable as a list? I have been using: def islist(a): "Returns 'True' if input is a list and 'False' otherwise" return type(a)==type([]) Parting query: Is there a way to explicitly force a shallow copy to convert to a deep? copy? Or, similarly, when copying into a variable, is there a way of declaring that the assignment is supposed to replace the pointer, too, and not merely the value? (s.t.the assignment won't propagate to other shallow copies) Similarly, using that might be useful, as well, from time to time, so being able to control when it does or doesn't occur sounds really nice. (I really stepped all over myself when I prepared my table for inserting by calling: response=[[[0]*N]*B]*A ) Edit: Further investigation lead to most of this working fine. I've since made the class and tested it. it works fine. I'll leave the list comprehension forms intact for reference. def byB(array_a_b_c): y=range(len(array_a_b_c)) x=range(len(array_a_b_c[0])) return [[array_a_b_c[i][j][k] for k in range(len(array_a_b_c[0][0])) for i in y] for j in x] def byA(array_a_b_c): return [[repn for rowB in rowA for repn in rowB] for rowA in array_a_b_c] def byAxB(array_a_b_c): return [rowB for rowA in array_a_b_c for rowB in rowA] def byO(array_a_b_c): return [rep for rowA in array_a_b_c for rowB in rowA for rep in rowB] def gen3d(row, col, inner): """Produces a 3d nested array without any naughty shallow copies. [row[col[inner]] named s.t. the outer can be split on, per lprn for easy display""" return [[[k for k in range(inner)] for i in range(col)] for j in range(row)] def lprn(X): """This prints a list by lines. Not fancy, but works""" if isiterable(X): for line in X: print line else: print x def isiterable(a): return hasattr(a, "__iter__") Thanks to everyone who responded. Already see a noticeable improvement in code quality due to improvements in my gnosis. Further thoughts are still appreciated, of course.
[ "\nbyAxB= [item for sublist in response for item in sublist] Again could someone explain why?\n\nI am sure A.M. will be able to give you a good explanation. Here is my stab at it while waiting for him to turn up.\nI would approach this from left to right. Take these four words:\nfor sublist in response\n\nI hope yo...
[ 6, 1, 1 ]
[]
[]
[ "arrays", "list", "python", "python_2.6", "statistics" ]
stackoverflow_0003597955_arrays_list_python_python_2.6_statistics.txt
Q: Python Tool Windows TL.attributes('-toolwindow', True) I'm making a GUI in Tkinter that uses a tool window, is there anyway to make this window show up in the task bar? A: On most systems, you can temporarily remove the window from the screen by iconifying it. In Tk, whether or not a window is iconified is referred to as the window's state. The possible states for a window include "normal" and "iconic" (for an iconified window). There are some others too. thestate = window.state() window.state('normal') window.iconify() window.deiconify() Docs at : http://effbot.org/tkinterbook/wm.htm should be of some help.
Python Tool Windows
TL.attributes('-toolwindow', True) I'm making a GUI in Tkinter that uses a tool window, is there anyway to make this window show up in the task bar?
[ "On most systems, you can temporarily remove the window from the screen by iconifying it. In Tk, whether or not a window is iconified is referred to as the window's state. The possible states for a window include \"normal\" and \"iconic\" (for an iconified window). There are some others too.\nthestate = window.stat...
[ 2 ]
[]
[]
[ "python", "taskbar", "tkinter", "windows" ]
stackoverflow_0003598291_python_taskbar_tkinter_windows.txt
Q: Is there a way to iterate a specified number of times without introducing an unnecessary variable? If I want to iterate n times in Java, I write: for (i = 0; i < n; i++) { // do stuff } In Python, it seems the standard way to do this is: for x in range(n): # do stuff As always, Python is more concise and more readable. But the x bothers me, as it is unnecessary, and PyDev generates a warning, since x is never used. Is there a way to do this that doesn't generate any warnings, and doesn't introduce unnecessary variables? A: Idiomatic Python (and many other languages) would have you use _ as the temporary variable, which generally indicates to readers that the variable is intentionally unused. Aside from that convention, the in loop-construct in Python always requires you to iterate over something and assign that value to a variable. (The comments in the accepted answer of this question suggest that PyDev won't create a warning for _). for _ in range(n): # do stuff A: In Python, you don't create an additional variable in the sort of situation you described. for i in range(10): Creates a range object, over which the loop iterates. The range object holds it's current value at any given time. i is merely a name that's created and bound to this value. The variable exists whether it has a name or not, since the range object must know it's current value. If you think about a loop in terms of cpu instructions, you see why there must be a variable: push x loop: do something increment x jump if x > y goto loop There is a facility in some JIT compiled languages that sometimes detects a loop being just a small amount of repetitions of the same code and optimises the code to be a series of the same instructions. But, as far as I know, python does no such thing. Here's a for-loop in bytecode: 4 0 SETUP_LOOP 20 (to 23) 3 LOAD_GLOBAL 0 (range) 6 LOAD_FAST 0 (x) 9 CALL_FUNCTION 1 12 GET_ITER >> 13 FOR_ITER 6 (to 22) 16 STORE_FAST 1 (i) 5 19 JUMP_ABSOLUTE 13 >> 22 POP_BLOCK Notice that there's no comparison. The loop is quit by the iteration object raising StopIteration, the interpreter then looks up the loop setup and jumps to the end of the loop (23 in this case). Of course you could avoid all of this by just repeating your code x number of times. As soon as this number may vary, there needs to be some sort of facility to provide next() and StopIteration for the for loop to work.Remember, python's for-loop is if anything comparable to a for-each loop in Java. There really isn't a traditional for-loop available at all. Just as an aside: I always use i, j and k for iterating variables. Using the underscore somehow seems inelegant to me.
Is there a way to iterate a specified number of times without introducing an unnecessary variable?
If I want to iterate n times in Java, I write: for (i = 0; i < n; i++) { // do stuff } In Python, it seems the standard way to do this is: for x in range(n): # do stuff As always, Python is more concise and more readable. But the x bothers me, as it is unnecessary, and PyDev generates a warning, since x is never used. Is there a way to do this that doesn't generate any warnings, and doesn't introduce unnecessary variables?
[ "Idiomatic Python (and many other languages) would have you use _ as the temporary variable, which generally indicates to readers that the variable is intentionally unused.\nAside from that convention, the in loop-construct in Python always requires you to iterate over something and assign that value to a variable....
[ 6, 2 ]
[]
[]
[ "coding_style", "iteration", "python" ]
stackoverflow_0003524048_coding_style_iteration_python.txt
Q: Qt: best way to add a context menu to the central widget? I do not understand why in the book Rapid GUI Programming with Python and Qt, a context menu is added to a central widget by calling addActions() on the main window (self), like so (p. 180): self.addActions(self.imageLabel, (editInvertAction, …)) where self is a QMainWindow, and imageLabel is a QLabel set as the central widget with # Added actions will be put in a context menu: self.imageLabel.setContextMenuPolicy(Qt.ActionsContextMenu) self.setCentralWidget(self.imageLabel) Now, why would the main window be associated in some way (through self.addActions()) to the context menu of the central widget? Isn't it enough to call addActions() directly on the central widget? In fact, the following does create a context menu: self.imageLabel.addActions((editInvertAction, …)) Why doesn't the book example the context menu this way? isn't this equivalent to the more involved self.addActions(…) form? PS: I even see that the documentation for QMainWindow.addActions() does not even mention any first argument (self.imageLabel, above)! I'm completely lost as to why the book uses the first snippet above instead of the last one… Help! :) A: Using self.addAction() on QMainWindow allow all QMainWindow childs (Docks, StatusBar, ToolBar, MenuBar, ...) to use theses actions, not only the central widget. But the best way to get a fine-grained context menu control is to use the customContextMenuRequested signal (http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qwidget.html#customContextMenuRequested).
Qt: best way to add a context menu to the central widget?
I do not understand why in the book Rapid GUI Programming with Python and Qt, a context menu is added to a central widget by calling addActions() on the main window (self), like so (p. 180): self.addActions(self.imageLabel, (editInvertAction, …)) where self is a QMainWindow, and imageLabel is a QLabel set as the central widget with # Added actions will be put in a context menu: self.imageLabel.setContextMenuPolicy(Qt.ActionsContextMenu) self.setCentralWidget(self.imageLabel) Now, why would the main window be associated in some way (through self.addActions()) to the context menu of the central widget? Isn't it enough to call addActions() directly on the central widget? In fact, the following does create a context menu: self.imageLabel.addActions((editInvertAction, …)) Why doesn't the book example the context menu this way? isn't this equivalent to the more involved self.addActions(…) form? PS: I even see that the documentation for QMainWindow.addActions() does not even mention any first argument (self.imageLabel, above)! I'm completely lost as to why the book uses the first snippet above instead of the last one… Help! :)
[ "Using self.addAction() on QMainWindow allow all QMainWindow childs (Docks, StatusBar, ToolBar, MenuBar, ...) to use theses actions, not only the central widget.\nBut the best way to get a fine-grained context menu control is to use the customContextMenuRequested signal (http://www.riverbankcomputing.co.uk/static/D...
[ 1 ]
[]
[]
[ "pyqt", "python", "qmainwindow", "qt", "qwidget" ]
stackoverflow_0003582554_pyqt_python_qmainwindow_qt_qwidget.txt
Q: non-technical benefits of having string-type immutable I am wondering about the benefits of having the string-type immutable from the programmers point-of-view. Technical benefits (on the compiler/language side) can be summarized mostly that it is easier to do optimisations if the type is immutable. Read here for a related question. Also, in a mutable string type, either you have thread-safety already built-in (then again, optimisations are harder to do) or you have to do it yourself. You will have in any case the choice to use a mutable string type with built-in thread safety, so that is not really an advantage of immutable string-types. (Again, it will be easier to do the handling and optimisations to ensure thread-safety on the immutable type but that is not the point here.) But what are the benefits of immutable string-types in the usage? What is the point of having some types immutable and others not? That seems very inconsistent to me. In C++, if I want to have some string to be immutable, I am passing it as const reference to a function (const std::string&). If I want to have a changeable copy of the original string, I am passing it as std::string. Only if I want to have it mutable, I am passing it as reference (std::string&). So I just have the choice about what I want to do. I can just do this with every possible type. In Python or in Java, some types are immutable (mostly all primitive types and strings), others are not. In pure functional languages like Haskell, everything is immutable. Is there a good reason why it make sense to have this inconsistency? Or is it just purely for technical lower level reasons? A: What is the point of having some types immutable and others not? Without some mutable types, you'd have to go the whole hog to pure functional programming -- a completely different paradigm than the OOP and procedural approaches which are currently most popular, and, while extremely powerful, apparently very challenging to a lot of programmers (what happens when you do need side effects in a language where nothing is mutable, and in real-world programming of course you inevitably do, is part of the challenge -- Haskell's Monads are a very elegant approach, for example, but how many programmers do you know that fully and confidently understand them and can use them as well as typical OOP constructs?-). If you don't understand the enormous value of having multiple paradigms available (both FP one and ones crucially relying on mutable data), I recommend studying Haridi's and Van Roy's masterpiece, Concepts, Techniques, and Models of Computer Programming -- "a SICP for the 21st Century", as I once described it;-). Most programmers, whether familiar with Haridi and Van Roy or not, will readily admit that having at least some mutable data types is important to them. Despite the sentence I've quoted above from your Q, which takes a completely different viewpoint, I believe that may also be the root of your perplexity: not "why some of each", but rather "why some immutables at all". The "thoroughly mutable" approach was once (accidentally) obtained in a Fortran implementation. If you had, say, SUBROUTINE ZAP(I) I = 0 RETURN then a program snippet doing, e.g., PRINT 23 ZAP(23) PRINT 23 would print 23, then 0 -- the number 23 had been mutated, so all references to 23 in the rest of the program would in fact refer to 0. Not a bug in the compiler, technically: Fortran had subtle rules about what your program is and is not allowed to do in passing constants vs variables to procedures that assign to their arguments, and this snippet violates those little-known, non-compiler-enforceable rules, so it's a but in the program, not in the compiler. In practice, of course, the number of bugs caused this way was unacceptably high, so typical compilers soon switched to less destructive behavior in such situations (putting constants in read-only segments to get a runtime error, if the OS supported that; or, passing a fresh copy of the constant rather than the constant itself, despite the overhead; and so forth) even though technically they were program bugs allowing the compiler to display undefined behavior quite "correctly";-). The alternative enforced in some other languages is to add the complication of multiple ways of parameter passing -- most notably perhaps in C++, what with by-value, by-reference, by constant reference, by pointer, by constant pointer, ... and then of course you see programmers baffled by declarations such as const foo* const bar (where the rightmost const is basically irrelevant if bar is an argument to some function... but crucial instead if bar is a local variable...!-). Actually Algol-68 probably went farther along this direction (if you can have a value and a reference, why not a reference to a reference? or reference to reference to reference? &c -- Algol 68 put no limitations on this, and the rules to define what was going on are perhaps the subtlest, hardest mix ever found in an "intended for real use" programming language). Early C (which only had by-value and by-explicit-pointer -- no const, no references, no complications) was no doubt in part a reaction to it, as was the original Pascal. But const soon crept in, and complications started mounting again. Java and Python (among other languages) cut through this thicket with a powerful machete of simplicity: all argument passing, and all assignment, is "by object reference" (never reference to a variable or other reference, never semantically implicit copies, &c). Defining (at least) numbers as semantically immutable preserves programmers' sanity (as well as this precious aspect of language simplicity) by avoiding "oopses" such as that exhibited by the Fortran code above. Treating strings as primitives just like numbers is quite consistent with the languages' intended high semantic level, because in real life we do need strings that are just as simple to use as numbers; alternatives such as defining strings as lists of characters (Haskell) or as arrays of characters (C) poses challenges to both the compiler (keeping efficient performance under such semantics) and the programmer (effectively ignoring this arbitrary structuring to enable use of strings as simple primitives, as real life programming often requires). Python went a bit further by adding a simple immutable container (tuple) and tying hashing to "effective immutability" (which avoids certain surprises to the programmer that are found, e.g., in Perl, with its hashes allowing mutable strings as keys) -- and why not? Once you have immutability (a precious concept that saves the programmer from having to learn about N different semantics for assignment and argument passing, with N tending to increase with time;-), you might as well get full mileage out of it;-). A: I am not sure if this qualifies as non-technical, nevertheless: if strings are mutable, then most(*) collections need to make private copies of their string keys. Otherwise a "foo" key changed externally to "bar" would result in "bar" sitting in the internal structures of the collection where "foo" is expected. This way "foo" lookup would find "bar", which is less of a problem (return nothing, reindex the offending key) but "bar" lookup would find nothing, which is a bigger problem. (*) A dumb collection that does a linear scan of all keys on each lookup would not have to do that, since it would naturally accomodate key changes. A: There is no overarching, fundamental reason not to have strings mutable. The best explanation I have found for their immutability is that it promotes a more functional, less side-effectsy way of programming. This ends up being cleaner, more elegant, and more Pythonic. Semantically, they should be immutable, no? The string "hello" should always represent "hello". You can't change it any more than you can change the number three! A: Not sure if you would count this as a 'technical low level' benefit, but the fact that immutable string is implicitly threadsafe saves you a lot of effort of coding for thread safety. Slightly toy example... Thread A - Check user with login name FOO has permission to do something, return true Thread B - Modify user string to login name BAR Thread A - Perform some operation with login name BAR due to previous permission check passing against FOO. The fact that the String can't change saves you the effort of guarding against this. A: If you want full consistency you can only make everything immutable, because mutable Bools or Ints would simply make no sense at all. Some functional languages do that in fact. Python's philosophy is "Simple is better than complex." In C you need to be aware that strings can change and think about how that can affect you. Python assumes that the default use case for strings is "put text together" - there is absolutely nothing you need to know about strings to do that. But if you want your strings to change, you just have to use a more appropriate type (ie lists, StringIO, templates, etc). A: In a language with reference semantics for user-defined types, having mutable strings would be a desaster, because every time you assign a string variable, you would alias a mutable string object, and you would have to do defensive copies all over the place. That's why strings are immutable in Java and C# -- if the string object is immutable, it does not matter how many variables point to it. Note that in C++, two string variables never share state (at least conceptionally -- technically, there might be copy-on-write going on, but that is getting out of fashion due to inefficiencies in multi-threading scenarios). A: If strings are mutable, then many consumers of a string will have to to make copies of it. If strings are immutable, this is far less important (unless immutability is enforced by hardware interlocks, it might not be a bad idea for some security-conscious consumers of a string to make their own copies in case the strings they're given aren't as immutable as they should be). The StringBuilder class is pretty good, though I think it would be nicer if it had a "Value" property (read would be equivalent to ToString, but it would show up in object inspectors; write would allow direct setting of the whole content) and a default widening conversion to a string. It would have been nice in theory to have MutableString type descended from a common ancestor with String, so a mutable string could be passed to a function which didn't care whether a string was mutable, though I suspect that optimizations which rely on the fact that Strings have a certain fixed implementation would have been less effective. A: The main advantage for the programmer is that with mutable strings, you never need to worry about who might alter your string. Therefore, you never have to consciously decide "Should I copy this string here?".
non-technical benefits of having string-type immutable
I am wondering about the benefits of having the string-type immutable from the programmers point-of-view. Technical benefits (on the compiler/language side) can be summarized mostly that it is easier to do optimisations if the type is immutable. Read here for a related question. Also, in a mutable string type, either you have thread-safety already built-in (then again, optimisations are harder to do) or you have to do it yourself. You will have in any case the choice to use a mutable string type with built-in thread safety, so that is not really an advantage of immutable string-types. (Again, it will be easier to do the handling and optimisations to ensure thread-safety on the immutable type but that is not the point here.) But what are the benefits of immutable string-types in the usage? What is the point of having some types immutable and others not? That seems very inconsistent to me. In C++, if I want to have some string to be immutable, I am passing it as const reference to a function (const std::string&). If I want to have a changeable copy of the original string, I am passing it as std::string. Only if I want to have it mutable, I am passing it as reference (std::string&). So I just have the choice about what I want to do. I can just do this with every possible type. In Python or in Java, some types are immutable (mostly all primitive types and strings), others are not. In pure functional languages like Haskell, everything is immutable. Is there a good reason why it make sense to have this inconsistency? Or is it just purely for technical lower level reasons?
[ "\nWhat is the point of having some\n types immutable and others not?\n\nWithout some mutable types, you'd have to go the whole hog to pure functional programming -- a completely different paradigm than the OOP and procedural approaches which are currently most popular, and, while extremely powerful, apparently ve...
[ 16, 2, 1, 1, 1, 1, 1, 1 ]
[]
[]
[ "c++", "immutability", "java", "python", "string" ]
stackoverflow_0003584945_c++_immutability_java_python_string.txt
Q: Any way to stringify a variable id / symbol in Python? I'm wondering if it is possible at all in python to stringify variable id/symbol -- that is, a function that behaves as follows: >>> symbol = 'whatever' >>> symbol_name(symbol) 'symbol' Now, it is easy to do it on a function or a class (if it is a direct reference to the object): >>> def fn(): pass >>> fn.func_name 'fn' But I'm looking for a general method that works on all cases, even for indirect object references. I've thought of somehow using id(var), but no luck yet. Is there any way to do it? A: Here is, I'm sure you can turn it into a better form =) def symbol_name(a): for k,v in globals().items(): if id(a)==id(v): return k Update: As unbeli has noted, if you have: a = [] b = a The function will not be able to show you the right name, since id(a)==id(b). A: I don't think it's possible. Even for functions, that is not the variable name: >>> def fn(): pass ... >>> fn.func_name 'fn' >>> b=fn >>> b.func_name 'fn' >>> del fn >>> b.func_name 'fn' >>> b() >>> fn() Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'fn' is not defined A: "Not possible" is the answer.
Any way to stringify a variable id / symbol in Python?
I'm wondering if it is possible at all in python to stringify variable id/symbol -- that is, a function that behaves as follows: >>> symbol = 'whatever' >>> symbol_name(symbol) 'symbol' Now, it is easy to do it on a function or a class (if it is a direct reference to the object): >>> def fn(): pass >>> fn.func_name 'fn' But I'm looking for a general method that works on all cases, even for indirect object references. I've thought of somehow using id(var), but no luck yet. Is there any way to do it?
[ "Here is, I'm sure you can turn it into a better form =)\ndef symbol_name(a):\n for k,v in globals().items():\n if id(a)==id(v): return k\n\nUpdate: As unbeli has noted, if you have:\na = []\nb = a\n\nThe function will not be able to show you the right name, since id(a)==id(b).\n", "I don't think it's p...
[ 4, 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003000566_python.txt
Q: Fastest implementation to do multiple string substitutions in Python Is there any recommended way to do multiple string substitutions other than doing replace chaining on a string (i.e. text.replace(a, b).replace(c, d).replace(e, f)...)? How would you, for example, implement a fast function that behaves like PHP's htmlspecialchars in Python? I compared (1) multiple replace method, (2) the regular expression method, and (3) Matt Anderson's method. With n=10 runs, the results came up as follows: On 100 characters: TIME: 0 ms [ replace_method(str) ] TIME: 5 ms [ regular_expression_method(str, dict) ] TIME: 1 ms [ matts_multi_replace_method(list, str) ] On 1000 characters: TIME: 0 ms [ replace_method(str) ] TIME: 3 ms [ regular_expression_method(str, dict) ] TIME: 2 ms [ matts_multi_replace_method(list, str) ] On 10000 characters: TIME: 3 ms [ replace_method(str) ] TIME: 7 ms [ regular_expression_method(str, dict) ] TIME: 5 ms [ matts_multi_replace_method(list, str) ] On 100000 characters: TIME: 36 ms [ replace_method(str) ] TIME: 46 ms [ regular_expression_method(str, dict) ] TIME: 39 ms [ matts_multi_replace_method(list, str) ] On 1000000 characters: TIME: 318 ms [ replace_method(str) ] TIME: 360 ms [ regular_expression_method(str, dict) ] TIME: 320 ms [ matts_multi_replace_method(list, str) ] On 3687809 characters: TIME: 1.277524 sec [ replace_method(str) ] TIME: 1.290590 sec [ regular_expression_method(str, dict) ] TIME: 1.116601 sec [ matts_multi_replace_method(list, str) ] So kudos to Matt for beating the multi replace method on a fairly large input string. Anyone got ideas for beating it on a smaller string? A: Something like the following maybe? Split the text into pieces with the first "from" item to be replaced, then recursively split each of those parts into sub-parts with the next "from" item to be replaced, and so on, until you've visited all your replacements. Then join with the "to" replacement item for each as recursive function completes. A little hard to wrap your head around the following code perhaps (it was for me, and I wrote it), but it seems to function as intended. I didn't benchmark it, but I suspect it would be reasonably fast. def multi_replace(pairs, text): stack = list(pairs) stack.reverse() def replace(stack, parts): if not stack: return parts # copy the stack so I don't disturb parallel recursions stack = list(stack) from_, to = stack.pop() #print 'split (%r=>%r)' % (from_, to), parts split_parts = [replace(stack, part.split(from_)) for part in parts] parts = [to.join(split_subparts) for split_subparts in split_parts] #print 'join (%r=>%r)' % (from_, to), parts return parts return replace(stack, [text])[0] print multi_replace( [('foo', 'bar'), ('baaz', 'foo'), ('quux', 'moop')], 'foobarbaazfooquuxquux') for: barbarfoobarmoopmoop A: Normally, .replace method beats all other methods. (See my benchmarks above.) A: How fast? Also, how big are your strings? There's a fairly simple recipe for building a regular expression to do the job on another site. It might need some tweaking to handle regex metacharacters; I didn't look too closely. If that's not good enough, you probably need to write some C code, honestly. You can build a simple state machine to do all the replacements, and then process any string byte by byte with no backtracking along the machine to actually do the work. However, I doubt you will beat the regex engine without going to C and optimizing that.
Fastest implementation to do multiple string substitutions in Python
Is there any recommended way to do multiple string substitutions other than doing replace chaining on a string (i.e. text.replace(a, b).replace(c, d).replace(e, f)...)? How would you, for example, implement a fast function that behaves like PHP's htmlspecialchars in Python? I compared (1) multiple replace method, (2) the regular expression method, and (3) Matt Anderson's method. With n=10 runs, the results came up as follows: On 100 characters: TIME: 0 ms [ replace_method(str) ] TIME: 5 ms [ regular_expression_method(str, dict) ] TIME: 1 ms [ matts_multi_replace_method(list, str) ] On 1000 characters: TIME: 0 ms [ replace_method(str) ] TIME: 3 ms [ regular_expression_method(str, dict) ] TIME: 2 ms [ matts_multi_replace_method(list, str) ] On 10000 characters: TIME: 3 ms [ replace_method(str) ] TIME: 7 ms [ regular_expression_method(str, dict) ] TIME: 5 ms [ matts_multi_replace_method(list, str) ] On 100000 characters: TIME: 36 ms [ replace_method(str) ] TIME: 46 ms [ regular_expression_method(str, dict) ] TIME: 39 ms [ matts_multi_replace_method(list, str) ] On 1000000 characters: TIME: 318 ms [ replace_method(str) ] TIME: 360 ms [ regular_expression_method(str, dict) ] TIME: 320 ms [ matts_multi_replace_method(list, str) ] On 3687809 characters: TIME: 1.277524 sec [ replace_method(str) ] TIME: 1.290590 sec [ regular_expression_method(str, dict) ] TIME: 1.116601 sec [ matts_multi_replace_method(list, str) ] So kudos to Matt for beating the multi replace method on a fairly large input string. Anyone got ideas for beating it on a smaller string?
[ "Something like the following maybe? Split the text into pieces with the first \"from\" item to be replaced, then recursively split each of those parts into sub-parts with the next \"from\" item to be replaced, and so on, until you've visited all your replacements. Then join with the \"to\" replacement item for eac...
[ 7, 1, 0 ]
[]
[]
[ "php", "python", "string" ]
stackoverflow_0003411006_php_python_string.txt
Q: Add/remove programs in Windows XP with Python script I would like to add add/programs like adobe acrobat reader and other application in windows XP using Python script. Kindly looking for some help. Thanks in advance! Everest. A: Are you installing or uninstalling? Installing: Easy way: subprocess.Popen the installer. Nearly-as-easy way: subprocess.Popen the installer, with some Windows hackery so that the user doesn't have to click anything. Uninstalling: As above. Hard way: work out the files changed on the computer and revert them manually.
Add/remove programs in Windows XP with Python script
I would like to add add/programs like adobe acrobat reader and other application in windows XP using Python script. Kindly looking for some help. Thanks in advance! Everest.
[ "Are you installing or uninstalling?\nInstalling:\nEasy way: subprocess.Popen the installer.\nNearly-as-easy way: subprocess.Popen the installer, with some Windows hackery so that the user doesn't have to click anything.\nUninstalling:\nAs above.\nHard way: work out the files changed on the computer and revert them...
[ 2 ]
[]
[]
[ "administration", "python", "system", "windows" ]
stackoverflow_0003599213_administration_python_system_windows.txt
Q: Changing the words keeping its meaning intact We have a requirement in which we need to change change the words or phrases in the sentence while keeping its meaning intact. This application is going to provide suggestions to users who are involved in copy-writing. I don't know where should I start... we have not yet finalized the technology but would like to do it in a Python or in .Net. A: Just for laughs: import urllib2 import urllib import sys import json def translate(text,lang1,lang2): base_url='http://ajax.googleapis.com/ajax/services/language/translate?' langpair='%s|%s'%(lang1,lang2) params=urllib.urlencode( (('v',1.0), ('q',text.encode('utf-8')), ('langpair',langpair),) ) url=base_url+params content=urllib2.urlopen(url).read() try: trans_dict=json.loads(content) except AttributeError: try: trans_dict=json.load(content) except AttributeError: trans_dict=json.read(content) return trans_dict['responseData']['translatedText'] languages='de da nl zh-tw ko es pt el'.split() text=(' '.join(sys.argv[1:])).decode('utf-8') for lang in languages: result=translate(text,'en',lang) result=translate(result,lang,'en') print(result) print Running test.py "Hi, We have a requirement in which we need to change the words or phrases in the sentence while keeping its meaning intact." yields Hi, we have a commitment in which we have to change the words or phrases in a sentence while preserving its meaning. Hello, We have a requirement where we need to change words or phrases in the sentence while keeping its meaning intact. Hi, We have a requirement we need the words or phrases within the meaning while changing its meaning intact. Hey, we have a requirement, we need to change the word or phrase in the sentence meaning, while maintaining its integrity. Hi, we maintain that we need to change the word or phrase in the sentence requirements have meant that literally. Hello, We have a requirement that we must change the words or phrases in the sentence, keeping intact its meaning. Hi, we have an obligation that we need to change words or phrases in the sentence, keeping intact its meaning. Hello, We have a requirement where we need to change the words or phrases in the sentence, while keeping intact the concept. A: Use nltk in python. Access to part-of-speech tagging and wordnet, both of which will be necessary to make reasonable substitutions. http://www.nltk.org/ A: Some combination of synonyms and Markov chains might work, but you'll always get strange results. Don't expect a program to make better phrases than humans. A: If you are looking for computer aid, where the software provides suggestions for solutions or part of solutions, I think to provide automated thesaurus lookup for the content words in each sentence would be a good start. Just use a stop-word list to filter out uninteresting words. Translation Memory is a related concept, where NLP is used to aid in translation, I'm sure you can get ideas for the user-interface etc. from this. There are several open source solutions available. If you want a totally unsupervised process, I think parsing into some semantic representation and changing some content words based on WordNet for example, and then generate from this is perhaps the theoretically cleanest approach. If only grammatical restructuring is okay then drop the changing. The quality, however, will most probably be low. If you only need this for a narrow field, it is possible to do a lot of tailoring, and making quite good results possible.
Changing the words keeping its meaning intact
We have a requirement in which we need to change change the words or phrases in the sentence while keeping its meaning intact. This application is going to provide suggestions to users who are involved in copy-writing. I don't know where should I start... we have not yet finalized the technology but would like to do it in a Python or in .Net.
[ "Just for laughs:\nimport urllib2\nimport urllib\nimport sys\nimport json\n\ndef translate(text,lang1,lang2):\n base_url='http://ajax.googleapis.com/ajax/services/language/translate?' \n langpair='%s|%s'%(lang1,lang2)\n params=urllib.urlencode( (('v',1.0),\n ('q',text.encode('utf-8...
[ 14, 1, 0, 0 ]
[]
[]
[ ".net", "nlp", "python" ]
stackoverflow_0003591474_.net_nlp_python.txt
Q: Threading in python: retrieve return value when using target= Possible Duplicate: Return value from thread I want to get the "free memory" of a bunch of servers like this: def get_mem(servername): res = os.popen('ssh %s "grep MemFree /proc/meminfo | sed \'s/[^0-9]//g\'"' % servername) return res.read().strip() since this can be threaded I want to do something like that: import threading thread1 = threading.Thread(target=get_mem, args=("server01", )) thread1.start() But now: how can I access the return value(s) of the get_mem functions? Do I really need to go the full fledged way creating a class MemThread(threading.Thread) and overwriting __init__ and __run__? A: You could create a synchronised queue, pass it to the thread function and have it report back by pushing the result into the queue, e.g.: def get_mem(servername, q): res = os.popen('ssh %s "grep MemFree /proc/meminfo | sed \'s/[^0-9]//g\'"' % servername) q.put(res.read().strip()) # ... import threading, queue q = queue.Queue() threading.Thread(target=get_mem, args=("server01", q)).start() result = q.get() A: For the record, this is what I finally came up with (deviated from multiprocessing examples from multiprocessing import Process, Queue def execute_parallel(hostnames, command, max_processes=None): """ run the command parallely on the specified hosts, returns output of the commands as dict >>> execute_parallel(['host01', 'host02'], 'hostname') {'host01': 'host01', 'host02': 'host02'} """ NUMBER_OF_PROCESSES = max_processes if max_processes else len(hostnames) def worker(jobs, results): for hostname, command in iter(jobs.get, 'STOP'): results.put((hostname, execute_host_return_output(hostname, command))) job_queue = Queue() result_queue = Queue() for hostname in hostnames: job_queue.put((hostname, command)) for i in range(NUMBER_OF_PROCESSES): Process(target=worker, args=(job_queue, result_queue)).start() result = {} for i in range(len(hostnames)): result.update([result_queue.get()]) # tell the processes to stop for i in range(NUMBER_OF_PROCESSES): job_queue.put('STOP') return result
Threading in python: retrieve return value when using target=
Possible Duplicate: Return value from thread I want to get the "free memory" of a bunch of servers like this: def get_mem(servername): res = os.popen('ssh %s "grep MemFree /proc/meminfo | sed \'s/[^0-9]//g\'"' % servername) return res.read().strip() since this can be threaded I want to do something like that: import threading thread1 = threading.Thread(target=get_mem, args=("server01", )) thread1.start() But now: how can I access the return value(s) of the get_mem functions? Do I really need to go the full fledged way creating a class MemThread(threading.Thread) and overwriting __init__ and __run__?
[ "You could create a synchronised queue, pass it to the thread function and have it report back by pushing the result into the queue, e.g.:\ndef get_mem(servername, q):\n res = os.popen('ssh %s \"grep MemFree /proc/meminfo | sed \\'s/[^0-9]//g\\'\"' % servername)\n q.put(res.read().strip())\n\n# ...\n\nimport ...
[ 19, 2 ]
[]
[]
[ "memory", "multithreading", "python" ]
stackoverflow_0002577233_memory_multithreading_python.txt
Q: General utility to remove/strip all comments from source code in various languages? I am looking for a command-line tool that removes all comments from an input file and returns the stripped output. It'd be nice it supports popular programming languages like c, c++, python, php, javascript, html, css, etc. It has to be syntax-aware as opposed to regexp-based, since the latter will catch the pattern in source code strings as well. Is there any such tool? I am fully aware that comments are useful information and often leaving them as they are is a good idea. It's just that my focus is on different use cases. A: cloc, a free Perl script, can do this. Remove Comments from Source Code How can you tell if cloc correctly identifies comments? One way to convince yourself cloc is doing the right thing is to use its --strip-comments option to remove comments and blank lines from files, then compare the stripped-down files to originals. It supports a lot of languages. A: What you want can be done with emacs scripting. I wrote this script for you which does exactly what you want and can be easily extended to any language. Filename: kill-comments #!/usr/bin/python import subprocess import sys import os target_file = sys.argv[1] command = "emacs -batch -l ~/.emacs-batch " + \ target_file + \ " --eval '(kill-comment (count-lines (point-min) (point-max)))'" + \ " -f save-buffer" #to load a custom .emacs script (for more syntax support), #use -l <file> in the above command #print command fnull = open(os.devnull, 'w') subprocess.call(command, shell = True, stdout = fnull, stderr = fnull) fnull.close() to use it just call: kill-comments <file-name> To add any language to it edit ~/.emacs-batch and add that language's major mode. You can find syntax aware modes for basically everything you could want at http://www.emacswiki.org. As an example, here is my ~/.emacs-batch file. It extends the above script to remove comments from javascript files. (I have javascript.el in my ~/.el directory) (setq load-path (append (list (concat (getenv "HOME") "/.el")) load-path)) (load "javascript") (setq auto-mode-alist (cons '("\\.js$" . javascript-mode) auto-mode-alist)) With the javascript addition this will remove comments from all the filetypes you mentioned as well as many more. Good Luck and happy coding! A: Paul Dixon's response to this question on stripping comments from a script might be worth looking at. A: I don't know of such a tool - which isn't the same as saying there isn't one. I once started to design one, but it quickly gets insane - not helped by the comment rules in C and C++. /\ * Comment? *\ / (Answer: yes!) "/\ * Comment? *\ /" (Answer: no!) To do the job reasonably, you have to be aware of: Language comment conventions Language quoted string conventions (Python and Perl are enough to drive you insane here) Escape conventions (Shell gets you here - along with the quotes) These combine to make the job tolerably close to impossible. I ended up with a program, scc, to strip C and C++ comments. Its torture test includes worse examples than the comments shown above - and it does a decent job. But extending that to do shell or Perl or Python or (take your pick) was sufficiently non-trivial that I did not do it. A: No such tool exists yet.
General utility to remove/strip all comments from source code in various languages?
I am looking for a command-line tool that removes all comments from an input file and returns the stripped output. It'd be nice it supports popular programming languages like c, c++, python, php, javascript, html, css, etc. It has to be syntax-aware as opposed to regexp-based, since the latter will catch the pattern in source code strings as well. Is there any such tool? I am fully aware that comments are useful information and often leaving them as they are is a good idea. It's just that my focus is on different use cases.
[ "cloc, a free Perl script, can do this.\n\nRemove Comments from Source Code\nHow can you tell if cloc correctly identifies comments? One way to convince yourself cloc is doing the right thing is to use its --strip-comments option to remove comments and blank lines from files, then compare the stripped-down files to...
[ 4, 3, 1, 0, 0 ]
[ "You might coax GNU Source-highlight into doing this.\n" ]
[ -1 ]
[ "c", "php", "python" ]
stackoverflow_0003349156_c_php_python.txt
Q: Finding the common elements of a list Hi as per the earlier post. Given the following list: ['Jellicle', 'Cats', 'are', 'black', 'and', 'white,', 'Jellicle', 'Cats', 'are', 'rather', 'small;', 'Jellicle', 'Cats', 'are', 'merry', 'and', 'bright,', 'And', 'pleasant', 'to', 'hear', 'when', 'they', 'caterwaul.', 'Jellicle', 'Cats', 'have', 'cheerful', 'faces,', 'Jellicle', 'Cats', 'have', 'bright', 'black', 'eyes;', 'They', 'like', 'to', 'practise', 'their', 'airs', 'and', 'graces', 'And', 'wait', 'for', 'the', 'Jellicle', 'Moon', 'to', 'rise.', ''] I am trying to count how many times each word THAT STARTS WITH A CAPITAL appears and display the top 3. I am not interested in words that do not start with a capital. If a word appears multiple times, sometimes starting with a capital and sometimes not, only count the times it does with a capital. THis is what my code looks like currently: words = "" for word in open('novel.txt', 'rU'): words += word words = words.split(' ') words= list(words) words = ('\n'.join(words)).split('\n') word_counter = {} for word in words: if word in word_counter: word_counter[word] += 1 else: word_counter[word] = 1 popular_words = sorted(word_counter, key = word_counter.get, reverse = True) top_3 = popular_words[:3] matches = [] for i in range(3): print word_counter[top_3[i]], top_3[i] A: #uncomment to produce the word file ##words = ['Jellicle', 'Cats', 'are', 'black', 'and', 'white,', 'Jellicle', 'Cats', 'are', 'rather', 'small;', 'Jellicle', 'Cats', 'are', 'merry', 'and', 'bright,', 'And', 'pleasant', 'to', 'hear', 'when', 'they', 'caterwaul.', 'Jellicle', 'Cats', 'have', 'cheerful', 'faces,', 'Jellicle', 'Cats', 'have', 'bright', 'black', 'eyes;', 'They', 'like', 'to', 'practise', 'their', 'airs', 'and', 'graces', 'And', 'wait', 'for', 'the', 'Jellicle', 'Moon', 'to', 'rise.', ''] ##open('novel.txt','w').write('\n'.join(words)) import string cap_words = [word.strip(string.punctuation) for word in open('novel.txt').read().split() if word.istitle()] ##print(cap_words) # debug try: from collections import Counter # Python >= 2.7 print('Counter') print(Counter(cap_words).most_common(3)) except ImportError: print('Normal dict') wordcount= dict() for word in cap_words: wordcount[word] = (wordcount[word] + 1 if word in wordcount else 1) print(sorted(wordcount.items(), key = lambda x: x[1], reverse = True)[:3]) I do not get it why you would like to keep different kinds of line termination with 'rU' mode. I would use normally normal open as I wrote in edited code above. EDIT: You had words together with punctuation, so cleaned up those with strip() A: print "\n".join(sorted(["%d %s" % (lst.count(i), i) \ for i in set(lst) if i.istitle()])[-3:]) 2 And 5 Cats 6 Jellicle A: Here are some additional comments: words = "" for word in open('novel.txt', 'rU'): words += word words = words.split(' ') words= list(words) words = ('\n'.join(words)).split('\n') can be replaced with: text = open('novel.txt', 'rU').read() # read everything wordlist = text.split() # split on all whitespace But you don't use your 'must start with a capital letter' requirement yet. Time to add: capwordlist = (word for word in wordlist if word.istitle()) istitle() means word[0].isupper() and word[1:].islower(). This means 'SO'.istitle() -> False. That might work for you, but maybe you just want the word[0].isupper() instead. This part is good if you can't use collections.Counter (new in 2.7) word_counter = {} for word in capwordlist: if word in word_counter: word_counter[word] += 1 else: word_counter[word] = 1 popular_words = sorted(word_counter, key = word_counter.get, reverse = True) top_3 = popular_words[:3] else this simply becomes: from collections import Counter word_counter = Counter(capwords) top_3 = word_counter.most_common(3) # gives `word, count` pairs! And this: for i in range(3): print word_counter[top_3[i]], top_3[i] can be this: for word in top_3: print word_counter[word], word A: One thing i'd avoid is reading all the words in before processing. It will work, but IMHO, it's better not to do that if you don't need to, and you don't. Here's my solution (with elements liberally stolen from previous ones!), done with 2.6.2: import sys # a generator function which iterates over the words in a file def words(f): for line in f: for word in line.split(): yield word # returns a generator expression filtering an iterator down to titlecase words def titles(s): return (word for word in s if word.istitle()) # count the titlecase words in the file count = {} for word in titles(words(file(sys.argv[1]))): count[word] = count.get(word, 0) + 1 # build a list of tuples with the count for each word countsAndWords = [(kv[1], kv[0]) for kv in count.iteritems()] # put them in decreasing order countsAndWords.sort() countsAndWords.reverse() # print the top three for count, word in countsAndWords[:3]: print word, count I do a sort of decorate-sort-undecorate on the counts rather than doing the sort with a comparator which does lookups in the count dictionary; it's less elegant, but i believe it will be faster. That's probably a sinful thing to do. A: In general, word[0].isupper() will tel you if a word starts with an uppercase letter. Combine this into a list comprehension (or your loop) [x for x in my_list if x[0].isupper()] (assuming there are no empty strings) and you get all words starting with an uppercase letter. A: Since you aren't using Python2.7 and don't have Counter from collections import defaultdict counter = defaultdict(int) words = ['Jellicle', 'Cats', 'are', 'black', 'and', 'white,', 'Jellicle', 'Cats', 'are', 'rather', 'small;', 'Jellicle', 'Cats', 'are', 'merry', 'and', 'bright,', 'And', 'pleasant', 'to', 'hear', 'when', 'they', 'caterwaul.', 'Jellicle', 'Cats', 'have', 'cheerful', 'faces,', 'Jellicle', 'Cats', 'have', 'bright', 'black', 'eyes;', 'They', 'like', 'to', 'practise', 'their', 'airs', 'and', 'graces', 'And', 'wait', 'for', 'the', 'Jellicle', 'Moon', 'to', 'rise.', ''] for word in (word for word in words if word[0].isupper()): counter[word]+=1 print counter A: you could use itertools import itertools words = ['Jellicle', 'Cats', 'are', 'black', 'and', 'white,', 'Jellicle', 'Cats', 'are', 'rather', 'small;', 'Jellicle', 'Cats', 'are', 'merry', 'and', 'bright,', 'And', 'pleasant', 'to', 'hear', 'when', 'they', 'caterwaul.', 'Jellicle', 'Cats', 'have', 'cheerful', 'faces,', 'Jellicle', 'Cats', 'have', 'bright', 'black', 'eyes;', 'They', 'like', 'to', 'practise', 'their', 'airs', 'and', 'graces', 'And', 'wait', 'for', 'the', 'Jellicle', 'Moon', 'to', 'rise.', ''] capwords = (word for word in words if len(word) > 1 and word[0].isupper()) capwordssorted = sorted(capwords) wordswithcounts = ((k,len(list(g))) for (k,g) in itertools.groupby(capwordssorted)) print sorted(wordswithcounts,key=lambda x:x[1],reverse=True)[:3]
Finding the common elements of a list
Hi as per the earlier post. Given the following list: ['Jellicle', 'Cats', 'are', 'black', 'and', 'white,', 'Jellicle', 'Cats', 'are', 'rather', 'small;', 'Jellicle', 'Cats', 'are', 'merry', 'and', 'bright,', 'And', 'pleasant', 'to', 'hear', 'when', 'they', 'caterwaul.', 'Jellicle', 'Cats', 'have', 'cheerful', 'faces,', 'Jellicle', 'Cats', 'have', 'bright', 'black', 'eyes;', 'They', 'like', 'to', 'practise', 'their', 'airs', 'and', 'graces', 'And', 'wait', 'for', 'the', 'Jellicle', 'Moon', 'to', 'rise.', ''] I am trying to count how many times each word THAT STARTS WITH A CAPITAL appears and display the top 3. I am not interested in words that do not start with a capital. If a word appears multiple times, sometimes starting with a capital and sometimes not, only count the times it does with a capital. THis is what my code looks like currently: words = "" for word in open('novel.txt', 'rU'): words += word words = words.split(' ') words= list(words) words = ('\n'.join(words)).split('\n') word_counter = {} for word in words: if word in word_counter: word_counter[word] += 1 else: word_counter[word] = 1 popular_words = sorted(word_counter, key = word_counter.get, reverse = True) top_3 = popular_words[:3] matches = [] for i in range(3): print word_counter[top_3[i]], top_3[i]
[ "#uncomment to produce the word file\n##words = ['Jellicle', 'Cats', 'are', 'black', 'and', 'white,', 'Jellicle', 'Cats', 'are', 'rather', 'small;', 'Jellicle', 'Cats', 'are', 'merry', 'and', 'bright,', 'And', 'pleasant', 'to', 'hear', 'when', 'they', 'caterwaul.', 'Jellicle', 'Cats', 'have', 'cheerful', 'faces,', ...
[ 7, 3, 2, 2, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003594740_python.txt
Q: I can't instantiate a simple class in Python I want to generate a Python class via a file. This is a very simple file, named testy.py: def __init__(self,var): print (var) When I try to instantiate it I get: >>> import testy >>> testy('1') Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'module' object is not callable Then , I try something else: class testy_rev1: def __init__(self,var): print (var) I try to instanicate it and I get: >>> import testy_rev1 >>> a=testy_rev1('1') Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'module' object is not callable >>> a=testy_rev1.testy_rev1('1') 1 What I am looking for is a way to import it from a file w/o resorting to: import <module name>.<module name> A: Attempt 1 failed because you were not defining a class, just a function (which you fixed with attempt 2). Attempt 2 is failing because you looking at the import statement like it is a Java import statement. In Python, an import makes a module object that can be used to access items inside it. If you want use a class with in a module without first specifying the module you want to use the following: from my_module import MyClass a = MyClass() As a side note, your print method in the 2nd attempt in not indented after the __init__ method. This might just me a formatting error when you posted here, but it will not run the code how you expect. A: With a file called testy.py with this: class testy_rev1: def __init__(self, var): print (var) You will have to do either: >>> import testy >>> testy.testy_rev1('1') Or: >>> from testy import testy_rev1 >>> testy_rev1('1') Or (not recommended, since you will not see where the definition came from in the source): >>> from testy import * >>> testy_rev1('1') Other than that I do not know how you could do it. A: import x imports a module called x. import y.x imports the module d from the module/package y. Anything in this module is refered to as x.stuff or y.x.stuff. That's how it works and they won't change the language for your convenience ;) You can always do from module import thingy. But consider that importing the whole module is usually preferred over this... for a reason (to make clearer where it came from, to avoid namespace clashes, because "explicit is better than mplicit")!
I can't instantiate a simple class in Python
I want to generate a Python class via a file. This is a very simple file, named testy.py: def __init__(self,var): print (var) When I try to instantiate it I get: >>> import testy >>> testy('1') Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'module' object is not callable Then , I try something else: class testy_rev1: def __init__(self,var): print (var) I try to instanicate it and I get: >>> import testy_rev1 >>> a=testy_rev1('1') Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'module' object is not callable >>> a=testy_rev1.testy_rev1('1') 1 What I am looking for is a way to import it from a file w/o resorting to: import <module name>.<module name>
[ "Attempt 1 failed because you were not defining a class, just a function (which you fixed with attempt 2).\nAttempt 2 is failing because you looking at the import statement like it is a Java import statement. In Python, an import makes a module object that can be used to access items inside it. If you want use a cl...
[ 2, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003600153_python.txt
Q: SOAPpy, C# and object passing I'm trying to write a SOAPpy client to my C# WebService. It is arriving as null :( How can I get any debug from the C# SOAP parser that WebService uses? This is what Python sends: <?xml version="1.0" encoding="UTF-8"?> <SOAP-ENV:Envelope SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/1999/XMLSchema" > <SOAP-ENV:Body> <ns1:UpdateSession xmlns:ns1="http://www.xlogic.pl/SENACA" SOAP-ENC:root="1"> <xsd:Session> <ID xsi:type="xsd:int">420</ID> <RecordCreationTime SOAP-ENC:arrayType="xsd:ur-type[6]" xsi:type="SOAP-ENC:Array"> <item xsi:type="xsd:int">2010</item> <item xsi:type="xsd:int">8</item> <item xsi:type="xsd:int">17</item> <item xsi:type="xsd:int">11</item> <item xsi:type="xsd:int">13</item> <item xsi:type="xsd:double">21.0</item> </RecordCreationTime> <ASP_SessionID xsi:type="xsd:string">92072674A04CB88D62776EA7</ASP_SessionID> <LangID xsi:type="xsd:string">fr-FR</LangID> <OneTimeKey xsi:type="xsd:string">a334cea18e014f4d8d04</OneTimeKey> </xsd:Session> </ns1:UpdateSession> </SOAP-ENV:Body> </SOAP-ENV:Envelope> This is what C# expects <?xml version="1.0" encoding="utf-16"?> <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:tns="http://www.xlogic.pl/SENACA" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Body> <tns:UpdateSession> <s href="#id1"/> </tns:UpdateSession> <tns:Session id="id1" xsi:type="tns:Session"> <ID xsi:type="xsd:int">int</ID> <RecordCreationTime xsi:type="xsd:dateTime">dateTime</RecordCreationTime> <ASP_SessionID xsi:type="xsd:string">string</ASP_SessionID> <LangID xsi:type="xsd:string">string</LangID> <OneTimeKey xsi:type="xsd:string">string</OneTimeKey> </tns:Session> </soap:Body> </soap:Envelope> A: Not a Python answer, but soapUI is a very useful facility for debugging and automated testing of web services. I used it heavily on a C# WCF project, with a variety of clients, including Python, Boo, Java, and C#.
SOAPpy, C# and object passing
I'm trying to write a SOAPpy client to my C# WebService. It is arriving as null :( How can I get any debug from the C# SOAP parser that WebService uses? This is what Python sends: <?xml version="1.0" encoding="UTF-8"?> <SOAP-ENV:Envelope SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/1999/XMLSchema" > <SOAP-ENV:Body> <ns1:UpdateSession xmlns:ns1="http://www.xlogic.pl/SENACA" SOAP-ENC:root="1"> <xsd:Session> <ID xsi:type="xsd:int">420</ID> <RecordCreationTime SOAP-ENC:arrayType="xsd:ur-type[6]" xsi:type="SOAP-ENC:Array"> <item xsi:type="xsd:int">2010</item> <item xsi:type="xsd:int">8</item> <item xsi:type="xsd:int">17</item> <item xsi:type="xsd:int">11</item> <item xsi:type="xsd:int">13</item> <item xsi:type="xsd:double">21.0</item> </RecordCreationTime> <ASP_SessionID xsi:type="xsd:string">92072674A04CB88D62776EA7</ASP_SessionID> <LangID xsi:type="xsd:string">fr-FR</LangID> <OneTimeKey xsi:type="xsd:string">a334cea18e014f4d8d04</OneTimeKey> </xsd:Session> </ns1:UpdateSession> </SOAP-ENV:Body> </SOAP-ENV:Envelope> This is what C# expects <?xml version="1.0" encoding="utf-16"?> <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:tns="http://www.xlogic.pl/SENACA" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Body> <tns:UpdateSession> <s href="#id1"/> </tns:UpdateSession> <tns:Session id="id1" xsi:type="tns:Session"> <ID xsi:type="xsd:int">int</ID> <RecordCreationTime xsi:type="xsd:dateTime">dateTime</RecordCreationTime> <ASP_SessionID xsi:type="xsd:string">string</ASP_SessionID> <LangID xsi:type="xsd:string">string</LangID> <OneTimeKey xsi:type="xsd:string">string</OneTimeKey> </tns:Session> </soap:Body> </soap:Envelope>
[ "Not a Python answer, but soapUI is a very useful facility for debugging and automated testing of web services. I used it heavily on a C# WCF project, with a variety of clients, including Python, Boo, Java, and C#.\n" ]
[ 0 ]
[]
[]
[ "c#", "python", "soap", "soappy", "web_services" ]
stackoverflow_0003600225_c#_python_soap_soappy_web_services.txt
Q: Scroll to the end (right) in wx.ScrolledPanel I add dynamically images to wx.ScrolledPanel. I add them sizer which is inside ScrolledPanel. I want to scroll ScrollBar automatically to the end. It is possible? I've read that: self.scroll.SetupScrolling(scroll_x=True, scroll_y=False, scrollToTop=False) Can resolve this problem, but in my application it doesn't work. Scrolled Panel definition: self.scroll = scrolled.ScrolledPanel(self, id = -1, pos = wx.DefaultPosition, size = (510, 200), style = wx.SUNKEN_BORDER) self.sizer.Add(self.scroll) Add elements to them: self.scroll.SetSizer(self.hbox ) self.scroll.SetAutoLayout(1) self.scroll.SetupScrolling(scrollToTop=False) self.scroll.FitInside() self.SetSizerAndFit(self.sizer) self.Refresh() self.Layout() Scroll automatically return to the left (begin of my image's list).. Anyone help? A: self.Scroll(self.GetClientSize()[0], -1) clientSize is a tuple (x, y) of the widget's size and -1 specifies to not make any changes across the Y direction.
Scroll to the end (right) in wx.ScrolledPanel
I add dynamically images to wx.ScrolledPanel. I add them sizer which is inside ScrolledPanel. I want to scroll ScrollBar automatically to the end. It is possible? I've read that: self.scroll.SetupScrolling(scroll_x=True, scroll_y=False, scrollToTop=False) Can resolve this problem, but in my application it doesn't work. Scrolled Panel definition: self.scroll = scrolled.ScrolledPanel(self, id = -1, pos = wx.DefaultPosition, size = (510, 200), style = wx.SUNKEN_BORDER) self.sizer.Add(self.scroll) Add elements to them: self.scroll.SetSizer(self.hbox ) self.scroll.SetAutoLayout(1) self.scroll.SetupScrolling(scrollToTop=False) self.scroll.FitInside() self.SetSizerAndFit(self.sizer) self.Refresh() self.Layout() Scroll automatically return to the left (begin of my image's list).. Anyone help?
[ "self.Scroll(self.GetClientSize()[0], -1)\n\nclientSize is a tuple (x, y) of the widget's size and -1 specifies to not make any changes across the Y direction.\n" ]
[ 1 ]
[]
[]
[ "python", "scroll", "wxpython" ]
stackoverflow_0003598905_python_scroll_wxpython.txt
Q: Sys.path modification or more complex issue? I have problems with importing correctly a module on appengine. My app generally uses django with app-engine-patch, but this part is task queues using only the webapp framework. I need to import django settings for the app to work properly. My script starts with: import os import sys sys.path.append('common/') # Force Django to reload its settings. from django.conf import settings settings._target = None # Must set this env var before importing any part of Django os.environ['DJANGO_SETTINGS_MODULE'] = 'settings' I always get this error, or something related: <type 'exceptions.ImportError'>: No module named ragendja.settings_pre because the settings.py file starts with from ragendja.settings_pre import * I think I need to add ragendja to sys.path again but I had several tries that didn't work. Here is my directory: project/ app.yaml setting.py common/ appenginepatch/ ragendja/ setting_pre.py myapp/ script.py Is it only a sys.path problem and how do I need to modify it with the correct syntax? Thanks A: App engine patch manipulates sys.path internally. Background tasks bypass that code, so your path will not be ready for Django calls. You have two choices: Fix the paths manually. The app engine documentation (see the sub-section called "Handling import path manipulation") suggests factoring the path manipulation code into a module that can be imported by your task script. Eliminate dependencies on django code, if possible. If you can write your task to be pure python and/or google api calls, you're good to go. In your case, this might mean refactoring your settings code. A: Why not: sys.path.append('common/appenginepatch') since the ragendja is in this directory?
Sys.path modification or more complex issue?
I have problems with importing correctly a module on appengine. My app generally uses django with app-engine-patch, but this part is task queues using only the webapp framework. I need to import django settings for the app to work properly. My script starts with: import os import sys sys.path.append('common/') # Force Django to reload its settings. from django.conf import settings settings._target = None # Must set this env var before importing any part of Django os.environ['DJANGO_SETTINGS_MODULE'] = 'settings' I always get this error, or something related: <type 'exceptions.ImportError'>: No module named ragendja.settings_pre because the settings.py file starts with from ragendja.settings_pre import * I think I need to add ragendja to sys.path again but I had several tries that didn't work. Here is my directory: project/ app.yaml setting.py common/ appenginepatch/ ragendja/ setting_pre.py myapp/ script.py Is it only a sys.path problem and how do I need to modify it with the correct syntax? Thanks
[ "App engine patch manipulates sys.path internally. Background tasks bypass that code, so your path will not be ready for Django calls. You have two choices:\n\nFix the paths manually. The app engine documentation (see the sub-section called \"Handling import path manipulation\") suggests factoring the path manip...
[ 3, 0 ]
[]
[]
[ "app_engine_patch", "django", "django_settings", "google_app_engine", "python" ]
stackoverflow_0003599387_app_engine_patch_django_django_settings_google_app_engine_python.txt
Q: Recognizing notes within recorded sound - Python I'm wondering if I can extract a sequence of musical notes from a recorded sound using Python. It is the first time I'm considering using Python for this. Help would be truly awesome :) A: What you would want to do is take your audio samples, convert them into the frequency domain with a Fast Fourier Transform (FFT), find the most powerful frequency in the sample, and convert that frequency into a note. See FFT for Spectrograms in Python for pointers to libraries to help with the first two items. See http://80.68.92.234/sigproc.html for some sample code to get you started.
Recognizing notes within recorded sound - Python
I'm wondering if I can extract a sequence of musical notes from a recorded sound using Python. It is the first time I'm considering using Python for this. Help would be truly awesome :)
[ "What you would want to do is take your audio samples, convert them into the frequency domain with a Fast Fourier Transform (FFT), find the most powerful frequency in the sample, and convert that frequency into a note.\nSee FFT for Spectrograms in Python for pointers to libraries to help with the first two items. S...
[ 11 ]
[]
[]
[ "audio", "python" ]
stackoverflow_0003600795_audio_python.txt
Q: Does MongoDB have a Ruby Shell or Python Shell in addition to the Javascript shell? Or, does using Ruby's irb and then require 'mongo' and adding some Connect statement essentially act like a Ruby shell... it would be great if a Ruby shell can be possible which as convenient as the Javascript Shell. A: Your idea is fundamentally correct. I mean, as long as the language can handle command-line interpretation and support a MongoDB driver, then you could theoretically build a new MongoDB shell. However, I regularly read through the MongoDB mailing lists and I think that you're kind of on your own for this idea right now. Hey, writing a Ruby shell for Mongo would be an awesome way to learn a lot about Mongo. However, the current Mongo community is still relatively small and no one is really complaining too much about the javascript shell. A: You may find hirb handy for creating ascii tables from mongodb objects.
Does MongoDB have a Ruby Shell or Python Shell in addition to the Javascript shell?
Or, does using Ruby's irb and then require 'mongo' and adding some Connect statement essentially act like a Ruby shell... it would be great if a Ruby shell can be possible which as convenient as the Javascript Shell.
[ "Your idea is fundamentally correct. I mean, as long as the language can handle command-line interpretation and support a MongoDB driver, then you could theoretically build a new MongoDB shell.\nHowever, I regularly read through the MongoDB mailing lists and I think that you're kind of on your own for this idea rig...
[ 1, 0 ]
[]
[]
[ "mongodb", "nosql", "python", "ruby" ]
stackoverflow_0003595948_mongodb_nosql_python_ruby.txt
Q: How i parse with lxml a result page with form? I try to parse a secondary page with form . I use example code source from this link : http://blog.ianbicking.org/2007/09/24/lxmlhtml/ On my test i use this url: http://www.infofer.ro/ Like on example , I use this values : >>> pprint(form.form_values()) [('cboData', '8/30/2010'), ('txtPlecare', 'Bucuresti Nord'), ('txtSosire', 'Constanta'), ('tip', 'GO'), ('lng', '1')] The result is take it with this : result = parse(submit_form(form)).getroot() This is another page with another form . I try something like this : >>> page2=parse(result).getroot() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.6/site-packages/lxml/html/__init__.py", line 661, in parse return etree.parse(filename_or_url, parser, base_url=base_url, **kw) File "lxml.etree.pyx", line 2706, in lxml.etree.parse (src/lxml/lxml.etree.c:49945) File "parser.pxi", line 1525, in lxml.etree._parseDocument (src/lxml/lxml.etree.c:72026) TypeError: cannot parse from 'HtmlElement' How i parse the form from secondary page ? Regards. A: The getroot method does not give you another "page", but an instance of lxml.html.HtmlElement. There is no need (and no way) to parse this once more, you already have everything you need packed into the result variable.
How i parse with lxml a result page with form?
I try to parse a secondary page with form . I use example code source from this link : http://blog.ianbicking.org/2007/09/24/lxmlhtml/ On my test i use this url: http://www.infofer.ro/ Like on example , I use this values : >>> pprint(form.form_values()) [('cboData', '8/30/2010'), ('txtPlecare', 'Bucuresti Nord'), ('txtSosire', 'Constanta'), ('tip', 'GO'), ('lng', '1')] The result is take it with this : result = parse(submit_form(form)).getroot() This is another page with another form . I try something like this : >>> page2=parse(result).getroot() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.6/site-packages/lxml/html/__init__.py", line 661, in parse return etree.parse(filename_or_url, parser, base_url=base_url, **kw) File "lxml.etree.pyx", line 2706, in lxml.etree.parse (src/lxml/lxml.etree.c:49945) File "parser.pxi", line 1525, in lxml.etree._parseDocument (src/lxml/lxml.etree.c:72026) TypeError: cannot parse from 'HtmlElement' How i parse the form from secondary page ? Regards.
[ "The getroot method does not give you another \"page\", but an instance of lxml.html.HtmlElement. \nThere is no need (and no way) to parse this once more, you already have everything you need packed into the result variable.\n" ]
[ 2 ]
[]
[]
[ "lxml", "python" ]
stackoverflow_0003601222_lxml_python.txt
Q: How to glob for iterable element I have a python dictionary that contains iterables, some of which are lists, but most of which are other dictionaries. I'd like to do glob-style assignment similar to the following: myiter['*']['*.txt']['name'] = 'Woot' That is, for each element in myiter, look up all elements with keys ending in '.txt' and then set their 'name' item to 'Woot'. I've thought about sub-classing dict and using the fnmatch module. But, it's unclear to me what the best way of accomplishing this is. A: The best way, I think, would be not to do it -- '*' is a perfectly valid key in a dict, so myiter['*'] has a perfectly well defined meaning and usefulness, and subverting that can definitely cause problems. How to "glob" over keys which are not strings, including the exclusively integer "keys" (indices) in elements which are lists and not mappings, is also quite a design problem. If you nevertheless must do it, I would recommend taking full control by subclassing the abstract base class collections.MutableMapping, and implement the needed methods (__len__, __iter__, __getitem__, __setitem__, __delitem__, and, for better performance, also override others such as __contains__, which the ABC does implement on the base of the others, but slowly) in terms of a contained dict. Subclassing dict instead, as per other suggestions, would require you to override a huge number of methods to avoid inconsistent behavior between the use of "keys containing wildcards" in the methods you do override, and in those you don't. Whether you subclass collections.MutableMapping, or dict, to make your Globbable class, you have to make a core design decision: what does yourthing[somekey] return when yourthing is a Globbable? Presumably it has to return a different type when somekey is a string containing wildcards, versus anything else. In the latter case, one would imagine, just what is actually at that entry; but in the former, it can't just return another Globbable -- otherwise, what would yourthing[somekey] = 'bah' do in the general case? For your single "slick syntax" example, you want it to set a somekey entry in each of the items of yourthing (a HUGE semantic break with the behavior of every other mapping in the universe;-) -- but then, how would you ever set an entry in yourthing itself?! Let's see if the Zen of Python has anything to say about this "slick syntax" for which you yearn...: >>> import this ... If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Consider for a moment the alternative of losing the "slick syntax" (and all the huge semantic headaches it necessarily implies) in favor of clarity and simplicity (using Python 2.7-and-better syntax here, just for the dict comprehension -- use an explicit dict(...) call instead if you're stuck with 2.6 or earlier), e.g.: def match(s, pat): try: return fnmatch.fnmatch(s, pat) except TypeError: return False def sel(ds, pat): return [d[k] for d in ds for k in d if match(k, pat)] def set(ds, k, v): for d in ds: d[k] = v so your assignment might become set(sel(sel([myiter], '*')), '*.txt'), 'name', 'Woot') (the selection with '*' being redundant if all , I'm just omitting it). Is this so horrible as to be worth the morass of issues I've mentioned above in order to use instead myiter['*']['*.txt']['name'] = 'Woot' ...? By far the clearest and best-performing way, of course, remains the even-simpler def match(k, v, pat): try: if fnmatch.fnmatch(k, pat): return isinstance(v, dict) except TypeError: return False for k, v in myiter.items(): if match(k, v, '*'): for sk, sv in v.items(): if match(sk, sv, '*.txt'): sv['name'] = 'Woot' but if you absolutely crave conciseness and compactness, despising the Zen of Python's koan "Sparse is better than dense", you can at least obtain them without the various nightmares I mentioned as needed to achieve your ideal "syntax sugar". A: The best way is to subclass dict and use the fnmatch module. subclass dict: adding functionality you want in an object-oriented way. fnmatch module: reuse of existing functionality. A: You could use fnmatch for functionality to match on dictionary keys although you would have to compromise syntax slightly, especially if you wanted to do this on a nested dictionary. Perhaps a custom dictionary-like class with a search method to return wildcard matches would work well. Here is a VERY BASIC example that comes with a warning that this is NOT RECURSIVE and will not handle nested dictionaries: from fnmatch import fnmatch class GlobDict(dict): def glob(self, match): """@match should be a glob style pattern match (e.g. '*.txt')""" return dict([(k,v) for k,v in self.items() if fnmatch(k, match)]) # Start with a basic dict basic_dict = {'file1.jpg':'image', 'file2.txt':'text', 'file3.mpg':'movie', 'file4.txt':'text'} # Create a GlobDict from it glob_dict = GlobDict( **basic_dict ) # Then get glob-styl results! globbed_results = glob_dict.glob('*.txt') # => {'file4.txt': 'text', 'file2.txt': 'text'} As for what way is the best? The best way is the one that works. Don't try to optimize a solution before it's even created! A: Following the principle of least magic, perhaps just define a recursive function, rather than subclassing dict: import fnmatch def set_dict_with_pat(it,key_patterns,value): if len(key_patterns)>1: for key in it: if fnmatch.fnmatch(key,key_patterns[0]): set_dict_with_pat(it[key],key_patterns[1:],value) else: for key in it: if fnmatch.fnmatch(key,key_patterns[0]): it[key]=value Which could be used like this: myiter=({'dir1':{'a.txt':{'name':'Roger'},'b.notxt':{'name':'Carl'}},'dir2':{'b.txt':{'name':'Sally'}}}) set_dict_with_pat(myiter,['*','*.txt','name'],'Woot') print(myiter) # {'dir2': {'b.txt': {'name': 'Woot'}}, 'dir1': {'b.notxt': {'name': 'Carl'}, 'a.txt': {'name': 'Woot'}}}
How to glob for iterable element
I have a python dictionary that contains iterables, some of which are lists, but most of which are other dictionaries. I'd like to do glob-style assignment similar to the following: myiter['*']['*.txt']['name'] = 'Woot' That is, for each element in myiter, look up all elements with keys ending in '.txt' and then set their 'name' item to 'Woot'. I've thought about sub-classing dict and using the fnmatch module. But, it's unclear to me what the best way of accomplishing this is.
[ "The best way, I think, would be not to do it -- '*' is a perfectly valid key in a dict, so myiter['*'] has a perfectly well defined meaning and usefulness, and subverting that can definitely cause problems. How to \"glob\" over keys which are not strings, including the exclusively integer \"keys\" (indices) in el...
[ 5, 2, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003601309_python.txt
Q: Running multiple instances of a python program efficiently & economically? I wrote a program that calls a function with the following prototype: def Process(n): # the function uses data that is stored as binary files on the hard drive and # -- based on the value of 'n' -- scans it using functions from numpy & cython. # the function creates new binary files and saves the results of the scan in them. # # I optimized the running time of the function as much as I could using numpy & # cython, and at present it takes about 4hrs to complete one function run on # a typical winXP desktop (three years old machine, 2GB memory etc). My goal is to run this function exactly 10,000 times (for 10,000 different values of 'n') in the fastest & most economical way. following these runs, I will have 10,000 different binary files with the results of all the individual scans. note that every function 'run' is independent (meaning, there is no dependency whatsoever between the individual runs). So the question is this. having only one PC at home, it is obvious that it will take me around 4.5 years (10,000 runs x 4hrs per run = 40,000 hrs ~= 4.5 years) to complete all runs at home. yet, I would like to have all the runs completed within a week or two. I know the solution would involve accessing many computing resources at once. what is the best (fastest / most affordable, as my budget is limited) way to do so? must I buy a strong server (how much would it cost?) or can I have this run online? in such a case, is my propritary code gets exposed, by doing so? in case it helps, every instance of 'Process()' only needs about 500MB of memory. thanks. A: Check out PiCloud: http://www.picloud.com/ import cloud cloud.call(function) Maybe it's an easy solution. A: Does Process access the data on the binary files directly or do you cache it in memory? Reducing the usage of I/O operations should help. Also, isn't it possible to break Process into separate functions running in parallel? How is the data dependency inside the function? Finally, you could give some cloud computing service like Amazon EC2 a try (don't forget to read this for tools), but it won't be cheap (EC2 starts at $0.085 per hour) - an alternative would be going to an university with a computer cluster (they are pretty common nowadays, but it will be easier if you know someone there). A: Well, from your description, it sounds like things are IO bound... In which case parallelism (at least on one IO device) isn't going to help much. Edit: I just realized that you were referring more to full cloud computing, rather than running multiple processes on one machine... My advice below still holds, though.... PyTables is quite nice for out-of-core calculations! You mentioned that you're using numpy's mmap to access the data. Therefore, your execution time is likely to depend heavily on how your data is structured on the disc. Memmapping can actually be quite slow in any situation where the physical hardware has to spend most of its time seeking (e.g. reading a slice along a plane of constant Z in a C-ordered 3D array). One way of mitigating this is to change the way your data is ordered to reduce the number of seeks required to access the parts you are most likely to need. Another option that may help is compressing the data. If your process is extremely IO bound, you can actually get significant speedups by compressing the data on disk (and sometimes even in memory) and decompressing it on-the-fly before doing your calculation. The good news is that there's a very flexible, numpy-oriented library that's already been put together to help you with both of these. Have a look at pytables. I would be very surprised if tables.Expr doesn't significantly (~ 1 order of magnitude) outperform your out-of-core calculation using a memmapped array. See here for a nice, (though canned) example. From that example:
Running multiple instances of a python program efficiently & economically?
I wrote a program that calls a function with the following prototype: def Process(n): # the function uses data that is stored as binary files on the hard drive and # -- based on the value of 'n' -- scans it using functions from numpy & cython. # the function creates new binary files and saves the results of the scan in them. # # I optimized the running time of the function as much as I could using numpy & # cython, and at present it takes about 4hrs to complete one function run on # a typical winXP desktop (three years old machine, 2GB memory etc). My goal is to run this function exactly 10,000 times (for 10,000 different values of 'n') in the fastest & most economical way. following these runs, I will have 10,000 different binary files with the results of all the individual scans. note that every function 'run' is independent (meaning, there is no dependency whatsoever between the individual runs). So the question is this. having only one PC at home, it is obvious that it will take me around 4.5 years (10,000 runs x 4hrs per run = 40,000 hrs ~= 4.5 years) to complete all runs at home. yet, I would like to have all the runs completed within a week or two. I know the solution would involve accessing many computing resources at once. what is the best (fastest / most affordable, as my budget is limited) way to do so? must I buy a strong server (how much would it cost?) or can I have this run online? in such a case, is my propritary code gets exposed, by doing so? in case it helps, every instance of 'Process()' only needs about 500MB of memory. thanks.
[ "Check out PiCloud: http://www.picloud.com/\nimport cloud\ncloud.call(function)\n\nMaybe it's an easy solution.\n", "Does Process access the data on the binary files directly or do you cache it in memory? Reducing the usage of I/O operations should help.\nAlso, isn't it possible to break Process into separate fun...
[ 9, 1, 1 ]
[]
[]
[ "cython", "numpy", "python" ]
stackoverflow_0003596029_cython_numpy_python.txt
Q: calculate distance between 2 nodes in a graph I have directed graph stored in the following format in the database {STARTNODE, ENDNODE}. Therefore, {5,3} means there is an arrow from node 5 to node 3. Now I need to calculate the distance between two random nodes. What is the most efficient way? By the way, the graph is has loops. Thanks a lot! A: As you can see here If you have unweighted edges you can use BFS If you have non-negative edges you can use Dijkstra If you have negative or positive edges you most use Bellman-Ford A: If by distance we mean the minimum number of hops, then you could use Guido van Rossum's find_shortest_path function: def find_shortest_path(graph, start, end, path=[]): """ __source__='https://www.python.org/doc/essays/graphs/' __author__='Guido van Rossum' """ path = path + [start] if start == end: return path if not graph.has_key(start): return None shortest = None for node in graph[start]: if node not in path: newpath = find_shortest_path(graph, node, end, path) if newpath: if not shortest or len(newpath) < len(shortest): shortest = newpath return shortest if __name__=='__main__': graph = {'A': ['B', 'C'], 'B': ['C', 'D'], 'C': ['D'], 'D': ['C'], 'E': ['F'], 'F': ['C']} print(find_shortest_path(graph,'A','D')) # ['A', 'B', 'D'] print(len(find_shortest_path(graph,'A','D'))) # 3 A: Given that the distance is the number of hops, and is optimal (shortest path.) You may keep track of visited nodes and current reachable nodes using Python's list/set. Starts from the first node and then keep hopping from the current set of nodes until you reach the target. For example, given this graph: [hop 0] visited: {} current: {A} [hop 1] visited: {A} current: {B, C, J} [hop 2] visited: {A, B, C, J} current: {D, E, F, G, H} [hop 3] visited: {A, B, C, D, E, F, G, H, J} current: {K} // destination is reachable within 3 hops The point of visited-node list is to prevent visiting the visited nodes, resulting in a loop. And to get shortest distance, it's no use to make a revisit as it always makes the distance of resulting path longer. This is a simple implementation of Breadth-first search. The efficiency partly depends on how to check visited nodes, and how to query adjacent nodes of given node. The Breadth-first search always guarantee to give optimal distance but this implementation could create a problem if you have lots of node, say billion/million, in your database. I hope this gives the idea. A: Dijkstra's algorithm A: If you are really looking for the most efficient way, then the solution is to implement breadth first search in C and then call the implementation from the Python layer. (Of course this applies only if the edges are unweighted; weighted edges require Dijkstra's algorithm if the weights are non-negative, or the Bellman-Ford algorithm if weights can be negative). Incidentally, the igraph library implements all these algorithms in C, so you might want to try that. If you prefer a pure Python-based solution (which is easier to install than igraph), try the NetworkX package.
calculate distance between 2 nodes in a graph
I have directed graph stored in the following format in the database {STARTNODE, ENDNODE}. Therefore, {5,3} means there is an arrow from node 5 to node 3. Now I need to calculate the distance between two random nodes. What is the most efficient way? By the way, the graph is has loops. Thanks a lot!
[ "As you can see here\nIf you have unweighted edges you can use BFS\nIf you have non-negative edges you can use Dijkstra\nIf you have negative or positive edges you most use Bellman-Ford\n", "If by distance we mean the minimum number of hops, then you could use Guido van Rossum's find_shortest_path function:\ndef ...
[ 13, 5, 5, 4, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003601180_python.txt
Q: What is the meaning of error code 24 on Linux? I'm running a Java program through a Python script on Linux, but the program crashes without outputting any error messages. The os.system command that executes the Java program outputs an error code of 24. What does this mean? A: On my system this is found in /usr/include/asm-generic/errno-base.h: #define EMFILE 24 /* Too many open files */ This means your process has exceeded the limit on C/system file descriptors. Generally the limit is around 1024, there may be a bug in that some file descriptors are not being closed. (This would seem unlikely in Python or Java code where it's done for you...). Update0 I've just realised you may be talking about the return code from the Java program. This is program specific, you'll need to check the documentation or code for the program. A: From http://docs.python.org/library/os.html#os.system: On Unix, the return value is the exit status of the process encoded in the format specified for wait(). Note that POSIX does not specify the meaning of the return value of the C system() function, so the return value of the Python function is system-dependent. Luckily, the C macros used to dissect the return status are available in the os module (starting here) I ran these on amd64/Linux: >>> import os >>> os.WIFEXITED(24) #Return True if the process exited using the exit(2) system call False >>> os.WIFSIGNALED(24) #Return True if the process exited due to a signal True >>> os.WTERMSIG(24) #Return the signal which caused the process to exit 24 According to http://linux.die.net/man/7/signal, I think signal 24 may be SIGTSTP, (someone stopped the process by hitting CTRL+Z). What platform/architecture are you running on? (Going forward, I would recommend using the subprocess module so that you can capture stdout/stderror) update Someone had posted it and then it disappeared, but signal 24 is likely SIGXCPU (CPU time limit exceeded)
What is the meaning of error code 24 on Linux?
I'm running a Java program through a Python script on Linux, but the program crashes without outputting any error messages. The os.system command that executes the Java program outputs an error code of 24. What does this mean?
[ "On my system this is found in /usr/include/asm-generic/errno-base.h:\n#define EMFILE 24 /* Too many open files */\n\nThis means your process has exceeded the limit on C/system file descriptors. Generally the limit is around 1024, there may be a bug in that some file descriptors are not being closed. (This wo...
[ 7, 2 ]
[]
[]
[ "error_code", "java", "linux", "python" ]
stackoverflow_0003602160_error_code_java_linux_python.txt
Q: Facebook stream API error works in Browser but not Server-side If I enter this URL in a browser it returns to me the valid XML data that I am interested in scraping. http://www.facebook.com/ajax/stream/profile.php?__a=1&profile_id=36343869811&filter=2&max_time=0&try_scroll_load=false&_log_clicktype=Filter%20Stories%20or%20Pagination&ajax_log=0 However, if I do it from the server-side, it doesn't work as it previously did. Now it just returns this error, which seems to be the default error message {u'silentError': 0, u'errorDescription': u"Something went wrong. We're working on getting it fixed as soon as we can.", u'errorSummary': u'Oops', u'errorIsWarning': False, u'error': 1357010, u'payload': None} here is the code in question, I've tried multiple User Agents, to no avail: import urllib2 user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 6.1; he; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3' uaheader = { 'User-Agent' : user_agent } wallurl='http://www.facebook.com/ajax/stream/profile.php?__a=1&profile_id=36343869811&filter=2&max_time=0&try_scroll_load=false&_log_clicktype=Filter%20Stories%20or%20Pagination&ajax_log=0' req = urllib2.Request(wallurl, headers=uaheader) resp = urllib2.urlopen(req) pageData=convertTextToUnicode(resp.read()) print pageData #and get that error What would be the difference between the server calls and my own browser aside from User Agents and IP addresses? A: I tried the above url in both chrome and firefox. It works on chrome but fails on firefox. On chrome, I am signed into facebook while on Firefox, I am not. This could be the reason for this discrepancy. You will need to provide authentication in your urllib2 based script that you have posted. There is a existing question on authentication with urllib2.
Facebook stream API error works in Browser but not Server-side
If I enter this URL in a browser it returns to me the valid XML data that I am interested in scraping. http://www.facebook.com/ajax/stream/profile.php?__a=1&profile_id=36343869811&filter=2&max_time=0&try_scroll_load=false&_log_clicktype=Filter%20Stories%20or%20Pagination&ajax_log=0 However, if I do it from the server-side, it doesn't work as it previously did. Now it just returns this error, which seems to be the default error message {u'silentError': 0, u'errorDescription': u"Something went wrong. We're working on getting it fixed as soon as we can.", u'errorSummary': u'Oops', u'errorIsWarning': False, u'error': 1357010, u'payload': None} here is the code in question, I've tried multiple User Agents, to no avail: import urllib2 user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 6.1; he; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3' uaheader = { 'User-Agent' : user_agent } wallurl='http://www.facebook.com/ajax/stream/profile.php?__a=1&profile_id=36343869811&filter=2&max_time=0&try_scroll_load=false&_log_clicktype=Filter%20Stories%20or%20Pagination&ajax_log=0' req = urllib2.Request(wallurl, headers=uaheader) resp = urllib2.urlopen(req) pageData=convertTextToUnicode(resp.read()) print pageData #and get that error What would be the difference between the server calls and my own browser aside from User Agents and IP addresses?
[ "I tried the above url in both chrome and firefox. It works on chrome but fails on firefox. On chrome, I am signed into facebook while on Firefox, I am not. \nThis could be the reason for this discrepancy. You will need to provide authentication in your urllib2 based script that you have posted.\nThere is a existin...
[ 2 ]
[]
[]
[ "facebook", "python", "scraper" ]
stackoverflow_0003602438_facebook_python_scraper.txt
Q: Why won't recursive generator work? I have a class where each instance is basically of a bunch of nested lists, each of which holds a number of integers or another list containing integers, or a list of lists, etc., like so: class Foo(list): def __init__(self): self.extend( list(1), list(2), list(3), range(5), [range(3), range(2)] ) I want to define a method to walk the nested lists and give me one integer at a time, not unlike os.walk. I tried this: def _walk(self): def kids(node): for x in node: try: for y in kids(x): yield y except TypeError: yield x return kids(x) But it immediately raises a stopiteration error. If I add a print statement to print each "node" in the first for loop, the function appears to iterate over the whole container in the way I want, but without yielding each node. It just prints them all the first time I call next on the generator. I'm stumped. Please help! A: It works if you change return kids(x) to return kids(self) A: Here's a function that is a simpler version of your _walk method that does what you want on an arbitrary iterable. The internal kids function is not required. def walk(xs): for x in xs: try: for y in walk(x): yield y except TypeError: yield x This could be trivially adapted to work as a method on your Foo object.
Why won't recursive generator work?
I have a class where each instance is basically of a bunch of nested lists, each of which holds a number of integers or another list containing integers, or a list of lists, etc., like so: class Foo(list): def __init__(self): self.extend( list(1), list(2), list(3), range(5), [range(3), range(2)] ) I want to define a method to walk the nested lists and give me one integer at a time, not unlike os.walk. I tried this: def _walk(self): def kids(node): for x in node: try: for y in kids(x): yield y except TypeError: yield x return kids(x) But it immediately raises a stopiteration error. If I add a print statement to print each "node" in the first for loop, the function appears to iterate over the whole container in the way I want, but without yielding each node. It just prints them all the first time I call next on the generator. I'm stumped. Please help!
[ "It works if you change return kids(x) to return kids(self)\n", "Here's a function that is a simpler version of your _walk method that does what you want on an arbitrary iterable. The internal kids function is not required.\ndef walk(xs):\n for x in xs:\n try:\n for y in walk(x):\n ...
[ 1, 1 ]
[]
[]
[ "generator", "python", "recursion" ]
stackoverflow_0003602550_generator_python_recursion.txt
Q: Wrap a function in python supplying an additional boolean I'm porting some code from Perl to Python, and one of the functions I am moving does the following: sub _Run($verbose, $cmd, $other_stuff...) { ... } sub Run { _Run(1, @_); } sub RunSilent { _Run(0, @_); } so to do it Python, I naively thought I could do the following: def _Run(verbose, cmd, other_stuff...) ... def Run(*args) return _Run(True, args); def RunSilent return _Run(False, args); but that doesn't work, because args is passed as an array/tuple. To make it work, I did the following: def _Run(verbose, cmd, other_stuff...) ... def Run(*args) return _Run(True, ','.join(args)); def RunSilent return _Run(False, ','.join(args)); but that looks kind of ugly. Is there a better way? A: The * can be used for passing (positional) arguments too. def Run(*args): return _Run(True, *args) Note that, with only this, you can't call the function with keyword arguments. To support them one need to include the ** as well: def Run(*args, **kwargs): return _Run(True, *args, **kwargs) Actually you could declare the function as def run(cmd, other_stuff, silent=False): ... then it could be called as run("foo", etc) # Run run("foo", etc, silent=True) # RunSilent A: There's also functools.partial: from functools import partial Run = partial(_Run, True) RunSilent = partial(_Run, False) This will create the two functions you want. Requires python 2.5 or higher.
Wrap a function in python supplying an additional boolean
I'm porting some code from Perl to Python, and one of the functions I am moving does the following: sub _Run($verbose, $cmd, $other_stuff...) { ... } sub Run { _Run(1, @_); } sub RunSilent { _Run(0, @_); } so to do it Python, I naively thought I could do the following: def _Run(verbose, cmd, other_stuff...) ... def Run(*args) return _Run(True, args); def RunSilent return _Run(False, args); but that doesn't work, because args is passed as an array/tuple. To make it work, I did the following: def _Run(verbose, cmd, other_stuff...) ... def Run(*args) return _Run(True, ','.join(args)); def RunSilent return _Run(False, ','.join(args)); but that looks kind of ugly. Is there a better way?
[ "The * can be used for passing (positional) arguments too.\ndef Run(*args):\n return _Run(True, *args)\n\nNote that, with only this, you can't call the function with keyword arguments. To support them one need to include the ** as well:\ndef Run(*args, **kwargs):\n return _Run(True, *args, **kwargs)\n\n\nActually...
[ 5, 3 ]
[]
[]
[ "python", "wrapper" ]
stackoverflow_0003602938_python_wrapper.txt
Q: Making python files executable in Ubuntu In windows to make one of my codes execute all I have to do is double click on the file. However, I can't seem to figure out how to do a similar task in Ubuntu. A: Make sure you have #!/usr/bin/env python as the first line of your script, then in your shell do: chmod +x file.py ./file.py A: .pyw files are just .py files that have been renamed so that Windows file associations will launch them with the console-free Python interpreter instead of the regular one. To get run-on-doubleclick working on Ubuntu, first, you need to make sure the kernel sees the script as executable and knows what to do with it. To do that: Use either the Nautilus file properties dialog or the chmod command to mark it executable (chmod +x whatever.pyw) Make sure that the first line in the file says #!/usr/bin/env python (See wikipedia for more info) Make sure the file was saved with Unix-style LF (\n) line-endings rather than DOS/Windows-style CRLF (\r\n) line-endings. (The kernel expects Unix-style line endings for step 2 and, if you forget, it sees the CR (\r) character as part of the path and errors out) You can test whether you've completed these steps properly by running your script in a terminal window. (cd to the directory it's in and run ./your_script.pyw) If it works, then Nautilus should just automatically display an "Edit or run?" dialog when you double-click. However, it's been a while since I've used GNOME, so I can't be sure. If it doesn't, try renaming the file to .py. (I remember Nautilus having a "Extension matches header?" safety check which may not be aware that .pyw is a valid synonym for .py) A: You have to set the permission for the file for it to be executable using chmod. See the manpages for chmod for details.
Making python files executable in Ubuntu
In windows to make one of my codes execute all I have to do is double click on the file. However, I can't seem to figure out how to do a similar task in Ubuntu.
[ "Make sure you have #!/usr/bin/env python as the first line of your script, then in your shell do:\nchmod +x file.py\n./file.py\n\n", ".pyw files are just .py files that have been renamed so that Windows file associations will launch them with the console-free Python interpreter instead of the regular one.\nTo ge...
[ 7, 4, 0 ]
[]
[]
[ "python", "ubuntu", "windows_7" ]
stackoverflow_0003603287_python_ubuntu_windows_7.txt
Q: Why are my forms not returning field errors? Recently I upgraded my django server. Going from 1.2 to a new version. The forms exhibit a strange behavior. When a field is left blank the whole page simply refreshes, rather than showing errors like I remember. What could cause this? What ought I do to fix it? {%extends "baseAUTH.html" %} {% block title %} {{ title }} {% endblock %} {% block content %} {% load adminmedia %} <script type="text/javascript"> window.__admin_media_prefix__ = "{% filter escapejs %}{% admin_media_prefix %}{% endfilter %}"; </script> <script type="text/javascript" src="/admin/jsi18n/"></script> <script type="text/javascript" src="/media/js/core.js"></script> <link rel="stylesheet" type="text/css" href="/media/css/forms.css"/> <link rel="stylesheet" type="text/css" href="/media/css/base.css"/> <link rel="stylesheet" type="text/css" href="/media/css/global.css"/> <link rel="stylesheet" type="text/css" href="/media/css/widgets.css"/> {{ form.media }} <h1>{{ title }}</h1> {% if form.errors %} <p style="color: red;"> Please correct the error{{ form.errors|pluralize }} below. </p> {% endif %} <form action="" method="post" enctype="multipart/form-data"> {% csrf_token %} <table valign=TOP> {{ form.as_table }} </table> <input type="submit" value="Submit"> </form> {% endblock %} A: I found the issue. I reverted some changes back and found the point where I broke it. In the following function I tried to abstract def FormToEmail(request, token, title, subject, message, reciever, attachlist): if request.method == 'POST': sender = AddSender(request) reciever.append(sender) form = token(request.POST, request.FILES) if form.is_valid(): mail = EmailMessage(subject, message, sender, reciever) if len(attachlist) > 0: for item in attachlist: if form.cleaned_data[item]: temp = request.FILES[item] mail.attach(temp.name, temp.read(), \ temp.content_type) return SendIt(request, mail) Here to else: form = token() if request.user.is_authenticated(): return render_to_response('FormTemplate.html', \ {'form': form, 'title' : title}, \ context_instance=RequestContext(request)) else: return HttpResponseRedirect('/Webtemplate/accounts/login') here. Into return RenderFormForAuth(request, token(), title) with the function defined as def RenderFormForAuth(request, form, title): if request.user.is_authenticated(): return render_to_response('FormTemplate.html', \ {'form': form, 'title' : title}, \ context_instance=RequestContext(request)) else: return HttpResponseRedirect('/Webtemplate/accounts/login') which broke everything. (I can paste the whole function/ how it's called if need be, but seems like a waste of space.) Does anyone know why this wouldn't work?
Why are my forms not returning field errors?
Recently I upgraded my django server. Going from 1.2 to a new version. The forms exhibit a strange behavior. When a field is left blank the whole page simply refreshes, rather than showing errors like I remember. What could cause this? What ought I do to fix it? {%extends "baseAUTH.html" %} {% block title %} {{ title }} {% endblock %} {% block content %} {% load adminmedia %} <script type="text/javascript"> window.__admin_media_prefix__ = "{% filter escapejs %}{% admin_media_prefix %}{% endfilter %}"; </script> <script type="text/javascript" src="/admin/jsi18n/"></script> <script type="text/javascript" src="/media/js/core.js"></script> <link rel="stylesheet" type="text/css" href="/media/css/forms.css"/> <link rel="stylesheet" type="text/css" href="/media/css/base.css"/> <link rel="stylesheet" type="text/css" href="/media/css/global.css"/> <link rel="stylesheet" type="text/css" href="/media/css/widgets.css"/> {{ form.media }} <h1>{{ title }}</h1> {% if form.errors %} <p style="color: red;"> Please correct the error{{ form.errors|pluralize }} below. </p> {% endif %} <form action="" method="post" enctype="multipart/form-data"> {% csrf_token %} <table valign=TOP> {{ form.as_table }} </table> <input type="submit" value="Submit"> </form> {% endblock %}
[ "I found the issue. I reverted some changes back and found the point where I broke it. In the following function I tried to abstract\ndef FormToEmail(request, token, title, subject, message, reciever, attachlist):\n\n if request.method == 'POST':\n sender = AddSender(request)\n reciever.append(se...
[ 0 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0003602258_django_django_forms_python.txt
Q: Can python's mechanize use localhost sites? Can Mechanize access sites being locally hosted by Apache? A: Yes. It can use any URL available so long as it is reachable. Just make sure it's properly formatted! A: How about trying it out? Well, seriously, I used twill (a wrapper around mechanize) on localhost, and it worked. It just wants to make a http connection without knowing where it is. Is this the answer you expected?
Can python's mechanize use localhost sites?
Can Mechanize access sites being locally hosted by Apache?
[ "Yes. It can use any URL available so long as it is reachable. Just make sure it's properly formatted!\n", "How about trying it out? Well, seriously, I used twill (a wrapper around mechanize) on localhost, and it worked. It just wants to make a http connection without knowing where it is. Is this the answer you...
[ 0, 0 ]
[]
[]
[ "mechanize", "python" ]
stackoverflow_0003603883_mechanize_python.txt
Q: windows/python manipulate versioninfo during runtime I have multiple python processes running in their console output windows. I can set their console title via win32api.SetConsoleTitle(). Thats nice, but it would be even nicer to set some versioninfo strings (like description/company name/version) during runtime as that would allow me to easier differentiate between the (generic) python proceses in the taskmanager/process-explorer. Has anybody ever done something like that. thnx, dirkse A: Version Information are stored as a resource in the executable. You cannot change them during runtime.
windows/python manipulate versioninfo during runtime
I have multiple python processes running in their console output windows. I can set their console title via win32api.SetConsoleTitle(). Thats nice, but it would be even nicer to set some versioninfo strings (like description/company name/version) during runtime as that would allow me to easier differentiate between the (generic) python proceses in the taskmanager/process-explorer. Has anybody ever done something like that. thnx, dirkse
[ "Version Information are stored as a resource in the executable. You cannot change them during runtime.\n" ]
[ 0 ]
[]
[]
[ "console", "python", "winapi", "windows" ]
stackoverflow_0003542426_console_python_winapi_windows.txt
Q: Regular expression matching anything greater than eight letters in length, in Python Despite attempts to master grep and related GNU software, I haven't come close to mastering regular expressions. I do like them, but I find them a bit of an eyesore all the same. I suppose this question isn't difficult for some, but I've spent hours trying to figure out how to search through my favorite book for words greater than a certain length, and in the end, came up with some really ugly code: twentyfours = [w for w in vocab if re.search('^........................$', w)] twentyfives = [w for w in vocab if re.search('^.........................$', w)] twentysixes = [w for w in vocab if re.search('^..........................$', w)] twentysevens = [w for w in vocab if re.search('^...........................$', w)] twentyeights = [w for w in vocab if re.search('^............................$', w)] ... a line for each length, all the way from a certain length to another one. What I want instead is to be able to say 'give me every word in vocab that's greater than eight letters in length.' How would I do that? A: You don't need regex for this. result = [w for w in vocab if len(w) >= 8] but if regex must be used: rx = re.compile('^.{8,}$') # ^^^^ {8,} means 8 or more. result = [w for w in vocab if rx.match(w)] See http://www.regular-expressions.info/repeat.html for detail on the {a,b} syntax. A: \w will match letter and characters, {min,[max]} allows you to define size. An expression like \w{9,} will give all letter/number combinations of 9 characters or more A: .{9,} for "more than eight", .{8,} for "eight or more" Or just len(w) > 8 A: ^.{8,}$ This will match something that has at least 8 characters. You can also place a number after the coma to limit the upper bound or remove the first number to not restrict the lower bound. A: if you do want to use a regular expression result = [ w for w in vocab if re.search('^.{24}',w) ] the {x} says match x characters. but it is probably better to use len(w)
Regular expression matching anything greater than eight letters in length, in Python
Despite attempts to master grep and related GNU software, I haven't come close to mastering regular expressions. I do like them, but I find them a bit of an eyesore all the same. I suppose this question isn't difficult for some, but I've spent hours trying to figure out how to search through my favorite book for words greater than a certain length, and in the end, came up with some really ugly code: twentyfours = [w for w in vocab if re.search('^........................$', w)] twentyfives = [w for w in vocab if re.search('^.........................$', w)] twentysixes = [w for w in vocab if re.search('^..........................$', w)] twentysevens = [w for w in vocab if re.search('^...........................$', w)] twentyeights = [w for w in vocab if re.search('^............................$', w)] ... a line for each length, all the way from a certain length to another one. What I want instead is to be able to say 'give me every word in vocab that's greater than eight letters in length.' How would I do that?
[ "You don't need regex for this.\nresult = [w for w in vocab if len(w) >= 8]\n\nbut if regex must be used:\nrx = re.compile('^.{8,}$')\n# ^^^^ {8,} means 8 or more.\nresult = [w for w in vocab if rx.match(w)]\n\nSee http://www.regular-expressions.info/repeat.html for detail on the {a,b} syntax.\n", ...
[ 36, 18, 8, 4, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003604105_python_regex.txt
Q: Python: Find out what method on derived class called base class method Hope the title isn't to confusing wasn't sure how I should put it. I wonder if it's possible for the base class to know which method of the derived class called one of it's methods. Example: class Controller(object): def __init__(self): self.output = {} def output(self, s): method_that_called_me = #is it possible? self.output[method_that_called_me] = s class Public(Controller): def about_us(self): self.output('Damn good coffee!') def contact(self): self.output('contact me') So is it possible for the output method to know which method from the Public class called it? A: There is a somewhat magical way to do what you are looking for using introspection on the call stack. But that isn't portable since not all implementations of Python have the necessary functions. It's probably not a good design decision to use introspection either. Better, I think, to be explicit: class Controller(object): def __init__(self): self._output = {} def output(self, s, caller): method_that_called_me = caller.__name__ self._output[method_that_called_me] = s class Public(Controller): def about_us(self): self.output('Damn good coffee!',self.about_us) def contact(self): self.output('contact me',self.contact) PS. Note that you have self.output as both a dict and a method. I've altered it so self._output is a dict, and self.output is the method. PPS. Just to show you what I was referring to by magical introspection: import traceback class Controller(object): def output_method(self, s): (filename,line_number,function_name,text)=traceback.extract_stack()[-2] method_that_called_me = function_name self.output[method_that_called_me] = s A: Have a look at the inspect module. import inspect frame = inspect.currentframe() method_that_called_me = inspect.getouterframes(frame)[1][3] where method_that_called_me will be a string. The 1 is for the direct caller, the 3 the position of the function name in the 'frame record'
Python: Find out what method on derived class called base class method
Hope the title isn't to confusing wasn't sure how I should put it. I wonder if it's possible for the base class to know which method of the derived class called one of it's methods. Example: class Controller(object): def __init__(self): self.output = {} def output(self, s): method_that_called_me = #is it possible? self.output[method_that_called_me] = s class Public(Controller): def about_us(self): self.output('Damn good coffee!') def contact(self): self.output('contact me') So is it possible for the output method to know which method from the Public class called it?
[ "There is a somewhat magical way to do what you are looking for using introspection on the call stack. But that isn't portable since not all implementations of Python have the necessary functions. It's probably not a good design decision to use introspection either. \nBetter, I think, to be explicit:\nclass Control...
[ 4, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003604206_python.txt
Q: "None not in" vs "not None in" Unless I'm crazy if None not in x and if not None in x are equivalent. Is there a preferred version? I guess None not in is more english-y and therefore more pythonic, but not None in is more like other language syntax. Is there a preferred version? A: They compile to the same bytecode, so yes they are equivalent. >>> import dis >>> dis.dis(lambda: None not in x) 1 0 LOAD_CONST 0 (None) 3 LOAD_GLOBAL 1 (x) 6 COMPARE_OP 7 (not in) 9 RETURN_VALUE >>> dis.dis(lambda: not None in x) 1 0 LOAD_CONST 0 (None) 3 LOAD_GLOBAL 1 (x) 6 COMPARE_OP 7 (not in) 9 RETURN_VALUE The documentation also makes it clear that the two are equivalent: x not in s returns the negation of x in s. As you mention None not in x is more natural English so I prefer to use this. If you write not y in x it might be unclear whether you meant not (y in x) or (not y) in x. There is no ambiguity if you use not in. A: The expression not (None in x) (parens added for clarity) is an ordinary boolean negation. However, None not in x is special syntax added for more readable code (there's no possibility here, nor does it make sense, to use and, or, etc in front of the in). If this special case was added, use it. Same applies to foo is not None vs. not foo is None I find the "is not" much clearer to read. As an additional bonus, if the expression is part of a larger boolean expression, the scope of the not is immediately clear.
"None not in" vs "not None in"
Unless I'm crazy if None not in x and if not None in x are equivalent. Is there a preferred version? I guess None not in is more english-y and therefore more pythonic, but not None in is more like other language syntax. Is there a preferred version?
[ "They compile to the same bytecode, so yes they are equivalent.\n>>> import dis\n>>> dis.dis(lambda: None not in x)\n 1 0 LOAD_CONST 0 (None)\n 3 LOAD_GLOBAL 1 (x)\n 6 COMPARE_OP 7 (not in)\n 9 RETURN_VALUE\n>>> dis.dis(lambd...
[ 14, 7 ]
[]
[]
[ "logic", "python", "syntax" ]
stackoverflow_0003604222_logic_python_syntax.txt
Q: Are there an GUI libraries for Python that allow you to compile to an EXE (windows) and APP(Mac)? I'm working on an application that I need to be cross-platform. I'd like to use Python for it, and am looking for GUI toolkits that make interface programming simple and easy. After a slight hunt, I found PythonCard. This looks like it fits the bill perfectly, but I'm not sure if it will be possible to compile this down to an appropriate executable for each operating system. I found these instructions, but they're 6 years old. Whatever solution I choose must support the following: Write one GUI to work on both Windows and Mac OSX Must 'compile' into an easily distributable file for both windows/mac Compiled file must not require Python to be installed on the users computer Can anyone recommend a library/solution before I have to wade into the desolate world of Java? A: Use PyInstaller to distribute an app using PyQt or WxPython gui toolkits. From the website: PyInstaller is a program that converts (packages) Python programs into stand-alone executables, under Windows, Linux, and Mac OS X. As for gui toolkits, PyInstaller is documented to work with Qt3, Qt4, and WxPython. StackOverflow contributor dF, uses PyInstaller "for an app which depends on PyQt, PyQwt, numpy, scipy and a few more." A: I think the answer here is less about the particular GUI toolkit and more about distributing stand-alone python applications. Personally, I've found the tools for this a little less perfect than I'd like but, after some finagling, they get the job done. The most likely candidate that'd fit your needs is cx_Freeze. Though there's a Windows specific py2exe and Mac specific py2app that might fill the bill if cx_Freeze is insufficient. A: Hmm. Maybe it'd better to move my post to comments, but. Why do you want to 'compile' python code, and why do you think that some GUI framework should provide some packaging/installation facilities? In our company we wrote cross-platform GUI app and of course we must make it easily deliverable for customers. So, we found suitable GUI framework with python bindings (Qt), then we chosen the method to hide unneeded details about realisation and vanish dependancies (Py2Exe for Windows, Py2App for Mac, and nothing for linux, but you can try PyInstaller or cx-freeze). Installation for every OS made in that OS' way, according to the least astonishment principle. That's why we did not pack linux version in some kind of binary executables. A: If you want your application to look and feel native, then wxPython is the way to go. PyQt can look native, but it doesn't sound like it always behaves in a native way (according to some threads I've read). To build binaries, use py2exe or some such for Windows and py2app for Mac A: This presentation walks through the process and also winds up with Py2exe and Py2app... A: For Wxpython GUI designers check this question. I breifly tried boa-contstructor but I found it too limiting -as not all widgets are supported. AFAIK none of the wxpython designers support all widgets (out of the box atleast). I personally find it faster and easier to hand code my GUI's. Id say it only took me a few days to become reasonably comfortable/familar wxpython. If you need to do anything other then creating a simple application then taking a little bit of time to learn wxpython will pay its dividends. If your bound to the idea of having a descent GUI designer then your best bet is probabaly PyQt as this IMHO is the only toolkit that has a solid mature editor -Qt Designer As for creating standalone excutables Ive only used py2exe for windows. py2app does the same for mac although I have not tried that yet. For windows installers checkout this thread
Are there an GUI libraries for Python that allow you to compile to an EXE (windows) and APP(Mac)?
I'm working on an application that I need to be cross-platform. I'd like to use Python for it, and am looking for GUI toolkits that make interface programming simple and easy. After a slight hunt, I found PythonCard. This looks like it fits the bill perfectly, but I'm not sure if it will be possible to compile this down to an appropriate executable for each operating system. I found these instructions, but they're 6 years old. Whatever solution I choose must support the following: Write one GUI to work on both Windows and Mac OSX Must 'compile' into an easily distributable file for both windows/mac Compiled file must not require Python to be installed on the users computer Can anyone recommend a library/solution before I have to wade into the desolate world of Java?
[ "Use PyInstaller to distribute an app using PyQt or WxPython gui toolkits. From the website:\n\nPyInstaller is a program that converts (packages) Python programs into stand-alone executables, under Windows, Linux, and Mac OS X.\n\nAs for gui toolkits, PyInstaller is documented to work with Qt3, Qt4, and WxPython.\...
[ 4, 4, 0, 0, 0, 0 ]
[]
[]
[ "distribution", "python", "user_interface" ]
stackoverflow_0003604113_distribution_python_user_interface.txt
Q: if you don't use scaffolding, is ruby on rails still good for rapid development? If you take out the scaffolding feature where it creates the model/controller, and CRUD pages for you, is ruby on rails still any faster to market than say, django? It seems very similiar to be if you take away that step...(even though I believe django has similar auto-gen capabilities) I am reading the starting guide on the rails site, and when it introduces the scaffolding feature, it says that many people prefer to hand code these types of areas. A: I have never seen Rails scaffold-generated view code used in a production app. The chances that it's going to create the look that you want is nearly zero. I use the generators for models and controllers all the time, as they are very useful. To your question of frameworks: If you know Python better, use Django. If you know Ruby better, use Rails. If this is a hobby site, use whichever one interests you the most. A: The default scaffolding is generally only useful as a starting point, and doesn't provide too much of a leg up on a real app. If you want something Rails-based that provides better scaffolding, check out Hobo or ActiveScaffold -- both provide scaffold-style functionality, but take it a lot further than Rails does by default. As far as Rails vs. Django, they provide pretty similar functionality, though Django has built-in account management. Which one you use should be more a matter of language preference than anything else. A: Scaffolding is just a demo and learning feature. It's not intended for use in real site development. It's certainly not Rails' primary strength.
if you don't use scaffolding, is ruby on rails still good for rapid development?
If you take out the scaffolding feature where it creates the model/controller, and CRUD pages for you, is ruby on rails still any faster to market than say, django? It seems very similiar to be if you take away that step...(even though I believe django has similar auto-gen capabilities) I am reading the starting guide on the rails site, and when it introduces the scaffolding feature, it says that many people prefer to hand code these types of areas.
[ "I have never seen Rails scaffold-generated view code used in a production app. The chances that it's going to create the look that you want is nearly zero. I use the generators for models and controllers all the time, as they are very useful.\nTo your question of frameworks:\nIf you know Python better, use Django....
[ 4, 2, 1 ]
[]
[]
[ "django", "python", "ruby_on_rails" ]
stackoverflow_0003604205_django_python_ruby_on_rails.txt
Q: How can I randomize this text generator even further? I'm working on a random text generator -without using Markov chains- and currently it works without too many problems -actually generates a good amount of random sentences by my criteria but I want to make it even more accurate to prevent as many sentence repeats as possible-. Firstly, here is my code flow: Enter a sentence as input -this is called trigger string, is assigned to a variable- Get longest word in trigger string Search all Project Gutenberg database for sentences that contain this word -regardless of uppercase lowercase- Return the longest sentence that has the word I spoke about in step 3 Append the sentence in Step 1 and Step4 together Assign the sentence in Step 4 as the new 'trigger' sentence and repeat the process. Note that I have to get the longest word in second sentence and continue like that and so on- And here is my code: import nltk from nltk.corpus import gutenberg from random import choice import smtplib #will be for send e-mail option later triggerSentence = raw_input("Please enter the trigger sentence: ")#get input str longestLength = 0 longestString = "" longestLen2 = 0 longestStr2 = "" listOfSents = gutenberg.sents() #all sentences of gutenberg are assigned -list of list format- listOfWords = gutenberg.words()# all words in gutenberg books -list format- while triggerSentence:#run the loop so long as there is a trigger sentence sets = [] sets2 = [] split_str = triggerSentence.split()#split the sentence into words #code to find the longest word in the trigger sentence input for piece in split_str: if len(piece) > longestLength: longestString = piece longestLength = len(piece) #code to get the sentences containing the longest word, then selecting #random one of these sentences that are longer than 40 characters for sentence in listOfSents: if sentence.count(longestString): sents= " ".join(sentence) if len(sents) > 40: sets.append(" ".join(sentence)) triggerSentence = choice(sets) print triggerSentence #the first sentence that comes up after I enter input- split_str = triggerSentence.split() for apiece in triggerSentence: #find the longest word in this new sentence if len(apiece) > longestLen2: longestStr2 = piece longestLen2 = len(apiece) if longestStr2 == longestString: second_longest = sorted(split_str, key=len)[-2]#this should return the second longest word in the sentence in case it's longest word is as same as the longest word of last sentence #print second_longest #now get second longest word if first is same #as longest word in previous sentence for sentence in listOfSents: if sentence.count(second_longest): sents = " ".join(sentence) if len(sents) > 40: sets2.append(" ".join(sentence)) triggerSentence = choice(sets2) else: for sentence in listOfSents: if sentence.count(longestStr2): sents = " ".join(sentence) if len(sents) > 40: sets.append(" ".join(sentence)) triggerSentence = choice(sets) print triggerSentence According to my code, once I enter a trigger sentence, I should get another one that contains the longest word of the trigger sentence I entered. Then this new sentence becomes the trigger sentence and it's longest word is picked. This is where the problem sometimes occurs. I observed that despite the code lines I placed - starting from line 47 to the end- , the algorithm still can pick the same longest word in the sentences that come along, not looking for the second longest word. For example: Trigger string = "Scotland is a nice place." Sentence 1 = -This is a random sentence with the word Scotland in it- Now, this is where the problem can occur in my code at times -doesn't matter whether it comes up in sentence 2 or 942 or zillion or whatever, but I give it in sent.2 for example's sake- Sentence 2 = Another sentence that has the word Scotland in it but not the second longest word in sentence 1. According to my code, this sentence should have been some sentence that contained the second longest word in sentence 1, not Scotland ! How can I solve this ? I'm trying to optimize the code as much as possible and any help is welcome. A: There is nothing random about your algorithm at all. It should always be deterministic. I'm not quite sure what you want to do here. If it is to generate random words, just use a dictionary and the random module. If you want to grab random sentences from the Gutenberg project, use the random module to pick a work and then a sentence out of that work.
How can I randomize this text generator even further?
I'm working on a random text generator -without using Markov chains- and currently it works without too many problems -actually generates a good amount of random sentences by my criteria but I want to make it even more accurate to prevent as many sentence repeats as possible-. Firstly, here is my code flow: Enter a sentence as input -this is called trigger string, is assigned to a variable- Get longest word in trigger string Search all Project Gutenberg database for sentences that contain this word -regardless of uppercase lowercase- Return the longest sentence that has the word I spoke about in step 3 Append the sentence in Step 1 and Step4 together Assign the sentence in Step 4 as the new 'trigger' sentence and repeat the process. Note that I have to get the longest word in second sentence and continue like that and so on- And here is my code: import nltk from nltk.corpus import gutenberg from random import choice import smtplib #will be for send e-mail option later triggerSentence = raw_input("Please enter the trigger sentence: ")#get input str longestLength = 0 longestString = "" longestLen2 = 0 longestStr2 = "" listOfSents = gutenberg.sents() #all sentences of gutenberg are assigned -list of list format- listOfWords = gutenberg.words()# all words in gutenberg books -list format- while triggerSentence:#run the loop so long as there is a trigger sentence sets = [] sets2 = [] split_str = triggerSentence.split()#split the sentence into words #code to find the longest word in the trigger sentence input for piece in split_str: if len(piece) > longestLength: longestString = piece longestLength = len(piece) #code to get the sentences containing the longest word, then selecting #random one of these sentences that are longer than 40 characters for sentence in listOfSents: if sentence.count(longestString): sents= " ".join(sentence) if len(sents) > 40: sets.append(" ".join(sentence)) triggerSentence = choice(sets) print triggerSentence #the first sentence that comes up after I enter input- split_str = triggerSentence.split() for apiece in triggerSentence: #find the longest word in this new sentence if len(apiece) > longestLen2: longestStr2 = piece longestLen2 = len(apiece) if longestStr2 == longestString: second_longest = sorted(split_str, key=len)[-2]#this should return the second longest word in the sentence in case it's longest word is as same as the longest word of last sentence #print second_longest #now get second longest word if first is same #as longest word in previous sentence for sentence in listOfSents: if sentence.count(second_longest): sents = " ".join(sentence) if len(sents) > 40: sets2.append(" ".join(sentence)) triggerSentence = choice(sets2) else: for sentence in listOfSents: if sentence.count(longestStr2): sents = " ".join(sentence) if len(sents) > 40: sets.append(" ".join(sentence)) triggerSentence = choice(sets) print triggerSentence According to my code, once I enter a trigger sentence, I should get another one that contains the longest word of the trigger sentence I entered. Then this new sentence becomes the trigger sentence and it's longest word is picked. This is where the problem sometimes occurs. I observed that despite the code lines I placed - starting from line 47 to the end- , the algorithm still can pick the same longest word in the sentences that come along, not looking for the second longest word. For example: Trigger string = "Scotland is a nice place." Sentence 1 = -This is a random sentence with the word Scotland in it- Now, this is where the problem can occur in my code at times -doesn't matter whether it comes up in sentence 2 or 942 or zillion or whatever, but I give it in sent.2 for example's sake- Sentence 2 = Another sentence that has the word Scotland in it but not the second longest word in sentence 1. According to my code, this sentence should have been some sentence that contained the second longest word in sentence 1, not Scotland ! How can I solve this ? I'm trying to optimize the code as much as possible and any help is welcome.
[ "There is nothing random about your algorithm at all. It should always be deterministic.\nI'm not quite sure what you want to do here. If it is to generate random words, just use a dictionary and the random module. If you want to grab random sentences from the Gutenberg project, use the random module to pick a wor...
[ 0 ]
[]
[]
[ "nltk", "python", "text" ]
stackoverflow_0003596744_nltk_python_text.txt
Q: Python ConfigParser persist configuration to file I have a configuration file (feedbar.cfg), having the following content: [last_session] last_position_x=10 last_position_y=10 After I run the following python script: #!/usr/bin/env python import pygtk import gtk import ConfigParser import os pygtk.require('2.0') class FeedbarConfig(): """ Configuration class for Feedbar. Used to persist / read data from feedbar's cfg file """ def __init__(self, cfg_file_name="feedbar.cfg"): self.cfg_file_name = cfg_file_name self.cfg_parser = ConfigParser.ConfigParser() self.cfg_parser.readfp(open(cfg_file_name)) def update_file(self): with open(cfg_file_name,"wb") as cfg_file: self.cfg_parser.write(cfg_file) #PROPERTIES def get_last_position_x(self): return self.cfg_parser.getint("last_session", "last_position_x") def set_last_position_x(self, new_x): self.cfg_parser.set("last_session", "last_position_x", new_x) self.update_file() last_position_x = property(get_last_position_x, set_last_position_x) if __name__ == "__main__": #feedbar = FeedbarWindow() #feedbar.main() config = FeedbarConfig() print config.last_position_x config.last_position_x = 5 print config.last_position_x The output is: 10 5 But the file is not updated. The cfg file contents remain the same. Any suggestions ? Is there another way to bind config information from a file into a python class ? Something like JAXB in Java (but not for XML, just .ini files). Thanks! A: Edit2: The reason why your code is not working is because FeedbarConfig must inherit from object to be a new-style class. Properties do not work with classic classes.: So the solution is to use class FeedbarConfig(object) Edit: Does JAXB read XML files and convert them to objects? If so, you may want to look at lxml.objectify. This would give you an easy way to read and save your configuration as XML. Is there another way to bind config information from a file into a python class ? Yes. You could use shelve, marshal, or pickle to save Python objects (e.g. a list, or dict). Last time I tried to use ConfigParser, I ran into some problems: ConfigParser does not handle multi-line values well. You have to put whitespace on subsequent lines, and once parsed, the whitespace is removed. So all your multi-line strings get converted into one long string anyway. ConfigParser downcases all option names. There is no way to guarantee the order in which the options are written to file. Although, these are not the issue that you currently face, and although saving the file may be easy to fix, you may want to consider using one of the other modules to avoid future problems. A: [I would put this in a comment, but I'm not permitted to comment at this time] As an aside, you may want to use decorator-style properties, they make things look better, at least in my opinion: #PROPERTIES @property def position_x(self): return self.cfg_parser.getint("last_session", "last_position_x") @position_x.setter def position_x(self, new_x): self.cfg_parser.set("last_session", "last_position_x", new_x) self.update_file() Also, according to python docs, SafeConfigParser is the way to go for new applications: "New applications should prefer this version if they don’t need to be compatible with older versions of Python." -- http://docs.python.org/library/configparser.html
Python ConfigParser persist configuration to file
I have a configuration file (feedbar.cfg), having the following content: [last_session] last_position_x=10 last_position_y=10 After I run the following python script: #!/usr/bin/env python import pygtk import gtk import ConfigParser import os pygtk.require('2.0') class FeedbarConfig(): """ Configuration class for Feedbar. Used to persist / read data from feedbar's cfg file """ def __init__(self, cfg_file_name="feedbar.cfg"): self.cfg_file_name = cfg_file_name self.cfg_parser = ConfigParser.ConfigParser() self.cfg_parser.readfp(open(cfg_file_name)) def update_file(self): with open(cfg_file_name,"wb") as cfg_file: self.cfg_parser.write(cfg_file) #PROPERTIES def get_last_position_x(self): return self.cfg_parser.getint("last_session", "last_position_x") def set_last_position_x(self, new_x): self.cfg_parser.set("last_session", "last_position_x", new_x) self.update_file() last_position_x = property(get_last_position_x, set_last_position_x) if __name__ == "__main__": #feedbar = FeedbarWindow() #feedbar.main() config = FeedbarConfig() print config.last_position_x config.last_position_x = 5 print config.last_position_x The output is: 10 5 But the file is not updated. The cfg file contents remain the same. Any suggestions ? Is there another way to bind config information from a file into a python class ? Something like JAXB in Java (but not for XML, just .ini files). Thanks!
[ "Edit2: The reason why your code is not working is because FeedbarConfig must inherit from object to be a new-style class. Properties do not work with classic classes.:\nSo the solution is to use\nclass FeedbarConfig(object)\n\n\nEdit: Does JAXB read XML files and convert them to objects? If so, you may want to loo...
[ 3, 2 ]
[]
[]
[ "configparser", "python" ]
stackoverflow_0003604254_configparser_python.txt
Q: Calling a Perl module from Python my question is the inverse of this one. In particular, I've dozens of existing modules written in Perl, some are object oriented and others just export a group of functions. Now since I have to write certain scripts in python but still would like to call those Perl modules, I'm wondering 1) if it is achievable, and 2) if so, what would be the best way of doing it Ideally, the Perl modules would appear as "black boxes" to Python, so to speak. Something like: from perl_module import * return_value = perl_func(arg1, arg2, ...) and object = perl_module.new() object.method1(arg1, arg2, ...) but I'm sure to achieve this one needs to have something else imported / running at the background, if possible at all. Anything that is the counterpart to the Inline::Python would also be nice (but not ideal). Thx! A: http://wiki.python.org/moin/PyPerl http://www.boriel.com/files/perlfunc.py
Calling a Perl module from Python
my question is the inverse of this one. In particular, I've dozens of existing modules written in Perl, some are object oriented and others just export a group of functions. Now since I have to write certain scripts in python but still would like to call those Perl modules, I'm wondering 1) if it is achievable, and 2) if so, what would be the best way of doing it Ideally, the Perl modules would appear as "black boxes" to Python, so to speak. Something like: from perl_module import * return_value = perl_func(arg1, arg2, ...) and object = perl_module.new() object.method1(arg1, arg2, ...) but I'm sure to achieve this one needs to have something else imported / running at the background, if possible at all. Anything that is the counterpart to the Inline::Python would also be nice (but not ideal). Thx!
[ "\nhttp://wiki.python.org/moin/PyPerl\nhttp://www.boriel.com/files/perlfunc.py\n\n" ]
[ 6 ]
[]
[]
[ "call", "module", "perl", "python" ]
stackoverflow_0003604388_call_module_perl_python.txt
Q: Making __import__ get the dynamically added methods At my work place there is a script (kind of automation system) that loads and runs our application tests from an XML file. In the middle of the process the script calls __import__(testModule) which loads the module from its file. The problem starts when I tried adding a feature by dynamically adding functions to the testModule at runtime. As expected, the __import__ gets the old version of the module which doesn't have the methods I just added at runtime. Is it possible to make the __import__ calls import the newer version of the class (which includes the methods I added)? Please note that I prefer keeping the automation system untouched (even when it would help solving the problem faster). Thanks Tal. A: You need to be aware that reloading a module won't magically replace old instances. Even if you do reload, only new objects will use the new code! The only way to replace code during runtime is to wrap everything in a proxy object! You can sometimes do this, ie for specific, self-contained modules, but in most cases it's simply not a reasonable approach. Quick demonstration: >>> import asd >>> asd.s 'old' >>> t = asd.s >>> reload(asd) # I edited asd.py before <module 'asd' from 'asd.py'> >>> asd.s # new module content 'new' >>> t # but this is still old! 'old' Most applications that looks like it reloads code actually just restart! A: reload(testmodule) might work.
Making __import__ get the dynamically added methods
At my work place there is a script (kind of automation system) that loads and runs our application tests from an XML file. In the middle of the process the script calls __import__(testModule) which loads the module from its file. The problem starts when I tried adding a feature by dynamically adding functions to the testModule at runtime. As expected, the __import__ gets the old version of the module which doesn't have the methods I just added at runtime. Is it possible to make the __import__ calls import the newer version of the class (which includes the methods I added)? Please note that I prefer keeping the automation system untouched (even when it would help solving the problem faster). Thanks Tal.
[ "You need to be aware that reloading a module won't magically replace old instances. Even if you do reload, only new objects will use the new code! \nThe only way to replace code during runtime is to wrap everything in a proxy object! You can sometimes do this, ie for specific, self-contained modules, but in most c...
[ 2, 1 ]
[]
[]
[ "metaprogramming", "python" ]
stackoverflow_0003604611_metaprogramming_python.txt
Q: Python/Numpy error: NULL result without error in PyObject_Call I've never seen this error before, and none of the hits on Google seem to apply. I've got a very large NumPy array that holds Boolean values. When I try writing the array using numpy.dump(), I get the following error: SystemError: NULL result without error in PyObject_Call The array is initialized with all False values, and the only time I ever access it is to set some of the values to True, so I have no idea why any of the values would be null. When I try running the same program with a smaller array, I get no error. However, since the error occurs at the writing step, I don't think that it's a memory issue. Has anybody else seen this error before? A: That message comes directly from the CPython interpreter (see abstract.c method PyObject_Call). You may get a better response on a Python or NumPy mailing list regarding that error message because it looks like a problem in C code. Write a simple example to demonstrating the problem and you should be able to narrow the issue down to a module then a method. A: It appears that this may have been an error from using the 32-bit version of NumPy and not the 64 bit. For whatever reason, though the program has no problem keeping the array in memory, it trips up when writing the array to a file if the number of elements in the array is greater than 2^32.
Python/Numpy error: NULL result without error in PyObject_Call
I've never seen this error before, and none of the hits on Google seem to apply. I've got a very large NumPy array that holds Boolean values. When I try writing the array using numpy.dump(), I get the following error: SystemError: NULL result without error in PyObject_Call The array is initialized with all False values, and the only time I ever access it is to set some of the values to True, so I have no idea why any of the values would be null. When I try running the same program with a smaller array, I get no error. However, since the error occurs at the writing step, I don't think that it's a memory issue. Has anybody else seen this error before?
[ "That message comes directly from the CPython interpreter (see abstract.c method PyObject_Call). You may get a better response on a Python or NumPy mailing list regarding that error message because it looks like a problem in C code. \nWrite a simple example to demonstrating the problem and you should be able to nar...
[ 1, 1 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0003576430_numpy_python.txt
Q: x or y: acceptable idiom, or obfuscation? I have to extract values from a variable that may be None, with some defaults in mind. I first wrote this code: if self.maxTiles is None: maxX, maxY = 2, 2 else: maxX, maxY = self.maxTiles Then I realized I could shorten it to: maxX, maxY = self.maxTiles if self.maxTiles is not None else (2, 2) But then I realized this might be the most succinct and easily readable: maxX, maxY = self.maxTiles or (2, 2) Is the latter acceptable, or too hackish? A: About, specifically, self.maxTiles if self.maxTiles is not None else (2, 2) I've found that "double negatives" of the general form if not A: B else: C (whether as statements or expressions) can be quite confusing / misleading; this isn't literally an if not .. else, but moving the not doesn't make the "double negative" go away. So, in general, I just rewrite such constructs to if A: C else: B. In this particular case, if I did choose the ternary-operator form, I'd code it as (2, 2) if self.maxTiles is None else self.maxTiles On to the more general question: a = b or c is fine if and only if you really want to use c for any false value of b -- it's not fine to deal specifically with b being None. IOW, b or c is a better way to express b if b else c but it's not a way to express a similar expression where the core test is, instead, b is None. In theory, if you "know" that the only possible false value for b is None, they're semantically equivalent, but that strong "only possible false value" constraint will not be apparent to readers / maintainers of your code -- and if you have to add a comment to explain that, any conciseness advantages that or might claim are nullified... better, when feasible, to "say it in code", rather than have the code be obscure and need comments to clarify exactly what it's doing and when (comments that are really useful are rather those which explain, not the what and the when [[the code itself should show that!-)]], but rather the why when it's not obvious -- what's the application purpose being served by this specific tidbit of code functionality). A: Along with the answer of gddc ( of the problems of assuming maxTiles is a tuple), I would probably do the second option, but add parenthesis for clarity: maxX, maxY = (self.maxTiles) if (self.maxTiles is not None) else (2, 2) A: If you're doing this at the beginning of a function, I'd use the longer form as it's more idiomatic and instantly recognizable. Yeah, it's more lines, but you barely save any characters, and short lines that fit into 79 character lines = good. Plus if you ever have to adjust the logic or add more steps you'd likely revert to the long form anyways. A: I avoid the y if x else z syntax when I can. It's inherently an ugly, unintuitive syntax, and one of the bigger mistakes in Python's design. It's an out-of-order expression: x is evaluated before y. It's unintuitive; it's naturally read as "if x then y, else z". C's syntax gives us a decades-established, universally-understood order for this: x? y:z. Python got this one very wrong. That said, ternary syntax is the wrong mechanism for supplying a default anyway. In self.maxTiles if self.maxTiles is not None else (2, 2), note the redundancy: you have to specify self.maxTiles twice. That's repetitive, so it takes more work to read the code. I have to read it twice to be sure it doesn't say, for example, self.minTiles if self.maxTiles is not None else (2, 2). self.maxTiles or (0,2) avoids these problems; it's perfectly clear at a glance. One caveat: if self.maxTiles is () or 0 or some other false value, the result is different. This is probably acceptable based on what you seem to be doing, but keep this in mind. It's an issue when providing a default for a boolean or an integer, and you really do need the is None test. For those I prefer a simple conditional, but will sometimes fall back on a ternary expression. Edit; a clearer way of writing the conditional version is: if self.maxTiles is None: maxX, maxY = 2, 2 else: maxX, maxY = self.maxTiles A: You code is perfectly acceptable idiom. In fact I find it more readable than the first two. My only consideration is you are doing two things in one line, to supply a default and to unpack them into x,y. It maybe more clear if you separate them into two. maxTiles = self.maxTiles or (2, 2) maxX, maxY = maxTiles This also deflect the criticism of g.d.d.c, although it is not really a serious one. A: I don't like using or and and as replacements for a ternary operator in Python. I've run into problems like a 0 value being treated as "false" too many times, when I only intended to check for None. I consider it much better to be explicit, even if its more verbose, so your second example is best: maxX, maxY = self.maxTiles if self.maxTiles is not None else (2, 2)
x or y: acceptable idiom, or obfuscation?
I have to extract values from a variable that may be None, with some defaults in mind. I first wrote this code: if self.maxTiles is None: maxX, maxY = 2, 2 else: maxX, maxY = self.maxTiles Then I realized I could shorten it to: maxX, maxY = self.maxTiles if self.maxTiles is not None else (2, 2) But then I realized this might be the most succinct and easily readable: maxX, maxY = self.maxTiles or (2, 2) Is the latter acceptable, or too hackish?
[ "About, specifically,\nself.maxTiles if self.maxTiles is not None else (2, 2)\n\nI've found that \"double negatives\" of the general form if not A: B else: C (whether as statements or expressions) can be quite confusing / misleading; this isn't literally an if not .. else, but moving the not doesn't make the \"doub...
[ 6, 4, 4, 3, 1, 0 ]
[]
[]
[ "coding_style", "idioms", "obfuscation", "python" ]
stackoverflow_0003604726_coding_style_idioms_obfuscation_python.txt
Q: How do I modify a dict locally as to not effect the global variable in python How do I create a dictionary in python that is passed to a function so it would look like this: def foobar(dict): dict = tempdict # I want tempdict to not point to dict, but to be a different dict #logic that modifies tempdict return tempdict How do I do this? A: You need to copy dict to tempdict. def foobar(d): temp = d.copy() # your logic goes here return temp copy makes a shallow copy of the dict (i.e. copying its values, but not its values' values). % python Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> d = {'x': 17, 'y': 23} >>> t = d.copy() >>> t {'y': 23, 'x': 17} >>> t['x'] = 93 >>> t {'y': 23, 'x': 93} >>> d {'y': 23, 'x': 17} >>>
How do I modify a dict locally as to not effect the global variable in python
How do I create a dictionary in python that is passed to a function so it would look like this: def foobar(dict): dict = tempdict # I want tempdict to not point to dict, but to be a different dict #logic that modifies tempdict return tempdict How do I do this?
[ "You need to copy dict to tempdict.\ndef foobar(d):\n temp = d.copy()\n # your logic goes here\n return temp\n\ncopy makes a shallow copy of the dict (i.e. copying its values, but not its values' values).\n% python\nPython 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) \n[GCC 4.4.3] on linux2\nType \"help\", \"...
[ 4 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0003605075_dictionary_python.txt
Q: Python PyGTK. What's this component? I'm trying to write a simple GTD-style todo list app with python and gtk to learn python. I want a container that can select an individual list from a lot of choices. It would be something like the list of notebooks area in tomboy. Not a combobox. As you can probably tell I'm a beginner and the terminology is probably off. Can you please tell me what it is I'm looking for and an overview of how to implement it? A: It sounds like you just want a listbox, unless you're describing something more complex than I'm picturing. Wikipedia has a list of GUI widgets that you may find informative. A: You mean a widget to filter a large collection into multiple subsets / views? I would guess you have to implement this yourself - a list of options on the left and filtered results on the right, I don't know of any existing (gtk) widgets. A: The 'Notebooks' button in Tomboy is a gtk.MenuToolItem with a gtk.Menu containing gtk.RadioMenuItems. Here is a short example: import gtk window = gtk.Window() box = gtk.VBox() toolbar = gtk.Toolbar() toolbutton = gtk.MenuToolButton(gtk.STOCK_FLOPPY) menu = gtk.Menu() labels = ['Disk 1', 'Disk 2', 'Disk 3'] items = [gtk.RadioMenuItem(label=l) for l in labels] window.set_default_size(300, 300) window.add(box) box.pack_start(toolbar, expand=False, fill=True) toolbar.insert(toolbutton, 0) toolbutton.set_menu(menu) for item in items: if item is not items[0]: item.set_group(items[0]) item.show() menu.append(item) window.show_all() window.connect('destroy', gtk.main_quit) gtk.main()
Python PyGTK. What's this component?
I'm trying to write a simple GTD-style todo list app with python and gtk to learn python. I want a container that can select an individual list from a lot of choices. It would be something like the list of notebooks area in tomboy. Not a combobox. As you can probably tell I'm a beginner and the terminology is probably off. Can you please tell me what it is I'm looking for and an overview of how to implement it?
[ "It sounds like you just want a listbox, unless you're describing something more complex than I'm picturing.\nWikipedia has a list of GUI widgets that you may find informative.\n", "You mean a widget to filter a large collection into multiple subsets / views? \nI would guess you have to implement this yourself - ...
[ 1, 0, 0 ]
[]
[]
[ "gtk", "python", "user_interface" ]
stackoverflow_0003604357_gtk_python_user_interface.txt
Q: google-app-engine-django loading fixtures I'm having troubles loading fixtures on GAE with google-app-engine-django. I receive an error that says "DeserializationError: Invalid model identifier: 'fcl.User'" ./manage.py loaddata users I'm trying to load a fixture that has the following data: - model: fcl.User fields: firstname: test lastname: testerson email: test@example.com user_id: '981167207188616462253' status: active usertype: player creationtime: '2010-08-29 00:00:00' do I need to do any other qualifying of my model name? The fixture lives at fcl/fixtures/users.yaml and model lives in at 'fcl/models.py'. Any help would be greatly appreciated. A: Turns out the issue was caused because I wasn't declaring my model correctly in models.py When using google-app-engine-django, each model should be a subclass of: appengine_django.db.BaseModel after fixing this, it works. I also needed to put a valid pk: value in my fixture.
google-app-engine-django loading fixtures
I'm having troubles loading fixtures on GAE with google-app-engine-django. I receive an error that says "DeserializationError: Invalid model identifier: 'fcl.User'" ./manage.py loaddata users I'm trying to load a fixture that has the following data: - model: fcl.User fields: firstname: test lastname: testerson email: test@example.com user_id: '981167207188616462253' status: active usertype: player creationtime: '2010-08-29 00:00:00' do I need to do any other qualifying of my model name? The fixture lives at fcl/fixtures/users.yaml and model lives in at 'fcl/models.py'. Any help would be greatly appreciated.
[ "Turns out the issue was caused because I wasn't declaring my model correctly in models.py\nWhen using google-app-engine-django, each model should be a subclass of:\n\nappengine_django.db.BaseModel\n\nafter fixing this, it works. I also needed to put a valid pk: value in my fixture.\n" ]
[ 1 ]
[]
[]
[ "django", "django_fixtures", "fixtures", "google_app_engine", "python" ]
stackoverflow_0003597332_django_django_fixtures_fixtures_google_app_engine_python.txt
Q: Reading Python source code to improve programming skills I am trying improve my programming skills reading other peoples code, but I'd like to know what's the best source code to read? EDIT I have read some books: How to Think Like a Computer Scientist Learning Python, Fourth Edition Expert Python Programming Core Python Programming I am not new to programming, I am just trying to improve my skills. A: I would recommend finding an open source program that seems interesting and start contributing. This would require you to read and understand code well enough to improve it. Most open source hosting sites will let you find projects by what language they are written in. For example Github. You can also check out the results over at topcoder A: Just reading source won't improve your skills all that much. You might learn a trick here and there, but on the whole, changing the code will teach you far more than reading it ever will. I would recommend finding an open source project that you like and use, identifying a few bugs that you are interested in fixing (finding bugs should be pretty easy, and if you can't do it yourself, check the bug tracker), and then fix them. Some bugs may be harder to fix than others, which is why I suggest finding a few different bugs; if you get stuck on one, move on to another. You will have read plenty of code in order to find the bug, and you will have thought the code through enough to be able to fix a bug in it. Furthermore, you will have improved a piece of software that you know and use, and if you submit the patch back to the project, you may get good review and criticism on your patch, as well as helping out future users and getting something to stick on your resume. A: In Python, I love Django source code. It isn't going to make sense unless you learn how to use it first, which is probably a good thing to do anyway. Then pick a random thing you want to know more about and read the source. It is really clean Python code. A: Reading, understanding and then applying the methods used by a better coder is the best way to learn coding if you just started. A: Honestly, I don't think that just reading it will improve if you're a newbie, I'd try actually writing code, hands-on experience is the best method for learning. A: Just reading won't improve your skills but depending on how you learn it can be very helpful until you get a grasp on things. Open-source projects are your best bet, because they are code that is in use. It may not always be the prettiest, but it's guaranteed to be functional. Some of the ones I've looked at are Django and Trac by Edgewall. Neither is probably the best, but they do help a little. There are others that are also widely used, such as Plone (and Zope) A: More language agnostic, but when I am trying to learn new languages, techniques or use 3rd party tools/libraries, I like to start with a problem I would like to solve. For myself, I like to write golf statistic applications, so I have now implemented it in a number of different languages. My code is far from perfect, but I can then work on re-factoring and slowly working in specific patterns and practices for the language of choice. Reading code isn't bad, but the best thing to do is get your feet wet and code up an application that you are familiar with and that will add value (if even just for yourself).
Reading Python source code to improve programming skills
I am trying improve my programming skills reading other peoples code, but I'd like to know what's the best source code to read? EDIT I have read some books: How to Think Like a Computer Scientist Learning Python, Fourth Edition Expert Python Programming Core Python Programming I am not new to programming, I am just trying to improve my skills.
[ "I would recommend finding an open source program that seems interesting and start contributing. This would require you to read and understand code well enough to improve it. Most open source hosting sites will let you find projects by what language they are written in. For example Github.\nYou can also check out...
[ 7, 5, 3, 2, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003605337_python.txt
Q: Regular expression with [ or ( in python I need to extract IP address in the form prosseek.amer.corp.com [10.0.40.147] or prosseek.amer.corp.com (10.0.40.147) with Python. How can I get the IP for either case with Python? I started with something like site = "prosseek.amer.corp.com" m = re.search("%s.*[\(\[](\d+\.\d+\.\d+\.\d+)" % site, r) but it doesn't work. ADDED m = re.search("%s.+(\(|\[)(\d+\.\d+\.\d+\.\d+)" % site, r) m.group(2) m = re.search(r"%s.*[([](\d+\.\d+\.\d+\.\d+)" % site, r) m.group(1) seems to work. A: You don't need to escape meta-characters (*, (, ), ., ...) in character groups (except ], unless it is the first character in the character group; [][]+ would match a sequence of square brackets.) Another tip when it comes to Python is to use r'...'-style strings. With them, backslashes has no special meaning. r'\\' would print \\, since backslash has no special meaning: m = re.search(r"%s.*[([](\d+\.\d+\.\d+\.\d+)" % site, r) In the above string it doesn't make any difference though, since \d doesn't mean anything in Python, but when it comes to stuff like \r, \\, etc., it makes lives easier. A: Use [([] The characters inside the outer brackets are taken literally. You do not need to escape them with a backslash. For example: import re site = "prosseek.amer.corp.com " m = re.search("%s\s*[([](\d+\.\d+\.\d+\.\d+)" % site, 'prosseek.amer.corp.com (10.0.40.147)') A: I'd like to suggest a few slight refinements to what you have: site = "prosseek.amer.corp.com" m = re.search(r"%s\s+[([](\d+\.\d+\.\d+\.\d+)" % re.escape(site), r) m.group(2) The changes are: Pass site through re.escape so that it is interpreted literally; otherwise the dots in the domain name can match any character. This is extra important if site comes from user input; you don't want someone to be able to stick a regular expression in there and break your program. Use \s+ instead of .+ in between the site name and the IP address, so that it only accepts whitespace. A: re.findall("(?:\d{1,3}\.){3}\d{1,3}", site) A: How about you just ignore the brackets? site = "prosseek.amer.corp.com" m = re.search("%s.*(\d+\.\d+\.\d+\.\d+)" % site, r) A: import string site='prosseek.amer.corp.com (10.0.40.147)' ''.join([c for c in site if c not in string.ascii_letters+' []()']).strip('.') For some reason I like this better than regex
Regular expression with [ or ( in python
I need to extract IP address in the form prosseek.amer.corp.com [10.0.40.147] or prosseek.amer.corp.com (10.0.40.147) with Python. How can I get the IP for either case with Python? I started with something like site = "prosseek.amer.corp.com" m = re.search("%s.*[\(\[](\d+\.\d+\.\d+\.\d+)" % site, r) but it doesn't work. ADDED m = re.search("%s.+(\(|\[)(\d+\.\d+\.\d+\.\d+)" % site, r) m.group(2) m = re.search(r"%s.*[([](\d+\.\d+\.\d+\.\d+)" % site, r) m.group(1) seems to work.
[ "You don't need to escape meta-characters (*, (, ), ., ...) in character groups (except ], unless it is the first character in the character group; [][]+ would match a sequence of square brackets.)\nAnother tip when it comes to Python is to use r'...'-style strings. With them, backslashes has no special meaning. r'...
[ 3, 1, 1, 1, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003602225_python_regex.txt
Q: How to decode Get/Post Request headers into tuples using Cherry Py? Ok. I've been told by at least one really helpful individual who believes that its easy to decode and parse a GET/POST request header from within CherryPy. I've been here: http://www.cherrypy.org/wiki/BuiltinTools#tools.decode but it doesn't give you an example. Can someone direct me to a more helpful example? A: I guess there are two parts embedded to your question: 1) How to get the headers cherrypy.request.headers is a dict, you can extract information like any other dictionary 2) How to use the decoding / encoding support provided in tools.decode @tools.decode(encoding='ISO-88510-1') def decodingFunction(self, data): return "%s" % (data, ) This will allow you to decode a string using above encoding set. The string returned is unicode. Pass the information you extract from the dictionary to your decoding and encoding functions and you should be able to use this.
How to decode Get/Post Request headers into tuples using Cherry Py?
Ok. I've been told by at least one really helpful individual who believes that its easy to decode and parse a GET/POST request header from within CherryPy. I've been here: http://www.cherrypy.org/wiki/BuiltinTools#tools.decode but it doesn't give you an example. Can someone direct me to a more helpful example?
[ "I guess there are two parts embedded to your question:\n1) How to get the headers \ncherrypy.request.headers is a dict, you can extract information like any other dictionary\n2) How to use the decoding / encoding support provided in tools.decode\n@tools.decode(encoding='ISO-88510-1') \ndef decodingFunction(self, d...
[ 2 ]
[]
[]
[ "cherrypy", "http_headers", "python" ]
stackoverflow_0003605443_cherrypy_http_headers_python.txt
Q: Help me with py2exe I made my program, and tested it in Command Prompt(by entering in the directory). Then I made a set up file, and put the setup file and my program in the same folder. My setup file: from distutils.core import setup import py2exe setup(console=['C:\Python26\test\testprogram.py']) I went to run the setup program in command prompt(by entering in the directory and got the following error: What am I doing wrong? Also this program contains several pictures and modules, could this be linked to that? A: The setup file is used to build / install files for distribution. you need to provide command to setup.py : "./setup.py command" Go through, http://wiki.python.org/moin/Distutils/Tutorial and others on google search to understand it. Py2Exe is an additional command to DistUtils, that creates standalone distributions for Win32. so in your case it should be setup.py py2exe Look at http://www.py2exe.org/index.cgi/Tutorial
Help me with py2exe
I made my program, and tested it in Command Prompt(by entering in the directory). Then I made a set up file, and put the setup file and my program in the same folder. My setup file: from distutils.core import setup import py2exe setup(console=['C:\Python26\test\testprogram.py']) I went to run the setup program in command prompt(by entering in the directory and got the following error: What am I doing wrong? Also this program contains several pictures and modules, could this be linked to that?
[ "The setup file is used to build / install files for distribution. you need to provide command to setup.py : \"./setup.py command\"\nGo through, http://wiki.python.org/moin/Distutils/Tutorial and others on google search to understand it.\nPy2Exe is an additional command to DistUtils, that creates standalone distrib...
[ 2 ]
[]
[]
[ "exe", "py2exe", "python" ]
stackoverflow_0003605755_exe_py2exe_python.txt
Q: Why does my remote MongoDB connection require authentication on every query? After fighting with different things here and there, I was finally able to get BottlePY running on Apache and run a MongoDB powered site. I am used to running Django apps, so I will be relating to that a bit in my question. The Problem Every time a page is loaded via BottlePY, the connection to the MongoDB database located on MongoHQ.com needs to be re-authenticated (meaning it probably had to reconnect). What I Found I attached a db.keep_alive() function to the top of each model function, so that before any mongodb query is run, it trys to run a simple query. If it fails, it catches the OperationFailure or AutoReconnect errors and then calls the db.authenticate() function. After it reauthenticates, I have it add a log to a logs db to monitor how often it needs to reauthenticate. Currently, it needs to reauthenticate on every page load (that requires running a query). This isn't right. Difference from Django I use this same concept in django, and have found that the db connection only needs to be authenticated after 10-15 minutes of no queries being run. I don't understand why creating a pymongo connection in django would be different from creating one in bottle, since I am using the same driver, functions and methods. I am not using any ORMS or anything like that either. Versions Bottle: 0.9.dev Django: 1.2.1 final PyMongo: 1.8 I appreciate the help! Update: A friend was able to take a quick look and noticed the following that may help with answering my question. It appears that each request is launching a new Python process, as opposed to Django, in which a single process remains running for a long period of time. A: This just ended up to be a weird thing between Bottle and MongoHQ. No real solution was found, but I couldn't recreate it with other frameworks. Any other ideas are appreciated. A: does your apache xxx.conf contain something like: WSGIDaemonProcess project user=mysite group=www-data processes=5 threads=1 WSGIProcessGroup project I think most important should be threads=1
Why does my remote MongoDB connection require authentication on every query?
After fighting with different things here and there, I was finally able to get BottlePY running on Apache and run a MongoDB powered site. I am used to running Django apps, so I will be relating to that a bit in my question. The Problem Every time a page is loaded via BottlePY, the connection to the MongoDB database located on MongoHQ.com needs to be re-authenticated (meaning it probably had to reconnect). What I Found I attached a db.keep_alive() function to the top of each model function, so that before any mongodb query is run, it trys to run a simple query. If it fails, it catches the OperationFailure or AutoReconnect errors and then calls the db.authenticate() function. After it reauthenticates, I have it add a log to a logs db to monitor how often it needs to reauthenticate. Currently, it needs to reauthenticate on every page load (that requires running a query). This isn't right. Difference from Django I use this same concept in django, and have found that the db connection only needs to be authenticated after 10-15 minutes of no queries being run. I don't understand why creating a pymongo connection in django would be different from creating one in bottle, since I am using the same driver, functions and methods. I am not using any ORMS or anything like that either. Versions Bottle: 0.9.dev Django: 1.2.1 final PyMongo: 1.8 I appreciate the help! Update: A friend was able to take a quick look and noticed the following that may help with answering my question. It appears that each request is launching a new Python process, as opposed to Django, in which a single process remains running for a long period of time.
[ "This just ended up to be a weird thing between Bottle and MongoHQ. No real solution was found, but I couldn't recreate it with other frameworks. Any other ideas are appreciated.\n", "does your apache xxx.conf contain something like:\nWSGIDaemonProcess project user=mysite group=www-data processes=5 threads=1\n WS...
[ 1, 0 ]
[]
[]
[ "bottle", "mongodb", "pymongo", "python" ]
stackoverflow_0003456267_bottle_mongodb_pymongo_python.txt
Q: GAE datastore date property auto produce date of 1970 I have datastore Model bellow: class ThisCategory(search.SearchableModel): ancestor = db.ListProperty(db.Key, default=[]) no_ancestor = db.BooleanProperty(default=True) name = db.StringProperty() description = db.TextProperty() last_modified = db.TimeProperty(auto_now=True) #<----- (1970-01-01 15:36:47.987352) in datastore How to create/result correct now date? A: A TimeProperty is just a DateTime object with the date part set to 0 (which means 1970-01-01). The idea is that when you use a TimeProperty you ignore the date part. If you want to use the Date information too, then you want a DateTimeProperty. The DateTimeProperty's auto_now will properly set both the date and time parts.
GAE datastore date property auto produce date of 1970
I have datastore Model bellow: class ThisCategory(search.SearchableModel): ancestor = db.ListProperty(db.Key, default=[]) no_ancestor = db.BooleanProperty(default=True) name = db.StringProperty() description = db.TextProperty() last_modified = db.TimeProperty(auto_now=True) #<----- (1970-01-01 15:36:47.987352) in datastore How to create/result correct now date?
[ "A TimeProperty is just a DateTime object with the date part set to 0 (which means 1970-01-01).\nThe idea is that when you use a TimeProperty you ignore the date part.\nIf you want to use the Date information too, then you want a DateTimeProperty. The DateTimeProperty's auto_now will properly set both the date and...
[ 6 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0003605869_google_app_engine_google_cloud_datastore_python.txt
Q: Opening a website frame or image in python So i am fairly fluent with python and have used urllib2 and Cookies a lot for website automation. I just stumbled upon the "webbrowser" module which can open a url in your default browser. Im wondering if its possible to select just one object from that url and open that up. Specifically i want to open a "captcha" so that the user can input it, and continue doing something else. this is line containing the captcha in the html, i think: script type="text/javascript" src="http://api.recaptcha.net/challenge?k=6LcZ-AAAAAAAANX-xwVtzow1f4RpSrbSViRUx9Js"></script> <input type="submit" name="submitBtn" value="Submit" and clicking on that api link opens this: var RecaptchaState = { site : '6LcZ-AAAAAAAANX-xwVtzow1f4RpSrbSViRUx9Js', challenge : '03AHJ_VuvoUHPdfoXLsVHGa7a26GR9s9Y5dkyKmqk2XsJ1SdiwF_2u0SV_sKnr1artkpc-5MjUe7SYD40xr7sAyvikKwpFCQTBdKUFfl76UP6EbDhezoTC8B1X8fjixuIJ4wJhI6yTc8vlX4ioh6je9lwFbPXllbGh2w', is_incorrect : false, programming_error : '', error_message : '', server : 'http://www.google.com/recaptcha/api/', timeout : 18000 }; document.write('<scr'+'ipt type="text/javascript" s'+'rc="' + RecaptchaState.server + 'js/recaptcha.js"></scr'+'ipt>'); any info would help with this. A: It's not possible with the webbrowser module. All webbrowser does is provide a simple way to identify the default web browser and feed a URL to it. If you want to render just a portion of a page, you need something that can either take arbitrary HTML fragments or can inject some Javascript after loading a page to strip out the unwanted elements. For that, what you need is to build a purpose-specific web browser that's nothing more than a dialog box containing a web widget. That can be done using any of the following combinations of libraries: PyQt and the included QtWebKit (GPL or Commercial, Windows/Mac/Linux) PySide and the included QtWebKit (LGPL, Linux) PyGTK and PyWebKitGTK (LGPL, Easy on Linux... no clue about Windows or OSX) PyGTK and GTKMozEmbed (LGPL, Easy on Linux... no clue about Windows or OSX) wxPython and the included wxIEHtmlWindow (BSD-like, Windows-only. Embeds Internet Explorer.) wxPython and the included wxWebKitCtrl (BSD-like, OSX-only) wxPython and wxWebKit (BSD-like, Windows/Mac/Linux) My advice: If GPL licensing is OK, use PyQt. If GPL licensing isn't OK: For Linux, use PySide or PyGTK with PyWebKitGTK (GTKMozEmbed is heavy) For Windows, use wxPython with wxIEHtmlWindow For OSX, you'll have to ask someone else.
Opening a website frame or image in python
So i am fairly fluent with python and have used urllib2 and Cookies a lot for website automation. I just stumbled upon the "webbrowser" module which can open a url in your default browser. Im wondering if its possible to select just one object from that url and open that up. Specifically i want to open a "captcha" so that the user can input it, and continue doing something else. this is line containing the captcha in the html, i think: script type="text/javascript" src="http://api.recaptcha.net/challenge?k=6LcZ-AAAAAAAANX-xwVtzow1f4RpSrbSViRUx9Js"></script> <input type="submit" name="submitBtn" value="Submit" and clicking on that api link opens this: var RecaptchaState = { site : '6LcZ-AAAAAAAANX-xwVtzow1f4RpSrbSViRUx9Js', challenge : '03AHJ_VuvoUHPdfoXLsVHGa7a26GR9s9Y5dkyKmqk2XsJ1SdiwF_2u0SV_sKnr1artkpc-5MjUe7SYD40xr7sAyvikKwpFCQTBdKUFfl76UP6EbDhezoTC8B1X8fjixuIJ4wJhI6yTc8vlX4ioh6je9lwFbPXllbGh2w', is_incorrect : false, programming_error : '', error_message : '', server : 'http://www.google.com/recaptcha/api/', timeout : 18000 }; document.write('<scr'+'ipt type="text/javascript" s'+'rc="' + RecaptchaState.server + 'js/recaptcha.js"></scr'+'ipt>'); any info would help with this.
[ "It's not possible with the webbrowser module. All webbrowser does is provide a simple way to identify the default web browser and feed a URL to it.\nIf you want to render just a portion of a page, you need something that can either take arbitrary HTML fragments or can inject some Javascript after loading a page to...
[ 4 ]
[]
[]
[ "browser", "cookies", "python", "urllib2" ]
stackoverflow_0003605832_browser_cookies_python_urllib2.txt
Q: How can I add a test method to a group of Django TestCase-derived classes? I have a group of test cases that all should have exactly the same test done, along the lines of "Does method x return the name of an existing file?" I thought that the best way to do it would be a base class deriving from TestCase that they all share, and simply add the test to that class. Unfortunately, the testing framework still tries to run the test for the base class, where it doesn't make sense. class SharedTest(TestCase): def x(self): ...do test... class OneTestCase(SharedTest): ...my tests are performed, and 'SharedTest.x()'... I tried to hack in a check to simply skip the test if it's called on an object of the base class rather than a derived class like this: class SharedTest(TestCase): def x(self): if type(self) != type(SharedTest()): ...do test... else: pass but got this error: ValueError: no such test method in <class 'tests.SharedTest'>: runTest First, I'd like any elegant suggestions for doing this. Second, though I don't really want to use the type() hack, I would like to understand why it's not working. A: You could use a mixin by taking advantage that the test runner only runs tests inheriting from unittest.TestCase (which Django's TestCase inherits from.) For example: class SharedTestMixin(object): # This class will not be executed by the test runner (it inherits from object, not unittest.TestCase. # If it did, assertEquals would fail , as it is not a method that exists in `object` def test_common(self): self.assertEquals(1, 1) class TestOne(TestCase, SharedTestMixin): def test_something(self): pass # test_common is also run class TestTwo(TestCase, SharedTestMixin): def test_another_thing(self): pass # test_common is also run For more information on why this works do a search for python method resolution order and multiple inheritance. A: I faced a similar problem. I couldn't prevent the test method in the base class being executed but I ensured that it did not exercise any actual code. I did this by checking for an attribute and returning immediately if it was set. This attribute was only set for the Base class and hence the tests ran everywhere else but the base class. class SharedTest(TestCase): def setUp(self): self.do_not_run = True def test_foo(self): if getattr(self, 'do_not_run', False): return # Rest of the test body. class OneTestCase(SharedTest): def setUp(self): super(OneTestCase, self).setUp() self.do_not_run = False This is a bit of a hack. There is probably a better way to do this but I am not sure how. Update As sdolan says a mixin is the right way. Why didn't I see that before? Update 2 (After reading comments) It would be nice if (1) the superclass method could avoid the hackish if getattr(self, 'do_not_run', False): check; (2) if the number of tests were counted accurately. There is a possible way to do this. Django picks up and executes all test classes in tests, be it tests.py or a package with that name. If the test superclass is declared outside the tests module then this won't happen. It can still be inherited by test classes. For instance SharedTest can be located in app.utils and then used by the test cases. This would be a cleaner version of the above solution. # module app.utils.test class SharedTest(TestCase): def test_foo(self): # Rest of the test body. # module app.tests from app.utils import test class OneTestCase(test.SharedTest): ...
How can I add a test method to a group of Django TestCase-derived classes?
I have a group of test cases that all should have exactly the same test done, along the lines of "Does method x return the name of an existing file?" I thought that the best way to do it would be a base class deriving from TestCase that they all share, and simply add the test to that class. Unfortunately, the testing framework still tries to run the test for the base class, where it doesn't make sense. class SharedTest(TestCase): def x(self): ...do test... class OneTestCase(SharedTest): ...my tests are performed, and 'SharedTest.x()'... I tried to hack in a check to simply skip the test if it's called on an object of the base class rather than a derived class like this: class SharedTest(TestCase): def x(self): if type(self) != type(SharedTest()): ...do test... else: pass but got this error: ValueError: no such test method in <class 'tests.SharedTest'>: runTest First, I'd like any elegant suggestions for doing this. Second, though I don't really want to use the type() hack, I would like to understand why it's not working.
[ "You could use a mixin by taking advantage that the test runner only runs tests inheriting from unittest.TestCase (which Django's TestCase inherits from.) For example:\nclass SharedTestMixin(object):\n # This class will not be executed by the test runner (it inherits from object, not unittest.TestCase.\n # I...
[ 31, 4 ]
[]
[]
[ "django", "python", "subclassing", "unit_testing" ]
stackoverflow_0003605936_django_python_subclassing_unit_testing.txt
Q: Constructing objects in __init__ I've seen code that looks something like this: class MyClass: def __init__(self, someargs): myObj = OtherClass() myDict = {} ...code to setup myObj, myDict... self.myObj = myObj self.myDict = myDict My first thought when I saw this was: Why not just use self.myObj and self.myDict in the beginning? It seems inefficient to construct local objects, then assign them to the members. The code to construct the objects do possibly throw exceptions, maybe they did this so it wouldn't leave a half-constructed object? Do you do this, or just construct the members directly? A: It's faster and more readable to construct the object and then attach it to self. class Test1(object): def __init__(self): d = {} d['a'] = 1 d['b'] = 2 d['c'] = 3 self.d = d class Test2(object): def __init__(self): self.d = {} self.d['a'] = 1 self.d['b'] = 2 self.d['c'] = 3 import dis print "Test1.__init__" dis.dis(Test1.__init__) print "Test2.__init__" dis.dis(Test2.__init__) disassemles to: Test1.__init__ 4 0 BUILD_MAP 0 3 STORE_FAST 1 (d) 5 6 LOAD_CONST 1 (1) 9 LOAD_FAST 1 (d) 12 LOAD_CONST 2 ('a') 15 STORE_SUBSCR 6 16 LOAD_CONST 3 (2) 19 LOAD_FAST 1 (d) 22 LOAD_CONST 4 ('b') 25 STORE_SUBSCR 7 26 LOAD_CONST 5 (3) 29 LOAD_FAST 1 (d) 32 LOAD_CONST 6 ('c') 35 STORE_SUBSCR 8 36 LOAD_FAST 1 (d) 39 LOAD_FAST 0 (self) 42 STORE_ATTR 0 (d) 45 LOAD_CONST 0 (None) 48 RETURN_VALUE Test2.__init__ 12 0 BUILD_MAP 0 3 LOAD_FAST 0 (self) 6 STORE_ATTR 0 (d) 13 9 LOAD_CONST 1 (1) 12 LOAD_FAST 0 (self) 15 LOAD_ATTR 0 (d) 18 LOAD_CONST 2 ('a') 21 STORE_SUBSCR 14 22 LOAD_CONST 3 (2) 25 LOAD_FAST 0 (self) 28 LOAD_ATTR 0 (d) 31 LOAD_CONST 4 ('b') 34 STORE_SUBSCR 15 35 LOAD_CONST 5 (3) 38 LOAD_FAST 0 (self) 41 LOAD_ATTR 0 (d) 44 LOAD_CONST 6 ('c') 47 STORE_SUBSCR 48 LOAD_CONST 0 (None) 51 RETURN_VALUE You can see that STORE_ATTR only gets called once doing it the first way at the end. Doing it the other way, STORE_ATTR still gets called right at the beginning but now LOAD_ATTR gets called for every access to the dictionary. The more assignments there are, the higher the cost. Every other instruction is the same. It's still a ridiculously small cost. This trick can be exploited to make loops with many iterations run faster. It's not uncommon to see things like foo = self.foo factorial = math.factorial for x in really_big_iterator: foo(factorial(x)) another trick is to pass global functions as default arguments to a function that has a loop like that or gets called a whole bunch to save some attribute lookups: it's in the local scope which is the first one looked in. def fast(iterators, sum=sum): for i in iterator: yield sum(i) now sum is right in the local scope. A: If you are worried about the performance implication of copying an object reference, you are probably using the wrong language :) Do what's more readable to you. In this case, it depends on how long is the init method. A: I'm not sure I fully understand your question, but keep in mind that assigning self.myObj = myObj will simply assign a reference so it isn't likely to slow things down much. My guess is that idiom is being used to save the programmer from typing the word self a bunch of times. A: There is really no significant difference either way. One reason to create a local variable is if you are going to use the variable in __init__ a lot, you don't have to repeat the self. so much. e.g. def __init__(self, someargs): self.myObj = OtherClass() self.myDict = {} self.myDict[1] = self.myObj self.myDict[2] = self.myObj self.myDict[3] = self.myObj self.myDict[4] = self.myObj self.myObj = myObj self.myDict = myDict v.s. def __init__(self, someargs): obj = OtherClass() d = {} d[1] = obj d[2] = obj d[3] = obj d[4] = obj self.myObj = obj self.myDict = d I won't worry performance so much unless you have a good reason to. A: Assigning a reference doesn't take too much time, but typing 'self' each time does take you time.
Constructing objects in __init__
I've seen code that looks something like this: class MyClass: def __init__(self, someargs): myObj = OtherClass() myDict = {} ...code to setup myObj, myDict... self.myObj = myObj self.myDict = myDict My first thought when I saw this was: Why not just use self.myObj and self.myDict in the beginning? It seems inefficient to construct local objects, then assign them to the members. The code to construct the objects do possibly throw exceptions, maybe they did this so it wouldn't leave a half-constructed object? Do you do this, or just construct the members directly?
[ "It's faster and more readable to construct the object and then attach it to self.\nclass Test1(object):\n def __init__(self):\n d = {}\n d['a'] = 1\n d['b'] = 2\n d['c'] = 3\n self.d = d\n\nclass Test2(object):\n def __init__(self):\n self.d = {}\n self.d['a']...
[ 8, 3, 1, 0, 0 ]
[]
[]
[ "constructor", "python" ]
stackoverflow_0003605766_constructor_python.txt
Q: Is it possible to change the color of one individual pixel in Python? I need python to change the color of one individual pixel on a picture, how do I go about that? A: To build upon the example given in Gabi Purcaru's link, here's something cobbled together from the PIL docs. The simplest way to reliably modify a single pixel using PIL would be: x, y = 10, 25 shade = 20 from PIL import Image im = Image.open("foo.png") pix = im.load() if im.mode == '1': value = int(shade >= 127) # Black-and-white (1-bit) elif im.mode == 'L': value = shade # Grayscale (Luminosity) elif im.mode == 'RGB': value = (shade, shade, shade) elif im.mode == 'RGBA': value = (shade, shade, shade, 255) elif im.mode == 'P': raise NotImplementedError("TODO: Look up nearest color in palette") else: raise ValueError("Unexpected mode for PNG image: %s" % im.mode) pix[x, y] = value im.save("foo_new.png") That will work in PIL 1.1.6 and up. If you have the bad luck of having to support an older version, you can sacrifice performance and replace pix[x, y] = value with im.putpixel((x, y), value).
Is it possible to change the color of one individual pixel in Python?
I need python to change the color of one individual pixel on a picture, how do I go about that?
[ "To build upon the example given in Gabi Purcaru's link, here's something cobbled together from the PIL docs.\nThe simplest way to reliably modify a single pixel using PIL would be:\nx, y = 10, 25\nshade = 20\n\nfrom PIL import Image\nim = Image.open(\"foo.png\")\npix = im.load()\n\nif im.mode == '1':\n value = ...
[ 25 ]
[]
[]
[ "pixel", "python", "python_imaging_library" ]
stackoverflow_0003596433_pixel_python_python_imaging_library.txt
Q: What would be the simplest way to daemonize a python script in Linux? What would be the simplest way to daemonize a python script in Linux ? I need that this works with every flavor of Linux, so it should only use python based tools. A: See Stevens and also this lengthy thread on activestate which I found personally to be both mostly incorrect and much to verbose, and I came up with this: from os import fork, setsid, umask, dup2 from sys import stdin, stdout, stderr if fork(): exit(0) umask(0) setsid() if fork(): exit(0) stdout.flush() stderr.flush() si = file('/dev/null', 'r') so = file('/dev/null', 'a+') se = file('/dev/null', 'a+', 0) dup2(si.fileno(), stdin.fileno()) dup2(so.fileno(), stdout.fileno()) dup2(se.fileno(), stderr.fileno()) If you need to stop that process again, it is required to know the pid, the usual solution to this is pidfiles. Do this if you need one from os import getpid outfile = open(pid_file, 'w') outfile.write('%i' % getpid()) outfile.close() For security reasons you might consider any of these after demonizing from os import setuid, setgid, chdir from pwd import getpwnam from grp import getgrnam setuid(getpwnam('someuser').pw_uid) setgid(getgrnam('somegroup').gr_gid) chdir('/') You could also use nohup but that does not work well with python's subprocess module A: nohup Creating a daemon the Python way A: I have recently used Turkmenbashi : $ easy_install turkmenbashi import Turkmenbashi class DebugDaemon (Turkmenbashi.Daemon): def config(self): self.debugging = True def go(self): self.debug('a debug message') self.info('an info message') self.warn('a warning message') self.error('an error message') self.critical('a critical message') if __name__=="__main__": d = DebugDaemon() d.config() d.setenv(30, '/var/run/daemon.pid', '/tmp', None) d.start(d.go) A: If you do not care for actual discussions (which tend to go offtopic and do not offer authoritative response), you can choose some library that will make your tast easier. I'd recomment taking a look at ll-xist, this library contains large amount of life-saving code, like cron jobs helper, daemon framework, and (what is not interesting to you, but is really great) object-oriented XSL (ll-xist itself). A: Use grizzled.os.daemonize: $ easy_install grizzled >>> from grizzled.os import daemonize >>> daemon.daemonize() To understand how this works or to do it yourself, read the discussion on ActiveState.
What would be the simplest way to daemonize a python script in Linux?
What would be the simplest way to daemonize a python script in Linux ? I need that this works with every flavor of Linux, so it should only use python based tools.
[ "See Stevens and also this lengthy thread on activestate which I found personally to be both mostly incorrect and much to verbose, and I came up with this:\nfrom os import fork, setsid, umask, dup2\nfrom sys import stdin, stdout, stderr\n\nif fork(): exit(0)\numask(0) \nsetsid() \nif fork(): exit(0)\n\nstdout.flush...
[ 21, 4, 2, 1, 0 ]
[]
[]
[ "daemon", "python", "scripting" ]
stackoverflow_0000115974_daemon_python_scripting.txt
Q: True = False == True Possible Duplicate: Why can't Python handle true/false values as I expect? False = True should raise an error in this case. False = True True == False True True + False == True? if True + False: print True True True Again? if str(True + False) + str(False + False) == '10': print True True LOL if True + False + True * (False * True ** True / True - True % True) - (True / True) ** True + True - (False ** True ** True): print True, 'LOL' True LOL why this is all True? A: False is just a global variable, you can assign to it. It will, however, break just about everything if you do so. Note that this behavior has been removed in python3k Python 3.1 (r31:73578, Jun 27 2009, 21:49:46) >>> False = True File "<stdin>", line 1 SyntaxError: assignment to keyword also, int(False) == 0 and int(True) == 1, so you can do arbitrary arithmetic with them A: See Why can't Python handle true/false values as I expect?, that will answer your first question. Basically you can think of: False = True True == False True as var = True True == var True (reminds me of #define TRUE FALSE // Happy debugging suckers *chuckles*) As for the other questions, when you do arithmetic operations on True and False they get converted to 1 and 0. True + False is the same as 1 + 0, which is 1, which is True. str(True + False) + str(False + False) is the same as str(1) + str(0), and the + here concatenates strings, so you'll get 10 Your last one is a bunch of arithmetic operations that give a non-zero result (1), which is True.
True = False == True
Possible Duplicate: Why can't Python handle true/false values as I expect? False = True should raise an error in this case. False = True True == False True True + False == True? if True + False: print True True True Again? if str(True + False) + str(False + False) == '10': print True True LOL if True + False + True * (False * True ** True / True - True % True) - (True / True) ** True + True - (False ** True ** True): print True, 'LOL' True LOL why this is all True?
[ "False is just a global variable, you can assign to it. It will, however, break just about everything if you do so.\nNote that this behavior has been removed in python3k\nPython 3.1 (r31:73578, Jun 27 2009, 21:49:46) \n>>> False = True\n File \"<stdin>\", line 1\nSyntaxError: assignment to keyword\n\nalso, int(Fal...
[ 12, 7 ]
[]
[]
[ "python" ]
stackoverflow_0003606333_python.txt
Q: Hide password when checking config file in git Possible Duplicates: What is the best practice for dealing with passwords in github? How can I track system-specific config files in a repo/project? Hi, I would like to hide DATABASE_NAME = '' DATABASE_USER = '' DATABASE_PASSWORD = '' DATABASE_HOST = '' Line 13 to 17 of the default Django settings.py file when checking it in github. I still want to check it in tho, because I am adding modifications from time to time. I just want these four lines to always be set to empty. A: You could also have an extra settings file which holds passwords and just import them in your main settings.py For example: settings.py DATABASE_PASSWORD = '' try: from dev_settings import * except ImportError: pass dev_settings.py DATABASE_PASSWORD = 'mypassword' And keep dev_settings.py out of revision control. A: For my configuration files, I create a config.py-example and a config.py. config.py is ignored by the version control. When I deploy, I just copy config.py-example to config.py and update the passwords. A: Unfortunately, that's not how Git works - either a file is in version control, or it isn't. If you don't want the info in Github, then don't check it in. You could keep a copy of the config file in a separate (private) repository elsewhere if you wanted, though. A: I would recommend keeping settings.py with those four lines exactly as you've shown them, and have a separate, tiny Python script to add and remove the four bits of secret information (reading them from a file that's not part of your git repository, but rather is safely and secretly kept -- in a couple of copies, for safety -- in very secure places). You can have a presubmit check to make sure you never, ever push a settings.py that has not been shorn of the secrets (I don't know git enough to tell if it has "presubmit triggers" that can modify the repo, as well as presubmit checks that just check it, but, if it does, then clearly it may be more convenient for you to use said tiny Python script in such a trigger -- indeed, if that's the case, you might want to consider doing the removal/restoring of the secrets by using patch, and a simple diff file to use as its input, so you don't have to write even a line of script for the purpose).
Hide password when checking config file in git
Possible Duplicates: What is the best practice for dealing with passwords in github? How can I track system-specific config files in a repo/project? Hi, I would like to hide DATABASE_NAME = '' DATABASE_USER = '' DATABASE_PASSWORD = '' DATABASE_HOST = '' Line 13 to 17 of the default Django settings.py file when checking it in github. I still want to check it in tho, because I am adding modifications from time to time. I just want these four lines to always be set to empty.
[ "You could also have an extra settings file which holds passwords and just import them in your main settings.py\nFor example:\nsettings.py\nDATABASE_PASSWORD = ''\n\ntry:\n from dev_settings import *\nexcept ImportError:\n pass\n\ndev_settings.py\nDATABASE_PASSWORD = 'mypassword'\n\nAnd keep dev_settings.py out...
[ 21, 5, 1, 1 ]
[]
[]
[ "django", "git", "github", "python" ]
stackoverflow_0003605866_django_git_github_python.txt
Q: Python how to format currency string I have three floats that I want to output as a 2 decimal places string. amount1 = 0.1 amount2 = 0.0 amount3 = 1.87 I want to output all of them as a string that looks like 0.10, 0.00, and 1.87 respectively. How do I do that efficiently? A: An alternative to directly formatting them is the locale stdlib module >>> import locale >>> locale.setlocale(locale.LC_ALL, '') 'en_US.utf8' >>> locale.currency(123.2342343234234234) '$123.23' >>> locale.currency(123.2342343234234234, '') # the second argument controls the symbol '123.23' This is nice because you can just set the locale to the users default as I do and then print in their conventions.
Python how to format currency string
I have three floats that I want to output as a 2 decimal places string. amount1 = 0.1 amount2 = 0.0 amount3 = 1.87 I want to output all of them as a string that looks like 0.10, 0.00, and 1.87 respectively. How do I do that efficiently?
[ "An alternative to directly formatting them is the locale stdlib module\n>>> import locale\n>>> locale.setlocale(locale.LC_ALL, '')\n'en_US.utf8'\n>>> locale.currency(123.2342343234234234)\n'$123.23'\n>>> locale.currency(123.2342343234234234, '') # the second argument controls the symbol\n'123.23'\n\nThis is nice ...
[ 5 ]
[]
[]
[ "python", "string" ]
stackoverflow_0003606517_python_string.txt
Q: Google App Engine Python WebApp framework supported self.error() codes I know we can return errors to requests by calling self.error(http_error_code_here). However, there are some error codes that don't seem to be supported. "Unsupported error code" comes out when I use error code 510. I used http://en.wikipedia.org/wiki/List_of_HTTP_status_codes as a reference for the error codes I am using. What http error codes are currently supported by the GAE Python WebApp Framework? A: You'll find the supported status codes in google_appengine/google/appengine/ext/webapp/__init__.py around line 270. __HTTP_STATUS_MESSAGES = { 100: 'Continue', 101: 'Switching Protocols', 200: 'OK', 201: 'Created', 202: 'Accepted', 203: 'Non-Authoritative Information', 204: 'No Content', 205: 'Reset Content', 206: 'Partial Content', Splitted for easier browsing. 300: 'Multiple Choices', 301: 'Moved Permanently', 302: 'Moved Temporarily', 303: 'See Other', 304: 'Not Modified', 305: 'Use Proxy', 306: 'Unused', 307: 'Temporary Redirect', 400: 'Bad Request', 401: 'Unauthorized', 402: 'Payment Required', 403: 'Forbidden', 404: 'Not Found', 405: 'Method Not Allowed', 406: 'Not Acceptable', 407: 'Proxy Authentication Required', 408: 'Request Time-out', 409: 'Conflict', 410: 'Gone', 411: 'Length Required', 412: 'Precondition Failed', 413: 'Request Entity Too Large', 414: 'Request-URI Too Large', 415: 'Unsupported Media Type', 416: 'Requested Range Not Satisfiable', 417: 'Expectation Failed', 500: 'Internal Server Error', 501: 'Not Implemented', 502: 'Bad Gateway', 503: 'Service Unavailable', 504: 'Gateway Time-out', 505: 'HTTP Version not supported' }
Google App Engine Python WebApp framework supported self.error() codes
I know we can return errors to requests by calling self.error(http_error_code_here). However, there are some error codes that don't seem to be supported. "Unsupported error code" comes out when I use error code 510. I used http://en.wikipedia.org/wiki/List_of_HTTP_status_codes as a reference for the error codes I am using. What http error codes are currently supported by the GAE Python WebApp Framework?
[ "You'll find the supported status codes in \ngoogle_appengine/google/appengine/ext/webapp/__init__.py\n\naround line 270.\n__HTTP_STATUS_MESSAGES = {\n 100: 'Continue',\n 101: 'Switching Protocols',\n 200: 'OK',\n 201: 'Created',\n 202: 'Accepted',\n 203: 'Non-Authoritative Information',\n 204: 'No Content',...
[ 3 ]
[]
[]
[ "google_app_engine", "http_error", "python", "webob" ]
stackoverflow_0003606300_google_app_engine_http_error_python_webob.txt
Q: Installing Python SSL module on Windows Vista I'm running GAE SDK on a Windows Vista laptop. It keeps reminding me to install the SSL module. I've been having great difficulty on how to do that. I've downloaded the SSL module. I've done 'python setup.py install' in cmd, but it just says "python is not recognized as an internal..." I've added C:\Python2.5.2 to my PATH. Still the same message "python is not recognized as an internal or external command..." What else should I do? A: On the command line, run set path and confirm that c:\Python2.5.2 is in your path? Or, just run c:\Python2.5.2\python setup.py install Also by the way I would recommend that you use 2.5.4 for app engine development, as that is the version google use in production. The following question also has some info which might be useful: How to install Python ssl module on Windows? A: Why don't you provide the complete path to python executable. That should work. C:\"Python2.5.2"\python.exe setup.py install A: Note: this answer is not specific to the ssl module, but reminded me of a problem I encountered when installing Sphinx on a Win7 machine. You might want to call python setup.py install from a command prompt with administrator privileges (see here how to start a cmd prompt "as administrator"). I ran into similar problems (using easy_install) and running from an admin prompt was the solution.
Installing Python SSL module on Windows Vista
I'm running GAE SDK on a Windows Vista laptop. It keeps reminding me to install the SSL module. I've been having great difficulty on how to do that. I've downloaded the SSL module. I've done 'python setup.py install' in cmd, but it just says "python is not recognized as an internal..." I've added C:\Python2.5.2 to my PATH. Still the same message "python is not recognized as an internal or external command..." What else should I do?
[ "On the command line, run set path and confirm that c:\\Python2.5.2 is in your path?\nOr, just run c:\\Python2.5.2\\python setup.py install\nAlso by the way I would recommend that you use 2.5.4 for app engine development, as that is the version google use in production.\nThe following question also has some info wh...
[ 2, 0, 0 ]
[]
[]
[ "google_app_engine", "python", "ssl" ]
stackoverflow_0003606743_google_app_engine_python_ssl.txt
Q: Validate Certificate using Python I want to access a web service over HTTPS. I have been given a client certificate (p12 file) in order to access it. Previously we were using basic authentication. Using python I am unsure how to access it. I want to use httplib2 h = Http() #h.add_credentials("testuser", "testpass") #h.add_certificate(keyfile, certfile, '') resp, content = h.request("https://example.com/webservice", "POST", xml_data) print content Now, I am quite new to SSL, Can I just call add_cert or somethign similar and give it the p12 file. Do I need to convert it to a PEM file? A: The answer to my question was IN my question h.add_certificate(keyfile, certfile, '') I had a pkcs12 file, I just needed to extract out the key and cert from the p12 file. openssl pkcs12 -in file.p12 -out key.pem -nodes -nocerts openssl pkcs12 -in file.p12 -out cert.pem -nodes -nokeys
Validate Certificate using Python
I want to access a web service over HTTPS. I have been given a client certificate (p12 file) in order to access it. Previously we were using basic authentication. Using python I am unsure how to access it. I want to use httplib2 h = Http() #h.add_credentials("testuser", "testpass") #h.add_certificate(keyfile, certfile, '') resp, content = h.request("https://example.com/webservice", "POST", xml_data) print content Now, I am quite new to SSL, Can I just call add_cert or somethign similar and give it the p12 file. Do I need to convert it to a PEM file?
[ "The answer to my question was IN my question\nh.add_certificate(keyfile, certfile, '')\n\nI had a pkcs12 file, I just needed to extract out the key and cert from the p12 file.\nopenssl pkcs12 -in file.p12 -out key.pem -nodes -nocerts\nopenssl pkcs12 -in file.p12 -out cert.pem -nodes -nokeys\n\n" ]
[ 2 ]
[]
[]
[ "openssl", "python", "ssl_certificate" ]
stackoverflow_0003600527_openssl_python_ssl_certificate.txt
Q: Python regex with unicode characters bug? Long story short: >>> re.compile(r"\w*").match(u"Français") <_sre.SRE_Match object at 0x1004246b0> >>> re.compile(r"^\w*$").match(u"Français") >>> re.compile(r"^\w*$").match(u"Franais") <_sre.SRE_Match object at 0x100424780> >>> Why doesn't it match the string with unicode characters with ^ and $ in the regex? As far as I understand ^ stands for the beginning of the string(line) and $ - for the end of it. A: You need to specify the UNICODE flag, otherwise \w is just equivalent to [a-zA-Z0-9_], which does not include the character 'ç'. >>> re.compile(r"^\w*$", re.U).match(u"Fran\xe7ais") <_sre.SRE_Match object at 0x101474168>
Python regex with unicode characters bug?
Long story short: >>> re.compile(r"\w*").match(u"Français") <_sre.SRE_Match object at 0x1004246b0> >>> re.compile(r"^\w*$").match(u"Français") >>> re.compile(r"^\w*$").match(u"Franais") <_sre.SRE_Match object at 0x100424780> >>> Why doesn't it match the string with unicode characters with ^ and $ in the regex? As far as I understand ^ stands for the beginning of the string(line) and $ - for the end of it.
[ "You need to specify the UNICODE flag, otherwise \\w is just equivalent to [a-zA-Z0-9_], which does not include the character 'ç'.\n>>> re.compile(r\"^\\w*$\", re.U).match(u\"Fran\\xe7ais\")\n<_sre.SRE_Match object at 0x101474168>\n\n" ]
[ 5 ]
[]
[]
[ "character_properties", "match", "python", "regex", "unicode" ]
stackoverflow_0003607323_character_properties_match_python_regex_unicode.txt
Q: Abort a running task in Celery within django I would like to be able to abort a task that is running from a Celery queue (using rabbitMQ). I call the task using task_id = AsyncBoot.apply_async(args=[name], name=name, connect_timeout=3) where AsyncBoot is a defined task. I can get the task ID (assuming that is the long string that apply_async returns) and store it in a database but I'm unsure how to call an abort method. I see how to make methods abortable with the Abortable tasks class but if I only have the task-id string, how do I call .abort() on the task? Thanks. A: apply_async returns an AsyncResult instance, or in this case an AbortableAsyncResult. Save the task_id and use that to instantiate a new AbortableAsyncResult later, making sure you supply the backend optional argument if you're not using the default_backend. abortable_async_result = AsyncBoot.apply_async(args=[name], name=name, connect_timeout=3) myTaskId = abortable_async_result.task_id Later: abortable_async_result = AbortableAsyncResult(myTaskId) abortable_async_result.abort() A: Did you see the reference documentation? http://celeryq.org/docs/reference/celery.contrib.abortable.html To abort the task use result.abort(): >>> result = AsyncBoot.apply_async(...) >>> result.abort()
Abort a running task in Celery within django
I would like to be able to abort a task that is running from a Celery queue (using rabbitMQ). I call the task using task_id = AsyncBoot.apply_async(args=[name], name=name, connect_timeout=3) where AsyncBoot is a defined task. I can get the task ID (assuming that is the long string that apply_async returns) and store it in a database but I'm unsure how to call an abort method. I see how to make methods abortable with the Abortable tasks class but if I only have the task-id string, how do I call .abort() on the task? Thanks.
[ "apply_async returns an AsyncResult instance, or in this case an AbortableAsyncResult. Save the task_id and use that to instantiate a new AbortableAsyncResult later, making sure you supply the backend optional argument if you're not using the default_backend.\nabortable_async_result = AsyncBoot.apply_async(args=[na...
[ 11, 4 ]
[]
[]
[ "celery", "celery_task", "django", "python", "rabbitmq" ]
stackoverflow_0003576512_celery_celery_task_django_python_rabbitmq.txt
Q: Uninstall and Install Programs in windows using python script Possible Duplicate: Add/remove programs in Windows XP with Python script I am a newbie in python and basically do windows sysadmin tasks and sometimes write batch script. However i am trying to learn python by implementing the scripts in windows tasks. The actual task i want to do is a follows: To remove acrobat reader or acrobat standard version and install acrobat professional. I also have to remove SAP client application from the machine and be able to run another SAP install.cmd file which then installs an updated version of SAP.could your or someone post me a more or less complete working script? Thanks in advance – Everest A: To call a function as if you had entered it on the command line, use subprocess.Popen. There are various scripting functions (copy, remove) in the os and shutil modules.
Uninstall and Install Programs in windows using python script
Possible Duplicate: Add/remove programs in Windows XP with Python script I am a newbie in python and basically do windows sysadmin tasks and sometimes write batch script. However i am trying to learn python by implementing the scripts in windows tasks. The actual task i want to do is a follows: To remove acrobat reader or acrobat standard version and install acrobat professional. I also have to remove SAP client application from the machine and be able to run another SAP install.cmd file which then installs an updated version of SAP.could your or someone post me a more or less complete working script? Thanks in advance – Everest
[ "To call a function as if you had entered it on the command line, use subprocess.Popen. There are various scripting functions (copy, remove) in the os and shutil modules.\n" ]
[ 0 ]
[]
[]
[ "administration", "python", "system", "windows" ]
stackoverflow_0003607640_administration_python_system_windows.txt
Q: How to edit a StringListProperty value in Google App Engine? I would like to edit the value of a StringListProperty variable on App Engine. Is it possible? I don't see any sign of editable field for a StringListProperty variable right inside the DataViewer panel. A: You need to edit it programmatically. Not all property types can be edited in the data viewer.
How to edit a StringListProperty value in Google App Engine?
I would like to edit the value of a StringListProperty variable on App Engine. Is it possible? I don't see any sign of editable field for a StringListProperty variable right inside the DataViewer panel.
[ "You need to edit it programmatically. Not all property types can be edited in the data viewer.\n" ]
[ 2 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003607201_google_app_engine_python.txt
Q: Smart way to find out string encoding? I wonder whether it is possible to find what is the encoding of string? I know that it may be impossible for some strings (e.g. that do not have non-ASCII characters). Maybe it is possible to obtain a list of encodings that may be correct (possible) for a given string? I'm looking for some other way than trying to decode/encode and wait for an exception. A: Chardet does a educated guess. Read the FAQ before you use it!
Smart way to find out string encoding?
I wonder whether it is possible to find what is the encoding of string? I know that it may be impossible for some strings (e.g. that do not have non-ASCII characters). Maybe it is possible to obtain a list of encodings that may be correct (possible) for a given string? I'm looking for some other way than trying to decode/encode and wait for an exception.
[ "Chardet does a educated guess. Read the FAQ before you use it!\n" ]
[ 15 ]
[]
[]
[ "character_encoding", "encoding", "python" ]
stackoverflow_0003608954_character_encoding_encoding_python.txt
Q: Where's the Python 2.6.6 Mac OS X Installer Disk Image? Python 2.6.6 was released on August 24, 2010. However, there isn't a Mac OS X Installer Disk Image. Is there a Mac OS X Installer Disk Image available for Python 2.6.6? A: [ORIGINAL: Unfortunately, the official python.org OS X installer for 2.6.6 is not yet available. I expect it should be available soon.] UPDATE: As of 2010-08-31, it is available here. The installer image you mention in your own answer is one produced by a daily testing buildbot, not by the python.org core developer for OS X, so it should not be considered the official installer. A: The installer can now be downloaded at http://www.python.org/download/releases/2.6.6/ A: After a little searching, I did find python-2.6.6-macosx10.3-2010-08-24.dmg available from the daily-dmg Python page. Update: As Ned Deily states in his answer, the daily-dmg listed above is not the official Python.org Mac OS X Installer Disk Image.
Where's the Python 2.6.6 Mac OS X Installer Disk Image?
Python 2.6.6 was released on August 24, 2010. However, there isn't a Mac OS X Installer Disk Image. Is there a Mac OS X Installer Disk Image available for Python 2.6.6?
[ "[ORIGINAL: Unfortunately, the official python.org OS X installer for 2.6.6 is not yet available. I expect it should be available soon.]\nUPDATE: As of 2010-08-31, it is available here.\nThe installer image you mention in your own answer is one produced by a daily testing buildbot, not by the python.org core devel...
[ 1, 1, 0 ]
[]
[]
[ "installation", "python", "python_2.6" ]
stackoverflow_0003604669_installation_python_python_2.6.txt