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: What's the difference between quantize() and str.format()? I don't mean what's the technical difference, but rather, what's the faster/more logical or Pythonic, etc. way to do this: def __quantized_price(self): TWOPLACES = Decimal(10) ** -2 return self.price.quantize(TWOPLACES) or def __formatted_price(self): TWOPLACES = Decimal(10) ** -2 return '{0:.2f}'.format(self.price) They seem to be exactly the same so I'm just wondering why they created quantize when A: Decimal.quantize returns a new Decimal that has a different value. ''.format() formats a string. In this particular case printing the result yields the same output. Other than that they are totally different operations returning totally different types.
What's the difference between quantize() and str.format()?
I don't mean what's the technical difference, but rather, what's the faster/more logical or Pythonic, etc. way to do this: def __quantized_price(self): TWOPLACES = Decimal(10) ** -2 return self.price.quantize(TWOPLACES) or def __formatted_price(self): TWOPLACES = Decimal(10) ** -2 return '{0:.2f}'.format(self.price) They seem to be exactly the same so I'm just wondering why they created quantize when
[ "Decimal.quantize returns a new Decimal that has a different value.\n''.format() formats a string. \nIn this particular case printing the result yields the same output. Other than that they are totally different operations returning totally different types. \n" ]
[ 8 ]
[]
[]
[ "django", "python", "quantization", "string" ]
stackoverflow_0002015359_django_python_quantization_string.txt
Q: Trying to get a solid Python install working on my Mac? I have Mac OSX 10.5.8 with Xcode installed. I want to avoid MacPorts and want to just get a solid Python install foundation so I can then move on to mess with Django and other things. I want to use Buildout with my Python applications. I have installed binary Python 2.6.4 from the official site and installed this. Following other advice I have put this in my ~/.bash_profile file: export PATH=/usr/local/bin:$PATH So, when I do a which python it shows /usr/local/bin/python. And, when I do a python -V it shows Python 2.6.4 - this all seems great. I've looked inside the /usr/local/bin/ folder and, among other things, I seem to have the correct stuff pointing to Python 2.6: python -> ../../../Library/Frameworks/Python.framework/Versions/2.6/bin/python BUT, when I do an easy_install of virtualenv (that I want to use with Buildout) it seems to install it in /Library/Python/2.5/site-packages/virtualenv-1.4.3-py2.5.egg ...which is Python 2.5? Also, when I setup my Buildout folder using virtualenv, in there the .Python symlink is going to: .Python -> /System/Library/Frameworks/Python.framework/Versions/2.5/Python Why is this? I don't understand this. How can I get it all pointing to the correct Python 2.6? Thank you so much for any answers, it's annoying the hell out of me. Cheers. A: Firstly, there's absolutely no need to install a new version of Python to work on Django in Leopard. The stock Python 2.5 works absolutely fine, and Django is 100% compatible with that version. Secondly, if you do want to use virtualenv with a different version of Python other than the system default, you simply need to tell it when you create the virtualenv: virtualenv --python=/path/to/python/2.6 virtualenvname A: When you install a new Python instance, you also need to install a new copy of easy_install for it. Follow the instructions for either the classic setuptools version or the newer Distribute. In either case, for the python.org 2.6.4 on OS X the easy_install script will be installed in /Library/Frameworks/Python.framework/Versions/2.6/bin which should come before /usr/bin on your shell $PATH. A: Personally, what I do is leave my system python completely as is. I use the following to install 2.4, 2.5 and 2.6 versions of Python: Use a buildout from the plone collective to get python2.{4,5,6} installed with easy_install and PIL (including libjpeg support) Checkout the python buildout files from the plone collective. I like to put it in /home/dev/python-buildout # svn co http://svn.plone.org/svn/collective/buildout/python /home/dev/python-buildout Add a new local.cfg file into the src directory. This is where you specify what you want to build. Use the following in your buildout file: [buildout] extends = base.cfg readline.cfg libjpeg.cfg python24.cfg python25.cfg python26.cfg links.cfg parts = ${buildout:base-parts} ${buildout:readline-parts} ${buildout:libjpeg-parts} ${buildout:python24-parts} ${buildout:python25-parts} ${buildout:python26-parts} ${buildout:links-parts} Bootstrap with your system python and then run the buildout. # python bootstrap.py # ./bin/buildout -c src/local.cfg When everything has been compiled, you should have a new python binaries here: /home/dev/python-buildout/src/python-2.{4,5,6}/bin/python To use them, either add the bin directory to your path, or source the 'activate' script in the bin directory, which will set it as the active python in your current shell daniel@madmax # which python /usr/bin/python daniel@madmax # python -V Python 2.6.1 daniel@madmax # source /home/dev/python-buildout/src/python-2.4/bin/activate (python-2.4)daniel@madmax # which python /home/dev/python-buildout/src/python-2.4/bin/python (python-2.4)daniel@madmax # python -V Python 2.4.6 daniel@madmax # source /home/dev/python-buildout/src/python-2.6/bin/activate (python-2.6)daniel@madmax # which python /home/dev/python-buildout/src/python-2.6/bin/python (python-2.6)daniel@madmax # python -V Python 2.6.4 For each project I'm working on, I tend to create a new virtual environment, using no-site-packages and the appropriate version of Python. A: PirosBOX:~ piros$ python -V Python 2.5.1 Have OSX 10.5.8 and i write django apps fine :D The important thing is to get the SVN release of Django, better! A: I found the following two links particularly useful when I had to do it: http://jessenoller.com/2009/03/16/so-you-want-to-use-python-on-the-mac/ http://blog.captnswing.net/2009/04/19/python-mod_wsgi-64bit-mac-os-x-105/
Trying to get a solid Python install working on my Mac?
I have Mac OSX 10.5.8 with Xcode installed. I want to avoid MacPorts and want to just get a solid Python install foundation so I can then move on to mess with Django and other things. I want to use Buildout with my Python applications. I have installed binary Python 2.6.4 from the official site and installed this. Following other advice I have put this in my ~/.bash_profile file: export PATH=/usr/local/bin:$PATH So, when I do a which python it shows /usr/local/bin/python. And, when I do a python -V it shows Python 2.6.4 - this all seems great. I've looked inside the /usr/local/bin/ folder and, among other things, I seem to have the correct stuff pointing to Python 2.6: python -> ../../../Library/Frameworks/Python.framework/Versions/2.6/bin/python BUT, when I do an easy_install of virtualenv (that I want to use with Buildout) it seems to install it in /Library/Python/2.5/site-packages/virtualenv-1.4.3-py2.5.egg ...which is Python 2.5? Also, when I setup my Buildout folder using virtualenv, in there the .Python symlink is going to: .Python -> /System/Library/Frameworks/Python.framework/Versions/2.5/Python Why is this? I don't understand this. How can I get it all pointing to the correct Python 2.6? Thank you so much for any answers, it's annoying the hell out of me. Cheers.
[ "Firstly, there's absolutely no need to install a new version of Python to work on Django in Leopard. The stock Python 2.5 works absolutely fine, and Django is 100% compatible with that version.\nSecondly, if you do want to use virtualenv with a different version of Python other than the system default, you simply need to tell it when you create the virtualenv: \nvirtualenv --python=/path/to/python/2.6 virtualenvname\n\n", "When you install a new Python instance, you also need to install a new copy of easy_install for it. Follow the instructions for either the classic setuptools version or the newer Distribute. In either case, for the python.org 2.6.4 on OS X the easy_install script will be installed in /Library/Frameworks/Python.framework/Versions/2.6/bin which should come before /usr/bin on your shell $PATH.\n", "Personally, what I do is leave my system python completely as is.\nI use the following to install 2.4, 2.5 and 2.6 versions of Python:\nUse a buildout from the plone collective to get python2.{4,5,6} installed with easy_install and PIL (including libjpeg support) \nCheckout the python buildout files from the plone collective. I like to put it in /home/dev/python-buildout\n# svn co http://svn.plone.org/svn/collective/buildout/python /home/dev/python-buildout\n\nAdd a new local.cfg file into the src directory. This is where you specify what you want to build. Use the following in your buildout file:\n[buildout] \nextends = \n base.cfg \n readline.cfg \n libjpeg.cfg \n python24.cfg \n python25.cfg\n python26.cfg\n links.cfg \n\nparts = \n ${buildout:base-parts} \n ${buildout:readline-parts} \n ${buildout:libjpeg-parts} \n ${buildout:python24-parts} \n ${buildout:python25-parts} \n ${buildout:python26-parts} \n ${buildout:links-parts} \n\nBootstrap with your system python and then run the buildout.\n# python bootstrap.py \n# ./bin/buildout -c src/local.cfg\n\nWhen everything has been compiled, you should have a new python binaries here:\n/home/dev/python-buildout/src/python-2.{4,5,6}/bin/python\n\nTo use them, either add the bin directory to your path, or source the 'activate' script in the bin directory, which will set it as the active python in your current shell\ndaniel@madmax # which python \n/usr/bin/python \ndaniel@madmax # python -V \nPython 2.6.1 \n\ndaniel@madmax # source /home/dev/python-buildout/src/python-2.4/bin/activate\n(python-2.4)daniel@madmax # which python \n/home/dev/python-buildout/src/python-2.4/bin/python \n(python-2.4)daniel@madmax # python -V \nPython 2.4.6 \n\ndaniel@madmax # source /home/dev/python-buildout/src/python-2.6/bin/activate\n(python-2.6)daniel@madmax # which python \n/home/dev/python-buildout/src/python-2.6/bin/python \n(python-2.6)daniel@madmax # python -V \nPython 2.6.4\n\nFor each project I'm working on, I tend to create a new virtual environment, using no-site-packages and the appropriate version of Python. \n", "PirosBOX:~ piros$ python -V\nPython 2.5.1\nHave OSX 10.5.8 and i write django apps fine :D\nThe important thing is to get the SVN release of Django, better!\n", "I found the following two links particularly useful when I had to do it:\nhttp://jessenoller.com/2009/03/16/so-you-want-to-use-python-on-the-mac/\nhttp://blog.captnswing.net/2009/04/19/python-mod_wsgi-64bit-mac-os-x-105/\n" ]
[ 2, 1, 0, 0, 0 ]
[]
[]
[ "buildout", "installation", "macos", "python", "unix" ]
stackoverflow_0002012959_buildout_installation_macos_python_unix.txt
Q: SQLAlchemy filter query by related object Using SQLAlchemy, I have a one to many relation with two tables - users and scores. I am trying to query the top 10 users sorted by their aggregate score over the past X amount of days. users: id user_name score scores: user score_amount created My current query is: top_users = DBSession.query(User).options(eagerload('scores')).filter_by(User.scores.created > somedate).order_by(func.sum(User.scores).desc()).all() I know this is clearly not correct, it's just my best guess. However, after looking at the documentation and googling I cannot find an answer. EDIT: Perhaps it would help if I sketched what the MySQL query would look like: SELECT user.*, SUM(scores.amount) as score_increase FROM user LEFT JOIN scores ON scores.user_id = user.user_id WITH scores.created_at > someday ORDER BY score_increase DESC A: The single-joined-row way, with a group_by added in for all user columns although MySQL will let you group on just the "id" column if you choose: sess.query(User, func.sum(Score.amount).label('score_increase')).\ join(User.scores).\ filter(Score.created_at > someday).\ group_by(User).\ order_by("score increase desc") Or if you just want the users in the result: sess.query(User).\ join(User.scores).\ filter(Score.created_at > someday).\ group_by(User).\ order_by(func.sum(Score.amount)) The above two have an inefficiency in that you're grouping on all columns of "user" (or you're using MySQL's "group on only a few columns" thing, which is MySQL only). To minimize that, the subquery approach: subq = sess.query(Score.user_id, func.sum(Score.amount).label('score_increase')).\ filter(Score.created_at > someday).\ group_by(Score.user_id).subquery() sess.query(User).join((subq, subq.c.user_id==User.user_id)).order_by(subq.c.score_increase) An example of the identical scenario is in the ORM tutorial at: http://docs.sqlalchemy.org/en/latest/orm/tutorial.html#selecting-entities-from-subqueries A: You will need to use a subquery in order to compute the aggregate score for each user. Subqueries are described here: http://www.sqlalchemy.org/docs/05/ormtutorial.html?highlight=subquery#using-subqueries A: I am assuming the column (not the relation) you're using for the join is called Score.user_id, so change it if this is not the case. You will need to do something like this: DBSession.query(Score.user_id, func.sum(Score.score_amount).label('total_score')).group_by(Score.user_id).filter(Score.created > somedate).order_by('total_score DESC')[:10] However this will result in tuples of (user_id, total_score). I'm not sure if the computed score is actually important to you, but if it is, you will probably want to do something like this: users_scores = [] q = DBSession.query(Score.user_id, func.sum(Score.score_amount).label('total_score')).group_by(Score.user_id).filter(Score.created > somedate).order_by('total_score DESC')[:10] for user_id, total_score in q: user = DBSession.query(User) users_scores.append((user, total_score)) This will result in 11 queries being executed, however. It is possible to do it all in a single query, but due to various limitations in SQLAlchemy, it will likely create a very ugly multi-join query or subquery (dependent on engine) and it won't be very performant. If you plan on doing something like this often and you have a large amount of scores, consider denormalizing the current score onto the user table. It's more work to upkeep, but will result in a single non-join query like: DBSession.query(User).order_by(User.computed_score.desc()) Hope that helps.
SQLAlchemy filter query by related object
Using SQLAlchemy, I have a one to many relation with two tables - users and scores. I am trying to query the top 10 users sorted by their aggregate score over the past X amount of days. users: id user_name score scores: user score_amount created My current query is: top_users = DBSession.query(User).options(eagerload('scores')).filter_by(User.scores.created > somedate).order_by(func.sum(User.scores).desc()).all() I know this is clearly not correct, it's just my best guess. However, after looking at the documentation and googling I cannot find an answer. EDIT: Perhaps it would help if I sketched what the MySQL query would look like: SELECT user.*, SUM(scores.amount) as score_increase FROM user LEFT JOIN scores ON scores.user_id = user.user_id WITH scores.created_at > someday ORDER BY score_increase DESC
[ "The single-joined-row way, with a group_by added in for all user columns although MySQL will let you group on just the \"id\" column if you choose:\n sess.query(User, func.sum(Score.amount).label('score_increase')).\\\n join(User.scores).\\\n filter(Score.created_at > someday).\\\n group_by(User).\\\n order_by(\"score increase desc\")\n\nOr if you just want the users in the result:\nsess.query(User).\\\n join(User.scores).\\\n filter(Score.created_at > someday).\\\n group_by(User).\\\n order_by(func.sum(Score.amount))\n\nThe above two have an inefficiency in that you're grouping on all columns of \"user\" (or you're using MySQL's \"group on only a few columns\" thing, which is MySQL only). To minimize that, the subquery approach:\nsubq = sess.query(Score.user_id, func.sum(Score.amount).label('score_increase')).\\\n filter(Score.created_at > someday).\\\n group_by(Score.user_id).subquery()\nsess.query(User).join((subq, subq.c.user_id==User.user_id)).order_by(subq.c.score_increase)\n\nAn example of the identical scenario is in the ORM tutorial at: http://docs.sqlalchemy.org/en/latest/orm/tutorial.html#selecting-entities-from-subqueries\n", "You will need to use a subquery in order to compute the aggregate score for each user. Subqueries are described here: http://www.sqlalchemy.org/docs/05/ormtutorial.html?highlight=subquery#using-subqueries\n", "I am assuming the column (not the relation) you're using for the join is called Score.user_id, so change it if this is not the case.\nYou will need to do something like this:\nDBSession.query(Score.user_id, func.sum(Score.score_amount).label('total_score')).group_by(Score.user_id).filter(Score.created > somedate).order_by('total_score DESC')[:10]\n\nHowever this will result in tuples of (user_id, total_score). I'm not sure if the computed score is actually important to you, but if it is, you will probably want to do something like this:\nusers_scores = []\nq = DBSession.query(Score.user_id, func.sum(Score.score_amount).label('total_score')).group_by(Score.user_id).filter(Score.created > somedate).order_by('total_score DESC')[:10]\nfor user_id, total_score in q:\n user = DBSession.query(User)\n users_scores.append((user, total_score))\n\nThis will result in 11 queries being executed, however. It is possible to do it all in a single query, but due to various limitations in SQLAlchemy, it will likely create a very ugly multi-join query or subquery (dependent on engine) and it won't be very performant.\nIf you plan on doing something like this often and you have a large amount of scores, consider denormalizing the current score onto the user table. It's more work to upkeep, but will result in a single non-join query like:\nDBSession.query(User).order_by(User.computed_score.desc())\n\nHope that helps.\n" ]
[ 22, 1, 0 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0002010454_python_sqlalchemy.txt
Q: Custom Django template tag to look up a string username and return it as a user object I use some third-party template tags in my Django Application (maintained elsewhere) that return a username as a string I can access in my templates like this. {% for user in gr.user.foll.list %} {{user}} Trouble is because {{user}} is returned as a string - I need to convert into a Django User Object, if it exists in the Django DB, or set a varible unRegistered if not so I can do things like: { user.get_profile.about }} # get profile information So I thought I would write my first Django Template Tag so I could use it like this: {% webapp_user_lookup user %} # my custom tag {% ifnot unRegistered %} {{ user.get_profile.about }} # get profile information - would fail with a string {% endifnot %} {% endfor %} The code I use elsewhere to look up a user in a view is: try: user = User.objects.get(username__iexact=user) unRegistered = False if not other_user.is_active: unRegistered = True except: unRegistered = True However looking at the Django Template tag examples I'm having trouble understanding how best to structure the custom template tag, to take my string username - and send back the results as an object if they exist, or set a varible if not and the original string. I'd really like to better understand how the structure works, and if I need a 'class' and if so, why. (I'm new to programming). A: use a template filter like so: {{username|get_user}} in your user_template_tags.py: from django import template from django.contrib.auth.models import User register = template.Library() ######################## def get_user(username): try: user = User.objects.get(username__iexact=username) except User.DoesNotExist: user = User.objects.none() return user register.filter('get_user',get_user) then in your template you can do something like: {% with username|getuser as user %} {% if user %}DO USER STUFF {% else %}DO UNREGISTERED STUFF {% endif %} {% endwith %}
Custom Django template tag to look up a string username and return it as a user object
I use some third-party template tags in my Django Application (maintained elsewhere) that return a username as a string I can access in my templates like this. {% for user in gr.user.foll.list %} {{user}} Trouble is because {{user}} is returned as a string - I need to convert into a Django User Object, if it exists in the Django DB, or set a varible unRegistered if not so I can do things like: { user.get_profile.about }} # get profile information So I thought I would write my first Django Template Tag so I could use it like this: {% webapp_user_lookup user %} # my custom tag {% ifnot unRegistered %} {{ user.get_profile.about }} # get profile information - would fail with a string {% endifnot %} {% endfor %} The code I use elsewhere to look up a user in a view is: try: user = User.objects.get(username__iexact=user) unRegistered = False if not other_user.is_active: unRegistered = True except: unRegistered = True However looking at the Django Template tag examples I'm having trouble understanding how best to structure the custom template tag, to take my string username - and send back the results as an object if they exist, or set a varible if not and the original string. I'd really like to better understand how the structure works, and if I need a 'class' and if so, why. (I'm new to programming).
[ "use a template filter like so:\n{{username|get_user}}\n\nin your user_template_tags.py:\nfrom django import template\nfrom django.contrib.auth.models import User\n\nregister = template.Library()\n\n########################\n\ndef get_user(username):\n try:\n user = User.objects.get(username__iexact=username)\n except User.DoesNotExist: \n user = User.objects.none()\n return user\n\nregister.filter('get_user',get_user)\n\nthen in your template you can do something like:\n{% with username|getuser as user %}\n{% if user %}DO USER STUFF\n{% else %}DO UNREGISTERED STUFF\n{% endif %}\n{% endwith %}\n\n" ]
[ 4 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0002015740_django_django_templates_python.txt
Q: Deploying Pylons with Nginx reverse proxy? Is there a tutorial on how to deploy Pylons with Nginx? I've been able to start nginx and then serve pylons to :8080 with paster serve development.ini However, I can't seem to do other stuff as pylons locks me into that serve mode. If I try to CTRL+Z out of pylons serving to do other stuff on my server, pylons goes down. There must be a different method of deployment. PS - I've done all this: http://wiki.pylonshq.com/display/pylonscookbook/Running+Pylons+with+NGINX?showComments=true#comments I just have no clue what to do with the Pylons app other than paster serve. Not sure if tehre is a different method. A: Run Pylons in daemon mode. paster serve development.ini --daemon A: Running Pylons with nginx tutorial found here: wiki.pylonshq.com/display/pylonscookbook/Running+Pylons+with+NGINX Pylons on Nginx with Memcached and SSI: http://www.reshetseret.com/app/blog/?p=3 UPDATE: link is broken, here is google cached version: http://webcache.googleusercontent.com/search?q=cache:http://www.reshetseret.com/app/blog/
Deploying Pylons with Nginx reverse proxy?
Is there a tutorial on how to deploy Pylons with Nginx? I've been able to start nginx and then serve pylons to :8080 with paster serve development.ini However, I can't seem to do other stuff as pylons locks me into that serve mode. If I try to CTRL+Z out of pylons serving to do other stuff on my server, pylons goes down. There must be a different method of deployment. PS - I've done all this: http://wiki.pylonshq.com/display/pylonscookbook/Running+Pylons+with+NGINX?showComments=true#comments I just have no clue what to do with the Pylons app other than paster serve. Not sure if tehre is a different method.
[ "Run Pylons in daemon mode.\npaster serve development.ini --daemon\n\n", "Running Pylons with nginx tutorial found here:\nwiki.pylonshq.com/display/pylonscookbook/Running+Pylons+with+NGINX\nPylons on Nginx with Memcached and SSI:\nhttp://www.reshetseret.com/app/blog/?p=3\nUPDATE: link is broken, here is google cached version:\nhttp://webcache.googleusercontent.com/search?q=cache:http://www.reshetseret.com/app/blog/\n" ]
[ 5, 2 ]
[]
[]
[ "nginx", "paster", "pylons", "python" ]
stackoverflow_0001071088_nginx_paster_pylons_python.txt
Q: Search a file for strings from a second file I have two files. The first file contains a list of 6 character keys (SA0001, SA1001, etc.). The second file contains a list of dates and amounts where the first six positions will match the key in the first file. I want to verify that every key in the first file has at least one match in the second file. There may be more than one match which is okay and there may be records in the second file with no key in the first file which is also okay. So basically a loop within a loop. The problem arises when I want to break out of the inner loop after the first match because the second file could be quite large. It prints out the "found" message correctly and breaks, but it won't print the "not found" message if it reaches the end of the second file with out finding a match. My code so far is: unvalues = open("file1.txt", "r") newfunds = open("file2.txt", "r").readlines() i = 1 for line in newfunds: line = line.strip() for line2 in iter(unvalues.readline, ""): try: if line == line2[:6]: print "%s: Matching %s to %s for date %s" % (i, line, line2[:6], line2[6:14]) break except StopIteration: print "%s: No match for %s" % (i, line) i += 1 unvalues.seek(0) A: Use sets instead: set1=set(line[:6] for line in open('file1.txt')) set2=set(line[:6] for line in open('file2.txt')) not_found = set1 - set2 if not_found: print "Some keys not found: " + ', '.join(not_found) A: first_file=open("file1.txt","r") #save all items from first file into a set first_file_items=set(line.strip() for line in first_file) second_file=open("file2.txt","r") for line in second_file: if line[:6] in first_file_items: #if this is item from the first file, remove it from the set first_file_items.remove(line[:6]) #when nothing is left in the set, we found everything if not first_file_items: break if first_file_items: print "Elements in first file but not in second", first_file_items A: I don't think break; throws a StopIteration. You generally don't want to use exceptions for flow control like that. A: Go through each file once, adding each record to a hash with value equal to 1. Then make sure that the keys of the first hash are a subset of the keys of the second. hashes = [] for f in ["file1.txt","file2.txt"]: lines = open(f,"r").readlines() hash = {} for line in lines: hash[line[:6] = 1 hashes.append(hash) set_keys1 = set(hashes[0].keys()) set_keys2 = set(hashes[1].keys()) assert(set_keys1.issubset(set_keys2)) A: I think this might be closer to what you want: unvalues = dict((line[:6], line[6:14]) for line in open("file1.txt", "r")) newfunds = [line for line in open("file2.txt", "r")] for i, line in enumerate(newfunds): key = line.strip() if key in unvalues: v = unvalues[key] print "%s: Matching %s to %s for date %s" % (i+1, line, key, v) else: print "%s: No match for %s" % (i+1, line) A: You cannot (and need not) catch the StopIteration exception that occurs when the iterator is finished, because it gets caught by the for loop automatically. To do what you appear to be trying to do, you could use an else block after your for block, e.g. you could replace your inner loop with this: for line2 in iter(unvalues.readline, ""): if line == line2[:6]: print "%s: Matching %s to %s for date %s" % (i, line, line2[:6], line2[6:14]) break else: print "%s: No match for %s" % (i, line) The else block is executed when the for loop finishes without the break statement getting hit. However, you may well find that one of the other approaches using sets is quicker. A: from collections import defaultdict unvalues = open("file1.txt", "r").readlines() newfunds = open("file2.txt", "r").readlines() unvals = defaultdict(int) for val in unvalues: unvals[val] = 0 for line in newfunds: line = line.strip() if line[:6] in unvals.keys(): unvals[line[:6]] += 1 for k in unvals.keys(): if unvals[k] == 0: print "Match Not Found For %s" % k might give you a good starting point for what you want to achieve, without being terribly messy. This gives you the performance advantage of only looping through each data set individually. As a quick addendum, if you want line numbers, rather than building a counting variable outside the loop and incrementing it, try this instead: for i, line in enumerate(newfunds): enumerate() basically zips a sequential integer iterator with your list to produce the desired result without unnecessary counting operations. A: Another approach using sets keys = set(line[:6] for line in open('file.txt')) missing = set(value[:6] for value in open('file2.txt') if value[:6] not in keys) if missing: print "Keys Missing " + ', '.join(missing)
Search a file for strings from a second file
I have two files. The first file contains a list of 6 character keys (SA0001, SA1001, etc.). The second file contains a list of dates and amounts where the first six positions will match the key in the first file. I want to verify that every key in the first file has at least one match in the second file. There may be more than one match which is okay and there may be records in the second file with no key in the first file which is also okay. So basically a loop within a loop. The problem arises when I want to break out of the inner loop after the first match because the second file could be quite large. It prints out the "found" message correctly and breaks, but it won't print the "not found" message if it reaches the end of the second file with out finding a match. My code so far is: unvalues = open("file1.txt", "r") newfunds = open("file2.txt", "r").readlines() i = 1 for line in newfunds: line = line.strip() for line2 in iter(unvalues.readline, ""): try: if line == line2[:6]: print "%s: Matching %s to %s for date %s" % (i, line, line2[:6], line2[6:14]) break except StopIteration: print "%s: No match for %s" % (i, line) i += 1 unvalues.seek(0)
[ "Use sets instead:\nset1=set(line[:6] for line in open('file1.txt'))\nset2=set(line[:6] for line in open('file2.txt'))\nnot_found = set1 - set2\nif not_found:\n print \"Some keys not found: \" + ', '.join(not_found)\n\n", "first_file=open(\"file1.txt\",\"r\")\n#save all items from first file into a set\nfirst_file_items=set(line.strip() for line in first_file)\nsecond_file=open(\"file2.txt\",\"r\")\nfor line in second_file:\n if line[:6] in first_file_items:\n #if this is item from the first file, remove it from the set\n first_file_items.remove(line[:6])\n #when nothing is left in the set, we found everything\n if not first_file_items: break\n\nif first_file_items:\n print \"Elements in first file but not in second\", first_file_items\n\n", "I don't think break; throws a StopIteration. \nYou generally don't want to use exceptions for flow control like that.\n", "Go through each file once, adding each record to a hash with value equal to 1. Then make sure that the keys of the first hash are a subset of the keys of the second.\nhashes = []\nfor f in [\"file1.txt\",\"file2.txt\"]:\n lines = open(f,\"r\").readlines()\n hash = {}\n for line in lines:\n hash[line[:6] = 1\n hashes.append(hash)\n\nset_keys1 = set(hashes[0].keys())\nset_keys2 = set(hashes[1].keys())\nassert(set_keys1.issubset(set_keys2))\n\n", "I think this might be closer to what you want:\nunvalues = dict((line[:6], line[6:14]) for line in open(\"file1.txt\", \"r\"))\nnewfunds = [line for line in open(\"file2.txt\", \"r\")]\nfor i, line in enumerate(newfunds):\n key = line.strip()\n if key in unvalues:\n v = unvalues[key]\n print \"%s: Matching %s to %s for date %s\" % (i+1, line, key, v)\n else:\n print \"%s: No match for %s\" % (i+1, line)\n\n", "You cannot (and need not) catch the StopIteration exception that occurs when the iterator is finished, because it gets caught by the for loop automatically. To do what you appear to be trying to do, you could use an else block after your for block, e.g. you could replace your inner loop with this:\nfor line2 in iter(unvalues.readline, \"\"):\n if line == line2[:6]:\n print \"%s: Matching %s to %s for date %s\" % (i, line, line2[:6], line2[6:14])\n break\nelse:\n print \"%s: No match for %s\" % (i, line)\n\nThe else block is executed when the for loop finishes without the break statement getting hit.\nHowever, you may well find that one of the other approaches using sets is quicker.\n", "from collections import defaultdict\n\nunvalues = open(\"file1.txt\", \"r\").readlines()\nnewfunds = open(\"file2.txt\", \"r\").readlines()\n\nunvals = defaultdict(int)\n\nfor val in unvalues:\n unvals[val] = 0\n\nfor line in newfunds:\n line = line.strip()\n\n if line[:6] in unvals.keys():\n unvals[line[:6]] += 1\n\nfor k in unvals.keys():\n if unvals[k] == 0:\n print \"Match Not Found For %s\" % k\n\nmight give you a good starting point for what you want to achieve, without being terribly messy. This gives you the performance advantage of only looping through each data set individually.\nAs a quick addendum, if you want line numbers, rather than building a counting variable outside the loop and incrementing it, try this instead:\nfor i, line in enumerate(newfunds):\n\nenumerate() basically zips a sequential integer iterator with your list to produce the desired result without unnecessary counting operations.\n", "Another approach using sets\nkeys = set(line[:6] for line in open('file.txt'))\nmissing = set(value[:6] for value in open('file2.txt') if value[:6] not in keys)\nif missing:\n print \"Keys Missing \" + ', '.join(missing)\n\n" ]
[ 3, 2, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002016006_python.txt
Q: Entity groups in Google App Engine Datastore So I have an app that if I'm honest doesn't really need transactional integrity (lots of updates, none of them critical). So I was planning on simply leaving entity groups by the wayside for now. But I'd still like to understand it (coming from a relational background). The way I see it, all queries for my app will be on a user by user basis. Therefore I do not need to group any higher than a user entity, according to the docs recommendations. But I wasn't planning on having a specific user entity, instead relying on UserProperty in the entities themselves. The way I see it, if I want transactions (on a per-user basis), I will need some kind of root user entity as the parent of all entities that are part of the hierarchy of her data, no matter how thin this entity would actually be i.e. basically no properties. Is this correct? Apologies for verboseness, I only really pinged what schema-less actually meant in practice tonight... A: The way I see it, if I want transactions (on a per-user basis), I will need some kind of root user entity as the parent of all entities that are part of the hierarchy of her data, no matter how thin this entity would actually be i.e. basically no properties. I wouldn't just create a root user entity and throw everything in its entity group. Think about what you need transactions for. If you have no properties on your user entity, what would you be using it in transactions with? I don't know about your data, but let's assume it's a blog system and you have users, posts and comments. The Post model holds a number_of_comments so you don't have to count them. You might want transactions to ensure when you create a comment, the number_of_comments property can be updated safely. In this case, it would be an unnecessary overhead to have all of a users posts and comments in a single entity group. Instead, you can post the comments in the same entity group as the post they belong to. There would be no need to put the posts into the same group as a user, and in fact this would be a bad idea, since comments posted in any of a users post would all be contending to write the same entity group. I wrote a short article about entity groups on my blog today. You might find it useful. A: You are essentially correct. You need to group them if you want transactional capability. However, you can group several entities together without creating an actual root entity, in the sense of an entity in the datastore. You instead create a sort of virtual root entity. One important use case of this feature is the ability to create a child object before you create it parent. You can create an entity with an ancestor path without first creating the parent entity. To do so, you create a Key for the ancestor using a kind and key name, then use it as the parent of the new entity. All entities with the same root ancestor belong to the same entity group, whether or not the root of the path represents an actual entity. That quote is from the same doc you linked to.
Entity groups in Google App Engine Datastore
So I have an app that if I'm honest doesn't really need transactional integrity (lots of updates, none of them critical). So I was planning on simply leaving entity groups by the wayside for now. But I'd still like to understand it (coming from a relational background). The way I see it, all queries for my app will be on a user by user basis. Therefore I do not need to group any higher than a user entity, according to the docs recommendations. But I wasn't planning on having a specific user entity, instead relying on UserProperty in the entities themselves. The way I see it, if I want transactions (on a per-user basis), I will need some kind of root user entity as the parent of all entities that are part of the hierarchy of her data, no matter how thin this entity would actually be i.e. basically no properties. Is this correct? Apologies for verboseness, I only really pinged what schema-less actually meant in practice tonight...
[ "\nThe way I see it, if I want transactions (on a per-user basis), I will need some kind of root user entity as the parent of all entities that are part of the hierarchy of her data, no matter how thin this entity would actually be i.e. basically no properties.\n\nI wouldn't just create a root user entity and throw everything in its entity group. Think about what you need transactions for. If you have no properties on your user entity, what would you be using it in transactions with?\nI don't know about your data, but let's assume it's a blog system and you have users, posts and comments. The Post model holds a number_of_comments so you don't have to count them. You might want transactions to ensure when you create a comment, the number_of_comments property can be updated safely.\nIn this case, it would be an unnecessary overhead to have all of a users posts and comments in a single entity group. Instead, you can post the comments in the same entity group as the post they belong to. There would be no need to put the posts into the same group as a user, and in fact this would be a bad idea, since comments posted in any of a users post would all be contending to write the same entity group.\nI wrote a short article about entity groups on my blog today. You might find it useful.\n", "You are essentially correct. You need to group them if you want transactional capability. However, you can group several entities together without creating an actual root entity, in the sense of an entity in the datastore. You instead create a sort of virtual root entity. One important use case of this feature is the ability to create a child object before you create it parent.\n\nYou can create an entity with an\n ancestor path without first creating\n the parent entity. To do so, you\n create a Key for the ancestor using a\n kind and key name, then use it as the\n parent of the new entity. All entities\n with the same root ancestor belong to\n the same entity group, whether or not\n the root of the path represents an\n actual entity.\n\nThat quote is from the same doc you linked to.\n" ]
[ 12, 3 ]
[]
[]
[ "google_app_engine", "python", "schemaless" ]
stackoverflow_0001515135_google_app_engine_python_schemaless.txt
Q: Python/Django: If 5 and 5.00 are different values (when expressed in Decimal), then If 5 and 5.00 and 5.000 are all different, then why does Django's decimal field save without the .00 even when I have decimal_places=2 ? More importantly, how can I save a value 5.00 as 5.00 in Django without using String. A: I think it would be more correct to say those are different representations of the same value '5'. Internally, the value saved (unless you're actually storing a string) is 5. When the value is displayed, ie converted to a string representation for the screen, it might be shown as 5, 5.00 or 5.000 but internally, it's still 5 The two decimal places do not appear (if I can put it that way) until the value is output. You can't save a number with 2 decimal places unless you use a string. A: You have an argument that Django ought to enforce a certain precision on its Python objects, but decimal_places is probably more about maximum precision. I believe precision is not stored in the database, so it will be lost in any case. In any case, if you want to enforce precision, use something like: Decimal(5).quantize(Decimal(10)**-DECIMAL_PLACES) You can overload the to_python method in a custom django.db.models.DecimalField to ensure that a python Decimal object with the correct precision is returned.
Python/Django: If 5 and 5.00 are different values (when expressed in Decimal), then
If 5 and 5.00 and 5.000 are all different, then why does Django's decimal field save without the .00 even when I have decimal_places=2 ? More importantly, how can I save a value 5.00 as 5.00 in Django without using String.
[ "I think it would be more correct to say those are different representations of the same value '5'. \nInternally, the value saved (unless you're actually storing a string) is 5.\nWhen the value is displayed, ie converted to a string representation for the screen, it might be shown as 5, 5.00 or 5.000 but internally, it's still 5\nThe two decimal places do not appear (if I can put it that way) until the value is output.\nYou can't save a number with 2 decimal places unless you use a string.\n", "You have an argument that Django ought to enforce a certain precision on its Python objects, but decimal_places is probably more about maximum precision. I believe precision is not stored in the database, so it will be lost in any case.\nIn any case, if you want to enforce precision, use something like: Decimal(5).quantize(Decimal(10)**-DECIMAL_PLACES)\nYou can overload the to_python method in a custom django.db.models.DecimalField to ensure that a python Decimal object with the correct precision is returned.\n" ]
[ 3, 2 ]
[]
[]
[ "decimal", "django", "python" ]
stackoverflow_0002016292_decimal_django_python.txt
Q: Creating several profile classes in django I'm getting started with django and I'd like to extend the basic django.contrib.auth.models.User class to create my own site profile(s). Here is described how to do it, got that. As far as I've understood it, you can only specify a single class as AUTH_PROFILE_MODULE in your settings.py. Now, if I create an extension class of my profile class like this class UserProfile(models.Model): user = models.ForeignKey(User, unique=True) somefield = models.CharField() class UserProfileExtended(UserProfile): extrafield = models.CharField() then I cannot make both of them profile classes, right? (I know, in this case you'd just add the extrafield to the superclass and drop the UserProfileExtended entirely. Just imagine you have so many fields in UserProfileExtended that you really want to split them up) Thanks for your help! A: There can be only one profile class. I guess I don't understand the scenario where you would want to split them up. In any case, AUTH_PROFILE_MODULE = "UserProfileExtended" should handle the inheritance correctly for the simple example you give.
Creating several profile classes in django
I'm getting started with django and I'd like to extend the basic django.contrib.auth.models.User class to create my own site profile(s). Here is described how to do it, got that. As far as I've understood it, you can only specify a single class as AUTH_PROFILE_MODULE in your settings.py. Now, if I create an extension class of my profile class like this class UserProfile(models.Model): user = models.ForeignKey(User, unique=True) somefield = models.CharField() class UserProfileExtended(UserProfile): extrafield = models.CharField() then I cannot make both of them profile classes, right? (I know, in this case you'd just add the extrafield to the superclass and drop the UserProfileExtended entirely. Just imagine you have so many fields in UserProfileExtended that you really want to split them up) Thanks for your help!
[ "There can be only one profile class. I guess I don't understand the scenario where you would want to split them up. In any case,\nAUTH_PROFILE_MODULE = \"UserProfileExtended\"\n\nshould handle the inheritance correctly for the simple example you give.\n" ]
[ 1 ]
[]
[]
[ "django", "profile", "python" ]
stackoverflow_0002016452_django_profile_python.txt
Q: Simple non-web based bug tracker There's a ton and and a half of questions and even more answers here concerning people looking for bug trackers. However all of them (that I found) seem to be about web based solutions. Since I'm working on a local project where I don't want to set up a web / DB server, and I don't want to use a hosted tracker either, I'm looking for something that runs locally. very preferably open-source pure Python or (at least) Windows executable no need for a database server (sqlite is obviously fine) Doesn't have to be fancy, just the basic bug / issue tracking functionality; just a little bit more than my current TODO text file or an Excel table. Any suggestions? A: I'm surprised nobody has mentioned Roundup. It meets all your criteria, including not requiring a web-based interface (as per your specification, and unlike the accepted answer which suggested Trac). Roundup is: Open source Pure Python Supports SQLite Not fancy, focuses on solid bug tracking And as a significant point of differentiation, it has command-line and email interfaces in addition to a web interface. It's very easy to get started - I suggest you take it for a spin. A: Trac might be a bit too over engineered, but you could still run it locally via tracd on localhost. It's: opensource. pure Python uses sqlite But as I said, might be too complex for your use case. Link: http://trac.edgewall.org A: If you don't need to share your bug tracker system with a team (i.e., it's okay to have it isolated to your computer) I would recommend using Tiddlywiki. Technically it's web-based, but it's entirely encapsulated within a single HTML document and requires no database or server whatsoever (only a web browser) so I think it follows the spirit of what you are wanting. It's extremely customizable since it's 100% HTML/CSS/javascript. I have been using a tiddlywiki as a project notebook for years, keeping track of my to-do list, bug list, and general project documentation in one centralized, cross-referenced place. You can also find all sorts of tiddlywikis that you can download pre-configured for productivity (for example, TeamTasks, MonkeyGTD, or GTDTiddlyWiki Plus). A: Maybe Fossil is of any use to you? It is actually a DVCS but it also integrates a bugtracker and wiki, very much like trac (although I like trac, don't get me wrong). And its webbased, on the other hand the installation is supossedly dead simple. A: Proprietary TestTrack (http://www.seapine.com/ttpro.html) has a client edition that will those things. We use it at work and I'm very happy using it. Maybe you can check out this wikipedia article for hints http://en.wikipedia.org/wiki/Comparison_of_issue_tracking_systems
Simple non-web based bug tracker
There's a ton and and a half of questions and even more answers here concerning people looking for bug trackers. However all of them (that I found) seem to be about web based solutions. Since I'm working on a local project where I don't want to set up a web / DB server, and I don't want to use a hosted tracker either, I'm looking for something that runs locally. very preferably open-source pure Python or (at least) Windows executable no need for a database server (sqlite is obviously fine) Doesn't have to be fancy, just the basic bug / issue tracking functionality; just a little bit more than my current TODO text file or an Excel table. Any suggestions?
[ "I'm surprised nobody has mentioned Roundup.\nIt meets all your criteria, including not requiring a web-based interface (as per your specification, and unlike the accepted answer which suggested Trac).\nRoundup is:\n\nOpen source\nPure Python\nSupports SQLite\nNot fancy, focuses on solid bug tracking\n\nAnd as a significant point of differentiation, it has command-line and email interfaces in addition to a web interface.\nIt's very easy to get started - I suggest you take it for a spin.\n", "Trac might be a bit too over engineered, but you could still run it locally via tracd on localhost.\nIt's:\n\nopensource.\npure Python\nuses sqlite\n\nBut as I said, might be too complex for your use case.\nLink: http://trac.edgewall.org\n", "If you don't need to share your bug tracker system with a team (i.e., it's okay to have it isolated to your computer) I would recommend using Tiddlywiki. Technically it's web-based, but it's entirely encapsulated within a single HTML document and requires no database or server whatsoever (only a web browser) so I think it follows the spirit of what you are wanting. It's extremely customizable since it's 100% HTML/CSS/javascript. I have been using a tiddlywiki as a project notebook for years, keeping track of my to-do list, bug list, and general project documentation in one centralized, cross-referenced place. You can also find all sorts of tiddlywikis that you can download pre-configured for productivity (for example, TeamTasks, MonkeyGTD, or GTDTiddlyWiki Plus).\n", "Maybe Fossil is of any use to you?\nIt is actually a DVCS but it also integrates a bugtracker and wiki, very much like trac (although I like trac, don't get me wrong). And its webbased, on the other hand the installation is supossedly dead simple.\n", "Proprietary TestTrack (http://www.seapine.com/ttpro.html) has a client edition that will those things. We use it at work and I'm very happy using it.\nMaybe you can check out this wikipedia article for hints \nhttp://en.wikipedia.org/wiki/Comparison_of_issue_tracking_systems \n" ]
[ 9, 8, 6, 2, 0 ]
[ "Do yourself a favor. Get over this \"must not be web based\" obsession, Install a local WAMP stack on your PC or on a LAN server. Now, you can install your own wiki. And something like Trac. I'd like to find an implementation of google code's bugtracker and integrated wiki thats runnable locally - Trac seems to be the closest.\nYou have also installed a local SVN server? Even for personal projects the ability to track changes over time. revert etc. and integration with Trac are too good to pass up even for purely 1 man projects.\n" ]
[ -13 ]
[ "bug_tracking", "non_web", "python", "windows" ]
stackoverflow_0001211463_bug_tracking_non_web_python_windows.txt
Q: What programs are used to build standalone desktop widgets that interact with online php and mysql? I have seen mention of Java and Python. I need something that can be installed on a users desktop without them having to also install Java or anything else. User simplicity is a must. This widget will log into an online php based calendar that accesses mySQL. Any pointers on what I should be reading up on? Python? Thanks! Joel Update: Thanks for the comments so far. This will eventually need to be for any OS, but certainly Windows. To clarify, I'm wanting something the user will download from me, install, and then it'll show up in the system tray (windows) For Mac-I guess it'll show up in the dashboard? A: Sounds like something like Adobe Air, Microsoft's Silverlight, or Appcelerators Titanium is what you want. A: Adobe Air is the popular solution to this problem these days A: The others here are basically right. You don't specify what the platform you want to put this on. You have a couple of options: Native program. This can be made to require no installation. This would be Win32/MFC and C/C++, or Cocoa and Objective-C. Not necessarily easy to program (fetching a web page in Win32?), not portable, but it will work. Python/Ruby/Perl/etc. These are easier, but require either the runtime, or the runtime to be bundled up in the application, which makes it rather large. Flash applications can bundle the runtime, I think. Java/.NET. A good way to do it, but they will need the runtime, which can't be put inside the executable. A widget. A special web page, recent OSes support it. See below. I would go with the widget, if possible. It's just HTML and JavaScript. They're easy to write, and work well. OS X, Vista, Windows 7, and Linux all have support for widgets and won't need additional software. Windows XP would need a runtime (like Yahoo! Widgets) to be installed first. Each OS does things slightly differently, so changes would have to be made to make a widget run in Dashboard in OS X and as a Gadget in Windows Vista/7. I hope this helps. I made a widget to interact with a web application that company made. I made is for OS X (my OS), and it was quite easy. It just uses XMLHttpRequest to load some XML, parses it out, and updates it's self. It's quite simple. The same server side code can serve any kind of widget, as well as real applications. A: Or Yahoo Widgets. now discontinued A: Should it be OS independent? Widgets for Apple's dashboard are just HTML, CSS and Javascript. A: Check out Tcl. Then use starkit/starpack or freewrap to generate your stand-alone app. Tcl gets little love from the general development community but it has a very friendly and dedicated community of users. Tcl developers can generally be reached at The tcler's wiki (wiki.tcl.tk) and the comp.lang.tcl newsgroup. And of course on stackoverflow.
What programs are used to build standalone desktop widgets that interact with online php and mysql?
I have seen mention of Java and Python. I need something that can be installed on a users desktop without them having to also install Java or anything else. User simplicity is a must. This widget will log into an online php based calendar that accesses mySQL. Any pointers on what I should be reading up on? Python? Thanks! Joel Update: Thanks for the comments so far. This will eventually need to be for any OS, but certainly Windows. To clarify, I'm wanting something the user will download from me, install, and then it'll show up in the system tray (windows) For Mac-I guess it'll show up in the dashboard?
[ "Sounds like something like Adobe Air, Microsoft's Silverlight, or Appcelerators Titanium is what you want.\n", "Adobe Air is the popular solution to this problem these days\n", "The others here are basically right. You don't specify what the platform you want to put this on. You have a couple of options:\n\nNative program. This can be made to require no installation. This would be Win32/MFC and C/C++, or Cocoa and Objective-C. Not necessarily easy to program (fetching a web page in Win32?), not portable, but it will work.\nPython/Ruby/Perl/etc. These are easier, but require either the runtime, or the runtime to be bundled up in the application, which makes it rather large. Flash applications can bundle the runtime, I think.\nJava/.NET. A good way to do it, but they will need the runtime, which can't be put inside the executable.\nA widget. A special web page, recent OSes support it. See below.\n\nI would go with the widget, if possible. It's just HTML and JavaScript. They're easy to write, and work well. OS X, Vista, Windows 7, and Linux all have support for widgets and won't need additional software. Windows XP would need a runtime (like Yahoo! Widgets) to be installed first.\nEach OS does things slightly differently, so changes would have to be made to make a widget run in Dashboard in OS X and as a Gadget in Windows Vista/7.\nI hope this helps. I made a widget to interact with a web application that company made. I made is for OS X (my OS), and it was quite easy. It just uses XMLHttpRequest to load some XML, parses it out, and updates it's self. It's quite simple. The same server side code can serve any kind of widget, as well as real applications.\n", "Or Yahoo Widgets. now discontinued\n", "Should it be OS independent? Widgets for Apple's dashboard are just HTML, CSS and Javascript.\n", "Check out Tcl. Then use starkit/starpack or freewrap to generate your stand-alone app. Tcl gets little love from the general development community but it has a very friendly and dedicated community of users.\nTcl developers can generally be reached at The tcler's wiki (wiki.tcl.tk) and the comp.lang.tcl newsgroup. And of course on stackoverflow.\n" ]
[ 3, 2, 1, 0, 0, 0 ]
[]
[]
[ "mysql", "php", "python", "widget" ]
stackoverflow_0002016609_mysql_php_python_widget.txt
Q: How can I auto-fill a paragraph in Eclipse? I would like to auto-fill a paragraph to 80 characters (or some other fixed width) in Eclipse. Is this possible via a keyboard command like in Emacs? Or is there maybe a plugin (I did not find anything on google)? Edit: I am not sure if this is relevant, but I need this for docstrings in Python code (using the PyDev plugin). A: You can wrap the paragraph in Pydev with Ctrl+2+w (see Pydev keybindings at: http://pydev.org/manual_adv_keybindings.html) A: Highlight the text, then press Ctrl-Shift-F, or open the context menu and select Source / Format.
How can I auto-fill a paragraph in Eclipse?
I would like to auto-fill a paragraph to 80 characters (or some other fixed width) in Eclipse. Is this possible via a keyboard command like in Emacs? Or is there maybe a plugin (I did not find anything on google)? Edit: I am not sure if this is relevant, but I need this for docstrings in Python code (using the PyDev plugin).
[ "You can wrap the paragraph in Pydev with Ctrl+2+w (see Pydev keybindings at: http://pydev.org/manual_adv_keybindings.html)\n", "Highlight the text, then press Ctrl-Shift-F, or open the context menu and select Source / Format.\n" ]
[ 6, 2 ]
[]
[]
[ "eclipse", "formatting", "python", "word_wrap" ]
stackoverflow_0000643422_eclipse_formatting_python_word_wrap.txt
Q: Have writen a program to extract text from a PDF in python, and now need to make it run for every PDF in the folder and save as a text file So far here is the code I have (it is working and extracting text as it should.) import pyPdf def getPDFContent(path): content = "" # Load PDF into pyPDF pdf = pyPdf.PdfFileReader(file(path, "rb")) # Iterate pages for i in range(0, pdf.getNumPages()): # Extract text from page and add to content content += pdf.getPage(i).extractText() + "\n" # Collapse whitespace content = " ".join(content.replace(u"\xa0", " ").strip().split()) return content print getPDFContent("/home/nick/TAM_work/TAM_pdfs/2006-1.pdf").encode("ascii", "ignore") I now need to add a for loop to get it to run on all PDF's in /TAM_pdfs, save the text as a CSV and (if possible) add something to count the pictures. Any help would be greatly appreciated. Thanks for looking. Matt A: Take a look at os.walk() A: The glob module can help you find all files in a single directory that match a wildcard pattern. A: for loop to get it to run on all PDF's in a directory: look at the glob module save the text as a CSV: look at the csv module count the pictures: look at the pyPDF module :-) Two comments on this statement: content = " ".join(content.replace(u"\xa0", " ").strip().split()) (1) It is not necessary to replace the NBSP (U+00A0) with a SPACE, because NBSP is (naturally) considered to be whitespace by unicode.split() (2) Using strip() is redundant: >>> u" foo bar ".split() [u'foo', u'bar'] >>>
Have writen a program to extract text from a PDF in python, and now need to make it run for every PDF in the folder and save as a text file
So far here is the code I have (it is working and extracting text as it should.) import pyPdf def getPDFContent(path): content = "" # Load PDF into pyPDF pdf = pyPdf.PdfFileReader(file(path, "rb")) # Iterate pages for i in range(0, pdf.getNumPages()): # Extract text from page and add to content content += pdf.getPage(i).extractText() + "\n" # Collapse whitespace content = " ".join(content.replace(u"\xa0", " ").strip().split()) return content print getPDFContent("/home/nick/TAM_work/TAM_pdfs/2006-1.pdf").encode("ascii", "ignore") I now need to add a for loop to get it to run on all PDF's in /TAM_pdfs, save the text as a CSV and (if possible) add something to count the pictures. Any help would be greatly appreciated. Thanks for looking. Matt
[ "Take a look at os.walk()\n", "The glob module can help you find all files in a single directory that match a wildcard pattern.\n", "for loop to get it to run on all PDF's in a directory: look at the glob module\nsave the text as a CSV: look at the csv module\ncount the pictures: look at the pyPDF module :-)\nTwo comments on this statement:\ncontent = \" \".join(content.replace(u\"\\xa0\", \" \").strip().split())\n\n(1) It is not necessary to replace the NBSP (U+00A0) with a SPACE, because NBSP is (naturally) considered to be whitespace by unicode.split()\n(2) Using strip() is redundant:\n>>> u\" foo bar \".split()\n[u'foo', u'bar']\n>>>\n\n" ]
[ 4, 0, 0 ]
[]
[]
[ "csv", "pdf", "python" ]
stackoverflow_0002016777_csv_pdf_python.txt
Q: Conditional statements in Eclipse templates Eclipse templates can automatically insert text and variables as you are coding. When variables are used with the ${variable} form, the value is inserted automatically. My question is whether you can add sections to these templates conditionally. Can you have a method definition template that will fill in multiple variables and add local definitions of them, but only if they are filled in? def method(${var1}, ${var2}, ${var3}): self.${var1} = ${var1} self.${var2} = ${var2} self.${var3} = ${var3} So, the ${var2} and ${var3} local variables would only exist if their definitions existed in the method definition? This question is specifically for Python development with PyDev but answers for other languages would be welcome too. A: It can be done through Jython scripting in Pydev in the latest nightly build (which will be 1.5.4). See http://pydev.org/download.html for details on getting it. Shortly, you can define a variable in scripting and program it in Jython to be how you want it to be (and you can update the templates cache on the fly after creating your variable). There are some variables defined by default like that at: http://github.com/aptana/Pydev/blob/master/plugins/org.python.pydev.jython/jysrc/pytemplate_defaults.py That module has comments on how to proceed (and you can use that module as an example). A: Not currently possible in eclipse editor templates. You can define custom VariableResolvers that generate whatever you would like. However, I don't think that would do what you're looking for. A variable resolver can return "", you'd have to have basically the entire template in the resolver; not terribly reusable in other templates. Sorry - I don't see any way to do that (though I'd love to have that capability).
Conditional statements in Eclipse templates
Eclipse templates can automatically insert text and variables as you are coding. When variables are used with the ${variable} form, the value is inserted automatically. My question is whether you can add sections to these templates conditionally. Can you have a method definition template that will fill in multiple variables and add local definitions of them, but only if they are filled in? def method(${var1}, ${var2}, ${var3}): self.${var1} = ${var1} self.${var2} = ${var2} self.${var3} = ${var3} So, the ${var2} and ${var3} local variables would only exist if their definitions existed in the method definition? This question is specifically for Python development with PyDev but answers for other languages would be welcome too.
[ "It can be done through Jython scripting in Pydev in the latest nightly build (which will be 1.5.4).\nSee http://pydev.org/download.html for details on getting it.\nShortly, you can define a variable in scripting and program it in Jython to be how you want it to be (and you can update the templates cache on the fly after creating your variable).\nThere are some variables defined by default like that at: http://github.com/aptana/Pydev/blob/master/plugins/org.python.pydev.jython/jysrc/pytemplate_defaults.py\nThat module has comments on how to proceed (and you can use that module as an example).\n", "Not currently possible in eclipse editor templates.\nYou can define custom VariableResolvers that generate whatever you would like. However, I don't think that would do what you're looking for.\nA variable resolver can return \"\", you'd have to have basically the entire template in the resolver; not terribly reusable in other templates.\nSorry - I don't see any way to do that (though I'd love to have that capability).\n" ]
[ 2, 1 ]
[]
[]
[ "eclipse", "pydev", "python", "templates" ]
stackoverflow_0001890330_eclipse_pydev_python_templates.txt
Q: How do you reload your Python source into the console window in Eclipse/Pydev? In other Python IDEs (PythonWin and Idle) it's possible to hit a key and have your current source file window reloaded into the console. I find this useful when experimenting with a piece of code; you can call functions from the console interactively and inspect data structures there. Is there a way to do this with Eclipse/Pydev? So far I've been making do with this hack in my source file: def relo(): execfile("/Path/To/Source.py", __builtins__) I call relo() in the console after I save changes to the source. But I'd much rather just tap a key. I'm using pydev 1.4.7.2843. This is somewhat related to this question, but I want to just reload the whole source file. A: You can do it with Ctrl+Alt+Enter on the latest Pydev for details on what Ctrl+Alt+Enter provides as it can do a number of things related to the interactive console. A: Use the revert option on the File menu. You can bind a key to it in Windows > Preferences > General > Keys. Edit: The reload(module) function will update packages in the interactive console. It's built in for python 2.x and in the imp module for 3.x. Python docs link: http://docs.python.org/3.1/library/imp.html?#imp.reload Couldn't find a way to run it by hotkey, I'd like to know if you find a way.
How do you reload your Python source into the console window in Eclipse/Pydev?
In other Python IDEs (PythonWin and Idle) it's possible to hit a key and have your current source file window reloaded into the console. I find this useful when experimenting with a piece of code; you can call functions from the console interactively and inspect data structures there. Is there a way to do this with Eclipse/Pydev? So far I've been making do with this hack in my source file: def relo(): execfile("/Path/To/Source.py", __builtins__) I call relo() in the console after I save changes to the source. But I'd much rather just tap a key. I'm using pydev 1.4.7.2843. This is somewhat related to this question, but I want to just reload the whole source file.
[ "You can do it with Ctrl+Alt+Enter on the latest Pydev for details on what Ctrl+Alt+Enter provides as it can do a number of things related to the interactive console.\n", "Use the revert option on the File menu.\nYou can bind a key to it in Windows > Preferences > General > Keys.\nEdit:\nThe reload(module) function will update packages in the interactive console. It's built in for python 2.x and in the imp module for 3.x.\nPython docs link: http://docs.python.org/3.1/library/imp.html?#imp.reload\nCouldn't find a way to run it by hotkey, I'd like to know if you find a way.\n" ]
[ 7, 1 ]
[]
[]
[ "pydev", "python" ]
stackoverflow_0001191018_pydev_python.txt
Q: Newbie needs help with Python Tutorial I am a newbie going through a byte of python (3.0). This is the first programming language I have ever used. I am stuck at the point where you make a simple program that creates a backup zip file (p.75). I'm running Windows 7 (64 bit) with python 3.1. Prior to this I installed GNUWin32 + sources, and added C:\Program Files(x86)\GnuWin32\bin to my Path enviornmental variable. This is the program: #!C:\Python31\mystuff # Filename : my_backup_v1.py import os import time # backing up a couple small files that I made source = [r'C:\AB\a', r'C:\AB\b'] #my back up directory target_dir = 'C:\\Backup' #name of back up file target = target_dir + os.sep + time.strftime('%Y%m%d%H%M%S') + '.zip' zip_command = "zip -qr {0} {1}".format(target,' '.join(source)) print(zip_command) if os.system(zip_command) == 0: print('Successful backup to', target) else: print('Backup failed!') print('source files are', source) print('target directory is', target_dir) print('target is', target) Output: zip -qr C:\Backup\20100106143030.zip C:\AB\a C:\AB\b Backup failed! source files are ['C:\\AB\\a', 'C:\\AB\\b'] target directory is C:\Backup target is C:\Backup\20100106143030.zip The Tutorial includes a little bit troubleshooting advice: copy and paste the zip_command in the python shell prompt to see if that atleast works: >>> zip -qr C:\Backup\20100106143030.zip C:\AB\a C:\AB\b SyntaxError: invalid syntax (<pyshell#17>, line 1) Since that didn't work, the tutorial said to read the GNUWin32 manual for additional help. I've looked through it and have yet to see anything that will help me out. To see if the zip function is working I did help(zip) and got the following: >>> help(zip) Help on class zip in module builtins: class zip(object) | zip(iter1 [,iter2 [...]]) --> zip object | | Return a zip object whose .__next__() method returns a tuple where | the i-th element comes from the i-th iterable argument. The .__next__() | method continues until the shortest iterable in the argument sequence | is exhausted and then it raises StopIteration. | | Methods defined here: | | __getattribute__(...) | x.__getattribute__('name') <==> x.name | | __iter__(...) | x.__iter__() <==> iter(x) | | __next__(...) | x.__next__() <==> next(x) | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __new__ = <built-in method __new__ of type object at 0x1E1B8D80> | T.__new__(S, ...) -> a new object with type S, a subtype of T Unfortuneatly I can not really understand the 'help' yet. However I played around a bit with the zip function to see how it works. >>> zip (r'C:AB\a') <zip object at 0x029CE8C8> So it appears that the zip function works, but I guess I'm not using it correctly. Please help me out, and keep in mind I haven't had much experience with programming yet. If you would like to view the tutorial you can find it at www.swaroopch.com/notes/Python . A: >>> zip -qr C:\Backup\20100106143030.zip C:\AB\a C:\AB\b sounds like a command you should type in your operating system's shell, not in python's shell. Maybe you can try os.system('zip -qr C:\Backup\20100106143030.zip C:\AB\a C:\AB\b') in the python shell... A: That's not giving you the help for the shell command zip, it's giving you the help for the python function zip, which is unrelated to zip file compression. A: The reason "zip -qr C:\Backup\20100106143030.zip C:\AB\a C:\AB\b" failed at the prompt is because in this case, "zip" is supposed to be a command you're sending the operating system... nothing to do with Python. This is a little confusing, I'm afraid - when you did "zip(r'C:AB\a')", you were using Python's built-in zip() function, which is unrelated to what you're trying to do. Do you have the proper directory struture? I mean, do C:\AB\a and C:\AB\b exist? Edit - You should copy/paste that long "zip" line to the command prompt (hit windows key + R, then type "cmd" and hit enter), to see if it works; not the Python shell. A: A couple suggestions for you to use to improve: Use the subprocess.call([command', 'arg', 'arg', 'arg']) command to call the external zip command. This will ensure that the command gets called correctly with data escaped properly. Use os.path.join to join path componenets together cleanly. This will also help prevent subtle bugs. Ensure your zip command works from the Command Prompt before trying it in python. -- Other than that, it looks pretty good. PS. zip() is a builtin, used for joining two iterables. Not for zipping files. Important: see Andrew's comment (copied here for reference): Looks like you should have done zip -qr C:\Backup\20100106143030.zip C:\AB\a C:\AB\b at the terminal prompt, not a python prompt. Does that help? – Andrew McGregor 3 mins ago
Newbie needs help with Python Tutorial
I am a newbie going through a byte of python (3.0). This is the first programming language I have ever used. I am stuck at the point where you make a simple program that creates a backup zip file (p.75). I'm running Windows 7 (64 bit) with python 3.1. Prior to this I installed GNUWin32 + sources, and added C:\Program Files(x86)\GnuWin32\bin to my Path enviornmental variable. This is the program: #!C:\Python31\mystuff # Filename : my_backup_v1.py import os import time # backing up a couple small files that I made source = [r'C:\AB\a', r'C:\AB\b'] #my back up directory target_dir = 'C:\\Backup' #name of back up file target = target_dir + os.sep + time.strftime('%Y%m%d%H%M%S') + '.zip' zip_command = "zip -qr {0} {1}".format(target,' '.join(source)) print(zip_command) if os.system(zip_command) == 0: print('Successful backup to', target) else: print('Backup failed!') print('source files are', source) print('target directory is', target_dir) print('target is', target) Output: zip -qr C:\Backup\20100106143030.zip C:\AB\a C:\AB\b Backup failed! source files are ['C:\\AB\\a', 'C:\\AB\\b'] target directory is C:\Backup target is C:\Backup\20100106143030.zip The Tutorial includes a little bit troubleshooting advice: copy and paste the zip_command in the python shell prompt to see if that atleast works: >>> zip -qr C:\Backup\20100106143030.zip C:\AB\a C:\AB\b SyntaxError: invalid syntax (<pyshell#17>, line 1) Since that didn't work, the tutorial said to read the GNUWin32 manual for additional help. I've looked through it and have yet to see anything that will help me out. To see if the zip function is working I did help(zip) and got the following: >>> help(zip) Help on class zip in module builtins: class zip(object) | zip(iter1 [,iter2 [...]]) --> zip object | | Return a zip object whose .__next__() method returns a tuple where | the i-th element comes from the i-th iterable argument. The .__next__() | method continues until the shortest iterable in the argument sequence | is exhausted and then it raises StopIteration. | | Methods defined here: | | __getattribute__(...) | x.__getattribute__('name') <==> x.name | | __iter__(...) | x.__iter__() <==> iter(x) | | __next__(...) | x.__next__() <==> next(x) | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __new__ = <built-in method __new__ of type object at 0x1E1B8D80> | T.__new__(S, ...) -> a new object with type S, a subtype of T Unfortuneatly I can not really understand the 'help' yet. However I played around a bit with the zip function to see how it works. >>> zip (r'C:AB\a') <zip object at 0x029CE8C8> So it appears that the zip function works, but I guess I'm not using it correctly. Please help me out, and keep in mind I haven't had much experience with programming yet. If you would like to view the tutorial you can find it at www.swaroopch.com/notes/Python .
[ ">>> zip -qr C:\\Backup\\20100106143030.zip C:\\AB\\a C:\\AB\\b \n\nsounds like a command you should type in your operating system's shell, not in python's shell. Maybe you can try \nos.system('zip -qr C:\\Backup\\20100106143030.zip C:\\AB\\a C:\\AB\\b') \n\nin the python shell...\n", "That's not giving you the help for the shell command zip, it's giving you the help for the python function zip, which is unrelated to zip file compression.\n", "The reason \"zip -qr C:\\Backup\\20100106143030.zip C:\\AB\\a C:\\AB\\b\" failed at the prompt is because in this case, \"zip\" is supposed to be a command you're sending the operating system... nothing to do with Python.\nThis is a little confusing, I'm afraid - when you did \"zip(r'C:AB\\a')\", you were using Python's built-in zip() function, which is unrelated to what you're trying to do.\nDo you have the proper directory struture? I mean, do C:\\AB\\a and C:\\AB\\b exist?\nEdit - You should copy/paste that long \"zip\" line to the command prompt (hit windows key + R, then type \"cmd\" and hit enter), to see if it works; not the Python shell.\n", "A couple suggestions for you to use to improve:\nUse the subprocess.call([command', 'arg', 'arg', 'arg']) command to call the external zip command. This will ensure that the command gets called correctly with data escaped properly.\nUse os.path.join to join path componenets together cleanly. This will also help prevent subtle bugs.\nEnsure your zip command works from the Command Prompt before trying it in python. \n--\nOther than that, it looks pretty good.\nPS. zip() is a builtin, used for joining two iterables. Not for zipping files.\n\nImportant: see Andrew's comment (copied here for reference):\nLooks like you should have done zip -qr C:\\Backup\\20100106143030.zip C:\\AB\\a C:\\AB\\b at the terminal prompt, not a python prompt. Does that help? – Andrew McGregor 3 mins ago\n" ]
[ 2, 1, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002017320_python.txt
Q: Python Thread Pause and Wait I have an array of threads. Each of them call the run method continuously. At the end of each run method I want them to pause and wait. How can I get the threads to execute one at a time, and then continue the loop when all are finished? I need them to ALWAYS execute in order (ie: 1, 2, 3, 4 - 1, 2, 3, 4...) I'm currently using threading.Event, but the results are inconsistent. Thanks UPDATE Thanks everybody for your answers so far. I'm writing something similar to Robocode in python. Players program a bot and the bots battle it out until one remains. After each "turn" the bots are "paused" then updated and drawn to the screen. Then they all start a new turn. Example: # Bot extends threading.Thread class DemoBot(Bot): def __init__(self): super(DemoBot, self).__init__() def run(self): while True: self.moveForward(100) self.turnLeft(90) As you can see, the bot is in an infinite loop. In the moveForward method, the bot would move forward 100px. But in order to update the screen correctly, I have to move once, pause, update, then move again. This is why I need to be able to "pause" a bot once its finished and have the program wait for the others before updating the screen. Hope that makes a little more sense. A: Your description seems to imply you don't want the threads to execute concurrently, which would bring into question why you're using threading in the first place. I sense two possible answers as to why you'd want to do this. The first possibility is that you are trying to prevent your threads from working on some sort of shared resource at the same time. If this is the case, you probably want to use threading.Lock or threading.RLock to lock your critical code section. (the below example is coded for python 2.5+, you will need to use explicit lock acquire/releasing on older pythons) from __future__ import with_statement # only needed on python 2.5 from threading import Lock lock = Lock() def worker1(): #noncritical code with lock: pass # critical code in here def worker2(): with lock: critical_code This will not enforce any sort of ordering, however. When multiple threads try to acquire a lock, all but one will block (and which one acquires the lock next is not determinate) The fact that you mention ordering makes me think you instead have some sort of producer-consumer cycle going on. That is, one thread generates some output which the next needs to work with. You can use queue.Queue to provide data between threads and have them wake up to gobble the next bit of data. from queue import Queue one_to_two = Queue(maxsize=10) def worker1(): while i_have_some_data_stream: data = get_data_from_somewhere() modified_data = munge_data_somehow(data) one_to_two.put(modified_data) #blocks only if queue is currently full def worker2(): while True: data = one_to_two.get() # blocks until data available # do something with data # Optionally, put this newly processed data into the next queue. Queues are a powerful primitive that let you pass messages between threads and implement bounded producer-consumers. If that is your use case, the queue will be more efficient than trying to manually synchronize your thread's ordering. A: maybe something like while True: list = [] for i in xrange(100): t = myThread(data[i]) list.append(t) t.start() for t in list: t.join()
Python Thread Pause and Wait
I have an array of threads. Each of them call the run method continuously. At the end of each run method I want them to pause and wait. How can I get the threads to execute one at a time, and then continue the loop when all are finished? I need them to ALWAYS execute in order (ie: 1, 2, 3, 4 - 1, 2, 3, 4...) I'm currently using threading.Event, but the results are inconsistent. Thanks UPDATE Thanks everybody for your answers so far. I'm writing something similar to Robocode in python. Players program a bot and the bots battle it out until one remains. After each "turn" the bots are "paused" then updated and drawn to the screen. Then they all start a new turn. Example: # Bot extends threading.Thread class DemoBot(Bot): def __init__(self): super(DemoBot, self).__init__() def run(self): while True: self.moveForward(100) self.turnLeft(90) As you can see, the bot is in an infinite loop. In the moveForward method, the bot would move forward 100px. But in order to update the screen correctly, I have to move once, pause, update, then move again. This is why I need to be able to "pause" a bot once its finished and have the program wait for the others before updating the screen. Hope that makes a little more sense.
[ "Your description seems to imply you don't want the threads to execute concurrently, which would bring into question why you're using threading in the first place. \nI sense two possible answers as to why you'd want to do this.\nThe first possibility is that you are trying to prevent your threads from working on some sort of shared resource at the same time. If this is the case, you probably want to use threading.Lock or threading.RLock to lock your critical code section. (the below example is coded for python 2.5+, you will need to use explicit lock acquire/releasing on older pythons)\nfrom __future__ import with_statement # only needed on python 2.5\nfrom threading import Lock\nlock = Lock()\n\n\ndef worker1():\n #noncritical code\n with lock:\n pass # critical code in here\n\ndef worker2():\n with lock:\n critical_code\n\nThis will not enforce any sort of ordering, however. When multiple threads try to acquire a lock, all but one will block (and which one acquires the lock next is not determinate)\nThe fact that you mention ordering makes me think you instead have some sort of producer-consumer cycle going on. That is, one thread generates some output which the next needs to work with. You can use queue.Queue to provide data between threads and have them wake up to gobble the next bit of data.\nfrom queue import Queue\n\none_to_two = Queue(maxsize=10) \n\ndef worker1():\n while i_have_some_data_stream:\n data = get_data_from_somewhere()\n modified_data = munge_data_somehow(data)\n one_to_two.put(modified_data) #blocks only if queue is currently full\n\ndef worker2():\n while True:\n data = one_to_two.get() # blocks until data available\n # do something with data\n # Optionally, put this newly processed data into the next queue.\n\nQueues are a powerful primitive that let you pass messages between threads and implement bounded producer-consumers. If that is your use case, the queue will be more efficient than trying to manually synchronize your thread's ordering.\n", "maybe something like\nwhile True:\n list = []\n for i in xrange(100):\n t = myThread(data[i])\n list.append(t)\n t.start()\n for t in list: t.join()\n\n" ]
[ 3, 0 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0002017261_multithreading_python.txt
Q: a(*{'q':'qqq'}),why only print key def a(*x): print x a({'q':'qqq'}) a(*{'q':'qqq'})#why only print key. traceback: ({'q': 'qqq'},) ('q',) A: That's how dictionaries get converted to sequences. tuple(dictionary) = tuple(dictionary.keys()) for a similar reason for x in dictionary: assigns keys, not pairs, to x A: When you're calling a function, using an asterisk before a list or dict will pass it in as positional parameters. For example: >>> a(*('test', 'testing')) ('test', 'testing') >>> a(*{'a': 'b', 'c': 'd'}) ('a', 'c') A: Using * in front of an expression in a function call iterates over the value of the expression (your dict, in this case) and makes each item in the iteration another parameter to the function invocation. Iterating over a dict in Python yields the keys (for better or worse). A: a(*{'q' : 'qqq'}) will try to expand your dict ({'q':'qqq'}) into an itemized list of arguments for the function. Note that: tuple({'q' : 'qqq'}) returns ('q',), which is exactly what you're seeing. When you coerce a dictionary to a list/tuple, you only get the list of keys. A: Iterating a dictionary will yield its keys. d = {'a': 1, 'b': 2, 'c': 3 } for x in d: print x # prints a, b, c but not necessarily in that order sorted(d): # Gives a, b, c in that order. No 1/2/3. If you want to get both keys and values from a dictionary, you can use .items() or .iteritems() sorted(d.items()) # [('a,' 1), ('b', 2), ('c', 3)] A: You are asking for a list of arguments, and then telling python to send a dict as a sequence of arguments. When a dict is converted to a sequence, it uses the keys. I guess you are really looking for **, not *. A: Probably because that's what a dictionary returns when you do a standard iteration over it. It gets converted to a sequence containing it's keys. This example exhibits the same behaviour: >>> for i in {"a": "1", "b": "2"}: ... print i ... a b To get what I assume you expect you would pass it as variable keyword arguments instead, like this: >>> def a(**kwargs): ... print kwargs ... >>> a(**{"a": "1", "b": "2"}) {'a': '1', 'b': '2'} Note that you are now basically back where you began and have gained nothing.
a(*{'q':'qqq'}),why only print key
def a(*x): print x a({'q':'qqq'}) a(*{'q':'qqq'})#why only print key. traceback: ({'q': 'qqq'},) ('q',)
[ "That's how dictionaries get converted to sequences.\ntuple(dictionary) = tuple(dictionary.keys())\nfor a similar reason\nfor x in dictionary:\n\nassigns keys, not pairs, to x\n", "When you're calling a function, using an asterisk before a list or dict will pass it in as positional parameters.\nFor example:\n>>> a(*('test', 'testing'))\n('test', 'testing')\n\n>>> a(*{'a': 'b', 'c': 'd'})\n('a', 'c')\n\n", "Using * in front of an expression in a function call iterates over the value of the expression (your dict, in this case) and makes each item in the iteration another parameter to the function invocation. Iterating over a dict in Python yields the keys (for better or worse).\n", "a(*{'q' : 'qqq'})\n\nwill try to expand your dict ({'q':'qqq'}) into an itemized list of arguments for the function. \nNote that: \ntuple({'q' : 'qqq'})\n\nreturns ('q',), which is exactly what you're seeing. When you coerce a dictionary to a list/tuple, you only get the list of keys.\n", "Iterating a dictionary will yield its keys.\nd = {'a': 1, 'b': 2, 'c': 3 }\n\nfor x in d:\n print x # prints a, b, c but not necessarily in that order\n\nsorted(d): # Gives a, b, c in that order. No 1/2/3.\n\nIf you want to get both keys and values from a dictionary, you can use .items() or .iteritems()\nsorted(d.items()) # [('a,' 1), ('b', 2), ('c', 3)]\n\n", "You are asking for a list of arguments, and then telling python to send a dict as a sequence of arguments. When a dict is converted to a sequence, it uses the keys.\nI guess you are really looking for **, not *.\n", "Probably because that's what a dictionary returns when you do a standard iteration over it. It gets converted to a sequence containing it's keys. This example exhibits the same behaviour:\n>>> for i in {\"a\": \"1\", \"b\": \"2\"}:\n... print i\n...\na\nb\n\nTo get what I assume you expect you would pass it as variable keyword arguments instead, like this:\n>>> def a(**kwargs):\n... print kwargs\n...\n>>> a(**{\"a\": \"1\", \"b\": \"2\"})\n{'a': '1', 'b': '2'}\n\nNote that you are now basically back where you began and have gained nothing.\n" ]
[ 5, 2, 2, 1, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002017548_python.txt
Q: Get memory usage of computer in Windows with Python How can I tell what the computer's overall memory usage is from Python, running on Windows XP? A: You can also just call GlobalMemoryStatusEx() (or any other kernel32 or user32 export) directly from python: import ctypes class MEMORYSTATUSEX(ctypes.Structure): _fields_ = [ ("dwLength", ctypes.c_ulong), ("dwMemoryLoad", ctypes.c_ulong), ("ullTotalPhys", ctypes.c_ulonglong), ("ullAvailPhys", ctypes.c_ulonglong), ("ullTotalPageFile", ctypes.c_ulonglong), ("ullAvailPageFile", ctypes.c_ulonglong), ("ullTotalVirtual", ctypes.c_ulonglong), ("ullAvailVirtual", ctypes.c_ulonglong), ("sullAvailExtendedVirtual", ctypes.c_ulonglong), ] def __init__(self): # have to initialize this to the size of MEMORYSTATUSEX self.dwLength = ctypes.sizeof(self) super(MEMORYSTATUSEX, self).__init__() stat = MEMORYSTATUSEX() ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(stat)) print("MemoryLoad: %d%%" % (stat.dwMemoryLoad)) Not necessarily as useful as WMI in this case, but definitely a nice trick to have in your back pocket. A: You'll want to use the wmi module. Something like this: import wmi comp = wmi.WMI() for i in comp.Win32_ComputerSystem(): print i.TotalPhysicalMemory, "bytes of physical memory" for os in comp.Win32_OperatingSystem(): print os.FreePhysicalMemory, "bytes of available memory" A: You can query the performance counters in WMI. I've done something similar but with disk space instead. A very useful link is the Python WMI Tutorial by Tim Golden.
Get memory usage of computer in Windows with Python
How can I tell what the computer's overall memory usage is from Python, running on Windows XP?
[ "You can also just call GlobalMemoryStatusEx() (or any other kernel32 or user32 export) directly from python: \nimport ctypes\n\nclass MEMORYSTATUSEX(ctypes.Structure):\n _fields_ = [\n (\"dwLength\", ctypes.c_ulong),\n (\"dwMemoryLoad\", ctypes.c_ulong),\n (\"ullTotalPhys\", ctypes.c_ulonglong),\n (\"ullAvailPhys\", ctypes.c_ulonglong),\n (\"ullTotalPageFile\", ctypes.c_ulonglong),\n (\"ullAvailPageFile\", ctypes.c_ulonglong),\n (\"ullTotalVirtual\", ctypes.c_ulonglong),\n (\"ullAvailVirtual\", ctypes.c_ulonglong),\n (\"sullAvailExtendedVirtual\", ctypes.c_ulonglong),\n ]\n\n def __init__(self):\n # have to initialize this to the size of MEMORYSTATUSEX\n self.dwLength = ctypes.sizeof(self)\n super(MEMORYSTATUSEX, self).__init__()\n\nstat = MEMORYSTATUSEX()\nctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(stat))\n\nprint(\"MemoryLoad: %d%%\" % (stat.dwMemoryLoad))\n\nNot necessarily as useful as WMI in this case, but definitely a nice trick to have in your back pocket. \n", "You'll want to use the wmi module. Something like this:\nimport wmi\ncomp = wmi.WMI()\n\nfor i in comp.Win32_ComputerSystem():\n print i.TotalPhysicalMemory, \"bytes of physical memory\"\n\nfor os in comp.Win32_OperatingSystem():\n print os.FreePhysicalMemory, \"bytes of available memory\"\n\n", "You can query the performance counters in WMI. I've done something similar but with disk space instead.\nA very useful link is the Python WMI Tutorial by Tim Golden.\n" ]
[ 23, 13, 0 ]
[]
[]
[ "memory", "memory_management", "python", "pywin32", "winapi" ]
stackoverflow_0002017545_memory_memory_management_python_pywin32_winapi.txt
Q: Why does tarfile.extractall ignore errors by default? Python's tarfile module ignores errors during extraction by default, unless errorlevel is set to either 1 or 2 (or debug to 1 if only error messages need to be printed). Try doing a mkdir /tmp/foo && sudo chown root /tmp/foo && chmod a-w /tmp/foo and using tarfile to extract a .tar.gz file over /tmp/foo -- you will see that your Python code threw no exceptions at all. The files would not have been extracted over /tmp/foo which still is an empty directory. Why this behavior? Who/what benefits from this default behavior? In other words, just who/what would want to ignore, say, permissions errors when decompressing a tarfile? A: FWIW, this nasty behavior is will be changed in Python 2.7 and 3.2. http://svn.python.org/view?view=rev&revision=76780 Apparently the reason for ignoring the errors before was to be more like GNU tar, which ignores errors.
Why does tarfile.extractall ignore errors by default?
Python's tarfile module ignores errors during extraction by default, unless errorlevel is set to either 1 or 2 (or debug to 1 if only error messages need to be printed). Try doing a mkdir /tmp/foo && sudo chown root /tmp/foo && chmod a-w /tmp/foo and using tarfile to extract a .tar.gz file over /tmp/foo -- you will see that your Python code threw no exceptions at all. The files would not have been extracted over /tmp/foo which still is an empty directory. Why this behavior? Who/what benefits from this default behavior? In other words, just who/what would want to ignore, say, permissions errors when decompressing a tarfile?
[ "FWIW, this nasty behavior is will be changed in Python 2.7 and 3.2. http://svn.python.org/view?view=rev&revision=76780 Apparently the reason for ignoring the errors before was to be more like GNU tar, which ignores errors.\n" ]
[ 2 ]
[]
[]
[ "permissions", "python", "tarfile" ]
stackoverflow_0002017725_permissions_python_tarfile.txt
Q: Data Carving loop improvements I currently have a Python app I am developing which will data carve a block device for jpeg files. Let's just say that it sometimes works and sometimes doesn't. I have created it so that I read the block device till I find a ffd8, then I keep the stream open and search via looping for the ffd9 closure. Though I always need to take into account all ffd9 closures even after the first. So it tends to be a really intensive operation. Given a device with let's say 25 jpegs as well as lots of other data, the looping is pretty dramatic and it runs though a lot. The program is not the slowest thing in the world, but I think it could be much faster and much more efficient. I am looking for a better way to search the block device and extract the data in a more efficient manner. I also don't want to kill the HDD or the drive holding the image of the block device. So does anybody knew of a better way to systematically handle the searching and extraction of the data? A: The trouble with reading the block device directly is that there is no guarantee that the blocks of any given file are contiguous. That means that even if you find your magic marker bytes 0xFFD8 in block 13, say, there is no guarantee that block 14 belongs to the same file, whether or not it contains the 0xFFD9 end marker or not. (Most files will start on a block boundary; the end of the file may be anywhere, possibly even across block boundaries.) What's the better way to deal with it? Well, it depends what you're after - but if you're looking only at currently allocated blocks, then scan the file system using the Python analog of the POSIX C function ftw (nftw), and read each file in turn. This won't find evidence of deleted JPEG files in the free list - if that's what you are after, then you'll need to do as you are doing, more or less, but correlate that information with what you find in the file system proper. Mapping those blocks will (at best) be hard.
Data Carving loop improvements
I currently have a Python app I am developing which will data carve a block device for jpeg files. Let's just say that it sometimes works and sometimes doesn't. I have created it so that I read the block device till I find a ffd8, then I keep the stream open and search via looping for the ffd9 closure. Though I always need to take into account all ffd9 closures even after the first. So it tends to be a really intensive operation. Given a device with let's say 25 jpegs as well as lots of other data, the looping is pretty dramatic and it runs though a lot. The program is not the slowest thing in the world, but I think it could be much faster and much more efficient. I am looking for a better way to search the block device and extract the data in a more efficient manner. I also don't want to kill the HDD or the drive holding the image of the block device. So does anybody knew of a better way to systematically handle the searching and extraction of the data?
[ "The trouble with reading the block device directly is that there is no guarantee that the blocks of any given file are contiguous. That means that even if you find your magic marker bytes 0xFFD8 in block 13, say, there is no guarantee that block 14 belongs to the same file, whether or not it contains the 0xFFD9 end marker or not. (Most files will start on a block boundary; the end of the file may be anywhere, possibly even across block boundaries.)\nWhat's the better way to deal with it? Well, it depends what you're after - but if you're looking only at currently allocated blocks, then scan the file system using the Python analog of the POSIX C function ftw (nftw), and read each file in turn. This won't find evidence of deleted JPEG files in the free list - if that's what you are after, then you'll need to do as you are doing, more or less, but correlate that information with what you find in the file system proper. Mapping those blocks will (at best) be hard.\n" ]
[ 2 ]
[]
[]
[ "io", "python" ]
stackoverflow_0002018210_io_python.txt
Q: How to create a class from function I am still struggling with understanding classes, I am not certain but I have an idea that this function I have created is probably a good candidate for a class. The function takes a list of dictionaries, identifies the keys and writes out a csv file. First Q, is this function a good candidate for a class (I write out a lot of csv files Second Q If the answer to 1 is yes, how do I do it Third Q how do I use the instances of the class (did I say that right) import csv def writeCSV(dictList,outfile): maxLine=dictList[0] for item in dictList: if len(item)>len(maxLine): maxLine=item dictList.insert(0,dict( (key,key) for key in maxLine.keys())) csv_file=open(outfile,'ab') writer = csv.DictWriter(csv_file,fieldnames=[key for key in maxLine.keys()],restval='notScanned',dialect='excel') for dataLine in dictList: writer.writerow(dataLine) csv_file.close() return A: The main idea behind objects is that an object is data plus methods. Whenever you are thinking about making something an object, you must ask yourself what will be the object's data, and what operations (methods) will you want to perform on that data. Functions, more readily translate to methods than classes. So, for instance, if your dictList is data upon which you often call writeCSV, then perhaps make a dictList object with method writeCSV: class DictList(object): def __init__(self,data): self.data=data def writeCSV(self,outfile): maxLine=self.data[0] for item in self.data: if len(item)>len(maxLine): maxLine=item self.data.insert(0,dict( (key,key) for key in maxLine.keys())) csv_file=open(outfile,'ab') writer = csv.DictWriter( csv_file,fieldnames=[key for key in maxLine.keys()], restval='notScanned',dialect='excel') for dataLine in self.data: writer.writerow(dataLine) csv_file.close() Then you could instantiate a DictList object: dl=DictList([{},{},...]) dl.writeCSV(outfile) Doing this might make sense if you have more methods that could operate on the same DictList.data. Otherwise, you'd probably be better off sticking with the original function. A: For this you need to understand little bit concepts of classes first and then follow the next step. I too faced a same problem and followed this LINK , I m sure u will also start working on classes from your structured programming. A: If you want to write a lot of CSV files with the same dictList (is that what you're saying...?), turning the function into a class would let you perform initialization just once, and then write repeatedly from the same initialized instance. E.g., with other minor opts: class CsvWriter(object): def __init__(self, dictList): self.maxline = max(dictList, key=len) self.dictList = [dict((k,k) for k in self.maxline)] self.dictList.extend(dictList) def doWrite(self, outfile): csv_file=open(outfile,'ab') writer = csv.DictWriter(csv_file, fieldnames=self.maxLine.keys(), restval='notScanned', dialect='excel') for dataLine in self.dictList: writer.writerow(dataLine) csv_file.close() This seems a dubious use case, but if it does match your desire, then you'd instantiate and use this class as follows...: cw = CsvWriter(dataList) for ou in many_outfiles: cw.doWrite(ou) A: When thinking about making objects, remember this: Classes have attributes - things that describe different instances of the class differently Classes have methods - things that the objects do (often involving using their attributes) Objects and classes are wonderful, but the first thing to keep in mind is that they are not always necessary, or even desirable. That said, in answer to your first question, this doesn't seem like a particularly good candidate for a class. The only thing different between the different CVS files you're writing are the data and the file you write to, and the only thing you do with them (ie, the only method you would have) is the function you've already written). Even though the first answer is no, it's still instructive to see how a class is built. class CSVWriter: # this function is called when you create an instance of the class # it sets up the initial attributes of the instance def __init__(self, dictList, outFile): self.dictList = dictList self.outFile = outFile def writeCSV(self): # basically exactly what you have above, except you can use the instance's # own variables (ie, self.dictList and self.outFile) instead of the local # variables For your final question - the first step to using an instance of a class (an individual object, if you will) is to create that instance: myCSV = CSVWriter(dictList, outFile) When the object is created, init is called with the arguments you gave it - that allows your object to have its own data. Now you can access any of the attributes or methods that your myCSV object has with the '.' operator: myCSV.writeCSV() print "Wrote a file to", myCSV.outFile One way to think about objects versus functions is that objects are generally nouns (eg, I created a CSVWriter), while functions are verbs (eg, you wrote a the function that writes CSV files). If you're just doing something over and over again, without re-using any of the same data, a function by itself is fine. But, if you have lots of related data, and part of it gets changed in the course of the action, classes may be a good idea. A: I don't think your writeCSV is in need of a class, typicaly class would be used when you have to update some state(data) and then act on it, may be with various options. e.g. if you need to pass around your object, so that other function/method can add values to it or your final action/output function has many options or you think same data can be processed, acted upon in many ways. Typically practical case would be if you have multiple functions which act on same data or a singe function whose optional parameter list is going to long, you may think of converting it into a class. If in your case you had various options and need to insert data in increments, you should make it a class. Usually class name would be noun, so function(verb) writeCSV -> class(noun) CSVWriter class CSVWriter(object): def __init__(self, init-params...): self.data = {} def addData(self, data): self.data.update(data) def dumpCSV(self, filePath): ... def dumpJSON(self, filePath): .... A: I think question 1 is pretty crucial as it goes to the heart of what a class is. Yes, you can put this function in a class. A class is a set of functions (called methods) and data together in one logical unit. As other posters noted, probably overkill to have a class with one method.
How to create a class from function
I am still struggling with understanding classes, I am not certain but I have an idea that this function I have created is probably a good candidate for a class. The function takes a list of dictionaries, identifies the keys and writes out a csv file. First Q, is this function a good candidate for a class (I write out a lot of csv files Second Q If the answer to 1 is yes, how do I do it Third Q how do I use the instances of the class (did I say that right) import csv def writeCSV(dictList,outfile): maxLine=dictList[0] for item in dictList: if len(item)>len(maxLine): maxLine=item dictList.insert(0,dict( (key,key) for key in maxLine.keys())) csv_file=open(outfile,'ab') writer = csv.DictWriter(csv_file,fieldnames=[key for key in maxLine.keys()],restval='notScanned',dialect='excel') for dataLine in dictList: writer.writerow(dataLine) csv_file.close() return
[ "The main idea behind objects is that an object is data plus methods.\nWhenever you are thinking about making something an object, you must ask yourself what will be the object's data, and what operations (methods) will you want to perform on that data.\nFunctions, more readily translate to methods than classes.\nSo, for instance, if your dictList is data upon which you often call writeCSV,\nthen perhaps make a dictList object with method writeCSV:\nclass DictList(object):\n def __init__(self,data):\n self.data=data\n def writeCSV(self,outfile):\n maxLine=self.data[0]\n for item in self.data:\n if len(item)>len(maxLine):\n maxLine=item\n self.data.insert(0,dict( (key,key) for key in maxLine.keys()))\n csv_file=open(outfile,'ab')\n writer = csv.DictWriter(\n csv_file,fieldnames=[key for key in maxLine.keys()],\n restval='notScanned',dialect='excel')\n for dataLine in self.data:\n writer.writerow(dataLine)\n csv_file.close()\n\nThen you could instantiate a DictList object:\ndl=DictList([{},{},...])\ndl.writeCSV(outfile)\n\nDoing this might make sense if you have more methods that could operate on the same DictList.data. Otherwise, you'd probably be better off sticking with the original function.\n", "For this you need to understand little bit concepts of classes first and then follow the next step.\nI too faced a same problem and followed this LINK , I m sure u will also start working on classes from your structured programming. \n", "If you want to write a lot of CSV files with the same dictList (is that what you're saying...?), turning the function into a class would let you perform initialization just once, and then write repeatedly from the same initialized instance. E.g., with other minor opts:\nclass CsvWriter(object):\n\n def __init__(self, dictList):\n self.maxline = max(dictList, key=len)\n self.dictList = [dict((k,k) for k in self.maxline)]\n self.dictList.extend(dictList)\n\n def doWrite(self, outfile):\n csv_file=open(outfile,'ab')\n writer = csv.DictWriter(csv_file,\n fieldnames=self.maxLine.keys(),\n restval='notScanned',\n dialect='excel')\n for dataLine in self.dictList:\n writer.writerow(dataLine)\n csv_file.close()\n\nThis seems a dubious use case, but if it does match your desire, then you'd instantiate and use this class as follows...:\ncw = CsvWriter(dataList)\nfor ou in many_outfiles:\n cw.doWrite(ou)\n\n", "When thinking about making objects, remember this:\n\nClasses have attributes - things that describe different instances of the class differently\nClasses have methods - things that the objects do (often involving using their attributes)\n\nObjects and classes are wonderful, but the first thing to keep in mind is that they are not always necessary, or even desirable.\nThat said, in answer to your first question, this doesn't seem like a particularly good candidate for a class. The only thing different between the different CVS files you're writing are the data and the file you write to, and the only thing you do with them (ie, the only method you would have) is the function you've already written).\nEven though the first answer is no, it's still instructive to see how a class is built.\nclass CSVWriter:\n # this function is called when you create an instance of the class\n # it sets up the initial attributes of the instance\n def __init__(self, dictList, outFile):\n self.dictList = dictList\n self.outFile = outFile\n\n def writeCSV(self):\n # basically exactly what you have above, except you can use the instance's\n # own variables (ie, self.dictList and self.outFile) instead of the local\n # variables\n\nFor your final question - the first step to using an instance of a class (an individual object, if you will) is to create that instance:\nmyCSV = CSVWriter(dictList, outFile)\n\nWhen the object is created, init is called with the arguments you gave it - that allows your object to have its own data. Now you can access any of the attributes or methods that your myCSV object has with the '.' operator:\nmyCSV.writeCSV()\nprint \"Wrote a file to\", myCSV.outFile\n\nOne way to think about objects versus functions is that objects are generally nouns (eg, I created a CSVWriter), while functions are verbs (eg, you wrote a the function that writes CSV files). If you're just doing something over and over again, without re-using any of the same data, a function by itself is fine. But, if you have lots of related data, and part of it gets changed in the course of the action, classes may be a good idea.\n", "I don't think your writeCSV is in need of a class, typicaly class would be used when you have to update some state(data) and then act on it, may be with various options.\ne.g. if you need to pass around your object, so that other function/method can add values to it or your final action/output function has many options or you think same data can be processed, acted upon in many ways.\nTypically practical case would be if you have multiple functions which act on same data or a singe function whose optional parameter list is going to long, you may think of converting it into a class.\nIf in your case you had various options and need to insert data in increments, you should make it a class.\nUsually class name would be noun, so function(verb) writeCSV -> class(noun) CSVWriter\nclass CSVWriter(object):\n def __init__(self, init-params...):\n self.data = {}\n\n def addData(self, data):\n self.data.update(data)\n\n def dumpCSV(self, filePath):\n ...\n\n def dumpJSON(self, filePath):\n ....\n\n", "I think question 1 is pretty crucial as it goes to the heart of what a class is.\nYes, you can put this function in a class. A class is a set of functions (called methods) and data together in one logical unit. As other posters noted, probably overkill to have a class with one method.\n" ]
[ 2, 2, 1, 1, 0, 0 ]
[]
[]
[ "class", "python" ]
stackoverflow_0002018282_class_python.txt
Q: Examples of using Doctests in Django in an Agile / BDD way I'm interested in learning how to Doctests and Unit tests in a more Agile / BDD way. I've found a few tutorials that seem reasonable, but they are just thumbnails. What I would really like to see is the source code of some Django projects that were developed BDD style. The things I'm unclear about are how do you handle request objects etc. I have a situation where I have deployed my app and I'm getting completely different behavior in production that I did in development or even from the Python shell on the production server. I'm hoping some Doctests will help me diagnose this and well as open the door for a more Agile process of writing the tests first. Specifically, here is the code I'm trying to test: def match_pictures_with_products( queryset, number_of_images = 3): products = [] i = 0 for product in queryset: if i < ( number_of_images ): image = product.imagemain_set.all()[:1] product.photo_url = image[0].photo.url products.append(product) i += 1 return products def index(request): """returns the top 10 most clicked products""" products = Product.objects.all()[:10] products = match_pictures_with_products( products, 10) . return render_to_response('products/product_list.html', {'products': products}) How do I create a Doctest that ensures that index returns 10 objects? The Product queries seem to work fine from the shell on the production server. The actual server is not returning any products at all. A: I've asked myself the same question before. I've found doctests to be of limited utility for things like views, model methods and managers because You need to be able to setup and teardown a test data set to actually use for testing Views need to take a request object. In a doctest, where does that come from? For that reason, I've always used the Django unit testing framework which handles all this for you. Unfortunately, though, you don't get some of the benefits of the doctests and it makes TDD/BDD harder to do. What follows next is pure speculation about how you might make this work: I think you'd want to grab doctests from their respective modules and functions and execute them within the unit testing framework. This would take care of test data setup/teardown. If your doctests were executed from within a test method of something that subclasses Django's unittest.TestCase they'd be able to use that test DB. You'd also be able to pass a mock request object into the doc test's execution context. Here's a Django snippet that provides a mock request object and info on it. Let's say you wanted to test the docstrings from all of an applications views. You could do something like this in tests.py : from ??? import RequestFactory from doctest import testmod, DocTestFailure from django.test import TestCase from myapp import views class MyAppTest(TestCase): fixtures = ['test_data.json'] def test_doctests(self): try: testmod(views, extraglobs={ 'REQUEST': RequestFactory() }, raise_on_error=True) except DocTestFailure, e: self.fail(e) This should allow you to do something like this: def index(request): """ returns the top 10 most clicked products >>> response = index(REQUEST) >>> [test response content here] """ products = Product.objects.all()[:10] products = match_pictures_with_products( products, 10) . return render_to_response('products/product_list.html', {'products': products}) Again, this is just off the top of my head and not at all tested, but it's the only way that I think you could what you want without just putting all your view tests in the unit testing framework. A: The way your view is written, it would be hard to test. You'd have to scrape the html to see if the content you want is present, and then you're testing more than you need to. Better would be to rewrite your view to make it easier to test. Start by parameterizing your template name, so you can create a simple test template: def index(request, template_name='products/product_list.html'): """returns the top 10 most clicked products""" products = Product.objects.all()[:10] products = match_pictures_with_products( products, 10) . return render_to_response(template_name, {'products': products}) Then you can write a simple template that just counts the number of products: {{ products.count }} And make sure the template returns "10". A: You can use the django testclient and test the context variables that get set: >>> response = client.get('/foo/') >>> response.context['name'] 'Arthur' You can also check the response code to make sure the page returned a success 200. A: The zope.testbrowser package might be useful in your doctests, since you want to analyse the rendered HTML answer of your production server.
Examples of using Doctests in Django in an Agile / BDD way
I'm interested in learning how to Doctests and Unit tests in a more Agile / BDD way. I've found a few tutorials that seem reasonable, but they are just thumbnails. What I would really like to see is the source code of some Django projects that were developed BDD style. The things I'm unclear about are how do you handle request objects etc. I have a situation where I have deployed my app and I'm getting completely different behavior in production that I did in development or even from the Python shell on the production server. I'm hoping some Doctests will help me diagnose this and well as open the door for a more Agile process of writing the tests first. Specifically, here is the code I'm trying to test: def match_pictures_with_products( queryset, number_of_images = 3): products = [] i = 0 for product in queryset: if i < ( number_of_images ): image = product.imagemain_set.all()[:1] product.photo_url = image[0].photo.url products.append(product) i += 1 return products def index(request): """returns the top 10 most clicked products""" products = Product.objects.all()[:10] products = match_pictures_with_products( products, 10) . return render_to_response('products/product_list.html', {'products': products}) How do I create a Doctest that ensures that index returns 10 objects? The Product queries seem to work fine from the shell on the production server. The actual server is not returning any products at all.
[ "I've asked myself the same question before. I've found doctests to be of limited utility for things like views, model methods and managers because\n\nYou need to be able to setup and teardown a test data set to actually use for testing\nViews need to take a request object. In a doctest, where does that come from?\n\nFor that reason, I've always used the Django unit testing framework which handles all this for you. Unfortunately, though, you don't get some of the benefits of the doctests and it makes TDD/BDD harder to do. What follows next is pure speculation about how you might make this work:\nI think you'd want to grab doctests from their respective modules and functions and execute them within the unit testing framework. This would take care of test data setup/teardown. If your doctests were executed from within a test method of something that subclasses Django's unittest.TestCase they'd be able to use that test DB. You'd also be able to pass a mock request object into the doc test's execution context. Here's a Django snippet that provides a mock request object and info on it. Let's say you wanted to test the docstrings from all of an applications views. You could do something like this in tests.py :\nfrom ??? import RequestFactory\nfrom doctest import testmod, DocTestFailure\nfrom django.test import TestCase\n\nfrom myapp import views\n\nclass MyAppTest(TestCase):\n\n fixtures = ['test_data.json']\n\n def test_doctests(self): \n try:\n testmod(views, extraglobs={\n 'REQUEST': RequestFactory()\n }, raise_on_error=True)\n except DocTestFailure, e:\n self.fail(e)\n\nThis should allow you to do something like this:\ndef index(request): \n \"\"\"\n returns the top 10 most clicked products\n\n >>> response = index(REQUEST)\n >>> [test response content here]\n\n \"\"\" \n products = Product.objects.all()[:10] \n products = match_pictures_with_products( products, 10) . \n return render_to_response('products/product_list.html', {'products': products})\n\nAgain, this is just off the top of my head and not at all tested, but it's the only way that I think you could what you want without just putting all your view tests in the unit testing framework. \n", "The way your view is written, it would be hard to test. You'd have to scrape the html to see if the content you want is present, and then you're testing more than you need to. Better would be to rewrite your view to make it easier to test. Start by parameterizing your template name, so you can create a simple test template:\ndef index(request, template_name='products/product_list.html'): \n \"\"\"returns the top 10 most clicked products\"\"\" \n products = Product.objects.all()[:10] \n products = match_pictures_with_products( products, 10) . \n return render_to_response(template_name, {'products': products})\n\nThen you can write a simple template that just counts the number of products:\n{{ products.count }} \n\nAnd make sure the template returns \"10\". \n", "You can use the django testclient and test the context variables that get set:\n>>> response = client.get('/foo/')\n>>> response.context['name']\n'Arthur'\n\nYou can also check the response code to make sure the page returned a success 200.\n", "The zope.testbrowser package might be useful in your doctests, since you want to analyse the rendered HTML answer of your production server.\n" ]
[ 3, 1, 1, 0 ]
[]
[]
[ "agile", "django", "doctest", "python" ]
stackoverflow_0001907610_agile_django_doctest_python.txt
Q: What is the difference between these two classes? class SortedDict(dict): def __init__(self, data=None): if data is None: data = {} super(SortedDict, self).__init__(data) and class SortedDict(dict): def __init__(self, data={}): dict(data) I think they are same. A: dict(data) just creates a dictionary from data without saving the result anywhere. super(SortedDict, self).__init__(data) on the other hand calls the parent class constructor. Also, in the case of multiple inheritance, using super ensures that all the right constructors are called in the right order. Using None as a default argument instead of a mutable {} ensures that those other constructors don't accidentally modify SortedDicts default argument. A: The first class doesn't seem to work class SortedDict2(dict): def __init__(self, data={}): dict(data) class SortedDict(dict): def __init__(self, data=None): if data is None: data = {} super(SortedDict, self).__init__(data) x = SortedDict2("bleh") y = SortedDict({1: 'blah'}) print x print y File "rere.py", line 3, in __init__ dict(data) ValueError: dictionary update sequence element #0 has length 1; 2 is required x = SortedDict2({1: "bleh"}) y = SortedDict({1: 'blah'}) print x print y >> {} >>{1: 'blah'}
What is the difference between these two classes?
class SortedDict(dict): def __init__(self, data=None): if data is None: data = {} super(SortedDict, self).__init__(data) and class SortedDict(dict): def __init__(self, data={}): dict(data) I think they are same.
[ "dict(data) just creates a dictionary from data without saving the result anywhere. super(SortedDict, self).__init__(data) on the other hand calls the parent class constructor.\nAlso, in the case of multiple inheritance, using super ensures that all the right constructors are called in the right order. Using None as a default argument instead of a mutable {} ensures that those other constructors don't accidentally modify SortedDicts default argument.\n", "The first class doesn't seem to work\nclass SortedDict2(dict):\n def __init__(self, data={}):\n dict(data)\n\nclass SortedDict(dict):\n def __init__(self, data=None):\n if data is None:\n data = {}\n super(SortedDict, self).__init__(data)\n\n\n\nx = SortedDict2(\"bleh\")\ny = SortedDict({1: 'blah'})\n\nprint x\nprint y\n\nFile \"rere.py\", line 3, in __init__\n dict(data)\nValueError: dictionary update sequence element #0 has length 1; 2 is required\n\n\nx = SortedDict2({1: \"bleh\"})\ny = SortedDict({1: 'blah'})\n\nprint x\nprint y\n\n>> {}\n>>{1: 'blah'}\n\n" ]
[ 5, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002018543_python.txt
Q: Real-world examples of nested functions I asked previously how the nested functions work, but unfortunately I still don't quite get it. To understand it better, can someone please show some real-wold, practical usage examples of nested functions? Many thanks A: Your question made me curious, so I looked in some real-world code: the Python standard library. I found 67 examples of nested functions. Here are a few, with explanations. One very simple reason to use a nested function is simply that the function you're defining doesn't need to be global, because only the enclosing function uses it. A typical example from Python's quopri.py standard library module: def encode(input, output, quotetabs, header = 0): ... def write(s, output=output, lineEnd='\n'): # RFC 1521 requires that the line ending in a space or tab must have # that trailing character encoded. if s and s[-1:] in ' \t': output.write(s[:-1] + quote(s[-1]) + lineEnd) elif s == '.': output.write(quote(s) + lineEnd) else: output.write(s + lineEnd) ... # 35 more lines of code that call write in several places Here there was some common code within the encode function, so the author simply factored it out into a write function. Another common use for nested functions is re.sub. Here's some code from the json/encode.py standard library module: def encode_basestring(s): """Return a JSON representation of a Python string """ def replace(match): return ESCAPE_DCT[match.group(0)] return '"' + ESCAPE.sub(replace, s) + '"' Here ESCAPE is a regular expression, and ESCAPE.sub(replace, s) finds all matches of ESCAPE in s and replaces each one with replace(match). In fact, any API, like re.sub, that accepts a function as a parameter can lead to situations where nested functions are convenient. For example, in turtle.py there's some silly demo code that does this: def baba(xdummy, ydummy): clearscreen() bye() ... tri.write(" Click me!", font = ("Courier", 12, "bold") ) tri.onclick(baba, 1) onclick expects you to pass an event-handler function, so we define one and pass it in. A: Decorators are a very popular use for nested functions. Here's an example of a decorator that prints a statement before and after any call to the decorated function. def entry_exit(f): def new_f(*args, **kwargs): print "Entering", f.__name__ f(*args, **kwargs) print "Exited", f.__name__ return new_f @entry_exit def func1(): print "inside func1()" @entry_exit def func2(): print "inside func2()" func1() func2() print func1.__name__ A: Nested functions avoid cluttering other parts of the program with other functions and variables that only make sense locally. A function that return Fibonacci numbers could be defined as follows: >>> def fib(n): def rec(): return fib(n-1) + fib(n-2) if n == 0: return 0 elif n == 1: return 1 else: return rec() >>> map(fib, range(10)) [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] EDIT: In practice, generators would be a better solution for this, but the example shows how to take advantage of nested functions. A: They are useful when using functions that take other functions as input. Say you're in a function, and want to sort a list of items based on the items' value in a dict: def f(items): vals = {} for i in items: vals[i] = random.randint(0,100) def key(i): return vals[i] items.sort(key=key) You can just define key right there and have it use vals, a local variable. Another use-case is callbacks. A: I have only had to use nested functions when creating decorators. A nested function is basically a way of adding some behavior to a function without knowing what the function is that you are adding behavior to. from functools import wraps from types import InstanceType def printCall(func): def getArgKwargStrings(*args, **kwargs): argsString = "".join(["%s, " % (arg) for arg in args]) kwargsString = "".join(["%s=%s, " % (key, value) for key, value in kwargs.items()]) if not len(kwargs): if len(argsString): argsString = argsString[:-2] else: kwargsString = kwargsString[:-2] return argsString, kwargsString @wraps(func) def wrapper(*args, **kwargs): ret = None if args and isinstance(args[0], InstanceType) and getattr(args[0], func.__name__, None): instance, args = args[0], args[1:] argsString, kwargsString = getArgKwargStrings(*args, **kwargs) ret = func(instance, *args, **kwargs) print "Called %s.%s(%s%s)" % (instance.__class__.__name__, func.__name__, argsString, kwargsString) print "Returned %s" % str(ret) else: argsString, kwargsString = getArgKwargStrings(*args, **kwargs) ret = func(*args, **kwargs) print "Called %s(%s%s)" % (func.__name__, argsString, kwargsString) print "Returned %s" % str(ret) return ret return wrapper def sayHello(name): print "Hello, my name is %s" % (name) if __name__ == "__main__": sayHelloAndPrintDebug = printCall(sayHello) name = "Nimbuz" sayHelloAndPrintDebug(name) Ignore all the mumbo jumbo in the "printCall" function for right now and focus only the "sayHello" function and below. What we're doing here is we want to print out how the "sayHello" function was called everytime it is called without knowing or altering what the "sayHello" function does. So we redefine the "sayHello" function by passing it to "printCall", which returns a NEW function that does what the "sayHello" function does AND prints how the "sayHello" function was called. This is the concept of decorators. Putting "@printCall" above the sayHello definition accomplishes the same thing: @printCall def sayHello(name): print "Hello, my name is %s" % (name) if __name__ == "__main__": name = "Nimbuz" sayHello(name) A: Yet another (very simple) example. A function that returns another function. Note how the inner function (that is returned) can use variables from the outer function's scope. def create_adder(x): def _adder(y): return x + y return _adder add2 = create_adder(2) add100 = create_adder(100) >>> add2(50) 52 >>> add100(50) 150 A: Python Decorators This is actually another topic to learn, but if you look at the stuff on 'Using Functions as Decorators', you'll see some examples of nested functions. A: OK, besides decorators: Say you had an application where you needed to sort a list of strings based on substrings which varied from time to time. Now the sorted functions takes a key= argument which is a function of one argument: the items (strings in this case) to be sorted. So how to tell this function which substrings to sort on? A closure or nested function, is perfect for this: def sort_key_factory(start, stop): def sort_key(string): return string[start: stop] return sort_key Simple eh? You can expand on this by encapsulating start and stop in a tuple or a slice object and then passing a sequence or iterable of these to the sort_key_factory.
Real-world examples of nested functions
I asked previously how the nested functions work, but unfortunately I still don't quite get it. To understand it better, can someone please show some real-wold, practical usage examples of nested functions? Many thanks
[ "Your question made me curious, so I looked in some real-world code: the Python standard library. I found 67 examples of nested functions. Here are a few, with explanations.\nOne very simple reason to use a nested function is simply that the function you're defining doesn't need to be global, because only the enclosing function uses it. A typical example from Python's quopri.py standard library module:\ndef encode(input, output, quotetabs, header = 0):\n ...\n def write(s, output=output, lineEnd='\\n'):\n # RFC 1521 requires that the line ending in a space or tab must have\n # that trailing character encoded.\n if s and s[-1:] in ' \\t':\n output.write(s[:-1] + quote(s[-1]) + lineEnd)\n elif s == '.':\n output.write(quote(s) + lineEnd)\n else:\n output.write(s + lineEnd)\n\n ... # 35 more lines of code that call write in several places\n\nHere there was some common code within the encode function, so the author simply factored it out into a write function.\n\nAnother common use for nested functions is re.sub. Here's some code from the json/encode.py standard library module:\ndef encode_basestring(s):\n \"\"\"Return a JSON representation of a Python string\n\n \"\"\"\n def replace(match):\n return ESCAPE_DCT[match.group(0)]\n return '\"' + ESCAPE.sub(replace, s) + '\"'\n\nHere ESCAPE is a regular expression, and ESCAPE.sub(replace, s) finds all matches of ESCAPE in s and replaces each one with replace(match).\n\nIn fact, any API, like re.sub, that accepts a function as a parameter can lead to situations where nested functions are convenient. For example, in turtle.py there's some silly demo code that does this:\n def baba(xdummy, ydummy):\n clearscreen()\n bye()\n\n ...\n tri.write(\" Click me!\", font = (\"Courier\", 12, \"bold\") )\n tri.onclick(baba, 1)\n\nonclick expects you to pass an event-handler function, so we define one and pass it in.\n", "Decorators are a very popular use for nested functions. Here's an example of a decorator that prints a statement before and after any call to the decorated function.\ndef entry_exit(f):\n def new_f(*args, **kwargs):\n print \"Entering\", f.__name__\n f(*args, **kwargs)\n print \"Exited\", f.__name__\n return new_f\n\n@entry_exit\ndef func1():\n print \"inside func1()\"\n\n@entry_exit\ndef func2():\n print \"inside func2()\"\n\nfunc1()\nfunc2()\nprint func1.__name__\n\n", "Nested functions avoid cluttering other parts of the program with other functions and variables that only make sense locally.\nA function that return Fibonacci numbers could be defined as follows:\n>>> def fib(n):\n def rec():\n return fib(n-1) + fib(n-2)\n\n if n == 0:\n return 0\n elif n == 1:\n return 1\n else:\n return rec()\n\n>>> map(fib, range(10))\n[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]\n\nEDIT: In practice, generators would be a better solution for this, but the example shows how to take advantage of nested functions.\n", "They are useful when using functions that take other functions as input. Say you're in a function, and want to sort a list of items based on the items' value in a dict:\ndef f(items):\n vals = {}\n for i in items: vals[i] = random.randint(0,100)\n def key(i): return vals[i] \n items.sort(key=key)\n\nYou can just define key right there and have it use vals, a local variable.\nAnother use-case is callbacks. \n", "I have only had to use nested functions when creating decorators. A nested function is basically a way of adding some behavior to a function without knowing what the function is that you are adding behavior to.\nfrom functools import wraps\nfrom types import InstanceType\n\n\n\ndef printCall(func):\n def getArgKwargStrings(*args, **kwargs):\n argsString = \"\".join([\"%s, \" % (arg) for arg in args])\n kwargsString = \"\".join([\"%s=%s, \" % (key, value) for key, value in kwargs.items()])\n if not len(kwargs):\n if len(argsString):\n argsString = argsString[:-2]\n else:\n kwargsString = kwargsString[:-2]\n return argsString, kwargsString\n\n @wraps(func)\n def wrapper(*args, **kwargs):\n ret = None\n if args and isinstance(args[0], InstanceType) and getattr(args[0], func.__name__, None):\n instance, args = args[0], args[1:]\n argsString, kwargsString = getArgKwargStrings(*args, **kwargs)\n ret = func(instance, *args, **kwargs)\n print \"Called %s.%s(%s%s)\" % (instance.__class__.__name__, func.__name__, argsString, kwargsString)\n print \"Returned %s\" % str(ret)\n else:\n argsString, kwargsString = getArgKwargStrings(*args, **kwargs)\n ret = func(*args, **kwargs)\n print \"Called %s(%s%s)\" % (func.__name__, argsString, kwargsString)\n print \"Returned %s\" % str(ret)\n return ret\n return wrapper\n\n\ndef sayHello(name):\n print \"Hello, my name is %s\" % (name)\n\nif __name__ == \"__main__\":\n sayHelloAndPrintDebug = printCall(sayHello)\n name = \"Nimbuz\"\n sayHelloAndPrintDebug(name)\n\nIgnore all the mumbo jumbo in the \"printCall\" function for right now and focus only the \"sayHello\" function and below. What we're doing here is we want to print out how the \"sayHello\" function was called everytime it is called without knowing or altering what the \"sayHello\" function does. So we redefine the \"sayHello\" function by passing it to \"printCall\", which returns a NEW function that does what the \"sayHello\" function does AND prints how the \"sayHello\" function was called. This is the concept of decorators. \nPutting \"@printCall\" above the sayHello definition accomplishes the same thing:\n@printCall\ndef sayHello(name):\n print \"Hello, my name is %s\" % (name)\n\nif __name__ == \"__main__\":\n name = \"Nimbuz\"\n sayHello(name)\n\n", "Yet another (very simple) example. A function that returns another function. Note how the inner function (that is returned) can use variables from the outer function's scope.\ndef create_adder(x):\n def _adder(y):\n return x + y\n return _adder\n\nadd2 = create_adder(2)\nadd100 = create_adder(100)\n\n>>> add2(50)\n52\n>>> add100(50)\n150\n\n", "Python Decorators\nThis is actually another topic to learn, but if you look at the stuff on 'Using Functions as Decorators', you'll see some examples of nested functions.\n", "OK, besides decorators: Say you had an application where you needed to sort a list of strings based on substrings which varied from time to time. Now the sorted functions takes a key= argument which is a function of one argument: the items (strings in this case) to be sorted. So how to tell this function which substrings to sort on? A closure or nested function, is perfect for this:\ndef sort_key_factory(start, stop):\n def sort_key(string):\n return string[start: stop]\n return sort_key\n\nSimple eh? You can expand on this by encapsulating start and stop in a tuple or a slice object and then passing a sequence or iterable of these to the sort_key_factory.\n" ]
[ 10, 8, 4, 3, 2, 2, 1, 1 ]
[]
[]
[ "function", "nested", "python" ]
stackoverflow_0002017101_function_nested_python.txt
Q: 3d Histogram in Python I am trying to generate a 3D histogram using python. I tried the following code but I am getting an error too many values to unpack. from matplotlib import pyplot import pylab from mpl_toolkits.mplot3d import Axes3D import numpy fig = pylab.figure() ax = Axes3D(fig) data_filename = 'C:\csvfiles\luxury.txt' data_file = numpy.loadtxt(data_filename, delimiter=',') X = data_file[:,1] Y = data_file[:,2] Z = data_file[:,3] ax.hist(X, Y, Z) pyplot.show() What am I doing wrong? A: "Too many values to unpack" happens when you do something like this: (a, b) = (1, 2, 3) That is, not enough variables on the left to accept all of the values on the right of the =. Update: Try: ax.hist( (X, Y, Z) ) The hist function wants a tuple as the first argument.
3d Histogram in Python
I am trying to generate a 3D histogram using python. I tried the following code but I am getting an error too many values to unpack. from matplotlib import pyplot import pylab from mpl_toolkits.mplot3d import Axes3D import numpy fig = pylab.figure() ax = Axes3D(fig) data_filename = 'C:\csvfiles\luxury.txt' data_file = numpy.loadtxt(data_filename, delimiter=',') X = data_file[:,1] Y = data_file[:,2] Z = data_file[:,3] ax.hist(X, Y, Z) pyplot.show() What am I doing wrong?
[ "\"Too many values to unpack\" happens when you do something like this: \n(a, b) = (1, 2, 3)\n\nThat is, not enough variables on the left to accept all of the values on the right of the =. \nUpdate:\nTry: ax.hist( (X, Y, Z) )\nThe hist function wants a tuple as the first argument. \n" ]
[ 3 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0002018572_matplotlib_python.txt
Q: What is the relationship between '@1' and '@2' class SortedDict(dict): def __new__(cls, *args, **kwargs): instance = super(SortedDict, cls).__new__(cls, *args, **kwargs) instance.keyOrder = [] return instance def __setitem__(self, key, value): super(SortedDict, self).__setitem__(key, value)#@1 if key not in self.keyOrder:#@2 self.keyOrder.append(key) why make @2,why make a list 'keyOrder'. thanks A: The SortedDict is "A dictionary that keeps its keys in the order in which they're inserted." (See: documentation). Your @1 line is storing the key-value pair in the dictionary. The @2 stores the key in an internal list to maintain order. A: Because this is a Sorted dict. Dictionaries normally are unsorted, so this implementation adds a keyOrder to record the order that items are added.
What is the relationship between '@1' and '@2'
class SortedDict(dict): def __new__(cls, *args, **kwargs): instance = super(SortedDict, cls).__new__(cls, *args, **kwargs) instance.keyOrder = [] return instance def __setitem__(self, key, value): super(SortedDict, self).__setitem__(key, value)#@1 if key not in self.keyOrder:#@2 self.keyOrder.append(key) why make @2,why make a list 'keyOrder'. thanks
[ "The SortedDict is \"A dictionary that keeps its keys in the order in which they're inserted.\" (See: documentation). \nYour @1 line is storing the key-value pair in the dictionary. The @2 stores the key in an internal list to maintain order. \n", "Because this is a Sorted dict. Dictionaries normally are unsorted, so this implementation adds a keyOrder to record the order that items are added.\n" ]
[ 3, 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002018900_django_python.txt
Q: Problems with Trac post commit script (SyntaxError: invalid syntax) I've setup a post commit script found at http://trac.edgewall.org/browser/trunk/contrib/trac-post-commit-hook to associate changesets with tickets When I try to commit, I get the following error 'post-commit' hook failed with error output: File "/var/www/svn/repo/hooks/trac-post-commit-hook", line 101 (options, args) = parser.parse_args(sys.argv[1:]) ^ SyntaxError: invalid syntax I'm running Python 2.4.3 on CentOS. I'm not familiar with Python, so I can't really tell whats happening here and no one seems to have had this issue before (according to Google). I was hoping someone here would know what's going on. Thanks in advance. EDIT: If it helps, here is my post-commit script REPOS="$1" REV="$2" LOG='/usr/bin/svnlook log -r $REV $REPOS' AUTHOR='/usr/bin/svnlook author -r $REV $REPOS' TRAC_ENV="/var/www/trac/[xxx]/" TRAC_URL='http://trac.[xxx].com/' /usr/bin/python /var/www/svn/repo/hooks/trac-post-commit-hook -p "$TRAC_ENV" -r "$REV" -u "$AUTHOR" -m "$LOG" -s "$TRAC_URL" A: May be you have space or tab before (options,args)? may be like this. >>> (options, args) = parser.parse_args(sys.argv[1:]) >>> # this is fine >>> >>> (options, args) = parser.parse_args(sys.argv[1:]) File "<stdin>", line 1 (options, args) = parser.parse_args(sys.argv[1:]) ^ SyntaxError: invalid syntax >>> A: Wow, that is weird. The line is definitely valid syntax, and the Python version should also not be a problem since the script's copyright statement has the same year Python 2.4 was released in. Do you have multiple Python installations on your machine? If so, can you check whether /usr/bin/env python returns the correct one?
Problems with Trac post commit script (SyntaxError: invalid syntax)
I've setup a post commit script found at http://trac.edgewall.org/browser/trunk/contrib/trac-post-commit-hook to associate changesets with tickets When I try to commit, I get the following error 'post-commit' hook failed with error output: File "/var/www/svn/repo/hooks/trac-post-commit-hook", line 101 (options, args) = parser.parse_args(sys.argv[1:]) ^ SyntaxError: invalid syntax I'm running Python 2.4.3 on CentOS. I'm not familiar with Python, so I can't really tell whats happening here and no one seems to have had this issue before (according to Google). I was hoping someone here would know what's going on. Thanks in advance. EDIT: If it helps, here is my post-commit script REPOS="$1" REV="$2" LOG='/usr/bin/svnlook log -r $REV $REPOS' AUTHOR='/usr/bin/svnlook author -r $REV $REPOS' TRAC_ENV="/var/www/trac/[xxx]/" TRAC_URL='http://trac.[xxx].com/' /usr/bin/python /var/www/svn/repo/hooks/trac-post-commit-hook -p "$TRAC_ENV" -r "$REV" -u "$AUTHOR" -m "$LOG" -s "$TRAC_URL"
[ "May be you have space or tab before (options,args)? may be like this.\n>>> (options, args) = parser.parse_args(sys.argv[1:])\n>>> # this is fine\n>>>\n>>> (options, args) = parser.parse_args(sys.argv[1:])\n File \"<stdin>\", line 1\n (options, args) = parser.parse_args(sys.argv[1:])\n ^\nSyntaxError: invalid syntax\n>>>\n\n", "Wow, that is weird. The line is definitely valid syntax, and the Python version should also not be a problem since the script's copyright statement has the same year Python 2.4 was released in. Do you have multiple Python installations on your machine? If so, can you check whether /usr/bin/env python returns the correct one?\n" ]
[ 3, 2 ]
[]
[]
[ "post_commit", "python", "svn", "trac" ]
stackoverflow_0002018888_post_commit_python_svn_trac.txt
Q: Dynamically Naming Groups in Python Regular Expressions Is there a way to dynamically update the name of regex groups in Python? For example, if the text is: person 1: name1 person 2: name2 person 3: name3 ... person N: nameN How would you name groups 'person1', 'person2', 'person3', ..., and 'personN' without knowing beforehand how many people there are? A: No, but you can do something like this: >>> import re >>> p = re.compile('(?m)^(.*?)\\s*:\\s*(.*)$') >>> text = '''person 1: name1 person 2: name2 person 3: name3 ... person N: nameN''' >>> p.findall(text) output: [('person 1', 'name1'), ('person 2', 'name2'), ('person 3', 'name3'), ('person N', 'nameN')] A quick explanation: (?m) # enable multi-line mode ^ # match the start of a new line (.*?) # un-greedily match zero or more chars and store it in match group 1 \s*:\s* # match a colon possibly surrounded by space chars (.*) # match the rest of the line and store it in match group 2 $ # match the end of the line References multi-line mode: http://www.regular-expressions.info/modifiers.html greedy/ungreedy matching: http://www.regular-expressions.info/repeat.html match groups http://www.regular-expressions.info/brackets.html A: named capture groups and numbered groups (\1, \2, etc.) cannot be dynamic, but you can achieve the same thing with findall: re.findall(pattern, string[, flags]) Return all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result unless they touch the beginning of another match. A: judging from your accepted answer, there's no need for regex p=""" person 1: name1 person 2: name2 person 3: name3 person N: nameN """ ARR=[] for item in p.split("\n"): if item: s=item.split(":") ARR.append(s) print ARR output $ ./python.py [['person 1', ' name1'], ['person 2', ' name2'], ['person 3', ' name3'], ['person N', ' nameN']] A: Regexes in Python (and I'm pretty certain that that's true for regexes in general) don't allow for an arbitrary number of matches. You can either capture a repeated match in its entirety (by placing capturing parentheses around a repeated group) or capture the last match in a series of matches (by repeating a capturing group). This is independent of whether these are named or numbered capturing groups. You need to do this programmatically by iterating over all matches in a string, like for match in re.findall(pattern, string): do_something(match)
Dynamically Naming Groups in Python Regular Expressions
Is there a way to dynamically update the name of regex groups in Python? For example, if the text is: person 1: name1 person 2: name2 person 3: name3 ... person N: nameN How would you name groups 'person1', 'person2', 'person3', ..., and 'personN' without knowing beforehand how many people there are?
[ "No, but you can do something like this:\n>>> import re\n>>> p = re.compile('(?m)^(.*?)\\\\s*:\\\\s*(.*)$')\n>>> text = '''person 1: name1\nperson 2: name2\nperson 3: name3\n...\nperson N: nameN'''\n>>> p.findall(text)\n\noutput:\n[('person 1', 'name1'), ('person 2', 'name2'), ('person 3', 'name3'), ('person N', 'nameN')]\n\nA quick explanation:\n(?m) # enable multi-line mode\n^ # match the start of a new line\n(.*?) # un-greedily match zero or more chars and store it in match group 1\n\\s*:\\s* # match a colon possibly surrounded by space chars\n(.*) # match the rest of the line and store it in match group 2\n$ # match the end of the line\n\nReferences\n\nmulti-line mode: http://www.regular-expressions.info/modifiers.html\ngreedy/ungreedy matching: http://www.regular-expressions.info/repeat.html\nmatch groups http://www.regular-expressions.info/brackets.html\n\n", "named capture groups and numbered groups (\\1, \\2, etc.) cannot be dynamic, but you can achieve the same thing with findall:\n\nre.findall(pattern, string[, flags])\nReturn all non-overlapping matches of pattern in string, as a list of\n strings. The string is scanned\n left-to-right, and matches are\n returned in the order found. If one or\n more groups are present in the\n pattern, return a list of groups; this\n will be a list of tuples if the\n pattern has more than one group. Empty\n matches are included in the result\n unless they touch the beginning of\n another match.\n\n", "judging from your accepted answer, there's no need for regex\np=\"\"\"\nperson 1: name1\nperson 2: name2\nperson 3: name3\nperson N: nameN\n\"\"\"\n\nARR=[]\nfor item in p.split(\"\\n\"):\n if item:\n s=item.split(\":\")\n ARR.append(s)\nprint ARR\n\noutput\n$ ./python.py\n[['person 1', ' name1'], ['person 2', ' name2'], ['person 3', ' name3'], ['person N', ' nameN']]\n\n", "Regexes in Python (and I'm pretty certain that that's true for regexes in general) don't allow for an arbitrary number of matches. You can either capture a repeated match in its entirety (by placing capturing parentheses around a repeated group) or capture the last match in a series of matches (by repeating a capturing group). This is independent of whether these are named or numbered capturing groups.\nYou need to do this programmatically by iterating over all matches in a string, like\nfor match in re.findall(pattern, string):\n do_something(match)\n\n" ]
[ 2, 1, 1, 0 ]
[]
[]
[ "python", "regex", "regex_group" ]
stackoverflow_0002019005_python_regex_regex_group.txt
Q: using python expect to run openvpn i need a python script to run open vpn automaticaly but i use sudo for run the open vpn sudo openvpn --cd /etc/openvpn --config openvpn.conf & thats my terminal command. i have to give the password for sudo, can i use pexpect to run that command? and i have to get the exit code because i want to know that the openvpn is run succesful or not thanks A: You can change /etc/sudoers so that openvpn command can be run without giving the password. yourusername ALL=(all) NOPASSWD: /path/to/openvpn and in python, do something like: import subprocess exitcode = subprocess.call(["sudo","openvpn","--cd /etc/openvpn --config openvpn.conf"])
using python expect to run openvpn
i need a python script to run open vpn automaticaly but i use sudo for run the open vpn sudo openvpn --cd /etc/openvpn --config openvpn.conf & thats my terminal command. i have to give the password for sudo, can i use pexpect to run that command? and i have to get the exit code because i want to know that the openvpn is run succesful or not thanks
[ "You can change /etc/sudoers so that openvpn command can be run without giving the password. \nyourusername ALL=(all) NOPASSWD: /path/to/openvpn\n\nand in python, do something like:\nimport subprocess\nexitcode = subprocess.call([\"sudo\",\"openvpn\",\"--cd /etc/openvpn --config openvpn.conf\"])\n\n" ]
[ 4 ]
[]
[]
[ "expect", "openvpn", "python" ]
stackoverflow_0002018606_expect_openvpn_python.txt
Q: How to wait for messages on multiple queues using py-amqplib I'm using py-amqplib to access RabbitMQ in Python. The application receives requests to listen on certain MQ topics from time to time. The first time it receives such a request it creates an AMQP connection and a channel and starts a new thread to listen for messages: connection = amqp.Connection(host = host, userid = "guest", password = "guest", virtual_host = "/", insist = False) channel = connection.channel() listener = AMQPListener(channel) listener.start() AMQPListener is very simple: class AMQPListener(threading.Thread): def __init__(self, channel): threading.Thread.__init__(self) self.__channel = channel def run(self): while True: self.__channel.wait() After creating the connection it subscribes to the topic of interest, like this: channel.queue_declare(queue = queueName, exclusive = False) channel.exchange_declare(exchange = MQ_EXCHANGE_NAME, type = "direct", durable = False, auto_delete = True) channel.queue_bind(queue = queueName, exchange = MQ_EXCHANGE_NAME, routing_key = destination) def receive_callback(msg): self.queue.put(msg.body) channel.basic_consume(queue = queueName, no_ack = True, callback = receive_callback) The first time this all works fine. However, it fails on a subsequent request to subscribe to another topic. On subsequent requests I re-use the AMQP connection and AMQPListener thread (since I don't want to start a new thread for each topic) and when I call the code block above the channel.queue_declare() method call never returns. I've also tried creating a new channel at that point and the connection.channel() call never returns, either. The only way I've been able to get it to work is to create a new connection, channel and listener thread per topic (ie. routing_key), but this is really not ideal. I suspect it's the wait() method that's somehow blocking the entire connection, but I'm not sure what to do about it. Surely I should be able to receive messages with several routing keys (or even on several channels) using a single listener thread? A related question is: how do I stop the listener thread when that topic is no longer of interest? The channel.wait() call appears to block forever if there are no messages. The only way I can think of is to send a dummy message to the queue that would "poison" it, ie. be interpreted by the listener as a signal to stop. A: If you want more than one comsumer per channel just attach another one using basic_consume() and use channel.wait() after. It will listen to all queues attached via basic_consume(). Make sure you define different consumer tags for each basic_consume(). Use channel.basic_cancel(consumer_tag) if you want to cancel a specific consumer on a queue (cancelling listen to a specific topic).
How to wait for messages on multiple queues using py-amqplib
I'm using py-amqplib to access RabbitMQ in Python. The application receives requests to listen on certain MQ topics from time to time. The first time it receives such a request it creates an AMQP connection and a channel and starts a new thread to listen for messages: connection = amqp.Connection(host = host, userid = "guest", password = "guest", virtual_host = "/", insist = False) channel = connection.channel() listener = AMQPListener(channel) listener.start() AMQPListener is very simple: class AMQPListener(threading.Thread): def __init__(self, channel): threading.Thread.__init__(self) self.__channel = channel def run(self): while True: self.__channel.wait() After creating the connection it subscribes to the topic of interest, like this: channel.queue_declare(queue = queueName, exclusive = False) channel.exchange_declare(exchange = MQ_EXCHANGE_NAME, type = "direct", durable = False, auto_delete = True) channel.queue_bind(queue = queueName, exchange = MQ_EXCHANGE_NAME, routing_key = destination) def receive_callback(msg): self.queue.put(msg.body) channel.basic_consume(queue = queueName, no_ack = True, callback = receive_callback) The first time this all works fine. However, it fails on a subsequent request to subscribe to another topic. On subsequent requests I re-use the AMQP connection and AMQPListener thread (since I don't want to start a new thread for each topic) and when I call the code block above the channel.queue_declare() method call never returns. I've also tried creating a new channel at that point and the connection.channel() call never returns, either. The only way I've been able to get it to work is to create a new connection, channel and listener thread per topic (ie. routing_key), but this is really not ideal. I suspect it's the wait() method that's somehow blocking the entire connection, but I'm not sure what to do about it. Surely I should be able to receive messages with several routing keys (or even on several channels) using a single listener thread? A related question is: how do I stop the listener thread when that topic is no longer of interest? The channel.wait() call appears to block forever if there are no messages. The only way I can think of is to send a dummy message to the queue that would "poison" it, ie. be interpreted by the listener as a signal to stop.
[ "If you want more than one comsumer per channel just attach another one using basic_consume() and use channel.wait() after. It will listen to all queues attached via basic_consume(). Make sure you define different consumer tags for each basic_consume().\nUse channel.basic_cancel(consumer_tag) if you want to cancel a specific consumer on a queue (cancelling listen to a specific topic).\n" ]
[ 1 ]
[]
[]
[ "amqp", "message_queue", "py_amqplib", "python", "rabbitmq" ]
stackoverflow_0001807113_amqp_message_queue_py_amqplib_python_rabbitmq.txt
Q: Python Instantiating SubClasses I wrote the following code trying to figure out how to instantiate the subclasses within the main class.. I came up with something that doesn't feel right.. at least for me. Is there something wrong with this type of instancing? Is there a better way to call subclasses? class Family(): def __init__(self): self.Father = self.Father(self) self.Mother = self.Mother(self) class Father(): def __init__(self, instance = ''): self = instance if instance != '' else self print self def method(self): print "Father Method" def fatherMethod(self): print "Father Method" class Mother(): def __init__(self, instance = ''): self = instance if instance != '' else self print self def method(self): print "Mother Method" def motherMethod(self): print "Mother Method" if __name__ == "__main__": Family = Family() Family.Father.method() Family.Mother.method() A: What you've defined there are not (in Python terminology at least) subclasses - they're inner classes, or nested classes. I'm guessing that this isn't actually what you were trying to achieve, but I'm not sure what you did actually want - but here are my four best guesses: A subclass is where the class inheriting from another class is called a subclass. To make father a subclass of family, use the syntax class Father(Family):. What you've created here is actually called an Inner Class, not a subclass. When you see something like Family.Father.method(), it often means Family is a module and Father is a class in that module. In Python, module basically means .py file. A module doesn't have an __init__ method, but all code at the top level of the module (such as the if __name__ ... line) gets executed when a module is imported. Similarly, you could make Family a package - which in Python basically means a directory on the filesystem containing an __init__.py file. Father and Mother would then be modules or classes within the package Possibly what you're trying to achieve is declare that an object of type Family always has a Father object and a Mother object. This doesn't require nested classes (in fact, nested classes are a completely bizarre way to do this). Just use: >>> class Mother(): ... def whoami(self): ... print "I'm a mother" ... >>> class Father(): ... def whoami(self): ... print "I'm a father" ... >>> class Family(): ... def __init__(self): ... self.mother = Mother() ... self.father = Father() ... >>> f = Family() >>> f.father.whoami() I'm a father >>> f.mother.whoami() I'm a mother >>> A: You are right, this code does not feel right. My questions would be .. What are you trying to achieve? There is not need to define Father and Mother inside Family, they could be defined outside Family and aggregated into it. (Is it the fact, that Father and Mother should not be accessed outside of a Family? Python has no visibility modifiers, e.g. because of a principle that goes: 'we are all grown-up here', meaning that developers should be responsible and assume responsible handling of code ...) Do you really need something like Class.Class.method? Beside the fact, that method lookups are a little costly, these kind of chains may indicate a wrong axis, meaning you're trying to take hold of functionality from a not very clearly designed point (sorry for being so blurry here.) A: Blergh. Why are Father and Mother nested under Family? There's no reason to do this. Define them outside, then instantiate them inside. I'm not sure exactly what you want to do. You may want to look into Descriptors, which are a way of defining sub-objects within a clss.
Python Instantiating SubClasses
I wrote the following code trying to figure out how to instantiate the subclasses within the main class.. I came up with something that doesn't feel right.. at least for me. Is there something wrong with this type of instancing? Is there a better way to call subclasses? class Family(): def __init__(self): self.Father = self.Father(self) self.Mother = self.Mother(self) class Father(): def __init__(self, instance = ''): self = instance if instance != '' else self print self def method(self): print "Father Method" def fatherMethod(self): print "Father Method" class Mother(): def __init__(self, instance = ''): self = instance if instance != '' else self print self def method(self): print "Mother Method" def motherMethod(self): print "Mother Method" if __name__ == "__main__": Family = Family() Family.Father.method() Family.Mother.method()
[ "What you've defined there are not (in Python terminology at least) subclasses - they're inner classes, or nested classes. I'm guessing that this isn't actually what you were trying to achieve, but I'm not sure what you did actually want - but here are my four best guesses:\n\nA subclass is where the class inheriting from another class is called a subclass. To make father a subclass of family, use the syntax class Father(Family):. What you've created here is actually called an Inner Class, not a subclass.\nWhen you see something like Family.Father.method(), it often means Family is a module and Father is a class in that module. In Python, module basically means .py file. A module doesn't have an __init__ method, but all code at the top level of the module (such as the if __name__ ... line) gets executed when a module is imported.\nSimilarly, you could make Family a package - which in Python basically means a directory on the filesystem containing an __init__.py file. Father and Mother would then be modules or classes within the package\nPossibly what you're trying to achieve is declare that an object of type Family always has a Father object and a Mother object. This doesn't require nested classes (in fact, nested classes are a completely bizarre way to do this). Just use:\n\n\n>>> class Mother():\n... def whoami(self):\n... print \"I'm a mother\"\n... \n>>> class Father():\n... def whoami(self):\n... print \"I'm a father\"\n...\n>>> class Family():\n... def __init__(self):\n... self.mother = Mother()\n... self.father = Father()\n... \n>>> f = Family()\n>>> f.father.whoami()\nI'm a father\n>>> f.mother.whoami()\nI'm a mother\n>>> \n\n", "You are right, this code does not feel right. My questions would be ..\n\nWhat are you trying to achieve? There is not need to define Father and Mother inside Family, they could be defined outside Family and aggregated into it. (Is it the fact, that Father and Mother should not be accessed outside of a Family? Python has no visibility modifiers, e.g. because of a principle that goes: 'we are all grown-up here', meaning that developers should be responsible and assume responsible handling of code ...)\nDo you really need something like Class.Class.method? Beside the fact, that method lookups are a little costly, these kind of chains may indicate a wrong axis, meaning you're trying to take hold of functionality from a not very clearly designed point (sorry for being so blurry here.)\n\n", "Blergh.\nWhy are Father and Mother nested under Family? There's no reason to do this. Define them outside, then instantiate them inside.\nI'm not sure exactly what you want to do. You may want to look into Descriptors, which are a way of defining sub-objects within a clss.\n" ]
[ 6, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002019415_python.txt
Q: how to use 'pickle' my code(i was unable to use 'pickle'): class A(object): def __getstate__(self): print 'www' return 'sss' def __setstate__(self,d): print 'aaaa' import pickle a = A() s = pickle.dumps(a) e = pickle.loads(s) print s,e print : www aaaa ccopy_reg _reconstructor p0 (c__main__ A p1 c__builtin__ object p2 Ntp3 Rp4 S'sss' p5 b. <__main__.A object at 0x00B08CF0> who can tell me how to use. A: What are you trying to do? It works for me: class A(object): def __init__(self): self.val = 100 def __str__(self): """What a looks like if your print it""" return 'A:'+str(self.val) import pickle a = A() a_pickled = pickle.dumps(a) a.val = 200 a2 = pickle.loads(a_pickled) print 'the original a' print a print # newline print 'a2 - a clone of a before we changed the value' print a2 print print 'Why are you trying to use __setstate__, not __init__?' print So this will print: the original a A:200 a2 - a clone of a before we changed the value A:100 If you need setstate: class B(object): def __init__(self): print 'Perhaps __init__ must not happen twice?' print self.val = 100 def __str__(self): """What a looks like if your print it""" return 'B:'+str(self.val) def __getstate__(self): return self.val def __setstate__(self,val): self.val = val b = B() b_pickled = pickle.dumps(b) b.val = 200 b2 = pickle.loads(b_pickled) print 'the original b' print b print # newline print 'b2 - b clone of b before we changed the value' print b2 which prints: Why are you trying to use __setstate__, not __init__? Perhaps __init__ must not happen twice? the original b B:200 b2 - b clone of b before we changed the value B:100 A: You are able to pickle (meaning, this code works as it should). You just seem to get a result, you don't expect. If you expect the same 'output', try: import pickle a = A() s = pickle.dumps(a) e = pickle.loads(s) print s, pickle.dumps(e) Your example isn't, well, a typical 'pickling' example. Usually pickled objects are saved somewhere persistently or sent over the wire. See e.g. pickletest.py: http://www.sthurlow.com/python/lesson10/. There are advanced uses of pickling, see for example David Mertz XML object serialisation article: http://www.ibm.com/developerworks/xml/library/x-matters11.html A: In a nutshell, in your example, e equals a. Don't have to care about these strang strings, you can dumps these strings to save to anywhere, just remember when you loads them, you got 'a' object again.
how to use 'pickle'
my code(i was unable to use 'pickle'): class A(object): def __getstate__(self): print 'www' return 'sss' def __setstate__(self,d): print 'aaaa' import pickle a = A() s = pickle.dumps(a) e = pickle.loads(s) print s,e print : www aaaa ccopy_reg _reconstructor p0 (c__main__ A p1 c__builtin__ object p2 Ntp3 Rp4 S'sss' p5 b. <__main__.A object at 0x00B08CF0> who can tell me how to use.
[ "What are you trying to do? It works for me:\nclass A(object):\n def __init__(self):\n self.val = 100\n\n def __str__(self):\n \"\"\"What a looks like if your print it\"\"\"\n return 'A:'+str(self.val)\n\nimport pickle\na = A()\na_pickled = pickle.dumps(a)\na.val = 200\na2 = pickle.loads(a_pickled)\nprint 'the original a'\nprint a\nprint # newline\nprint 'a2 - a clone of a before we changed the value'\nprint a2\nprint \n\nprint 'Why are you trying to use __setstate__, not __init__?'\nprint\n\nSo this will print:\nthe original a\nA:200\n\na2 - a clone of a before we changed the value\nA:100\n\nIf you need setstate:\nclass B(object):\n def __init__(self):\n print 'Perhaps __init__ must not happen twice?'\n print\n self.val = 100\n\n def __str__(self):\n \"\"\"What a looks like if your print it\"\"\"\n return 'B:'+str(self.val)\n\n def __getstate__(self):\n return self.val\n\n def __setstate__(self,val):\n self.val = val\n\nb = B()\nb_pickled = pickle.dumps(b)\nb.val = 200\nb2 = pickle.loads(b_pickled)\nprint 'the original b'\nprint b\nprint # newline\nprint 'b2 - b clone of b before we changed the value'\nprint b2\n\nwhich prints:\nWhy are you trying to use __setstate__, not __init__?\n\nPerhaps __init__ must not happen twice?\n\nthe original b\nB:200\n\nb2 - b clone of b before we changed the value\nB:100\n\n", "You are able to pickle (meaning, this code works as it should). You just seem to get a result, you don't expect. If you expect the same 'output', try:\nimport pickle\na = A()\ns = pickle.dumps(a)\ne = pickle.loads(s)\nprint s, pickle.dumps(e)\n\nYour example isn't, well, a typical 'pickling' example. Usually pickled objects are saved somewhere persistently or sent over the wire. See e.g. pickletest.py: http://www.sthurlow.com/python/lesson10/.\nThere are advanced uses of pickling, see for example David Mertz XML object serialisation article: http://www.ibm.com/developerworks/xml/library/x-matters11.html\n", "In a nutshell, in your example, e equals a.\nDon't have to care about these strang strings, you can dumps these strings to save to anywhere, just remember when you loads them, you got 'a' object again. \n" ]
[ 4, 3, 0 ]
[]
[]
[ "pickle", "python" ]
stackoverflow_0002019489_pickle_python.txt
Q: Integer division compared to floored quotient: why this surprising result? The // "integer division" operator of Python surprised me, today: >>> math.floor(11/1.1) 10.0 >>> 11//1.1 9.0 The documentation reads "(floored) quotient of x and y". So, why is math.floor(11/1.1) equal to 10, but 11//1.1 equal to 9? A: Because 1.1 can't be represented in binary form exactly; the approximation is a littler higher than 1.1 - therefore the division result is a bit too small. Try the following: Under Python 2, type at the console: >>> 1.1 1.1000000000000001 In Python 3.1, the console will display 1.1, but internally, it's still the same number. But: >>> 11/1.1 10.0 As gnibbler points out, this is the result of "internal rounding" within the available precision limits of floats. And as The MYYN points out in his comment, // uses a different algorithm to calculate the floor division result than math.floor() in order to preserve a == (a//b)*b + a%b as well as possible. Use the Decimal type if you need this precision.
Integer division compared to floored quotient: why this surprising result?
The // "integer division" operator of Python surprised me, today: >>> math.floor(11/1.1) 10.0 >>> 11//1.1 9.0 The documentation reads "(floored) quotient of x and y". So, why is math.floor(11/1.1) equal to 10, but 11//1.1 equal to 9?
[ "Because 1.1 can't be represented in binary form exactly; the approximation is a littler higher than 1.1 - therefore the division result is a bit too small. \nTry the following:\nUnder Python 2, type at the console:\n>>> 1.1\n1.1000000000000001\n\nIn Python 3.1, the console will display 1.1, but internally, it's still the same number.\nBut:\n>>> 11/1.1\n10.0\n\nAs gnibbler points out, this is the result of \"internal rounding\" within the available precision limits of floats. And as The MYYN points out in his comment, // uses a different algorithm to calculate the floor division result than math.floor() in order to preserve a == (a//b)*b + a%b as well as possible.\nUse the Decimal type if you need this precision.\n" ]
[ 6 ]
[]
[]
[ "floor", "integer_division", "python", "python_2.x", "python_3.x" ]
stackoverflow_0002019588_floor_integer_division_python_python_2.x_python_3.x.txt
Q: How to import a variable from different file types I am trying to obtain a variable from a different file type and import it into a Python script. The file is version.mk, it has a variable called VARIABLE_ID. The import module does not work as normally, is there any way to call variables from other file types? Thanks for any help import os from version import VERSION_ID def versionid: print VERSION_ID This is the code that does not work. The version ID is 0.0.2 format. When I run the below code it says there is a syntax error in the number. I have read that distutils has a version numbering convention. I am not sure how this could be used, has anyone heard or know how this works? Is there a way of having cooments in this file, when comments are in the file it interferes with the file. Could the read() just read the version_id and not the comments, thanks VERSION_ID=map(int,re.match("VERSION_ID\s*=\s*(\S+)",open("version.mk").read()).group(1).split(".")) A: If you are sure about version.mk is valid python file, and does not have any harm codes, you can execute it. >>> exec(open("version.mk")) >>> print VERSION_ID 1 UPDATE: because OP Added VERSION_ID is not a valid python number version.mk #version no is here VERSION_ID=0.0.2 #some more info here .... - >>> import re >>> VERSION_ID=map(int,re.search("VERSION_ID\s*=\s*(\S+)",open("version.mk").read()).group(1).split(".")) >>> VERSION_ID [0, 0, 2] A: If your file isn't Python code, you can't import it as if it were. You need to open the file manually and parse for the setting. Especially if the line containing the number is something like VERSION_ID = 0.0.2 Since this can never be valid Python (there's no literal that looks like that). This might be a case where a regular expression makes sense, something like r'VERSION_ID\s*=\s*([0-9.]+) could work.
How to import a variable from different file types
I am trying to obtain a variable from a different file type and import it into a Python script. The file is version.mk, it has a variable called VARIABLE_ID. The import module does not work as normally, is there any way to call variables from other file types? Thanks for any help import os from version import VERSION_ID def versionid: print VERSION_ID This is the code that does not work. The version ID is 0.0.2 format. When I run the below code it says there is a syntax error in the number. I have read that distutils has a version numbering convention. I am not sure how this could be used, has anyone heard or know how this works? Is there a way of having cooments in this file, when comments are in the file it interferes with the file. Could the read() just read the version_id and not the comments, thanks VERSION_ID=map(int,re.match("VERSION_ID\s*=\s*(\S+)",open("version.mk").read()).group(1).split("."))
[ "If you are sure about version.mk is valid python file, and does not have any harm codes, you can execute it.\n>>> exec(open(\"version.mk\"))\n>>> print VERSION_ID\n1\n\n\nUPDATE: because OP Added VERSION_ID is not a valid python number\nversion.mk \n#version no is here\nVERSION_ID=0.0.2\n\n#some more info here\n....\n\n-\n>>> import re\n>>> VERSION_ID=map(int,re.search(\"VERSION_ID\\s*=\\s*(\\S+)\",open(\"version.mk\").read()).group(1).split(\".\"))\n>>> VERSION_ID\n[0, 0, 2]\n\n", "If your file isn't Python code, you can't import it as if it were.\nYou need to open the file manually and parse for the setting. Especially if the line containing the number is something like\nVERSION_ID = 0.0.2\n\nSince this can never be valid Python (there's no literal that looks like that).\nThis might be a case where a regular expression makes sense, something like r'VERSION_ID\\s*=\\s*([0-9.]+) could work.\n" ]
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002019552_python.txt
Q: SFTP using ftplib I need to download a file from a host using SFTP. Do you know if is it possible to do that using Python ftplib? I saw an example here, but when I try to connect I receive EOFError. I tried this code: import ftplib ftp = ftplib.FTP() ftp.connect( "1.2.3.4", "22" ) This method returns with an error after long time so I cannot perform a call to login. I cannot try the constructor FTP([host[, user[, passwd[, acct[, timeout]]]]]) because my port is 22 but ftplib default is 21. If I follow the example ftp = ftplib.FTP("1.2.3.4") ftp = ftplib.FTP("1.2.3.4","22") I receive a connection refused so I cannot enter any username password. Can you help me? Thank you very much A: As the question you linked to states, ftplib doesn't support SFTP (which is a transfer protocol over SSH and has nothing to do with FTPS, FTP over SSL). Use the recommended Paramiko instead.
SFTP using ftplib
I need to download a file from a host using SFTP. Do you know if is it possible to do that using Python ftplib? I saw an example here, but when I try to connect I receive EOFError. I tried this code: import ftplib ftp = ftplib.FTP() ftp.connect( "1.2.3.4", "22" ) This method returns with an error after long time so I cannot perform a call to login. I cannot try the constructor FTP([host[, user[, passwd[, acct[, timeout]]]]]) because my port is 22 but ftplib default is 21. If I follow the example ftp = ftplib.FTP("1.2.3.4") ftp = ftplib.FTP("1.2.3.4","22") I receive a connection refused so I cannot enter any username password. Can you help me? Thank you very much
[ "As the question you linked to states, ftplib doesn't support SFTP (which is a transfer protocol over SSH and has nothing to do with FTPS, FTP over SSL). Use the recommended Paramiko instead.\n" ]
[ 21 ]
[]
[]
[ "ftplib", "python", "sftp" ]
stackoverflow_0002019780_ftplib_python_sftp.txt
Q: Error when install python mysql module on windows? When i try to install mysql on windows i get this error MySQL-python-0.9.2>python setup.py build running build running build_py running build_ext building '_mysql' extension error: Unable to find vcvarsall.bat A: I guess, you don't have visual c++ compiler installed or compiler not in the PATH. If you have mingw32, you can pass paramter -c mingw32 And mysql-python is available as binary in windows, you may not need to compile yourself. UPDATE: OP is using python 2.6, no binaries for 1.2.3 in mysql-python page for windows. Here is the one I have compiled before
Error when install python mysql module on windows?
When i try to install mysql on windows i get this error MySQL-python-0.9.2>python setup.py build running build running build_py running build_ext building '_mysql' extension error: Unable to find vcvarsall.bat
[ "I guess, you don't have visual c++ compiler installed or compiler not in the PATH.\nIf you have mingw32, you can pass paramter -c mingw32\nAnd mysql-python is available as binary in windows, you may not need to compile yourself.\nUPDATE: OP is using python 2.6, no binaries for 1.2.3 in mysql-python page for windows.\nHere is the one I have compiled before \n" ]
[ 5 ]
[]
[]
[ "mysql", "python", "windows" ]
stackoverflow_0002019827_mysql_python_windows.txt
Q: https username and pwd + saving file with webbrowser I would like to use python webbrowser to access a secure https page and save it into a file. Am I right if I say that with webbrowser control is not possible to save an entire web page but only opening a URL? I didn't see any 'save' method. Other than this, the page I want to use is a secure http page and I don't know how to automatically provide username and password for authentication into my script. Can you help me in solving one of the 2 issues above? Thank you very much Mn A: Save means "Write a file to the disk". Of course there's no "save" method. The library opens the URL so your program can read it. Period. If your program wants to write it to disk, that's not part of reading a URL, so it's not part of browsing. Use urllib2 for this. Not the webbrowser. It's much, much simpler. Read Python Authentication with urllib2 for help in using urllib2.
https username and pwd + saving file with webbrowser
I would like to use python webbrowser to access a secure https page and save it into a file. Am I right if I say that with webbrowser control is not possible to save an entire web page but only opening a URL? I didn't see any 'save' method. Other than this, the page I want to use is a secure http page and I don't know how to automatically provide username and password for authentication into my script. Can you help me in solving one of the 2 issues above? Thank you very much Mn
[ "\nSave means \"Write a file to the disk\". Of course there's no \"save\" method. The library opens the URL so your program can read it. Period. If your program wants to write it to disk, that's not part of reading a URL, so it's not part of browsing.\nUse urllib2 for this. Not the webbrowser. It's much, much simpler.\nRead Python Authentication with urllib2 for help in using urllib2.\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0002019482_python.txt
Q: python vs java on web service development? i am currently using php as backend language in webdevelopment. but im wondering what you need to install to get running with python and java. with php i need apache and mysql. can i use those for java and python too? i cant find good guides equivalent to LAMP/MAMP/WAMP so i understand the parts when using either java or python. would be great if you could give me some good links on the installation and what is required. and i have read that its easier with python. but is this the only advantage of using python instead of java. cause with java i can create java applets, desktop and mobile applications. they all tend to have java installed. but not python. so why should i use python instead of java. A: You need to look into the Web Application Framework subject. Some SO pointers: simple-webserver-or-web-testing-framework web-application-frameworks-c-vs-python django-vs-other-python-web-frameworks what-web-application-framework-for-java-is-recommended can-anyone-recommend-a-simple-java-web-app-framework ... Good luck. A: I can only give suggestions for web development in python: Use Tornado - A non blocking web server. Use Jinja2 - A templating engine. Use MongoDB - A schema less database server | You can also use any RDBMS according to your requirement. Above 3 tools are enough to build a web application in python. or you can always choose Django - The giant web framework with all the features required to build a scalable web application in python. A: web2py is a python web framework that is completely self-contained, runs portably off a USB drive even. The manual is available on scribd, and after an hour or two of tutorial you will have a pretty good idea of what a python web framework will be like. I can't comment on Java at all. EDIT: Django and web2py are very, very similar. I think I prefer web2py because it does more for me that I don't have to do, but from the POV of, say, Java frameworks, Django and web2py may as well be the same thing.
python vs java on web service development?
i am currently using php as backend language in webdevelopment. but im wondering what you need to install to get running with python and java. with php i need apache and mysql. can i use those for java and python too? i cant find good guides equivalent to LAMP/MAMP/WAMP so i understand the parts when using either java or python. would be great if you could give me some good links on the installation and what is required. and i have read that its easier with python. but is this the only advantage of using python instead of java. cause with java i can create java applets, desktop and mobile applications. they all tend to have java installed. but not python. so why should i use python instead of java.
[ "You need to look into the Web Application Framework subject. Some SO pointers:\n\nsimple-webserver-or-web-testing-framework\nweb-application-frameworks-c-vs-python\ndjango-vs-other-python-web-frameworks\nwhat-web-application-framework-for-java-is-recommended\ncan-anyone-recommend-a-simple-java-web-app-framework\n...\n\nGood luck.\n", "I can only give suggestions for web development in python:\n\nUse Tornado - A non blocking web server.\nUse Jinja2 - A templating engine.\nUse MongoDB - A schema less database server | You can also use any RDBMS according to your requirement.\n\nAbove 3 tools are enough to build a web application in python.\nor you can always choose Django - The giant web framework with all the features required to build a scalable web application in python.\n", "web2py is a python web framework that is completely self-contained, runs portably off a USB drive even. The manual is available on scribd, and after an hour or two of tutorial you will have a pretty good idea of what a python web framework will be like. I can't comment on Java at all.\nEDIT: Django and web2py are very, very similar. I think I prefer web2py because it does more for me that I don't have to do, but from the POV of, say, Java frameworks, Django and web2py may as well be the same thing.\n" ]
[ 4, 4, 2 ]
[]
[]
[ "java", "python" ]
stackoverflow_0002019621_java_python.txt
Q: Python basic maths My friend wrote up this script for me to calculate the quantity of construction materials needed for a theoretical site. It basically takes 2 numbers and increases them independently until the large number reaches 50,000. It then prints a list like this: 20000:6.40,21000:6.61,22000:6.82,23000:7.03,24000:7.24,25000:7.45,26000:7.66,27000:7.87,28000:8.08,29000:8.29,30000:8.50,31000:8.71,32000:8.92,33000:9.13,34000:9.34,35000:9.55,36000:9.76,37000:9.97,38000:10.18,39000:10.39,40000:10.60,41000:10.81,42000:11.02,43000:11.23,44000:11.44,45000:11.65,46000:11.86,47000:12.07,48000:12.28,49000:12.49,50000:12.70 I need to make a small edit to the code so that the small number is multiplied by 1.225 when it is printed. I do not want this to be compounded as I want to keep the increment the same. getbingint = input("Enter big start value: ") getbiginc = input("Enter big increment value: ") getsmallint = input("Enter small start value: ") getsmalinc = input("Enter small increment value: ") getbigend = input("Enter big end value: ") string = "" while getbingint <= getbigend: string += str(getbingint) + ":" + str("%.2f") % getsmallint + "," getbingint += getbiginc getsmallint += getsmalinc print string raw_input() A: Replace the line: string += str(getbingint) + ":" + str("%.2f") % getsmallint + "," with string += str(getbingint) + ":" + str("%.2f") % (getsmallint*1.225) + "," A: You can replace string += str(getsmallint) with string += str(getsmallint*1.225) A: here's another version getbingint = input("Enter big start value: ") getbiginc = input("Enter big increment value: ") getsmallint = input("Enter small start value: ") getsmalinc = input("Enter small increment value: ") getbigend = input("Enter big end value: ") for i in range(getbingint,getbigend,getbiginc+1): getsmallint += getsmalinc print str(i) +":"+ str("%.2f") % (getsmallint*1.225) + ",",
Python basic maths
My friend wrote up this script for me to calculate the quantity of construction materials needed for a theoretical site. It basically takes 2 numbers and increases them independently until the large number reaches 50,000. It then prints a list like this: 20000:6.40,21000:6.61,22000:6.82,23000:7.03,24000:7.24,25000:7.45,26000:7.66,27000:7.87,28000:8.08,29000:8.29,30000:8.50,31000:8.71,32000:8.92,33000:9.13,34000:9.34,35000:9.55,36000:9.76,37000:9.97,38000:10.18,39000:10.39,40000:10.60,41000:10.81,42000:11.02,43000:11.23,44000:11.44,45000:11.65,46000:11.86,47000:12.07,48000:12.28,49000:12.49,50000:12.70 I need to make a small edit to the code so that the small number is multiplied by 1.225 when it is printed. I do not want this to be compounded as I want to keep the increment the same. getbingint = input("Enter big start value: ") getbiginc = input("Enter big increment value: ") getsmallint = input("Enter small start value: ") getsmalinc = input("Enter small increment value: ") getbigend = input("Enter big end value: ") string = "" while getbingint <= getbigend: string += str(getbingint) + ":" + str("%.2f") % getsmallint + "," getbingint += getbiginc getsmallint += getsmalinc print string raw_input()
[ "Replace the line:\nstring += str(getbingint) + \":\" + str(\"%.2f\") % getsmallint + \",\" \n\nwith\nstring += str(getbingint) + \":\" + str(\"%.2f\") % (getsmallint*1.225) + \",\" \n\n", "You can replace string += str(getsmallint) with string += str(getsmallint*1.225)\n", "here's another version\ngetbingint = input(\"Enter big start value: \")\ngetbiginc = input(\"Enter big increment value: \")\ngetsmallint = input(\"Enter small start value: \")\ngetsmalinc = input(\"Enter small increment value: \")\ngetbigend = input(\"Enter big end value: \")\nfor i in range(getbingint,getbigend,getbiginc+1):\n getsmallint += getsmalinc\n print str(i) +\":\"+ str(\"%.2f\") % (getsmallint*1.225) + \",\",\n\n" ]
[ 2, 1, 1 ]
[]
[]
[ "multiplication", "python" ]
stackoverflow_0002019850_multiplication_python.txt
Q: Python's CSV reader and iteration I have a CSV file that looks like this: "Company, Inc.",,,,,,,,,,,,10/30/09 A/R Summary Aged Analysis Report,,,,,,,,,,,,10:35:01 All Clients,,,,,,,,,,,,USER Client Account,Customer Name,15-Jan,16 - 30,31 - 60,61 - 90,91 - 120,120 - Over,Total,Status,Credit Limit 1000001111,CLIENT A,0,0,"3,711.32",0,0,"18,629.64","22,340.96",COD,"20,000.00" 1000002222,CLIENT B,0,0,0,"3,591.27",0,0,"3,591.27",COD,0 1000003333,CLIENT C,536.78,0,0,0,0,"11,216.60","11,753.38",COD,0 1000004444,CLIENT D,0,514.94,"3,147.45",690,0,0,"4,352.39",COD,0 Grand Total,,"139,203,856.06","84,607,749.30","110,746,640.18","58,474,379.45","52,025,869.06","292,653,734.82","737,712,228.87",,,, But I only want to process the lines after the line "Client Account..." and before "Grand Total..." Here's the code that I'm using now: inputFile = csv.reader(open(filename), dialect='excel') records = [line for line in inputFile if line and line[0].isdigit()] A: Via generators. You can build all kinds of complexity from simple generator-filter functions. While considerably more complex than your filter, this is more extensible and can easily handle really complex spreadsheets. def skip_blank( rdr ): for row in rdr: if len(row) == 0: continue if all(len(col)==0 for col in row): continue yield row def after_heading( text, rdr ): i= iter(rdr) for row in i: if any( column == text for column in row ): break for row in i: yield row def before_footing( text, rdr ): for row in rdr: if any( column == text for column in row ): break yield row def between( start, end, rdr ): for row in before_footing( end, after_heading( start, rdr ) ): yield row for row in between( 'Grand Total', 'Client Account', skip_blank( inputFile ) ): print row A: you can do it like this, by setting flag import csv file = "file" f=0 reader = csv.reader(open(file),delimiter=',') for row in reader: if "Grand Total" in row: break if "Client Account" in row: f=1;continue if f: if row[0].isdigit(): print row A: import re import StringIO data=re.search("Client Account[^\r\n]+[\r\n]+(.*)(?=Grand Total)",open(filename).read(),re.DOTALL).group(1) datafile=StringIO.StringIO(data) inputFile = csv.reader(datafile, dialect='excel') records = [line for line in inputFile if line and line[0].isdigit()] A: Use a nice little generator for something like this. This one could be generalized a little more if your requirements change: def lines_between(source, first, second): for line in source: if line and line[0] == first: break for line in source: if line: and line[0] == second: break if line: # only non-empty lines yield line for record in lines_between(inputFile, 'Client Account', 'Grand Total'): # process record You didn't ask explicitly for the "non-empty lines" filter, but your own approach was doing this so I assume you wanted it. If you don't want to process the rows "lazily" like that, but just want a list with everything built in advance, do this: records = list(lines_between(inputFile, 'Client Account', 'Grand Total')) By the way, on Windows, be sure to open the real source file using binary mode, with csv.reader(open(filename, 'rb'), dialect='excel') as the csv docs note.
Python's CSV reader and iteration
I have a CSV file that looks like this: "Company, Inc.",,,,,,,,,,,,10/30/09 A/R Summary Aged Analysis Report,,,,,,,,,,,,10:35:01 All Clients,,,,,,,,,,,,USER Client Account,Customer Name,15-Jan,16 - 30,31 - 60,61 - 90,91 - 120,120 - Over,Total,Status,Credit Limit 1000001111,CLIENT A,0,0,"3,711.32",0,0,"18,629.64","22,340.96",COD,"20,000.00" 1000002222,CLIENT B,0,0,0,"3,591.27",0,0,"3,591.27",COD,0 1000003333,CLIENT C,536.78,0,0,0,0,"11,216.60","11,753.38",COD,0 1000004444,CLIENT D,0,514.94,"3,147.45",690,0,0,"4,352.39",COD,0 Grand Total,,"139,203,856.06","84,607,749.30","110,746,640.18","58,474,379.45","52,025,869.06","292,653,734.82","737,712,228.87",,,, But I only want to process the lines after the line "Client Account..." and before "Grand Total..." Here's the code that I'm using now: inputFile = csv.reader(open(filename), dialect='excel') records = [line for line in inputFile if line and line[0].isdigit()]
[ "Via generators. You can build all kinds of complexity from simple generator-filter functions. While considerably more complex than your filter, this is more extensible and can easily handle really complex spreadsheets. \ndef skip_blank( rdr ):\n for row in rdr:\n if len(row) == 0: continue\n if all(len(col)==0 for col in row): continue\n yield row\n\ndef after_heading( text, rdr ):\n i= iter(rdr)\n for row in i:\n if any( column == text for column in row ):\n break\n for row in i:\n yield row\n\ndef before_footing( text, rdr ):\n for row in rdr:\n if any( column == text for column in row ):\n break\n yield row\n\ndef between( start, end, rdr ):\n for row in before_footing( end, after_heading( start, rdr ) ):\n yield row\n\nfor row in between( 'Grand Total', 'Client Account', skip_blank( inputFile ) ):\n print row\n\n", "you can do it like this, by setting flag\nimport csv\nfile = \"file\"\nf=0\nreader = csv.reader(open(file),delimiter=',')\nfor row in reader:\n if \"Grand Total\" in row: break\n if \"Client Account\" in row: f=1;continue\n if f:\n if row[0].isdigit():\n print row\n\n", "import re\nimport StringIO\n\ndata=re.search(\"Client Account[^\\r\\n]+[\\r\\n]+(.*)(?=Grand Total)\",open(filename).read(),re.DOTALL).group(1)\ndatafile=StringIO.StringIO(data)\n\ninputFile = csv.reader(datafile, dialect='excel')\nrecords = [line for line in inputFile if line and line[0].isdigit()]\n\n", "Use a nice little generator for something like this. This one could be generalized a little more if your requirements change:\ndef lines_between(source, first, second):\n for line in source:\n if line and line[0] == first:\n break\n\n for line in source:\n if line: and line[0] == second:\n break\n\n if line: # only non-empty lines\n yield line\n\nfor record in lines_between(inputFile, 'Client Account', 'Grand Total'):\n # process record\n\nYou didn't ask explicitly for the \"non-empty lines\" filter, but your own approach was doing this so I assume you wanted it. If you don't want to process the rows \"lazily\" like that, but just want a list with everything built in advance, do this:\nrecords = list(lines_between(inputFile, 'Client Account', 'Grand Total'))\n\nBy the way, on Windows, be sure to open the real source file using binary mode, with csv.reader(open(filename, 'rb'), dialect='excel') as the csv docs note.\n" ]
[ 12, 10, 6, 3 ]
[]
[]
[ "csv", "iteration", "python" ]
stackoverflow_0002019573_csv_iteration_python.txt
Q: python json unicode - how do I eval using javascript Really spent a lot of time searching for this. Please need some help. I am trying to add multilingual feature to my web app framework. For this I am unable to send non ascii characters as JSON. Here is what I am doing Here is what I get from the database '\xe0\xa4\xa4\xe0\xa5\x87\xe0\xa4\xb8\xe0\xa5\x8d\xe0\xa4\xa4' which when I print gives me which is okay तेस्त I make the response object response = {'a':'\xe0\xa4\xa4\xe0\xa5\x87\xe0\xa4\xb8\xe0\xa5\x8d\xe0\xa4\xa4'} Send the repsonse import json sys.stdout.write(json.dumps(response)) This is what it prints Returns u'{"a": "\u0924\u0947\u0938\u094d\u0924"}' Any help, pointers will be welcome Thanks! Rushabh A: Is this your desired output (see ensure_ascii argument for json.dumps)? sys.stdout.write(json.dumps(response, ensure_ascii=False)) {"a": "तेस्त"}
python json unicode - how do I eval using javascript
Really spent a lot of time searching for this. Please need some help. I am trying to add multilingual feature to my web app framework. For this I am unable to send non ascii characters as JSON. Here is what I am doing Here is what I get from the database '\xe0\xa4\xa4\xe0\xa5\x87\xe0\xa4\xb8\xe0\xa5\x8d\xe0\xa4\xa4' which when I print gives me which is okay तेस्त I make the response object response = {'a':'\xe0\xa4\xa4\xe0\xa5\x87\xe0\xa4\xb8\xe0\xa5\x8d\xe0\xa4\xa4'} Send the repsonse import json sys.stdout.write(json.dumps(response)) This is what it prints Returns u'{"a": "\u0924\u0947\u0938\u094d\u0924"}' Any help, pointers will be welcome Thanks! Rushabh
[ "Is this your desired output (see ensure_ascii argument for json.dumps)?\nsys.stdout.write(json.dumps(response, ensure_ascii=False))\n{\"a\": \"तेस्त\"}\n\n" ]
[ 4 ]
[]
[]
[ "cgi", "json", "python", "unicode" ]
stackoverflow_0002019966_cgi_json_python_unicode.txt
Q: Python inserting a short integer into a list of bytes I have a list of bytes as follows pkt_bytes = [ 0x02,0x07, 0xff,0xff ,0x00,0x03] in the position 0xff,0xff I want to put a 16bit short integer How do I do it Regards A: You can use the struct module to pack values into appropriate formats: >>> pkt_bytes = [0x02, 0x07, 0xff, 0xff, 0x00, 0x03] >>> myint = 123 >>> pkt_bytes[3:5] = [ord(b) for b in struct.pack("H",myint)] >>> pkt_bytes [2, 7, 255, 123, 0, 3] By default this will use the native byte order but you can override this using modifiers to format string. Since your variable is called pkt_bytes I'm guessing you want network (big-endian) byte order which is signified by a !: >>> struct.pack("!H",5000) '\x13\x88' A: Try: >>> pkt_bytes.insert(3, 0xaa) >>> help(pkt_bytes.insert) Help on built-in function insert: insert(...) L.insert(index, object) -- insert object before index A: The code below will replace every occurrence of 0xff with 0x04 until there are no more 0xff left in the list. pkt_bytes = [0x02, 0x07, 0xff, 0xff ,0x00, 0x03] while True: try: idx = pkt_bytes.index(0xff) pkt_bytes[idx] = 0x04 except ValueError: break A: >>> pkt_bytes = [ 0x02,0x07, 0xff,0xff ,0x00,0x03] >>> pkt_bytes[2:4] = [pkt_bytes[2] << 8 | pkt_bytes[3]] >>> pkt_bytes [2, 7, 65535, 0, 3]
Python inserting a short integer into a list of bytes
I have a list of bytes as follows pkt_bytes = [ 0x02,0x07, 0xff,0xff ,0x00,0x03] in the position 0xff,0xff I want to put a 16bit short integer How do I do it Regards
[ "You can use the struct module to pack values into appropriate formats:\n>>> pkt_bytes = [0x02, 0x07, 0xff, 0xff, 0x00, 0x03]\n>>> myint = 123\n>>> pkt_bytes[3:5] = [ord(b) for b in struct.pack(\"H\",myint)]\n>>> pkt_bytes\n[2, 7, 255, 123, 0, 3]\n\nBy default this will use the native byte order but you can override this using modifiers to format string. Since your variable is called pkt_bytes I'm guessing you want network (big-endian) byte order which is signified by a !:\n>>> struct.pack(\"!H\",5000)\n'\\x13\\x88'\n\n", "Try:\n>>> pkt_bytes.insert(3, 0xaa)\n\n>>> help(pkt_bytes.insert)\nHelp on built-in function insert:\n\ninsert(...)\n L.insert(index, object) -- insert object before index\n\n", "The code below will replace every occurrence of 0xff with 0x04 until there are no more 0xff left in the list.\npkt_bytes = [0x02, 0x07, 0xff, 0xff ,0x00, 0x03]\nwhile True:\n try:\n idx = pkt_bytes.index(0xff)\n pkt_bytes[idx] = 0x04\n except ValueError:\n break\n\n", ">>> pkt_bytes = [ 0x02,0x07, 0xff,0xff ,0x00,0x03]\n>>> pkt_bytes[2:4] = [pkt_bytes[2] << 8 | pkt_bytes[3]]\n>>> pkt_bytes\n[2, 7, 65535, 0, 3]\n\n" ]
[ 7, 0, 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0002019929_list_python.txt
Q: cross module variable from here I got an idea about how using variables from other modules. this all works fine with import foo as bar But I don't want to import my modules as "bar" I want to use it without any prefix like from foo import * Using this it´s impossible to modify variables from other modules. reading will work! any idea? suggestions? A: Short answer: No, it's impossible, and you'll have to use a prefix. It's important to understand that from foo import x, y is copying x to your namespace. It's equivallent to: import foo # COPY TO YOUR NAMESPACE x = foo.x y = foo.y # `from foo import` does NOT leave `foo` in your namespace def foo This way, each module will get a local copy of x and y. Changing x won't be seen in other modules, and you won't see changes other modules do :-( To change the central copy of a variable you must import the module itself: import foo and change foo.x. This way only one copy exists and everybody is accessing it :-) [The linked questions also mention the possibility to put the shared variable in the module builtin. DON'T! This would eliminate the prefix for reading it, but not for writing, and is extremely bad style.] A note in defense of Python If you resent the need to use a foo. prefix here, you'll probably also resent the need for the self. prefix to access object variables. The bottom line is that's how Python works - since you don't declare variables, there is no choice but to use prefixes. But there is also an upside: when reading Python code, you easily see where each variable lives. IMHO that's very good. Supporting evidence: in other languages like C++/Java, many people observe conventions like an m_ prefix on all object variable names to achieve a similar effect... Style remarks You don't need import foo as bar, just use import foo. The as form doesn't do anything new, it just renames it, which is just confusing. It's only useful if "foo" is a very long name; a particularly accepted case is when "foo" lives deep in some package, so you can do import long.package.foo as foo. The from foo import * is considered very bad style in programs because: The person reading your code won't know where names came from. It pollutes your namespace, which can lead to subtle bugs when names from different modules clash. The explicit form from foo import x, y is OK, but starts suffering from the same problems if you use many names from the module. In such cases, it's best to import foo and explicitly write foo.x, foo.y. Bottom line: when in doubt, a simple import foo is best. Exception: It is very handy to use import * when experimenting at the interactive interpreter. Note however that it doesn't play well with reload(), so don't use it when debugging changing code. (To debug a module you are writing, it's best to launch a fresh interpreter inside the module's namespace - python -i mymodule.py / F5 in IDLE.) A: As far as I know, there is no way to import a value from a module and have it readable and writable by the importing scope. When you just import foo in Python, it creates a module object named foo. Getting and setting attributes on a module object will change them in the module's scope. But when you from foo import something, foo is imported and a module object is created, but is not returned. Instead, Python copies the values you specified out of foo and puts them in the local scope. If what you are importing is an immutable type like int or str, then changing it and having the changes reflect in the foo module is impossible. It's similar to this: >>> class N(object): ... def __init__(self, value): ... self.value = value >>> n = N(3) >>> value = n.value >>> print value, n.value 3 3 >>> value = 4 >>> print value, n.value 4 3 Excepting crude hacks, if you really want to be able to modify the module's variable, you will need to import the module itself and modify the variable on the module. But generally, having to do this is indicative of bad design. If you are the writer of the foo module in question, you may want to look at some other, more Pythonic ways to solve your problem. A: By using import foo from bar you don't import bar as a variable but as a constant. A: from foo import * is frowned upon (by me, by Google's style guide, by the OLPC style guide - which you should see, as it has the best explanations of why this is bad - but not by PEP-8, unfortunately). - it makes for unreadable code. Consider: from foo import * from bar import * from baz import * dostuff() If you have an error running dostuff(), where do you look for the problem? It could have come from any of those imports. For readable, maintainable code, stick with from foo import bar. For readable, modular, maintainable code, don't hack with globals - extend bar (by subclassing, if you can't change the upstream source) to expose methods for modifying the values you need to access.
cross module variable
from here I got an idea about how using variables from other modules. this all works fine with import foo as bar But I don't want to import my modules as "bar" I want to use it without any prefix like from foo import * Using this it´s impossible to modify variables from other modules. reading will work! any idea? suggestions?
[ "Short answer: No, it's impossible, and you'll have to use a prefix. \nIt's important to understand that from foo import x, y is copying x to your namespace. It's equivallent to:\nimport foo\n# COPY TO YOUR NAMESPACE\nx = foo.x\ny = foo.y\n# `from foo import` does NOT leave `foo` in your namespace\ndef foo\n\nThis way, each module will get a local copy of x and y. Changing x won't be seen in other modules, and you won't see changes other modules do :-(\nTo change the central copy of a variable you must import the module itself: import foo and change foo.x. This way only one copy exists and everybody is accessing it :-)\n[The linked questions also mention the possibility to put the shared variable in the module builtin. DON'T! This would eliminate the prefix for reading it, but not for writing, and is extremely bad style.]\nA note in defense of Python\nIf you resent the need to use a foo. prefix here, you'll probably also resent the need for the self. prefix to access object variables. The bottom line is that's how Python works - since you don't declare variables, there is no choice but to use prefixes.\nBut there is also an upside: when reading Python code, you easily see where each variable lives. IMHO that's very good.\nSupporting evidence: in other languages like C++/Java, many people observe conventions like an m_ prefix on all object variable names to achieve a similar effect...\nStyle remarks\n\nYou don't need import foo as bar, just use import foo.\nThe as form doesn't do anything new, it just renames it, which is just confusing.\nIt's only useful if \"foo\" is a very long name; a particularly accepted case is when \"foo\" lives deep in some package, so you can do import long.package.foo as foo.\nThe from foo import * is considered very bad style in programs because:\n\nThe person reading your code won't know where names came from. \nIt pollutes your namespace, which can lead to subtle bugs when names from \ndifferent modules clash.\n\nThe explicit form from foo import x, y is OK, but starts suffering from the same problems if you use many names from the module.\nIn such cases, it's best to import foo and explicitly write foo.x, foo.y. \n\nBottom line: when in doubt, a simple import foo is best.\nException: It is very handy to use import * when experimenting at the interactive interpreter. Note however that it doesn't play well with reload(), so don't use it when debugging changing code. (To debug a module you are writing, it's best to launch a fresh interpreter inside the module's namespace - python -i mymodule.py / F5 in IDLE.)\n", "As far as I know, there is no way to import a value from a module and have it readable and writable by the importing scope. When you just import foo in Python, it creates a module object named foo. Getting and setting attributes on a module object will change them in the module's scope. But when you from foo import something, foo is imported and a module object is created, but is not returned. Instead, Python copies the values you specified out of foo and puts them in the local scope. If what you are importing is an immutable type like int or str, then changing it and having the changes reflect in the foo module is impossible. It's similar to this:\n>>> class N(object):\n... def __init__(self, value):\n... self.value = value\n>>> n = N(3)\n>>> value = n.value\n>>> print value, n.value\n3 3\n>>> value = 4\n>>> print value, n.value\n4 3\n\nExcepting crude hacks, if you really want to be able to modify the module's variable, you will need to import the module itself and modify the variable on the module. But generally, having to do this is indicative of bad design. If you are the writer of the foo module in question, you may want to look at some other, more Pythonic ways to solve your problem.\n", "By using import foo from bar you don't import bar as a variable but as a constant.\n", "from foo import * is frowned upon (by me, by Google's style guide, by the OLPC style guide - which you should see, as it has the best explanations of why this is bad - but not by PEP-8, unfortunately). - it makes for unreadable code. \nConsider:\nfrom foo import *\nfrom bar import *\nfrom baz import *\n\ndostuff()\n\nIf you have an error running dostuff(), where do you look for the problem? It could have come from any of those imports.\nFor readable, maintainable code, stick with from foo import bar. For readable, modular, maintainable code, don't hack with globals - extend bar (by subclassing, if you can't change the upstream source) to expose methods for modifying the values you need to access.\n" ]
[ 3, 2, 0, 0 ]
[]
[]
[ "import", "module", "python" ]
stackoverflow_0002019877_import_module_python.txt
Q: Given a unicode error I don't understand Here is my code, I'm sure it looks terrible but it all works as it should, only problem I'm having is with the last line... import pyPdf import os import csv class UnicodeWriter: """ A CSV writer which will write rows to CSV file "f", which is encoded in the given encoding. """ def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds): # Redirect output to a queue self.queue = cStringIO.StringIO() self.writer = csv.writer(self.queue, dialect=dialect, **kwds) self.stream = f self.encoder = codecs.getincrementalencoder(encoding)() def writerow(self, row): self.writer.writerow([s.encode("utf-8") for s in row]) # Fetch UTF-8 output from the queue ... data = self.queue.getvalue() data = data.decode("utf-8") # ... and reencode it into the target encoding data = self.encoder.encode(data) # write to the target stream self.stream.write(data) # empty queue self.queue.truncate(0) def writerows(self, rows): for row in rows: self.writerow(row) PDFWriter = csv.writer(open('/home/nick/TAM_work/text/text.doc', 'a'), delimiter=' ', quotechar='|', quoting=csv.QUOTE_ALL) def getPDFContent(path): content = "" # Load PDF into pyPDF pdf = pyPdf.PdfFileReader(file(path, "rb")) # Iterate pages for i in range(0, pdf.getNumPages()): # Extract text from page and add to content content += pdf.getPage(i).extractText() + "\n" # Collapse whitespace content = " ".join(content.replace(u"\xa0", " ").strip().split()) return content for word in os.listdir("/home/nick/TAM_work/TAM_pdfs"): print getPDFContent("/home/nick/TAM_work/TAM_pdfs/" + word) PDFWriter.writerow ([getPDFContent("/home/nick/TAM_work/TAM_pdfs/" + word)]) When I run it everything works until it hits this... Traceback (most recent call last): File "Saving_fuction_added.py", line 52, in <module> PDFWriter.writerow ([getPDFContent("/home/nick/TAM_work/TAM_pdfs/" + word)]) UnicodeEncodeError: 'ascii' codec can't encode character u'\u2122' in position 81: ordinal not in range(128) I'd love any help. Thanks guys. Matt A: Here's the code that answered that question. But now it only writes the last file. import pyPdf import os import csv class UnicodeWriter: """ A CSV writer which will write rows to CSV file "f", which is encoded in the given encoding. """ def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds): # Redirect output to a queue self.queue = cStringIO.StringIO() self.writer = csv.writer(self.queue, dialect=dialect, **kwds) self.stream = f self.encoder = codecs.getincrementalencoder(encoding)() def writerow(self, row): self.writer.writerow([s.encode("utf-8") for s in row]) # Fetch UTF-8 output from the queue ... data = self.queue.getvalue() data = data.decode("utf-8") # ... and reencode it into the target encoding data = self.encoder.encode(data) # write to the target stream self.stream.write(data) # empty queue self.queue.truncate(0) def writerows(self, rows): for row in rows: self.writerow(row) PDFWriter = csv.writer(open('/home/nick/TAM_work/text/text.doc', 'a'), delimiter=' ', quotechar='|', quoting=csv.QUOTE_ALL) def getPDFContent(path): content = "" # Load PDF into pyPDF pdf = pyPdf.PdfFileReader(file(path, "rb")) # Iterate pages for i in range(0, pdf.getNumPages()): # Extract text from page and add to content content += pdf.getPage(i).extractText() + "\n" # Collapse whitespace content = " ".join(content.replace(u"\xa0", " ").strip().split()) return content for word in os.listdir("/home/nick/TAM_work/TAM_pdfs"): print getPDFContent("/home/nick/TAM_work/TAM_pdfs/" + word) PDFWriter.writerow ([getPDFContent("/home/nick/TAM_work/TAM_pdfs/" + word).encode("ascii", "ignore")])
Given a unicode error I don't understand
Here is my code, I'm sure it looks terrible but it all works as it should, only problem I'm having is with the last line... import pyPdf import os import csv class UnicodeWriter: """ A CSV writer which will write rows to CSV file "f", which is encoded in the given encoding. """ def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds): # Redirect output to a queue self.queue = cStringIO.StringIO() self.writer = csv.writer(self.queue, dialect=dialect, **kwds) self.stream = f self.encoder = codecs.getincrementalencoder(encoding)() def writerow(self, row): self.writer.writerow([s.encode("utf-8") for s in row]) # Fetch UTF-8 output from the queue ... data = self.queue.getvalue() data = data.decode("utf-8") # ... and reencode it into the target encoding data = self.encoder.encode(data) # write to the target stream self.stream.write(data) # empty queue self.queue.truncate(0) def writerows(self, rows): for row in rows: self.writerow(row) PDFWriter = csv.writer(open('/home/nick/TAM_work/text/text.doc', 'a'), delimiter=' ', quotechar='|', quoting=csv.QUOTE_ALL) def getPDFContent(path): content = "" # Load PDF into pyPDF pdf = pyPdf.PdfFileReader(file(path, "rb")) # Iterate pages for i in range(0, pdf.getNumPages()): # Extract text from page and add to content content += pdf.getPage(i).extractText() + "\n" # Collapse whitespace content = " ".join(content.replace(u"\xa0", " ").strip().split()) return content for word in os.listdir("/home/nick/TAM_work/TAM_pdfs"): print getPDFContent("/home/nick/TAM_work/TAM_pdfs/" + word) PDFWriter.writerow ([getPDFContent("/home/nick/TAM_work/TAM_pdfs/" + word)]) When I run it everything works until it hits this... Traceback (most recent call last): File "Saving_fuction_added.py", line 52, in <module> PDFWriter.writerow ([getPDFContent("/home/nick/TAM_work/TAM_pdfs/" + word)]) UnicodeEncodeError: 'ascii' codec can't encode character u'\u2122' in position 81: ordinal not in range(128) I'd love any help. Thanks guys. Matt
[ "Here's the code that answered that question. But now it only writes the last file. \n import pyPdf\nimport os\nimport csv\n\nclass UnicodeWriter:\n \"\"\"\n A CSV writer which will write rows to CSV file \"f\",\n which is encoded in the given encoding.\n \"\"\"\n\n def __init__(self, f, dialect=csv.excel, encoding=\"utf-8\", **kwds):\n # Redirect output to a queue\n self.queue = cStringIO.StringIO()\n self.writer = csv.writer(self.queue, dialect=dialect, **kwds)\n self.stream = f\n self.encoder = codecs.getincrementalencoder(encoding)()\n\n def writerow(self, row):\n self.writer.writerow([s.encode(\"utf-8\") for s in row])\n # Fetch UTF-8 output from the queue ...\n data = self.queue.getvalue()\n data = data.decode(\"utf-8\")\n # ... and reencode it into the target encoding\n data = self.encoder.encode(data)\n # write to the target stream\n self.stream.write(data)\n # empty queue\n self.queue.truncate(0)\n\n def writerows(self, rows):\n for row in rows:\n self.writerow(row)\n\n\nPDFWriter = csv.writer(open('/home/nick/TAM_work/text/text.doc', 'a'), delimiter=' ', quotechar='|', quoting=csv.QUOTE_ALL)\n\ndef getPDFContent(path):\n content = \"\"\n # Load PDF into pyPDF\n pdf = pyPdf.PdfFileReader(file(path, \"rb\"))\n # Iterate pages\n for i in range(0, pdf.getNumPages()):\n # Extract text from page and add to content\n content += pdf.getPage(i).extractText() + \"\\n\"\n # Collapse whitespace\n content = \" \".join(content.replace(u\"\\xa0\", \" \").strip().split())\n return content\n\nfor word in os.listdir(\"/home/nick/TAM_work/TAM_pdfs\"):\n print getPDFContent(\"/home/nick/TAM_work/TAM_pdfs/\" + word)\n\nPDFWriter.writerow ([getPDFContent(\"/home/nick/TAM_work/TAM_pdfs/\" + word).encode(\"ascii\", \"ignore\")])\n\n" ]
[ 1 ]
[ "as I Underestand you put a large number in a small varible and its throw an exception.\nI introduce you a C# tool that work very fine with unicode , you can find it at http://unicode.codeplex.com\nin your case I recommand to change the \n for i in range(0, pdf.getNumPages()): \n\npdf.getNumPages() is above than 128 just controll it.\n" ]
[ -1 ]
[ "ascii", "python", "unicode" ]
stackoverflow_0002018058_ascii_python_unicode.txt
Q: how do i get the byte count of a variable in python just like wc -c gives in unix i am facing some problem with files with huge data. i need to skip doing some execution on those files. i get the data of the file into a variable. now i need to get the byte of the variable and if it is greater than 102400 , then print a message. update : i cannot open the files , since it is present in a tar file. the content is already getting copied to a variable called 'data' i am able to print contents of the variable data. i just need to check if it has more than 102400 bytes. thanks A: import os length_in_bytes = os.stat('file.txt').st_size if length_in_bytes > 102400: print 'Its a big file!' Update to work on files in a tarfile import tarfile tf = tarfile.TarFile('foo.tar') for member in tarfile.getmembers(): if member.size > 102400: print 'It's a big file in a tarfile - the file is called %s!' % member.name A: If I'm understanding the question correctly, you want to skip certain input files if they're too large. For that, you can use os.path.getsize(): import os.path if os.path.getsize('f') <= 102400: doit(); A: Just check the length of the string, then: if len(data) > 102400: print "Skipping file which is too large, at %d bytes" % len(data) else: process(data) # The normal processing A: len(data) gives you the size in bytes if it's binary data. With strings the size depends on the encoding used. A: This answer seems irrelevant, since I seem to have misunderstood the question, which has now been clarified. However, should someone find this question, while searching with pretty much the same terms, this answer may still be relevant: Just open the file in binary mode f = open(filename, 'rb') read/skip a bunch and print the next byte(s). I used the same method to 'fix' the n-th byte in a zillion images once.
how do i get the byte count of a variable in python just like wc -c gives in unix
i am facing some problem with files with huge data. i need to skip doing some execution on those files. i get the data of the file into a variable. now i need to get the byte of the variable and if it is greater than 102400 , then print a message. update : i cannot open the files , since it is present in a tar file. the content is already getting copied to a variable called 'data' i am able to print contents of the variable data. i just need to check if it has more than 102400 bytes. thanks
[ "import os\nlength_in_bytes = os.stat('file.txt').st_size\nif length_in_bytes > 102400:\n print 'Its a big file!'\n\nUpdate to work on files in a tarfile\nimport tarfile\ntf = tarfile.TarFile('foo.tar')\nfor member in tarfile.getmembers():\n if member.size > 102400:\n print 'It's a big file in a tarfile - the file is called %s!' % member.name\n\n", "If I'm understanding the question correctly, you want to skip certain input files if they're too large. For that, you can use os.path.getsize():\nimport os.path\nif os.path.getsize('f') <= 102400:\n doit();\n\n", "Just check the length of the string, then:\nif len(data) > 102400:\n print \"Skipping file which is too large, at %d bytes\" % len(data)\nelse:\n process(data) # The normal processing\n\n", "len(data) gives you the size in bytes if it's binary data. With strings the size depends on the encoding used.\n", "This answer seems irrelevant, since I seem to have misunderstood the question, which has now been clarified. However, should someone find this question, while searching with pretty much the same terms, this answer may still be relevant:\nJust open the file in binary mode\nf = open(filename, 'rb')\nread/skip a bunch and print the next byte(s). I used the same method to 'fix' the n-th byte in a zillion images once.\n" ]
[ 6, 2, 2, 1, 0 ]
[]
[]
[ "python", "tar" ]
stackoverflow_0002020318_python_tar.txt
Q: PyQt4 Signalling between classes I have a family of classes (based on the same parent class) that are data cells in a QTableWidget (so they are all derived from QItemDelegate). I'm trying to create a signal that these classes can pass up to the controller to communicate data changes. I can't find the right combination (despite much experimentation and reading) which accomplished. Here's my class structure: Base Class: class Criteria(QItemDelegate): def bind(self, update): self.connect(self,SIGNAL("criteriaChange(int, int, QVariant)"),update) def emitCommitData(self): self.emit(SIGNAL("criteriaChange(int, int, QVariant)"), self.Row, self.Col, self.getValue()) Example Sub-class (just the relevant parts -- LMK if more info needed): class YesNo(Criteria): .... def createEditor(self, parent, option, index): self.comboBox = QComboBox(parent) for item in self.getChoices(): self.comboBox.addItem(item) self.comboBox.activated.connect(self.emitCommitData) return self.comboBox .... Here's the relevant portion of my master class: @pyqtSlot(int, int, QVariant, name='criteriaChanged') def setItem(self, row, col, item): print row, col, item.toString() # TODO: Remove when tested self.Data[row][col] = item.toString() def addCriteria(self, row, cname, ctype): self.setDirty() c = YesNo(cname, "YesNo") c.bind(self.setItem) The above code gives an "Underlying C++ object has been deleted". I've tried this: def addCriteria(self, row, cname, ctype): self.setDirty() c = YesNo(cname, "YesNo") self.connect(c,SIGNAL("criteriaChange(int, int, QVariant)"),self.setItem) Any suggestions? I don't have to use this method, but rather need a way to get that data out of the individual controls. TIA Mike A: I'm really embarrassed about this. Hopefully this will help somebody else. I didn't call the Qt initialization for the appropriate object: class YesNo(Criteria): def __init__(self, name, ctype): Criteria.__init__(self) # <<<<----- This was missing before self.Name = name self.Index = ctype and class Criteria(QItemDelegate): def __init__(self): QItemDelegate.__init__(self) # <<<<----- This was missing before A: criteria.py def criteria_change(row, col, new_value): print "change at", row, col, "new_value:", new_value class Criteria: def __init__(self, row, col): self.row, self.col = row, col def on_change(self): criteria_change(self.row, self.col, self.value()) yes_no_maybe.py from PyQt4.QtGui import * from criteria import Criteria class YesNoMaybe(Criteria): def create_editor(self): group_box = QGroupBox() layout = QVBoxLayout() group_box.setLayout(layout) self.buttons = [] for s in ["yes", "no", "maybe"]: button = QRadioButton(s) self.buttons.append(button) layout.addWidget(button) button.toggled.connect(self.on_toggle) return group_box # def on_toggle(self, is_now_on): if is_now_on: self.on_change() def value(self): for button in self.buttons: if button.isChecked(): return button.text() # yes_no.py from PyQt4.QtGui import QComboBox from criteria import Criteria class YesNo(Criteria): def create_editor(self): combo_box = self.combo_box = QComboBox() for s in ["red", "blue"]: combo_box.addItem(s) combo_box.activated.connect(self.on_change) return combo_box # def value(self): return self.combo_box.currentText() # main.py import sys from PyQt4.QtGui import * from yes_no_maybe import YesNoMaybe from yes_no import YesNo app = QApplication(sys.argv) table_classes = [[YesNo, YesNo], [YesNoMaybe, YesNoMaybe]] table = QTableWidget(len(table_classes), len(table_classes[0])) table.criteria = [] for r, cls_row in enumerate(table_classes): criteria_row = [] table.criteria.append(criteria_row) for c, criteria_cls in enumerate(cls_row): criteria = criteria_cls(r, c) criteria_row.append(criteria) table.setCellWidget(r, c, criteria.create_editor()) table.setRowHeight(1, 100) table.show() app.exec_()
PyQt4 Signalling between classes
I have a family of classes (based on the same parent class) that are data cells in a QTableWidget (so they are all derived from QItemDelegate). I'm trying to create a signal that these classes can pass up to the controller to communicate data changes. I can't find the right combination (despite much experimentation and reading) which accomplished. Here's my class structure: Base Class: class Criteria(QItemDelegate): def bind(self, update): self.connect(self,SIGNAL("criteriaChange(int, int, QVariant)"),update) def emitCommitData(self): self.emit(SIGNAL("criteriaChange(int, int, QVariant)"), self.Row, self.Col, self.getValue()) Example Sub-class (just the relevant parts -- LMK if more info needed): class YesNo(Criteria): .... def createEditor(self, parent, option, index): self.comboBox = QComboBox(parent) for item in self.getChoices(): self.comboBox.addItem(item) self.comboBox.activated.connect(self.emitCommitData) return self.comboBox .... Here's the relevant portion of my master class: @pyqtSlot(int, int, QVariant, name='criteriaChanged') def setItem(self, row, col, item): print row, col, item.toString() # TODO: Remove when tested self.Data[row][col] = item.toString() def addCriteria(self, row, cname, ctype): self.setDirty() c = YesNo(cname, "YesNo") c.bind(self.setItem) The above code gives an "Underlying C++ object has been deleted". I've tried this: def addCriteria(self, row, cname, ctype): self.setDirty() c = YesNo(cname, "YesNo") self.connect(c,SIGNAL("criteriaChange(int, int, QVariant)"),self.setItem) Any suggestions? I don't have to use this method, but rather need a way to get that data out of the individual controls. TIA Mike
[ "I'm really embarrassed about this. Hopefully this will help somebody else. \nI didn't call the Qt initialization for the appropriate object:\nclass YesNo(Criteria):\n def __init__(self, name, ctype):\n Criteria.__init__(self) # <<<<----- This was missing before\n self.Name = name\n self.Index = ctype\n\nand\nclass Criteria(QItemDelegate):\n def __init__(self):\n QItemDelegate.__init__(self) # <<<<----- This was missing before\n\n", "criteria.py\ndef criteria_change(row, col, new_value):\n print \"change at\", row, col, \"new_value:\", new_value\n\nclass Criteria:\n def __init__(self, row, col):\n self.row, self.col = row, col\n\n def on_change(self):\n criteria_change(self.row, self.col, self.value())\n\nyes_no_maybe.py\nfrom PyQt4.QtGui import *\n\nfrom criteria import Criteria\n\nclass YesNoMaybe(Criteria):\n def create_editor(self):\n group_box = QGroupBox()\n layout = QVBoxLayout()\n group_box.setLayout(layout)\n self.buttons = []\n\n for s in [\"yes\", \"no\", \"maybe\"]:\n button = QRadioButton(s)\n self.buttons.append(button)\n layout.addWidget(button)\n button.toggled.connect(self.on_toggle)\n\n return group_box\n #\n\n def on_toggle(self, is_now_on):\n if is_now_on:\n self.on_change()\n\n def value(self):\n for button in self.buttons:\n if button.isChecked():\n return button.text()\n#\n\nyes_no.py\nfrom PyQt4.QtGui import QComboBox\n\nfrom criteria import Criteria\n\nclass YesNo(Criteria):\n def create_editor(self): \n combo_box = self.combo_box = QComboBox()\n for s in [\"red\", \"blue\"]:\n combo_box.addItem(s)\n combo_box.activated.connect(self.on_change) \n return combo_box\n #\n\n def value(self):\n return self.combo_box.currentText()\n#\n\nmain.py\nimport sys\n\nfrom PyQt4.QtGui import *\n\nfrom yes_no_maybe import YesNoMaybe\nfrom yes_no import YesNo\n\napp = QApplication(sys.argv)\n\n\ntable_classes = [[YesNo, YesNo],\n [YesNoMaybe, YesNoMaybe]] \n\ntable = QTableWidget(len(table_classes), len(table_classes[0]))\ntable.criteria = []\nfor r, cls_row in enumerate(table_classes):\n criteria_row = []\n table.criteria.append(criteria_row)\n for c, criteria_cls in enumerate(cls_row):\n criteria = criteria_cls(r, c)\n criteria_row.append(criteria)\n table.setCellWidget(r, c, criteria.create_editor())\n\ntable.setRowHeight(1, 100)\ntable.show()\n\napp.exec_()\n\n" ]
[ 1, 0 ]
[]
[]
[ "pyqt", "pyqt4", "python" ]
stackoverflow_0002004060_pyqt_pyqt4_python.txt
Q: Increment a VERSION ID by one and write to .mk file I have code to read in the version number from a make file. VERSION_ID=map(int,re.match("VERSION_ID\s*=\s*(\S+)",open("version.mk").read()).group(1).split(".")) This code takes VERSION_ID=0.0.2 and stores it as [0, 0, 2]. Is there any way I can increment this number by one and write the new version number into the version.mk file with the variable VERSION_ID. Thanks I have tried the same statement with write() instead of read() but I am getting an error saying that I can not write a list. I have also tried to write it as a string but am getting a bad file descriptor message. s = str(VERSION_ID) VERSION_ID=map(int,re.search("VERSION_ID\s*=\s*(\S+)",open("version.mk").write(s)).group(1).split(".")) I know this is rubbish, I just can't seem to find what to do here in the online docs. I have also tried the pickle module to no avail. Maybe I'd be able to write a pickled list instead and then unpickle it. Or I was thinking I could just write over the whole line altogether. I've tried to do anther approach, Ihave tried to get list to be entered as a string. I have tried this but I am not sure if it will work. for x in VERSION_ID: "VERSION_ID={0}.{1}.{2}.format(x) A: perhpas something like this (you should also check for errors and that) #! /usr/bin/python import re fn = "version.mk" omk = open(fn).readlines() nmk = open(fn, "w") r = re.compile(r'(VERSION_ID\s*=\s*)(\S+)') for l in omk: m1 = r.match(l) if m1: VERSION_ID=map(int,m1.group(2).split(".")) VERSION_ID[2]+=1 # increment version l = r.sub(r'\g<1>' + '.'.join(['%s' % (v) for v in VERSION_ID]), l) nmk.write(l) nmk.close()
Increment a VERSION ID by one and write to .mk file
I have code to read in the version number from a make file. VERSION_ID=map(int,re.match("VERSION_ID\s*=\s*(\S+)",open("version.mk").read()).group(1).split(".")) This code takes VERSION_ID=0.0.2 and stores it as [0, 0, 2]. Is there any way I can increment this number by one and write the new version number into the version.mk file with the variable VERSION_ID. Thanks I have tried the same statement with write() instead of read() but I am getting an error saying that I can not write a list. I have also tried to write it as a string but am getting a bad file descriptor message. s = str(VERSION_ID) VERSION_ID=map(int,re.search("VERSION_ID\s*=\s*(\S+)",open("version.mk").write(s)).group(1).split(".")) I know this is rubbish, I just can't seem to find what to do here in the online docs. I have also tried the pickle module to no avail. Maybe I'd be able to write a pickled list instead and then unpickle it. Or I was thinking I could just write over the whole line altogether. I've tried to do anther approach, Ihave tried to get list to be entered as a string. I have tried this but I am not sure if it will work. for x in VERSION_ID: "VERSION_ID={0}.{1}.{2}.format(x)
[ "perhpas something like this (you should also check for errors and that)\n#! /usr/bin/python\n\nimport re\n\nfn = \"version.mk\"\nomk = open(fn).readlines()\nnmk = open(fn, \"w\")\nr = re.compile(r'(VERSION_ID\\s*=\\s*)(\\S+)')\n\nfor l in omk:\n m1 = r.match(l)\n if m1:\n VERSION_ID=map(int,m1.group(2).split(\".\"))\n VERSION_ID[2]+=1 # increment version\n l = r.sub(r'\\g<1>' + '.'.join(['%s' % (v) for v in VERSION_ID]), l)\n nmk.write(l)\nnmk.close()\n\n" ]
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0002020180_python.txt
Q: python list that matches everything I probably didn't ask correctly: I would like a list value that can match any list: the "inverse" of (None,) but even with (None,) it will match item as None (which I don't want) The point is I have a function working with: [x for x in my_list if x[field] not in filter_list] and I would like to filter everything or nothing without making tests like: if filter_list==(None,): return [] and if filter_list==('*',): return my_list PS: I wanted to simplify my question leading to some errors (list identifier) or stupid thing [x for x in x] ;) Hi, I need to do some filtering with list comprehension in python. if I do something like that: [x for x in list if x in (None,)] I get rid of all values, which is fine but I would like to have the same thing to match everything I can do something like: [x for x in list if x not in (None,)] but it won't be homogeneous with the rest I tried some things but for example (True,) matches only 1 Note than the values to filter are numeric, but if you have something generic (like (None,) to match nothing), it would be great Thanks Louis A: __contains__ is the magic method that checks if something is in a sequence: class everything(object): def __contains__(self, _): return True for x in (1,2,3): print x in everything() A: The better syntax would be: [x for x in lst if x is None] [x for x in lst if x is not None] A: What do you mean by I would like to have the same thing to match everything Just do [x for x in list] and every item in list is matched. A: You could change your program to accept a filter object, instead of a list. The abstract base filter would have a matches method, that returns true if x *matches". Your general case filters would be constructed with a list argument, and would filter on membership of the list - the matches function would search the list and return true if the argument was in the list. You could also have two special subclasses of the filter object : none and all. These would have special match functions which either always return true (all) or false (none). A: You don't need an if, you can just say [x for x in list] A: but I would like to have the same thing to match everything To match everything, you don't need if statement [x for x in list1] or If you really like to do [x for x in list1 if x in [x]] A: Answering your revised question: the list that "matches" all possible values is effectively of infinite length. So you can't do what you want to do without an if test. I suggest that your arg should be either a list or one of two values representing the "all" and "none" cases: FILTER_NONE = object() # or [] FILTER_ALL = object() def filter_func(alist, filter_list): if filter_list is FILTER_ALL: return [] elif filter_list is FILTER_NONE: return alist # or maybe alist[:] # copy the list return [x for x in alist if x not in filter_list] If filter_list is large, you may wish the replace the last line by: filter_set = set(filter_list) return [x for x in alist if x not in filter_set] Alternatively, don't bother; just document that filter_list (renamed as filter_collection) can be anything that supports __contains__() and remind readers that sets will be faster than lists.
python list that matches everything
I probably didn't ask correctly: I would like a list value that can match any list: the "inverse" of (None,) but even with (None,) it will match item as None (which I don't want) The point is I have a function working with: [x for x in my_list if x[field] not in filter_list] and I would like to filter everything or nothing without making tests like: if filter_list==(None,): return [] and if filter_list==('*',): return my_list PS: I wanted to simplify my question leading to some errors (list identifier) or stupid thing [x for x in x] ;) Hi, I need to do some filtering with list comprehension in python. if I do something like that: [x for x in list if x in (None,)] I get rid of all values, which is fine but I would like to have the same thing to match everything I can do something like: [x for x in list if x not in (None,)] but it won't be homogeneous with the rest I tried some things but for example (True,) matches only 1 Note than the values to filter are numeric, but if you have something generic (like (None,) to match nothing), it would be great Thanks Louis
[ "__contains__ is the magic method that checks if something is in a sequence:\nclass everything(object):\n def __contains__(self, _):\n return True \n\nfor x in (1,2,3):\n print x in everything()\n\n", "The better syntax would be:\n[x for x in lst if x is None]\n[x for x in lst if x is not None]\n\n", "What do you mean by\n\nI would like to have the same thing to match everything\n\nJust do\n[x for x in list]\n\nand every item in list is matched.\n", "You could change your program to accept a filter object, instead of a list. \nThe abstract base filter would have a matches method, that returns true if x *matches\".\nYour general case filters would be constructed with a list argument, and would filter on membership of the list - the matches function would search the list and return true if the argument was in the list.\nYou could also have two special subclasses of the filter object : none and all.\nThese would have special match functions which either always return true (all) or false (none).\n", "You don't need an if, you can just say\n[x for x in list]\n\n", "\nbut I would like to have the same\n thing to match everything\n\nTo match everything, you don't need if statement\n[x for x in list1]\n\nor If you really like to do\n[x for x in list1 if x in [x]]\n\n", "Answering your revised question: the list that \"matches\" all possible values is effectively of infinite length. So you can't do what you want to do without an if test. I suggest that your arg should be either a list or one of two values representing the \"all\" and \"none\" cases:\nFILTER_NONE = object() # or []\nFILTER_ALL = object()\n\ndef filter_func(alist, filter_list):\n if filter_list is FILTER_ALL:\n return []\n elif filter_list is FILTER_NONE:\n return alist\n # or maybe alist[:] # copy the list\n return [x for x in alist if x not in filter_list]\n\nIf filter_list is large, you may wish the replace the last line by:\n filter_set = set(filter_list)\n return [x for x in alist if x not in filter_set]\n\nAlternatively, don't bother; just document that filter_list (renamed as filter_collection) can be anything that supports __contains__() and remind readers that sets will be faster than lists.\n" ]
[ 5, 4, 3, 3, 0, 0, 0 ]
[]
[]
[ "filtering", "list_comprehension", "python" ]
stackoverflow_0002019791_filtering_list_comprehension_python.txt
Q: Download file using urllib in Python with the wget -c feature I am programming a software in Python to download HTTP PDF from a database. Sometimes the download stop with this message : retrieval incomplete: got only 3617232 out of 10689634 bytes How can I ask the download to restart where it stops using the 206 Partial Content HTTP feature ? I can do it using wget -c and it works pretty well, but I would like to implement it directly in my Python software. Any idea ? Thank you A: You can request a partial download by sending a GET with the Range header: import urllib2 req = urllib2.Request('http://www.python.org/') # # Here we request that bytes 18000--19000 be downloaded. # The range is inclusive, and starts at 0. # req.headers['Range'] = 'bytes=%s-%s' % (18000, 19000) f = urllib2.urlopen(req) # This shows you the *actual* bytes that have been downloaded. range=f.headers.get('Content-Range') print(range) # bytes 18000-18030/18031 print(repr(f.read())) # ' </div>\n</body>\n</html>\n\n\n\n\n\n\n' Be careful to check the Content-Range to learn what bytes have actually been downloaded, since your range may be out of bounds, and/or not all servers seem to respect the Range header.
Download file using urllib in Python with the wget -c feature
I am programming a software in Python to download HTTP PDF from a database. Sometimes the download stop with this message : retrieval incomplete: got only 3617232 out of 10689634 bytes How can I ask the download to restart where it stops using the 206 Partial Content HTTP feature ? I can do it using wget -c and it works pretty well, but I would like to implement it directly in my Python software. Any idea ? Thank you
[ "You can request a partial download by sending a GET with the Range header:\nimport urllib2\nreq = urllib2.Request('http://www.python.org/')\n#\n# Here we request that bytes 18000--19000 be downloaded.\n# The range is inclusive, and starts at 0.\n#\nreq.headers['Range'] = 'bytes=%s-%s' % (18000, 19000)\nf = urllib2.urlopen(req)\n# This shows you the *actual* bytes that have been downloaded.\nrange=f.headers.get('Content-Range')\nprint(range)\n# bytes 18000-18030/18031\nprint(repr(f.read()))\n# ' </div>\\n</body>\\n</html>\\n\\n\\n\\n\\n\\n\\n'\n\nBe careful to check the Content-Range to learn what bytes have actually been downloaded, since your range may be out of bounds, and/or not all servers seem to respect the Range header.\n" ]
[ 7 ]
[]
[]
[ "download", "http", "python", "urllib", "urllib2" ]
stackoverflow_0002021519_download_http_python_urllib_urllib2.txt
Q: Why does the Python gettext module require a compilation step (.po -> .mo)? I don't see that the compilation step is adding any value. A: Reading just quickly about .mo files, it is clear that: It is a machine-readable representation It is a hash table Given gettext's function, to lookup strings by keys at runtime, it is reasonable for this lookup to be implemented efficiently. Also, it is needed for gettext's performance impact to be negligible; else interest to play nice with the international community would be even lower for english-speaking hackers (from all countries, we all speak english, programming languages are in english). Making the .mo file an already processed representation is good since The format is well suited for quick lookup (hash table) The format needs little processing at application launch (custom-representation binary) A: Because gettext module in Python follows GNU gettext standards which required to use PO files for do translations by people, and MO files for using by application in runtime. When you're using gettext module you're actually using GNUTranslations class, which name suggests it's implementation of GNU gettext. But you can provide your own Translations class and load translations from PO files, there is nothing special about it. There is even some implementation of PO files reader in standard Python distribution, see script msgfmt.py in Tools directory. A: I think that the compilation is .po -> .mo The letters PO in .po files means Portable Object, to distinguish it from .mo files, where MO stands for Machine Object. MO files are meant to be read by programs, and are binary in nature. A few systems already offer tools for creating and handling MO files as part of the Native Language Support coming with the system, but the format of these MO files is often different from system to system, and non-portable. GNU `gettext' utilities - 1.4 Files Conveying Translations
Why does the Python gettext module require a compilation step (.po -> .mo)?
I don't see that the compilation step is adding any value.
[ "Reading just quickly about .mo files, it is clear that:\n\nIt is a machine-readable representation\nIt is a hash table\n\nGiven gettext's function, to lookup strings by keys at runtime, it is reasonable for this lookup to be implemented efficiently.\nAlso, it is needed for gettext's performance impact to be negligible; else interest to play nice with the international community would be even lower for english-speaking hackers (from all countries, we all speak english, programming languages are in english).\nMaking the .mo file an already processed representation is good since\n\nThe format is well suited for quick lookup (hash table)\nThe format needs little processing at application launch (custom-representation binary)\n\n", "Because gettext module in Python follows GNU gettext standards which required to use PO files for do translations by people, and MO files for using by application in runtime. When you're using gettext module you're actually using GNUTranslations class, which name suggests it's implementation of GNU gettext.\nBut you can provide your own Translations class and load translations from PO files, there is nothing special about it. There is even some implementation of PO files reader in standard Python distribution, see script msgfmt.py in Tools directory.\n", "I think that the compilation is .po -> .mo\n\nThe letters PO in .po files means Portable Object, to distinguish it from .mo files, where MO stands for Machine Object.\nMO files are meant to be read by programs, and are binary in nature. A few systems already offer tools for creating and handling MO files as part of the Native Language Support coming with the system, but the format of these MO files is often different from system to system, and non-portable.\n\nGNU `gettext' utilities - 1.4 Files Conveying Translations\n" ]
[ 5, 1, 0 ]
[]
[]
[ "gettext", "python" ]
stackoverflow_0001407364_gettext_python.txt
Q: How do I execute (not import) a python script from a python prompt? I need to execute a Python script from an already started Python session, as if it were launched from the command line. I'm thinking of similar to doing source in bash or sh. A: In Python 2, the builtin function execfile does this. execfile(filename) A: If you're running ipython (which I highly recommend for interactive python sessions), you can type: %run filename or %run filename.py to execute the module (rather than importing it). You'll get file-name completion, which is great for ReallyLongModuleName.py (not that you'd name your modules like that or anything).
How do I execute (not import) a python script from a python prompt?
I need to execute a Python script from an already started Python session, as if it were launched from the command line. I'm thinking of similar to doing source in bash or sh.
[ "In Python 2, the builtin function execfile does this.\nexecfile(filename)\n\n", "If you're running ipython (which I highly recommend for interactive python sessions), you can type:\n%run filename \n\nor\n%run filename.py\n\nto execute the module (rather than importing it). You'll get file-name completion, which is great for ReallyLongModuleName.py (not that you'd name your modules like that or anything).\n" ]
[ 12, 3 ]
[]
[]
[ "bash", "import", "module", "python" ]
stackoverflow_0002021345_bash_import_module_python.txt
Q: how to update a record using DBSession in turbogears 2 Hi I'm trying to update a user row upon the user logging in. I simply want to increase the users login count by one. Here is the code in the post_login controller method: @expose() def post_login(self, came_from=url('/')): """ Redirect the user to the initially requested page on successful authentication or redirect her back to the login page if login failed. """ if not request.identity: login_counter = request.environ['repoze.who.logins'] + 1 redirect(url('/user/login', came_from=came_from, __logins=login_counter)) user_name = request.identity['repoze.who.userid'] user = User.by_user_name(user_name) user.tll_num_logins += 1 user.tll_last_login = datetime.now() redirect(came_from) The user record simply isnt getting updated in the database. The TG documentation says that the transaction manager should flush all of the transactions and automatically execute all the outstanding SQL but it doesnt seem to be working with update. I've tried putting in a DBSession.commit() after to manually commit but get an error message. Likewise, adding DBSession.flush() to the controller method does not error but does not actually update the record either. A: Sorry all, turns out the TG2 transaction manager was working after all. The error came because I was calling the post_login function outside of the transaction manager and so the record update was not getting flushed. I'm not sure why it wasn't letting me commit. But I moved the post_login controller and now the above code I specified works, it updates automatically - no need even for DBSession.update(user). A: You must tell the session object to update the object: DBSession.update(user)
how to update a record using DBSession in turbogears 2
Hi I'm trying to update a user row upon the user logging in. I simply want to increase the users login count by one. Here is the code in the post_login controller method: @expose() def post_login(self, came_from=url('/')): """ Redirect the user to the initially requested page on successful authentication or redirect her back to the login page if login failed. """ if not request.identity: login_counter = request.environ['repoze.who.logins'] + 1 redirect(url('/user/login', came_from=came_from, __logins=login_counter)) user_name = request.identity['repoze.who.userid'] user = User.by_user_name(user_name) user.tll_num_logins += 1 user.tll_last_login = datetime.now() redirect(came_from) The user record simply isnt getting updated in the database. The TG documentation says that the transaction manager should flush all of the transactions and automatically execute all the outstanding SQL but it doesnt seem to be working with update. I've tried putting in a DBSession.commit() after to manually commit but get an error message. Likewise, adding DBSession.flush() to the controller method does not error but does not actually update the record either.
[ "Sorry all, turns out the TG2 transaction manager was working after all. The error came because I was calling the post_login function outside of the transaction manager and so the record update was not getting flushed. I'm not sure why it wasn't letting me commit. But I moved the post_login controller and now the above code I specified works, it updates automatically - no need even for DBSession.update(user). \n", "You must tell the session object to update the object:\nDBSession.update(user)\n\n" ]
[ 2, 1 ]
[]
[]
[ "python", "sqlalchemy", "turbogears2" ]
stackoverflow_0002018494_python_sqlalchemy_turbogears2.txt
Q: Python asyncore vs plain old C i'm stress testing 2 different projects: one is proxsmtpd - smtp proxy written in C And the other one, smtp_proxy.py, which i developed under 1 hour, with use of asyncore and smtpd python modules. I stressed both projects under heavy load, and found out that proxsmtpd is able to hold 400 smtp sessions / sec, while my python program, is able to do only 160 smtp sessions /sec. So, my question is, does it because there are some performance limitations in asyncore, or C programs are just faster? Or maybe it's me, using asyncore in inefficient way? A: I think it's a fair assumption that given a good C version and a good Python version, the C version will be faster and more scalable but in your case, you might want to run a profiler and see why and where your program is not scaling up as much as the C version. Perhaps you can uncover the tight spots and optimise it to squeeze some more performance out of your code. Also, I don't know much about asyncore but the first Python library people seem to gravitate towards when they want to do async stuff is twisted. So, perhaps there is a performance improvement there.
Python asyncore vs plain old C
i'm stress testing 2 different projects: one is proxsmtpd - smtp proxy written in C And the other one, smtp_proxy.py, which i developed under 1 hour, with use of asyncore and smtpd python modules. I stressed both projects under heavy load, and found out that proxsmtpd is able to hold 400 smtp sessions / sec, while my python program, is able to do only 160 smtp sessions /sec. So, my question is, does it because there are some performance limitations in asyncore, or C programs are just faster? Or maybe it's me, using asyncore in inefficient way?
[ "I think it's a fair assumption that given a good C version and a good Python version, the C version will be faster and more scalable but in your case, you might want to run a profiler and see why and where your program is not scaling up as much as the C version. Perhaps you can uncover the tight spots and optimise it to squeeze some more performance out of your code. Also, I don't know much about asyncore but the first Python library people seem to gravitate towards when they want to do async stuff is twisted. So, perhaps there is a performance improvement there. \n" ]
[ 2 ]
[]
[]
[ "asyncore", "proxy", "python", "smtp", "smtpd" ]
stackoverflow_0002022211_asyncore_proxy_python_smtp_smtpd.txt
Q: Database Design Inquiry I'm making a trivia webapp that will feature both standalone questions, and 5+ question quizzes. I'm looking for suggestions for designing this model. Should a quiz and its questions be stored in separate tables/objects, with a key to tie them together, or am I better off creating the quiz as a standalone entity, with lists stored for each of a question's characteristics? Or perhaps someone has another idea... Thank you in advance. It would probably help to say that I am using Google App Engine, which typically frowns upon relational db models, but I'm willing to go my own route if it makes sense. A: It's hard to say without more information, but having the following relations would be sensible, based on what you've said: Quiz (id, title) Question (id, question, answer) QuizQuestion (quiz_id, question_id) That way questions can appear in multiple quizzes. A: My first cut (I assumed the questions were multiple choice): I'd have a table of Questions, with ID_Question as the PK, the question text, and a category (if you want). I'd have a table of Answers, with ID_Answer as the PK, QuestionID as a FK back to the Questions table, the answer text, and a flag as to whether it's the correct answer or not. I'd have a table of Quizzes, with ID_Quiz as the PK, and a description of the quiz, and a category (if you want). I'd have a table of QuizQuestions, with ID_QuizQuestion as the PK, QuizID as a FK back to the Quizzes table, and QuestionID as a FK back to the Questions table. This model lets you: Use questions standalone or in quizzes Lets you have as many or few questions in a quiz as you want Lets you have as many of few choices for questions as you want (or even multiple correct answers) Use questions in several different quizzes A: I recently completed an App Engine app for taking personality quizzes. I would say go the super simple route and store everything about each quiz in a single Quiz entity. If you don't need to reuse questions between quizzes, don't need to search or in any other way access the structure of a quiz besides taking the quiz, you could simply do: class Quiz(db.Model): data = db.TextProperty(default=None) Then data can be a JSON structure like: data = { "title" : "Capitals quiz", "questions" : [ { "text" : "What is the capital of Finland?" "options" : ["Stockholm, Helsinki, London"], "correct" : 1 } ... ] } Things for which you want indexes you will want to leave out of this data structure. For example in my app I found I need to leave ID of the quiz creator outside the data so that I can make a data store query for all quizzes created by a certain person. Also I have creation date outside of the data, so that I can query for latest quizzes. created = db.DateTimeProperty(auto_now_add=True) You might have some other fields like this. Like I said this is a very simple way to store quizzes without needing to have multiple data store entities or queries for a quiz. However it has worked well in practice in my own personality tests app and is an increasingly popular way of storing data. A: Have a table of questions, a table of quizzes and a mapping table between them. That will give you the most flexibility. This is simple enough that you wouldn't even necessarily need a whole relational database management system. I think people tend to forget that relations are pretty simple mathematical/logical concepts. An RDBMS just handles a lot of the messy book keeping for you. A: Here's a design that will account for having a many-to-many relationship between Quizess and Questions. In other words, a Quiz can have many questions, and a Question can belong to many Quizzes. There is only one copy of a Question, so changes can be made to it that will then be reflected in each Quiz to which the Question belongs. class Quiz(db.Model): # Data specific to your Quiz: number, name, times shown, etc questions = db.ListProperty(db.Key) class Questions(db.Model): question = db.StringProperty() choices = db.StringListProperty() # List of possible anwsers correct = db.IntegerpProperty() # index of string in choices that is correct The questions property of a Quiz entity holds the Key of each Question entity which is assigned to the Quiz. Look up by key is speedy, and it allows any one Question to be assigned to any number of individual Quizzes.
Database Design Inquiry
I'm making a trivia webapp that will feature both standalone questions, and 5+ question quizzes. I'm looking for suggestions for designing this model. Should a quiz and its questions be stored in separate tables/objects, with a key to tie them together, or am I better off creating the quiz as a standalone entity, with lists stored for each of a question's characteristics? Or perhaps someone has another idea... Thank you in advance. It would probably help to say that I am using Google App Engine, which typically frowns upon relational db models, but I'm willing to go my own route if it makes sense.
[ "It's hard to say without more information, but having the following relations would be sensible, based on what you've said:\nQuiz (id, title)\nQuestion (id, question, answer)\nQuizQuestion (quiz_id, question_id)\n\nThat way questions can appear in multiple quizzes. \n", "My first cut (I assumed the questions were multiple choice):\n\nI'd have a table of Questions, with ID_Question as the PK, the question text, and a category (if you want).\nI'd have a table of Answers, with ID_Answer as the PK, QuestionID as a FK back to the Questions table, the answer text, and a flag as to whether it's the correct answer or not.\nI'd have a table of Quizzes, with ID_Quiz as the PK, and a description of the quiz, and a category (if you want).\nI'd have a table of QuizQuestions, with ID_QuizQuestion as the PK, QuizID as a FK back to the Quizzes table, and QuestionID as a FK back to the Questions table.\n\nThis model lets you:\n\nUse questions standalone or in quizzes\nLets you have as many or few questions in a quiz as you want\nLets you have as many of few choices for questions as you want (or even multiple correct answers)\nUse questions in several different quizzes\n\n", "I recently completed an App Engine app for taking personality quizzes.\nI would say go the super simple route and store everything about each quiz in a single Quiz entity. If you don't need to reuse questions between quizzes, don't need to search or in any other way access the structure of a quiz besides taking the quiz, you could simply do:\nclass Quiz(db.Model):\n data = db.TextProperty(default=None)\n\nThen data can be a JSON structure like:\ndata = {\n \"title\" : \"Capitals quiz\",\n \"questions\" : [\n {\n \"text\" : \"What is the capital of Finland?\"\n \"options\" : [\"Stockholm, Helsinki, London\"],\n \"correct\" : 1\n }\n ...\n ]\n}\n\nThings for which you want indexes you will want to leave out of this data structure. For example in my app I found I need to leave ID of the quiz creator outside the data so that I can make a data store query for all quizzes created by a certain person. Also I have creation date outside of the data, so that I can query for latest quizzes.\ncreated = db.DateTimeProperty(auto_now_add=True)\n\nYou might have some other fields like this. Like I said this is a very simple way to store quizzes without needing to have multiple data store entities or queries for a quiz. However it has worked well in practice in my own personality tests app and is an increasingly popular way of storing data.\n", "Have a table of questions, a table of quizzes and a mapping table between them. That will give you the most flexibility. This is simple enough that you wouldn't even necessarily need a whole relational database management system. I think people tend to forget that relations are pretty simple mathematical/logical concepts. An RDBMS just handles a lot of the messy book keeping for you.\n", "Here's a design that will account for having a many-to-many relationship between Quizess and Questions. In other words, a Quiz can have many questions, and a Question can belong to many Quizzes. There is only one copy of a Question, so changes can be made to it that will then be reflected in each Quiz to which the Question belongs.\nclass Quiz(db.Model):\n # Data specific to your Quiz: number, name, times shown, etc\n questions = db.ListProperty(db.Key)\n\nclass Questions(db.Model):\n question = db.StringProperty()\n choices = db.StringListProperty() # List of possible anwsers\n correct = db.IntegerpProperty() # index of string in choices that is correct\n\nThe questions property of a Quiz entity holds the Key of each Question entity which is assigned to the Quiz. Look up by key is speedy, and it allows any one Question to be assigned to any number of individual Quizzes.\n" ]
[ 3, 1, 1, 0, 0 ]
[]
[]
[ "database_design", "google_app_engine", "python", "schema" ]
stackoverflow_0002017930_database_design_google_app_engine_python_schema.txt
Q: How to diff file and output stream "on-the-fly"? I need to create a diff file using standard UNIX diff command with python subprocess module. The problem is that I must compare file and stream without creating tempopary file. I thought about using named pipes via os.mkfifo method, but didn't reach any good result. Please, can you write a simple example on how to solve this stuff? I tried like so: fifo = 'pipe' os.mkfifo(fifo) op = popen('cat ', fifo) print >> open(fifo, 'w'), output os.unlink(fifo) proc = Popen(['diff', '-u', dumpfile], stdin=op, stdout=PIPE) but it seems like diff doesn't see the second argument. A: You can use "-" as an argument to diff to mean stdin. A: You could perhaps consider using the difflib python module (I've linked to an example here) and create something that generates and prints the diff directly rather than relying on diff. The various function methods inside difflib can receive character buffers which can be processed into diffs of various types. Alternatively, you can construct a shell pipeline and use process substitution like so diff <(cat pipe) dumpfile # You compare the output of a process and a physical file without explicitly using a temporary file. For details, check out http://tldp.org/LDP/abs/html/process-sub.html
How to diff file and output stream "on-the-fly"?
I need to create a diff file using standard UNIX diff command with python subprocess module. The problem is that I must compare file and stream without creating tempopary file. I thought about using named pipes via os.mkfifo method, but didn't reach any good result. Please, can you write a simple example on how to solve this stuff? I tried like so: fifo = 'pipe' os.mkfifo(fifo) op = popen('cat ', fifo) print >> open(fifo, 'w'), output os.unlink(fifo) proc = Popen(['diff', '-u', dumpfile], stdin=op, stdout=PIPE) but it seems like diff doesn't see the second argument.
[ "You can use \"-\" as an argument to diff to mean stdin.\n", "You could perhaps consider using the difflib python module (I've linked to an example here) and create something that generates and prints the diff directly rather than relying on diff. The various function methods inside difflib can receive character buffers which can be processed into diffs of various types. \nAlternatively, you can construct a shell pipeline and use process substitution like so\ndiff <(cat pipe) dumpfile # You compare the output of a process and a physical file without explicitly using a temporary file.\n\nFor details, check out http://tldp.org/LDP/abs/html/process-sub.html\n" ]
[ 38, 8 ]
[]
[]
[ "diff", "pipe", "python", "subprocess" ]
stackoverflow_0002022492_diff_pipe_python_subprocess.txt
Q: Create a new Tuple with one element modified (I am working interactively with a WordprocessingDocument object in IronPython using the OpenXML SDK, but this is really a general Python question that should be applicable across all implementations) I am trying to scrape out some tables from a number of Word documents. For each table, I have an iterator that is giving me table row objects. I then use the following generator statement to get a tuple of cells from each row: for row in rows: t = tuple([c.InnerText for c in row.Descendants[TableCell]()]) Each tuple contains 4 elements. Now, in column t[1] for each tuple, I need to apply a regex to the data. I know that tuples are immutable, so I'm happy to either create a new tuple, or build the tuple in a different way. Given that row.Descendants[TableCell]() returns an iterator, what's the most Pythonic (or at least simplest) way to construct a tuple from an iterator where I want to modify the nth element returned? My brute-force method right now is to create a tuple from the left slice (t[:n-1]), the modified data in t[n] and the right slice (t[n+1:]) but I feel like the itertools module should have something to help me out here. A: def item(i, v): if i != 1: return v return strangestuff(v) for row in rows: t = tuple(item(i, c.InnerText) for i, c in enumerate(row.Descendants[TableCell]()) ) A: I would do this: temp_list = [c.InnerText for c in row.Descendants[TableCell]()] temp_list[2] = "Something different" t = tuple(temp_list) It would work like this: >>> temp_list = [i for i in range(4)] >>> temp_list[2] = "Something different" >>> t = tuple(temp_list) >>> t (0, 1, 'Something different', 3) A: If every tuple contains 4 elements, then, frankly, I think you'd be better off assigning them to individual variables, manipulating those, and then building your tuple: for row in rows: t1, t2, t3, t4 = tuple([c.InnerText for c in row.Descendants[TableCell]()]) t1 = ... t = (t1, t2, t3, t4) A: What i've generally done, but am not a fan of: l = list(oldtuple) l[2] = foo t = tuple(l) I kind of want something like update() for dicts newtuple = update(oldtuple, (None, None, val, None)) Or perhaps the right structure is a zip newtuple = update(oldtuple, ((2, val), (3, val)))
Create a new Tuple with one element modified
(I am working interactively with a WordprocessingDocument object in IronPython using the OpenXML SDK, but this is really a general Python question that should be applicable across all implementations) I am trying to scrape out some tables from a number of Word documents. For each table, I have an iterator that is giving me table row objects. I then use the following generator statement to get a tuple of cells from each row: for row in rows: t = tuple([c.InnerText for c in row.Descendants[TableCell]()]) Each tuple contains 4 elements. Now, in column t[1] for each tuple, I need to apply a regex to the data. I know that tuples are immutable, so I'm happy to either create a new tuple, or build the tuple in a different way. Given that row.Descendants[TableCell]() returns an iterator, what's the most Pythonic (or at least simplest) way to construct a tuple from an iterator where I want to modify the nth element returned? My brute-force method right now is to create a tuple from the left slice (t[:n-1]), the modified data in t[n] and the right slice (t[n+1:]) but I feel like the itertools module should have something to help me out here.
[ "def item(i, v):\n if i != 1: return v\n return strangestuff(v)\n\nfor row in rows:\n t = tuple(item(i, c.InnerText)\n for i, c in enumerate(row.Descendants[TableCell]())\n )\n\n", "I would do this:\ntemp_list = [c.InnerText for c in row.Descendants[TableCell]()]\ntemp_list[2] = \"Something different\"\nt = tuple(temp_list)\n\nIt would work like this:\n>>> temp_list = [i for i in range(4)]\n>>> temp_list[2] = \"Something different\"\n>>> t = tuple(temp_list)\n>>> t\n(0, 1, 'Something different', 3)\n\n", "If every tuple contains 4 elements, then, frankly, I think you'd be better off assigning them to individual variables, manipulating those, and then building your tuple:\nfor row in rows:\n t1, t2, t3, t4 = tuple([c.InnerText for c in row.Descendants[TableCell]()])\n t1 = ...\n t = (t1, t2, t3, t4)\n\n", "What i've generally done, but am not a fan of:\nl = list(oldtuple)\nl[2] = foo\nt = tuple(l)\nI kind of want something like update() for dicts \nnewtuple = update(oldtuple, (None, None, val, None))\nOr perhaps the right structure is a zip\nnewtuple = update(oldtuple, ((2, val), (3, val)))\n" ]
[ 6, 2, 1, 0 ]
[]
[]
[ "generator", "ironpython", "iterator", "python" ]
stackoverflow_0001784478_generator_ironpython_iterator_python.txt
Q: Beginner wondering if his code is 'Pythonic' This is really the first thing that I have written in python. I come from Java background. I don't want to just learn how to program java code with Python syntax. I want to learn how to program in a pythonic paradigm. Could you guys please comment on how I can make the following code more pythonic? from math import sqrt # recursively computes the factors of a number def factors(num): factorList = [] numroot = int(sqrt(num)) + 1 numleft = num # brute force divide the number until you find a factor for i in range(2, numroot): if num % i == 0: # if we found a factor, add it to the list and compute the remainder factorList.append(i) numleft = num / i break # if we didn't find a factor, get out of here! if numleft == num: factorList.append(num) return factorList # now recursively find the rest of the factors restFactors = factors(numleft) factorList.extend(restFactors) return factorList # grabs all of the twos in the list and puts them into 2 ^ x form def transformFactorList(factorList): num2s = 0 # remove all twos, counting them as we go while 2 in factorList: factorList.remove(2) num2s += 1 # simply return the list with the 2's back in the right spot if num2s == 0: return factorList if num2s == 1: factorList.insert(0, 2) return factorList factorList.insert(0, '2 ^ ' + str(num2s)) return factorList print transformFactorList(factors(#some number)) A: There is an excellent primer by David Goodger called "Code Like a Pythonista" here. A couple of things from that text re naming (quoting): joined_lower for functions, methods, attributes joined_lower or ALL_CAPS for constants StudlyCaps for classes camelCase only to conform to pre-existing conventions A: Just use 'import math' and 'math.sqrt()' instead of 'from math import sqrt' and 'sqrt()'; you don't win anything by just importing 'sqrt', and code quickly gets unwieldy with too many from-imports. Also, things like reload() and mocking out for tests break a lot faster when you use from-import a lot. The divmod() function is a convenient way to perform both division and modulo. You can use for/else instead of the separate check on numleft. Your factors function is a natural candidate for a generator. xrange() was already mentioned in another answer. Here's it all done that way: import math # recursively computes the factors of a number as a generator def factors(num): numroot = int(math.sqrt(num)) + 1 # brute force divide the number until you find a factor for i in xrange(2, numroot): divider, remainder = divmod(num, i) if not remainder: # if we found a factor, add it to the list and compute the # remainder yield i break else: # if we didn't find a factor, get out of here! yield num return # now recursively find the rest of the factors for factor in factors(divider): yield factor Using a generator does mean you can only iterate over the result once; if you simply want a list (like you do in translateFactorsList) you will have to wrap the call to factors() in list(). A: One other thing you might want to look at is the docstring. For example, the comment for this function: # recursively computes the factors of a number def factors(num): Could be converted into this: def factors(num): """ recursively computes the factors of a number""" It's not really 100% necessary to do it this way, but it's a good habit to get into in case you ever start using something along the lines of pydoc. You can also do this: docstring.py """This is a docstring""" at the command line: >>> import docstring >>> help(docstring) results: Help on module docstring: NAME docstring - This is a docstring FILE /Users/jason/docstring.py A: A few comments: I would replace range() with xrange(); when you call range(), it allocates the entire range all at once, whereas when you iterate over xrange(), it returns each result one at a time, saving memory. Don't put expressions after conditionals on the same line (if num2s -- 0: return factorList). It makes it harder to see at a glance what it's doing (that it's a block). Don't be afraid to use modules. The [sympy][1] module already has code to compute factors, which may simplify your code by eliminating most of it. Python's string formatting is simple and effective. For example: factorList.insert(0, '2 ^ ' + str(num2s)) could be changed to factorlist.insert(0, '2 ^ %s' % num2s) All in all, I don't find your code to be extensively un-pythonic. Just make sure you want to use floor division, because that's what tends to happen by default with integer values. Otherwise, you'll need to fix up the division operator: from __future__ import division A sometimes-frustrating caveat of the language. A: from itertools import takewhile def transform_factor_list(factor_list): num_2s = len(list(takewhile(lambda e: e == 2, factor_list))) if num_2s > 1: factor_list[:num_2s] = ["2 ^ %i" % (num_2s, )] return factor_list That's what I would make out of the second function. Most pythonic changes: PEP-8 compatible naming slicing (and assigning to slices) iterators string formatting The function assumes that the input is ordered, which is fulfilled by factors. Edit: removed special cases for some lists, more compact this way A: Based on chris's answer, slightly simplified: for instead of external while internal while to preserve ability to use same divisor repeatedly use itertools.groupby simplifies compress() by much fix a small bug in tostring() HTH: import itertools def factorize(n): # ideally an iterator of prime numbers # this'll work though divisors = itertools.count(2) for divisor in divisors: # This condition is very clever! # Note that `n` is decreasing, while `divisor` is increasing. # And we know that `n` is not divisible by anything smaller, # so this stops as soon as the remaining `n` is obviously prime. if divisor**2 > n: yield n break while n % divisor == 0: yield divisor n //= divisor def compress(factors): for (factor, copies) in itertools.groupby(factors): # The second object yielded by groupby is a generator of equal factors. # Using list() to count its length. power = len(list(copies)) yield (factor, power) def tostring(compressed): return ' * '.join("%d**%d" % (factor, power) for (factor, power) in compressed) # test assert tostring(compress(factorize(12))) == '2**2 * 3**1' A: Don't be afraid of list comprehensions. Switching from Java to Python and discovering them was a good day. For the factors function, maybe something like this: def factors(num): return [i for i in xrange(1, num+1) if num % i == 0] Probably not the best code but it's short and easy to understand. Good luck with Python, it's a great language. A: this is how I'd do this... import itertools import collections def factorize(n): # ideally an iterator of prime numbers # this'll work though divisors = itertools.count(2) divisor = divisors.next() while True: if divisor**2 > n: yield n break a,b = divmod(n, divisor) if b == 0: yield divisor n = a else: divisor = divisors.next() def compress(factors): summands = collections.defaultdict(lambda: 0) for factor in factors: summands[factor] += 1 return [(base, summands[base]) for base in sorted(summands)] def tostring(compressed): return ' * '.join("%d**%d" % factor for factor in compressed) A: Here's what jumps out at me: def transformFactorList(factorList): oldsize = len(factorList) factorList = [f for f in factorList if f != 2] num2s = oldsize - len(factorList) if num2s == 0: return [] if num2s == 1: return [2]+factorList return ['2 ^ %s' % num2s] + [factorList] The form [f for f in factorList if f != 2] is called a list-comprehension. A: Since this post seems to be resurrected by Casey (lol), I'll add in my 2 cents. Go over everything in PEP-8. It helped me out substantially when I had code formatting issues. A: I'd use a list comprehension to get the twos out: def transformFactorList(factorList): twos = [x for x in factorList if x == 2] rest = [x for x in factorList if x != 2] rest.insert(0, "2 ^ %d" % len(twos)) return rest Note that this will give you 2^0 and 2^1, which your code didn't. What you're doing with the twos seems arbitraty (sometimes you get a string, sometimes a number, sometimes nothing), so I figured that would be fine. You can change that easily if you want: def transformFactorList(factorList): twos = [x for x in factorList if x == 2] rest = [x for x in factorList if x != 2] if twos: rest.insert(0, 2 if len(twos)==1 else "2 ^ %d" % len(twos)) return rest A: Using recursion (where not necessary) is not pythonic. Python doesn't have tail recursion elimination and flat is better than nested. When in doubt, try import this update: by popular request, here goes the iterative factorization (sigh): """returns an iterator of tuples (factor, power) such that reduce(operator.mul, (factor**power for factor, power in factors(n))) == n """ def factors(n): i = 2 while n > 1: p = 0 while n > 1 and n % i == 0: p += 1 n /= i if p: yield (i, p) i += 1
Beginner wondering if his code is 'Pythonic'
This is really the first thing that I have written in python. I come from Java background. I don't want to just learn how to program java code with Python syntax. I want to learn how to program in a pythonic paradigm. Could you guys please comment on how I can make the following code more pythonic? from math import sqrt # recursively computes the factors of a number def factors(num): factorList = [] numroot = int(sqrt(num)) + 1 numleft = num # brute force divide the number until you find a factor for i in range(2, numroot): if num % i == 0: # if we found a factor, add it to the list and compute the remainder factorList.append(i) numleft = num / i break # if we didn't find a factor, get out of here! if numleft == num: factorList.append(num) return factorList # now recursively find the rest of the factors restFactors = factors(numleft) factorList.extend(restFactors) return factorList # grabs all of the twos in the list and puts them into 2 ^ x form def transformFactorList(factorList): num2s = 0 # remove all twos, counting them as we go while 2 in factorList: factorList.remove(2) num2s += 1 # simply return the list with the 2's back in the right spot if num2s == 0: return factorList if num2s == 1: factorList.insert(0, 2) return factorList factorList.insert(0, '2 ^ ' + str(num2s)) return factorList print transformFactorList(factors(#some number))
[ "There is an excellent primer by David Goodger called \"Code Like a Pythonista\" here. A couple of things from that text re naming (quoting):\n\njoined_lower for functions, methods,\nattributes\njoined_lower or ALL_CAPS for\nconstants\nStudlyCaps for classes\ncamelCase only to conform to\npre-existing conventions\n\n", "Just use 'import math' and 'math.sqrt()' instead of 'from math import sqrt' and 'sqrt()'; you don't win anything by just importing 'sqrt', and code quickly gets unwieldy with too many from-imports. Also, things like reload() and mocking out for tests break a lot faster when you use from-import a lot.\nThe divmod() function is a convenient way to perform both division and modulo. You can use for/else instead of the separate check on numleft. Your factors function is a natural candidate for a generator. xrange() was already mentioned in another answer. Here's it all done that way:\nimport math\n\n# recursively computes the factors of a number as a generator\ndef factors(num):\n numroot = int(math.sqrt(num)) + 1\n # brute force divide the number until you find a factor\n for i in xrange(2, numroot):\n divider, remainder = divmod(num, i)\n if not remainder:\n # if we found a factor, add it to the list and compute the\n # remainder\n yield i\n break\n else:\n # if we didn't find a factor, get out of here!\n yield num\n return\n # now recursively find the rest of the factors\n for factor in factors(divider):\n yield factor\n\nUsing a generator does mean you can only iterate over the result once; if you simply want a list (like you do in translateFactorsList) you will have to wrap the call to factors() in list().\n", "One other thing you might want to look at is the docstring. For example, the comment for this function:\n# recursively computes the factors of a number\ndef factors(num):\n\nCould be converted into this:\ndef factors(num):\n \"\"\" recursively computes the factors of a number\"\"\"\n\nIt's not really 100% necessary to do it this way, but it's a good habit to get into in case you ever start using something along the lines of pydoc.\nYou can also do this:\ndocstring.py\n\"\"\"This is a docstring\"\"\"\n\nat the command line:\n>>> import docstring\n>>> help(docstring)\n\nresults:\nHelp on module docstring:\n\nNAME\n docstring - This is a docstring\n\nFILE\n /Users/jason/docstring.py\n\n", "A few comments:\n\nI would replace range() with xrange(); when you call range(), it allocates the entire range all at once, whereas when you iterate over xrange(), it returns each result one at a time, saving memory.\nDon't put expressions after conditionals on the same line (if num2s -- 0: return factorList). It makes it harder to see at a glance what it's doing (that it's a block).\nDon't be afraid to use modules. The [sympy][1] module already has code to compute factors, which may simplify your code by eliminating most of it.\nPython's string formatting is simple and effective.\n\nFor example:\nfactorList.insert(0, '2 ^ ' + str(num2s))\n\ncould be changed to \nfactorlist.insert(0, '2 ^ %s' % num2s)\n\nAll in all, I don't find your code to be extensively un-pythonic. Just make sure you want to use floor division, because that's what tends to happen by default with integer values. Otherwise, you'll need to fix up the division operator:\nfrom __future__ import division\n\nA sometimes-frustrating caveat of the language.\n", "from itertools import takewhile\n\ndef transform_factor_list(factor_list):\n num_2s = len(list(takewhile(lambda e: e == 2, factor_list)))\n if num_2s > 1:\n factor_list[:num_2s] = [\"2 ^ %i\" % (num_2s, )]\n return factor_list\n\nThat's what I would make out of the second function. \nMost pythonic changes:\n\nPEP-8 compatible naming\nslicing (and assigning to slices)\niterators\nstring formatting\n\nThe function assumes that the input is ordered, which is fulfilled by factors.\nEdit: removed special cases for some lists, more compact this way\n", "Based on chris's answer, slightly simplified:\n\nfor instead of external while\ninternal while to preserve ability to use same divisor repeatedly\nuse itertools.groupby simplifies compress() by much\nfix a small bug in tostring()\n\nHTH:\nimport itertools\n\ndef factorize(n):\n # ideally an iterator of prime numbers\n # this'll work though\n divisors = itertools.count(2)\n\n for divisor in divisors:\n # This condition is very clever!\n # Note that `n` is decreasing, while `divisor` is increasing.\n # And we know that `n` is not divisible by anything smaller,\n # so this stops as soon as the remaining `n` is obviously prime.\n if divisor**2 > n:\n yield n\n break\n\n while n % divisor == 0:\n yield divisor\n n //= divisor\n\ndef compress(factors):\n for (factor, copies) in itertools.groupby(factors):\n # The second object yielded by groupby is a generator of equal factors.\n # Using list() to count its length.\n power = len(list(copies))\n yield (factor, power)\n\ndef tostring(compressed):\n return ' * '.join(\"%d**%d\" % (factor, power) for (factor, power) in compressed)\n\n# test\nassert tostring(compress(factorize(12))) == '2**2 * 3**1'\n\n", "Don't be afraid of list comprehensions. Switching from Java to Python and discovering them was a good day.\nFor the factors function, maybe something like this:\ndef factors(num):\n return [i for i in xrange(1, num+1) if num % i == 0]\n\nProbably not the best code but it's short and easy to understand.\nGood luck with Python, it's a great language. \n", "this is how I'd do this...\nimport itertools\nimport collections\n\ndef factorize(n):\n # ideally an iterator of prime numbers\n # this'll work though\n divisors = itertools.count(2)\n\n divisor = divisors.next()\n while True:\n if divisor**2 > n:\n yield n\n break\n\n a,b = divmod(n, divisor)\n\n if b == 0:\n yield divisor\n n = a\n else:\n divisor = divisors.next()\n\ndef compress(factors):\n summands = collections.defaultdict(lambda: 0)\n\n for factor in factors:\n summands[factor] += 1\n\n return [(base, summands[base]) for base in sorted(summands)]\n\ndef tostring(compressed):\n return ' * '.join(\"%d**%d\" % factor for factor in compressed)\n\n", "Here's what jumps out at me:\ndef transformFactorList(factorList):\n oldsize = len(factorList)\n factorList = [f for f in factorList if f != 2]\n num2s = oldsize - len(factorList)\n if num2s == 0:\n return []\n if num2s == 1:\n return [2]+factorList\n return ['2 ^ %s' % num2s] + [factorList]\n\nThe form [f for f in factorList if f != 2] is called a list-comprehension.\n", "Since this post seems to be resurrected by Casey (lol), I'll add in my 2 cents.\nGo over everything in PEP-8. It helped me out substantially when I had code formatting issues.\n", "I'd use a list comprehension to get the twos out:\ndef transformFactorList(factorList):\n twos = [x for x in factorList if x == 2]\n rest = [x for x in factorList if x != 2]\n rest.insert(0, \"2 ^ %d\" % len(twos))\n return rest\n\nNote that this will give you 2^0 and 2^1, which your code didn't. What you're doing with the twos seems arbitraty (sometimes you get a string, sometimes a number, sometimes nothing), so I figured that would be fine. You can change that easily if you want:\ndef transformFactorList(factorList):\n twos = [x for x in factorList if x == 2]\n rest = [x for x in factorList if x != 2]\n if twos:\n rest.insert(0, 2 if len(twos)==1 else \"2 ^ %d\" % len(twos))\n return rest\n\n", "Using recursion (where not necessary) is not pythonic. Python doesn't have tail recursion elimination and flat is better than nested.\nWhen in doubt, try import this\nupdate: by popular request, here goes the iterative factorization (sigh):\n\"\"\"returns an iterator of tuples (factor, power) such that \nreduce(operator.mul, (factor**power for factor, power in factors(n))) == n \"\"\"\ndef factors(n):\n i = 2\n while n > 1:\n p = 0\n while n > 1 and n % i == 0:\n p += 1\n n /= i\n if p:\n yield (i, p)\n i += 1\n\n" ]
[ 22, 21, 17, 8, 4, 4, 3, 3, 2, 2, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0000134834_python.txt
Q: cherrypy and wxpython I'm trying to make a cherrypy application with a wxpython ui. The problem is both libraries use closed loop event handlers. Is there a way for this to work? If I have the wx ui start cherrypy is that going to lock up the ui? A: See my answer at CherryPy interferes with Twisted shutting down on Windows In short, CherryPy handles the main loop by default, but it definitely doesn't need to. Stop using quickstart and call engine.start without engine.block, and CP will run in its own threads and leave the main thread for your other framework to control. A: If you use threading, you should be able to start up the CherryPy server in one thread and run wxPython in the other. This article (http://wiki.wxpython.org/LongRunningTasks) on the wxPython wiki has some info on threading, and the CherryPy server source code (http://www.cherrypy.org/browser/trunk/cherrypy/wsgiserver/__init__.py) has some documentation on how the server works, and possibly how you could get it to interact with threads. A: One way to decouple them would be to start them up as two separate processes and have them communicate via some kind of IPC mechanism. You might have to write a small adaptor to have them speak a common protocol. Since you're doing CherryPy, you might also be able to expose a control interface via HTTP which the wx GUI can use to drive your server. A: I would encourage you to take a look at the Calibre (e-book manager) source. It is written in PyQT, but uses CherryPy to allow people to view their library from outside their LAN.
cherrypy and wxpython
I'm trying to make a cherrypy application with a wxpython ui. The problem is both libraries use closed loop event handlers. Is there a way for this to work? If I have the wx ui start cherrypy is that going to lock up the ui?
[ "See my answer at CherryPy interferes with Twisted shutting down on Windows\nIn short, CherryPy handles the main loop by default, but it definitely doesn't need to. Stop using quickstart and call engine.start without engine.block, and CP will run in its own threads and leave the main thread for your other framework to control.\n", "If you use threading, you should be able to start up the CherryPy server in one thread and run wxPython in the other. This article (http://wiki.wxpython.org/LongRunningTasks) on the wxPython wiki has some info on threading, and the CherryPy server source code (http://www.cherrypy.org/browser/trunk/cherrypy/wsgiserver/__init__.py) has some documentation on how the server works, and possibly how you could get it to interact with threads.\n", "One way to decouple them would be to start them up as two separate processes and have them communicate via some kind of IPC mechanism. You might have to write a small adaptor to have them speak a common protocol.\nSince you're doing CherryPy, you might also be able to expose a control interface via HTTP which the wx GUI can use to drive your server.\n", "I would encourage you to take a look at the Calibre (e-book manager) source. It is written in PyQT, but uses CherryPy to allow people to view their library from outside their LAN.\n" ]
[ 5, 1, 1, 1 ]
[]
[]
[ "cherrypy", "python", "wxpython" ]
stackoverflow_0002022376_cherrypy_python_wxpython.txt
Q: Getting started w/ Python on the desktop I'm interested in getting started w/ developing Python based applications for a desktop environment and have a few (seemingly simple) questions: What is the best method for developing GUI applications? I've seen several frameworks but the indexes I've found are a bit convoluted and mix (what seem to be) legacy packages. In your opinion, what is the best approach in this regard? I've been reading a few books I recently picked up, but have been having trouble finding (rather, recognizing) a decent 'getting started' tutorial that focuses on Python apps for the desktop. Do you have any recommendations? Thanks very much in advance! :) A: wxPython is the best GUI framework. The official docs are the best resource. They helped me quite a bit. A: Have you considered Iron Python as an option? It's basically the Python language on top of the .NET Framework. Having been fortunate enough to work with the .NET Framework in the past on desktop-applications, I can attest to its depth of excellent. A: wxPython is a phenomenal GUI toolkit for developing native applications. I highly recommend it. Also, if you combine it with py2exe you can create .exe files for running on Windows. A: easyGUI and Tkinter are VERY easy libraries that can be used with Python to make GUIs. Further, as stealthdragon has suggested, you can use py2exe to compile your GUIs into EXEs for your PC. There are also other compilers such as pyc. As Jonathan Sampson suggests, you might consider using IronPython and use it to wield the full power of the .NET framework. The IronPython Cookbook, which among other things shows you how to make a basic Twitter Client.
Getting started w/ Python on the desktop
I'm interested in getting started w/ developing Python based applications for a desktop environment and have a few (seemingly simple) questions: What is the best method for developing GUI applications? I've seen several frameworks but the indexes I've found are a bit convoluted and mix (what seem to be) legacy packages. In your opinion, what is the best approach in this regard? I've been reading a few books I recently picked up, but have been having trouble finding (rather, recognizing) a decent 'getting started' tutorial that focuses on Python apps for the desktop. Do you have any recommendations? Thanks very much in advance! :)
[ "\nwxPython is the best GUI framework.\nThe official docs are the best resource. They helped me quite a bit.\n\n", "Have you considered Iron Python as an option? It's basically the Python language on top of the .NET Framework. Having been fortunate enough to work with the .NET Framework in the past on desktop-applications, I can attest to its depth of excellent.\n", "wxPython is a phenomenal GUI toolkit for developing native applications. I highly recommend it. Also, if you combine it with py2exe you can create .exe files for running on Windows.\n", "easyGUI and Tkinter are VERY easy libraries that can be used with Python to make GUIs. Further, as stealthdragon has suggested, you can use py2exe to compile your GUIs into EXEs for your PC. There are also other compilers such as pyc.\nAs Jonathan Sampson suggests, you might consider using IronPython and use it to wield the full power of the .NET framework. The IronPython Cookbook, which among other things shows you how to make a basic Twitter Client.\n" ]
[ 4, 1, 1, 1 ]
[]
[]
[ "desktop_application", "python" ]
stackoverflow_0002022967_desktop_application_python.txt
Q: Get list of open windows in Python I am writing an app in Python that must be able to send keys or text to another app. For example, if I have Firefox open, I should be able to send it an URL to open it. I already have the SendKeys module, and I have read about the win32 module too, but I do not know if there is a way to filter out process without open windows. A: Usually, for this sort of "GUI automation" pyWinAuto is a good way to go. We use it to allow automated testing of GUI applications, and it ought to let you "type" URLs into Firefox (not to mention finding its window) as well. A: Even if you need to use automation for everything else your app is going to do, it would probably be a lot easier to use the webbrowser module for opening urls in the user's browser. A: try using dragonfly. It has a whole lot of automation stuff built into it. You don't need the speech recognition part in order to use the automation stuff. For example: from dragonfly import Window Window.get_all_windows() will return a list of all the windows. you also want to look at the FocusWindow() and Keys() objects in dragonfly.
Get list of open windows in Python
I am writing an app in Python that must be able to send keys or text to another app. For example, if I have Firefox open, I should be able to send it an URL to open it. I already have the SendKeys module, and I have read about the win32 module too, but I do not know if there is a way to filter out process without open windows.
[ "Usually, for this sort of \"GUI automation\" pyWinAuto is a good way to go. We use it to allow automated testing of GUI applications, and it ought to let you \"type\" URLs into Firefox (not to mention finding its window) as well.\n", "Even if you need to use automation for everything else your app is going to do, it would probably be a lot easier to use the webbrowser module for opening urls in the user's browser.\n", "try using dragonfly. It has a whole lot of automation stuff built into it. You don't need the speech recognition part in order to use the automation stuff. For example:\nfrom dragonfly import Window\nWindow.get_all_windows()\n\nwill return a list of all the windows.\nyou also want to look at the FocusWindow() and Keys() objects in dragonfly.\n" ]
[ 5, 3, 3 ]
[]
[]
[ "python", "pywin32", "windows" ]
stackoverflow_0002022219_python_pywin32_windows.txt
Q: Trying to get HTTP code. Can someone try this code for me in their Python interpretor and see why it doesn't work? import httplib def httpCode(theurl): if theurl.startswith("http://"): theurl = theurl[7:] head = theurl[:theurl.find('/')] tail = theurl[theurl.find('/'):] response_code = 0 conn = httplib.HTTPConnection(head) conn.request("HEAD",tail) res = conn.getresponse() response_code = int(res.status) return response_code Basically, this function will take a URL and return its HTTP code (200, 404, etc) The error I got was: Exception Value: (-2, 'Name or service not known') I must do it with this method. That is, I am usually passing in large video files. I need to get the "header" and get the HTTP code. I cannot download the file and then get the HTTP code, because it would take too long. Python 2.6.2 (release26-maint, Apr 19 2009, 01:58:18) [GCC 4.3.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import httplib >>> def httpCode(theurl): ... if theurl.startswith("http://"): theurl = theurl[7:] ... head = theurl[:theurl.find('/')] ... tail = theurl[theurl.find('/'):] ... response_code = 0 ... conn = httplib.HTTPConnection(head) ... conn.request("HEAD",tail) ... res = conn.getresponse() ... response_code = int(res.status) ... print response_code ... >>> httpCode('http://youtube.com') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 7, in httpCode File "/usr/lib/python2.6/httplib.py", line 874, in request self._send_request(method, url, body, headers) File "/usr/lib/python2.6/httplib.py", line 911, in _send_request self.endheaders() File "/usr/lib/python2.6/httplib.py", line 868, in endheaders self._send_output() File "/usr/lib/python2.6/httplib.py", line 740, in _send_output self.send(msg) File "/usr/lib/python2.6/httplib.py", line 699, in send self.connect() File "/usr/lib/python2.6/httplib.py", line 683, in connect self.timeout) File "/usr/lib/python2.6/socket.py", line 498, in create_connection for res in getaddrinfo(host, port, 0, SOCK_STREAM): socket.gaierror: [Errno -2] Name or service not known >>> A: Your code worked for me, and for one other person who commented. This implies that the URL you're using is causing a problem with your parsing somehow. head and tail should both be examined in order to determine what it thinks the host is. For example: head = theurl[:theurl.find('/')] print head tail = theurl[theurl.find('/'):] print tail Once you can see what head and tail are, you can determine if it really should be able to resolve head. For example, what if the url was: http://myhost.com:8080/blah/blah It would fail because of the port number. A: As suggested in comment by Adam Crossland, you should be checking your head and tail values. In your case, without a trailing slash you end up with head = "youtube.co" tail = "m" string.find returns -1 if it is not found, hence you are grabbing all but last character for head and only the last character for tail.
Trying to get HTTP code. Can someone try this code for me in their Python interpretor and see why it doesn't work?
import httplib def httpCode(theurl): if theurl.startswith("http://"): theurl = theurl[7:] head = theurl[:theurl.find('/')] tail = theurl[theurl.find('/'):] response_code = 0 conn = httplib.HTTPConnection(head) conn.request("HEAD",tail) res = conn.getresponse() response_code = int(res.status) return response_code Basically, this function will take a URL and return its HTTP code (200, 404, etc) The error I got was: Exception Value: (-2, 'Name or service not known') I must do it with this method. That is, I am usually passing in large video files. I need to get the "header" and get the HTTP code. I cannot download the file and then get the HTTP code, because it would take too long. Python 2.6.2 (release26-maint, Apr 19 2009, 01:58:18) [GCC 4.3.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import httplib >>> def httpCode(theurl): ... if theurl.startswith("http://"): theurl = theurl[7:] ... head = theurl[:theurl.find('/')] ... tail = theurl[theurl.find('/'):] ... response_code = 0 ... conn = httplib.HTTPConnection(head) ... conn.request("HEAD",tail) ... res = conn.getresponse() ... response_code = int(res.status) ... print response_code ... >>> httpCode('http://youtube.com') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 7, in httpCode File "/usr/lib/python2.6/httplib.py", line 874, in request self._send_request(method, url, body, headers) File "/usr/lib/python2.6/httplib.py", line 911, in _send_request self.endheaders() File "/usr/lib/python2.6/httplib.py", line 868, in endheaders self._send_output() File "/usr/lib/python2.6/httplib.py", line 740, in _send_output self.send(msg) File "/usr/lib/python2.6/httplib.py", line 699, in send self.connect() File "/usr/lib/python2.6/httplib.py", line 683, in connect self.timeout) File "/usr/lib/python2.6/socket.py", line 498, in create_connection for res in getaddrinfo(host, port, 0, SOCK_STREAM): socket.gaierror: [Errno -2] Name or service not known >>>
[ "Your code worked for me, and for one other person who commented. This implies that the URL you're using is causing a problem with your parsing somehow. head and tail should both be examined in order to determine what it thinks the host is. For example:\nhead = theurl[:theurl.find('/')]\nprint head\ntail = theurl[theurl.find('/'):]\nprint tail\n\nOnce you can see what head and tail are, you can determine if it really should be able to resolve head. For example, what if the url was:\nhttp://myhost.com:8080/blah/blah\n\nIt would fail because of the port number.\n", "As suggested in comment by Adam Crossland, you should be checking your head and tail values. In your case, without a trailing slash you end up with\nhead = \"youtube.co\"\ntail = \"m\"\n\nstring.find returns -1 if it is not found, hence you are grabbing all but last character for head and only the last character for tail.\n" ]
[ 2, 2 ]
[]
[]
[ "exception", "http", "python", "url" ]
stackoverflow_0002023312_exception_http_python_url.txt
Q: Socket module does not work in my Python Very simple. >>> import socket >>> socket.gethostbyname('http://yahoo.com') Traceback (most recent call last): File "<stdin>", line 1, in <module> socket.gaierror: [Errno -2] Name or service not known A: Very simple. "http://yahoo.com" is not a host name. Try socket.gethostbyname('yahoo.com') :) A: It is because, quite frankly, http://yahoo.com is in no way a domain name, which gethostbyname expects from you. http://yahoo.com is an URL. >>> import socket >>> socket.gethostbyname("yahoo.com") '69.147.114.224'
Socket module does not work in my Python
Very simple. >>> import socket >>> socket.gethostbyname('http://yahoo.com') Traceback (most recent call last): File "<stdin>", line 1, in <module> socket.gaierror: [Errno -2] Name or service not known
[ "Very simple.\n\"http://yahoo.com\" is not a host name. Try socket.gethostbyname('yahoo.com') :)\n", "It is because, quite frankly, http://yahoo.com is in no way a domain name, which gethostbyname expects from you. http://yahoo.com is an URL.\n>>> import socket\n>>> socket.gethostbyname(\"yahoo.com\")\n'69.147.114.224'\n\n" ]
[ 11, 2 ]
[]
[]
[ "http", "python", "sockets" ]
stackoverflow_0002023429_http_python_sockets.txt
Q: How do I turn a dictionary into a JSON object using simplejson, in Python? It's something like this, but this example seems a little complicated. import simplejson as json json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}]) My dictionary is: myfruits = {'fruit':4, 'color':11} How can I turn this into a JSON, and then use render_to_response to shoot it to a template? I'm using Django. A: I think this is the easiest way to do it import simplejson as json myfruits = {'fruit':4, 'color':11} json.dumps(myfruits) A: use json.dumps() (see doc here). import simplejson simplejson.dumps({'fruit':4, 'color':11})
How do I turn a dictionary into a JSON object using simplejson, in Python?
It's something like this, but this example seems a little complicated. import simplejson as json json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}]) My dictionary is: myfruits = {'fruit':4, 'color':11} How can I turn this into a JSON, and then use render_to_response to shoot it to a template? I'm using Django.
[ "I think this is the easiest way to do it\nimport simplejson as json \nmyfruits = {'fruit':4, 'color':11}\njson.dumps(myfruits)\n\n", "use json.dumps() (see doc here).\nimport simplejson\nsimplejson.dumps({'fruit':4, 'color':11})\n\n" ]
[ 6, 1 ]
[]
[]
[ "django", "json", "python" ]
stackoverflow_0002023491_django_json_python.txt
Q: C#, Pass Array As Function Parameters In python the * allows me to pass a list as function parameters: def add(a,b): return a+b x = [1,2] add(*x) Can I replicate this behavior in C# with an array? Thanks. A: The params keyword allows something similar public int Add(params int[] numbers) { int result = 0; foreach (int i in numbers) { result += i; } return result; } // to call: int result = Add(1, 2, 3, 4); // you can also use an array directly int result = Add(new int[] { 1, 2, 3, 4}); A: Except for: Changing the method signature to accept an array Adding an overload that accepts an array, extracts the values and calls the original overload Using reflection to call the method then unfortunately, no, you cannot do that. Keyword-based and positional-based parameter passing like in Python is not supported in .NET, except for through reflection. Note that there's probably several good reasons for why this isn't supported, but the one that comes to my mind is just "why do you need to do this?". Typically, you only use this pattern when you're wrapping the method in another layer, and in .NET you have strongly typed delegates, so typically all that's left is reflection-based code, and even then you usually have a strong grip on the method being called. So my gut reaction, even if I answered your question, is that you should not do this, and find a better, more .NET-friendly way to accomplish what you want. Here's an example using reflection: using System; using System.Reflection; namespace ConsoleApplication1 { class Program { public Int32 Add(Int32 a, Int32 b) { return a + b; } static void Main(string[] args) { Program obj = new Program(); MethodInfo m = obj.GetType().GetMethod("Add"); Int32 result = (Int32)m.Invoke(obj, new Object[] { 1, 2 }); } } } A: You could using reflection. However if it's a variable length all the time you might be better off using an array as your method defenition however you would still need to parse the list unless it's a basic need that can be handled by collection methods / array methods. A: I'm fairly sure you could use reflection to access your method, and then use Invoke, using your array as the parameter list. Kind of round-about, though.
C#, Pass Array As Function Parameters
In python the * allows me to pass a list as function parameters: def add(a,b): return a+b x = [1,2] add(*x) Can I replicate this behavior in C# with an array? Thanks.
[ "The params keyword allows something similar\npublic int Add(params int[] numbers) {\n int result = 0;\n\n foreach (int i in numbers) {\n result += i;\n }\n\n return result;\n}\n\n// to call:\nint result = Add(1, 2, 3, 4);\n// you can also use an array directly\nint result = Add(new int[] { 1, 2, 3, 4});\n\n", "Except for:\n\nChanging the method signature to accept an array\nAdding an overload that accepts an array, extracts the values and calls the original overload\nUsing reflection to call the method\n\nthen unfortunately, no, you cannot do that.\nKeyword-based and positional-based parameter passing like in Python is not supported in .NET, except for through reflection.\nNote that there's probably several good reasons for why this isn't supported, but the one that comes to my mind is just \"why do you need to do this?\". Typically, you only use this pattern when you're wrapping the method in another layer, and in .NET you have strongly typed delegates, so typically all that's left is reflection-based code, and even then you usually have a strong grip on the method being called.\nSo my gut reaction, even if I answered your question, is that you should not do this, and find a better, more .NET-friendly way to accomplish what you want.\nHere's an example using reflection:\nusing System;\nusing System.Reflection;\n\nnamespace ConsoleApplication1\n{\n class Program\n {\n public Int32 Add(Int32 a, Int32 b) { return a + b; }\n static void Main(string[] args)\n {\n Program obj = new Program();\n\n MethodInfo m = obj.GetType().GetMethod(\"Add\");\n Int32 result = (Int32)m.Invoke(obj, new Object[] { 1, 2 });\n }\n }\n}\n\n", "You could using reflection. However if it's a variable length all the time you might be better off using an array as your method defenition however you would still need to parse the list unless it's a basic need that can be handled by collection methods / array methods.\n", "I'm fairly sure you could use reflection to access your method, and then use Invoke, using your array as the parameter list. Kind of round-about, though.\n" ]
[ 12, 9, 2, 1 ]
[]
[]
[ "c#", "python" ]
stackoverflow_0002023528_c#_python.txt
Q: buildbot: connect to IRC server using SSL How can I use buildbot's IRC bot to connect to an IRC server that wants SSL connections? A: I just submitted a small patch to BuildBot which will allow the IRC bot to connect to SSL-enabled servers. Should be included in the next release (0.7.12?). If you want to apply it to your setup, it's a simple patch to backport. A: You could fix the tunnel on the buildbots localhost with stunnel, for e.g.: stunnel -c -D5 -r dest.irc.server:port -d 127.0.0.1:6667 And then let buildbot connect to 127.0.0.1:6667
buildbot: connect to IRC server using SSL
How can I use buildbot's IRC bot to connect to an IRC server that wants SSL connections?
[ "I just submitted a small patch to BuildBot which will allow the IRC bot to connect to SSL-enabled servers. Should be included in the next release (0.7.12?).\nIf you want to apply it to your setup, it's a simple patch to backport.\n", "You could fix the tunnel on the buildbots localhost with stunnel, for e.g.:\n stunnel -c -D5 -r dest.irc.server:port -d 127.0.0.1:6667\n\nAnd then let buildbot connect to 127.0.0.1:6667\n" ]
[ 3, 1 ]
[]
[]
[ "buildbot", "irc", "python", "ssl", "twisted" ]
stackoverflow_0001995474_buildbot_irc_python_ssl_twisted.txt
Q: How to handle new files to process in cron job How can I check files that I already processed in a script so I don't process those again? and/or What is wrong with the way I am doing this now? Hello, I am running tshark with the ring buffer option to dump to files after 5MB or 1 hour. I wrote a python script to read these files in XML and dump into a database, this works fine. My issue is that this is really process intensive, one of those 5MB can turn into a 200MB file when converted to XML, so I do not want to do any unnecessary processing. The script is running every 10 minutes and processes ~5 files per run, since is scanning the folder where the files are created for any new entries, I dump a hash of the file into the database and on the next run check the hash and if it isn't in the database I scan the file. The problem is that this does not appear to work every time, it ends up processing files that it has already done. When I check the hash of the file that it keeps trying to process it doesn't show up anywhere in the database, hence why is trying to process it over and over. I am printing out the filename + hash in the output of the script: using file /var/ss01/SS01_00086_20100107100828.cap with hash: 982d664b574b84d6a8a5093889454e59 using file /var/ss02/SS02_00053_20100106125828.cap with hash: 8caceb6af7328c4aed2ea349062b74e9 using file /var/ss02/SS02_00075_20100106184519.cap with hash: 1b664b2e900d56ca9750d27ed1ec28fc using file /var/ss02/SS02_00098_20100107104437.cap with hash: e0d7f5b004016febe707e9823f339fce using file /var/ss02/SS02_00095_20100105132356.cap with hash: 41a3938150ec8e2d48ae9498c79a8d0c using file /var/ss02/SS02_00097_20100107103332.cap with hash: 4e08b6926c87f5967484add22a76f220 using file /var/ss02/SS02_00090_20100105122531.cap with hash: 470b378ee5a2f4a14ca28330c2009f56 using file /var/ss03/SS03_00089_20100107104530.cap with hash: 468a01753a97a6a5dfa60418064574cc using file /var/ss03/SS03_00086_20100105122537.cap with hash: 1fb8641f10f733384de01e94926e0853 using file /var/ss03/SS03_00090_20100107105832.cap with hash: d6209e65348029c3d211d1715301b9f8 using file /var/ss03/SS03_00088_20100107103248.cap with hash: 56a26b4e84b853e1f2128c831628c65e using file /var/ss03/SS03_00072_20100105093543.cap with hash: dca18deb04b7c08e206a3b6f62262465 using file /var/ss03/SS03_00050_20100106140218.cap with hash: 36761e3f67017c626563601eaf68a133 using file /var/ss04/SS04_00010_20100105105912.cap with hash: 5188dc70616fa2971d57d4bfe029ec46 using file /var/ss04/SS04_00071_20100107094806.cap with hash: ab72eaddd9f368e01f9a57471ccead1a using file /var/ss04/SS04_00072_20100107100234.cap with hash: 79dea347b04a05753cb4ff3576883494 using file /var/ss04/SS04_00070_20100107093350.cap with hash: 535920197129176c4d7a9891c71e0243 using file /var/ss04/SS04_00067_20100107084826.cap with hash: 64a88ecc1253e67d49e3cb68febb2e25 using file /var/ss04/SS04_00042_20100106144048.cap with hash: bb9bfa773f3bf94fd3af2514395d8d9e using file /var/ss04/SS04_00007_20100105101951.cap with hash: d949e673f6138af2d388884f4a6b0f08 The only files it should be doing are one per folder, so only 4 files. This causes unecessary processing and I have to deal with overlapping cron jobs + other services been affected. What I am hoping to get from this post is a better way to do this or hopefully someone can tell me why is happening, I know that the latter might be hard since it can be a bunch of reasons. Here is the code (I am not a coder but a sys admin so be kind :P) line 30-32 handle the hash comparisons. Thanks in advance. A: A good way to handle/process files that are created at random times is to use incron rather than cron. (Note: since incron uses the Linux kernel's inotify syscalls, this solution only works with Linux.) Whereas cron runs a job based on dates and times, incron runs a job based on changes in a monitored directory. For example, you can configure incron to run a job every time a new file is created or modified. On Ubuntu, the package is called incron. I'm not sure about RedHat, but I believe this is the right package: http://rpmfind.net//linux/RPM/dag/redhat/el5/i386/incron-0.5.9-1.el5.rf.i386.html. Once you install the incron package, read man 5 incrontab for information on how to setup the incrontab config file. Your incron_config file might look something like this: /var/ss01/ IN_CLOSE_WRITE /path/to/processing/script.py $# /var/ss02/ IN_CLOSE_WRITE /path/to/processing/script.py $# /var/ss03/ IN_CLOSE_WRITE /path/to/processing/script.py $# /var/ss04/ IN_CLOSE_WRITE /path/to/processing/script.py $# Then to register this config with the incrond daemon, you'd run incrontab /path/to/incron_config That's all there is to it. Now whenever a file is created in /var/ss01, /var/ss02, /var/ss03 or /var/ss04, the command /path/to/processing/script.py $# is run, with $# replaced by the name of the newly created file. This will obviate the need to store/compare hashes, and files will only get processed once -- immediately after they are created. Just make sure your processing script does not write into the top level of the monitored directories. If it does, then incrond will notice the new file created, and launch script.py again, sending you into an infinite loop. incrond monitors individual directories, and does not recursively monitor subdirectories. So you could direct tshark to write to /var/ss01/tobeprocessed, use incron to monitor /var/ss01/tobeprocessed, and have your script.py write to /var/ss01, for example. PS. There is also a python interface to inotify, called pyinotify. Unlike incron, pyinotify can recursively monitor subdirectories. However, in your case, I don't think the recursive monitoring feature is useful or necessary. A: I don't know enough about what is in these files, so this may not work for you, but if you have only one intended consumer, I would recommend using directories and moving the files to reflect their state. Specifically, you could have a dir structure like /waiting /progress /done and use the relative atomicity of mv to change the "state" of each file. (Whether mv is truly atomic depends on your filesystem, I believe.) When your processing task wants to work on a file, it moves it from waiting to progress (and makes sure that the move succeeded). That way, no other task can pick it up, since it's no longer waiting. When the file is complete, it gets moved from progress to done, where a cleanup task might delete or archive old files that are no longer needed. A: I see several issues. If you have overlapping cron jobs you need to have a locking mechanism to control access. Only allow one process at a time to eliminate the overlap problem. You might setup a shell script to do that. Create a 'lock' by making a directory (mkdir is atomic), process the data, then delete the lock directory. If the shell script finds the directory already exists when it tries to make it then you know another copy is already running and it can just exit. If you can't change the cron table(s) then just rename the executable and name your shell script the same as the old executable. Hashes are not guaranteed to be unique identifiers for files, it's likely they are, but it's not absolutely guaranteed. A: Why not just move a processed file to a different directory? You mentioned overlapping cron jobs. Does this mean one conversion process can start before the previous one finished? That means you would perform the move at the beginning of the conversion. If you are worries about an interrupted conversion, use an intermediate directory, and move to a final directory after completion. A: If I'm reading the code correctly, you're updating the database (by which I mean the log of files processed) at the very end. So when you have a huge file that's being processed and not yet complete, another cron job will 'legally' start working on it. - both completing succesfully resulting in two entries in the database. I suggest you move up the logging-to-database, which would act as a lock for subsequent cronjobs and having a 'success' or 'completed' at the very end. The latter part is important as something that's shown as processing but doesnt have a completed state (coupled with the notion of time) can be programtically concluded as an error. (That is to say, a cronjob tried processing it but never completed it and the log show processing for 1 week!) To summarize Move up the log-to-database so that it would act as a lock Add a 'success' or 'completed' state which would give the notion of errored state PS: Dont take it in the wrong way, but the code is a little hard to understand. I am not sure whether I do at all.
How to handle new files to process in cron job
How can I check files that I already processed in a script so I don't process those again? and/or What is wrong with the way I am doing this now? Hello, I am running tshark with the ring buffer option to dump to files after 5MB or 1 hour. I wrote a python script to read these files in XML and dump into a database, this works fine. My issue is that this is really process intensive, one of those 5MB can turn into a 200MB file when converted to XML, so I do not want to do any unnecessary processing. The script is running every 10 minutes and processes ~5 files per run, since is scanning the folder where the files are created for any new entries, I dump a hash of the file into the database and on the next run check the hash and if it isn't in the database I scan the file. The problem is that this does not appear to work every time, it ends up processing files that it has already done. When I check the hash of the file that it keeps trying to process it doesn't show up anywhere in the database, hence why is trying to process it over and over. I am printing out the filename + hash in the output of the script: using file /var/ss01/SS01_00086_20100107100828.cap with hash: 982d664b574b84d6a8a5093889454e59 using file /var/ss02/SS02_00053_20100106125828.cap with hash: 8caceb6af7328c4aed2ea349062b74e9 using file /var/ss02/SS02_00075_20100106184519.cap with hash: 1b664b2e900d56ca9750d27ed1ec28fc using file /var/ss02/SS02_00098_20100107104437.cap with hash: e0d7f5b004016febe707e9823f339fce using file /var/ss02/SS02_00095_20100105132356.cap with hash: 41a3938150ec8e2d48ae9498c79a8d0c using file /var/ss02/SS02_00097_20100107103332.cap with hash: 4e08b6926c87f5967484add22a76f220 using file /var/ss02/SS02_00090_20100105122531.cap with hash: 470b378ee5a2f4a14ca28330c2009f56 using file /var/ss03/SS03_00089_20100107104530.cap with hash: 468a01753a97a6a5dfa60418064574cc using file /var/ss03/SS03_00086_20100105122537.cap with hash: 1fb8641f10f733384de01e94926e0853 using file /var/ss03/SS03_00090_20100107105832.cap with hash: d6209e65348029c3d211d1715301b9f8 using file /var/ss03/SS03_00088_20100107103248.cap with hash: 56a26b4e84b853e1f2128c831628c65e using file /var/ss03/SS03_00072_20100105093543.cap with hash: dca18deb04b7c08e206a3b6f62262465 using file /var/ss03/SS03_00050_20100106140218.cap with hash: 36761e3f67017c626563601eaf68a133 using file /var/ss04/SS04_00010_20100105105912.cap with hash: 5188dc70616fa2971d57d4bfe029ec46 using file /var/ss04/SS04_00071_20100107094806.cap with hash: ab72eaddd9f368e01f9a57471ccead1a using file /var/ss04/SS04_00072_20100107100234.cap with hash: 79dea347b04a05753cb4ff3576883494 using file /var/ss04/SS04_00070_20100107093350.cap with hash: 535920197129176c4d7a9891c71e0243 using file /var/ss04/SS04_00067_20100107084826.cap with hash: 64a88ecc1253e67d49e3cb68febb2e25 using file /var/ss04/SS04_00042_20100106144048.cap with hash: bb9bfa773f3bf94fd3af2514395d8d9e using file /var/ss04/SS04_00007_20100105101951.cap with hash: d949e673f6138af2d388884f4a6b0f08 The only files it should be doing are one per folder, so only 4 files. This causes unecessary processing and I have to deal with overlapping cron jobs + other services been affected. What I am hoping to get from this post is a better way to do this or hopefully someone can tell me why is happening, I know that the latter might be hard since it can be a bunch of reasons. Here is the code (I am not a coder but a sys admin so be kind :P) line 30-32 handle the hash comparisons. Thanks in advance.
[ "A good way to handle/process files that are created at random times is to use\nincron rather than cron. (Note: since incron uses the Linux kernel's\ninotify syscalls, this solution only works with Linux.)\nWhereas cron runs a job based on dates and times, incron runs a job based on\nchanges in a monitored directory. For example, you can configure incron to run a\njob every time a new file is created or modified.\nOn Ubuntu, the package is called incron. I'm not sure about RedHat, but I believe this is the right package: http://rpmfind.net//linux/RPM/dag/redhat/el5/i386/incron-0.5.9-1.el5.rf.i386.html.\nOnce you install the incron package, read \nman 5 incrontab \n\nfor information on how to setup the incrontab config file. Your incron_config file might look something like this:\n/var/ss01/ IN_CLOSE_WRITE /path/to/processing/script.py $#\n/var/ss02/ IN_CLOSE_WRITE /path/to/processing/script.py $#\n/var/ss03/ IN_CLOSE_WRITE /path/to/processing/script.py $#\n/var/ss04/ IN_CLOSE_WRITE /path/to/processing/script.py $#\n\nThen to register this config with the incrond daemon, you'd run \nincrontab /path/to/incron_config\n\nThat's all there is to it. Now whenever a file is created in /var/ss01, /var/ss02, /var/ss03 or /var/ss04, the command \n/path/to/processing/script.py $#\n\nis run, with $# replaced by the name of the newly created file.\nThis will obviate the need to store/compare hashes, and files will only get processed once -- immediately after they are created.\nJust make sure your processing script does not write into the top level of the monitored directories.\nIf it does, then incrond will notice the new file created, and launch script.py again, sending you into an infinite loop.\nincrond monitors individual directories, and does not recursively monitor subdirectories. So you could direct tshark to write to /var/ss01/tobeprocessed, use incron to monitor \n/var/ss01/tobeprocessed, and have your script.py write to /var/ss01, for example.\nPS. There is also a python interface to inotify, called pyinotify. Unlike incron, pyinotify can recursively monitor subdirectories. However, in your case, I don't think the recursive monitoring feature is useful or necessary.\n", "I don't know enough about what is in these files, so this may not work for you, but if you have only one intended consumer, I would recommend using directories and moving the files to reflect their state. Specifically, you could have a dir structure like\n/waiting\n/progress\n/done\n\nand use the relative atomicity of mv to change the \"state\" of each file. (Whether mv is truly atomic depends on your filesystem, I believe.)\nWhen your processing task wants to work on a file, it moves it from waiting to progress (and makes sure that the move succeeded). That way, no other task can pick it up, since it's no longer waiting. When the file is complete, it gets moved from progress to done, where a cleanup task might delete or archive old files that are no longer needed.\n", "I see several issues.\nIf you have overlapping cron jobs you need to have a locking mechanism to control access. Only allow one process at a time to eliminate the overlap problem. You might setup a shell script to do that. Create a 'lock' by making a directory (mkdir is atomic), process the data, then delete the lock directory. If the shell script finds the directory already exists when it tries to make it then you know another copy is already running and it can just exit.\nIf you can't change the cron table(s) then just rename the executable and name your shell script the same as the old executable.\nHashes are not guaranteed to be unique identifiers for files, it's likely they are, but it's not absolutely guaranteed.\n", "Why not just move a processed file to a different directory?\nYou mentioned overlapping cron jobs. Does this mean one conversion process can start before the previous one finished? That means you would perform the move at the beginning of the conversion. If you are worries about an interrupted conversion, use an intermediate directory, and move to a final directory after completion.\n", "If I'm reading the code correctly, you're updating the database (by which I mean the log of files processed) at the very end. So when you have a huge file that's being processed and not yet complete, another cron job will 'legally' start working on it. - both completing succesfully resulting in two entries in the database.\nI suggest you move up the logging-to-database, which would act as a lock for subsequent cronjobs and having a 'success' or 'completed' at the very end. The latter part is important as something that's shown as processing but doesnt have a completed state (coupled with the notion of time) can be programtically concluded as an error. (That is to say, a cronjob tried processing it but never completed it and the log show processing for 1 week!)\nTo summarize\n\nMove up the log-to-database so that it would act as a lock\nAdd a 'success' or 'completed' state which would give the notion of errored state\n\nPS: Dont take it in the wrong way, but the code is a little hard to understand. I am not sure whether I do at all.\n" ]
[ 6, 3, 0, 0, 0 ]
[]
[]
[ "file_io", "hash", "mysql", "python", "sysadmin" ]
stackoverflow_0002022775_file_io_hash_mysql_python_sysadmin.txt
Q: dumb question alert: use *both* ruby on rails and python possible? the front end and end-user data-collection we want to build in RoR since it's just some simple forms connected to a database. The integration with other external api's such as twitter and facebook and parsing of the data entered by the users we want to do in python, mostly because the developer for that part knows python. Is that possible? A: It sounds like the only place the two parts will interact is the database: the RoR parts collect data from the user, the python parts collect data from Twitter and elsewhere. As long as your database is supported by both languages, there's no a priori reason why this wouldn't work. Even if you end up needing the two parts to interact more directly, there are plenty of ways of providing an API in one part of the app that the other parts of the app can use regardless of what language they're written in - for instance, it should be easy to have the RoR parts provide a nice RESTful API, and have the python parts interact through that. If you're going to have different parts of the app developed by different teams, they're going to need a strong interface contract in order to make their parts work together anyway; having that contract be in the form of a RESTful API just makes the parts even more modular and gives you more freedom in the future. A: Yes, it is possible at some degree using Java. You may use JRuby and Jython in the same app. A: If you're parsing data with python, presumably it's going be put into a database. As long as this is the case you can just run two apps standalone. Saying that, using one language and framework is a better solution, especially when you think that you won't be able reuse any code between the two applications if they are written in two different languages. Also I know Ruby has good libraries to do all of what is mentioned in your post, as I'm sure Python also does, so there seems little advantage in using the two together.
dumb question alert: use *both* ruby on rails and python possible?
the front end and end-user data-collection we want to build in RoR since it's just some simple forms connected to a database. The integration with other external api's such as twitter and facebook and parsing of the data entered by the users we want to do in python, mostly because the developer for that part knows python. Is that possible?
[ "It sounds like the only place the two parts will interact is the database: the RoR parts collect data from the user, the python parts collect data from Twitter and elsewhere.\nAs long as your database is supported by both languages, there's no a priori reason why this wouldn't work.\nEven if you end up needing the two parts to interact more directly, there are plenty of ways of providing an API in one part of the app that the other parts of the app can use regardless of what language they're written in - for instance, it should be easy to have the RoR parts provide a nice RESTful API, and have the python parts interact through that. \nIf you're going to have different parts of the app developed by different teams, they're going to need a strong interface contract in order to make their parts work together anyway; having that contract be in the form of a RESTful API just makes the parts even more modular and gives you more freedom in the future.\n", "Yes, it is possible at some degree using Java. You may use JRuby and Jython in the same app.\n", "If you're parsing data with python, presumably it's going be put into a database. As long as this is the case you can just run two apps standalone. Saying that, using one language and framework is a better solution, especially when you think that you won't be able reuse any code between the two applications if they are written in two different languages.\nAlso I know Ruby has good libraries to do all of what is mentioned in your post, as I'm sure Python also does, so there seems little advantage in using the two together.\n" ]
[ 3, 0, 0 ]
[]
[]
[ "python", "ruby", "ruby_on_rails" ]
stackoverflow_0002023458_python_ruby_ruby_on_rails.txt
Q: Django 1.1.1: How should I store an empty IP address using PostgreSQL? I am writing a Django application that stores IP addresses with optional routing information. One of the fields for the IP model I have created is nexthop (for next-hop routes), which will usually be empty. Originally we intended to use MySQL, but now project requirements have changed to use PostgreSQL. Here is a stripped down version of my model: class IP(models.Model): address = models.IPAddressField() netmask = models.IPAddressField(default='255.255.255.255') nexthop = models.IPAddressField(null=True, blank=True, default=None) active = models.BooleanField('is active?', default=1) So, with MySQL I did not have a problem leaving the nexthop field empty. However, now that I switched the development environment to Postgres, we've run into a known issue in Django 1.1.1 in which a blank IP address raises a DataError invalid input syntax for type inet: "" LINE 1: ...-14 13:07:29', 1, E'1.2.3.4', E'255.255.255.255', E'', true) ^ As you can see, it bombs because it is trying to insert an empty string when the column will only accept a NULL. I have a very real need to be able to keep this field empty, because if an IP doesn't have a next-hop, then its behavior changes. Short of hacking the Django code manually, which is my ultimate last resort, I have also thought of defaulting next-hop to 255.255.255.255 and wrapping some business logic around that (i.e. If next-hop is 255.255.255.255, treat as normal route), but that just feels like a hack. I would like to know if there are any suggestions on a better way to do this that would not require hacking Django or writing hacky logic, or if there is a completely different approach altogether that can satisfy my requirement. Thanks in advance! Edit: Interim Solution For the time-being (as an interstitial fix) I decided to go with the sentinel value for the next-hop: In the model: IP_NEXTHOP_SENTINEL = '255.255.255.255' class IP(models.Model): nexthop = models.IPAddressField( null=True, blank=True, default=IP_NEXTHOP_SENTINEL, help_text='Use %s to indicate no next-hop' % IP_NEXTHOP_SENTINEL ) def save(self, *args, **kwargs): ## hack for Django #5622 (http://code.djangoproject.com/ticket/5622) if self.nexthop and self.nexthop == IP_NEXTHOP_SENTINEL: self.nexthop = None Overview: Creation of IP objects outside of the admin portal works as intended, which is why I kept the null=True argument on the nexthop field. The only place where 255.255.255.255 would ever be set as the next-hop would be through the admin portal, so I decided that overloading save() to always replace the sentinel with None would give me the final result I desire and it doesn't really feel too much like a hack. Thanks for your input on this! A: If you can convince the devs to accept one of the patches, I'd say just run a patched copy of Django until the patched version lands. If not, then it might be less headache to just use a sentinel value, as you suggested, even though it is a hack. You might also just use a regular CharField instead of an IPAddressField, but then you get stuck having to maintain validation logic on your own. A: Have you tried just using blank=True for nexthop, rather than both blank=True and null=True? As noted in the Django docs: Only use null=True for non-string fields such as integers, booleans and dates. A: And what about using empty string as sentinel, instead of 255.255.255.255 ? As admin back-end stores empty field as empty string (when blank=true), this solution has the advantage to be transparent for the user and doesn't force him to use a faked value...
Django 1.1.1: How should I store an empty IP address using PostgreSQL?
I am writing a Django application that stores IP addresses with optional routing information. One of the fields for the IP model I have created is nexthop (for next-hop routes), which will usually be empty. Originally we intended to use MySQL, but now project requirements have changed to use PostgreSQL. Here is a stripped down version of my model: class IP(models.Model): address = models.IPAddressField() netmask = models.IPAddressField(default='255.255.255.255') nexthop = models.IPAddressField(null=True, blank=True, default=None) active = models.BooleanField('is active?', default=1) So, with MySQL I did not have a problem leaving the nexthop field empty. However, now that I switched the development environment to Postgres, we've run into a known issue in Django 1.1.1 in which a blank IP address raises a DataError invalid input syntax for type inet: "" LINE 1: ...-14 13:07:29', 1, E'1.2.3.4', E'255.255.255.255', E'', true) ^ As you can see, it bombs because it is trying to insert an empty string when the column will only accept a NULL. I have a very real need to be able to keep this field empty, because if an IP doesn't have a next-hop, then its behavior changes. Short of hacking the Django code manually, which is my ultimate last resort, I have also thought of defaulting next-hop to 255.255.255.255 and wrapping some business logic around that (i.e. If next-hop is 255.255.255.255, treat as normal route), but that just feels like a hack. I would like to know if there are any suggestions on a better way to do this that would not require hacking Django or writing hacky logic, or if there is a completely different approach altogether that can satisfy my requirement. Thanks in advance! Edit: Interim Solution For the time-being (as an interstitial fix) I decided to go with the sentinel value for the next-hop: In the model: IP_NEXTHOP_SENTINEL = '255.255.255.255' class IP(models.Model): nexthop = models.IPAddressField( null=True, blank=True, default=IP_NEXTHOP_SENTINEL, help_text='Use %s to indicate no next-hop' % IP_NEXTHOP_SENTINEL ) def save(self, *args, **kwargs): ## hack for Django #5622 (http://code.djangoproject.com/ticket/5622) if self.nexthop and self.nexthop == IP_NEXTHOP_SENTINEL: self.nexthop = None Overview: Creation of IP objects outside of the admin portal works as intended, which is why I kept the null=True argument on the nexthop field. The only place where 255.255.255.255 would ever be set as the next-hop would be through the admin portal, so I decided that overloading save() to always replace the sentinel with None would give me the final result I desire and it doesn't really feel too much like a hack. Thanks for your input on this!
[ "If you can convince the devs to accept one of the patches, I'd say just run a patched copy of Django until the patched version lands. If not, then it might be less headache to just use a sentinel value, as you suggested, even though it is a hack. You might also just use a regular CharField instead of an IPAddressField, but then you get stuck having to maintain validation logic on your own.\n", "Have you tried just using blank=True for nexthop, rather than both blank=True and null=True? As noted in the Django docs:\n\nOnly use null=True for non-string fields such as integers, booleans and dates.\n\n", "And what about using empty string as sentinel, instead of 255.255.255.255 ?\nAs admin back-end stores empty field as empty string (when blank=true), this solution has the advantage to be transparent for the user and doesn't force him to use a faked value...\n" ]
[ 2, 1, 0 ]
[]
[]
[ "django", "postgresql", "python" ]
stackoverflow_0001862123_django_postgresql_python.txt
Q: Delayed execution in python for big data I'm trying to think about how a Python API might look for large datastores like Cassandra. R, Matlab, and NumPy tend to use the "everything is a matrix" formulation and execute each operation separately. This model has proven itself effective for data that can fit in memory. However, one of the benefits of SAS for big data is that it executes row by row, doing all the row calculations before moving to the next. For a datastore like Cassandra, this model seems like a huge win -- we only loop through data once. In Python, SAS's approach might look something like: with load('datastore') as data: for row in rows(data): row.logincome = row.log(income) row.rich = "Rich" if row.income > 100000 else "Poor" This is (too?) explicit but has the advantage of only looping once. For smaller datasets, performance will be very poor compared to NumPy because the functions aren't vectorized using compiled code. In R/Numpy we would have the much more concise and compiled: data.logincome = log(data.income) data.rich = ifelse(data.income > 100000, "Rich", Poor") This will execute extremely quickly because log and ifelse are both compiled functions that operator on vectors. A downside, however, is that we will loop twice. For small datasets this doesn't matter, but for a Cassandra backed datastore, I don't see how this approach works. Question: Is there a way to keep the second API (like R/Numpy/Matlab) but delay computation. Perhaps by calling a sync(data) function at the end? Alternative ideas? It would be nice to maintain the NumPy type syntax since users will be using NumPy for smaller operations and will have an intuitive grasp of how that works. A: I don't know anything about Cassandra/NumPy, but if you adapt your second approach (using NumPy) to process data in chunks of a reasonable size, you might benefit from the CPU and/or filesystem cache and therefore prevent any slowdown caused by looping over the data twice, without giving up the benefit of using optimized processing functions. A: I don't have a perfect answer, just a rough idea, but maybe it is worthwhile. It centers around Python generators, in sort of a producer-consumer style combination. For one, as you don't want to loop twice, I think there is no way around an explicit loop for the rows, like this: for row in rows(data): # do stuff with row Now, feed the row to (an arbitrary number of) consumers that are - don't choke - generators again. But you would be using the send method of the generator. As an example for such a consumer, here is a sketch of riches: def riches(): rich_data = [] while True: row = (yield) if row == None: break rich_data.append("Rich" if row.income > 100000 else "Poor") yield rich_data The first yield (expression) is just to fuel the individual rows into riches. It does its thing, here building up a result array. After the while loop, the second yield (statement) is used to actually provide the result data to the caller. Going back to the caller loop, it could look someting like this: richConsumer = riches() richConsumer.next() # advance to first yield for row in rows(data): richConsumer.send(row) # other consumers.send(row) here richConsumer.send(None) # make consumer exit its inner loop data.rich = richConsumer.next() # collect result data I haven't tested that code, but that's how I think about it. It doesn't have the nice compact syntax of the vector-based functions. But it makes the main loop very simple and encapsulates all processing in separate consumers. Additional consumers can be nicely stacked after each other. And the API could be further polished by pushing generator managing code behind e.g. object boundaries. HTH
Delayed execution in python for big data
I'm trying to think about how a Python API might look for large datastores like Cassandra. R, Matlab, and NumPy tend to use the "everything is a matrix" formulation and execute each operation separately. This model has proven itself effective for data that can fit in memory. However, one of the benefits of SAS for big data is that it executes row by row, doing all the row calculations before moving to the next. For a datastore like Cassandra, this model seems like a huge win -- we only loop through data once. In Python, SAS's approach might look something like: with load('datastore') as data: for row in rows(data): row.logincome = row.log(income) row.rich = "Rich" if row.income > 100000 else "Poor" This is (too?) explicit but has the advantage of only looping once. For smaller datasets, performance will be very poor compared to NumPy because the functions aren't vectorized using compiled code. In R/Numpy we would have the much more concise and compiled: data.logincome = log(data.income) data.rich = ifelse(data.income > 100000, "Rich", Poor") This will execute extremely quickly because log and ifelse are both compiled functions that operator on vectors. A downside, however, is that we will loop twice. For small datasets this doesn't matter, but for a Cassandra backed datastore, I don't see how this approach works. Question: Is there a way to keep the second API (like R/Numpy/Matlab) but delay computation. Perhaps by calling a sync(data) function at the end? Alternative ideas? It would be nice to maintain the NumPy type syntax since users will be using NumPy for smaller operations and will have an intuitive grasp of how that works.
[ "I don't know anything about Cassandra/NumPy, but if you adapt your second approach (using NumPy) to process data in chunks of a reasonable size, you might benefit from the CPU and/or filesystem cache and therefore prevent any slowdown caused by looping over the data twice, without giving up the benefit of using optimized processing functions.\n", "I don't have a perfect answer, just a rough idea, but maybe it is worthwhile. It centers around Python generators, in sort of a producer-consumer style combination.\nFor one, as you don't want to loop twice, I think there is no way around an explicit loop for the rows, like this:\nfor row in rows(data):\n # do stuff with row\n\nNow, feed the row to (an arbitrary number of) consumers that are - don't choke - generators again. But you would be using the send method of the generator. As an example for such a consumer, here is a sketch of riches:\ndef riches():\n rich_data = []\n while True:\n row = (yield)\n if row == None: break\n rich_data.append(\"Rich\" if row.income > 100000 else \"Poor\")\n yield rich_data\n\nThe first yield (expression) is just to fuel the individual rows into riches. It does its thing, here building up a result array. After the while loop, the second yield (statement) is used to actually provide the result data to the caller.\nGoing back to the caller loop, it could look someting like this:\nrichConsumer = riches()\nrichConsumer.next() # advance to first yield\nfor row in rows(data):\n richConsumer.send(row)\n # other consumers.send(row) here\nrichConsumer.send(None) # make consumer exit its inner loop\ndata.rich = richConsumer.next() # collect result data\n\nI haven't tested that code, but that's how I think about it. It doesn't have the nice compact syntax of the vector-based functions. But it makes the main loop very simple and encapsulates all processing in separate consumers. Additional consumers can be nicely stacked after each other. And the API could be further polished by pushing generator managing code behind e.g. object boundaries. HTH\n" ]
[ 2, 1 ]
[]
[]
[ "cassandra", "python" ]
stackoverflow_0002009708_cassandra_python.txt
Q: 2-dimensional interpolation I want to find a value of z at y = 12 and x = 3.5, given the below example data. How can I do this in C++? y = 10 x = [1,2, 3,4, 5,6] z = [2.3, 3.4, 5.6, 7.8, 9.6, 11.2] y = 20 x = [1,2, 3,4, 5,6] z = [4.3, 5.4, 7.6, 9.8, 11.6, 13.2] y = 30 x = [1,2, 3,4, 5,6] z = [6.3, 7.4, 8.6, 10.8, 13.6, 15.2] My current Python code: import scipy import math import numpy from scipy import interpolate x = [1, 2, 3, 4, 5, 6] y = [10, 20, 30] Y = numpy.array([[i]*len(x) for i in y]) X = numpy.array([x for i in y]) Z = numpy.array([[2.3, 3.4, 5.6, 7.8, 9.6, 11.2], [4.3, 5.4, 7.6, 9.8, 11.6, 13.2], [6.3, 7.4, 8.6, 10.8, 13.6, 15.2]]) tck = interpolate.bisplrep(X, Y, Z) print interpolate.bisplev(3.5, 15, tck) A: Just do the interpolation twice. First interpolate with Y to select the two Z tables. Then interpolate with X to pick the Z value. A: I would use Akima's Spline, which is very well-tested, very fast, and produces extremely good results. Unfortunately, it's in Fortran-66 (and messy at that), so you'll need to either translate it to C or a more modern variant of Fortran. I've gotten some help in getting it all to work, so I'd suggest reading through my threads on Usenet.
2-dimensional interpolation
I want to find a value of z at y = 12 and x = 3.5, given the below example data. How can I do this in C++? y = 10 x = [1,2, 3,4, 5,6] z = [2.3, 3.4, 5.6, 7.8, 9.6, 11.2] y = 20 x = [1,2, 3,4, 5,6] z = [4.3, 5.4, 7.6, 9.8, 11.6, 13.2] y = 30 x = [1,2, 3,4, 5,6] z = [6.3, 7.4, 8.6, 10.8, 13.6, 15.2] My current Python code: import scipy import math import numpy from scipy import interpolate x = [1, 2, 3, 4, 5, 6] y = [10, 20, 30] Y = numpy.array([[i]*len(x) for i in y]) X = numpy.array([x for i in y]) Z = numpy.array([[2.3, 3.4, 5.6, 7.8, 9.6, 11.2], [4.3, 5.4, 7.6, 9.8, 11.6, 13.2], [6.3, 7.4, 8.6, 10.8, 13.6, 15.2]]) tck = interpolate.bisplrep(X, Y, Z) print interpolate.bisplev(3.5, 15, tck)
[ "Just do the interpolation twice. First interpolate with Y to select the two Z tables. Then interpolate with X to pick the Z value.\n", "I would use Akima's Spline, which is very well-tested, very fast, and produces extremely good results.\nUnfortunately, it's in Fortran-66 (and messy at that), so you'll need to either translate it to C or a more modern variant of Fortran. I've gotten some help in getting it all to work, so I'd suggest reading through my threads on Usenet.\n" ]
[ 1, 1 ]
[]
[]
[ "c++", "math", "python" ]
stackoverflow_0002024274_c++_math_python.txt
Q: Python - automating MySQL query: passing parameter The code in the sequence is working fine, but looking to improve the MySQL code to a more efficient format. The first case is about a function that received a parameter and returns the customerID from MySQL db: def clean_table(self,customerName): getCustomerIDMySQL="""SELECT customerID FROM customer WHERE customerName = %s;""" self.cursorMySQL.execute(getCustomerIDMySQL,(customerName)) for getID_row in self.cursorMySQL: customerID=getID_row[0] return customerID In the case we know before hand that the result will be just one output, how to get the same thing into my getID_row, without using "for" statement? For the second case, the function is running with the table name ('customer') on it... def clean_tableCustomer(self): cleanTableQuery = """TRUNCATE TABLE customer;""" self.cursorMySQL.execute(cleanTableQuery) setIndexQuery = """ALTER TABLE customer AUTO_INCREMENT = 1;""" self.cursorMySQL.execute(setIndexQuery) then, how to replace the table name as a parameter passed through the function? Here is how I tried to get this done: def clean_table(self,tableName): cleanTableQuery = """TRUNCATE TABLE %s;""" self.cursorMySQL.execute(cleanTableQuery,(tableName)) setIndexQuery = """ALTER TABLE %s AUTO_INCREMENT = 1;""" self.cursorMySQL.execute(setIndexQuery,(tableName)) But MySQL didn't work this time. All comments and suggestions are highly appreciated. A: For the first case (simple, but easy to get a KeyError when there is no row): customerID = self.cursorMySQL.fetchone()[0] More correct is to implement a new method for the cursor class: def autofetch_value(self, sql, args=None): """ return a single value from a single row or None if there is no row """ self.execute(sql, args) returned_val = None row = self.fetchone() if row is not None: returned_val = row[0] return returned_val For the second case: def clean_table(self,tableName): cleanTableQuery = """TRUNCATE TABLE %s;""" % (tableName,) self.cursorMySQL.execute(cleanTableQuery) setIndexQuery = """ALTER TABLE %s AUTO_INCREMENT = 1;""" % (tableName,) self.cursorMySQL.execute(setIndexQuery) Make sure you sanitize the data, since the cursor won't. A: Unfortunately, you cannot parametrize the name of a table (see this post). You will have to use Python string operations to do what you are attempting here. Hope this helps, it took me a while to find out when I ran into this issue.
Python - automating MySQL query: passing parameter
The code in the sequence is working fine, but looking to improve the MySQL code to a more efficient format. The first case is about a function that received a parameter and returns the customerID from MySQL db: def clean_table(self,customerName): getCustomerIDMySQL="""SELECT customerID FROM customer WHERE customerName = %s;""" self.cursorMySQL.execute(getCustomerIDMySQL,(customerName)) for getID_row in self.cursorMySQL: customerID=getID_row[0] return customerID In the case we know before hand that the result will be just one output, how to get the same thing into my getID_row, without using "for" statement? For the second case, the function is running with the table name ('customer') on it... def clean_tableCustomer(self): cleanTableQuery = """TRUNCATE TABLE customer;""" self.cursorMySQL.execute(cleanTableQuery) setIndexQuery = """ALTER TABLE customer AUTO_INCREMENT = 1;""" self.cursorMySQL.execute(setIndexQuery) then, how to replace the table name as a parameter passed through the function? Here is how I tried to get this done: def clean_table(self,tableName): cleanTableQuery = """TRUNCATE TABLE %s;""" self.cursorMySQL.execute(cleanTableQuery,(tableName)) setIndexQuery = """ALTER TABLE %s AUTO_INCREMENT = 1;""" self.cursorMySQL.execute(setIndexQuery,(tableName)) But MySQL didn't work this time. All comments and suggestions are highly appreciated.
[ "For the first case (simple, but easy to get a KeyError when there is no row):\ncustomerID = self.cursorMySQL.fetchone()[0]\n\nMore correct is to implement a new method for the cursor class:\ndef autofetch_value(self, sql, args=None):\n \"\"\" return a single value from a single row or None if there is no row\n \"\"\"\n self.execute(sql, args)\n returned_val = None\n\n row = self.fetchone()\n if row is not None:\n returned_val = row[0]\n\n return returned_val\n\nFor the second case:\ndef clean_table(self,tableName):\n cleanTableQuery = \"\"\"TRUNCATE TABLE %s;\"\"\" % (tableName,)\n self.cursorMySQL.execute(cleanTableQuery)\n\n setIndexQuery = \"\"\"ALTER TABLE %s AUTO_INCREMENT = 1;\"\"\" % (tableName,)\n self.cursorMySQL.execute(setIndexQuery)\n\nMake sure you sanitize the data, since the cursor won't.\n", "Unfortunately, you cannot parametrize the name of a table (see this post). You will have to use Python string operations to do what you are attempting here.\nHope this helps, it took me a while to find out when I ran into this issue.\n" ]
[ 3, 0 ]
[]
[]
[ "automation", "mysql", "parameters", "python" ]
stackoverflow_0002024535_automation_mysql_parameters_python.txt
Q: Using 'super' when subclassing python class that is not derived from `object`(old-style?) I'm playing with subclassing OptionParser from the std library module optparser. (Python 2.5.2) When I attempt it I get the exception: TypeError: super() argument 1 must be type, not classobj Looking at OptionParser, it is not derived from object. So I added object as a parent class, (shown below) and super works properly. from optparse import OptionParser, Option class MyOptionParser(OptionParser, object): """Class to change """ def __init__(self, usage=None, option_list=None, option_class=Option, version=None, conflict_handler="error", description=None, formatter=None, add_help_option=True, prog=None, epilog=None, ): super(MyOptionParser, self).__init__(usage, option_list, option_class, version, conflict_handler, description, formatter, add_help_option, prog, epilog) if __name__ == '__main__': """Run a quick test """ parser = MyOptionParser() parser.add_option("-t", "--test", type="string", dest="test") (options, args) = parser.parse_args() print "The test option is: %s" % options.test Is this the correct way to go about it? A: Yes I dont see why it would not work. You just need to add couple of spaces right before that super call - as it's written right now, it is not part of your custom init method. Also, a shortcut you might want to use is **kwargs - you can do kwargs key check in your method if thats what you desire to do: class MyOptionParser(OptionParser, object): """Class to change """ def __init__(self, **kwargs): # You can limit kwargs keys here super(MyOptionParser, self).__init__(**kwargs)
Using 'super' when subclassing python class that is not derived from `object`(old-style?)
I'm playing with subclassing OptionParser from the std library module optparser. (Python 2.5.2) When I attempt it I get the exception: TypeError: super() argument 1 must be type, not classobj Looking at OptionParser, it is not derived from object. So I added object as a parent class, (shown below) and super works properly. from optparse import OptionParser, Option class MyOptionParser(OptionParser, object): """Class to change """ def __init__(self, usage=None, option_list=None, option_class=Option, version=None, conflict_handler="error", description=None, formatter=None, add_help_option=True, prog=None, epilog=None, ): super(MyOptionParser, self).__init__(usage, option_list, option_class, version, conflict_handler, description, formatter, add_help_option, prog, epilog) if __name__ == '__main__': """Run a quick test """ parser = MyOptionParser() parser.add_option("-t", "--test", type="string", dest="test") (options, args) = parser.parse_args() print "The test option is: %s" % options.test Is this the correct way to go about it?
[ "Yes I dont see why it would not work. You just need to add couple of spaces right before that super call - as it's written right now, it is not part of your custom init method. Also, a shortcut you might want to use is **kwargs - you can do kwargs key check in your method if thats what you desire to do:\nclass MyOptionParser(OptionParser, object):\n \"\"\"Class to change \n \"\"\"\n def __init__(self, **kwargs):\n # You can limit kwargs keys here\n super(MyOptionParser, self).__init__(**kwargs)\n\n" ]
[ 5 ]
[]
[]
[ "python" ]
stackoverflow_0002023940_python.txt
Q: What is the Python equivalent of PHP's set_time_limit()? I have a python script which is freezing (I think it stalls waiting for socket data somewhere), but I am having trouble getting a backtrace because the only way to stop it is to kill the process in. There is a timeout on the socket also, but it doesn't seem to work. I am hoping that Python has a feature like PHP's set_time_limit() function which can stop the script and give me a useful backtrace, perhaps showing a sock.recv() call which is frozen, or an endless loop somewhere. A: signal.alarm can help (on Unix platforms), but (depending on the platform) there may be uninterruptable system calls (and if I get the docs right, on Unix, PHP's set_time_limit does not count time spent in system calls, so a hanging system call would be a problem there too). A: You could set a timeout on your sockets instead. import socket socket.setdefaulttimeout(10) #10 seconds Do that at the start of your program and everything making socket connections should respect it.
What is the Python equivalent of PHP's set_time_limit()?
I have a python script which is freezing (I think it stalls waiting for socket data somewhere), but I am having trouble getting a backtrace because the only way to stop it is to kill the process in. There is a timeout on the socket also, but it doesn't seem to work. I am hoping that Python has a feature like PHP's set_time_limit() function which can stop the script and give me a useful backtrace, perhaps showing a sock.recv() call which is frozen, or an endless loop somewhere.
[ "signal.alarm can help (on Unix platforms), but (depending on the platform) there may be uninterruptable system calls (and if I get the docs right, on Unix, PHP's set_time_limit does not count time spent in system calls, so a hanging system call would be a problem there too).\n", "You could set a timeout on your sockets instead.\nimport socket\nsocket.setdefaulttimeout(10) #10 seconds\n\nDo that at the start of your program and everything making socket connections should respect it.\n" ]
[ 3, 1 ]
[]
[]
[ "php", "python" ]
stackoverflow_0002024644_php_python.txt
Q: setuptools "at least one of these" dependency specification In some cases, there are various modules which each implement a common API (in my case, the old pure-python elementtree, cElementTree, lxml.etree, and the built-in xml.etree). I can write the module using ElementTree to try each of these options, and take the first one that exists according to my own preference order -- but I can't find any information on specifying that only one of these must be installed in setup.py. I want to write something that looks like this: setup( ..., install_requires=""" elementtree | cElementTree | lxml """, ... ) Is this, or something like it, possible? A: I don't think so, but, if you're using a reasonably recent Python, elementtree being part of the standard Python libraries, why do you worry it might be absent? (I do understand this would be a problem for other cases of several possible implementations of an API, I just wonder if you really need it for your specific use case). A: You might want to try doing something like this in setup.py: install_requires = ["elementree"] try: import cElementTree install_requires = [] except ImportError: try: import lxml install_requires = [] except ImportError: # etc for remaining equivalent modules setup( install_requires = install_requires, # rest of setup parameters ) This will basically install elementree package as dependency if none of the equivalent are installed.
setuptools "at least one of these" dependency specification
In some cases, there are various modules which each implement a common API (in my case, the old pure-python elementtree, cElementTree, lxml.etree, and the built-in xml.etree). I can write the module using ElementTree to try each of these options, and take the first one that exists according to my own preference order -- but I can't find any information on specifying that only one of these must be installed in setup.py. I want to write something that looks like this: setup( ..., install_requires=""" elementtree | cElementTree | lxml """, ... ) Is this, or something like it, possible?
[ "I don't think so, but, if you're using a reasonably recent Python, elementtree being part of the standard Python libraries, why do you worry it might be absent? (I do understand this would be a problem for other cases of several possible implementations of an API, I just wonder if you really need it for your specific use case).\n", "You might want to try doing something like this in setup.py:\ninstall_requires = [\"elementree\"]\n\ntry:\n import cElementTree\n install_requires = []\nexcept ImportError:\n try:\n import lxml\n install_requires = []\n except ImportError:\n # etc for remaining equivalent modules\n\nsetup(\n install_requires = install_requires,\n # rest of setup parameters\n)\n\nThis will basically install elementree package as dependency if none of the equivalent are installed.\n" ]
[ 0, 0 ]
[]
[]
[ "dependencies", "python", "setuptools" ]
stackoverflow_0002023900_dependencies_python_setuptools.txt
Q: kwargs sent over pyAMF channel I'm using cherrypy server to receive requests over a pyAMF channel from a python client. I started with the mock up below and it works fine: Server: import cherrypy from pyamf.remoting.gateway.wsgi import WSGIGateway def echo(*args, **kwargs): return (args, kwargs) class Root(object): def index(self): return "running" index.exposed = True services = { 'myService.echo': echo, } gateway = WSGIGateway(services, debug=True) cherrypy.tree.graft(gateway, "/gateway/") cherrypy.quickstart(Root()) Client: from pyamf.remoting.client import RemotingService path = 'http://localhost:8080/gateway/' gw = RemotingService(path) service = gw.getService('myService') print service.echo('one=1, two=3') Result: [[u'one=1, two=3'], {}] now if instead of: def echo(*args, **kwargs): return (args, kwargs) I use: def echo(**kwargs): return kwargs and send the same request, I get the following error: TypeError: echo() takes exactly 0 arguments (1 given) while at the same time: >>> def f(**kwargs): return kwargs ... >>> f(one=1, two=3) {'two': 3, 'one': 1} >>> Question: Why is this happening? Please share insights I'm using: python 2.5.2, cherrypy 3.1.2, pyamf 0.5.1 A: Notice that with your first echo function, the only way to get the results you do is when it is called this way: echo(u"one=1, two=3") # in words: one unicode string literal, as a positional arg # *very* different from: echo(one=1, two=3) # which seems to be what you expect Because of this, you must write echo to accept positional arguments or change how it is called. A: By default, WSGIGateway sets expose_request=True which means that the WSGI environ dict is set as the first argument to any service method in that gateway. This means that echo should be written as: def echo(environ, *args): return args PyAMF provides a decorator which allows you to forcibly expose the request even if expose_request=False, an example: from pyamf.remoting.gateway import expose_request from pyamf.remoting.gateway.wsgi import WSGIGateway @expose_request def some_service_method(request, *args): return ['some', 'thing'] services = { 'a_service_method': some_service_method } gw = WSGIGateway(services, expose_request=False) Hope that clarifies why you are getting the TypeError in this case. You correctly point out that you cannot supply **kwargs directly in a PyAMF client/server call but you can use default named parameters: def update(obj, force=False): pass Then you can access the service: from pyamf.remoting.client import RemotingService path = 'http://localhost:8080/gateway/' gw = RemotingService(path) service = gw.getService('myService') print service.update('foo', True)
kwargs sent over pyAMF channel
I'm using cherrypy server to receive requests over a pyAMF channel from a python client. I started with the mock up below and it works fine: Server: import cherrypy from pyamf.remoting.gateway.wsgi import WSGIGateway def echo(*args, **kwargs): return (args, kwargs) class Root(object): def index(self): return "running" index.exposed = True services = { 'myService.echo': echo, } gateway = WSGIGateway(services, debug=True) cherrypy.tree.graft(gateway, "/gateway/") cherrypy.quickstart(Root()) Client: from pyamf.remoting.client import RemotingService path = 'http://localhost:8080/gateway/' gw = RemotingService(path) service = gw.getService('myService') print service.echo('one=1, two=3') Result: [[u'one=1, two=3'], {}] now if instead of: def echo(*args, **kwargs): return (args, kwargs) I use: def echo(**kwargs): return kwargs and send the same request, I get the following error: TypeError: echo() takes exactly 0 arguments (1 given) while at the same time: >>> def f(**kwargs): return kwargs ... >>> f(one=1, two=3) {'two': 3, 'one': 1} >>> Question: Why is this happening? Please share insights I'm using: python 2.5.2, cherrypy 3.1.2, pyamf 0.5.1
[ "Notice that with your first echo function, the only way to get the results you do is when it is called this way:\necho(u\"one=1, two=3\")\n# in words: one unicode string literal, as a positional arg\n\n# *very* different from:\necho(one=1, two=3) # which seems to be what you expect\n\nBecause of this, you must write echo to accept positional arguments or change how it is called.\n", "By default, WSGIGateway sets expose_request=True which means that the WSGI environ dict is set as the first argument to any service method in that gateway.\nThis means that echo should be written as:\ndef echo(environ, *args):\n return args\n\nPyAMF provides a decorator which allows you to forcibly expose the request even if expose_request=False, an example:\nfrom pyamf.remoting.gateway import expose_request\nfrom pyamf.remoting.gateway.wsgi import WSGIGateway\n\n@expose_request\ndef some_service_method(request, *args):\n return ['some', 'thing']\n\nservices = {\n 'a_service_method': some_service_method\n}\n\ngw = WSGIGateway(services, expose_request=False)\n\nHope that clarifies why you are getting the TypeError in this case.\nYou correctly point out that you cannot supply **kwargs directly in a PyAMF client/server call but you can use default named parameters:\ndef update(obj, force=False):\n pass\n\nThen you can access the service:\nfrom pyamf.remoting.client import RemotingService\n\npath = 'http://localhost:8080/gateway/'\ngw = RemotingService(path)\nservice = gw.getService('myService')\n\nprint service.update('foo', True)\n\n" ]
[ 2, 1 ]
[]
[]
[ "cherrypy", "pyamf", "python", "syntax" ]
stackoverflow_0002024024_cherrypy_pyamf_python_syntax.txt
Q: What is the relationship between 'unicode' and 'encode' print u'\xe4\xf6\xfc'.encode('utf-8') print unicode(u'\xe4\xf6\xfc') traceback: 盲枚眉 Traceback (most recent call last): File "D:\zjm_code\a.py", line 6, in <module> print unicode(u'\xe4\xf6\xfc') UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128) python shell >>>u"äöü".encode('utf-8') Unsupported characters in input A: In Python 2: case a: (unicode object).encode(somecodec) -> string of bytes case b: (string of bytes).decode(somecodec) -> unicode object case c: unicode(string of bytes, somecodec) -> unicode object Cases b and c are identical. In each of the three cases, you can omit the codec name: then it defaults to 'ascii', the ASCII decoder (supporting only the 128 ASCII characters -- you'll get an exception otherwise). Whenever a 'string of bytes' is required on the left of the arrow, you can pass a unicode object (it's converted with the 'ascii' codec). Whenever a 'unicode' is required on the left of the arrow, you can pass a string of bytes (it's converted with the 'ascii' codec). A: The encoding error: print unicode(u'\xe4\xf6\xfc') The unicode() call does nothing here, since it's parameter is already a unicode object. print then tries to output that unicode object, and to do so print wants to convert it to a string in the encoding of your terminal. But python doesn't seems to know which encoding your terminal uses and therefore goes with the "safe" alternative of Ascii. Since u'\xe4\xf6\xfc' cannot be represented in Ascii this leads to an encoding error. Unicode, encode and decode: Generally encode() converts a unicode object to a string with a certain character encoding like UTF-8 or ISO-8859-1. Every unicode code point is converted to a sequence of bytes in that encoding: >>> u'\xe4\xf6\xfc'.encode('utf-8') '\xc3\xa4\xc3\xb6\xc3\xbc' The opposite is decode(), it converts a string in a certain encoding to a unicode object containing the corresponding unicode codepoints. >>> '\xc3\xa4\xc3\xb6\xc3\xbc'.decode('utf-8') u'\xe4\xf6\xfc' Printing: print with a string parameter just prints the raw bytes of that string. If that results in the desired output depends on the character encoding of the terminal. >>> print '\xc3\xa4\xc3\xb6\xc3\xbc' # utf-8 encoding on utf-8 terminal äöü >>> print '\xe4\xf6\xfc' # same encoded as latin-1 ��� When given a unicode parameter, print first tries to encode the unicode object in the terminals encoding. This only works if python guesses the right encoding for the terminal and that encoding can actually represent all the characters of the unicode object. Otherwise the encoding throws exceptions or the output contains wrong characters. >>> print u'\xe4\xf6\xfc' # it correctly assumes a utf-8 terminal äöü A: This is covered in the tutorial and the unicode howto The unicode function converts non-unicode (by default, ascii, but it accepts other encodings too) strings into unicode. Your error here is that you're passing a string that is already unicode and asking it to be converted to unicode... The encode function on a unicode string converts it back to a non-unicode encoding - again, ascii is the default.
What is the relationship between 'unicode' and 'encode'
print u'\xe4\xf6\xfc'.encode('utf-8') print unicode(u'\xe4\xf6\xfc') traceback: 盲枚眉 Traceback (most recent call last): File "D:\zjm_code\a.py", line 6, in <module> print unicode(u'\xe4\xf6\xfc') UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128) python shell >>>u"äöü".encode('utf-8') Unsupported characters in input
[ "In Python 2:\ncase a: (unicode object).encode(somecodec) -> string of bytes\ncase b: (string of bytes).decode(somecodec) -> unicode object\ncase c: unicode(string of bytes, somecodec) -> unicode object\nCases b and c are identical. In each of the three cases, you can omit the codec name: then it defaults to 'ascii', the ASCII decoder (supporting only the 128 ASCII characters -- you'll get an exception otherwise).\nWhenever a 'string of bytes' is required on the left of the arrow, you can pass a unicode object (it's converted with the 'ascii' codec).\nWhenever a 'unicode' is required on the left of the arrow, you can pass a string of bytes (it's converted with the 'ascii' codec).\n", "The encoding error:\nprint unicode(u'\\xe4\\xf6\\xfc')\n\nThe unicode() call does nothing here, since it's parameter is already a unicode object. print then tries to output that unicode object, and to do so print wants to convert it to a string in the encoding of your terminal. But python doesn't seems to know which encoding your terminal uses and therefore goes with the \"safe\" alternative of Ascii.\nSince u'\\xe4\\xf6\\xfc' cannot be represented in Ascii this leads to an encoding error.\nUnicode, encode and decode:\nGenerally encode() converts a unicode object to a string with a certain character encoding like UTF-8 or ISO-8859-1. Every unicode code point is converted to a sequence of bytes in that encoding:\n>>> u'\\xe4\\xf6\\xfc'.encode('utf-8')\n'\\xc3\\xa4\\xc3\\xb6\\xc3\\xbc'\n\nThe opposite is decode(), it converts a string in a certain encoding to a unicode object containing the corresponding unicode codepoints.\n>>> '\\xc3\\xa4\\xc3\\xb6\\xc3\\xbc'.decode('utf-8')\nu'\\xe4\\xf6\\xfc'\n\nPrinting:\nprint with a string parameter just prints the raw bytes of that string. If that results in the desired output depends on the character encoding of the terminal.\n>>> print '\\xc3\\xa4\\xc3\\xb6\\xc3\\xbc' # utf-8 encoding on utf-8 terminal\näöü\n>>> print '\\xe4\\xf6\\xfc' # same encoded as latin-1\n���\n\nWhen given a unicode parameter, print first tries to encode the unicode object in the terminals encoding. This only works if python guesses the right encoding for the terminal and that encoding can actually represent all the characters of the unicode object. Otherwise the encoding throws exceptions or the output contains wrong characters.\n>>> print u'\\xe4\\xf6\\xfc' # it correctly assumes a utf-8 terminal\näöü\n\n", "This is covered in the tutorial and the unicode howto\nThe unicode function converts non-unicode (by default, ascii, but it accepts other encodings too) strings into unicode. Your error here is that you're passing a string that is already unicode and asking it to be converted to unicode...\nThe encode function on a unicode string converts it back to a non-unicode encoding - again, ascii is the default.\n" ]
[ 12, 7, 0 ]
[]
[]
[ "python", "unicode" ]
stackoverflow_0002025041_python_unicode.txt
Q: Lambda, calling itself into the lambda definition I'm doing a complicated hack in Python, it's a problem when you mix for+lambda+*args (don't do this at home kids), the boring details can be omited, the unique solution I found to resolve the problem is to pass the lambda object into the self lambda in this way: for ... lambda x=x, *y: foo(x, y, <selflambda>) It's possible?, thanks a lot. A: You are looking for a fixed-point combinator, like the Z combinator, for which Wikipedia gives this Python implementation: Z = lambda f: (lambda x: f(lambda *args: x(x)(*args)))(lambda x: f(lambda *args: x(x)(*args))) Z takes one argument, a function describing the function you want, and builds and returns that function. The function you're looking to build is: Z(lambda f: lambda x=x, *y: foo(x, y, f)) A: While your question is genuinely weird, try something like: >>> import functools >>> f = lambda selflambda, x=x, *y: foo(x, y, selflambda) >>> f = functools.partial(f, f) A: If you want to refer to it, you'll have to give it a name bar=lambda x=x, *y: foo(x, y, bar) such is the way of the snake A: The easiest way is to write a separate function to create the lambda. def mkfun(foo, x): f = lambda x=x, *y: foo(x, y, f) return f for ...: ...mkfun(foo, x)... This works just like gnibbler's suggestion but can be used in a for loop. EDIT: I wasn't joking. It really works! def foo(x, y, bar): print x if y: bar() # call the lambda. it should just print x again. # --- gnibbler's answer funs = [] for x in range(5): bar=lambda x=x, *y: foo(x, y, bar) # What does bar refer to? funs.append(bar) funs[2](2, True) # prints 2 4 -- oops! Where did the 4 come from? # --- this answer def mkfun(x, foo): bar = lambda x=x, *y: foo(x, y, bar) # different bar variable each time return bar funs = [] for x in range(5): funs.append(mkfun(x, foo)) funs[2](2, True) # prints 2 2 A: I don't understand why you want to do this with lambda. lambda: creates a function object that does not have a name def: creates a function object that does have a name a name: very useful for calling yourself for ... def selflambda(x=x, *y): return foo(x, y, selflambda) ... Doesn't this do exactly what you requested? I even called it selflambda. If it doesn't do what you want, would you please explain why it doesn't? EDIT: Okay, Jason Orendorff has pointed out that this won't work, because each time through the loop, the name selflambda will be rebound to a new function, so all the function objects will try to call the newest version of the function. I'll leave this up for the educational value, not because it is a good answer.
Lambda, calling itself into the lambda definition
I'm doing a complicated hack in Python, it's a problem when you mix for+lambda+*args (don't do this at home kids), the boring details can be omited, the unique solution I found to resolve the problem is to pass the lambda object into the self lambda in this way: for ... lambda x=x, *y: foo(x, y, <selflambda>) It's possible?, thanks a lot.
[ "You are looking for a fixed-point combinator, like the Z combinator, for which Wikipedia gives this Python implementation:\nZ = lambda f: (lambda x: f(lambda *args: x(x)(*args)))(lambda x: f(lambda *args: x(x)(*args)))\n\nZ takes one argument, a function describing the function you want, and builds and returns that function.\nThe function you're looking to build is:\nZ(lambda f: lambda x=x, *y: foo(x, y, f))\n\n", "While your question is genuinely weird, try something like:\n>>> import functools\n>>> f = lambda selflambda, x=x, *y: foo(x, y, selflambda)\n>>> f = functools.partial(f, f)\n\n", "If you want to refer to it, you'll have to give it a name\nbar=lambda x=x, *y: foo(x, y, bar)\n\nsuch is the way of the snake\n", "The easiest way is to write a separate function to create the lambda.\ndef mkfun(foo, x):\n f = lambda x=x, *y: foo(x, y, f)\n return f\n\nfor ...:\n ...mkfun(foo, x)...\n\nThis works just like gnibbler's suggestion but can be used in a for loop.\nEDIT: I wasn't joking. It really works!\ndef foo(x, y, bar):\n print x\n if y:\n bar() # call the lambda. it should just print x again.\n\n# --- gnibbler's answer\nfuns = []\nfor x in range(5):\n bar=lambda x=x, *y: foo(x, y, bar) # What does bar refer to?\n funs.append(bar)\nfuns[2](2, True) # prints 2 4 -- oops! Where did the 4 come from?\n\n# --- this answer\ndef mkfun(x, foo):\n bar = lambda x=x, *y: foo(x, y, bar) # different bar variable each time\n return bar\nfuns = []\nfor x in range(5):\n funs.append(mkfun(x, foo))\nfuns[2](2, True) # prints 2 2\n\n", "I don't understand why you want to do this with lambda.\nlambda: creates a function object that does not have a name\ndef: creates a function object that does have a name\na name: very useful for calling yourself\nfor ...\n def selflambda(x=x, *y):\n return foo(x, y, selflambda)\n ...\n\nDoesn't this do exactly what you requested? I even called it selflambda. If it doesn't do what you want, would you please explain why it doesn't?\nEDIT: Okay, Jason Orendorff has pointed out that this won't work, because each time through the loop, the name selflambda will be rebound to a new function, so all the function objects will try to call the newest version of the function. I'll leave this up for the educational value, not because it is a good answer.\n" ]
[ 8, 4, 0, 0, 0 ]
[]
[]
[ "functional_programming", "lambda", "python" ]
stackoverflow_0002023992_functional_programming_lambda_python.txt
Q: mobile python 2.6 distribution/development environment? I'm in an interesting situation. My current computer is going to go in for repairs, and in the meantime I want to get some work done on a friend's computer, but I can't and really don't want to have to set up my development environment on the new PC. Is there a way I can carry around a working Python development environment on a Flash drive? At the very least I'm going to need the Python 2.6 Interpreter + all the libraries I've got installed, and some form of source control (preferably Mercurial). A: Portable Python A: you can get PortablePython as suggested, OR you can copy the whole installed Python directory, eg C:\Python26 of your old PC into your flash drive. another you can try is Movable Python and web2py A: Another option is to set up a remote server on Slicehost or Rackspace cloud and SSH in from your friend's machine. You'll have full control over what libraries you want installed.
mobile python 2.6 distribution/development environment?
I'm in an interesting situation. My current computer is going to go in for repairs, and in the meantime I want to get some work done on a friend's computer, but I can't and really don't want to have to set up my development environment on the new PC. Is there a way I can carry around a working Python development environment on a Flash drive? At the very least I'm going to need the Python 2.6 Interpreter + all the libraries I've got installed, and some form of source control (preferably Mercurial).
[ "Portable Python\n", "you can get PortablePython as suggested, OR you can copy the whole installed Python directory, eg C:\\Python26 of your old PC into your flash drive. \nanother you can try is Movable Python\nand web2py\n", "Another option is to set up a remote server on Slicehost or Rackspace cloud and SSH in from your friend's machine. You'll have full control over what libraries you want installed.\n" ]
[ 3, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002025311_python.txt
Q: saving data in Bulk using Django I have objects A witch has many to many relation ship to object b. Is it possible to save objects A with it's B collection in a bulk ' I mean not to save B objects one by one then add them to A. for b in b_objects : A.b_objs.add(b) A.save() Thanks A: You could dump your model to json (from http://www.djangosnippets.org/snippets/125/): import sys, os sys.path.append('/Path/To/Django/Projects/') os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings' from django.core.serializers import serialize from myproject.myapp import models model_names = [] # a list of the names of the models you want to export for model_name in model_names: cls = getattr(models, model_name) filename = model_name.lower() + ".json" file = open(filename, "w") file.write(serialize("json", cls.objects.all())) A: I don't think so. The ManyToMany relationship is realized with an intermediate table than contains (id, a_id, b_id) tuples. Therefore A must pre-exist (See 'Sample API Usage') and each B must have an id before the intermediate row can be created. I looked at the source in django.db.models.fields.related and although create_many_related_manager has a method called _add_items(), it seems to assume that all of the B items being added already have id fields, meaning they must have been saved beforehand. I couldn't find anything that would allow the equivalent of A.add(bunch_of_Bs_that_havent_been_saved_yet). The above mentioned example does show add()ing multiple Bs in one shot, but they have all been saved before the add() happens. Sorry.
saving data in Bulk using Django
I have objects A witch has many to many relation ship to object b. Is it possible to save objects A with it's B collection in a bulk ' I mean not to save B objects one by one then add them to A. for b in b_objects : A.b_objs.add(b) A.save() Thanks
[ "You could dump your model to json (from http://www.djangosnippets.org/snippets/125/):\nimport sys, os\n\nsys.path.append('/Path/To/Django/Projects/')\nos.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings'\n\nfrom django.core.serializers import serialize\nfrom myproject.myapp import models\n\nmodel_names = [] # a list of the names of the models you want to export\n\nfor model_name in model_names:\n cls = getattr(models, model_name)\n filename = model_name.lower() + \".json\"\n file = open(filename, \"w\")\n file.write(serialize(\"json\", cls.objects.all()))\n\n", "I don't think so. The ManyToMany relationship is realized with an intermediate table than contains (id, a_id, b_id) tuples. Therefore A must pre-exist (See 'Sample API Usage') and each B must have an id before the intermediate row can be created. I looked at the source in django.db.models.fields.related and although create_many_related_manager has a method called _add_items(), it seems to assume that all of the B items being added already have id fields, meaning they must have been saved beforehand.\nI couldn't find anything that would allow the equivalent of A.add(bunch_of_Bs_that_havent_been_saved_yet). The above mentioned example does show add()ing multiple Bs in one shot, but they have all been saved before the add() happens. Sorry.\n" ]
[ 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002019379_django_python.txt
Q: Replacing text in Python I've been looking at the re documentation and at other questions but I keep running into trouble with regex. I need to take what ever is in the [tag] off of the string. string = "Article Name [Tag Name]" #and I want to go to string = "Article Name" I'd really appreciate it if anyone could help. A: re.sub("\s*\[.*?\]", "", string) A: If you are sure [Tag Name] is always come after Article Name, you could do this without regex. >>> string="Article Name [Tag Name]" >>> string[:string.find(" [")] 'Article Name' or with .partition >>> string.partition(" [")[0] 'Article Name' A: This does not use regex so if that is a requirement this is not an answer but you could do this: string = string.split('[')[0].strip() A: re.sub(r"(.*) \[.*\]", r"\1", string) This will only remove the tag if it's at the end of the string. A: Even better without regex: txt = "Article Name [Tag Name]" if txt.rfind('[') and txt.rfind(']') > txt.rfind('['): txt = txt[:txt.rfind('[')] if txt[-1] == ' ': txt = txt[:-1] A: here's one for multiple instances of [] tags >>> string = "Article Name [Tag Name] blah blah [tag name2] blah blah [tag name3]" >>> for i in string.split("]"): ... print i[ : i.find("[") ] ... Article Name blah blah blah blah
Replacing text in Python
I've been looking at the re documentation and at other questions but I keep running into trouble with regex. I need to take what ever is in the [tag] off of the string. string = "Article Name [Tag Name]" #and I want to go to string = "Article Name" I'd really appreciate it if anyone could help.
[ "re.sub(\"\\s*\\[.*?\\]\", \"\", string)\n\n", "If you are sure [Tag Name] is always come after Article Name, you could do this without regex.\n>>> string=\"Article Name [Tag Name]\"\n>>> string[:string.find(\" [\")]\n'Article Name'\n\nor with .partition\n>>> string.partition(\" [\")[0]\n'Article Name'\n\n", "This does not use regex so if that is a requirement this is not an answer but you could do this:\n string = string.split('[')[0].strip()\n\n", "re.sub(r\"(.*) \\[.*\\]\", r\"\\1\", string)\n\nThis will only remove the tag if it's at the end of the string.\n", "Even better without regex:\ntxt = \"Article Name [Tag Name]\"\nif txt.rfind('[') and txt.rfind(']') > txt.rfind('['): txt = txt[:txt.rfind('[')]\nif txt[-1] == ' ': txt = txt[:-1]\n\n", "here's one for multiple instances of [] tags\n>>> string = \"Article Name [Tag Name] blah blah [tag name2] blah blah [tag name3]\"\n>>> for i in string.split(\"]\"):\n... print i[ : i.find(\"[\") ]\n...\nArticle Name\n blah blah\n blah blah\n\n" ]
[ 2, 1, 1, 0, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002025513_python_regex.txt
Q: Popen always run, ignoring the if I want that when I respond other thing diferent that yes, the subprocess don't run. r = raw_input('\nDo you want play the video?\n\nY:Yes N:No\n\n') if r == "Y" or "y" or "yes" or"yep" or"yeah": message("Playing Video") subprocess.Popen(playvid) else: pass A: change this if r == "Y" or "y" or "yes" or"yep" or"yeah": to if r in ["Y","y","yes","yep","yeah"] : or change your response to lower case r = raw_input('\nDo you want play the video?\n\nY:Yes N:No\n\n').lower() if r in ["y","yes","yep","yeah"] : A: I'm not sure if I fully understand your question, but I believe the issue is your syntax in this line: if r == "Y" or "y" or "yes" or"yep" or"yeah": You are testing the truth of "Y", "y", etc, which all evaluate to "true". Put all of the values in a sequence and do: if r in seq: That should be a much cleaner way to do it than if r == "Y" or r == "y"...
Popen always run, ignoring the if
I want that when I respond other thing diferent that yes, the subprocess don't run. r = raw_input('\nDo you want play the video?\n\nY:Yes N:No\n\n') if r == "Y" or "y" or "yes" or"yep" or"yeah": message("Playing Video") subprocess.Popen(playvid) else: pass
[ "change this\nif r == \"Y\" or \"y\" or \"yes\" or\"yep\" or\"yeah\":\n\nto \nif r in [\"Y\",\"y\",\"yes\",\"yep\",\"yeah\"] :\n\nor change your response to lower case\nr = raw_input('\\nDo you want play the video?\\n\\nY:Yes N:No\\n\\n').lower()\nif r in [\"y\",\"yes\",\"yep\",\"yeah\"] :\n\n", "I'm not sure if I fully understand your question, but I believe the issue is your syntax in this line:\nif r == \"Y\" or \"y\" or \"yes\" or\"yep\" or\"yeah\":\n\nYou are testing the truth of \"Y\", \"y\", etc, which all evaluate to \"true\". Put all of the values in a sequence and do:\nif r in seq:\n\nThat should be a much cleaner way to do it than\nif r == \"Y\" or r == \"y\"...\n\n" ]
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002025885_python.txt
Q: See What Line a Function Was Called From in Python Decorator Given something like this: @my_decorator my_function(some, args) Is it possible for my_decorator to discover the file and line number my_function was called from? Thanks A: traceback.extract_stack() will allow you to examine the current stack frame.
See What Line a Function Was Called From in Python Decorator
Given something like this: @my_decorator my_function(some, args) Is it possible for my_decorator to discover the file and line number my_function was called from? Thanks
[ "traceback.extract_stack() will allow you to examine the current stack frame.\n" ]
[ 4 ]
[]
[]
[ "decorator", "inspect", "python" ]
stackoverflow_0002025941_decorator_inspect_python.txt
Q: Is it possible to tell a python script to stop at some point and give you the hand interactively, for example with ipython? Suppose I have a script that does a lot of stuff, and doesn't work well somewhere near the end. I'd love to be able to add a start_ipython() function at that point, which would stop the script at this point, and let me inspect variables and so on with ipython. How can I do this? A: Note that this has changed in IPython-0.11. Instead of what is described below, simply use the following import: from IPython import embed as shell The answer below works for IPython versions prior to 0.11. In the region where you want to drop into ipython, define this def start_ipython(): from IPython.Shell import IPShellEmbed shell = IPShellEmbed() shell() and call start_ipython where you want to drop into the interpreter. This will drop you into an interpreter and will preserve the locals() at that point. If you want a regular shell, do this def start_python(): import code code.interact() Check the documentation for the above functions for details. I'd recommend that you try the ipython one and if it throws an ImportError, switch to normal so that it will work even if ipython is not installed. A: Easiest way is to use the built-in debugger. At the point you want execution to stop, just do: import pdb; pdb.set_trace() and you'll be dumped into the pdb shell, which allows you to inspect variables and change them. There is also an external ipdb package which you can get via easy_install which should work the same way.
Is it possible to tell a python script to stop at some point and give you the hand interactively, for example with ipython?
Suppose I have a script that does a lot of stuff, and doesn't work well somewhere near the end. I'd love to be able to add a start_ipython() function at that point, which would stop the script at this point, and let me inspect variables and so on with ipython. How can I do this?
[ "Note that this has changed in IPython-0.11. Instead of what is described below, simply use the following import:\nfrom IPython import embed as shell\n\nThe answer below works for IPython versions prior to 0.11.\n\nIn the region where you want to drop into ipython, define this\ndef start_ipython():\n from IPython.Shell import IPShellEmbed\n shell = IPShellEmbed()\n shell()\n\nand call start_ipython where you want to drop into the interpreter. \nThis will drop you into an interpreter and will preserve the locals() at that point. \nIf you want a regular shell, do this\ndef start_python():\n import code\n code.interact()\n\nCheck the documentation for the above functions for details. I'd recommend that you try the ipython one and if it throws an ImportError, switch to normal so that it will work even if ipython is not installed. \n", "Easiest way is to use the built-in debugger. At the point you want execution to stop, just do:\nimport pdb; pdb.set_trace()\n\nand you'll be dumped into the pdb shell, which allows you to inspect variables and change them.\nThere is also an external ipdb package which you can get via easy_install which should work the same way.\n" ]
[ 15, 7 ]
[]
[]
[ "python" ]
stackoverflow_0002026447_python.txt
Q: Strategies or support for making parts of a Twisted application reloadable? I've written a specialized JSON-RPC server and just started working my way up into the application logic and finding it is a tad annoying to constantly having to stop/restart the server to make certain changes. Previously I had a handler that ran in intervals to compare module modified time stamps with the past check then reload the module as needed. Unfortunately I don't trust it to work correctly now. Is there a way for a reactor to stop and restart itself in a manner similar to Paster's Reloadable HTTPServer? A: Shipped with Twisted is the twisted.python.rebuild module, so that is probably a good place to start. Also see this SO question: Checking for code changes in all imported python modules A: You could write something similar to paster's reloader, that would work like this: start your main function, and before importing / using any twisted code, fork/spawn a subprocess. In the subprocess, run your twisted application. In the main process, run your code which checks for changed files. If code has changed, reload the subprocess. However, the issue here is that unlike a development webserver, most twisted apps have a lot more state and just flat out killing / restarting the process is a bad idea, you may lose some state. There is a way to do it cleanly: When you spawn the twisted app, use subprocess.Popen() or similar, to get stdin/stdout pipes. Now in your subprocess, use the twisted reactor to listen on stdin (there is code for this in twisted, see twisted.internet.stdio which allows you to have a Protocol which talks to a stdio transport, in the usual twisted non-blocking manner). Finally, when you decide it's time to reload, write something to the stdin of the subprocess telling it to shutdown. Now your twisted code can respond and shut down gracefully. Once it's cleanly quit, your master process can just spawn it again. (Alternately you can use signals to achieve this, but this may not be OS portable)
Strategies or support for making parts of a Twisted application reloadable?
I've written a specialized JSON-RPC server and just started working my way up into the application logic and finding it is a tad annoying to constantly having to stop/restart the server to make certain changes. Previously I had a handler that ran in intervals to compare module modified time stamps with the past check then reload the module as needed. Unfortunately I don't trust it to work correctly now. Is there a way for a reactor to stop and restart itself in a manner similar to Paster's Reloadable HTTPServer?
[ "Shipped with Twisted is the twisted.python.rebuild module, so that is probably a good place to start. \nAlso see this SO question: Checking for code changes in all imported python modules\n", "You could write something similar to paster's reloader, that would work like this:\n\nstart your main function, and before importing / using any twisted code, fork/spawn a subprocess.\nIn the subprocess, run your twisted application.\nIn the main process, run your code which checks for changed files. If code has changed, reload the subprocess.\n\nHowever, the issue here is that unlike a development webserver, most twisted apps have a lot more state and just flat out killing / restarting the process is a bad idea, you may lose some state. \nThere is a way to do it cleanly:\nWhen you spawn the twisted app, use subprocess.Popen() or similar, to get stdin/stdout pipes. Now in your subprocess, use the twisted reactor to listen on stdin (there is code for this in twisted, see twisted.internet.stdio which allows you to have a Protocol which talks to a stdio transport, in the usual twisted non-blocking manner).\nFinally, when you decide it's time to reload, write something to the stdin of the subprocess telling it to shutdown. Now your twisted code can respond and shut down gracefully. Once it's cleanly quit, your master process can just spawn it again.\n(Alternately you can use signals to achieve this, but this may not be OS portable)\n" ]
[ 2, 1 ]
[]
[]
[ "python", "twisted" ]
stackoverflow_0002026091_python_twisted.txt
Q: Python multiple inheritance: Whats wrong doing it dynamically? Based on this answer, of how __new__ and __init__ are supposed to work in Python, I wrote this code to dynamically define and create a new class and object. class A(object): def __new__(cls): class C(cls, B): pass self = C() return self def foo(self): print 'foo' class B(object): def bar(self): print 'bar' a = A() a.foo() a.bar() Basically, because the __new__ of A returns a dynamically created C that inherits A and B, it should have an attribute bar. Why does C not have a bar attribute? A: Since there is no actual question in the question, I am going to take it literally: Whats wrong doing it dynamically? Well, it is practically unreadable, extremely opaque and non-obvious to the user of your code (that includes you in a month :P). From my experience (quite limited, I must admit, unfortunately I don't have 20 years of programming under the belt), a need for such solutions indicates, that the class structure is not well defined, - means, there's almost always a better, more readable and less arcane way to do such things. For example, if you really want to define base classes on the fly, you are better off using a factory function, that will return appropriate classes according to your needs. Another take on the question: Whats wrong doing it dynamically? In your current implementation, it gives me a "maximum recursion depth exceeded" error. That happens, because A.__new__ calls itself from within itself indefinitely (since it inherits from itself and from B). 10: Inside A.__new__, "cls" is set to <class '.A'>. Inside the constructor you define a class C, which inherits from cls (which is actually A) and another class B. Upon instantiating C, its __new__ is called. Since it doesn't define its own __new__, its base class' __new__ is called. The base class just happens to be A. 20: GOTO 10 A: Resolve the infinite recursion: class A(object): def __new__(cls): class C(cls, B): pass self = object.__new__(C) return self (Thanks to balpha for pointing out the actual question.) A: If your question is "How can I accomplish this" – this works: class A(object): @classmethod def get_with_B(cls): class C(B, cls): pass return C() def foo(self): print 'foo' class B(object): def bar(self): print 'bar' a = A.get_with_B() a.foo() a.bar() If your question is "Why doesn't it work" – that's because you run into an infinite recursion when you call C(), which leads to A.__new__ being called, which again calls C() etc.
Python multiple inheritance: Whats wrong doing it dynamically?
Based on this answer, of how __new__ and __init__ are supposed to work in Python, I wrote this code to dynamically define and create a new class and object. class A(object): def __new__(cls): class C(cls, B): pass self = C() return self def foo(self): print 'foo' class B(object): def bar(self): print 'bar' a = A() a.foo() a.bar() Basically, because the __new__ of A returns a dynamically created C that inherits A and B, it should have an attribute bar. Why does C not have a bar attribute?
[ "Since there is no actual question in the question, I am going to take it literally:\nWhats wrong doing it dynamically?\nWell, it is practically unreadable, extremely opaque and non-obvious to the user of your code (that includes you in a month :P).\nFrom my experience (quite limited, I must admit, unfortunately I don't have 20 years of programming under the belt), a need for such solutions indicates, that the class structure is not well defined, - means, there's almost always a better, more readable and less arcane way to do such things.\nFor example, if you really want to define base classes on the fly, you are better off using a factory function, that will return appropriate classes according to your needs.\nAnother take on the question:\nWhats wrong doing it dynamically?\nIn your current implementation, it gives me a \"maximum recursion depth exceeded\" error. That happens, because A.__new__ calls itself from within itself indefinitely (since it inherits from itself and from B).\n10: Inside A.__new__, \"cls\" is set to <class '.A'>. Inside the constructor you define a class C, which inherits from cls (which is actually A) and another class B. Upon instantiating C, its __new__ is called. Since it doesn't define its own __new__, its base class' __new__ is called. The base class just happens to be A.\n20: GOTO 10\n", "Resolve the infinite recursion:\nclass A(object):\n def __new__(cls):\n class C(cls, B):\n pass\n self = object.__new__(C)\n return self\n\n(Thanks to balpha for pointing out the actual question.)\n", "If your question is \"How can I accomplish this\" – this works:\nclass A(object):\n @classmethod\n def get_with_B(cls):\n class C(B, cls):\n pass\n\n return C()\n\n def foo(self):\n print 'foo'\n\nclass B(object):\n def bar(self):\n print 'bar'\n\na = A.get_with_B()\na.foo()\na.bar()\n\nIf your question is \"Why doesn't it work\" – that's because you run into an infinite recursion when you call C(), which leads to A.__new__ being called, which again calls C() etc.\n" ]
[ 7, 7, 3 ]
[]
[]
[ "multiple_inheritance", "python" ]
stackoverflow_0002026572_multiple_inheritance_python.txt
Q: Python: Get importing module's details from within imported module I'm writing a piece of reusable code to import where I need it, but it needs some info about what is importing it. I have a workaround that does what I want, but it's a bit ugly. Is there a better way? Here is a simplified version of what I'm doing. What I want: Import a method and use it, but look at f in mod2. It needs some info from the importing module. mod1: from mod2 import f f(...) mod2: from things_i_want import parent_module, importing_module def f(*args, **kwargs): from importing_module.parent_module import models # ... do some stuff with it, including populating v with a string v = 'some_string' m = getattr(importing_module, v, None) if callable(m) return m(*args, **kwargs) My ugly workaround: mod1: from mod2 import f as _f def f(*a, **k):return _f(__name__, globals(), *a, **k) f(...) mod2: def f(module_name, globs, *args, **kwargs): # find parent modules path parent_module_path = module_name.split('.')[0:-1] # find models modules path models_path = parent_module_path + ['models',] # import it models = __import__('.'.join(models_path), {}, {}, ['']) # ... do some stuff with it, including populating v with a string v = 'some_string' if v in globs: return globs[v](*args, **kwargs) A: That's a bad idea, because modules are cached. So if another module, say, mod3.py, also imports mod2, it will get the same mod2 object of the first time. The module is not reimported. Maybe you imported some other module that imported mod2 before importing mod2 yourself, then you're not the one importing mod2 anymore. Modules are imported only once. So instead of trying to get who imported the module, you should use another, reusable approach. Perhaps using classes and passing the instance around?
Python: Get importing module's details from within imported module
I'm writing a piece of reusable code to import where I need it, but it needs some info about what is importing it. I have a workaround that does what I want, but it's a bit ugly. Is there a better way? Here is a simplified version of what I'm doing. What I want: Import a method and use it, but look at f in mod2. It needs some info from the importing module. mod1: from mod2 import f f(...) mod2: from things_i_want import parent_module, importing_module def f(*args, **kwargs): from importing_module.parent_module import models # ... do some stuff with it, including populating v with a string v = 'some_string' m = getattr(importing_module, v, None) if callable(m) return m(*args, **kwargs) My ugly workaround: mod1: from mod2 import f as _f def f(*a, **k):return _f(__name__, globals(), *a, **k) f(...) mod2: def f(module_name, globs, *args, **kwargs): # find parent modules path parent_module_path = module_name.split('.')[0:-1] # find models modules path models_path = parent_module_path + ['models',] # import it models = __import__('.'.join(models_path), {}, {}, ['']) # ... do some stuff with it, including populating v with a string v = 'some_string' if v in globs: return globs[v](*args, **kwargs)
[ "That's a bad idea, because modules are cached.\nSo if another module, say, mod3.py, also imports mod2, it will get the same mod2 object of the first time. The module is not reimported.\nMaybe you imported some other module that imported mod2 before importing mod2 yourself, then you're not the one importing mod2 anymore. Modules are imported only once.\nSo instead of trying to get who imported the module, you should use another, reusable approach. Perhaps using classes and passing the instance around?\n" ]
[ 6 ]
[]
[]
[ "django", "import", "python", "rest" ]
stackoverflow_0002026788_django_import_python_rest.txt
Q: How do you ask gstreamer if a file can be played? I'm trying to write a simple command line audio player using the Python Gstreamer bindings. Is there a function in the gstreamer API that determines in advance whether or not a particular file (URI) can be decoded and played by the currently installed set of codecs? A: I guess you can try to play it and see if that raises any error - in fact, there's no way to know the set of codecs necessary without opening the file. Some distributions even have hooks in place that ask the user to download the right codec when you start playing something.
How do you ask gstreamer if a file can be played?
I'm trying to write a simple command line audio player using the Python Gstreamer bindings. Is there a function in the gstreamer API that determines in advance whether or not a particular file (URI) can be decoded and played by the currently installed set of codecs?
[ "I guess you can try to play it and see if that raises any error - in fact, there's no way to know the set of codecs necessary without opening the file. Some distributions even have hooks in place that ask the user to download the right codec when you start playing something.\n" ]
[ 0 ]
[]
[]
[ "codec", "decode", "gstreamer", "python", "uri" ]
stackoverflow_0002025964_codec_decode_gstreamer_python_uri.txt
Q: Packaging Python applications with configuration files I'm using ConfigParser for configuring my application, and now I want to make it easily distributable, and at the same time preserve the configurability. I'm thinking I need a directory with configuration file templates, and some way of generating the configuration to actually use from these. Then I need a place to store it that will work in virtualenv, the users home directory etc. I want it to be as close to how normal Unix packages work, i.e. have config in etc, but with overrides in home directory. Is there a readymade solution for this, and if not, what should I put in my setup.py etc to make it work like I want? A: you can use data_files option of distutils to install files wherever you want. data_files specifies a sequence of (directory, files) pairs in the following way: setup(..., data_files=[('/etc', ['cfg/config1.ini', 'cfg/config2.ini']), ('/etc/init.d', ['bin/initscript1'])], .... ) When reading the config file on your app, you can merge a /home version if it exists, using .read() method of ConfigParser objects: files_read = cfgparserobj.read(['/etc/config1.ini', os.path.expanduser('~/.config1.ini')]) for fname in files_read: print "Reading config from", fname That will read /etc/config1.ini and then overwrite the definitions with stuff coming from .config1.ini in the user's home directory, if it exists.
Packaging Python applications with configuration files
I'm using ConfigParser for configuring my application, and now I want to make it easily distributable, and at the same time preserve the configurability. I'm thinking I need a directory with configuration file templates, and some way of generating the configuration to actually use from these. Then I need a place to store it that will work in virtualenv, the users home directory etc. I want it to be as close to how normal Unix packages work, i.e. have config in etc, but with overrides in home directory. Is there a readymade solution for this, and if not, what should I put in my setup.py etc to make it work like I want?
[ "you can use data_files option of distutils to install files wherever you want.\ndata_files specifies a sequence of (directory, files) pairs in the following way:\nsetup(...,\n data_files=[('/etc', ['cfg/config1.ini', 'cfg/config2.ini']),\n ('/etc/init.d', ['bin/initscript1'])],\n ....\n )\n\nWhen reading the config file on your app, you can merge a /home version if it exists, using .read() method of ConfigParser objects:\nfiles_read = cfgparserobj.read(['/etc/config1.ini', \n os.path.expanduser('~/.config1.ini')])\nfor fname in files_read:\n print \"Reading config from\", fname\n\nThat will read /etc/config1.ini and then overwrite the definitions with stuff coming from .config1.ini in the user's home directory, if it exists.\n" ]
[ 13 ]
[]
[]
[ "configuration_files", "packaging", "python" ]
stackoverflow_0002026876_configuration_files_packaging_python.txt
Q: Work with Postgres/PostGIS View in SQLAlchemy Two questions: i want to generate a View in my PostGIS-DB. How do i add this View to my geometry_columns Table? What i have to do, to use a View with SQLAlchemy? Is there a difference between a Table and View to SQLAlchemy or could i use the same way to use a View as i do to use a Table? sorry for my poor english. If there a questions about my question, please feel free to ask so i can try to explain it in another way maybe :) Nico A: Table objects in SQLAlchemy have two roles. They can be used to issue DDL commands to create the table in the database. But their main purpose is to describe the columns and types of tabular data that can be selected from and inserted to. If you only want to select, then a view looks to SQLAlchemy exactly like a regular table. It's enough to describe the view as a Table with the columns that interest you (you don't even need to describe all of the columns). If you want to use the ORM you'll need to declare for SQLAlchemy that some combination of the columns can be used as the primary key (anything that's unique will do). Declaring some columns as foreign keys will also make it easier to set up any relations. If you don't issue create for that Table object, then it is just metadata for SQLAlchemy to know how to query the database. If you also want to insert to the view, then you'll need to create PostgreSQL rules or triggers on the view that redirect the writes to the correct location. I'm not aware of a good usage recipe to redirect writes on the Python side.
Work with Postgres/PostGIS View in SQLAlchemy
Two questions: i want to generate a View in my PostGIS-DB. How do i add this View to my geometry_columns Table? What i have to do, to use a View with SQLAlchemy? Is there a difference between a Table and View to SQLAlchemy or could i use the same way to use a View as i do to use a Table? sorry for my poor english. If there a questions about my question, please feel free to ask so i can try to explain it in another way maybe :) Nico
[ "Table objects in SQLAlchemy have two roles. They can be used to issue DDL commands to create the table in the database. But their main purpose is to describe the columns and types of tabular data that can be selected from and inserted to.\nIf you only want to select, then a view looks to SQLAlchemy exactly like a regular table. It's enough to describe the view as a Table with the columns that interest you (you don't even need to describe all of the columns). If you want to use the ORM you'll need to declare for SQLAlchemy that some combination of the columns can be used as the primary key (anything that's unique will do). Declaring some columns as foreign keys will also make it easier to set up any relations. If you don't issue create for that Table object, then it is just metadata for SQLAlchemy to know how to query the database.\nIf you also want to insert to the view, then you'll need to create PostgreSQL rules or triggers on the view that redirect the writes to the correct location. I'm not aware of a good usage recipe to redirect writes on the Python side.\n" ]
[ 4 ]
[]
[]
[ "postgis", "postgresql", "python", "sqlalchemy" ]
stackoverflow_0002026475_postgis_postgresql_python_sqlalchemy.txt
Q: + and += operators are different? >>> c = [1, 2, 3] >>> print(c, id(c)) [1, 2, 3] 43955984 >>> c += c >>> print(c, id(c)) [1, 2, 3, 1, 2, 3] 43955984 >>> del c >>> c = [1, 2, 3] >>> print(c, id(c)) [1, 2, 3] 44023976 >>> c = c + c >>> print(c, id(c)) [1, 2, 3, 1, 2, 3] 26564048 What's the difference? are += and + not supposed to be merely syntactic sugar? A: docs explain it very well, I think: __iadd__(), etc. These methods are called to implement the augmented arithmetic assignments (+=, -=, *=, /=, //=, %=, **=, <<=, >>=, &=, ^=, |=). These methods should attempt to do the operation in-place (modifying self) and return the result (which could be, but does not have to be, self). If a specific method is not defined, the augmented assignment falls back to the normal methods. For instance, to execute the statement x += y, where x is an instance of a class that has an __iadd__() method, x.__iadd__(y) is called. += are designed to implement in-place modification. in case of simple addition, new object created and it's labelled using already-used name (c). Also, you'd notice that such behaviour of += operator only possible because of mutable nature of lists. Integers - an immutable type - won't produce the same result: >>> c = 3 >>> print(c, id(c)) 3 505389080 >>> c += c >>> print(c, id(c)) 6 505389128 A: They are not same c += c append a copy of content of c to c itself c = c + c create new object with c + c A: For foo = [] foo+=foo is syntactic sugar for foo.extend(foo) (and not foo = foo + foo) In the first case, you're just appending members of a list into another (and not creating a new one). The id changes in the second case because a new list is created by adding two lists. It's incidental that both are the same and the result is being bound to the same identifier than once pointed to them. If you rephrase this question with different lists (and not c itself), it will probably become clearer. A: The += operator appends the second list to the first, but the modification is in-place, so the ID remains the same. When you use + , a new list is created, and the final "c" is a new list, so it has a different ID. The end result is the same for both operations though.
+ and += operators are different?
>>> c = [1, 2, 3] >>> print(c, id(c)) [1, 2, 3] 43955984 >>> c += c >>> print(c, id(c)) [1, 2, 3, 1, 2, 3] 43955984 >>> del c >>> c = [1, 2, 3] >>> print(c, id(c)) [1, 2, 3] 44023976 >>> c = c + c >>> print(c, id(c)) [1, 2, 3, 1, 2, 3] 26564048 What's the difference? are += and + not supposed to be merely syntactic sugar?
[ "docs explain it very well, I think:\n\n__iadd__(), etc.\n These methods are called to implement the augmented arithmetic assignments (+=, -=, *=, /=, //=, %=, **=, <<=, >>=, &=, ^=, |=). These methods should attempt to do the operation in-place (modifying self) and return the result (which could be, but does not have to be, self). If a specific method is not defined, the augmented assignment falls back to the normal methods. For instance, to execute the statement x += y, where x is an instance of a class that has an __iadd__() method, x.__iadd__(y) is called.\n\n+= are designed to implement in-place modification. in case of simple addition, new object created and it's labelled using already-used name (c).\nAlso, you'd notice that such behaviour of += operator only possible because of mutable nature of lists. Integers - an immutable type - won't produce the same result:\n>>> c = 3\n>>> print(c, id(c))\n3 505389080\n>>> c += c\n>>> print(c, id(c))\n6 505389128\n\n", "They are not same\nc += c append a copy of content of c to c itself\nc = c + c create new object with c + c\n", "For \nfoo = []\n\nfoo+=foo is syntactic sugar for foo.extend(foo) (and not foo = foo + foo)\nIn the first case, you're just appending members of a list into another (and not creating a new one).\nThe id changes in the second case because a new list is created by adding two lists. It's incidental that both are the same and the result is being bound to the same identifier than once pointed to them. \nIf you rephrase this question with different lists (and not c itself), it will probably become clearer.\n", "The += operator appends the second list to the first, but the modification is in-place, so the ID remains the same.\nWhen you use + , a new list is created, and the final \"c\" is a new list, so it has a different ID. \nThe end result is the same for both operations though.\n" ]
[ 13, 3, 2, 1 ]
[]
[]
[ "list", "operators", "python" ]
stackoverflow_0002027284_list_operators_python.txt
Q: conditional skip in python if i am trying for something like this def scanthefile(): x = 11 if x > 5 """ i want to come out of if and go to end of scanfile """ print x return info update: if have to check for the content size of a file. and if the content size is larger than a value say 500 , then i should go to the end of the scanfile A: If I understand your question, and I'm really unsure I do, you can just de-indent: x = 11 if x > 5: pass # Your code goes here. print x A: By "go to the end of file", do you mean "seek to the end of file"? Then: import os ... if x > 5: thefile.seek(0, os.SEEK_END) If you mean something completely different, you'd better clarify! A: OK, so to answer your update: import os fn = 'somefile.txt' thefile = open(fn, 'r') # The next line check the size of the file. Replace "stat(fn).st_size" with your own code if you want. if stat(fn).st_size > 500: thefile.seek(0, os.SEEK_END) # you are now at the end of the file if the size is > 500 A: The way I understand the question is that you want to break out of an if-statement, which you can't. You can however replace it with a while loop: def scanthefile(): x = 11 while x > 5: # do something here... if CONTENTSIZE > 500: break # do something else.. break # Which will make the while loop only run once. return info
conditional skip in python if
i am trying for something like this def scanthefile(): x = 11 if x > 5 """ i want to come out of if and go to end of scanfile """ print x return info update: if have to check for the content size of a file. and if the content size is larger than a value say 500 , then i should go to the end of the scanfile
[ "If I understand your question, and I'm really unsure I do, you can just de-indent:\nx = 11\nif x > 5:\n pass # Your code goes here.\nprint x\n\n", "By \"go to the end of file\", do you mean \"seek to the end of file\"? Then:\nimport os\n\n ...\n\nif x > 5:\n thefile.seek(0, os.SEEK_END)\n\nIf you mean something completely different, you'd better clarify!\n", "OK, so to answer your update:\nimport os\n\nfn = 'somefile.txt'\nthefile = open(fn, 'r')\n\n# The next line check the size of the file. Replace \"stat(fn).st_size\" with your own code if you want.\nif stat(fn).st_size > 500:\n thefile.seek(0, os.SEEK_END)\n# you are now at the end of the file if the size is > 500\n\n", "The way I understand the question is that you want to break out of an if-statement, which you can't.\nYou can however replace it with a while loop:\ndef scanthefile():\n x = 11\n\n while x > 5:\n # do something here...\n if CONTENTSIZE > 500:\n break\n # do something else..\n break # Which will make the while loop only run once.\n\n return info\n\n" ]
[ 2, 2, 2, 0 ]
[]
[]
[ "if_statement", "python" ]
stackoverflow_0002025701_if_statement_python.txt
Q: How to put values of a list into a string I am trying to place several values from a list into a string. The code I have is below: ID = [0, 1, 2] print 'ID {0}, {1}, and {2}.'.format(ID) or print (r'(ID\s*=\s*)(\S+)').format(ID) This does not work. Does anyone know where I'm going wrong. The code in the second line prints out the list: [0, 1, 2] the first line says: File "tset.py", line 39, in b print 'ID {0}, {1}, and {2}.'.format(ID) IndexError: tuple index out of range Thanks A: You have to unpack the list. ID = [0, 1, 2] print 'ID {0}, {1}, and {2}.'.format(*ID) See the docs: Unpacking argument lists. A: >>> 'ID {0}, {1}, and {2}.'.format(*ID) 'ID 0, 1, and 2.' You need to unpack your list. Your second code doesn't make much sense.
How to put values of a list into a string
I am trying to place several values from a list into a string. The code I have is below: ID = [0, 1, 2] print 'ID {0}, {1}, and {2}.'.format(ID) or print (r'(ID\s*=\s*)(\S+)').format(ID) This does not work. Does anyone know where I'm going wrong. The code in the second line prints out the list: [0, 1, 2] the first line says: File "tset.py", line 39, in b print 'ID {0}, {1}, and {2}.'.format(ID) IndexError: tuple index out of range Thanks
[ "You have to unpack the list.\nID = [0, 1, 2]\nprint 'ID {0}, {1}, and {2}.'.format(*ID)\n\nSee the docs: Unpacking argument lists.\n", ">>> 'ID {0}, {1}, and {2}.'.format(*ID)\n'ID 0, 1, and 2.'\n\nYou need to unpack your list.\nYour second code doesn't make much sense.\n" ]
[ 9, 4 ]
[]
[]
[ "python", "string_formatting" ]
stackoverflow_0002027391_python_string_formatting.txt
Q: Storing list variables as a string and storing it as a variable I am trying to enter list items into a string. I then want to store the string as a variable and print it out in another function. The code I have got so far is: def b(): ID = [0, 1, 2] ID2 = 'ID={0}.{1}.{2}'.format(*ID) return ID2 if __name__ == '__main__': ID2 = b() def c(ID2): print ID2 if __name__ == '__main__': myObject = c(ID2) The output I get is: [0, 1, 2] Any help would be appreciated. Thanks I was returning the list as well as ID2. This was causing the problem. Sorry about this. The code is now working. Thanks A: How about this: >>> ''.join([str(x) for x in [1, 2, 3]]) '123' A: If you want to change [0,1,2] to "0.1.2" (like version string in your previous questions), you could do like this. >>> '.'.join(map(str,[0, 1, 2])) '0.1.2' A: You should probably not have global variable names that match your function parameter names. It's legal but very, very confusing. And a debugging nightmare. You should probably not use ALL UPPERCASE VARIABLE NAMES. It's odd-looking and makes your code hard to read for experienced Python programmers. You should probably not have multiple if __name__ == "__main__" sections. It's very, very confusing and a debugging nightmare. I suspect that these "cosmetic" issues are making it hard to figure out what's really wrong with your program. def b(): id = [0, 1, 2] aString = 'ID={0}.{1}.{2}'.format(*id) return aString def c(id2): print id2 if __name__ == '__main__': someString = b() myObject = c(someString) You might find this a little easier to debug. My output. ID=0.1.2 BTW. Your function c always returns None. So the myObject = c(someString) doesn't make a lot of sense. A: def b(): ID = [0, 1, 2] ID2 = ('ID=%d.%d.%d' % tuple(ID)) return ID2 if __name__ == '__main__': ID2 = b() def c(ID2): print ID2 if __name__ == '__main__': myObject = c(ID2) works for me, don't have python3 handy so cannot try with the .format()-syntax. However myObject = c(ID2) does not make sense, function c() does not return anything
Storing list variables as a string and storing it as a variable
I am trying to enter list items into a string. I then want to store the string as a variable and print it out in another function. The code I have got so far is: def b(): ID = [0, 1, 2] ID2 = 'ID={0}.{1}.{2}'.format(*ID) return ID2 if __name__ == '__main__': ID2 = b() def c(ID2): print ID2 if __name__ == '__main__': myObject = c(ID2) The output I get is: [0, 1, 2] Any help would be appreciated. Thanks I was returning the list as well as ID2. This was causing the problem. Sorry about this. The code is now working. Thanks
[ "How about this:\n>>> ''.join([str(x) for x in [1, 2, 3]])\n'123'\n\n", "If you want to change [0,1,2] to \"0.1.2\" (like version string in your previous questions), you could do like this.\n>>> '.'.join(map(str,[0, 1, 2]))\n'0.1.2'\n\n", "\nYou should probably not have global variable names that match your function parameter names. It's legal but very, very confusing. And a debugging nightmare.\nYou should probably not use ALL UPPERCASE VARIABLE NAMES. It's odd-looking and makes your code hard to read for experienced Python programmers.\nYou should probably not have multiple if __name__ == \"__main__\" sections. It's very, very confusing and a debugging nightmare.\n\nI suspect that these \"cosmetic\" issues are making it hard to figure out what's really wrong with your program. \ndef b(): \n id = [0, 1, 2]\n aString = 'ID={0}.{1}.{2}'.format(*id) \n return aString \n\ndef c(id2): \n print id2 \n\nif __name__ == '__main__': \n someString = b() \n myObject = c(someString) \n\nYou might find this a little easier to debug.\nMy output.\nID=0.1.2\n\nBTW. Your function c always returns None. So the myObject = c(someString) doesn't make a lot of sense.\n", "def b():\n ID = [0, 1, 2]\n ID2 = ('ID=%d.%d.%d' % tuple(ID))\n return ID2\n\nif __name__ == '__main__': ID2 = b()\n\ndef c(ID2):\n print ID2\n\nif __name__ == '__main__': myObject = c(ID2)\n\nworks for me, don't have python3 handy so cannot try with the .format()-syntax.\nHowever myObject = c(ID2) does not make sense, function c() does not return anything\n" ]
[ 3, 2, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002027543_python.txt
Q: How to write an efficient hit counter for websites I want to write a hit counter script to keep track of hits on images on a website and the originating IPs. Impressions are upwards of hundreds of thousands per day, so the counters will be incremented many times a second. I'm looking for a simple, self-hosted method (php, python scripts, etc.). I was thinking of using MySQL to keep track of this, but I'm guessing there's a more efficient way. What are good methods of keeping counters? A: A fascinating subject. Incrementing a counter, simple as it may be, just has to be a transaction... meaning, it can lock out the whole DB for longer than makes sense!-) It can easily be the bottleneck for the whole system. If you need rigorously exact counts but don't need them to be instantly up-to-date, my favorite approach is to append the countable information to a log (switching logs as often as needed for data freshness purposes). Once a log is closed (with thousands of countable events in it), a script can read it and update all that's needed in a single transaction -- maybe not intuitive, but much faster than thousands of single locks. Then there's extremely-fast counters that are only statistically accurate -- but since you don't say that such imprecision is acceptable, I'm not going to explain them in more depth. A: You could take your webserver's Access log (Apache: access.log) and evaluate it time and again (cronjob) in case you do not need to have the data at hand at the exact moment in time when someone visits your site. Usually, the access.log is generated anyway and contains the requested resource as well as time, date and the user's IP. This way you do not have to route all trafic through a php-script. Lean, mean counting machine. A: Without a doubt, Redis is perfect for this problem. It requires about a minute to setup and install, supports atomic increments, is incredibly fast, has client libs for python and php (and many other languages), is durable (snapshots, journal, replication). Store each counter to its own key. Then simply INCR key A: There are two really easy ways: Parse it out of your web logs in batch. Run the hits through beanstalkd or gearmand and have a worker do the hard stuff in a controlled way. Option 1 works with off-the-shelf tools. Option 2 requires just a bit of programming, but gives you something closer to realtime updates without causing you to fall over when the traffic spikes (such as you'll find in your direct mysql case). A: If accuracy is important, you can do it slightly slower with MySql... create a HEAP / Memory table to store your counter values. These a in-memory tables that are blazingly fast. You can write the data into a normal table at intervals. Based on the app engine ideas, you could use memcache as a temporary store for your counter. Incrementing a memcache counter is faster than using the MySql heap tables (I think). Once every five or ten seconds, you could read the memcache counter and write that number into your DB. A: Not sure if it's up your alley, but AppEngine is a pretty nice platform to build on. Some sample code you can use to build a counter using their DataStore and transactions is described here: http://code.google.com/appengine/docs/python/datastore/transactions.html. A: You can use Redis - it`s very fast key-value storage with support for atomic increments. If need will arise -- counts data could be splitted between multiple servers easily. A: I've done something very similar, on a similar scale (multiple servers, hundreds of domains, several thousand hits per hour) and log file analysis was definitely the way to go. (It also checked hit rates, weighted them by file type, and blacklisted IP addresses at the firewall if they were making too many requests; its intended purpose was to auto-block bad bots, not to just be a counter, but counting was an essential piece of it.) No performance impact on the web server process itself, since it's not doing any additional work there, and you could easily publish periodically-updated hit counts by injecting them into the site's database every minute/5 minutes/100 hits/whatever without having to lock the relevant row/table/database (depending on the locking mechanism in use) on every hit.
How to write an efficient hit counter for websites
I want to write a hit counter script to keep track of hits on images on a website and the originating IPs. Impressions are upwards of hundreds of thousands per day, so the counters will be incremented many times a second. I'm looking for a simple, self-hosted method (php, python scripts, etc.). I was thinking of using MySQL to keep track of this, but I'm guessing there's a more efficient way. What are good methods of keeping counters?
[ "A fascinating subject. Incrementing a counter, simple as it may be, just has to be a transaction... meaning, it can lock out the whole DB for longer than makes sense!-) It can easily be the bottleneck for the whole system.\nIf you need rigorously exact counts but don't need them to be instantly up-to-date, my favorite approach is to append the countable information to a log (switching logs as often as needed for data freshness purposes). Once a log is closed (with thousands of countable events in it), a script can read it and update all that's needed in a single transaction -- maybe not intuitive, but much faster than thousands of single locks.\nThen there's extremely-fast counters that are only statistically accurate -- but since you don't say that such imprecision is acceptable, I'm not going to explain them in more depth.\n", "You could take your webserver's Access log (Apache: access.log) and evaluate it time and again (cronjob) in case you do not need to have the data at hand at the exact moment in time when someone visits your site.\nUsually, the access.log is generated anyway and contains the requested resource as well as time, date and the user's IP. This way you do not have to route all trafic through a php-script. Lean, mean counting machine.\n", "Without a doubt, Redis is perfect for this problem. It requires about a minute to setup and install, supports atomic increments, is incredibly fast, has client libs for python and php (and many other languages), is durable (snapshots, journal, replication). \nStore each counter to its own key. Then simply\nINCR key\n\n", "There are two really easy ways:\n\nParse it out of your web logs in batch.\nRun the hits through beanstalkd or gearmand and have a worker do the hard stuff in a controlled way.\n\nOption 1 works with off-the-shelf tools. Option 2 requires just a bit of programming, but gives you something closer to realtime updates without causing you to fall over when the traffic spikes (such as you'll find in your direct mysql case).\n", "If accuracy is important, you can do it slightly slower with MySql... create a HEAP / Memory table to store your counter values. These a in-memory tables that are blazingly fast. You can write the data into a normal table at intervals. \nBased on the app engine ideas, you could use memcache as a temporary store for your counter. Incrementing a memcache counter is faster than using the MySql heap tables (I think). Once every five or ten seconds, you could read the memcache counter and write that number into your DB. \n", "Not sure if it's up your alley, but AppEngine is a pretty nice platform to build on. Some sample code you can use to build a counter using their DataStore and transactions is described here: http://code.google.com/appengine/docs/python/datastore/transactions.html.\n", "You can use Redis - it`s very fast key-value storage with support for atomic increments. If need will arise -- counts data could be splitted between multiple servers easily.\n", "I've done something very similar, on a similar scale (multiple servers, hundreds of domains, several thousand hits per hour) and log file analysis was definitely the way to go. (It also checked hit rates, weighted them by file type, and blacklisted IP addresses at the firewall if they were making too many requests; its intended purpose was to auto-block bad bots, not to just be a counter, but counting was an essential piece of it.)\nNo performance impact on the web server process itself, since it's not doing any additional work there, and you could easily publish periodically-updated hit counts by injecting them into the site's database every minute/5 minutes/100 hits/whatever without having to lock the relevant row/table/database (depending on the locking mechanism in use) on every hit.\n" ]
[ 7, 4, 3, 2, 1, 0, 0, 0 ]
[ "Well if you happen to go the PHP route you could use an SQLite database, however MySQL is a perfectly reasonable way to store that info and usually (at least from the ones I've seen) is how it is done.\nIf you didn't want to store IP address and any other info a simple number in a\ntext file could work.\n" ]
[ -1 ]
[ "mysql", "php", "python", "tracking" ]
stackoverflow_0001535261_mysql_php_python_tracking.txt
Q: Using Python simplejson to return pregenerated json I have a GeoDjango model object that I want't to serialize to json. I do this in my view: lat = float(request.GET.get('lat')) lng = float(request.GET.get('lng')) a = Authority.objects.get(area__contains=Point(lng, lat)) if a: return HttpResponse(simplejson.dumps({'name': a.name, 'area': a.area.geojson, 'id': a.id}), mimetype='application/json') The problem is that simplejson considers the a.area.geojson as a simple string, even though it is beautiful pre-generated json. This is easily fixed in the client by eval()'ing the area-string, but I would like to do it proper. Can I tell simplejson that a particular string is already json and should be used as-is (and not returned as a simple string)? Or is there another workaround? UPDATE Just to clarify, this is the json currently returned: { "id": 95, "name": "Roskilde", "area": "{ \"type\": \"MultiPolygon\", \"coordinates\": [ [ [ [ 12.078701, 55.649927 ], ... ] ] ] }" } The challenge is to have "area" be a json dictionary instead of a simple string. A: I think the clean way to do this is by extending JSONEncoder, and creating an encoder that detects if the given object is already JSON. if it is - it just returns it. If its not, it uses the ordinary JSONEncoder to encode it. class SkipJSONEncoder(simplejson.JSONEncoder): def default(self, obj): if isinstance(obj, str) and (obj[0]=='{') and (obj[-1]=='}'): return obj return simplejson.JSONEncoder.default(self, obj) and in your view, you use: simplejson.dumps(..., cls=SkipJSONEncoder) If you have a cleaner way to test that something is already JSON, please use it (my way - looking for strings that start in '{' and end in '}' is ugly). A: EDITED after author's edit: Can you do something like this: lat = float(request.GET.get('lat')) lng = float(request.GET.get('lng')) a = Authority.objects.get(area__contains=Point(lng, lat)) if a: json = simplejson.dumps({'name': a.name, 'area': "{replaceme}", 'id': a.id}), return HttpResponse(json.replace('"{replaceme}"', a.area.geojson), mimetype='application/json')
Using Python simplejson to return pregenerated json
I have a GeoDjango model object that I want't to serialize to json. I do this in my view: lat = float(request.GET.get('lat')) lng = float(request.GET.get('lng')) a = Authority.objects.get(area__contains=Point(lng, lat)) if a: return HttpResponse(simplejson.dumps({'name': a.name, 'area': a.area.geojson, 'id': a.id}), mimetype='application/json') The problem is that simplejson considers the a.area.geojson as a simple string, even though it is beautiful pre-generated json. This is easily fixed in the client by eval()'ing the area-string, but I would like to do it proper. Can I tell simplejson that a particular string is already json and should be used as-is (and not returned as a simple string)? Or is there another workaround? UPDATE Just to clarify, this is the json currently returned: { "id": 95, "name": "Roskilde", "area": "{ \"type\": \"MultiPolygon\", \"coordinates\": [ [ [ [ 12.078701, 55.649927 ], ... ] ] ] }" } The challenge is to have "area" be a json dictionary instead of a simple string.
[ "I think the clean way to do this is by extending JSONEncoder, and creating an encoder that detects if the given object is already JSON. if it is - it just returns it. If its not, it uses the ordinary JSONEncoder to encode it.\nclass SkipJSONEncoder(simplejson.JSONEncoder):\n def default(self, obj):\n if isinstance(obj, str) and (obj[0]=='{') and (obj[-1]=='}'): \n return obj\n return simplejson.JSONEncoder.default(self, obj)\n\nand in your view, you use:\nsimplejson.dumps(..., cls=SkipJSONEncoder)\n\nIf you have a cleaner way to test that something is already JSON, please use it (my way - looking for strings that start in '{' and end in '}' is ugly).\n", "EDITED after author's edit:\nCan you do something like this:\nlat = float(request.GET.get('lat'))\nlng = float(request.GET.get('lng'))\na = Authority.objects.get(area__contains=Point(lng, lat))\nif a:\n json = simplejson.dumps({'name': a.name, \n 'area': \"{replaceme}\",\n 'id': a.id}), \n return HttpResponse(json.replace('\"{replaceme}\"', a.area.geojson),\n mimetype='application/json')\n\n" ]
[ 5, 2 ]
[]
[]
[ "django", "geodjango", "json", "python", "simplejson" ]
stackoverflow_0002027668_django_geodjango_json_python_simplejson.txt
Q: Why does not postgresql start returning rows immediately? The following query returns data right away: SELECT time, value from data order by time limit 100; Without the limit clause, it takes a long time before the server starts returning rows: SELECT time, value from data order by time; I observe this both by using the query tool (psql) and when querying using an API. Questions/issues: The amount of work the server has to do before starting to return rows should be the same for both select statements. Correct? If so, why is there a delay in case 2? Is there some fundamental RDBMS issue that I do not understand? Is there a way I can make postgresql start returning result rows to the client without pause, also for case 2? EDIT (see below). It looks like setFetchSize is the key to solving this. In my case I execute the query from python, using SQLAlchemy. How can I set that option for a single query (executed by session.execute)? I use the psycopg2 driver. The column time is the primary key, BTW. EDIT: I believe this excerpt from the JDBC driver documentation describes the problem and hints at a solution (I still need help - see the last bullet list item above): By default the driver collects all the results for the query at once. This can be inconvenient for large data sets so the JDBC driver provides a means of basing a ResultSet on a database cursor and only fetching a small number of rows. and Changing code to cursor mode is as simple as setting the fetch size of the Statement to the appropriate size. Setting the fetch size back to 0 will cause all rows to be cached (the default behaviour). // make sure autocommit is off conn.setAutoCommit(false); Statement st = conn.createStatement(); // Turn use of the cursor on. st.setFetchSize(50); A: The psycopg2 dbapi driver buffers the whole query result before returning any rows. You'll need to use server side cursor to incrementally fetch results. For SQLAlchemy see server_side_cursors in the docs and if you're using the ORM the Query.yield_per() method. SQLAlchemy currently doesn't have an option to set that per single query, but there is a ticket with a patch for implementing that. A: In theory, because your ORDER BY is by primary key, a sort of the results should not be necessary, and the DB could indeed return data right away in key order. I would expect a capable DB of noticing this, and optimizing for it. It seems that PGSQL is not. * shrug * You don't notice any impact if you have LIMIT 100 because it's very quick to pull those 100 results out of the DB, and you won't notice any delay if they're first gathered up and sorted before being shipped out to your client. I suggest trying to drop the ORDER BY. Chances are, your results will be correctly ordered by time anyway (there may even be a standard or specification that mandates this, given your PK), and you might get your results more quickly.
Why does not postgresql start returning rows immediately?
The following query returns data right away: SELECT time, value from data order by time limit 100; Without the limit clause, it takes a long time before the server starts returning rows: SELECT time, value from data order by time; I observe this both by using the query tool (psql) and when querying using an API. Questions/issues: The amount of work the server has to do before starting to return rows should be the same for both select statements. Correct? If so, why is there a delay in case 2? Is there some fundamental RDBMS issue that I do not understand? Is there a way I can make postgresql start returning result rows to the client without pause, also for case 2? EDIT (see below). It looks like setFetchSize is the key to solving this. In my case I execute the query from python, using SQLAlchemy. How can I set that option for a single query (executed by session.execute)? I use the psycopg2 driver. The column time is the primary key, BTW. EDIT: I believe this excerpt from the JDBC driver documentation describes the problem and hints at a solution (I still need help - see the last bullet list item above): By default the driver collects all the results for the query at once. This can be inconvenient for large data sets so the JDBC driver provides a means of basing a ResultSet on a database cursor and only fetching a small number of rows. and Changing code to cursor mode is as simple as setting the fetch size of the Statement to the appropriate size. Setting the fetch size back to 0 will cause all rows to be cached (the default behaviour). // make sure autocommit is off conn.setAutoCommit(false); Statement st = conn.createStatement(); // Turn use of the cursor on. st.setFetchSize(50);
[ "The psycopg2 dbapi driver buffers the whole query result before returning any rows. You'll need to use server side cursor to incrementally fetch results. For SQLAlchemy see server_side_cursors in the docs and if you're using the ORM the Query.yield_per() method.\nSQLAlchemy currently doesn't have an option to set that per single query, but there is a ticket with a patch for implementing that.\n", "In theory, because your ORDER BY is by primary key, a sort of the results should not be necessary, and the DB could indeed return data right away in key order.\nI would expect a capable DB of noticing this, and optimizing for it. It seems that PGSQL is not. * shrug *\nYou don't notice any impact if you have LIMIT 100 because it's very quick to pull those 100 results out of the DB, and you won't notice any delay if they're first gathered up and sorted before being shipped out to your client.\nI suggest trying to drop the ORDER BY. Chances are, your results will be correctly ordered by time anyway (there may even be a standard or specification that mandates this, given your PK), and you might get your results more quickly.\n" ]
[ 4, 0 ]
[]
[]
[ "postgresql", "python", "sql", "sqlalchemy" ]
stackoverflow_0002027645_postgresql_python_sql_sqlalchemy.txt
Q: Sorting a tuple of dicts I am new to Python and am curious if I am doing this correctly. I have a tuple of dicts (from a database call): companies = ( { 'companyid': 1, 'companyname': 'Company C' }, { 'companyid': 2, 'companyname': 'Company A' }, { 'companyid': 3, 'companyname': 'Company B' } ) I want to sort this on companyname. Is there a more correct way than this to do it? sortcompanies = list(companies) sortcompanies.sort(lambda x,y: cmp(x['companyname'],y['companyname'])) Thanks for your criticism! A: You could do something like: import operator ... sortcompanies.sort(key=operator.itemgetter("companyname")) I think that's a matter of taste. EDIT I got companyid in stead of companyname. Corrected that error. A: >>> companies = ( { 'companyid': 1, 'companyname': 'Company C' }, { 'companyid': 2, 'companyname': 'Company A' }, { 'companyid': 3, 'companyname': 'Company B' } ) >>> sorted(companies, key=lambda x: x['companyname']) [{'companyname': 'Company A', 'companyid': 2}, {'companyname': 'Company B', 'companyid': 3}, {'companyname': 'Company C', 'companyid': 1}] as you'll see when reading the docs of sorted first argument to the sorted might be any iterable, so you might not need even create the tuple. A: That's fine, but you might want to consider sorting by keys: sortcompanies.sort(key=lambda x:x['companyname']) instead. It's a little easier to read, and there will be fewer calls to x['companyname']. @extraneon makes a good point about using operator.itemgetter as your key. That's pretty readable as well.
Sorting a tuple of dicts
I am new to Python and am curious if I am doing this correctly. I have a tuple of dicts (from a database call): companies = ( { 'companyid': 1, 'companyname': 'Company C' }, { 'companyid': 2, 'companyname': 'Company A' }, { 'companyid': 3, 'companyname': 'Company B' } ) I want to sort this on companyname. Is there a more correct way than this to do it? sortcompanies = list(companies) sortcompanies.sort(lambda x,y: cmp(x['companyname'],y['companyname'])) Thanks for your criticism!
[ "You could do something like:\nimport operator\n...\nsortcompanies.sort(key=operator.itemgetter(\"companyname\"))\n\nI think that's a matter of taste.\nEDIT\nI got companyid in stead of companyname. Corrected that error.\n", ">>> companies = ( { 'companyid': 1, 'companyname': 'Company C' },\n { 'companyid': 2, 'companyname': 'Company A' },\n { 'companyid': 3, 'companyname': 'Company B' } )\n\n>>> sorted(companies, key=lambda x: x['companyname'])\n[{'companyname': 'Company A', 'companyid': 2}, {'companyname': 'Company B', 'companyid': 3}, {'companyname': 'Company C', 'companyid': 1}]\n\nas you'll see when reading the docs of sorted first argument to the sorted might be any iterable, so you might not need even create the tuple.\n", "That's fine, but you might want to consider sorting by keys:\nsortcompanies.sort(key=lambda x:x['companyname'])\n\ninstead. It's a little easier to read, and there will be fewer calls to x['companyname'].\n@extraneon makes a good point about using operator.itemgetter as your key. That's pretty readable as well.\n" ]
[ 7, 3, 2 ]
[]
[]
[ "python", "sorting" ]
stackoverflow_0002028375_python_sorting.txt
Q: Python: Downloading a large file to a local path and setting custom http headers I am looking to download a file from a http url to a local file. The file is large enough that I want to download it and save it chunks rather than read() and write() the whole file as a single giant string. The interface of urllib.urlretrieve is essentially what I want. However, I cannot see a way to set request headers when downloading via urllib.urlretrieve, which is something I need to do. If I use urllib2, I can set request headers via its Request object. However, I don't see an API in urllib2 to download a file directly to a path on disk like urlretrieve. It seems that instead I will have to use a loop to iterate over the returned data in chunks, writing them to a file myself and checking when we are done. What would be the best way to build a function that works like urllib.urlretrieve but allows request headers to be passed in? A: What is the harm in writing your own function using urllib2? import os import sys import urllib2 def urlretrieve(urlfile, fpath): chunk = 4096 f = open(fpath, "w") while 1: data = urlfile.read(chunk) if not data: print "done." break f.write(data) print "Read %s bytes"%len(data) and using request object to set headers request = urllib2.Request("http://www.google.com") request.add_header('User-agent', 'Chrome XXX') urlretrieve(urllib2.urlopen(request), "/tmp/del.html") A: If you want to use urllib and urlretrieve, subclass urllib.URLopener and use its addheader() method to adjust the headers (ie: addheader('Accept', 'sound/basic'), which I'm pulling from the docstring for urllib.addheader). To install your URLopener for use by urllib, see the example in the urllib._urlopener section of the docs (note the underscore): import urllib class MyURLopener(urllib.URLopener): pass # your override here, perhaps to __init__ urllib._urlopener = MyURLopener However, you'll be pleased to hear wrt your comment to the question comments, reading an empty string from read() is indeed the signal to stop. This is how urlretrieve handles when to stop, for example. TCP/IP and sockets abstract the reading process, blocking waiting for additional data unless the connection on the other end is EOF and closed, in which case read()ing from connection returns an empty string. An empty string means there is no data trickling in... you don't have to worry about ordered packet re-assembly as that has all been handled for you. If that's your concern for urllib2, I think you can safely use it.
Python: Downloading a large file to a local path and setting custom http headers
I am looking to download a file from a http url to a local file. The file is large enough that I want to download it and save it chunks rather than read() and write() the whole file as a single giant string. The interface of urllib.urlretrieve is essentially what I want. However, I cannot see a way to set request headers when downloading via urllib.urlretrieve, which is something I need to do. If I use urllib2, I can set request headers via its Request object. However, I don't see an API in urllib2 to download a file directly to a path on disk like urlretrieve. It seems that instead I will have to use a loop to iterate over the returned data in chunks, writing them to a file myself and checking when we are done. What would be the best way to build a function that works like urllib.urlretrieve but allows request headers to be passed in?
[ "What is the harm in writing your own function using urllib2?\nimport os\nimport sys\nimport urllib2\n\ndef urlretrieve(urlfile, fpath):\n chunk = 4096\n f = open(fpath, \"w\")\n while 1:\n data = urlfile.read(chunk)\n if not data:\n print \"done.\"\n break\n f.write(data)\n print \"Read %s bytes\"%len(data)\n\nand using request object to set headers\nrequest = urllib2.Request(\"http://www.google.com\")\nrequest.add_header('User-agent', 'Chrome XXX')\nurlretrieve(urllib2.urlopen(request), \"/tmp/del.html\")\n\n", "If you want to use urllib and urlretrieve, subclass urllib.URLopener and use its addheader() method to adjust the headers (ie: addheader('Accept', 'sound/basic'), which I'm pulling from the docstring for urllib.addheader).\nTo install your URLopener for use by urllib, see the example in the urllib._urlopener section of the docs (note the underscore):\nimport urllib\n\nclass MyURLopener(urllib.URLopener):\n pass # your override here, perhaps to __init__\n\nurllib._urlopener = MyURLopener\n\nHowever, you'll be pleased to hear wrt your comment to the question comments, reading an empty string from read() is indeed the signal to stop. This is how urlretrieve handles when to stop, for example. TCP/IP and sockets abstract the reading process, blocking waiting for additional data unless the connection on the other end is EOF and closed, in which case read()ing from connection returns an empty string. An empty string means there is no data trickling in... you don't have to worry about ordered packet re-assembly as that has all been handled for you. If that's your concern for urllib2, I think you can safely use it.\n" ]
[ 3, 2 ]
[]
[]
[ "download", "http", "python", "urllib", "urllib2" ]
stackoverflow_0000728118_download_http_python_urllib_urllib2.txt
Q: Can not remove french letters in a string returned by Python glob I would like to rename files with french letters. I am using glob to browse the files and a function I've found on the Internet to remove the french letters. The supprime_accent seems to work ok. However, it doesn't rename files returned by the glob function. Does anybody knows what can be the reason? Is it related with glob encoding? def supprime_accent(ligne): """ supprime les accents du texte source """ accents = { 'a': ['à', 'ã', 'á', 'â'], 'e': ['é', 'è', 'ê', 'ë'], 'i': ['î', 'ï'], 'u': ['ù', 'ü', 'û'], 'o': ['ô', 'ö'] } for (char, accented_chars) in accents.iteritems(): for accented_char in accented_chars: ligne = ligne.replace(accented_char, char) return ligne for file_name in glob.glob("attachments/*.jpg"): print supprime_accent(file_name) A: I see two potential problems here. First, you need to use unicode strings in your source code, and you need to tell Python what encoding the source code is in. Unfortunately doing it right doubles the number of vowels in your table... :-\ # -*- coding: UTF-8 -*- ... accents = { u'a': [u'à', u'ã', u'á', u'â'], u'e': [u'é', u'è', u'ê', u'ë'], u'i': [u'î', u'ï'], u'u': [u'ù', u'ü', u'û'], u'o': [u'ô', u'ö'] } Second, I think you need to convert the filename returned by glob to a unicode string. import sys file_name = file_name.decode(sys.getfilesystemencoding()) Python 3.0 fixed both these problems: filenames don't have to be decoded and unicode strings don't need a u tag. A: try this question and answers to it, in question I have given the final solution I am using latin-1 to ascii and pass a unicode string to glob, to get unicode file names back e.g. for file_name in glob.glob(u"attachments/*.jpg"): print file_name.encode('ascii', 'latin2ascii') A: I've succeed to fix the problem by converting file_name to unicode with cp1252 enncoding. for file_name in glob.glob("attachments/*.jpg"): file_name = file_name.decode(sys.getfilesystemencoding()) print unicodedata.normalize('NFKD', file_name).encode('ascii','ignore') Edit: Jason gave a better solution by replacing unicode(file_name, 'cp1252') with file_name.decode(sys.getfilesystemencoding())
Can not remove french letters in a string returned by Python glob
I would like to rename files with french letters. I am using glob to browse the files and a function I've found on the Internet to remove the french letters. The supprime_accent seems to work ok. However, it doesn't rename files returned by the glob function. Does anybody knows what can be the reason? Is it related with glob encoding? def supprime_accent(ligne): """ supprime les accents du texte source """ accents = { 'a': ['à', 'ã', 'á', 'â'], 'e': ['é', 'è', 'ê', 'ë'], 'i': ['î', 'ï'], 'u': ['ù', 'ü', 'û'], 'o': ['ô', 'ö'] } for (char, accented_chars) in accents.iteritems(): for accented_char in accented_chars: ligne = ligne.replace(accented_char, char) return ligne for file_name in glob.glob("attachments/*.jpg"): print supprime_accent(file_name)
[ "I see two potential problems here.\nFirst, you need to use unicode strings in your source code, and you need to tell Python what encoding the source code is in. Unfortunately doing it right doubles the number of vowels in your table... :-\\\n# -*- coding: UTF-8 -*-\n...\naccents = { u'a': [u'à', u'ã', u'á', u'â'],\n u'e': [u'é', u'è', u'ê', u'ë'],\n u'i': [u'î', u'ï'],\n u'u': [u'ù', u'ü', u'û'],\n u'o': [u'ô', u'ö'] }\n\nSecond, I think you need to convert the filename returned by glob to a unicode string.\nimport sys\nfile_name = file_name.decode(sys.getfilesystemencoding())\n\nPython 3.0 fixed both these problems: filenames don't have to be decoded and unicode strings don't need a u tag.\n", "try this question and answers to it, in question I have given the final solution I am using\nlatin-1 to ascii\nand pass a unicode string to glob, to get unicode file names back e.g.\nfor file_name in glob.glob(u\"attachments/*.jpg\"):\n print file_name.encode('ascii', 'latin2ascii')\n\n", "I've succeed to fix the problem by converting file_name to unicode with cp1252 enncoding.\nfor file_name in glob.glob(\"attachments/*.jpg\"):\n file_name = file_name.decode(sys.getfilesystemencoding())\n print unicodedata.normalize('NFKD', file_name).encode('ascii','ignore')\n\nEdit: Jason gave a better solution by replacing unicode(file_name, 'cp1252') with file_name.decode(sys.getfilesystemencoding())\n" ]
[ 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002028503_python.txt