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: csv utf-8 writer - compability with python2.4 At the bottom of this manual http://docs.python.org/library/csv.html we have example of UnicodeWriter But how can i use this example in python 2.4 I got exception about codecs.getincrementalencoder(encoding)(). Property getincrementalencoder created only in version 2.5. Who can replace this property? Thanks! A: Not sure if it will work, but try to use codecs.getencoder instead.
csv utf-8 writer - compability with python2.4
At the bottom of this manual http://docs.python.org/library/csv.html we have example of UnicodeWriter But how can i use this example in python 2.4 I got exception about codecs.getincrementalencoder(encoding)(). Property getincrementalencoder created only in version 2.5. Who can replace this property? Thanks!
[ "Not sure if it will work, but try to use codecs.getencoder instead.\n" ]
[ 1 ]
[]
[]
[ "csv", "python", "utf_8" ]
stackoverflow_0001910610_csv_python_utf_8.txt
Q: Import error with virtualenv I have a problem with virtualenv. I use it regulary, I use it on my development machine and on several servers. But on this last server I tried to use i got a problem. I created a virtualenv with the --no-site-packages argument, and then I installed some python modules inside the virtualenv. I can confirm that the modules is located inside the virtualenvs site-packages and everything seems to be fine. But when i try to do:source virtualenv/bin/activate and then import one of the module python import modulename i get an import error that says that the module doesnt exist. How is it that this is happending? It seems like it never activates even thoug that it says it do. Anybody have a clue on how to fix this? A: Is there a bash alias active on this machine for "python", by any chance? That will take priority over the PATH-modifications made by activate, and could cause the wrong python binary to be used. Try running virtualenv/bin/python directly (no need to activate) and see if you can import your module. If this fixes it, you just need to get rid of your python bash alias. A: After activating the virtual env, try: $ python >>> import sys >>> sys.executable ... ... and see if you are running the expected executable. Also check: >>> sys.path [...] A: IIRC, the activate script just puts your virtual env first on your path, so when you type "python" it finds the one in your virtual env first. If the activate script fails, you can always edit your path manually. Also - go here and search for "activate": http://pylonsbook.com/en/1.1/installing-pylons.html#setting-up-a-virtual-python-environment. This will tell you why the activate command can fail.
Import error with virtualenv
I have a problem with virtualenv. I use it regulary, I use it on my development machine and on several servers. But on this last server I tried to use i got a problem. I created a virtualenv with the --no-site-packages argument, and then I installed some python modules inside the virtualenv. I can confirm that the modules is located inside the virtualenvs site-packages and everything seems to be fine. But when i try to do:source virtualenv/bin/activate and then import one of the module python import modulename i get an import error that says that the module doesnt exist. How is it that this is happending? It seems like it never activates even thoug that it says it do. Anybody have a clue on how to fix this?
[ "Is there a bash alias active on this machine for \"python\", by any chance? That will take priority over the PATH-modifications made by activate, and could cause the wrong python binary to be used.\nTry running virtualenv/bin/python directly (no need to activate) and see if you can import your module.\nIf this fixes it, you just need to get rid of your python bash alias.\n", "After activating the virtual env, try:\n$ python\n>>> import sys\n>>> sys.executable\n...\n\n... and see if you are running the expected executable.\nAlso check:\n>>> sys.path\n[...]\n\n", "IIRC, the activate script just puts your virtual env first on your path, so when you type \"python\" it finds the one in your virtual env first. If the activate script fails, you can always edit your path manually. Also - go here and search for \"activate\": http://pylonsbook.com/en/1.1/installing-pylons.html#setting-up-a-virtual-python-environment. This will tell you why the activate command can fail.\n" ]
[ 22, 10, 0 ]
[]
[]
[ "python", "virtualenv" ]
stackoverflow_0001909025_python_virtualenv.txt
Q: How to do this GROUP BY query in Django's ORM with annotate and aggregate I don't really have groked how to translate GROUP BY and HAVING to Django's QuerySet.annotate and QuerySet.aggregate. I'm trying to translate this SQL query into ORM speak SELECT EXTRACT(year FROM pub_date) as year, EXTRACT(month from pub_date) as month, COUNT(*) as article_count FROM articles_article GROUP BY year,month; which outputs this: [(2008.0, 10.0, 1L), # year, month, number of articles (2009.0, 2.0, 1L), (2009.0, 7.0, 1L), (2008.0, 5.0, 3L), (2008.0, 9.0, 1L), (2008.0, 7.0, 1L), (2009.0, 5.0, 1L), (2008.0, 8.0, 1L), (2009.0, 12.0, 2L), (2009.0, 3.0, 1L), (2007.0, 12.0, 1L), (2008.0, 6.0, 1L), (2009.0, 4.0, 2L), (2008.0, 3.0, 1L)] My Django model: class Article(models.Model): title = models.CharField(max_length=150, verbose_name=_("title")) # ... more pub_date = models.DateTimeField(verbose_name=_('publishing date')) This project should run on a couple of different DB systems, so I'm trying to stay away from pure SQL as much as possible. A: I think to do it in one query you might have to have month and year as separate fields... Article.objects.values('pub_date').annotate(article_count=Count('title')) That would group by by pub_date. But there is no way I can think of to do the equivalent of the extract function clause inline there. If your model were: class Article(models.Model): title = models.CharField(max_length=150, verbose_name=_("title")) # ... more pub_date = models.DateTimeField(verbose_name=_('publishing date')) pub_year = models.IntegerField() pub_month = models.IntegerField() Then you could do: Article.objects.values('pub_year', 'pub_month').annotate(article_count=Count('title')) If you are going to do this, I would recommend having pub_year and pub_month be automatically populated by overriding the save() method for Article and extracting the values from pub_date. Edit: One way to do it is to use extra; but it won't grant you database independence... models.Issue.objects.extra(select={'year': "EXTRACT(year FROM pub_date)", 'month': "EXTRACT(month from pub_date)"}).values('year', 'month').annotate(Count('title')) While this will work, I think (untested), it will require you to modify the extra fields if you ever change database servers. For instance, in SQL Server you would do year(pub_date) instead of extract(year from pub_date)... This might not be so bad if you come up with a custom model manager that you prominently tag as requiring such database engine dependent changes. A: You can make an extract with dates: http://docs.djangoproject.com/en/dev/ref/models/querysets/#dates-field-kind-order-asc
How to do this GROUP BY query in Django's ORM with annotate and aggregate
I don't really have groked how to translate GROUP BY and HAVING to Django's QuerySet.annotate and QuerySet.aggregate. I'm trying to translate this SQL query into ORM speak SELECT EXTRACT(year FROM pub_date) as year, EXTRACT(month from pub_date) as month, COUNT(*) as article_count FROM articles_article GROUP BY year,month; which outputs this: [(2008.0, 10.0, 1L), # year, month, number of articles (2009.0, 2.0, 1L), (2009.0, 7.0, 1L), (2008.0, 5.0, 3L), (2008.0, 9.0, 1L), (2008.0, 7.0, 1L), (2009.0, 5.0, 1L), (2008.0, 8.0, 1L), (2009.0, 12.0, 2L), (2009.0, 3.0, 1L), (2007.0, 12.0, 1L), (2008.0, 6.0, 1L), (2009.0, 4.0, 2L), (2008.0, 3.0, 1L)] My Django model: class Article(models.Model): title = models.CharField(max_length=150, verbose_name=_("title")) # ... more pub_date = models.DateTimeField(verbose_name=_('publishing date')) This project should run on a couple of different DB systems, so I'm trying to stay away from pure SQL as much as possible.
[ "I think to do it in one query you might have to have month and year as separate fields...\nArticle.objects.values('pub_date').annotate(article_count=Count('title'))\n\nThat would group by by pub_date. But there is no way I can think of to do the equivalent of the extract function clause inline there.\nIf your model were:\nclass Article(models.Model):\n title = models.CharField(max_length=150, verbose_name=_(\"title\"))\n # ... more \n pub_date = models.DateTimeField(verbose_name=_('publishing date'))\n pub_year = models.IntegerField()\n pub_month = models.IntegerField()\n\nThen you could do:\nArticle.objects.values('pub_year', 'pub_month').annotate(article_count=Count('title'))\n\nIf you are going to do this, I would recommend having pub_year and pub_month be automatically populated by overriding the save() method for Article and extracting the values from pub_date.\n\nEdit:\nOne way to do it is to use extra; but it won't grant you database independence...\nmodels.Issue.objects.extra(select={'year': \"EXTRACT(year FROM pub_date)\", 'month': \"EXTRACT(month from pub_date)\"}).values('year', 'month').annotate(Count('title'))\n\nWhile this will work, I think (untested), it will require you to modify the extra fields if you ever change database servers. For instance, in SQL Server you would do year(pub_date) instead of extract(year from pub_date)...\nThis might not be so bad if you come up with a custom model manager that you prominently tag as requiring such database engine dependent changes.\n", "You can make an extract with dates: \nhttp://docs.djangoproject.com/en/dev/ref/models/querysets/#dates-field-kind-order-asc\n" ]
[ 14, 2 ]
[]
[]
[ "django", "group_by", "orm", "python" ]
stackoverflow_0001908741_django_group_by_orm_python.txt
Q: Inlines Python/Django technique for objects I am reading the source code of the Django application blog at git://github.com/nathanborror/django-basic-apps.git. How do you read the following Django code? {% tags_for_object object as tag_list %} My attempt: Make the variable object of the type tags_for_object and rename the variable to tag_list. The object apparently is based on the file blog/templates/inlines/default.html: {% if object %} {{ object }} {% else %} {% for object in object_list %} {{ object }} {% endfor %} {% endif %} What is the befefit of putting the logic to two-step procedure: run single object, else loop through a list of objects? A: It looks like tags_for_object is the template tag from the django-tagging application. From the django-tagging documentation: tags_for_object: Retrieves a list of Tag objects associated with an object and stores them in a context variable. Usage: {% tags_for_object [object] as [varname] %} Example: {% tags_for_object foo_object as tag_list %} You can then loop through the tag_list variable in the template to display the tags. {% tags_for_object foo_object as tag_list %} <ul> {% for tag in tag_list %} <li>{{ tag }}</li> {% endfor %} </ul> For the second part of your question, you understand the code correctly. If the variable object exists in the context (and doesn't evaluate to False), it is displayed. If it does not exist in the context (or if it evaluates to False), then the code loops through the objects in object_list, and displays them. As for why you would want to do this, you would have to look at the code that uses inlines/default.html to work out what the designer had in mind.
Inlines Python/Django technique for objects
I am reading the source code of the Django application blog at git://github.com/nathanborror/django-basic-apps.git. How do you read the following Django code? {% tags_for_object object as tag_list %} My attempt: Make the variable object of the type tags_for_object and rename the variable to tag_list. The object apparently is based on the file blog/templates/inlines/default.html: {% if object %} {{ object }} {% else %} {% for object in object_list %} {{ object }} {% endfor %} {% endif %} What is the befefit of putting the logic to two-step procedure: run single object, else loop through a list of objects?
[ "It looks like tags_for_object is the template tag from the django-tagging application.\nFrom the django-tagging documentation:\n\ntags_for_object:\nRetrieves a list of Tag objects\n associated with an object and stores\n them in a context variable.\nUsage:\n{% tags_for_object [object] as [varname] %}\n\nExample:\n{% tags_for_object foo_object as tag_list %}\n\n\nYou can then loop through the tag_list variable in the template to display the tags.\n{% tags_for_object foo_object as tag_list %}\n\n<ul>\n{% for tag in tag_list %}\n <li>{{ tag }}</li>\n{% endfor %}\n</ul>\n\n\nFor the second part of your question, you understand the code correctly. If the variable object exists in the context (and doesn't evaluate to False), it is displayed. If it does not exist in the context (or if it evaluates to False), then the code loops through the objects in object_list, and displays them. \nAs for why you would want to do this, you would have to look at the code that uses inlines/default.html to work out what the designer had in mind.\n" ]
[ 4 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001910953_django_python.txt
Q: concatenate items in dictionary in python using list comprehension EDIT: Clarified the question a bit How can I get a string from a dictionary with the format key1 = value1 key2 = value2 in a relatively fast way ? (relative to plain concatenation) A: print '\n'.join('%s = %s' % (key, value) for key, value in d.iteritems()) A: There's no reason to use list comprehension here. Python 3.x: for k,v in mydict.items(): print(k, '=', v) Python 2.x: for k,v in mydict.iteritems(): print k, '=', v EDIT because of comment by OP in another answer: If you're passing it to a function and not printing it here, then you should just pass the generator to the function, or the dict itself and let the function handle whatever it needs to do with it. This is much better than converting it to a string inside a scope where it's not even needed. The function should do that, since that's where it's used. I made a wrapper function, since editing the main function is out of the question. def log_wrap(mydict): mystr = '\n'.join(['%s = %s' % (k,v) for k,v in mydict.iteritems()]) write_to_log(mydict) log_wrap(mydict) A: Explicit is better than implicit List comprehension is a way to create list, not to avoid loops. From PEP 202: List comprehensions provide a more concise way to create lists in situations where map() and filter() and/or nested loops would currently be used. So you should ask yourself: When is it useful to create this code in Python? It may be more compact but code is read many more times than it is written so what is the advantage in it? Tor Valamo's solution, although not what was asked for in the original request, is in my opinion far more readable, and therefore should be preferred. EDIT after question update str.join is a good way to implement a fast concatenation from a list - and replies from Nadia and Ritchie are good examples of how to use it. Again, I would not perform everything in a single line, but I would split it in various steps to emphasize readability. A: Like this: DATA = {'key1': 'value1', 'key2': 'value2'} print "\n".join(sorted(["%s = %s" % (k,v) for (k,v) in DATA.iteritems()])) A: I prefer the pythonic way: mydict = {'a':1, 'b':2, 'c':3} for (key, value) in mydict.items(): print key, '=', value
concatenate items in dictionary in python using list comprehension
EDIT: Clarified the question a bit How can I get a string from a dictionary with the format key1 = value1 key2 = value2 in a relatively fast way ? (relative to plain concatenation)
[ "print '\\n'.join('%s = %s' % (key, value) for key, value in d.iteritems())\n\n", "There's no reason to use list comprehension here.\nPython 3.x:\nfor k,v in mydict.items():\n print(k, '=', v)\n\nPython 2.x:\nfor k,v in mydict.iteritems():\n print k, '=', v\n\nEDIT because of comment by OP in another answer:\nIf you're passing it to a function and not printing it here, then you should just pass the generator to the function, or the dict itself and let the function handle whatever it needs to do with it. \nThis is much better than converting it to a string inside a scope where it's not even needed. The function should do that, since that's where it's used.\nI made a wrapper function, since editing the main function is out of the question.\ndef log_wrap(mydict):\n mystr = '\\n'.join(['%s = %s' % (k,v) for k,v in mydict.iteritems()])\n write_to_log(mydict)\n\nlog_wrap(mydict)\n\n", "Explicit is better than implicit\nList comprehension is a way to create list, not to avoid loops.\nFrom PEP 202:\n\nList comprehensions provide a more\n concise way to create lists in\n situations where map() and filter()\n and/or nested loops would currently be\n used.\n\nSo you should ask yourself:\nWhen is it useful to create this code in Python? It may be more compact but code is read many more times than it is written so what is the advantage in it?\nTor Valamo's solution, although not what was asked for in the original request, is in my opinion far more readable, and therefore should be preferred.\nEDIT after question update\nstr.join is a good way to implement a fast concatenation from a list - and replies from Nadia and Ritchie are good examples of how to use it.\nAgain, I would not perform everything in a single line, but I would split it in various steps to emphasize readability.\n", "Like this:\nDATA = {'key1': 'value1', 'key2': 'value2'}\nprint \"\\n\".join(sorted([\"%s = %s\" % (k,v) for (k,v) in DATA.iteritems()]))\n\n", "I prefer the pythonic way:\nmydict = {'a':1, 'b':2, 'c':3}\nfor (key, value) in mydict.items():\n print key, '=', value\n\n" ]
[ 10, 10, 3, 2, 0 ]
[]
[]
[ "list_comprehension", "python" ]
stackoverflow_0001911014_list_comprehension_python.txt
Q: Facebook application Django server connection I am creating a Facebook application in Python and Django. I followed all the instructions mentioned on this page: http://wiki.developers.facebook.com/index.php/User:PyFacebook_Tutorial. But it ended up giving me this error: The URL http://amitverma.dyndns.org/fbsample/?auth_token=0e80c8dbba442763d2c539d6e64e992a is not valid. Please try again later. We appreciate your patience as the developers of roadies and Facebook resolve this issue. Thanks! Now here is the lowdown: I am on a ADSL modem/routed network with dynamic addressing. I tried to forward my port, 80 and 8080 on 192.168.2.2. That's my static IP address. I guess this is not visible from the Internet. Then I created a dynamic DNS through DynDNS, : amitverma.dyndns.org, but still no go. I have to run a simple server of sorts to make Django run. I make the server run like this: python manage.py runserver 0.0.0.0:80. The 0.0.0.0 is the IP address and 80 is the port number. What should I enter in the Facebook application edit settings page in the field that says Canvas page URL? My Facebook application canvas URL is: amitverma.dyndns.org/fbsample/. When I access it, it gives me the above error. I have spent the last 10 hours fiddling with this and still can't seem to make it run. PS: Please don't say it's not a programming question. I think more than networking, it's something else I am doing wrong.. A: You need to troubleshoot from somewhere outside your development box and local network. You need to figure out if this is a DNS issue, a port forwarding issue, or perhaps an issue on your dev. box (is a local firewall blocking the requests?). From a network location outside your home network, connect using the router's public IP address to see if the port forwarding works. try to ping the dns address, check that it resolves correctly etc. You could create a Amazon EC2 virtual machine and do the troubleshooting from there (that will be your 'outside' network location). EDIT: You have dyndns set up wrong. $ nslookup amitverma.dyndns.org Server: 10.0.0.1 Address: 10.0.0.1#53 Non-authoritative answer: Name: amitverma.dyndns.org Address: 192.168.1.5 192.168.* is your internal IP address (it is in the reserved private IPv4 address space). DNS should point to your router's public IP address. http://whatismyipaddress.com/ will tell you what your router's public IP address is at the moment.
Facebook application Django server connection
I am creating a Facebook application in Python and Django. I followed all the instructions mentioned on this page: http://wiki.developers.facebook.com/index.php/User:PyFacebook_Tutorial. But it ended up giving me this error: The URL http://amitverma.dyndns.org/fbsample/?auth_token=0e80c8dbba442763d2c539d6e64e992a is not valid. Please try again later. We appreciate your patience as the developers of roadies and Facebook resolve this issue. Thanks! Now here is the lowdown: I am on a ADSL modem/routed network with dynamic addressing. I tried to forward my port, 80 and 8080 on 192.168.2.2. That's my static IP address. I guess this is not visible from the Internet. Then I created a dynamic DNS through DynDNS, : amitverma.dyndns.org, but still no go. I have to run a simple server of sorts to make Django run. I make the server run like this: python manage.py runserver 0.0.0.0:80. The 0.0.0.0 is the IP address and 80 is the port number. What should I enter in the Facebook application edit settings page in the field that says Canvas page URL? My Facebook application canvas URL is: amitverma.dyndns.org/fbsample/. When I access it, it gives me the above error. I have spent the last 10 hours fiddling with this and still can't seem to make it run. PS: Please don't say it's not a programming question. I think more than networking, it's something else I am doing wrong..
[ "You need to troubleshoot from somewhere outside your development box and local network. You need to figure out if this is a DNS issue, a port forwarding issue, or perhaps an issue on your dev. box (is a local firewall blocking the requests?).\nFrom a network location outside your home network, connect using the router's public IP address to see if the port forwarding works. try to ping the dns address, check that it resolves correctly etc. \nYou could create a Amazon EC2 virtual machine and do the troubleshooting from there (that will be your 'outside' network location).\nEDIT:\nYou have dyndns set up wrong.\n$ nslookup amitverma.dyndns.org\nServer: 10.0.0.1\nAddress: 10.0.0.1#53\n\nNon-authoritative answer:\nName: amitverma.dyndns.org\nAddress: 192.168.1.5\n\n192.168.* is your internal IP address (it is in the reserved private IPv4 address space). DNS should point to your router's public IP address. http://whatismyipaddress.com/ will tell you what your router's public IP address is at the moment.\n" ]
[ 0 ]
[]
[]
[ "django", "facebook", "networking", "python" ]
stackoverflow_0001910846_django_facebook_networking_python.txt
Q: python checking for files learning python there. I want to write a script to check if my webserver has picture named in the root 123.jpg I have: import urllib2 numeruks=100 adresiuks="http://localhost/" + str(numeruks) +".jpg" try: if numeruks < 150: numeruks = numeruks + 1 urllib2.urlopen(adresiuks).read() reading manuals all day, can't solve it :( A: You can test for 404 in your attempts to access the URL (and without even having to issue a read()): import urllib2 n = 123 try: url = 'http://localhost/%d.jpg' % n urllib2.urlopen(url) except urllib2.HTTPError, e: if e.code == 404: print '%d.jpg was not found' % n else: raise # if the issue wasn't a 404, then re-raise the exception A: Is this code standing on its own? If so, you're missing a loop. Also, as codeape said, the indentation is wrong and you need an except or a finally. If you want to check all of the numbers between 100 and 150, you'll need to loop over them. Your code as it stands now only updates numeruks once, and never updates adresiuks at all. If you want to check for an error with a try, you need to follow it up with an except, which can be as simple as pass (but will more likely be continue). I'm a little hesitant to give you the actual code, as if you're learning, you'll probably learn it better if you figure it out yourself. ;) A: After you increment numeruks you should reset the adresiuks. I.E.: adresiuks="http://localhost/" + str(numeruks) + ".jpg" try: if numeruks < 150: numeruks = numeruks + 1 adresiuks = "http://localhost/" + str(numeruks) + ".jpg" print adresiuks urllib2.urlopen(adresiuks).read() Double check the file is available using your web browser. For example my web server is listening on port 8000 so I have to add the port, i.e. http://localhost:8000/123.jpg. Here is a simple running script, because it is a .jpg it will be garbage that is printed: import urllib2 numeruks = 123 adresiuks = "http://localhost/" + str(numeruks) + ".jpg" print adresiuks thefile = urllib2.urlopen(adresiuks).read() print thefile
python checking for files
learning python there. I want to write a script to check if my webserver has picture named in the root 123.jpg I have: import urllib2 numeruks=100 adresiuks="http://localhost/" + str(numeruks) +".jpg" try: if numeruks < 150: numeruks = numeruks + 1 urllib2.urlopen(adresiuks).read() reading manuals all day, can't solve it :(
[ "You can test for 404 in your attempts to access the URL (and without even having to issue a read()):\nimport urllib2\n\nn = 123\n\ntry:\n url = 'http://localhost/%d.jpg' % n\n urllib2.urlopen(url)\nexcept urllib2.HTTPError, e:\n if e.code == 404:\n print '%d.jpg was not found' % n\n else:\n raise # if the issue wasn't a 404, then re-raise the exception\n\n", "Is this code standing on its own? If so, you're missing a loop. Also, as codeape said, the indentation is wrong and you need an except or a finally.\nIf you want to check all of the numbers between 100 and 150, you'll need to loop over them. Your code as it stands now only updates numeruks once, and never updates adresiuks at all. If you want to check for an error with a try, you need to follow it up with an except, which can be as simple as pass (but will more likely be continue).\nI'm a little hesitant to give you the actual code, as if you're learning, you'll probably learn it better if you figure it out yourself. ;)\n", "After you increment numeruks you should reset the adresiuks.\nI.E.:\nadresiuks=\"http://localhost/\" + str(numeruks) + \".jpg\" \ntry: \n if numeruks < 150: \n numeruks = numeruks + 1 \n adresiuks = \"http://localhost/\" + str(numeruks) + \".jpg\" \n print adresiuks \n urllib2.urlopen(adresiuks).read() \n\nDouble check the file is available using your web browser. \nFor example my web server is listening on port 8000 so I have to add the port, i.e. \nhttp://localhost:8000/123.jpg.\nHere is a simple running script, because it is a .jpg it will be garbage that is printed:\nimport urllib2 \nnumeruks = 123 \nadresiuks = \"http://localhost/\" + str(numeruks) + \".jpg\" \nprint adresiuks \nthefile = urllib2.urlopen(adresiuks).read()\nprint thefile \n\n" ]
[ 1, 1, 0 ]
[]
[]
[ "python", "urllib2" ]
stackoverflow_0001911396_python_urllib2.txt
Q: Python: How do I find why IDLE restarts? I am using python 2.5 on windows. All I am doing is unpickling a large file (18MB - a list of dictionaries) and modifiying some of its values. Now this works fine. But when I add a couple of prints, IDLE restarts. And weirdly enough it seems to be happening where I added the print. I figured this out commenting and uncommenting things line by line. I added a try catch around the print, but am not able to catch anything. When does IDLE restart? And how do I catch any exceptions or errors it throws(if it does)? A: Have you tried running your script from the command line rather than IDLE? Open a command prompt and type python to enter the Python interpreter. See if it crashes there too. Secondly, you should try using the pdb module for debugging your Python scripts. This is far more effective than print statements since you can step through your code and check values at any point during the debug session. import pdb test_var = 'this is a test' # set this whenever you want to start a breakpoint pdb.set_trace() In a pdb debug session you can step through lines by pressing 'n' and print values directly using the print statement. For example, you could: > print test_var 'this is a test' A: Enable the debugger and see if it tells you anything.
Python: How do I find why IDLE restarts?
I am using python 2.5 on windows. All I am doing is unpickling a large file (18MB - a list of dictionaries) and modifiying some of its values. Now this works fine. But when I add a couple of prints, IDLE restarts. And weirdly enough it seems to be happening where I added the print. I figured this out commenting and uncommenting things line by line. I added a try catch around the print, but am not able to catch anything. When does IDLE restart? And how do I catch any exceptions or errors it throws(if it does)?
[ "Have you tried running your script from the command line rather than IDLE? Open a command prompt and type python to enter the Python interpreter. See if it crashes there too.\nSecondly, you should try using the pdb module for debugging your Python scripts. This is far more effective than print statements since you can step through your code and check values at any point during the debug session.\nimport pdb\n\ntest_var = 'this is a test'\n\n# set this whenever you want to start a breakpoint\npdb.set_trace()\n\nIn a pdb debug session you can step through lines by pressing 'n' and print values directly using the print statement. For example, you could:\n> print test_var\n'this is a test'\n\n", "Enable the debugger and see if it tells you anything.\n" ]
[ 1, 0 ]
[]
[]
[ "python", "python_idle" ]
stackoverflow_0001911615_python_python_idle.txt
Q: What is the best way to store database settings with Django? I'm attempting to write a browser game using Django but I'm getting a bit stuck on how to store the settings for the game. For example, the game is tick based and I want to store the current tick. I have decided that I want only one game per database to avoid problems with the built-in user authorisation system (e.g. I don't want to say username X is unavailable because it is already used in a different game). As far as I can tell, I still need to store this information in a database table, but I'm not sure how to best do that. I seem to have 2 options: A) Have the game as a normal model referenced by other tables (e.g. my User profile), and just ignore the possibility that there can be more than 1 game. This would mean that it would be technically possible to have 2 game rows, but if there were things would break very easily. B) I have a model that I always assume has one and only one row which stores all the configuration data for the game. This model only contains static methods and none of the other models have references to it. E.g.: class Game(models.Model): current_slot = models.PositiveIntegerField(default=0) @staticmethod def slots_per_day(self): Genre.objects.get(id=1).current_slot Neither of these options seem "right" to me but can anyone tell me if one is better than the other? Or if there is another option I haven't seen yet? A: You could be a bit more generic and just have a "Setting" record. This would allow you to expand the amount of settings you could store infinitely. class Setting(models.Model): name = models.CharField(max_length=50) value = models.TextField() # ... # Get the current slot setting current_slot = Setting.objects.get(name='current_slot').value # ... # Or wrap it in a helper method def get_setting(name, default_value): try: return Setting.objects.get(name=name).value except: return default_value current_slot = get_setting('current_slot', 0) A: I don't understand why you need one database per game. Why not have a Games table with one row per game, and have all other data tables reference the game_id of the game they're associated with?
What is the best way to store database settings with Django?
I'm attempting to write a browser game using Django but I'm getting a bit stuck on how to store the settings for the game. For example, the game is tick based and I want to store the current tick. I have decided that I want only one game per database to avoid problems with the built-in user authorisation system (e.g. I don't want to say username X is unavailable because it is already used in a different game). As far as I can tell, I still need to store this information in a database table, but I'm not sure how to best do that. I seem to have 2 options: A) Have the game as a normal model referenced by other tables (e.g. my User profile), and just ignore the possibility that there can be more than 1 game. This would mean that it would be technically possible to have 2 game rows, but if there were things would break very easily. B) I have a model that I always assume has one and only one row which stores all the configuration data for the game. This model only contains static methods and none of the other models have references to it. E.g.: class Game(models.Model): current_slot = models.PositiveIntegerField(default=0) @staticmethod def slots_per_day(self): Genre.objects.get(id=1).current_slot Neither of these options seem "right" to me but can anyone tell me if one is better than the other? Or if there is another option I haven't seen yet?
[ "You could be a bit more generic and just have a \"Setting\" record. This would allow you to expand the amount of settings you could store infinitely.\nclass Setting(models.Model):\n name = models.CharField(max_length=50)\n value = models.TextField()\n\n# ...\n\n# Get the current slot setting\ncurrent_slot = Setting.objects.get(name='current_slot').value\n\n# ...\n\n# Or wrap it in a helper method\ndef get_setting(name, default_value):\n try:\n return Setting.objects.get(name=name).value\n except:\n return default_value\n\ncurrent_slot = get_setting('current_slot', 0)\n\n", "I don't understand why you need one database per game. Why not have a Games table with one row per game, and have all other data tables reference the game_id of the game they're associated with?\n" ]
[ 7, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001911652_django_python.txt
Q: How do add multiple fields to a Form when trying to validate data? What is the best way to have the IP address be included with the Form is_valid. Let me start with some code examples. urls.py from django.conf.urls.defaults import * from testpost.views import TestPost urlpatterns = patterns('', (r'^djtestforms/', TestPost), ) model.py from django.db import models class TestPostModel(models.Model): name = models.CharField(max_length=100) comment = models.CharField(max_length=100) ip_address = models.IPAddressField() def __unicode__(self): return self.model @models.permalink def get_absolute_url(self): return ('TestPostModel', [self.id]) forms.py from django import forms from models import TestPostModel class TestPostForm(forms.ModelForm): class Meta: model = TestPostModel from forms import TestPostForm from models import TestPostModel from django.http import HttpResponse def TestPost(request): f = TestPostForm(request.POST) if f.is_valid(): object = f.save() return HttpResponse("That worked") else: return HttpResponse("That didn't work") My question is when I try to do "f=TestPostForm(request.POST)" what is the best way to have the IP address added to TestPostForm. I was thinking of something along the lines of "f = TestPostForm(request.POST, ip_address=request.META["REMOTE_ADDR"])" but that doesn't work. Any suggestions? A: @czarchaic - Your'e answer gave me a good hint on what to do. I changed the model so that blank=True for ip_address, and then did a f = TestPostForm(request.POST) f.data['ip_address']=request.META['REMOTE_ADDR'] After that is_valid worked. Thanks. A: Save with commit=False form=TestPostForm(data=request.POST) if form.is_valid(): object=form.save(commit=False) object.ip_address=request.META['REMOTE_ADDR'] object.save() You will probably need to set blank=True in the model or required=False in the form for the form to validate
How do add multiple fields to a Form when trying to validate data?
What is the best way to have the IP address be included with the Form is_valid. Let me start with some code examples. urls.py from django.conf.urls.defaults import * from testpost.views import TestPost urlpatterns = patterns('', (r'^djtestforms/', TestPost), ) model.py from django.db import models class TestPostModel(models.Model): name = models.CharField(max_length=100) comment = models.CharField(max_length=100) ip_address = models.IPAddressField() def __unicode__(self): return self.model @models.permalink def get_absolute_url(self): return ('TestPostModel', [self.id]) forms.py from django import forms from models import TestPostModel class TestPostForm(forms.ModelForm): class Meta: model = TestPostModel from forms import TestPostForm from models import TestPostModel from django.http import HttpResponse def TestPost(request): f = TestPostForm(request.POST) if f.is_valid(): object = f.save() return HttpResponse("That worked") else: return HttpResponse("That didn't work") My question is when I try to do "f=TestPostForm(request.POST)" what is the best way to have the IP address added to TestPostForm. I was thinking of something along the lines of "f = TestPostForm(request.POST, ip_address=request.META["REMOTE_ADDR"])" but that doesn't work. Any suggestions?
[ "@czarchaic - Your'e answer gave me a good hint on what to do. I changed the model so that blank=True for ip_address, and then did a \nf = TestPostForm(request.POST)\nf.data['ip_address']=request.META['REMOTE_ADDR']\n\nAfter that is_valid worked. Thanks.\n", "Save with commit=False\nform=TestPostForm(data=request.POST)\nif form.is_valid():\n object=form.save(commit=False)\n object.ip_address=request.META['REMOTE_ADDR']\n object.save()\n\nYou will probably need to set blank=True in the model or required=False in the form for the form to validate\n" ]
[ 2, -1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001911383_django_python.txt
Q: More efficient way to count intersections? I have a list of 300000 lists (fiber tracks), where each track is a list of (x,y,z) tuples/coordinates: tracks= [[(1,2,3),(3,2,4),...] [(4,2,1),(5,7,3),...] ... ] I also have a group of masks, where each mask is defined as a list of (x,y,z) tuples/coordinates: mask_coords_list= [[(1,2,3),(8,13,4),...] [(6,2,2),(5,7,3),...] ... ] I am trying to find, for all possible pairs of masks: the number of tracks that intersect each mask-mask pair (to create a connectivity matrix) the subset of tracks that intersect each mask, in order to add 1 to each (x,y,z) coordinate for each track in the subset (to create a "density" image) I'm currently doing part 1 like so: def mask_connectivity_matrix(tracks,masks,masks_coords_list): connect_mat=zeros((len(masks),len(masks))) for track in tracks: cur=[] for count,mask_coords in enumerate(masks_coords_list): if any(set(track) & set(mask_coords)): cur.append(count) for x,y in list(itertools.combinations(cur,2)): connect_mat[x,y] += 1 and part 2 like so: def mask_tracks(tracks,masks,masks_coords_list): vox_tracks_img=zeros((xdim,ydim,zdim,len(masks))) for track in tracks: for count,mask in enumerate(masks_coords_list): if any(set(track) & set(mask)): for x,y,z in track: vox_tracks_img[x,y,z,count] += 1 Using sets to find intersections has sped this process up significantly but both portions still take over an hour when I have a list of 70 or more masks. Is there a more efficient way to do this than iterating for each track? A: Linearize the voxel coordinates, and put them into two scipy.sparse.sparse.csc matrices. Let v be the number of voxels, m the number of masks, and t the number of tracks. Let M be the mask csc matrix, size (m x v), where a 1 at (i,j) means mask i overlaps voxel j. Let T be the track csc matrix, size (t x v), where a 1 at (k,j) means track k overlaps voxel j. Overlap = (M * T.transpose() > 0) # track T overlaps mask M Connected = (Overlap * Overlap.tranpose() > 0) # Connected masks Density[mask_idx] = numpy.take(T, nonzero(Overlap[mask_idx, :])[0], axis=0).sum(axis=0) I might be wrong on the last one, and I'm not sure css_matrices can be operated on by nonzero & take. You might need to pull out each column in a loop and convert it to a full matrix. I ran some experiments trying to simulate what I thought was a reasonable amount of data. The code below takes about 2 minutes on a 2-year old MacBook. If you use csr_matrices, it takes about 4 minutes. There is probably a tradeoff depending on how long each track is. from numpy import * from scipy.sparse import csc_matrix nvox = 1000000 ntracks = 300000 nmask = 100 # create about 100 entries per track tcoords = random.uniform(0, ntracks, ntracks * 100).astype(int) vcoords = random.uniform(0, nvox, ntracks * 100).astype(int) d = ones(ntracks * 100) T = csc_matrix((d, vstack((tcoords, vcoords))), shape=(ntracks, nvox), dtype=bool) # create around 10000 entries per mask mcoords = random.uniform(0, nmask, nmask * 10000).astype(int) vcoords = random.uniform(0, nvox, nmask * 10000).astype(int) d = ones(nmask * 10000) M = csc_matrix((d, vstack((mcoords, vcoords))), shape=(nmask, nvox), dtype=bool) Overlap = (M * T.transpose()).astype(bool) # mask M overlaps track T Connected = (Overlap * Overlap.transpose()).astype(bool) # mask M1 and M2 are connected Density = Overlap * T.astype(float) # number of tracks overlapping mask M summed across voxels A: OK, I think I finally have something that will reduce the complexity. This code should really fly compared to what you've got. It seems like first you need to know which tracks coincide with which masks, the incidence matrix. import numpy from collections import defaultdict def by_point(sets): d = defaultdict(list) for i, s in enumerate(sets): for pt in s: d[pt].append(i) return d def calc(xdim, ydim, zdim, mask_coords_list, tracks): masks_by_point = by_point(mask_coords_list) tracks_by_point = by_point(tracks) a = numpy.zeros((len(mask_coords_list), len(tracks)), dtype=int) for pt, maskids in masks_by_point.iteritems(): for trackid in tracks_by_point.get(pt, ()): a[maskids, trackid] = 1 m = numpy.matrix(a) The adjacency matrix you're looking for is m * m.T. The code you have so far computes the upper triangle only. You can use triu to grab just that half. am = m * m.T # calculate adjacency matrix am = numpy.triu(am, 1) # keep only upper triangle am = am.A # convert matrix back to array The voxel calculation can use the incidence matrix too. vox_tracks_img = numpy.zeros((xdim, ydim, zdim, len(mask_coords_list)), dtype=int) for trackid, track in enumerate(tracks): for x, y, z in track: vox_tracks_img[x, y, z, :] += a[:,trackid] return am, vox_tracks_img For me this runs in under a second for data sets having hundreds of masks and tracks. If you have many points that appear in masks but are not on any tracks, it might be worthwhile to delete the entries for those points from masks_by_point before entering the loop. A: You can probably start by combining the two functions to create both results at once. Also there's no need to make a list of the combinations before looping, as it is already a generator, and that might save you some time. def mask_connectivity_matrix_and_tracks(tracks,masks,masks_coords_list): connect_mat=zeros((len(masks),len(masks))) vox_tracks_img=zeros((xdim,ydim,zdim,len(masks))) for track in tracks: cur=[] for count,mask_coords in enumerate(masks_coords_list): if any(set(track) & set(mask_coords)): cur.append(count) for x,y,z in track: vox_tracks_img[x,y,z,count] += 1 for x,y in itertools.combinations(cur,2): connect_mat[x,y] += 1 Also, this will probably never be "fast" as in "finished before we die", so the best way is to eventually compile it with Cython as a c module for python. A: If you stored the each mask set of points: (1,2,3), (1,2,4), (1,3,1) as a dictionary like this: {1: [{2: set([3, 4])}, {3: set([1])}]}, you might end up being able to check for matches faster...but maybe not. A: A minor optimization (same big-O, sligthly smaller multiplier) can be had by removing redundant operations: don't call set so many times on each track and mask: call it once per track and once per mask, to set up auxiliary "parallel" lists of sets, then work on those if any(someset): is semantically the same as if someset: but a bit slower Won't make a dramatic difference, but might minutely help. A: Lame to suggest yet another incremental improvement that might be made, I know, but: Sets of small integers can be modeled as bit-vectors using Python's long ints. Suppose you replace each tuple with a small integer id, then convert each track and each set of mask-coords into a set of those small ids. You could represent those sets as long ints, making the intersection operation a bit faster (but not asymptotically faster).
More efficient way to count intersections?
I have a list of 300000 lists (fiber tracks), where each track is a list of (x,y,z) tuples/coordinates: tracks= [[(1,2,3),(3,2,4),...] [(4,2,1),(5,7,3),...] ... ] I also have a group of masks, where each mask is defined as a list of (x,y,z) tuples/coordinates: mask_coords_list= [[(1,2,3),(8,13,4),...] [(6,2,2),(5,7,3),...] ... ] I am trying to find, for all possible pairs of masks: the number of tracks that intersect each mask-mask pair (to create a connectivity matrix) the subset of tracks that intersect each mask, in order to add 1 to each (x,y,z) coordinate for each track in the subset (to create a "density" image) I'm currently doing part 1 like so: def mask_connectivity_matrix(tracks,masks,masks_coords_list): connect_mat=zeros((len(masks),len(masks))) for track in tracks: cur=[] for count,mask_coords in enumerate(masks_coords_list): if any(set(track) & set(mask_coords)): cur.append(count) for x,y in list(itertools.combinations(cur,2)): connect_mat[x,y] += 1 and part 2 like so: def mask_tracks(tracks,masks,masks_coords_list): vox_tracks_img=zeros((xdim,ydim,zdim,len(masks))) for track in tracks: for count,mask in enumerate(masks_coords_list): if any(set(track) & set(mask)): for x,y,z in track: vox_tracks_img[x,y,z,count] += 1 Using sets to find intersections has sped this process up significantly but both portions still take over an hour when I have a list of 70 or more masks. Is there a more efficient way to do this than iterating for each track?
[ "Linearize the voxel coordinates, and put them into two scipy.sparse.sparse.csc matrices. \nLet v be the number of voxels, m the number of masks, and t the number of tracks.\nLet M be the mask csc matrix, size (m x v), where a 1 at (i,j) means mask i overlaps voxel j.\nLet T be the track csc matrix, size (t x v), where a 1 at (k,j) means track k overlaps voxel j. \nOverlap = (M * T.transpose() > 0) # track T overlaps mask M \nConnected = (Overlap * Overlap.tranpose() > 0) # Connected masks\nDensity[mask_idx] = numpy.take(T, nonzero(Overlap[mask_idx, :])[0], axis=0).sum(axis=0)\n\nI might be wrong on the last one, and I'm not sure css_matrices can be operated on by nonzero & take. You might need to pull out each column in a loop and convert it to a full matrix.\n\nI ran some experiments trying to simulate what I thought was a reasonable amount of data. The code below takes about 2 minutes on a 2-year old MacBook. If you use csr_matrices, it takes about 4 minutes. There is probably a tradeoff depending on how long each track is. \nfrom numpy import *\nfrom scipy.sparse import csc_matrix\n\nnvox = 1000000\nntracks = 300000\nnmask = 100\n\n# create about 100 entries per track\ntcoords = random.uniform(0, ntracks, ntracks * 100).astype(int)\nvcoords = random.uniform(0, nvox, ntracks * 100).astype(int)\nd = ones(ntracks * 100)\nT = csc_matrix((d, vstack((tcoords, vcoords))), shape=(ntracks, nvox), dtype=bool)\n\n# create around 10000 entries per mask\nmcoords = random.uniform(0, nmask, nmask * 10000).astype(int)\nvcoords = random.uniform(0, nvox, nmask * 10000).astype(int)\nd = ones(nmask * 10000)\nM = csc_matrix((d, vstack((mcoords, vcoords))), shape=(nmask, nvox), dtype=bool)\n\nOverlap = (M * T.transpose()).astype(bool) # mask M overlaps track T\nConnected = (Overlap * Overlap.transpose()).astype(bool) # mask M1 and M2 are connected\nDensity = Overlap * T.astype(float) # number of tracks overlapping mask M summed across voxels\n\n", "OK, I think I finally have something that will reduce the complexity. This code should really fly compared to what you've got.\nIt seems like first you need to know which tracks coincide with which masks, the incidence matrix.\nimport numpy\nfrom collections import defaultdict\n\ndef by_point(sets):\n d = defaultdict(list)\n for i, s in enumerate(sets):\n for pt in s:\n d[pt].append(i)\n return d\n\ndef calc(xdim, ydim, zdim, mask_coords_list, tracks):\n masks_by_point = by_point(mask_coords_list)\n tracks_by_point = by_point(tracks)\n\n a = numpy.zeros((len(mask_coords_list), len(tracks)), dtype=int)\n for pt, maskids in masks_by_point.iteritems():\n for trackid in tracks_by_point.get(pt, ()):\n a[maskids, trackid] = 1\n m = numpy.matrix(a)\n\nThe adjacency matrix you're looking for is m * m.T.\nThe code you have so far computes the upper triangle only. You can use triu to grab just that half.\n am = m * m.T # calculate adjacency matrix\n am = numpy.triu(am, 1) # keep only upper triangle\n am = am.A # convert matrix back to array\n\nThe voxel calculation can use the incidence matrix too.\n vox_tracks_img = numpy.zeros((xdim, ydim, zdim, len(mask_coords_list)), dtype=int)\n for trackid, track in enumerate(tracks):\n for x, y, z in track:\n vox_tracks_img[x, y, z, :] += a[:,trackid]\n return am, vox_tracks_img\n\nFor me this runs in under a second for data sets having hundreds of masks and tracks.\nIf you have many points that appear in masks but are not on any tracks, it might be worthwhile to delete the entries for those points from masks_by_point before entering the loop.\n", "You can probably start by combining the two functions to create both results at once. Also there's no need to make a list of the combinations before looping, as it is already a generator, and that might save you some time.\ndef mask_connectivity_matrix_and_tracks(tracks,masks,masks_coords_list):\n connect_mat=zeros((len(masks),len(masks)))\n vox_tracks_img=zeros((xdim,ydim,zdim,len(masks)))\n for track in tracks:\n cur=[]\n for count,mask_coords in enumerate(masks_coords_list):\n if any(set(track) & set(mask_coords)):\n cur.append(count)\n for x,y,z in track:\n vox_tracks_img[x,y,z,count] += 1\n for x,y in itertools.combinations(cur,2):\n connect_mat[x,y] += 1\n\nAlso, this will probably never be \"fast\" as in \"finished before we die\", so the best way is to eventually compile it with Cython as a c module for python.\n", "If you stored the each mask set of points:\n(1,2,3), (1,2,4), (1,3,1) as a dictionary like this: {1: [{2: set([3, 4])}, {3: set([1])}]}, you might end up being able to check for matches faster...but maybe not. \n", "A minor optimization (same big-O, sligthly smaller multiplier) can be had by removing redundant operations:\n\ndon't call set so many times on each track and mask: call it once per track and once per mask, to set up auxiliary \"parallel\" lists of sets, then work on those\nif any(someset): is semantically the same as if someset: but a bit slower\n\nWon't make a dramatic difference, but might minutely help.\n", "Lame to suggest yet another incremental improvement that might be made, I know, but:\nSets of small integers can be modeled as bit-vectors using Python's long ints. Suppose you replace each tuple with a small integer id, then convert each track and each set of mask-coords into a set of those small ids. You could represent those sets as long ints, making the intersection operation a bit faster (but not asymptotically faster).\n" ]
[ 3, 1, 0, 0, 0, 0 ]
[]
[]
[ "algorithm", "python", "set" ]
stackoverflow_0001910744_algorithm_python_set.txt
Q: Set django-notification to be opt in rather than the default of opt out I'm using django-notification to allow my users to opt out of certain alerts I generate in my web-application. By default when I create a new notice type it is enabled rather than disabled In the users notification interface (checked) I'd like to make some alerts opt-in rather than the default of opt out. I've looked through the docs and been unable to see a way to do this, has anyone else managed to accomplish this? A: Its automatically set based on the 'default' column in the type itself, by default e-mail is a sensitivity of 2, so if you set the default to your new notice type default '1' it will no longer set it on by default for your users, the default when creating new notice types is '2' which would allow it to be sent to everyone. A: Looking at the code, the determining factor to sending the notice is a comparison between the 'default' column and the sensitivity filter NOTICE_MEDIA_DEFAULTS[medium]. Does this work from notification import models as notification notification.create_notice_type("friends_invite", "Invitation Received", "you have received an invitation", default=0)
Set django-notification to be opt in rather than the default of opt out
I'm using django-notification to allow my users to opt out of certain alerts I generate in my web-application. By default when I create a new notice type it is enabled rather than disabled In the users notification interface (checked) I'd like to make some alerts opt-in rather than the default of opt out. I've looked through the docs and been unable to see a way to do this, has anyone else managed to accomplish this?
[ "Its automatically set based on the 'default' column in the type itself, by default e-mail is a sensitivity of 2, so if you set the default to your new notice type default '1' it will no longer set it on by default for your users, the default when creating new notice types is '2' which would allow it to be sent to everyone.\n", "Looking at the code, the determining factor to sending the notice is a comparison between the 'default' column and the sensitivity filter NOTICE_MEDIA_DEFAULTS[medium]. \nDoes this work\nfrom notification import models as notification\n\nnotification.create_notice_type(\"friends_invite\", \"Invitation Received\", \"you have received an invitation\", default=0)\n\n" ]
[ 4, 0 ]
[]
[]
[ "code_reuse", "django", "pinax", "python" ]
stackoverflow_0001884801_code_reuse_django_pinax_python.txt
Q: deleter decorator using Property in Python I'm playing around with property in Python and I was wondering how this @propertyName.deleter decorator works. I'm probably missing something, I could not find clear answers by Google. What I would like to achieve is when this deleter behavior is called, I can trigger other actions (e.g: using my 3d application SDK). For now just a simple print() doesn't seem to get triggered. Is deleter fired when I delete the property using del(instance.property) ? Otherwise, how can I achieve this? class M(): def __init__(self): self._m = None @property def mmm(self): return self._m @mmm.setter def mmm(self, val): self._m = val @mmm.deleter def mmm(self): print('deleting') # Not printing del(self._m) if __name__ == '__main__': i = M() i.mmm = 150 print(i.mmm) del(i.mmm) print(i.mmm) Thank you very much (: A: Make M a new-style class: class M(object): See http://www.python.org/download/releases/2.2.3/descrintro/#property: Properties do not work for classic classes, but you don't get a clear error when you try this. Your get method will be called, so it appears to work, but upon attribute assignment, a classic class instance will simply set the value in its dict without calling the property's set method, and after that, the property's get method won't be called either. (You could override setattr to fix this, but it would be prohibitively expensive.) A: In Python 3 you WOULD see the print's result -- and then an AttributeError for the last print (because _m has disappeared). You may be using Python 2.6, in which case you need to change the class clause to class M(object): to make M new-style, and then you'll get the same behavior as in Python 3.
deleter decorator using Property in Python
I'm playing around with property in Python and I was wondering how this @propertyName.deleter decorator works. I'm probably missing something, I could not find clear answers by Google. What I would like to achieve is when this deleter behavior is called, I can trigger other actions (e.g: using my 3d application SDK). For now just a simple print() doesn't seem to get triggered. Is deleter fired when I delete the property using del(instance.property) ? Otherwise, how can I achieve this? class M(): def __init__(self): self._m = None @property def mmm(self): return self._m @mmm.setter def mmm(self, val): self._m = val @mmm.deleter def mmm(self): print('deleting') # Not printing del(self._m) if __name__ == '__main__': i = M() i.mmm = 150 print(i.mmm) del(i.mmm) print(i.mmm) Thank you very much (:
[ "Make M a new-style class:\nclass M(object):\n\nSee http://www.python.org/download/releases/2.2.3/descrintro/#property:\n\nProperties do not work for classic\n classes, but you don't get a clear\n error when you try this. Your get\n method will be called, so it appears\n to work, but upon attribute\n assignment, a classic class instance\n will simply set the value in its\n dict without calling the property's set method, and after that,\n the property's get method won't be\n called either. (You could override\n setattr to fix this, but it would be prohibitively expensive.)\n\n", "In Python 3 you WOULD see the print's result -- and then an AttributeError for the last print (because _m has disappeared). You may be using Python 2.6, in which case you need to change the class clause to class M(object): to make M new-style, and then you'll get the same behavior as in Python 3.\n" ]
[ 14, 9 ]
[]
[]
[ "decorator", "properties", "python" ]
stackoverflow_0001912229_decorator_properties_python.txt
Q: Limit calls to external database with Python CGI I've got a Python CGI script that pulls data from a GPS service; I'd like this information to be updated on the webpage about once every 10s (the max allowed by the GPS service's TOS). But there could be, say, 100 users viewing the webpage at once, all calling the script. I think the users' scripts need to grab data from a buffer page that itself only upates once every ten seconds. How can I make this buffer page auto-update if there's no one directly viewing the content (and not accessing the CGI)? Are there better ways to accomplish this? A: Cache the results of your GPS data query in a file or database (sqlite) along with a datetime. You can then do a datetime check against the last cached datetime to initiate another GPS data query. You'll probably run into concurrency issues with cgi and the datetime check though... To get around concurrency issues, you can use sqlite, and put the write in a try/except. Here's a sample cache implementation using sqlite. import datetime import sqlite3 class GpsCache(object): db_path = 'gps_cache.db' def __init__(self): self.con = sqlite3.connect(self.db_path) self.cur = self.con.cursor() def _get_period(self, dt=None): '''normalize time to 15 minute periods''' if dt.minute < 15: minute_period = 0 elif 15 <= dt.minute < 30: minute_period = 15 elif 30 <= dt_minute < 45: minute_period = 30 elif 45 <= dt_minute: minute_period = 25 period_dt = datetime.datetime(year=dt.year, month=dt.month, day=dt.day, hour=dt.hour, minute=minute_period) return period_dt def get_cache(dt=None): period_dt = self._get_period(dt) select_sql = 'SELECT * FROM GPS_CACHE WHERE date_time = "%s";' % period_dt.strftime('%Y-%m-%d %H:%M') self.cur.execut(select_sql) result = self.cur.fetchone()[0] return result def put_cache(dt=None, data=None): period_dt = self._get_period(dt) insert_sql = 'INSERT ....' # edit to your table structure try: self.cur.execute(insert_sql) self.con.commit() except sqlite3.OperationalError: # assume db is being updated by another process with the current resutls and ignore pass So we have the cache tool now the implementation side. You'll want to check the cache first then if it's not 'fresh' (doens't return anything), go grab the data using your current method. Then cache the data you grabbed. you should probably organize this better, but you should get the general idea here. Using this sample, you just replace your current calls to 'remote_get_gps_data' with 'get_gps_data'. from gps_cacher import GpsCache def remote_get_gps_data(): # your function here return data def get_gps_data(): data = None gps_cache = GpsCache() current_dt = datetime.datetime.now() cached_data = gps_cache.get_cache(current_dt) if cached_data: data = cached_data else: data = remote_get_gps_data() gps_cache.put_cache(current_dt, data) return data
Limit calls to external database with Python CGI
I've got a Python CGI script that pulls data from a GPS service; I'd like this information to be updated on the webpage about once every 10s (the max allowed by the GPS service's TOS). But there could be, say, 100 users viewing the webpage at once, all calling the script. I think the users' scripts need to grab data from a buffer page that itself only upates once every ten seconds. How can I make this buffer page auto-update if there's no one directly viewing the content (and not accessing the CGI)? Are there better ways to accomplish this?
[ "Cache the results of your GPS data query in a file or database (sqlite) along with a datetime.\nYou can then do a datetime check against the last cached datetime to initiate another GPS data query.\nYou'll probably run into concurrency issues with cgi and the datetime check though...\nTo get around concurrency issues, you can use sqlite, and put the write in a try/except.\nHere's a sample cache implementation using sqlite.\nimport datetime\nimport sqlite3 \n\nclass GpsCache(object):\n db_path = 'gps_cache.db'\n def __init__(self):\n self.con = sqlite3.connect(self.db_path)\n self.cur = self.con.cursor()\n\n def _get_period(self, dt=None):\n '''normalize time to 15 minute periods'''\n if dt.minute < 15:\n minute_period = 0\n elif 15 <= dt.minute < 30:\n minute_period = 15\n elif 30 <= dt_minute < 45: \n minute_period = 30\n elif 45 <= dt_minute:\n minute_period = 25\n period_dt = datetime.datetime(year=dt.year, month=dt.month, day=dt.day, hour=dt.hour, minute=minute_period)\n return period_dt\n\n def get_cache(dt=None):\n period_dt = self._get_period(dt)\n select_sql = 'SELECT * FROM GPS_CACHE WHERE date_time = \"%s\";' % period_dt.strftime('%Y-%m-%d %H:%M')\n self.cur.execut(select_sql)\n result = self.cur.fetchone()[0]\n return result\n\n\n def put_cache(dt=None, data=None):\n period_dt = self._get_period(dt)\n insert_sql = 'INSERT ....' # edit to your table structure\n try:\n self.cur.execute(insert_sql)\n self.con.commit()\n except sqlite3.OperationalError:\n # assume db is being updated by another process with the current resutls and ignore\n pass\n\nSo we have the cache tool now the implementation side.\nYou'll want to check the cache first then if it's not 'fresh' (doens't return anything), go grab the data using your current method. Then cache the data you grabbed.\nyou should probably organize this better, but you should get the general idea here.\nUsing this sample, you just replace your current calls to 'remote_get_gps_data' with 'get_gps_data'.\nfrom gps_cacher import GpsCache\n\ndef remote_get_gps_data():\n # your function here\n return data\n\ndef get_gps_data():\n data = None\n gps_cache = GpsCache()\n current_dt = datetime.datetime.now()\n cached_data = gps_cache.get_cache(current_dt) \n if cached_data:\n data = cached_data\n else:\n data = remote_get_gps_data()\n gps_cache.put_cache(current_dt, data)\n return data\n\n" ]
[ 1 ]
[]
[]
[ "cgi", "python", "sql" ]
stackoverflow_0001912253_cgi_python_sql.txt
Q: Extract data from a website's list, without superfluous tags Working code: Google dictionary lookup via python and beautiful soup -> simply execute and enter a word. I've quite simply extracted the first definition from a specific list item. However to get plain data, I've had to split my data at the line break, and then strip it to remove the superfluous list tag. My question is, is there a method to extract the data contained within a specific list without doing my above string manipulation - perhaps a function in beautiful soup that I have yet to see? This is the relevant section of code: # Retrieve HTML and parse with BeautifulSoup. doc = userAgentSwitcher().open(queryURL).read() soup = BeautifulSoup(doc) # Extract the first list item -> and encode it. definition = soup('li', limit=2)[0].encode('utf-8') # Format the return as word:definition removing superfluous data. print word + " : " + definition.split("<br />")[0].strip("<li>") A: I think you are looking for findAll(text=True) this will extract the text from the tags definitions = soup('ul')[0].findAll(text=True) Will return a ist of all the text contents broken at the tag boundaries
Extract data from a website's list, without superfluous tags
Working code: Google dictionary lookup via python and beautiful soup -> simply execute and enter a word. I've quite simply extracted the first definition from a specific list item. However to get plain data, I've had to split my data at the line break, and then strip it to remove the superfluous list tag. My question is, is there a method to extract the data contained within a specific list without doing my above string manipulation - perhaps a function in beautiful soup that I have yet to see? This is the relevant section of code: # Retrieve HTML and parse with BeautifulSoup. doc = userAgentSwitcher().open(queryURL).read() soup = BeautifulSoup(doc) # Extract the first list item -> and encode it. definition = soup('li', limit=2)[0].encode('utf-8') # Format the return as word:definition removing superfluous data. print word + " : " + definition.split("<br />")[0].strip("<li>")
[ "I think you are looking for findAll(text=True) this will extract the text from the tags \ndefinitions = soup('ul')[0].findAll(text=True)\n\nWill return a ist of all the text contents broken at the tag boundaries\n" ]
[ 1 ]
[]
[]
[ "beautifulsoup", "extract", "html", "python" ]
stackoverflow_0001911442_beautifulsoup_extract_html_python.txt
Q: App engine templates In app engine there a way to use templates a bit more like php/javascript(document.write)? for instance i would rather do: <html> <python> print "Hello world" </python> </html> rather than all the {IF } {ELSE } django stuff. A: You want embedded python in html page for that look into mako (http://www.makotemplates.org/), you don't even need print e.g. <%inherit file="base.html"/> <% rows = [[v for v in range(0,10)] for row in range(0,10)] %> <table> % for row in rows: ${makerow(row)} % endfor </table> <%def name="makerow(row)"> <tr> % for name in row: <td>${name}</td>\ % endfor </tr> </%def> it comes with inheritance, Callable blocks, is faster and IMO better than django and any day better than php style stuff. for mako on GAE see https://code.launchpad.net/~pylons-gae/mako/mako-gae A: The Tornado project's template module allows the insertion of python code, and it's very fast as well. It works well within App Engine, despite being designed to work with the rest of the Tornado framework and the Tornado HTTP server. A: The simplest way is to use string templates from the standard library. A: One of the web programming best practices it to not mix business or page logic with HTML. That's why the templates were created after all, so the code can process the request, call the appropriate logic and prepare the objects used to display the response before any output is made. Why do you want to go the other way around?
App engine templates
In app engine there a way to use templates a bit more like php/javascript(document.write)? for instance i would rather do: <html> <python> print "Hello world" </python> </html> rather than all the {IF } {ELSE } django stuff.
[ "You want embedded python in html page for that look into mako (http://www.makotemplates.org/), you don't even need print e.g.\n<%inherit file=\"base.html\"/>\n<%\n rows = [[v for v in range(0,10)] for row in range(0,10)]\n%>\n<table>\n % for row in rows:\n ${makerow(row)}\n % endfor\n</table>\n\n<%def name=\"makerow(row)\">\n <tr>\n % for name in row:\n <td>${name}</td>\\\n % endfor\n </tr>\n</%def>\n\nit comes with inheritance, Callable blocks, is faster and IMO better than django and any day better than php style stuff.\nfor mako on GAE see https://code.launchpad.net/~pylons-gae/mako/mako-gae\n", "The Tornado project's template module allows the insertion of python code, and it's very fast as well. It works well within App Engine, despite being designed to work with the rest of the Tornado framework and the Tornado HTTP server.\n", "The simplest way is to use string templates from the standard library.\n", "One of the web programming best practices it to not mix business or page logic with HTML. That's why the templates were created after all, so the code can process the request, call the appropriate logic and prepare the objects used to display the response before any output is made. Why do you want to go the other way around?\n" ]
[ 3, 2, 0, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0001907187_google_app_engine_python.txt
Q: Organizing python code for handling statistic information I'm going to create statistics based on information what builds were success or not and how much per project. I create ProjectStat class per new project I see and inside handled statistics. For printing overall statistic I need to pass through all ProjectStat instances. For printing success statistics per project I need to pass through them again and so on, on any kind of statistics. My question is about simplifying the way handling the cycles, i.e not to pass the dictionary every time. Perhaps using decorators or decorator pattern would be pythonic way? How then they can be used if number of instances of ProjectStat is dynamically changed? Here is the code: class ProjectStat(object): projectSuccess = 0 projectFailed = 0 projectTotal = 0 def addRecord(self, record): if len(record) == 5: record.append(None) try: (datetime, projectName, branchName, number, status, componentName) = record except ValueError: pass self.projectTotal += 1 if status == 'true': self.projectSuccess += 1 else: self.projectFailed += 1 def addDecorator(self, decorator): decorator = decorator def readBuildHistoryFile(): dict = {} f = open("filename") print("reading the file") try: for line in f.readlines(): #print(line) items = line.split() projectName = items[1] projectStat = dict[projectName] = dict.get(projectName, ProjectStat()) projectStat.addRecord(items) print(items[1]) finally: f.close() success = 0 failed = 0 total = 0 for k in dict.keys(): projectStat = dict[k] success += projectStat.projectSuccess failed += projectStat.projectFailed total += projectStat.projectTotal print("Total: " + str(total)) print("Success: " + str(success)) print("Failed: " + str(failed)) if __name__ == '__main__': readBuildHistoryFile() A: I'm not sure I understand the Q, but I'll try to answer anyway :) option1: total = sum([project.projectTotal for project in dict.values()]) success = sum([project.projectSuccess for project in dict.values()]) failed = sum([project.projectFailed for project in dict.values()]) option2: (total,success,failed) = reduce (lambda x,y:(x[0]+y[0],x[1]+y[1],x[2]+y[2]), [(project.projectTotal,project.projectSuccess,project.projectFailed) for project in dict.values()])
Organizing python code for handling statistic information
I'm going to create statistics based on information what builds were success or not and how much per project. I create ProjectStat class per new project I see and inside handled statistics. For printing overall statistic I need to pass through all ProjectStat instances. For printing success statistics per project I need to pass through them again and so on, on any kind of statistics. My question is about simplifying the way handling the cycles, i.e not to pass the dictionary every time. Perhaps using decorators or decorator pattern would be pythonic way? How then they can be used if number of instances of ProjectStat is dynamically changed? Here is the code: class ProjectStat(object): projectSuccess = 0 projectFailed = 0 projectTotal = 0 def addRecord(self, record): if len(record) == 5: record.append(None) try: (datetime, projectName, branchName, number, status, componentName) = record except ValueError: pass self.projectTotal += 1 if status == 'true': self.projectSuccess += 1 else: self.projectFailed += 1 def addDecorator(self, decorator): decorator = decorator def readBuildHistoryFile(): dict = {} f = open("filename") print("reading the file") try: for line in f.readlines(): #print(line) items = line.split() projectName = items[1] projectStat = dict[projectName] = dict.get(projectName, ProjectStat()) projectStat.addRecord(items) print(items[1]) finally: f.close() success = 0 failed = 0 total = 0 for k in dict.keys(): projectStat = dict[k] success += projectStat.projectSuccess failed += projectStat.projectFailed total += projectStat.projectTotal print("Total: " + str(total)) print("Success: " + str(success)) print("Failed: " + str(failed)) if __name__ == '__main__': readBuildHistoryFile()
[ "I'm not sure I understand the Q, but I'll try to answer anyway :)\noption1:\ntotal = sum([project.projectTotal for project in dict.values()])\nsuccess = sum([project.projectSuccess for project in dict.values()])\nfailed = sum([project.projectFailed for project in dict.values()])\n\noption2:\n(total,success,failed) = reduce (lambda x,y:(x[0]+y[0],x[1]+y[1],x[2]+y[2]), [(project.projectTotal,project.projectSuccess,project.projectFailed) for project in dict.values()])\n\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0001912635_python.txt
Q: Building app to Classify / Describe Products - Overwhelmed somewhere between planning & execution Greetings! I recently started working for a company that carries a line of 20,000 Surgical Instruments. Our data on all items is currently spotty and chaotic at best. I intend to fix this. I have been tasked with redesigning the web site. As part of the project, I'm building an app to classify and describe all products. We don't do any direct sales on the site, but have a network of sales reps and distributors that will utilize this info. A picture says a thousand words, so here's a link to a diagram I made showing what I'm trying to accomplish: http://i.imgur.com/gUuxB.png I'm currently trying to achieve this with CakePHP / MySQL. I'm not too heavily invested in these, and am open to suggestions for alternatives. Perhaps a CMS already has this functionality? Some sort of Open-Source gizmo? Python / Django? I'm having difficulties determining proper database structure and code logistics. I'm headed in to this project a novice, hoping to emerge as an intermediate. Any advice on how to tackle this enormous task would be helpful. I've spent almost 4 weeks in the planning phase, and can no longer see the forest for the trees. My head's about to explode. Thanks! A: Nice drawing:) Did you do any experiments with the actual table stucture? It does not look so hard. Here is a go while trying to keep things as simple as possible. ==products== id[int] number[varchar]: unique, ie. #50-334 category_id[int]: has-one relation to category.id ==categories== // What you call branches in your drawing. id[int] parent_id[int]: tree structure title[varchar] description[text] image[varchar] ==attributes== id[int] attribute_type_id[int]: has-one relation to attribute_types.id is_universal[bool]: is this attribute used for _all_ products? name[varchar] value[varchar] ==attribute_types== id[int] codetag[varchar]: name to identify the attribute type from the code. Each type haves different validation. Some types will maybe be validated using data from helper tables. title[varchar] description[text] ==products_has_attributes== // "Join table" with many-to-many relationship between products and attributes. id[int]: Optional product_id[int]: has-one relation to products.id attribute_id[int]: has-one relation to category.id ==categories_has_attributes== // "Join table" with many-to-many relationship between categories and attributes. id[int]: Optional category_id[int]: has-one relation to products.id attribute_id[int]: has-one relation to category.id First rough draft. Read it as such. A: Think about your user first. Then talk to your users. These sales reps have been working in this field longer than you and they will already have their own mental categorisations of the stock. What kind of interface would they expect to see? The interface you design should reflect the most common use cases! In what ways would they expect to query this database? If you consider the database design before asking these kind of questions then you may find that the most useful queries for the user are the ones that you haven't optimised for, and you have to jump through hoops to pull them off. Make sure you have an intuitive feel for what the user expects before you even start thinking about database schemas or which technology to use. A: Worry about your database design first, then what kind of framework you'll use. Regarding EAV, check out http://decipherinfosys.wordpress.com/2007/01/29/name-value-pair-design/ If you still really need to do it, consider PostgreSQL's hstore. (Google it, I don't have the rep to post the link.) A: Who will be using the app? How many people at one time? Any particular reasons for choosing CakePHP? From what I've heard, Rails and CakePHP have a lot of 'magic' involved; it becomes a problem when things suddenly don't work right and you have no idea why. If the app is only for people within the company and your ultimate goal is just to have these instruments classified, the easiest route would be to use Python with SQLite. But easiest does not necessarily equal best: Pros: - Using Python means that when you need to make changes to your code, it will be relatively painless. - Using SQLite equals ease of use; no setup required at all. If you're using Python 2.5 or higher, SQLite is built in, and it's very easy to use. - SQLite just interacts with one .db file, so when you need to move/change/export data from your database, there will be no hassle. Cons: - SQLite doesn't strongly enforce types. This means even though you set an attribute as 'integer', someone can come along and put text there and SQLite will happily accept it. Depending on how much data entry other people may be doing, this could become a problem since you could have inconsistent data. - SQLite is only meant for a few clients at a time. If a lot of people will be using your database, you'll need to go with MySQL instead. - SQLite won't work with terabytes of data; this may or may not be a limitation for you. A: It sounds like you need a rudimentary inventory system. A way to track the basic attributes of the items you've entered. You will also need some reporting, so the end users can query the system to get an idea of what is in the system. Find a solution that you can reference or review to get idea's from. Your solutions are a combinations of idea's from previous applications. With this in mind, find examples of works you like. Their might be an application that has an intuitive interface. Use it's interface. You might find a system that as a nice search feature. Implement the search feature. My advice in the enormity of the project is first; tackle the tasks one a time. Try to break the tasks down into small units. Don't worry about if it's the perfect solution. It will evolve. Second; this project might be beyond your skill level. It's not a bad thing to ask for help or admit you can't do it. Every company is different, so gauge your environment. As a developer I often inherit applications that were outsourced or written by an inexperienced developer. Nothing frustrates another developer more than working on code that has no structure or consistency. A: I think I like the choice of CakePHP in this instance. Basically you're just providing a web interface to your internal team so they can perform manual data classification, etc. So you just need to get a basic data editing interface up as quickly as possible. Cake's biggest strength, IMO, is its focus on rapid development. Sounds like a good fit here. Cake also has a Tree behavior, so it might serve as a basis for your schema. And it strongly suggests sensible defaults, so it will force you to think of your data in a very structured manner. That said, it's also not very nice when it solves the problem in a manner differently than the programmer wants. It's not as flexible as the others. The other big caution is that it's slow, but for an internal app like this, I don't envision that being a current major concern. In short, it's a good way to force structure on your data (and code). It's fast for development. And you don't have a requirement for performance. A: This sort of thing is dead easy in Django (assuming I really understand what you're asking). A models.py something like this: from django.db import models class Item(models.Model): price = models.DecimalField(max_digits=9, decimal_places=2) material = models.CharField(max_length=100) class Sprocket(Item): length = models.DecimalField(max_digits=9, decimal_places=6) shape = models.CharField(max_length=100) # straight/curved class SprocketProduct(Sprocket): radius = models.FloatField() maxload = models.FloatField() weight = models.FloatField() color = models.CharField(max_length=100) will more or less do the trick. Here, SprocketProduct inherits from Sprocket which inherits from Item. Also, asking for Item.objects.all() will give you all items, Sprocket.objects.all() will give you only sprockets -- you get the idea. A: I agree with drspod - you need to understand what the users want - you may build something of technical genius, but without users it doesn't return the value on your time investment. One you've understood that, I would recommend going down the Python/Django route, or consider Rails as a fast way of getting where you want to go. Django particularly has excellent documentation, which should be enough to achieve your goal of becoming a intermediately experienced web developer. Ben
Building app to Classify / Describe Products - Overwhelmed somewhere between planning & execution
Greetings! I recently started working for a company that carries a line of 20,000 Surgical Instruments. Our data on all items is currently spotty and chaotic at best. I intend to fix this. I have been tasked with redesigning the web site. As part of the project, I'm building an app to classify and describe all products. We don't do any direct sales on the site, but have a network of sales reps and distributors that will utilize this info. A picture says a thousand words, so here's a link to a diagram I made showing what I'm trying to accomplish: http://i.imgur.com/gUuxB.png I'm currently trying to achieve this with CakePHP / MySQL. I'm not too heavily invested in these, and am open to suggestions for alternatives. Perhaps a CMS already has this functionality? Some sort of Open-Source gizmo? Python / Django? I'm having difficulties determining proper database structure and code logistics. I'm headed in to this project a novice, hoping to emerge as an intermediate. Any advice on how to tackle this enormous task would be helpful. I've spent almost 4 weeks in the planning phase, and can no longer see the forest for the trees. My head's about to explode. Thanks!
[ "Nice drawing:)\nDid you do any experiments with the actual table stucture? It does not look so hard. Here is a go while trying to keep things as simple as possible.\n==products==\nid[int]\nnumber[varchar]: unique, ie. #50-334 \ncategory_id[int]: has-one relation to category.id\n\n==categories==\n// What you call branches in your drawing.\nid[int]\nparent_id[int]: tree structure\ntitle[varchar]\ndescription[text]\nimage[varchar]\n\n==attributes==\nid[int]\nattribute_type_id[int]: has-one relation to attribute_types.id\nis_universal[bool]: is this attribute used for _all_ products?\nname[varchar]\nvalue[varchar]\n\n==attribute_types==\nid[int]\ncodetag[varchar]: name to identify the attribute type from the code. Each type haves different validation. Some types will maybe be validated using data from helper tables.\ntitle[varchar]\ndescription[text]\n\n==products_has_attributes==\n// \"Join table\" with many-to-many relationship between products and attributes.\nid[int]: Optional\nproduct_id[int]: has-one relation to products.id\nattribute_id[int]: has-one relation to category.id\n\n==categories_has_attributes==\n// \"Join table\" with many-to-many relationship between categories and attributes.\nid[int]: Optional\ncategory_id[int]: has-one relation to products.id\nattribute_id[int]: has-one relation to category.id\n\nFirst rough draft. Read it as such.\n", "Think about your user first. Then talk to your users. These sales reps have been working in this field longer than you and they will already have their own mental categorisations of the stock.\nWhat kind of interface would they expect to see? The interface you design should reflect the most common use cases!\nIn what ways would they expect to query this database? If you consider the database design before asking these kind of questions then you may find that the most useful queries for the user are the ones that you haven't optimised for, and you have to jump through hoops to pull them off.\nMake sure you have an intuitive feel for what the user expects before you even start thinking about database schemas or which technology to use.\n", "Worry about your database design first, then what kind of framework you'll use.\nRegarding EAV, check out http://decipherinfosys.wordpress.com/2007/01/29/name-value-pair-design/ If you still really need to do it, consider PostgreSQL's hstore. (Google it, I don't have the rep to post the link.)\n", "Who will be using the app? How many people at one time? Any particular reasons for choosing CakePHP?\nFrom what I've heard, Rails and CakePHP have a lot of 'magic' involved; it becomes a problem when things suddenly don't work right and you have no idea why. If the app is only for people within the company and your ultimate goal is just to have these instruments classified, the easiest route would be to use Python with SQLite.\nBut easiest does not necessarily equal best:\nPros:\n- Using Python means that when you need to make changes to your code, it will be relatively painless.\n- Using SQLite equals ease of use; no setup required at all. If you're using Python 2.5 or higher, SQLite is built in, and it's very easy to use.\n- SQLite just interacts with one .db file, so when you need to move/change/export data from your database, there will be no hassle.\nCons:\n- SQLite doesn't strongly enforce types. This means even though you set an attribute as 'integer', someone can come along and put text there and SQLite will happily accept it. Depending on how much data entry other people may be doing, this could become a problem since you could have inconsistent data.\n- SQLite is only meant for a few clients at a time. If a lot of people will be using your database, you'll need to go with MySQL instead.\n- SQLite won't work with terabytes of data; this may or may not be a limitation for you.\n", "It sounds like you need a rudimentary inventory system. A way to track the basic attributes of the items you've entered. You will also need some reporting, so the end users can query the system to get an idea of what is in the system.\nFind a solution that you can reference or review to get idea's from. Your solutions are a combinations of idea's from previous applications. With this in mind, find examples of works you like. Their might be an application that has an intuitive interface. Use it's interface. You might find a system that as a nice search feature. Implement the search feature.\nMy advice in the enormity of the project is first; tackle the tasks one a time. Try to break the tasks down into small units. Don't worry about if it's the perfect solution. It will evolve. Second; this project might be beyond your skill level. It's not a bad thing to ask for help or admit you can't do it. Every company is different, so gauge your environment.\nAs a developer I often inherit applications that were outsourced or written by an inexperienced developer. Nothing frustrates another developer more than working on code that has no structure or consistency.\n", "I think I like the choice of CakePHP in this instance. Basically you're just providing a web interface to your internal team so they can perform manual data classification, etc. So you just need to get a basic data editing interface up as quickly as possible. Cake's biggest strength, IMO, is its focus on rapid development. Sounds like a good fit here.\nCake also has a Tree behavior, so it might serve as a basis for your schema. And it strongly suggests sensible defaults, so it will force you to think of your data in a very structured manner.\nThat said, it's also not very nice when it solves the problem in a manner differently than the programmer wants. It's not as flexible as the others. The other big caution is that it's slow, but for an internal app like this, I don't envision that being a current major concern.\nIn short, it's a good way to force structure on your data (and code). It's fast for development. And you don't have a requirement for performance.\n", "This sort of thing is dead easy in Django (assuming I really understand what you're asking). A models.py something like this:\nfrom django.db import models\n\nclass Item(models.Model):\n price = models.DecimalField(max_digits=9, decimal_places=2)\n material = models.CharField(max_length=100)\n\nclass Sprocket(Item):\n length = models.DecimalField(max_digits=9, decimal_places=6)\n shape = models.CharField(max_length=100) # straight/curved\n\nclass SprocketProduct(Sprocket):\n radius = models.FloatField()\n maxload = models.FloatField()\n weight = models.FloatField()\n color = models.CharField(max_length=100)\n\nwill more or less do the trick. Here, SprocketProduct inherits from Sprocket which inherits from Item.\nAlso, asking for Item.objects.all() will give you all items, Sprocket.objects.all() will give you only sprockets -- you get the idea.\n", "I agree with drspod - you need to understand what the users want - you may build something of technical genius, but without users it doesn't return the value on your time investment.\nOne you've understood that, I would recommend going down the Python/Django route, or consider Rails as a fast way of getting where you want to go.\nDjango particularly has excellent documentation, which should be enough to achieve your goal of becoming a intermediately experienced web developer.\nBen\n" ]
[ 3, 3, 2, 1, 1, 1, 1, 0 ]
[]
[]
[ "architecture", "cakephp", "database_design", "mysql", "python" ]
stackoverflow_0001909059_architecture_cakephp_database_design_mysql_python.txt
Q: How to become a good Python coder? I started with c++ but as we all know, c++ is a monster. I still have to take it and I do like C++ (it takes programming a step further) However, currently I have been working with python for a while. I see how you guys can turn some long algorithm into simple one. I know programming is a progress, and can take up to years of experience. I also know myself - I am not a natural programmer, and software engineering is not my first choice anyway. However, I would like to do heavy programming on my own, and create projects. How can I become a better python programmer? A: Write code Read books, http://www.coderholic.com/free-python-programming-books/ Read code Read tutorials, http://www.dabeaz.com/talks.html, ... Write more code Do exercises, e.g. Building Skills in Python Write even more code Answer SO python questions, https://stackoverflow.com/unanswered/tagged/python Check (your) code regularly, http://pypi.python.org/pypi/pylint Watch talks and presentations: Easy AI in python, Advanced python or understanding Python, http://pycon.blip.tv/, ... A: Read code. This will help you learn what works well in Python and what doesn't. As part of this, learn python idioms and the standard library. Some examples of literature to read: http://ivory.idyll.org/articles/advanced-swc/ http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html http://www.dabeaz.com/generators/ As for the algorithm part you mention, some specific parts of the standard library to learn include: itertools functools contextlib A: One suggestion is to find an open-source project in Python, and start contributing. You may ask "how can I contribute, if I'm a beginner?". One answer is "write tests". Almost any project will welcome you as a tester. Another answer is "documentation", though that is less likely to give immediate benefits. A: The already-posted answers are great. In addition, whenever you're coding something in Python and you start doing something that feels clumsy, take a step back and think. If you can't think of a more elegant way to do it, post it as a question on Stack Overflow. I can't count the number of times that I've seen someone reduce ten lines of Python into one (which is still perfectly easy to read and understand). A: in addition to suggestions pointed by "The MYYN" I would suggest use of pylint
How to become a good Python coder?
I started with c++ but as we all know, c++ is a monster. I still have to take it and I do like C++ (it takes programming a step further) However, currently I have been working with python for a while. I see how you guys can turn some long algorithm into simple one. I know programming is a progress, and can take up to years of experience. I also know myself - I am not a natural programmer, and software engineering is not my first choice anyway. However, I would like to do heavy programming on my own, and create projects. How can I become a better python programmer?
[ "\nWrite code\nRead books, http://www.coderholic.com/free-python-programming-books/\nRead code \nRead tutorials, http://www.dabeaz.com/talks.html, ...\nWrite more code\nDo exercises, e.g. Building Skills in Python\nWrite even more code\nAnswer SO python questions, https://stackoverflow.com/unanswered/tagged/python\nCheck (your) code regularly, http://pypi.python.org/pypi/pylint\nWatch talks and presentations: \n\nEasy AI in python, \nAdvanced python or understanding Python, \nhttp://pycon.blip.tv/, ...\n\n\n", "Read code. This will help you learn what works well in Python and what doesn't. As part of this, learn python idioms and the standard library.\nSome examples of literature to read:\n\nhttp://ivory.idyll.org/articles/advanced-swc/\nhttp://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html\nhttp://www.dabeaz.com/generators/\n\nAs for the algorithm part you mention, some specific parts of the standard library to learn include:\n\nitertools\nfunctools\ncontextlib\n\n", "One suggestion is to find an open-source project in Python, and start contributing. You may ask \"how can I contribute, if I'm a beginner?\". One answer is \"write tests\". Almost any project will welcome you as a tester. Another answer is \"documentation\", though that is less likely to give immediate benefits.\n", "The already-posted answers are great.\nIn addition, whenever you're coding something in Python and you start doing something that feels clumsy, take a step back and think. If you can't think of a more elegant way to do it, post it as a question on Stack Overflow. I can't count the number of times that I've seen someone reduce ten lines of Python into one (which is still perfectly easy to read and understand).\n", "in addition to suggestions pointed by \"The MYYN\" I would suggest use of pylint\n" ]
[ 24, 4, 4, 3, 3 ]
[]
[]
[ "python" ]
stackoverflow_0001908250_python.txt
Q: xml.dom.minidom python issue from xml.dom.minidom import * resp = "<title> This is a test! </title>" rssDoc = parseString(resp) titles = rssDoc.getElementsByTagName('title') moo = "" for t in titles: moo += t.nodeValue; Gives the following error: main.py, line 42, in get moo += t.nodeValue; TypeError: cannot concatenate 'str' and 'NoneType' objects A: The <title> node contains a text node as a subnode. Maybe you want to iterate through the subnodes instead? Something like this: from xml.dom.minidom import * resp = "<title> This is a test! </title>" rssDoc = parseString(resp) titles = rssDoc.getElementsByTagName('title') moo = "" for t in titles: for child in t.childNodes: if child.nodeType == child.TEXT_NODE: moo += child.data else: moo += "not text " print moo For learning xml.dom.minidom you might also check out the section in Dive Into Python. A: Because is not a text node, but an element node. The text node which contains the " This is a test! " string is actually a child node of this element node. So you can try this (untested, not assumes existence of the text node): if t.nodeType == t.ELEMENT_NODE: moo += t.childNodes[0].data A: because t.nodeType is not equal to t.TEXT_NODE of course.
xml.dom.minidom python issue
from xml.dom.minidom import * resp = "<title> This is a test! </title>" rssDoc = parseString(resp) titles = rssDoc.getElementsByTagName('title') moo = "" for t in titles: moo += t.nodeValue; Gives the following error: main.py, line 42, in get moo += t.nodeValue; TypeError: cannot concatenate 'str' and 'NoneType' objects
[ "The <title> node contains a text node as a subnode. Maybe you want to iterate through the subnodes instead? Something like this:\nfrom xml.dom.minidom import *\n\nresp = \"<title> This is a test! </title>\"\n\nrssDoc = parseString(resp)\n\ntitles = rssDoc.getElementsByTagName('title')\n\nmoo = \"\"\n\nfor t in titles:\n for child in t.childNodes:\n if child.nodeType == child.TEXT_NODE:\n moo += child.data\n else:\n moo += \"not text \"\n\nprint moo\n\nFor learning xml.dom.minidom you might also check out the section in Dive Into Python.\n", "Because is not a text node, but an element node. The text node which contains the \" This is a test! \" string is actually a child node of this element node.\nSo you can try this (untested, not assumes existence of the text node):\nif t.nodeType == t.ELEMENT_NODE:\n moo += t.childNodes[0].data\n\n", "because t.nodeType is not equal to t.TEXT_NODE of course.\n" ]
[ 2, 1, 0 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0001913613_python_xml.txt
Q: db.Model class variables and __init__ (New to Python and GAE) I'm looking for an explanation to the use of class variables in db.Model subclasses, which are treated like instance variables. Why are these declared in class scope and not in __init__? Is this some kind of special GAE requirement? A: Yes, this is a programming model special to GAE. You can think of the class properties as the table definition. The instance properties are the contents of a row, they are populated on the fly by the metclass db.PropertiedClass. There is a lot going on under the hood, if you are interested always have a look at the source: http://code.google.com/p/googleappengine/source/browse/trunk/python/google/appengine/ext/db/init.py
db.Model class variables and __init__
(New to Python and GAE) I'm looking for an explanation to the use of class variables in db.Model subclasses, which are treated like instance variables. Why are these declared in class scope and not in __init__? Is this some kind of special GAE requirement?
[ "Yes, this is a programming model special to GAE. You can think of the class properties as the table definition. The instance properties are the contents of a row, they are populated on the fly by the metclass db.PropertiedClass.\nThere is a lot going on under the hood, if you are interested always have a look at the source:\nhttp://code.google.com/p/googleappengine/source/browse/trunk/python/google/appengine/ext/db/init.py\n" ]
[ 3 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0001913775_google_app_engine_python.txt
Q: Best place to coerce/convert to the right type in Python I'm still fairly new to Python and I'm trying to get used to its dynamic typing. Sometimes I have a function or a class that expects a parameter of a certain type, but could get a value of another type that's coercible to it. For example, it might expect a float but instead receive an int or a decimal. Or it might expect a string, but instead receive an object that defines the __str__ special method. What is the best practice for coercing the argument to the right type (and the reason for it)? Do I do it in the function/class or in the caller? If in the caller, do I also check for it in the function? Eg. Alternative 1: def myfunc(takes_float): myval = float(takes_float) myfunc(5) Alternative 2: def myfunc(takes_float): myval = takes_float myfunc(float(5)) Alternative 3: def myfunc(takes_float): assert isinstance(takes_float, float) myval = takes_float myfunc(float(5)) I've already read this answer and this one and they say that checking types in Python is "bad", but I don't want to waste time tracking down very simple bugs which would be instantly picked up by the compiler in a statically typed language. A: You "coerce" (perhaps -- it could be a noop) when it's indispensable for you to do so, and no earlier. For example, say you have a function that takes a float and returns the sum of its sine and cosine: import math def spc(x): math.sin(x) + math.cos(x) Where should you "coerce" x to float? Answer: nowhere at all -- sin and cos do that job for you, e.g.: >>> spc(decimal.Decimal('1.9')) 0.62301052082391117 So when it is indispensable to coerce (as late as possible)? For example, if you want to call string methods on an argument, you do have to make sure it's a string -- trying to call e.g. .lower on a non-string won't work, len might work but do something different than you expect if the arg is e.g. a list (give you the number of items in the list, not the number of characters its representation as a string will take up), and so forth. As for catching errors -- think unit tests -- semidecent unit tests will catch all errors static typing would, and then some. But, that's a different subject. A: It really depends. Why do you need a float? Would an int break the function? If so, why? If you need the parameter to support a function/property that a float has but an int does not you should check for that function/property, not that the parameter happens to be a float. Check that the object can do what you need it to do, not that it happens to be a particular type that you're familiar with. Who knows, maybe someone will find some major problem with Python's implementation of float and create a notbrokenfloat library. It might support everything a float does while fixing some exotic bug, but its objects wouldn't be of type float. Manually casting it to a float might remove all the benefits of this nifty new class (or could break outright). Yes, that's an unlikely example, but I think that's the right mindset to get into when working with a dynamically typed language. A: There is exactly one time when integer vs. float will be a problem. This is the only time when you will find a "simple" bug that's weird and a challenge to debug. Division. Everything else does the conversion you need when you need it. If you are using Python 2.x and casually throwing around / operators without thinking, you can -- under some common circumstances -- wind up doing the wrong thing. You have several choices. from __future__ import division will give you Python 3 semantics for division. Run with the -Qnew option at all times to get the new division semantics. Use float near / operations. Division is the only place where type can matter. It's the only time that integers behave differently from floats in a way that silently affects your results. All other type mismatch problems will fail spectacularly with a TypeError exception. All others. You won't waste time debugging. You'll know immediately what's wrong. To be more specific. There's no debugging of "expect a string but didn't get a string". This will crash immediately with a traceback. No confusion. No time lost thinking. If a function expects a string, then the caller must provide the string -- that's the rule. Alternative 2 above is used RARELY to correct the problem where you have a function that expects a string AND you got confused and forgot to provide a string. This mistake happens RARELY and it leads to an immediate type exception.
Best place to coerce/convert to the right type in Python
I'm still fairly new to Python and I'm trying to get used to its dynamic typing. Sometimes I have a function or a class that expects a parameter of a certain type, but could get a value of another type that's coercible to it. For example, it might expect a float but instead receive an int or a decimal. Or it might expect a string, but instead receive an object that defines the __str__ special method. What is the best practice for coercing the argument to the right type (and the reason for it)? Do I do it in the function/class or in the caller? If in the caller, do I also check for it in the function? Eg. Alternative 1: def myfunc(takes_float): myval = float(takes_float) myfunc(5) Alternative 2: def myfunc(takes_float): myval = takes_float myfunc(float(5)) Alternative 3: def myfunc(takes_float): assert isinstance(takes_float, float) myval = takes_float myfunc(float(5)) I've already read this answer and this one and they say that checking types in Python is "bad", but I don't want to waste time tracking down very simple bugs which would be instantly picked up by the compiler in a statically typed language.
[ "You \"coerce\" (perhaps -- it could be a noop) when it's indispensable for you to do so, and no earlier. For example, say you have a function that takes a float and returns the sum of its sine and cosine:\nimport math\ndef spc(x):\n math.sin(x) + math.cos(x)\n\nWhere should you \"coerce\" x to float? Answer: nowhere at all -- sin and cos do that job for you, e.g.:\n>>> spc(decimal.Decimal('1.9'))\n0.62301052082391117\n\nSo when it is indispensable to coerce (as late as possible)? For example, if you want to call string methods on an argument, you do have to make sure it's a string -- trying to call e.g. .lower on a non-string won't work, len might work but do something different than you expect if the arg is e.g. a list (give you the number of items in the list, not the number of characters its representation as a string will take up), and so forth.\nAs for catching errors -- think unit tests -- semidecent unit tests will catch all errors static typing would, and then some. But, that's a different subject.\n", "It really depends. Why do you need a float? Would an int break the function? If so, why?\nIf you need the parameter to support a function/property that a float has but an int does not you should check for that function/property, not that the parameter happens to be a float. Check that the object can do what you need it to do, not that it happens to be a particular type that you're familiar with.\nWho knows, maybe someone will find some major problem with Python's implementation of float and create a notbrokenfloat library. It might support everything a float does while fixing some exotic bug, but its objects wouldn't be of type float. Manually casting it to a float might remove all the benefits of this nifty new class (or could break outright).\nYes, that's an unlikely example, but I think that's the right mindset to get into when working with a dynamically typed language.\n", "There is exactly one time when integer vs. float will be a problem. This is the only time when you will find a \"simple\" bug that's weird and a challenge to debug.\nDivision.\nEverything else does the conversion you need when you need it.\nIf you are using Python 2.x and casually throwing around / operators without thinking, you can -- under some common circumstances -- wind up doing the wrong thing.\nYou have several choices.\n\nfrom __future__ import division will give you Python 3 semantics for division.\nRun with the -Qnew option at all times to get the new division semantics.\nUse float near / operations.\n\nDivision is the only place where type can matter. It's the only time that integers behave differently from floats in a way that silently affects your results.\nAll other type mismatch problems will fail spectacularly with a TypeError exception. All others. You won't waste time debugging. You'll know immediately what's wrong.\n\nTo be more specific.\nThere's no debugging of \"expect a string but didn't get a string\". This will crash immediately with a traceback. No confusion. No time lost thinking. If a function expects a string, then the caller must provide the string -- that's the rule.\nAlternative 2 above is used RARELY to correct the problem where you have a function that expects a string AND you got confused and forgot to provide a string. This mistake happens RARELY and it leads to an immediate type exception.\n" ]
[ 8, 2, 0 ]
[]
[]
[ "dynamic_typing", "python" ]
stackoverflow_0001912476_dynamic_typing_python.txt
Q: Django + MySQL on Mac OS 10.6.2 Snow Leopard There were some excellent answers to this question already, however, they are now outdated. I've been able to get the module installed, but "python manage.py runserver" fails with iMac:myproject drhoden$ python manage.py runserver Validating models... Unhandled exception in thread started by <function inner_run at 0x10496f0> Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/commands/runserver.py", line 48, in inner_run self.validate(display_num_errors=True) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/base.py", line 249, in validate num_errors = get_validation_errors(s, app) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/validation.py", line 22, in get_validation_errors from django.db import models, connection File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/__init__.py", line 41, in <module> backend = load_backend(settings.DATABASE_ENGINE) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/__init__.py", line 17, in load_backend return import_module('.base', 'django.db.backends.%s' % backend_name) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/utils/importlib.py", line 35, in import_module __import__(name) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/backends/mysql/base.py", line 13, in <module> raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: dynamic module does not define init function (init_mysql) ^CiMac:segisys drhoden$ Likewise, from the python shell: iMac:myproject drhoden$ python Python 2.6.4 (r264:75821M, Oct 27 2009, 19:48:32) [GCC 4.0.1 (Apple Inc. build 5493)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import MySQLdb Traceback (most recent call last): File "<stdin>", line 1, in <module> File "build/bdist.macosx-10.3-fat/egg/MySQLdb/__init__.py", line 19, in <module> File "build/bdist.macosx-10.3-fat/egg/_mysql.py", line 7, in <module> File "build/bdist.macosx-10.3-fat/egg/_mysql.py", line 6, in __bootstrap__ ImportError: dynamic module does not define init function (init_mysql) >>> Using MySQL-python-1.2.3c1 with setuptools-0.6c11-py2.6.egg Any help would be appreciated. A: I have ultimately solved my own problem, with of course, the subconscious and conscious help from the many posts, blogs, and mail logs I've read. I would give links if I could remember. In a nutshell, I reinstalled EVERYTHING using MacPorts. After editing ~/.bash_profile and commenting out all the previous modifications to ${PATH}, I downloaded the dmg for Snow Leopard and ran through its installation. Then opened the terminal and ran the self update. sudo port selfupdate sudo port install python26 That second part, installing Python 2.6, took forever. But when it completed it prompted me with the following: To fully complete your installation and make python 2.6 the default, please run sudo port install python_select sudo python_select python26 I did both and they went quick. I forgot to mention how handy 'port search ' command is. I searched for 'mysql' and similar to find the thing to type after 'install'. But I proceeded with reinstalling both the client and server for MySQL. Perhaps I did this in reverse order, but the end result worked fine. sudo port install mysql5 ... ---> Installing mysql5 @5.1.41_0 The MySQL client has been installed. If you also want a MySQL server, install the mysql5-server port. So naturally: sudo port install mysql5-server I love how the so many of the macports installations give you feedback as to what to do next. At the end of the server installation, it said the following: ****************************************************** * In order to setup the database, you might want to run * sudo -u _mysql mysql_install_db5 * if this is a new install ****************************************************** It was a new install for me (didn't have any local schemas). For completeness, and for my own reference, here is the output of running that command: Installing MySQL system tables... OK Filling help tables... OK To start mysqld at boot time you have to copy support-files/mysql.server to the right place for your system PLEASE REMEMBER TO SET A PASSWORD FOR THE MySQL root USER ! To do so, start the server, then issue the following commands: /opt/local/lib/mysql5/bin/mysqladmin -u root password 'new-password' /opt/local/lib/mysql5/bin/mysqladmin -u root -h iMac.local password 'new-password' Alternatively you can run: /opt/local/lib/mysql5/bin/mysql_secure_installation which will also give you the option of removing the test databases and anonymous user created by default. This is strongly recommended for production servers. See the manual for more instructions. You can start the MySQL daemon with: cd /opt/local ; /opt/local/lib/mysql5/bin/mysqld_safe & You can test the MySQL daemon with mysql-test-run.pl cd /opt/local/mysql-test ; perl mysql-test-run.pl Please report any problems with the /opt/local/lib/mysql5/bin/mysqlbug script! The latest information about MySQL is available at http://www.mysql.com/ Support MySQL by buying support/licenses from http://shop.mysql.com/ Almost done. Earlier in my 'port search'ing I came across this interesting port: py26-mysql @1.2.2 (python, devel, databases) Python interface to mysql With much, much hope that this would provide me with MySQLdb package, I installed it (and it did). sudo port install py26-mysql Afterwords I cranked up the python interpreter attempted to import MySQLdb, the very thing in my way all this time. iMac:~ drhoden$ python Python 2.6.4 (r264:75706, Dec 15 2009, 18:00:14) [GCC 4.2.1 (Apple Inc. build 5646) (dot 1)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import MySQLdb /opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/MySQLdb/__init__.py:34: DeprecationWarning: the sets module is deprecated from sets import ImmutableSet >>> A warning, but It worked!! Just one more thing: sudo port install py26-django After all of this I was finally able to crank up my Django project and remotely connect to my company's MySQL server!! It may not have been necessary to reinstall Django using MacPorts, but I wasn't going to risk complications. A: I wrote a blog post a few months ago following my successful installation of MySQL on Snow Leopard: http://jboxer.com/2009/09/installing-mysql-on-snow-leopard/ If you follow those steps, it should (theoretically) fix your problem (which sounds like it's caused by a mix of 32-bit and 64-bit software). By the way, I'm not trying to self-promote here; the text in the blog post is basically what I would've posted here, and I'm trying to apply DRY to more areas of my life :) A: This happens when you have mixed 32 and 64bit software. Basically, for Snow Leopard, you need to install MySQL 64bit package (which still is listed as 10.5, but that is no problem) , after that do an easy install of python-mysql again. All will work.
Django + MySQL on Mac OS 10.6.2 Snow Leopard
There were some excellent answers to this question already, however, they are now outdated. I've been able to get the module installed, but "python manage.py runserver" fails with iMac:myproject drhoden$ python manage.py runserver Validating models... Unhandled exception in thread started by <function inner_run at 0x10496f0> Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/commands/runserver.py", line 48, in inner_run self.validate(display_num_errors=True) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/base.py", line 249, in validate num_errors = get_validation_errors(s, app) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/validation.py", line 22, in get_validation_errors from django.db import models, connection File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/__init__.py", line 41, in <module> backend = load_backend(settings.DATABASE_ENGINE) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/__init__.py", line 17, in load_backend return import_module('.base', 'django.db.backends.%s' % backend_name) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/utils/importlib.py", line 35, in import_module __import__(name) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/backends/mysql/base.py", line 13, in <module> raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: dynamic module does not define init function (init_mysql) ^CiMac:segisys drhoden$ Likewise, from the python shell: iMac:myproject drhoden$ python Python 2.6.4 (r264:75821M, Oct 27 2009, 19:48:32) [GCC 4.0.1 (Apple Inc. build 5493)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import MySQLdb Traceback (most recent call last): File "<stdin>", line 1, in <module> File "build/bdist.macosx-10.3-fat/egg/MySQLdb/__init__.py", line 19, in <module> File "build/bdist.macosx-10.3-fat/egg/_mysql.py", line 7, in <module> File "build/bdist.macosx-10.3-fat/egg/_mysql.py", line 6, in __bootstrap__ ImportError: dynamic module does not define init function (init_mysql) >>> Using MySQL-python-1.2.3c1 with setuptools-0.6c11-py2.6.egg Any help would be appreciated.
[ "I have ultimately solved my own problem, with of course, the subconscious and conscious help from the many posts, blogs, and mail logs I've read. I would give links if I could remember.\nIn a nutshell, I reinstalled EVERYTHING using MacPorts. \nAfter editing ~/.bash_profile and commenting out all the previous modifications to ${PATH}, I downloaded the dmg for Snow Leopard and ran through its installation.\nThen opened the terminal and ran the self update.\nsudo port selfupdate\nsudo port install python26\n\nThat second part, installing Python 2.6, took forever. But when it completed it prompted me with the following:\nTo fully complete your installation and make python 2.6 the default, please run\n\nsudo port install python_select \nsudo python_select python26\n\nI did both and they went quick.\nI forgot to mention how handy 'port search ' command is. I searched for 'mysql' and similar to find the thing to type after 'install'. But I proceeded with reinstalling both the client and server for MySQL. Perhaps I did this in reverse order, but the end result worked fine.\nsudo port install mysql5\n...\n---> Installing mysql5 @5.1.41_0\nThe MySQL client has been installed.\nIf you also want a MySQL server, install the mysql5-server port.\n\nSo naturally:\nsudo port install mysql5-server\n\nI love how the so many of the macports installations give you feedback as to what to do next. At the end of the server installation, it said the following:\n******************************************************\n* In order to setup the database, you might want to run\n* sudo -u _mysql mysql_install_db5\n* if this is a new install\n******************************************************\n\nIt was a new install for me (didn't have any local schemas). For completeness, and for my own reference, here is the output of running that command:\nInstalling MySQL system tables...\nOK\nFilling help tables...\nOK\n\nTo start mysqld at boot time you have to copy\nsupport-files/mysql.server to the right place for your system\n\nPLEASE REMEMBER TO SET A PASSWORD FOR THE MySQL root USER !\nTo do so, start the server, then issue the following commands:\n\n/opt/local/lib/mysql5/bin/mysqladmin -u root password 'new-password'\n/opt/local/lib/mysql5/bin/mysqladmin -u root -h iMac.local password 'new-password'\n\nAlternatively you can run:\n/opt/local/lib/mysql5/bin/mysql_secure_installation\n\nwhich will also give you the option of removing the test\ndatabases and anonymous user created by default. This is\nstrongly recommended for production servers.\n\nSee the manual for more instructions.\n\nYou can start the MySQL daemon with:\ncd /opt/local ; /opt/local/lib/mysql5/bin/mysqld_safe &\n\nYou can test the MySQL daemon with mysql-test-run.pl\ncd /opt/local/mysql-test ; perl mysql-test-run.pl\n\nPlease report any problems with the /opt/local/lib/mysql5/bin/mysqlbug script!\n\nThe latest information about MySQL is available at http://www.mysql.com/\nSupport MySQL by buying support/licenses from http://shop.mysql.com/\n\nAlmost done. Earlier in my 'port search'ing I came across this interesting port:\npy26-mysql @1.2.2 (python, devel, databases)\n Python interface to mysql\nWith much, much hope that this would provide me with MySQLdb package, I installed it (and it did).\nsudo port install py26-mysql\n\nAfterwords I cranked up the python interpreter attempted to import MySQLdb, the very thing in my way all this time.\niMac:~ drhoden$ python\nPython 2.6.4 (r264:75706, Dec 15 2009, 18:00:14) \n[GCC 4.2.1 (Apple Inc. build 5646) (dot 1)] on darwin\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import MySQLdb\n/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/MySQLdb/__init__.py:34: DeprecationWarning: the sets module is deprecated from sets import ImmutableSet\n>>> \n\nA warning, but It worked!!\nJust one more thing:\nsudo port install py26-django\n\nAfter all of this I was finally able to crank up my Django project and remotely connect to my company's MySQL server!! It may not have been necessary to reinstall Django using MacPorts, but I wasn't going to risk complications.\n", "I wrote a blog post a few months ago following my successful installation of MySQL on Snow Leopard:\nhttp://jboxer.com/2009/09/installing-mysql-on-snow-leopard/\nIf you follow those steps, it should (theoretically) fix your problem (which sounds like it's caused by a mix of 32-bit and 64-bit software).\nBy the way, I'm not trying to self-promote here; the text in the blog post is basically what I would've posted here, and I'm trying to apply DRY to more areas of my life :)\n", "This happens when you have mixed 32 and 64bit software. \nBasically, for Snow Leopard, you need to install MySQL 64bit package (which still is listed as 10.5, but that is no problem) , after that do an easy install of python-mysql again. All will work.\n" ]
[ 21, 4, 1 ]
[]
[]
[ "django", "mysql", "osx_snow_leopard", "python" ]
stackoverflow_0001904039_django_mysql_osx_snow_leopard_python.txt
Q: How can I use TOR as a proxy? I'm trying to use TOR as a generic proxy but it fails Right now I'm trying with python but I'm pretty sure it would be the same with any other language. I can connect to other proxies with python so I get how it "should" be done. I found a list of TOR entry nodes h = httplib.HTTPConnection("one entry node", 80) h.connect() h.request("GET", "www.google.com") resp = h.getresponse() page = resp.read() unfortunately that doesnt work, i get redirected to a 404 message. I'm just not sure of what I'm doing wrong. Probably the list of entry nodes cannot be connected just like that. I'm searching on how to do it properly but i dont get any documentation about how to program applications with tor edit : ditch the tor proxy list, i don't know why i should want to know about it. the "entry node" is yourself, after you've installed the (windows) vidalia client and privoxy (all bundled as one) httplib.HTTPConnection("one entry node", 80) becomes httplib.HTTPConnection("127.0.0.1", 8118) and voilà, everything is routed through TOR A: First, make sure you are using the correct node location and port. Most proxies use ports other than 80. Second, specify the protocol to use with the correct URL on your request string. Under normal circumstances, your code should work if it looks something like this one: h = httplib.HTTPConnection("138.45.68.134", 8080) h.connect() h.request("GET", "http://www.google.com") resp = h.getresponse() page = resp.read() h.close(); You can also use socket as an alternative but that's another issue and it's even more complicated than the one above. Hope that helps! :-)
How can I use TOR as a proxy?
I'm trying to use TOR as a generic proxy but it fails Right now I'm trying with python but I'm pretty sure it would be the same with any other language. I can connect to other proxies with python so I get how it "should" be done. I found a list of TOR entry nodes h = httplib.HTTPConnection("one entry node", 80) h.connect() h.request("GET", "www.google.com") resp = h.getresponse() page = resp.read() unfortunately that doesnt work, i get redirected to a 404 message. I'm just not sure of what I'm doing wrong. Probably the list of entry nodes cannot be connected just like that. I'm searching on how to do it properly but i dont get any documentation about how to program applications with tor edit : ditch the tor proxy list, i don't know why i should want to know about it. the "entry node" is yourself, after you've installed the (windows) vidalia client and privoxy (all bundled as one) httplib.HTTPConnection("one entry node", 80) becomes httplib.HTTPConnection("127.0.0.1", 8118) and voilà, everything is routed through TOR
[ "First, make sure you are using the correct node location and port. Most proxies use ports other than 80. Second, specify the protocol to use with the correct URL on your request string.\nUnder normal circumstances, your code should work if it looks something like this one:\nh = httplib.HTTPConnection(\"138.45.68.134\", 8080)\nh.connect()\nh.request(\"GET\", \"http://www.google.com\")\nresp = h.getresponse()\npage = resp.read()\nh.close();\n\nYou can also use socket as an alternative but that's another issue and it's even more complicated than the one above.\nHope that helps! :-)\n" ]
[ 4 ]
[]
[]
[ "language_agnostic", "proxies", "proxy", "python", "tor" ]
stackoverflow_0001914254_language_agnostic_proxies_proxy_python_tor.txt
Q: Python string pattern recognition/compression I can do basic regex alright, but this is slightly different, namely I don't know what the pattern is going to be. For example, I have a list of similar strings: lst = ['asometxt0moretxt', 'bsometxt1moretxt', 'aasometxt10moretxt', 'zzsometxt999moretxt'] In this case the common pattern is two segments of common text: 'sometxt' and 'moretxt', starting and separated by something else that is variable in length. The common string and variable string can of course occur at any order and at any number of occasions. What would be a good way to condense/compress the list of strings into their common parts and individual variations? An example output might be: c = ['sometxt', 'moretxt'] v = [('a','0'), ('b','1'), ('aa','10'), ('zz','999')] A: This solution finds the two longest common substrings and uses them to delimit the input strings: def an_answer_to_stackoverflow_question_1914394(lst): """ >>> lst = ['asometxt0moretxt', 'bsometxt1moretxt', 'aasometxt10moretxt', 'zzsometxt999moretxt'] >>> an_answer_to_stackoverflow_question_1914394(lst) (['sometxt', 'moretxt'], [('a', '0'), ('b', '1'), ('aa', '10'), ('zz', '999')]) """ delimiters = find_delimiters(lst) return delimiters, list(split_strings(lst, delimiters)) find_delimiters and friends finds the delimiters: import itertools def find_delimiters(lst): """ >>> lst = ['asometxt0moretxt', 'bsometxt1moretxt', 'aasometxt10moretxt', 'zzsometxt999moretxt'] >>> find_delimiters(lst) ['sometxt', 'moretxt'] """ candidates = list(itertools.islice(find_longest_common_substrings(lst), 3)) if len(candidates) == 3 and len(candidates[1]) == len(candidates[2]): raise ValueError("Unable to find useful delimiters") if candidates[1] in candidates[0]: raise ValueError("Unable to find useful delimiters") return candidates[0:2] def find_longest_common_substrings(lst): """ >>> lst = ['asometxt0moretxt', 'bsometxt1moretxt', 'aasometxt10moretxt', 'zzsometxt999moretxt'] >>> list(itertools.islice(find_longest_common_substrings(lst), 3)) ['sometxt', 'moretxt', 'sometx'] """ for i in xrange(min_length(lst), 0, -1): for substring in common_substrings(lst, i): yield substring def min_length(lst): return min(len(item) for item in lst) def common_substrings(lst, length): """ >>> list(common_substrings(["hello", "world"], 2)) [] >>> list(common_substrings(["aabbcc", "dbbrra"], 2)) ['bb'] """ assert length <= min_length(lst) returned = set() for i, item in enumerate(lst): for substring in all_substrings(item, length): in_all_others = True for j, other_item in enumerate(lst): if j == i: continue if substring not in other_item: in_all_others = False if in_all_others: if substring not in returned: returned.add(substring) yield substring def all_substrings(item, length): """ >>> list(all_substrings("hello", 2)) ['he', 'el', 'll', 'lo'] """ for i in range(len(item) - length + 1): yield item[i:i+length] split_strings splits the strings using the delimiters: import re def split_strings(lst, delimiters): """ >>> lst = ['asometxt0moretxt', 'bsometxt1moretxt', 'aasometxt10moretxt', 'zzsometxt999moretxt'] >>> list(split_strings(lst, find_delimiters(lst))) [('a', '0'), ('b', '1'), ('aa', '10'), ('zz', '999')] """ for item in lst: parts = re.split("|".join(delimiters), item) yield tuple(part for part in parts if part != '') A: Here is a scary one to get the ball rolling. >>> import re >>> makere = lambda n: ''.join(['(.*?)(.+)(.*?)(.+)(.*?)'] + ['(.*)(\\2)(.*)(\\4)(.*)'] * (n - 1)) >>> inp = ['asometxt0moretxt', 'bsometxt1moretxt', 'aasometxt10moretxt', 'zzsometxt999moretxt'] >>> re.match(makere(len(inp)), ''.join(inp)).groups() ('a', 'sometxt', '0', 'moretxt', '', 'b', 'sometxt', '1', 'moretxt', 'aa', '', 'sometxt', '10', 'moretxt', 'zz', '', 'sometxt', '999', 'moretxt', '') I hope its sheer ugliness will inspire better solutions :) A: This look much like the LZW algorithm for data (text) compression. There should be python implementations out there, which you may be able to adapt to your need. I assume you have no a priori knowledge of these sub strings that repeat often. A: This seems to be an example of the longest common subsequence problem. One way could be to look at how diffs are generated. The Hunt-McIlroy algorithm seems to have been the first, and is such the simplest, especially since it apparently is non-heuristic. The first link contains detailed discussion and (pseudo) code examples. Assuming, of course, Im not completely of the track here. A: I guess you should start by identifying substrings (patterns) that frequently occur in the strings. Since naively counting substrings in a set of strings is rather computationally expensive, you'll need to come up with something smart. I've done substring counting on a large amount of data using generalized suffix trees (example here). Once you know the most frequent substrings/patterns in the data, you can take it from there.
Python string pattern recognition/compression
I can do basic regex alright, but this is slightly different, namely I don't know what the pattern is going to be. For example, I have a list of similar strings: lst = ['asometxt0moretxt', 'bsometxt1moretxt', 'aasometxt10moretxt', 'zzsometxt999moretxt'] In this case the common pattern is two segments of common text: 'sometxt' and 'moretxt', starting and separated by something else that is variable in length. The common string and variable string can of course occur at any order and at any number of occasions. What would be a good way to condense/compress the list of strings into their common parts and individual variations? An example output might be: c = ['sometxt', 'moretxt'] v = [('a','0'), ('b','1'), ('aa','10'), ('zz','999')]
[ "This solution finds the two longest common substrings and uses them to delimit the input strings:\ndef an_answer_to_stackoverflow_question_1914394(lst):\n \"\"\"\n >>> lst = ['asometxt0moretxt', 'bsometxt1moretxt', 'aasometxt10moretxt', 'zzsometxt999moretxt']\n >>> an_answer_to_stackoverflow_question_1914394(lst)\n (['sometxt', 'moretxt'], [('a', '0'), ('b', '1'), ('aa', '10'), ('zz', '999')])\n \"\"\"\n delimiters = find_delimiters(lst)\n return delimiters, list(split_strings(lst, delimiters))\n\nfind_delimiters and friends finds the delimiters:\nimport itertools\n\ndef find_delimiters(lst):\n \"\"\"\n >>> lst = ['asometxt0moretxt', 'bsometxt1moretxt', 'aasometxt10moretxt', 'zzsometxt999moretxt']\n >>> find_delimiters(lst)\n ['sometxt', 'moretxt']\n \"\"\"\n candidates = list(itertools.islice(find_longest_common_substrings(lst), 3))\n if len(candidates) == 3 and len(candidates[1]) == len(candidates[2]):\n raise ValueError(\"Unable to find useful delimiters\")\n if candidates[1] in candidates[0]:\n raise ValueError(\"Unable to find useful delimiters\")\n return candidates[0:2]\n\ndef find_longest_common_substrings(lst):\n \"\"\"\n >>> lst = ['asometxt0moretxt', 'bsometxt1moretxt', 'aasometxt10moretxt', 'zzsometxt999moretxt']\n >>> list(itertools.islice(find_longest_common_substrings(lst), 3))\n ['sometxt', 'moretxt', 'sometx']\n \"\"\"\n for i in xrange(min_length(lst), 0, -1):\n for substring in common_substrings(lst, i):\n yield substring\n\n\ndef min_length(lst):\n return min(len(item) for item in lst)\n\ndef common_substrings(lst, length):\n \"\"\"\n >>> list(common_substrings([\"hello\", \"world\"], 2))\n []\n >>> list(common_substrings([\"aabbcc\", \"dbbrra\"], 2))\n ['bb']\n \"\"\"\n assert length <= min_length(lst)\n returned = set()\n for i, item in enumerate(lst):\n for substring in all_substrings(item, length):\n in_all_others = True\n for j, other_item in enumerate(lst):\n if j == i:\n continue\n if substring not in other_item:\n in_all_others = False\n if in_all_others:\n if substring not in returned:\n returned.add(substring)\n yield substring\n\ndef all_substrings(item, length):\n \"\"\"\n >>> list(all_substrings(\"hello\", 2))\n ['he', 'el', 'll', 'lo']\n \"\"\"\n for i in range(len(item) - length + 1):\n yield item[i:i+length]\n\nsplit_strings splits the strings using the delimiters:\nimport re\n\ndef split_strings(lst, delimiters):\n \"\"\"\n >>> lst = ['asometxt0moretxt', 'bsometxt1moretxt', 'aasometxt10moretxt', 'zzsometxt999moretxt']\n >>> list(split_strings(lst, find_delimiters(lst)))\n [('a', '0'), ('b', '1'), ('aa', '10'), ('zz', '999')]\n \"\"\"\n for item in lst:\n parts = re.split(\"|\".join(delimiters), item)\n yield tuple(part for part in parts if part != '')\n\n", "Here is a scary one to get the ball rolling.\n>>> import re\n>>> makere = lambda n: ''.join(['(.*?)(.+)(.*?)(.+)(.*?)'] + ['(.*)(\\\\2)(.*)(\\\\4)(.*)'] * (n - 1))\n>>> inp = ['asometxt0moretxt', 'bsometxt1moretxt', 'aasometxt10moretxt', 'zzsometxt999moretxt']\n>>> re.match(makere(len(inp)), ''.join(inp)).groups()\n('a', 'sometxt', '0', 'moretxt', '', 'b', 'sometxt', '1', 'moretxt', 'aa', '', 'sometxt', '10', 'moretxt', 'zz', '', 'sometxt', '999', 'moretxt', '')\n\nI hope its sheer ugliness will inspire better solutions :)\n", "This look much like the LZW algorithm for data (text) compression. There should be python implementations out there, which you may be able to adapt to your need.\nI assume you have no a priori knowledge of these sub strings that repeat often.\n", "This seems to be an example of the longest common subsequence problem. One way could be to look at how diffs are generated. The Hunt-McIlroy algorithm seems to have been the first, and is such the simplest, especially since it apparently is non-heuristic.\nThe first link contains detailed discussion and (pseudo) code examples. Assuming, of course, Im not completely of the track here.\n", "I guess you should start by identifying substrings (patterns) that frequently occur in the strings. Since naively counting substrings in a set of strings is rather computationally expensive, you'll need to come up with something smart.\nI've done substring counting on a large amount of data using generalized suffix trees (example here). Once you know the most frequent substrings/patterns in the data, you can take it from there.\n" ]
[ 8, 3, 2, 2, 1 ]
[ "How about subbing out the known text, and then splitting?\nimport re\n[re.sub('(sometxt|moretxt)', ',', x).split(',') for x in lst]\n# results in\n[['a', '0', ''], ['b', '1', ''], ['aa', '10', ''], ['zz', '999', '']]\n\n" ]
[ -1 ]
[ "compression", "pattern_recognition", "python", "string" ]
stackoverflow_0001914236_compression_pattern_recognition_python_string.txt
Q: How does this max() expression in Python work? Here's the code: a = [1,2,3,4] b = {} b[1] = 10 b[2] = 8 b[3] = 7 b[4] = 5 print max(a,key=lambda w: b[w]) This prints out 1. I don't understand how max(a,key=lambda w: b[w]) is being evaluated here though; I'm guessing for each value i in a, it finds the corresponding value b[i] by saving the current value of i as w in the lambda function getting the corresponding value from b[i] and storing it in key. But then why does it print out 1 instead of 11? Or why doesn't it print out 10, since that's really the maximum number? A: max(a,...) is always going to return an element of a. So the result will be either 1,2,3, or 4. For each value w in a, the key value is b[w]. The largest key value is 10, and that corresponds with w equalling 1. So max(a,key=lambda w: b[w]) returns 1.
How does this max() expression in Python work?
Here's the code: a = [1,2,3,4] b = {} b[1] = 10 b[2] = 8 b[3] = 7 b[4] = 5 print max(a,key=lambda w: b[w]) This prints out 1. I don't understand how max(a,key=lambda w: b[w]) is being evaluated here though; I'm guessing for each value i in a, it finds the corresponding value b[i] by saving the current value of i as w in the lambda function getting the corresponding value from b[i] and storing it in key. But then why does it print out 1 instead of 11? Or why doesn't it print out 10, since that's really the maximum number?
[ "max(a,...) is always going to return an element of a. So the result will be either 1,2,3, or 4.\nFor each value w in a, the key value is b[w]. The largest key value is 10, and that corresponds with w equalling 1. So max(a,key=lambda w: b[w]) returns 1.\n" ]
[ 9 ]
[ "Try:\na = [1,2,3,4]\nb = {}\nb[1] = 10\nb[2] = 8\nb[3] = 7\nb[4] = 5\nc = a + b.values()\nprint max(*c)\n\n" ]
[ -3 ]
[ "lambda", "max", "python" ]
stackoverflow_0001911981_lambda_max_python.txt
Q: How to open a webpage and search for a word in python How to open a webpage and search for a word in python? A: This is a little simplified: >>> import urllib >>> import re >>> page = urllib.urlopen("http://google.com").read() # => via regular expression >>> re.findall("Shopping", page) ['Shopping'] # => via string.find, returns the position ... >>> page.find("Shopping") 2716 First, get the page (e.g. via urllib.urlopen). Second use a regular expression to find portions of the text, you are interested in. Or use string.find. A: you can use urllib2 import urllib2 webp=urllib2.urlopen("the_page").read() webp.find("the_word") hope that helps :D A: How to open a webpage? I think the most convinient way is: from urllib2 import urlopen page = urlopen('http://www.example.com').read() How to search for a word? I guess you are going to search for some pattern in the page next, so here we go: import re pattern = re.compile('^some regex$') match = pattern.search(page)
How to open a webpage and search for a word in python
How to open a webpage and search for a word in python?
[ "This is a little simplified:\n>>> import urllib\n>>> import re\n>>> page = urllib.urlopen(\"http://google.com\").read()\n\n# => via regular expression\n\n>>> re.findall(\"Shopping\", page)\n['Shopping']\n\n# => via string.find, returns the position ...\n>>> page.find(\"Shopping\")\n2716\n\nFirst, get the page (e.g. via urllib.urlopen). Second use a regular expression to find portions of the text, you are interested in. Or use string.find.\n", "you can use urllib2\nimport urllib2\n\nwebp=urllib2.urlopen(\"the_page\").read()\n\nwebp.find(\"the_word\")\n\nhope that helps :D\n", "How to open a webpage?\nI think the most convinient way is:\nfrom urllib2 import urlopen\n\npage = urlopen('http://www.example.com').read()\n\nHow to search for a word?\nI guess you are going to search for some pattern in the page next, so here we go:\nimport re\npattern = re.compile('^some regex$')\nmatch = pattern.search(page)\n\n" ]
[ 4, 0, 0 ]
[]
[]
[ "http", "python" ]
stackoverflow_0001913871_http_python.txt
Q: Pickling a staticmethod in Python I've been trying to pickle an object which contains references to static class methods. Pickle fails (for example on module.MyClass.foo) stating it cannot be pickled, as module.foo does not exist. I have come up with the following solution, using a wrapper object to locate the function upon invocation, saving the container class and function name: class PicklableStaticMethod(object): """Picklable version of a static method. Typical usage: class MyClass: @staticmethod def doit(): print "done" # This cannot be pickled: non_picklable = MyClass.doit # This can be pickled: picklable = PicklableStaticMethod(MyClass.doit, MyClass) """ def __init__(self, func, parent_class): self.func_name = func.func_name self.parent_class = parent_class def __call__(self, *args, **kwargs): func = getattr(self.parent_class, self.func_name) return func(*args, **kwargs) I am wondering though, is there a better - more standard way - to pickle such an object? I do not want to make changes to the global pickle process (using copy_reg for example), but the following pattern would be great: class MyClass(object): @picklable_staticmethod def foo(): print "done." My attempts at this were unsuccessful, specifically because I could not extract the owner class from the foo function. I was even willing to settle for explicit specification (such as @picklable_staticmethod(MyClass)) but I don't know of any way to refer to the MyClass class right where it's being defined. Any ideas would be great! Yonatan A: This seems to work. class PickleableStaticMethod(object): def __init__(self, fn, cls=None): self.cls = cls self.fn = fn def __call__(self, *args, **kwargs): return self.fn(*args, **kwargs) def __get__(self, obj, cls): return PickleableStaticMethod(self.fn, cls) def __getstate__(self): return (self.cls, self.fn.__name__) def __setstate__(self, state): self.cls, name = state self.fn = getattr(self.cls, name).fn The trick is to snag the class when the static method is gotten from it. Alternatives: You could use metaclassing to give all your static methods a .__parentclass__ attribute. Then you could subclass Pickler and give each subclass instance its own .dispatch table which you can then modify without affecting the global dispatch table (Pickler.dispatch). Pickling, unpickling, and calling the method might then be a little faster. A: EDIT: modified after Jason comment. I think python is correct in not letting pickling a staticmethod object - as it is impossible to pickle instance or class methods! Such an object would make very little sense outside of its context: Check this: Descriptor Tutorial import pickle def dosomething(a, b): print a, b class MyClass(object): dosomething = staticmethod(dosomething) o = MyClass() pickled = pickle.dumps(dosomething) This works, and that's what should be done - define a function, pickle it, and use such function as a staticmethod in a certain class. If you've got an use case for your need, please write it down and I'll be glad to discuss it.
Pickling a staticmethod in Python
I've been trying to pickle an object which contains references to static class methods. Pickle fails (for example on module.MyClass.foo) stating it cannot be pickled, as module.foo does not exist. I have come up with the following solution, using a wrapper object to locate the function upon invocation, saving the container class and function name: class PicklableStaticMethod(object): """Picklable version of a static method. Typical usage: class MyClass: @staticmethod def doit(): print "done" # This cannot be pickled: non_picklable = MyClass.doit # This can be pickled: picklable = PicklableStaticMethod(MyClass.doit, MyClass) """ def __init__(self, func, parent_class): self.func_name = func.func_name self.parent_class = parent_class def __call__(self, *args, **kwargs): func = getattr(self.parent_class, self.func_name) return func(*args, **kwargs) I am wondering though, is there a better - more standard way - to pickle such an object? I do not want to make changes to the global pickle process (using copy_reg for example), but the following pattern would be great: class MyClass(object): @picklable_staticmethod def foo(): print "done." My attempts at this were unsuccessful, specifically because I could not extract the owner class from the foo function. I was even willing to settle for explicit specification (such as @picklable_staticmethod(MyClass)) but I don't know of any way to refer to the MyClass class right where it's being defined. Any ideas would be great! Yonatan
[ "This seems to work.\nclass PickleableStaticMethod(object):\n def __init__(self, fn, cls=None):\n self.cls = cls\n self.fn = fn\n def __call__(self, *args, **kwargs):\n return self.fn(*args, **kwargs)\n def __get__(self, obj, cls):\n return PickleableStaticMethod(self.fn, cls)\n def __getstate__(self):\n return (self.cls, self.fn.__name__)\n def __setstate__(self, state):\n self.cls, name = state\n self.fn = getattr(self.cls, name).fn\n\nThe trick is to snag the class when the static method is gotten from it.\nAlternatives: You could use metaclassing to give all your static methods a .__parentclass__ attribute. Then you could subclass Pickler and give each subclass instance its own .dispatch table which you can then modify without affecting the global dispatch table (Pickler.dispatch). Pickling, unpickling, and calling the method might then be a little faster.\n", "EDIT: modified after Jason comment.\nI think python is correct in not letting pickling a staticmethod object - as it is impossible to pickle instance or class methods! Such an object would make very little sense outside of its context:\nCheck this: Descriptor Tutorial\nimport pickle\n\ndef dosomething(a, b):\n print a, b\n\nclass MyClass(object):\n dosomething = staticmethod(dosomething) \n\no = MyClass()\n\npickled = pickle.dumps(dosomething)\n\nThis works, and that's what should be done - define a function, pickle it, and use such function as a staticmethod in a certain class.\nIf you've got an use case for your need, please write it down and I'll be glad to discuss it.\n" ]
[ 5, 0 ]
[]
[]
[ "pickle", "python", "static_methods" ]
stackoverflow_0001914261_pickle_python_static_methods.txt
Q: Alphabetizing functions in a Python class Warning, this is a sheer-laziness query! As my project develops, so also do the number of functions within a class. I also have a number of classes per .py file. So what I would like to do is re-sort them to that the function names are organised [sorry, UK here, I've already compromised hugely with the 'z' in Alphabetizing ;-)] alphabetically. Eg currently: class myClass(): stuff def __init__(): do stuff def b(): also do stuff def c(): do other stuff def a(): do even more stuff ..and for ease of lookup, I'd like to rearrange to: class myClass(): stuff def __init__(): do stuff def a(): do even more stuff def b(): also do stuff def c(): do other stuff purely for cosmetic reasons, as it makes searching for the relevant functions more intuitive. I'd obviously want to keep the init() etc at the top of the class. Now, I can (but haven't yet) do this with a python script that reads in the .py the class(es) reside in as a text file, and do a tonne of string manipulation. But I wonder is there a better way to do this? Perhaps there's a tool I can use somewhere? I've had a good hunt, but I can't really find anything I could use. I'm using emacs, so perhaps there's a big 5-minute key combination sequence that will do the magic (eg), but I can't see anything in python-mode! Finally, I would like some way to be able to visualise and publicise the class structure/docstrings. When I say visualise structure, I mean, for example, where myClass.a() calls myOtherClass.g(), that would be a link, so I'd be able to see what calls what, either on a class-by-class basis (ie, what functions/classes does myClass use?) or overall (here are a bunch of files, how do they 'connect'?) When I say publicise the class, I guess I mean something like the API documentation you see in eg1,eg2. A: I don't have a solution to your question, but I have a very strong opinion: if the number of methods in your classes becomes so large you have trouble finding them, you should consider reducing the number, perhaps by splitting the class into smaller ones. The same principles of cohesion that apply to functions and methods apply to classes as well. A: I am not sure sorting methods by name is such a great idea : That's what you see when browsing OLE objects and it is really hard to understand anything as related methods are all over the place because they dont start by the same letter. I'd rather see "open" just before "close", for example, without all other unrelated methods in between... Your problem is to list / view easily the functions in your class ? Here is a simple trick I use in emacs : M-x occur regex: ^ *def Give it a try ... (the same works for some other languages with a different regex (eg : "^sub ")
Alphabetizing functions in a Python class
Warning, this is a sheer-laziness query! As my project develops, so also do the number of functions within a class. I also have a number of classes per .py file. So what I would like to do is re-sort them to that the function names are organised [sorry, UK here, I've already compromised hugely with the 'z' in Alphabetizing ;-)] alphabetically. Eg currently: class myClass(): stuff def __init__(): do stuff def b(): also do stuff def c(): do other stuff def a(): do even more stuff ..and for ease of lookup, I'd like to rearrange to: class myClass(): stuff def __init__(): do stuff def a(): do even more stuff def b(): also do stuff def c(): do other stuff purely for cosmetic reasons, as it makes searching for the relevant functions more intuitive. I'd obviously want to keep the init() etc at the top of the class. Now, I can (but haven't yet) do this with a python script that reads in the .py the class(es) reside in as a text file, and do a tonne of string manipulation. But I wonder is there a better way to do this? Perhaps there's a tool I can use somewhere? I've had a good hunt, but I can't really find anything I could use. I'm using emacs, so perhaps there's a big 5-minute key combination sequence that will do the magic (eg), but I can't see anything in python-mode! Finally, I would like some way to be able to visualise and publicise the class structure/docstrings. When I say visualise structure, I mean, for example, where myClass.a() calls myOtherClass.g(), that would be a link, so I'd be able to see what calls what, either on a class-by-class basis (ie, what functions/classes does myClass use?) or overall (here are a bunch of files, how do they 'connect'?) When I say publicise the class, I guess I mean something like the API documentation you see in eg1,eg2.
[ "I don't have a solution to your question, but I have a very strong opinion: if the number of methods in your classes becomes so large you have trouble finding them, you should consider reducing the number, perhaps by splitting the class into smaller ones.\nThe same principles of cohesion that apply to functions and methods apply to classes as well.\n", "I am not sure sorting methods by name is such a great idea : \nThat's what you see when browsing OLE objects and it is really hard to understand anything as related methods are all over the place because they dont start by the same letter.\nI'd rather see \"open\" just before \"close\", for example, without all other unrelated methods in between...\nYour problem is to list / view easily the functions in your class ?\nHere is a simple trick I use in emacs :\nM-x occur\nregex: ^ *def\nGive it a try ... (the same works for some other languages with a different regex (eg : \"^sub \")\n" ]
[ 8, 3 ]
[]
[]
[ "alphabetized", "class", "publishing", "python", "visualization" ]
stackoverflow_0001914761_alphabetized_class_publishing_python_visualization.txt
Q: Authenticated request in Google App Engine using fetch() function: how to provide the information in the header of the request? I am trying to pass automatically, using Google App Engine, my password and ID to eBay, to this page: https://signin.ebay.com/ws/eBayISAPI.dll?SignIn&UsingSSL=1&pUserId=&co_partnerId=2&siteid=0&ru=http%3A%2F%2Fcgi5.ebay.com%2Fws2%2FeBayISAPI.dll%3FSellItem%26hm%3Dum.rundkoi376%26%26hc%3D1%26guest%3D1&pageType=1144 (It is where I get redirected to from this URL: https://signin.ebay.com). Here is how the page looks like: (source: narod.ru) Earlier I have asked some questions, and here one very nice supporter suggested that I use code from this link: http://chillorb.com/?p=195 If you have no time to go there, here is how that page looks like: (source: narod.ru) So, I pasted that code into my editor substituting the valid eBay URL, my ID and password. My ID there is seeyousoondanny and the password is happy1 (I created that account on eBay just for experimenting, so I am not afraid to give out my ID and password). Here is how the code looked in my editor: (source: narod.ru) But when I run this code I get only this: (source: narod.ru) What am I doing wrong here? ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Addition: Here is the bottom of the error page (I think it will be seen clearer if you click on the link to this image): +++++++++++++++++++++++++++++++++++++++++++++++++++ Addition: I guess this code has no syntax mistakes: from google.appengine.api import urlfetch import base64 url = "https://signin.ebay.com/ws/eBayISAPI.dll?SignIn&UsingSSL=1&pUserId=&co_partnerId=2&siteid=0&ru=http%3A%2F%2Fcgi5.ebay.com%2Fws2%2FeBayISAPI.dll%3FSellItem%26hm%3Dum.rundkoi376%26%26hc%3D1%26guest%3D1&pageType=1144" authString = 'Basic' + base64.encodestring('seeyousoondanny:happy1') data = urlfetch.fetch(url, headers= {'AUTHORIZATION' : authString }) if data.status_code == 200: print "content-type: text/plain" print print data.status_code A: I'm not sure if this helps, but ebay has an API that would be simpler to use and incorporate. Check out http://developer.ebay.com/businessbenefits/aboutus/ A: Looks like some of the quote-characters are the wrong kind -- reversed "smart quotes" rather than normal plain ordinary ASCII quote characters. Hard to say precisely from screenshots! The error screen you're showing (from GAE's SDK) shows the exact location of the error at the very bottom -- and you're showing it scrolled all the way to the very top, so it doesn't help. In GAE like in any other use of Python quote is done via plain single and double quote characters: ' and " ; not via slanted, inverted, or "smart" quote characters, such as ` (hard to clearly show the inverted single quote in SO except as a codeblock, since it's used to mark inline code;-) or ″, ”, “, and so forth. So check your code carefully to make sure you're using the normal, plain kinds of quotes!
Authenticated request in Google App Engine using fetch() function: how to provide the information in the header of the request?
I am trying to pass automatically, using Google App Engine, my password and ID to eBay, to this page: https://signin.ebay.com/ws/eBayISAPI.dll?SignIn&UsingSSL=1&pUserId=&co_partnerId=2&siteid=0&ru=http%3A%2F%2Fcgi5.ebay.com%2Fws2%2FeBayISAPI.dll%3FSellItem%26hm%3Dum.rundkoi376%26%26hc%3D1%26guest%3D1&pageType=1144 (It is where I get redirected to from this URL: https://signin.ebay.com). Here is how the page looks like: (source: narod.ru) Earlier I have asked some questions, and here one very nice supporter suggested that I use code from this link: http://chillorb.com/?p=195 If you have no time to go there, here is how that page looks like: (source: narod.ru) So, I pasted that code into my editor substituting the valid eBay URL, my ID and password. My ID there is seeyousoondanny and the password is happy1 (I created that account on eBay just for experimenting, so I am not afraid to give out my ID and password). Here is how the code looked in my editor: (source: narod.ru) But when I run this code I get only this: (source: narod.ru) What am I doing wrong here? ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Addition: Here is the bottom of the error page (I think it will be seen clearer if you click on the link to this image): +++++++++++++++++++++++++++++++++++++++++++++++++++ Addition: I guess this code has no syntax mistakes: from google.appengine.api import urlfetch import base64 url = "https://signin.ebay.com/ws/eBayISAPI.dll?SignIn&UsingSSL=1&pUserId=&co_partnerId=2&siteid=0&ru=http%3A%2F%2Fcgi5.ebay.com%2Fws2%2FeBayISAPI.dll%3FSellItem%26hm%3Dum.rundkoi376%26%26hc%3D1%26guest%3D1&pageType=1144" authString = 'Basic' + base64.encodestring('seeyousoondanny:happy1') data = urlfetch.fetch(url, headers= {'AUTHORIZATION' : authString }) if data.status_code == 200: print "content-type: text/plain" print print data.status_code
[ "I'm not sure if this helps, but ebay has an API that would be simpler to use and incorporate. Check out http://developer.ebay.com/businessbenefits/aboutus/\n", "Looks like some of the quote-characters are the wrong kind -- reversed \"smart quotes\" rather than normal plain ordinary ASCII quote characters. Hard to say precisely from screenshots! The error screen you're showing (from GAE's SDK) shows the exact location of the error at the very bottom -- and you're showing it scrolled all the way to the very top, so it doesn't help.\nIn GAE like in any other use of Python quote is done via plain single and double quote characters: ' and \" ; not via slanted, inverted, or \"smart\" quote characters, such as\n`\n\n(hard to clearly show the inverted single quote in SO except as a codeblock, since it's used to mark inline code;-) or ″, ”, “, and so forth. So check your code carefully to make sure you're using the normal, plain kinds of quotes!\n" ]
[ 3, 2 ]
[]
[]
[ "authorization", "google_app_engine", "header", "python" ]
stackoverflow_0001912845_authorization_google_app_engine_header_python.txt
Q: How to handle back and forward buttons in the hildon.Seekbar? The hildon.Seekbar widget consists of a scale widget and two buttons. What signals does the widget send when the buttons are clicked or how could I find out? Is there a way to monitor all signals/events that a widget sends in PyGTK? A: The documentation you linked to shows this: seekbar.connect("value-changed", control_changed, label) seekbar.connect("notify::fraction", fraction_changed, label) So it seems it has (at least) two signals called "value-changed" and "notify::fraction". It also shows an inheritance diagram that tells you that the Seekbar inherits the standard GTK+ Scale widget, which is where the first signal comes from (by further inheritance). Not sure where the "notify::fraction" signal comes from, though. A: gobjects have a way of notifying about property changes and it does this with signals. So connecting to notify::property gets you changes to property.
How to handle back and forward buttons in the hildon.Seekbar?
The hildon.Seekbar widget consists of a scale widget and two buttons. What signals does the widget send when the buttons are clicked or how could I find out? Is there a way to monitor all signals/events that a widget sends in PyGTK?
[ "The documentation you linked to shows this:\nseekbar.connect(\"value-changed\", control_changed, label)\nseekbar.connect(\"notify::fraction\", fraction_changed, label)\n\nSo it seems it has (at least) two signals called \"value-changed\" and \"notify::fraction\". It also shows an inheritance diagram that tells you that the Seekbar inherits the standard GTK+ Scale widget, which is where the first signal comes from (by further inheritance).\nNot sure where the \"notify::fraction\" signal comes from, though.\n", "gobjects have a way of notifying about property changes and it does this with signals. So connecting to notify::property gets you changes to property.\n" ]
[ 1, 0 ]
[]
[]
[ "gtk", "maemo", "pygtk", "python", "seekbar" ]
stackoverflow_0001083905_gtk_maemo_pygtk_python_seekbar.txt
Q: Python: List to ints to a single number? Say i have a several list if ints: x = [['48', '5', '0'], ['77', '56', '0'], ['23', '76', '34', '0']] I want this list to be converted to a single number, but the the single number type is still an integer i.e.: 4850775602376340 i have been using this code to carry out the process: num = int(''.join(map(str,x))) but i keep getting a value error. Also if my list contained negative integers how would i convert them to there absolute value? Then convert them to a single number? x2 = [['48', '-5', '0'], ['77', '56', '0'], ['23', '76', '-34', '0']] x2 = 4850775602376340 Thanks in advance. A: >>> int(''.join(reduce(lambda a, b: a + b, x))) 4850775602376340 A: I'd use itertools.chain.from_iterable for this (new in python 2.6) Example code: import itertools x = [['48', '5', '0'], ['77', '56', '0'], ['23', '76', '34', '0']] print int(''.join(itertools.chain.from_iterable(x))) A: >>> int(''.join(j for i in x for j in i)) 4850775602376340 A: Its a list of lists, so num = int(''.join(''.join(l) for l in lists)) or def flatten( nested ): for inner in nested: for x in inner: yield x num = ''.join(flatten(lists)) A: >>> x = [['48', '5', '0'], ['77', '56', '0'], ['23', '76', '34', '0']] >>> int(''.join([''.join(i) for i in x ] )) 4850775602376340 A: Enough good answers already ... just wanted to add the treatment of unlimited nesting: def flatten(obj): if not isinstance(obj, list): return obj else: return ''.join([flatten(x) for x in obj]) >>> x = [['48', '5', '0'], ['77', '56', '0'], ['23', '76', '34', '0']] >>> flatten(x) '4850775602376340' >>> x = [['48', '5', '0'], ['77', '56', '0'], [['23','123'], '76', '34', '0']] >>> flatten(x) '4850775602312376340' A: simply put: flattening the list [e for e in (itertools.chain(*x))] removing the negative sign e.replace('-','') joining the numbers in a list into a string and turning it into a number int(''.join(x)) putting it all together x2 = int(''.join([e.replace('-','') for e in (itertools.chain(*x))]))
Python: List to ints to a single number?
Say i have a several list if ints: x = [['48', '5', '0'], ['77', '56', '0'], ['23', '76', '34', '0']] I want this list to be converted to a single number, but the the single number type is still an integer i.e.: 4850775602376340 i have been using this code to carry out the process: num = int(''.join(map(str,x))) but i keep getting a value error. Also if my list contained negative integers how would i convert them to there absolute value? Then convert them to a single number? x2 = [['48', '-5', '0'], ['77', '56', '0'], ['23', '76', '-34', '0']] x2 = 4850775602376340 Thanks in advance.
[ ">>> int(''.join(reduce(lambda a, b: a + b, x)))\n4850775602376340\n\n", "I'd use itertools.chain.from_iterable for this (new in python 2.6)\nExample code:\nimport itertools\nx = [['48', '5', '0'], ['77', '56', '0'], ['23', '76', '34', '0']]\nprint int(''.join(itertools.chain.from_iterable(x)))\n\n", ">>> int(''.join(j for i in x for j in i))\n4850775602376340\n\n", "Its a list of lists, so \nnum = int(''.join(''.join(l) for l in lists))\n\nor\ndef flatten( nested ):\n for inner in nested:\n for x in inner:\n yield x\n\nnum = ''.join(flatten(lists))\n\n", ">>> x = [['48', '5', '0'], ['77', '56', '0'], ['23', '76', '34', '0']]\n>>> int(''.join([''.join(i) for i in x ] ))\n4850775602376340\n\n", "Enough good answers already ... just wanted to add the treatment of unlimited nesting:\ndef flatten(obj):\n if not isinstance(obj, list):\n return obj\n else:\n return ''.join([flatten(x) for x in obj])\n\n>>> x = [['48', '5', '0'], ['77', '56', '0'], ['23', '76', '34', '0']]\n>>> flatten(x)\n'4850775602376340'\n\n>>> x = [['48', '5', '0'], ['77', '56', '0'], [['23','123'], '76', '34', '0']]\n>>> flatten(x)\n'4850775602312376340'\n\n", "simply put:\n\nflattening the list\n[e for e in (itertools.chain(*x))]\n\nremoving the negative sign\ne.replace('-','')\n\njoining the numbers in a list into a string and turning it into a number\nint(''.join(x))\n\n\nputting it all together\nx2 = int(''.join([e.replace('-','') for e in (itertools.chain(*x))]))\n\n" ]
[ 6, 6, 4, 2, 1, 1, 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0001914883_list_python.txt
Q: On the google app engine, why does my 'import' statement fail on Live, but work on Dev(localmachine)? I have a python/django application that runs on the google app engine. My views.py file has some imports... from commands.userCommands import RegisterUserCommand from commands.accountCommands import CreateNewAccountCommand, RenameAccountCommand These imports work fine on my development environment (local machine). But when I upload to the google app engine, views.py fails with a "Could not import views. Error was: No module named userCommands" error. Any idea why I can't import my commands.userCommands module? My file structure looks as follows... - app.yaml - urls.py - views.py - etc... - commands/__init__.py - commands/userCommands.py Note: I did try to append my application name to the module name/path. No luck. Note: I did do an update with the --noisy argument, and it does appear to upload my commands folder successfully. A: You could be running into a clash with Python's own commands module (which doesn't have submodules like yours) -- naming your own modules and packages in ways that are meant to hide ones in the standard library (just like naming your variables in ways that are meant to hide builtin names, like list or file) is always a perilous undertaking, even though it "should" work there's always potential for confusion. Could you try renaming that commands package and its uses to something unambiguous and free from danger, such as mycommands, and see if that just makes the problem disappear? If that's the case you can then open a ticket on GAE's tracker (because it would show a minor but undeniable bug in GAE's runtime) but meanwhile your problem is solved!-) If the problem stays, ah well, at least we've eliminated one likely cause and can keep digging... A: The __init__.py files are required to make Python treat the directories as containing packages, so you need a commands/__init__.py file in your directory structure. See http://docs.python.org/tutorial/modules.html.
On the google app engine, why does my 'import' statement fail on Live, but work on Dev(localmachine)?
I have a python/django application that runs on the google app engine. My views.py file has some imports... from commands.userCommands import RegisterUserCommand from commands.accountCommands import CreateNewAccountCommand, RenameAccountCommand These imports work fine on my development environment (local machine). But when I upload to the google app engine, views.py fails with a "Could not import views. Error was: No module named userCommands" error. Any idea why I can't import my commands.userCommands module? My file structure looks as follows... - app.yaml - urls.py - views.py - etc... - commands/__init__.py - commands/userCommands.py Note: I did try to append my application name to the module name/path. No luck. Note: I did do an update with the --noisy argument, and it does appear to upload my commands folder successfully.
[ "You could be running into a clash with Python's own commands module (which doesn't have submodules like yours) -- naming your own modules and packages in ways that are meant to hide ones in the standard library (just like naming your variables in ways that are meant to hide builtin names, like list or file) is always a perilous undertaking, even though it \"should\" work there's always potential for confusion.\nCould you try renaming that commands package and its uses to something unambiguous and free from danger, such as mycommands, and see if that just makes the problem disappear? If that's the case you can then open a ticket on GAE's tracker (because it would show a minor but undeniable bug in GAE's runtime) but meanwhile your problem is solved!-) If the problem stays, ah well, at least we've eliminated one likely cause and can keep digging...\n", "The __init__.py files are required to make Python treat the directories as containing packages, so you need a \ncommands/__init__.py\n\nfile in your directory structure. See http://docs.python.org/tutorial/modules.html.\n" ]
[ 5, 2 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0001914881_django_google_app_engine_python.txt
Q: Python: List of lists of integers to absolute value to single number If i had a list of list of integers say: [['12' '-4' '66' '0'], ['23' '4' '-5' '0'], ['23' '77' '89' '-1' '0']] I wanted to convert the numbers to their absolute values and then to a single number, so the output would be: 1246602345023778910 A: What you're showing is (maybe) a list of lists of strings, and the syntax is extremely peculiar -- the sublists are shown with the normal, usual commas, but inside each there are just literal strings with spaces between them. If you actually type that into Python, you'll get a list where each sublist contains a single string -- Python, like C, concatenates at compile time string literals that are simply juxtaposed with whitespace in the middle. Assuming you did mean to have sublists of several strings each, WITH proper commas, and that your mentions of "lists of numbers" (which is not what you have -- you have lists of strings!-) are just small accidents, something like: ''.join(c for L in thelist for c in L).replace('-', '') is probably best -- just operate at the string level (so, replace dashes with nothing, rather than using abs), since you do need strings for concatenation/joining purposes anyway. If you're keen to do it the most complicated way you can, ''.join(str(abs(int(c))) for L in thelist for c in L) will also work (and more literally match what you're asking), but the first idea's better. A: What you gave above is a list of lists of strings. I suggest a two-pass approach: Get integers from strings and take their absolutes: [ abs(int(s)) for s in list ] Combine these numbers into a string and turn it into an integer ''.join([ ''.join(x) for x in listoflists ]) When you combine these two approaches you get: >>> listoflists = [['12','-4','66','0'],['23','4','-5','0'],['23','77','89','-1','0']] >>> int(''.join([ ''.join([ str(abs(int(s))) for s in list ]) for list in listoflists ])) 1246602345023778910L It's not nice and readable though, so you may want to keep it divided to make more sense to someone who might have the take the pain of understanding it. Note: If you indeed had a list of integers though, as you stated, then it's much easier: >>> listofints = [12,-4,66,0,23,4,-5,0,23,77,89,-1,0] >>> int(''.join( [ str(abs(x)) for x in listofints ])) 1246602345023778910L A: You can use itertools.chain here to get rid of the nesting, concatenate the number-strings, remove the '-' signs and then turn them into a number. import itertools mylist = [['12' '-4' '66' '0'], ['23' '4' '-5' '0'], ['23' '77' '89' '-1' '0']] num = int( ''.join(itertools.chain(*mylist)).replace('-','') ) Edit: I previously missed the abs requirement. Second edit: Used replace which is probably more efficient than str(abs(int(n))) and also less clumsy (courtesy: Alex's answer) A: I am new to Python, so please forgive me if there is a more efficient way :) #!/usr/bin/python str = '' lists = [['12' '-4' '66' '0'], ['23' '4' '-5' '0'], ['23' '77' '89' '-1' '0']] for list in lists: str += list[0].replace('-', '') print int(str) A: As pointed out in the other answers, your inner lists are not as 'listy' as they appear. Since commas are missing, Python will (I think) concatenate them all into one string thus giving you a list of one item. This will be the same as this: [['12-4660'], ['234-50'], ['237789-10']] In any case, you could just strip out eveything that's not a digit to get your result (this would work with or without the commas): ''.join(x for x in str(mylist) if x.isdigit())
Python: List of lists of integers to absolute value to single number
If i had a list of list of integers say: [['12' '-4' '66' '0'], ['23' '4' '-5' '0'], ['23' '77' '89' '-1' '0']] I wanted to convert the numbers to their absolute values and then to a single number, so the output would be: 1246602345023778910
[ "What you're showing is (maybe) a list of lists of strings, and the syntax is extremely peculiar -- the sublists are shown with the normal, usual commas, but inside each there are just literal strings with spaces between them. If you actually type that into Python, you'll get a list where each sublist contains a single string -- Python, like C, concatenates at compile time string literals that are simply juxtaposed with whitespace in the middle.\nAssuming you did mean to have sublists of several strings each, WITH proper commas, and that your mentions of \"lists of numbers\" (which is not what you have -- you have lists of strings!-) are just small accidents, something like:\n''.join(c for L in thelist for c in L).replace('-', '')\n\nis probably best -- just operate at the string level (so, replace dashes with nothing, rather than using abs), since you do need strings for concatenation/joining purposes anyway.\nIf you're keen to do it the most complicated way you can,\n''.join(str(abs(int(c))) for L in thelist for c in L)\n\nwill also work (and more literally match what you're asking), but the first idea's better.\n", "What you gave above is a list of lists of strings.\nI suggest a two-pass approach:\n\nGet integers from strings and take their absolutes:\n[ abs(int(s)) for s in list ]\nCombine these numbers into a string and turn it into an integer\n''.join([ ''.join(x) for x in listoflists ])\n\nWhen you combine these two approaches you get:\n>>> listoflists = [['12','-4','66','0'],['23','4','-5','0'],['23','77','89','-1','0']]\n>>> int(''.join([ ''.join([ str(abs(int(s))) for s in list ]) for list in listoflists ]))\n1246602345023778910L\n\nIt's not nice and readable though, so you may want to keep it divided to make more sense to someone who might have the take the pain of understanding it.\nNote: If you indeed had a list of integers though, as you stated, then it's much easier:\n>>> listofints = [12,-4,66,0,23,4,-5,0,23,77,89,-1,0]\n>>> int(''.join( [ str(abs(x)) for x in listofints ]))\n1246602345023778910L\n\n", "You can use itertools.chain here to get rid of the nesting, concatenate the number-strings, remove the '-' signs and then turn them into a number. \nimport itertools\nmylist = [['12' '-4' '66' '0'], ['23' '4' '-5' '0'], ['23' '77' '89' '-1' '0']]\nnum = int( ''.join(itertools.chain(*mylist)).replace('-','') )\n\nEdit: I previously missed the abs requirement.\nSecond edit: Used replace which is probably more efficient than str(abs(int(n))) and also less clumsy (courtesy: Alex's answer)\n", "I am new to Python, so please forgive me if there is a more efficient way :)\n#!/usr/bin/python\n\nstr = ''\nlists = [['12' '-4' '66' '0'], ['23' '4' '-5' '0'], ['23' '77' '89' '-1' '0']]\n\nfor list in lists:\n str += list[0].replace('-', '')\n\nprint int(str)\n\n", "As pointed out in the other answers, your inner lists are not as 'listy' as they appear. Since commas are missing, Python will (I think) concatenate them all into one string thus giving you a list of one item. This will be the same as this:\n[['12-4660'], ['234-50'], ['237789-10']]\n\nIn any case, you could just strip out eveything that's not a digit to get your result (this would work with or without the commas):\n''.join(x for x in str(mylist) if x.isdigit())\n\n" ]
[ 2, 1, 1, 0, 0 ]
[]
[]
[ "absolute", "integer", "list", "mapping", "python" ]
stackoverflow_0001915342_absolute_integer_list_mapping_python.txt
Q: python descriptors sharing values across classes A python descriptor that I'm working with is sharing its value across all instances of its owner class. How can I make each instance's descriptor contain its own internal values? class Desc(object): def __init__(self, initval=None,name='val'): self.val = initval self.name = name def __get__(self,obj,objtype): return self.val def __set__(self,obj,val): self.val = val def __delete__(self,obj): pass class MyClass(object): desc = Desc(10,'varx') if __name__ == "__main__": c = MyClass() c.desc = 'max' d = MyClass() d.desc = 'sally' print(c.desc) print(d.desc) The output is this, the last call set the value for both objects: localhost $ python descriptor_testing.py sally sally A: There is only one descriptor object, stored on the class object, so self is always the same. If you want to store data per-object and access it through the descriptor, you either have to store the data on each object (probably the better idea) or in some data-structure keyed by each object (an idea I don't like as much). I would save data on the instance object: class Desc(object): default_value = 10 def __init__(self, name): self.name = name def __get__(self,obj,objtype): return obj.__dict__.get(self.name, self.default_value) # alternatively the following; but won't work with shadowing: #return getattr(obj, self.name, self.default_value) def __set__(self,obj,val): obj.__dict__[self.name] = val # alternatively the following; but won't work with shadowing: #setattr(obj, self.name, val) def __delete__(self,obj): pass class MyClass(object): desc = Desc('varx') In this case, the data will be stored in the obj's 'varx' entry in its __dict__. Because of how data descriptor lookup works though, you can "shadow" the storage location with the descriptor: class MyClass(object): varx = Desc('varx') In this case, when you do the lookup: MyClass().varx The descriptor object gets called and can do its lookup, but when the lookup goes like this: MyClass().__dict__['varx'] The value is returned directly. Thus the descriptor is able to store its data in a 'hidden' place, so to speak.
python descriptors sharing values across classes
A python descriptor that I'm working with is sharing its value across all instances of its owner class. How can I make each instance's descriptor contain its own internal values? class Desc(object): def __init__(self, initval=None,name='val'): self.val = initval self.name = name def __get__(self,obj,objtype): return self.val def __set__(self,obj,val): self.val = val def __delete__(self,obj): pass class MyClass(object): desc = Desc(10,'varx') if __name__ == "__main__": c = MyClass() c.desc = 'max' d = MyClass() d.desc = 'sally' print(c.desc) print(d.desc) The output is this, the last call set the value for both objects: localhost $ python descriptor_testing.py sally sally
[ "There is only one descriptor object, stored on the class object, so self is always the same. If you want to store data per-object and access it through the descriptor, you either have to store the data on each object (probably the better idea) or in some data-structure keyed by each object (an idea I don't like as much).\nI would save data on the instance object: \nclass Desc(object):\n default_value = 10\n def __init__(self, name):\n self.name = name\n\n def __get__(self,obj,objtype):\n return obj.__dict__.get(self.name, self.default_value)\n # alternatively the following; but won't work with shadowing:\n #return getattr(obj, self.name, self.default_value)\n\n def __set__(self,obj,val):\n obj.__dict__[self.name] = val\n # alternatively the following; but won't work with shadowing:\n #setattr(obj, self.name, val)\n\n def __delete__(self,obj):\n pass\n\n\nclass MyClass(object):\n desc = Desc('varx')\n\nIn this case, the data will be stored in the obj's 'varx' entry in its __dict__. Because of how data descriptor lookup works though, you can \"shadow\" the storage location with the descriptor:\nclass MyClass(object):\n varx = Desc('varx')\n\nIn this case, when you do the lookup:\nMyClass().varx\n\nThe descriptor object gets called and can do its lookup, but when the lookup goes like this:\nMyClass().__dict__['varx']\n\nThe value is returned directly. Thus the descriptor is able to store its data in a 'hidden' place, so to speak.\n" ]
[ 7 ]
[]
[]
[ "descriptor", "python" ]
stackoverflow_0001915643_descriptor_python.txt
Q: with statement - backport for Python 2.5 I'd like to use with statement in Python 2.5 in some production code. It was backported, should I expect any problems (e.g. with availability/compatibility on other machines/etc)? Is this code from __future__ import with_statement compatible with Python 2.6? A: Yes, that statement is a no-operation in Python 2.6, so you can freely use it to make with a keyword in your 2.5 code as well, without affecting your code's operation in 2.6. This is in fact the general design intention of "importing from the future" in Python! A: You can call this in Python 2.6 and 3.0/1 without problems (it's a no-op there). A: with_statement wasn't back ported but implemented in Python 2.5. Adding new keywords or syntax can break existing applications. With Python the way they decided to handle this is allow people to opt-in to those features early so you can slowly transition your code over. From http://python.org/doc/2.5.2/ref/future.html A future statement is a directive to the compiler that a particular module should be compiled using syntax or semantics that will be available in a specified future release of Python. The future statement is intended to ease migration to future versions of Python that introduce incompatible changes to the language. It allows use of the new features on a per-module basis before the release in which the feature becomes standard. You can actually inspect futures to get information on when first supported, when the import isn't needed anymore, etc. Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import __future__ >>> dir(__future__) ['CO_FUTURE_ABSOLUTE_IMPORT', 'CO_FUTURE_DIVISION', 'CO_FUTURE_WITH_STATEMENT', 'CO_GENERATOR_ALLOWED', 'CO_NESTED', '_Feature', '__all__', '__builtins__', __doc__', '__file__', '__name__', 'absolute_import', 'all_feature_names', 'division', 'generators', 'nested_scopes', 'with_statement'] >>> __future__.with_statement _Feature((2, 5, 0, 'alpha', 1), (2, 6, 0, 'alpha', 0), 32768) >>> I personally have been heavily using the with_statement in Python 2.5 for well over a year and have not had issues. I also transparently run that code with Python 2.6. There are some weird corner cases they have worked at cleaning up in the language, mostly related to cleanly and correctly compacting nested with statements.
with statement - backport for Python 2.5
I'd like to use with statement in Python 2.5 in some production code. It was backported, should I expect any problems (e.g. with availability/compatibility on other machines/etc)? Is this code from __future__ import with_statement compatible with Python 2.6?
[ "Yes, that statement is a no-operation in Python 2.6, so you can freely use it to make with a keyword in your 2.5 code as well, without affecting your code's operation in 2.6. This is in fact the general design intention of \"importing from the future\" in Python!\n", "You can call this in Python 2.6 and 3.0/1 without problems (it's a no-op there).\n", "with_statement wasn't back ported but implemented in Python 2.5. Adding new keywords or syntax can break existing applications. With Python the way they decided to handle this is allow people to opt-in to those features early so you can slowly transition your code over.\nFrom http://python.org/doc/2.5.2/ref/future.html\n\nA future statement is a directive to\n the compiler that a particular module\n should be compiled using syntax or\n semantics that will be available in a\n specified future release of Python.\n The future statement is intended to\n ease migration to future versions of\n Python that introduce incompatible\n changes to the language. It allows use\n of the new features on a per-module\n basis before the release in which the\n feature becomes standard.\n\nYou can actually inspect futures to get information on when first supported, when the import isn't needed anymore, etc.\nPython 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import __future__\n>>> dir(__future__)\n['CO_FUTURE_ABSOLUTE_IMPORT', 'CO_FUTURE_DIVISION', 'CO_FUTURE_WITH_STATEMENT', 'CO_GENERATOR_ALLOWED', 'CO_NESTED', '_Feature', '__all__', '__builtins__',\n__doc__', '__file__', '__name__', 'absolute_import', 'all_feature_names', 'division', 'generators', 'nested_scopes', 'with_statement']\n>>> __future__.with_statement\n_Feature((2, 5, 0, 'alpha', 1), (2, 6, 0, 'alpha', 0), 32768)\n>>>\n\nI personally have been heavily using the with_statement in Python 2.5 for well over a year and have not had issues. I also transparently run that code with Python 2.6. There are some weird corner cases they have worked at cleaning up in the language, mostly related to cleanly and correctly compacting nested with statements.\n" ]
[ 7, 4, 3 ]
[]
[]
[ "backport", "python", "with_statement" ]
stackoverflow_0001915927_backport_python_with_statement.txt
Q: How do I add rows and columns to a NUMPY array? Hello I have a 1000 data series with 1500 points in each. They form a (1000x1500) size Numpy array created using np.zeros((1500, 1000)) and then filled with the data. Now what if I want the array to grow to say 1600 x 1100? Do I have to add arrays using hstack and vstack or is there a better way? I would want the data already in the 1000x1500 piece of the array not to be changed, only blank data (zeros) added to the bottom and right, basically. Thanks. A: This should do what you want (ie, using 3x3 array and 4x4 array to represent the two arrays in the OP) >>> import numpy as NP >>> a = NP.random.randint(0, 10, 9).reshape(3, 3) >>> a >>> array([[1, 2, 2], [7, 0, 7], [0, 3, 0]]) >>> b = NP.zeros((4, 4)) mapping a on to b: >>> b[:3,:3] = a >>> b array([[ 1., 2., 2., 0.], [ 7., 0., 7., 0.], [ 0., 3., 0., 0.], [ 0., 0., 0., 0.]]) A: If you want zeroes in the added elements, my_array.resize((1600, 1000)) should work. Note that this differs from numpy.resize(my_array, (1600, 1000)), in which previous lines are duplicated, which is probably not what you want. Otherwise (for instance if you want to avoid initializing elements to zero, which could be unnecessary), you can indeed use hstack and vstack to add an array containing the new elements; numpy.concatenate() (see pydoc numpy.concatenate) should work too (it is just more general, as far as I understand). In either case, I would guess that a new memory block has to be allocated in order to extend the array, and that all these methods take about the same time. A: No matter what, you'll be stuck reallocating a chunk of memory, so it doesn't really matter if you use arr.resize(), np.concatenate, hstack/vstack, etc. Note that if you're accumulating a lot of data sequentially, Python lists are usually more efficient. A: You should use reshape() and/or resize() depending on your precise requirement. If you want chapter and verse from the authors you are probably better off posting on the numpy discussion board.
How do I add rows and columns to a NUMPY array?
Hello I have a 1000 data series with 1500 points in each. They form a (1000x1500) size Numpy array created using np.zeros((1500, 1000)) and then filled with the data. Now what if I want the array to grow to say 1600 x 1100? Do I have to add arrays using hstack and vstack or is there a better way? I would want the data already in the 1000x1500 piece of the array not to be changed, only blank data (zeros) added to the bottom and right, basically. Thanks.
[ "This should do what you want (ie, using 3x3 array and 4x4 array to represent the two arrays in the OP)\n>>> import numpy as NP\n>>> a = NP.random.randint(0, 10, 9).reshape(3, 3)\n>>> a\n>>> array([[1, 2, 2],\n [7, 0, 7],\n [0, 3, 0]])\n\n>>> b = NP.zeros((4, 4))\n\nmapping a on to b:\n>>> b[:3,:3] = a\n\n>>> b\n array([[ 1., 2., 2., 0.],\n [ 7., 0., 7., 0.],\n [ 0., 3., 0., 0.],\n [ 0., 0., 0., 0.]])\n\n", "If you want zeroes in the added elements, my_array.resize((1600, 1000)) should work. Note that this differs from numpy.resize(my_array, (1600, 1000)), in which previous lines are duplicated, which is probably not what you want.\nOtherwise (for instance if you want to avoid initializing elements to zero, which could be unnecessary), you can indeed use hstack and vstack to add an array containing the new elements; numpy.concatenate() (see pydoc numpy.concatenate) should work too (it is just more general, as far as I understand).\nIn either case, I would guess that a new memory block has to be allocated in order to extend the array, and that all these methods take about the same time.\n", "No matter what, you'll be stuck reallocating a chunk of memory, so it doesn't really matter if you use arr.resize(), np.concatenate, hstack/vstack, etc. Note that if you're accumulating a lot of data sequentially, Python lists are usually more efficient.\n", "You should use reshape() and/or resize() depending on your precise requirement.\nIf you want chapter and verse from the authors you are probably better off posting on the numpy discussion board.\n" ]
[ 11, 3, 2, 0 ]
[]
[]
[ "arrays", "numpy", "python", "reshape" ]
stackoverflow_0001909994_arrays_numpy_python_reshape.txt
Q: Python: List to Hex I am writing a small forensics python app and I am having trouble converting a List entry to Hex. I have tried the encode/decode methood but get bogus conversions or odd-length string Type Errors. I have pasted the code below, and as you can see I need the address in hex, so I can add the count to it. def location_finder(line): count = 0 temp = line.split(' ') #3 Tokenizes first element, by first space address = str(temp[0].split(':')) # Take's : off of first element(address) print address, "dog" address = address.decode("hex") print address, "cat" #print temp[0] line_address = temp[0].upper() for addy in temp: if addy == "ffd8": return (address+count) if addy == "ffd9": return (address+count) count = count + 1 A: The hex function converts integers to their hexadecimal representation: >>> a = 123 >>> hex(a) '0x7b'
Python: List to Hex
I am writing a small forensics python app and I am having trouble converting a List entry to Hex. I have tried the encode/decode methood but get bogus conversions or odd-length string Type Errors. I have pasted the code below, and as you can see I need the address in hex, so I can add the count to it. def location_finder(line): count = 0 temp = line.split(' ') #3 Tokenizes first element, by first space address = str(temp[0].split(':')) # Take's : off of first element(address) print address, "dog" address = address.decode("hex") print address, "cat" #print temp[0] line_address = temp[0].upper() for addy in temp: if addy == "ffd8": return (address+count) if addy == "ffd9": return (address+count) count = count + 1
[ "The hex function converts integers to their hexadecimal representation:\n>>> a = 123\n>>> hex(a)\n'0x7b'\n\n" ]
[ 2 ]
[]
[]
[ "hex", "python" ]
stackoverflow_0001916493_hex_python.txt
Q: Does Django support model classes that inherit after many non-abstract models? Lets say I have three django model classes - lets call them A, B and C. If A and B are abstract, I can do something like: class C(A,B): pass What if they aren't abstract and I do the same? Will everything still work correctly or no? Or have I got it wrong and this should not be done with abstract models either? I'm having some issues which I'm attributing to the fact that the answer is probably no, but I'd still prefer to make sure about this if anyone knows :) The specific use case I had for this is probably better served by Generic Relations (I only recently discovered their existence), so I guess it would be understandable if the Django team made a design decision like this (I can't see many people needing to do this). I'd just like to know for sure what the case is. Edit 1 (after Dominic's answer) Interesting... The problem we're having is a structure similar to IMDb (I think IMDb is a bit easier to understand than the topic matter we actually have, so I'll use them as an example). On IMDb they have pages for People and pages for Movies and both People and Movies have their own message boards. We've ended up connecting message boards to the People and Movies by creating a model called MessageboardOwner (with only one attribute - the id added automatically by Django), which "owns" the message board and People and Movies inherit it. The problem is that our "People" class inherits from two other classes also. The class definition is something like: class Person(A,B,MessageboardOwner): Initially this seemed to work out fine, but then today something rather weird happened... I was deleting a Person in the admin and the admin asked the "Are you sure?" question and was showing me what other objects it would have to delete. It was trying to delete two message boards, not one. One of these message boards should have been owned by a Movie, not a Person. Upon looking at what exactly was in the database, I found that this Person instance was using the same MessageboardOwner instance as the Movie was. When I played around with it, what came out was that the Movie class, which inherited only after MessageboardOwner, seemed to work ok. Saving the Person, however, only created a MessageboardOwner object if one didn't already exist (or possibly overwrote the existing one - I'm not sure). I also found that the id fields inherited from A, B and MessageboardOwner were always equal, which seemed strange to me. A: Yes, you can use normal Python multiple-inheritance with models. Bear in mind this warning though: Just as with Python's subclassing, it's possible for a Django model to inherit from multiple parent models. Keep in mind that normal Python name resolution rules apply. The first base class that a particular name (e.g. Meta) appears in will be the one that is used; for example, this means that if multiple parents contain a Meta class, only the first one is going to be used, and all others will be ignored. Generally, you won't need to inherit from multiple parents. The main use-case where this is useful is for "mix-in" classes: adding a particular extra field or method to every class that inherits the mix-in. Try to keep your inheritance hierarchies as simple and straightforward as possible so that you won't have to struggle to work out where a particular piece of information is coming from. From the Django docs. Generally, multiple inheritance is a bad idea, and there are simpler ways to do things. If you flesh out what problem you're trying to solve a bit more clearly, we might be able to help a bit better.
Does Django support model classes that inherit after many non-abstract models?
Lets say I have three django model classes - lets call them A, B and C. If A and B are abstract, I can do something like: class C(A,B): pass What if they aren't abstract and I do the same? Will everything still work correctly or no? Or have I got it wrong and this should not be done with abstract models either? I'm having some issues which I'm attributing to the fact that the answer is probably no, but I'd still prefer to make sure about this if anyone knows :) The specific use case I had for this is probably better served by Generic Relations (I only recently discovered their existence), so I guess it would be understandable if the Django team made a design decision like this (I can't see many people needing to do this). I'd just like to know for sure what the case is. Edit 1 (after Dominic's answer) Interesting... The problem we're having is a structure similar to IMDb (I think IMDb is a bit easier to understand than the topic matter we actually have, so I'll use them as an example). On IMDb they have pages for People and pages for Movies and both People and Movies have their own message boards. We've ended up connecting message boards to the People and Movies by creating a model called MessageboardOwner (with only one attribute - the id added automatically by Django), which "owns" the message board and People and Movies inherit it. The problem is that our "People" class inherits from two other classes also. The class definition is something like: class Person(A,B,MessageboardOwner): Initially this seemed to work out fine, but then today something rather weird happened... I was deleting a Person in the admin and the admin asked the "Are you sure?" question and was showing me what other objects it would have to delete. It was trying to delete two message boards, not one. One of these message boards should have been owned by a Movie, not a Person. Upon looking at what exactly was in the database, I found that this Person instance was using the same MessageboardOwner instance as the Movie was. When I played around with it, what came out was that the Movie class, which inherited only after MessageboardOwner, seemed to work ok. Saving the Person, however, only created a MessageboardOwner object if one didn't already exist (or possibly overwrote the existing one - I'm not sure). I also found that the id fields inherited from A, B and MessageboardOwner were always equal, which seemed strange to me.
[ "Yes, you can use normal Python multiple-inheritance with models. Bear in mind this warning though:\n\nJust as with Python's subclassing,\n it's possible for a Django model to\n inherit from multiple parent models.\n Keep in mind that normal Python name\n resolution rules apply. The first base\n class that a particular name (e.g.\n Meta) appears in will be the one that\n is used; for example, this means that\n if multiple parents contain a Meta\n class, only the first one is going to\n be used, and all others will be\n ignored.\nGenerally, you won't need to inherit\n from multiple parents. The main\n use-case where this is useful is for\n \"mix-in\" classes: adding a particular\n extra field or method to every class\n that inherits the mix-in. Try to keep\n your inheritance hierarchies as simple\n and straightforward as possible so\n that you won't have to struggle to\n work out where a particular piece of\n information is coming from.\n\nFrom the Django docs.\nGenerally, multiple inheritance is a bad idea, and there are simpler ways to do things. If you flesh out what problem you're trying to solve a bit more clearly, we might be able to help a bit better.\n" ]
[ 2 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0001916522_django_django_models_python.txt
Q: List and Integer query If i had a list of numbers and some maybe negative, how would i ensure all numbers in my list were positive? I can covert the items in the list to integers thats no problem. Another question, I want to compare items in my list to an integer value say 'x' and sum all the values in my list that are less than x. Thank you. A: If you have a list Ns of numbers (if it's a list of strings as in several similar questions asked recently each will have to be made into an int, or whatever other kind of number, by calling int [[or float, etc]] on it), the list of their absolute values (if that's what you mean by "ensure") is [abs(n) for n in Ns] If you mean, instead, to check whether all numbers are >= 0, then all(n >= 0 for n in Ns) will give you a bool value respecting exactly that specification. The sum of the items of the list that are <x is sum(n for n in Ns if n < x) Of course you may combine all these kinds of operations in one sweep (e.g. if you need to take the abs(n) as well as checking if it's < x, checking if it's >= 0, summing, whatever). A: # input list is named "lst" pos_list = [int(a) for a in lst if int(a) > 0] # And num 2 (notice generator is used instead of list) return sum(a for a in lst if a < x) A: >>>mylist = [1,2,3,-2] >>>any(item for item in mylist if item < 0) True >>>mylist.pop() -2 >>>any(item for item in mylist if item < 0) False answers your first question. >>> x = 3 >>> sum(item for item in mylist if item < x) 3 answers your second question. A: Answer / First part: >>> a = [1, 2, -3, 4, 5, 6] >>> b = [1, 2, 3, 4, 5, 6] >>> max(map(lambda x: x < 0, a)) False >>> max(map(lambda x: x < 0, b)) True Or just use min: >>> min(a) < 0 True >>> min(b) < 0 False Second part: >>> x = 3 >>> sum(filter(lambda n: n < x, a)) >>> 0 >>> sum(filter(lambda n: n < x, b)) >>> 3 A: If I understand correctly your question, I guess you are asking because of some class about functional programming. In this case, what you are asking for can be accomplished with functional programming tools available in Python. In particular, the first point can be solved using filter, while the second with map and reduce (or, better, with map and sum).
List and Integer query
If i had a list of numbers and some maybe negative, how would i ensure all numbers in my list were positive? I can covert the items in the list to integers thats no problem. Another question, I want to compare items in my list to an integer value say 'x' and sum all the values in my list that are less than x. Thank you.
[ "If you have a list Ns of numbers (if it's a list of strings as in several similar questions asked recently each will have to be made into an int, or whatever other kind of number, by calling int [[or float, etc]] on it), the list of their absolute values (if that's what you mean by \"ensure\") is\n[abs(n) for n in Ns]\n\nIf you mean, instead, to check whether all numbers are >= 0, then\nall(n >= 0 for n in Ns)\n\nwill give you a bool value respecting exactly that specification.\nThe sum of the items of the list that are <x is\nsum(n for n in Ns if n < x)\n\nOf course you may combine all these kinds of operations in one sweep (e.g. if you need to take the abs(n) as well as checking if it's < x, checking if it's >= 0, summing, whatever).\n", "# input list is named \"lst\"\npos_list = [int(a) for a in lst if int(a) > 0]\n# And num 2 (notice generator is used instead of list)\nreturn sum(a for a in lst if a < x)\n\n", ">>>mylist = [1,2,3,-2]\n>>>any(item for item in mylist if item < 0)\nTrue\n>>>mylist.pop()\n-2\n>>>any(item for item in mylist if item < 0)\nFalse\n\nanswers your first question.\n>>> x = 3\n>>> sum(item for item in mylist if item < x)\n3\n\nanswers your second question.\n", "Answer / First part:\n>>> a = [1, 2, -3, 4, 5, 6]\n>>> b = [1, 2, 3, 4, 5, 6]\n\n>>> max(map(lambda x: x < 0, a))\nFalse\n\n>>> max(map(lambda x: x < 0, b))\nTrue\n\nOr just use min:\n>>> min(a) < 0\nTrue\n\n>>> min(b) < 0\nFalse\n\nSecond part:\n>>> x = 3\n>>> sum(filter(lambda n: n < x, a))\n>>> 0\n\n>>> sum(filter(lambda n: n < x, b))\n>>> 3\n\n", "If I understand correctly your question, I guess you are asking because of some class about functional programming. \nIn this case, what you are asking for can be accomplished with functional programming tools available in Python.\nIn particular, the first point can be solved using filter, while the second with map and reduce (or, better, with map and sum).\n" ]
[ 4, 0, 0, 0, 0 ]
[]
[]
[ "integer", "list", "python" ]
stackoverflow_0001916663_integer_list_python.txt
Q: resizing of button icons in pyqt4 I want to make image in my QMainWindow so when you click on it you have a signal translating like qpushbutton I use this: self.quit=QtGui.QPushButton(self) self.quit.setIcon(QtGui.QIcon('images/9.bmp')) But the problem is whene I resize the window qpushbutton resized too but not his icon, A: Qt won't stretch your image for you - and it's best this way. I recommend to keep the pushbutton of a constant size by adding stretchers to the layout holding it. A resizable pushbutton isn't very appealing visually, and is uncommon in GUIs, anyway. To make a clickable image, here's the simplest code I can think of: import sys from PyQt4.QtCore import * from PyQt4.QtGui import * class ImageLabel(QLabel): def __init__(self, image, parent=None): super(ImageLabel, self).__init__(parent) self.setPixmap(image) def mousePressEvent(self, event): print 'I was pressed' class AppForm(QMainWindow): def __init__(self, parent=None): QMainWindow.__init__(self, parent) self.create_main_frame() def create_main_frame(self): name_label = QLabel("Here's a clickable image:") img_label = ImageLabel(QPixmap('image.png')) vbox = QVBoxLayout() vbox.addWidget(name_label) vbox.addWidget(img_label) main_frame = QWidget() main_frame.setLayout(vbox) self.setCentralWidget(main_frame) if __name__ == "__main__": app = QApplication(sys.argv) form = AppForm() form.show() app.exec_() Just replace image.png with your image filename (acceptable format by QPixmap) and you're set.
resizing of button icons in pyqt4
I want to make image in my QMainWindow so when you click on it you have a signal translating like qpushbutton I use this: self.quit=QtGui.QPushButton(self) self.quit.setIcon(QtGui.QIcon('images/9.bmp')) But the problem is whene I resize the window qpushbutton resized too but not his icon,
[ "Qt won't stretch your image for you - and it's best this way. I recommend to keep the pushbutton of a constant size by adding stretchers to the layout holding it. A resizable pushbutton isn't very appealing visually, and is uncommon in GUIs, anyway.\nTo make a clickable image, here's the simplest code I can think of:\nimport sys\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\n\n\nclass ImageLabel(QLabel):\n def __init__(self, image, parent=None):\n super(ImageLabel, self).__init__(parent)\n self.setPixmap(image)\n\n def mousePressEvent(self, event):\n print 'I was pressed' \n\n\nclass AppForm(QMainWindow):\n def __init__(self, parent=None):\n QMainWindow.__init__(self, parent)\n\n self.create_main_frame() \n\n def create_main_frame(self):\n name_label = QLabel(\"Here's a clickable image:\")\n img_label = ImageLabel(QPixmap('image.png'))\n\n vbox = QVBoxLayout()\n vbox.addWidget(name_label)\n vbox.addWidget(img_label)\n\n main_frame = QWidget()\n main_frame.setLayout(vbox)\n self.setCentralWidget(main_frame)\n\n\nif __name__ == \"__main__\":\n app = QApplication(sys.argv)\n form = AppForm()\n form.show()\n app.exec_()\n\nJust replace image.png with your image filename (acceptable format by QPixmap) and you're set.\n" ]
[ 1 ]
[]
[]
[ "pyqt4", "python" ]
stackoverflow_0001916722_pyqt4_python.txt
Q: Why there are not any real lightweight threads for python? I'm new to Python and seems that the multiprocessing and threads module are not very interesting and suffer from the same problems such as threads in Perl. Is there a technical reason why the interpreter can't use lightweight threads such as posix threads to make an efficient thread implementation that really runs on several cores? A: It is using POSIX threads. The problem is the GIL. Note that the GIL is not part of the Python spec --- it's part of the CPython reference implementation. Jython, for example, does not suffer from this problem. That said, looked into Stackless ? A: Piotr, You might want to take a look at stackless (http://www.stackless.com/) which is a modified version of python running lightweight tasklets in message passing (erlang style) fashion. I'm not sure if you're looking for a multicore solution, but poking around in stackless might give you what you're looking for. Ben
Why there are not any real lightweight threads for python?
I'm new to Python and seems that the multiprocessing and threads module are not very interesting and suffer from the same problems such as threads in Perl. Is there a technical reason why the interpreter can't use lightweight threads such as posix threads to make an efficient thread implementation that really runs on several cores?
[ "It is using POSIX threads. The problem is the GIL.\nNote that the GIL is not part of the Python spec --- it's part of the CPython reference implementation. Jython, for example, does not suffer from this problem.\nThat said, looked into Stackless ?\n", "Piotr,\nYou might want to take a look at stackless (http://www.stackless.com/) which is a modified version of python running lightweight tasklets in message passing (erlang style) fashion.\nI'm not sure if you're looking for a multicore solution, but poking around in stackless might give you what you're looking for.\nBen\n" ]
[ 24, 0 ]
[]
[]
[ "multithreading", "pthreads", "python" ]
stackoverflow_0001914341_multithreading_pthreads_python.txt
Q: Determining Build Directory from SConscript I have an SConscript which is being copied to a build directory (variant_dir = ...) for construction. As a workaround for not being able to express dependencies, I'm trying to copy some additional files into the build directory. How do I determine what the current build directory is, within an SConscript? For instance, in the following layout, the inner SConscript file should set my_build_directory as, "build/something." project/ SConstruct # "SConscript('something/SConscript', variant_dir = 'build/something') something/ SConscript # "my_build_directory = ..." A: My answer seems too simple, so maybe I misunderstood the question, but ... For me, in subdir/SConscript: my_build_directory = '.' echo_cmd = Command('always.echo', [], "echo %s" % (Dir('.').abspath)) Alias('echo', echo_cmd) produces: # => cd test-scons # => ls # build/ SConstruct subdir/ # => scons echo # scons: Building targets ... # echo HOME/test-scons/build/subdir # HOME/test-scons/build/subdir # scons: done building targets.
Determining Build Directory from SConscript
I have an SConscript which is being copied to a build directory (variant_dir = ...) for construction. As a workaround for not being able to express dependencies, I'm trying to copy some additional files into the build directory. How do I determine what the current build directory is, within an SConscript? For instance, in the following layout, the inner SConscript file should set my_build_directory as, "build/something." project/ SConstruct # "SConscript('something/SConscript', variant_dir = 'build/something') something/ SConscript # "my_build_directory = ..."
[ "My answer seems too simple, so maybe I misunderstood the question, but ...\nFor me, in subdir/SConscript: \nmy_build_directory = '.'\n\necho_cmd = Command('always.echo', [], \"echo %s\" % (Dir('.').abspath))\nAlias('echo', echo_cmd)\n\nproduces:\n# => cd test-scons\n# => ls \n# build/ SConstruct subdir/\n# => scons echo \n# scons: Building targets ...\n# echo HOME/test-scons/build/subdir\n# HOME/test-scons/build/subdir\n# scons: done building targets.\n\n" ]
[ 2 ]
[]
[]
[ "build_automation", "python", "scons" ]
stackoverflow_0001916473_build_automation_python_scons.txt
Q: How to pass value for python for loop? In C/C++: for(int i=0;i<=5;i++) In Python: for i in range(0,5) Question is: s=[1,2,3,4,1] for i in s: for j in s: Here i wanna make second for loop j=1 (j value should be start with 1 like this s[1]=2).How do i pass that value. A: You should ask this on stackoverflow, but the answer is (if I got you right): for i in s: for j in s[1:]: Read this chapter about lists in python, this will help you.
How to pass value for python for loop?
In C/C++: for(int i=0;i<=5;i++) In Python: for i in range(0,5) Question is: s=[1,2,3,4,1] for i in s: for j in s: Here i wanna make second for loop j=1 (j value should be start with 1 like this s[1]=2).How do i pass that value.
[ "You should ask this on stackoverflow, but the answer is (if I got you right):\nfor i in s:\n for j in s[1:]:\n\nRead this chapter about lists in python, this will help you.\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0001916991_python.txt
Q: App engine app design questions I want to load info from another site (this part is done), but i am doing this every time the page is loaded and that wont do. So i was thinking of having a variable in a table of settings like 'last checked bbc site' and when the page loads it would check if its been long enough since last check to check again. Is there anything silly about doing it that way? Also do i absolutely have to use tables to store 1 off variables like this setting? A: I think there are 2 options that would work for you, besides creating a entity in the datastore to keep track of "last visited time". One way is to just check the external page periodically, using the cron api as described by jldupont. The second way is to store the last visited time in memcache. Although memcache is not permanent, it doesn't have to be if you are only storing last refresh times. If your entry in memcache were to disappear for some reason, the worst that would happen would be that you would fetch the page again, and update memcache with the current date/time. The first way would be best if you want to check the external page at regular intervals. The second way might be better if you want to check the external page only when a user clicks on your page, and you haven't fetched that page yourself in the recent past. With this method, you aren't wasting resources fetching the external page unless someone is actually looking for data related to it. A: You could also use Scheduled Tasks. Also, you don't absolutely need to use the Datastore for configuration parameters: you could have this in a script / config file. A: If you want some handler on your GAE app (including one for a scheduled task, reception of messages, web page visits, etc) to store some new information in such a way that some handler in the future can recover that information, then GAE's storage is the only good general way (memcache could expire from under you, for example). Not sure what you mean by "tables" (?!), but guessing that you actually mean GAE's storage the answer is "yes". (Under very specific circumstances you might want to put that data to some different place on the network, such as your visitor's browser e.g. via cookies, or an Amazon storage instance, etc, but it does not appear to me that those specific circumstances are appliable to your use case).
App engine app design questions
I want to load info from another site (this part is done), but i am doing this every time the page is loaded and that wont do. So i was thinking of having a variable in a table of settings like 'last checked bbc site' and when the page loads it would check if its been long enough since last check to check again. Is there anything silly about doing it that way? Also do i absolutely have to use tables to store 1 off variables like this setting?
[ "I think there are 2 options that would work for you, besides creating a entity in the datastore to keep track of \"last visited time\".\nOne way is to just check the external page periodically, using the cron api as described by jldupont. \nThe second way is to store the last visited time in memcache. Although memcache is not permanent, it doesn't have to be if you are only storing last refresh times. If your entry in memcache were to disappear for some reason, the worst that would happen would be that you would fetch the page again, and update memcache with the current date/time.\nThe first way would be best if you want to check the external page at regular intervals. The second way might be better if you want to check the external page only when a user clicks on your page, and you haven't fetched that page yourself in the recent past. With this method, you aren't wasting resources fetching the external page unless someone is actually looking for data related to it.\n", "You could also use Scheduled Tasks.\nAlso, you don't absolutely need to use the Datastore for configuration parameters: you could have this in a script / config file.\n", "If you want some handler on your GAE app (including one for a scheduled task, reception of messages, web page visits, etc) to store some new information in such a way that some handler in the future can recover that information, then GAE's storage is the only good general way (memcache could expire from under you, for example). Not sure what you mean by \"tables\" (?!), but guessing that you actually mean GAE's storage the answer is \"yes\". (Under very specific circumstances you might want to put that data to some different place on the network, such as your visitor's browser e.g. via cookies, or an Amazon storage instance, etc, but it does not appear to me that those specific circumstances are appliable to your use case).\n" ]
[ 2, 1, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0001916009_google_app_engine_python.txt
Q: How to launch a Python/Tkinter dialog box that self-destructs? Ok, I would like to put together a Python/Tkinter dialog box that displays a simple message and self-destructs after N seconds. Is there a simple way to do this? A: You can use the after function to call a function after a delay elapsed and the destroy to close the window. Here is an example from Tkinter import Label, Tk root = Tk() prompt = 'hello' label1 = Label(root, text=prompt, width=len(prompt)) label1.pack() def close_after_2s(): root.destroy() root.after(2000, close_after_2s) root.mainloop() Update: The after docstring says: Call function once after given time. MS specifies the time in milliseconds. FUNC gives the function which shall be called. Additional parameters are given as parameters to the function call. Return identifier to cancel scheduling with after_cancel. A: you could also use a thread. this example uses a Timer to call destroy() after a specified amount of time. import threading import Tkinter root = Tkinter.Tk() Tkinter.Frame(root, width=250, height=100).pack() Tkinter.Label(root, text='Hello').place(x=10, y=10) threading.Timer(3.0, root.destroy).start() root.mainloop()
How to launch a Python/Tkinter dialog box that self-destructs?
Ok, I would like to put together a Python/Tkinter dialog box that displays a simple message and self-destructs after N seconds. Is there a simple way to do this?
[ "You can use the after function to call a function after a delay elapsed and the destroy to close the window.\nHere is an example\nfrom Tkinter import Label, Tk\nroot = Tk()\nprompt = 'hello'\nlabel1 = Label(root, text=prompt, width=len(prompt))\nlabel1.pack()\n\ndef close_after_2s():\n root.destroy()\n\nroot.after(2000, close_after_2s)\nroot.mainloop()\n\nUpdate: The after docstring says:\n\nCall function once after given time.\n MS specifies the time in milliseconds. \n FUNC gives the function which shall be called. \n Additional parameters are given as parameters to the function call.\n Return identifier to cancel scheduling with after_cancel.\n\n", "you could also use a thread.\nthis example uses a Timer to call destroy() after a specified amount of time.\nimport threading\nimport Tkinter\n\n\nroot = Tkinter.Tk()\nTkinter.Frame(root, width=250, height=100).pack()\nTkinter.Label(root, text='Hello').place(x=10, y=10)\n\nthreading.Timer(3.0, root.destroy).start()\n\nroot.mainloop()\n\n" ]
[ 11, 1 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0001917198_python_tkinter.txt
Q: Would calling a function like this be considered bad practice? Suppose I have this function signature: def foo(a=True, b=True, c=True, d=True, e=True): I've decided these would be concise ways to call this function, considering all passed parameters should be False: foo(*5*[False]) foo(*[False]*5) But something tells me that would be bad Python style. What do you think? A: if it's hard to read, it's bad style. remember that code is read a lot more often than written. A: I like following the 80-20 rule with default values. If a function has default values for a parameter and I choose to use a different value, I need to make that evident in the call because that is an important piece of information. If you are actually going and "violating" five default parameters, I would explicitly show that in the call to make it clear to the reader. i.e., I would explicitly list each parameter by name and indicate the false. While the code you wrote should work, it is distracting, and someone would focus on figuring out what the hell you are doing rather than realizing the important bit - that you are making a very special call because you are not taking any of the defaults. This is not the place to save (electronic) trees. A: Your code should explain itself and be easy to read. The Style Guide for Python gives this example which should help answer your question: Use ''.startswith() and ''.endswith() instead of string slicing to check for prefixes or suffixes. startswith() and endswith() are cleaner and less error prone. For example: Yes: if foo.startswith('bar'): No: if foo[:3] == 'bar':
Would calling a function like this be considered bad practice?
Suppose I have this function signature: def foo(a=True, b=True, c=True, d=True, e=True): I've decided these would be concise ways to call this function, considering all passed parameters should be False: foo(*5*[False]) foo(*[False]*5) But something tells me that would be bad Python style. What do you think?
[ "if it's hard to read, it's bad style.\nremember that code is read a lot more often than written.\n", "I like following the 80-20 rule with default values. If a function has default values for a parameter and I choose to use a different value, I need to make that evident in the call because that is an important piece of information.\nIf you are actually going and \"violating\" five default parameters, I would explicitly show that in the call to make it clear to the reader. i.e., I would explicitly list each parameter by name and indicate the false.\nWhile the code you wrote should work, it is distracting, and someone would focus on figuring out what the hell you are doing rather than realizing the important bit - that you are making a very special call because you are not taking any of the defaults. This is not the place to save (electronic) trees.\n", "Your code should explain itself and be easy to read. The Style Guide for Python gives this example which should help answer your question:\n\nUse ''.startswith() and ''.endswith()\n instead of string slicing to check for\n prefixes or suffixes.\nstartswith() and endswith() are\n cleaner and less error prone. For\nexample:\n Yes: if foo.startswith('bar'):\n\n No: if foo[:3] == 'bar':\n\n\n" ]
[ 9, 4, 1 ]
[]
[]
[ "python" ]
stackoverflow_0001917537_python.txt
Q: Perl within Python? There is a Perl library I would like to access from within Python. How can I use it? FYI, the software is NCleaner. I would like to use it from within Python to transform an HTML string into text. (Yes, I know about aaronsw's Python html2text. NCleaner is better, because it removes boiler-plate.) I don't want to run the Perl program as a script and call it repeatedly, because it has an expensive initial load time and I am calling it many times. A: pyperl provides perl embedding for python, but honestly it's not the way I'd go. I second Roboto's suggestion -- write a script that runs NCleaner (either processing from stdin to stdout, or working on temporary files, whichever one is more appropriate), and run it as a subprocess. Or, since I see from the NCleaner page that it has a C implementation, use whatever facilities Python has for binding to C code and write a Python module that wraps the NCleaner C implementation. Then in the future the answer to invoking NCleaner from Python will just be "here, use this module." Footnote: Inline::Python is better code than pyperl, and I would suggest using that instead, but it only supports having Python call back to Perl when Python is invoked from Perl in the first place -- the ability to embed Perl into Python is listed as a possible future feature, but it's been so since 2001, so don't hold your breath.
Perl within Python?
There is a Perl library I would like to access from within Python. How can I use it? FYI, the software is NCleaner. I would like to use it from within Python to transform an HTML string into text. (Yes, I know about aaronsw's Python html2text. NCleaner is better, because it removes boiler-plate.) I don't want to run the Perl program as a script and call it repeatedly, because it has an expensive initial load time and I am calling it many times.
[ "pyperl provides perl embedding for python, but honestly it's not the way I'd go. I second Roboto's suggestion -- write a script that runs NCleaner (either processing from stdin to stdout, or working on temporary files, whichever one is more appropriate), and run it as a subprocess.\nOr, since I see from the NCleaner page that it has a C implementation, use whatever facilities Python has for binding to C code and write a Python module that wraps the NCleaner C implementation. Then in the future the answer to invoking NCleaner from Python will just be \"here, use this module.\"\nFootnote: Inline::Python is better code than pyperl, and I would suggest using that instead, but it only supports having Python call back to Perl when Python is invoked from Perl in the first place -- the ability to embed Perl into Python is listed as a possible future feature, but it's been so since 2001, so don't hold your breath.\n" ]
[ 13 ]
[]
[]
[ "perl", "python", "text_mining" ]
stackoverflow_0001917656_perl_python_text_mining.txt
Q: Python joining strings I have run into a problem joining two strings in Python. I have some code that is like this: for line in sites: site = line for line in files: url = site+line That should be easy I thougth but the strings ends up "looking wierd": http://example.com/ (this is the site) history.txt (Then the line comes on another "line" in the strings which screws it up when I try to open the url because it is invalid) Anyone knows a solution? A: The simplest thing is to avoid using the same variable in the for statements: for site in sites: for line in files: url = site + line Does that clear things up? It is good practice in any case. A: Maybe you have extra whitespace for example a newline at the end of the site for site in sites: for line in files: url = site.strip() + line.strip() A: Perhaps the problem is in using the identifier name 'line' twice?
Python joining strings
I have run into a problem joining two strings in Python. I have some code that is like this: for line in sites: site = line for line in files: url = site+line That should be easy I thougth but the strings ends up "looking wierd": http://example.com/ (this is the site) history.txt (Then the line comes on another "line" in the strings which screws it up when I try to open the url because it is invalid) Anyone knows a solution?
[ "The simplest thing is to avoid using the same variable in the for statements:\nfor site in sites:\n for line in files:\n url = site + line\n\nDoes that clear things up? It is good practice in any case.\n", "Maybe you have extra whitespace for example a newline at the end of the site\nfor site in sites:\n for line in files:\n url = site.strip() + line.strip()\n\n", "Perhaps the problem is in using the identifier name 'line' twice?\n" ]
[ 2, 1, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0001917705_python_string.txt
Q: Control decimal division precision in MySQLdb MySQLdb does some weirdness where it seems to always return a Decimal object with 2 more significant figures than the numerator of a division operation. If the denominator is relatively large, this means that sometimes the result gets truncated to zero: >>> import MySQLdb >>> db = MySQLdb.connect(.....) >>> c = db.cursor(); >>> c.execute("select 1000/ 20990933630") 1L >>> c.fetchall() ((Decimal("0.0000"),),) >>> c.execute("select 1000.0000000000000000000000/ 20990933630") 1L >>> c.fetchall() ((Decimal("4.763961516084313397E-8"),),) >>> c.execute("select (1000 + 0.000000000000000000000) / 20990933630") 1L >>> c.fetchall() ((Decimal("4.76396151608431340E-8"),),) Can I force float division? Is there a more elegant way of doing this than adding 0.0000000000 to everything? A: You can change the div_precision_increment variable. It defaults to 4. http://dev.mysql.com/doc/refman/5.0/en/server-system-variables.html#sysvar_div_precision_increment Here's an example using your division: mysql> select 1000/ 20990933630; +-------------------+ | 1000/ 20990933630 | +-------------------+ | 0.0000 | +-------------------+ 1 row in set (0.00 sec) mysql> set local div_precision_increment = 30; Query OK, 0 rows affected (0.00 sec) mysql> select 1000/ 20990933630; +----------------------------------+ | 1000/ 20990933630 | +----------------------------------+ | 0.000000047639615160843133969739 | +----------------------------------+ 1 row in set (0.00 sec) mysql>
Control decimal division precision in MySQLdb
MySQLdb does some weirdness where it seems to always return a Decimal object with 2 more significant figures than the numerator of a division operation. If the denominator is relatively large, this means that sometimes the result gets truncated to zero: >>> import MySQLdb >>> db = MySQLdb.connect(.....) >>> c = db.cursor(); >>> c.execute("select 1000/ 20990933630") 1L >>> c.fetchall() ((Decimal("0.0000"),),) >>> c.execute("select 1000.0000000000000000000000/ 20990933630") 1L >>> c.fetchall() ((Decimal("4.763961516084313397E-8"),),) >>> c.execute("select (1000 + 0.000000000000000000000) / 20990933630") 1L >>> c.fetchall() ((Decimal("4.76396151608431340E-8"),),) Can I force float division? Is there a more elegant way of doing this than adding 0.0000000000 to everything?
[ "You can change the div_precision_increment variable. It defaults to 4.\nhttp://dev.mysql.com/doc/refman/5.0/en/server-system-variables.html#sysvar_div_precision_increment\nHere's an example using your division:\nmysql> select 1000/ 20990933630;\n+-------------------+\n| 1000/ 20990933630 |\n+-------------------+\n| 0.0000 | \n+-------------------+\n1 row in set (0.00 sec)\n\nmysql> set local div_precision_increment = 30;\nQuery OK, 0 rows affected (0.00 sec)\n\nmysql> select 1000/ 20990933630;\n+----------------------------------+\n| 1000/ 20990933630 |\n+----------------------------------+\n| 0.000000047639615160843133969739 | \n+----------------------------------+\n1 row in set (0.00 sec)\n\nmysql> \n\n" ]
[ 3 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0001917385_mysql_python.txt
Q: Need to add httpd support to this wxPython code I need to add httpd support to this sample wxpython code. It parses the url and display different images. What's the easiest way to do this? import wx a = wx.PySimpleApp() wximg = wx.Image('w.png',wx.BITMAP_TYPE_PNG) wxbmp=wximg.ConvertToBitmap() f = wx.Frame(None, -1, "Show JPEG demo") f.SetSize( wxbmp.GetSize() ) wx.StaticBitmap(f,-1,wxbmp,(0,0)) f.Show(True) def callback(evt,a=a,f=f): # Closes the window upon any keypress f.Close() a.ExitMainLoop() wx.EVT_CHAR(f,callback) a.MainLoop() A: Problem solved. Need to add from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer .... class w_HttpThread(threading.Thread): def __init__(self, win): ... On particular URL, do wx.PostEvent to the wx windows. wxWindows code will update the window with new image. It works too. Love python!
Need to add httpd support to this wxPython code
I need to add httpd support to this sample wxpython code. It parses the url and display different images. What's the easiest way to do this? import wx a = wx.PySimpleApp() wximg = wx.Image('w.png',wx.BITMAP_TYPE_PNG) wxbmp=wximg.ConvertToBitmap() f = wx.Frame(None, -1, "Show JPEG demo") f.SetSize( wxbmp.GetSize() ) wx.StaticBitmap(f,-1,wxbmp,(0,0)) f.Show(True) def callback(evt,a=a,f=f): # Closes the window upon any keypress f.Close() a.ExitMainLoop() wx.EVT_CHAR(f,callback) a.MainLoop()
[ "Problem solved. \nNeed to add \nfrom BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer\n ....\n\nclass w_HttpThread(threading.Thread):\n def __init__(self, win):\n\n ...\n\nOn particular URL, do wx.PostEvent to the wx windows.\nwxWindows code will update the window with new image.\nIt works too. Love python!\n" ]
[ 0 ]
[]
[]
[ "apache", "python", "wxpython" ]
stackoverflow_0001910226_apache_python_wxpython.txt
Q: Auth_token error at Facebook i have been on this for the last 2 days with no result. i am running my facebook app on my localhost with port-forwarding method. i know my server setup is working fine as i can see the logs on the django runserver and dyndns log as well. django is properly responding to calls as well. the problem is as soon as the app authorizes with my user account, it straight follows to the page that says this: Errors while loading page from application The URL http://amitverma.dyndns.org/facebook_sample/?auth_token=817f8fbe99eff10582b634589de17b84 is not valid. Please try again later. We appreciate your patience as the developers of app_test and Facebook resolve this issue. Thanks! I am making a test app learning from facebook + django tutorial from here and here. I am still getting this error and I have no idea what i am doing wrong... Please help me out. A: This often happens with a failed authentication. I'm not sure what the Python client libraries might look like, but with the PHP ones you generally make an authorization call against the library, something like $facebook->require_login(). With the PHP library, if this call fails to verify the user's Facebook session, then it automatically outputs HTML that will redirect the browser and try to re-establish the session, hence the auth_token parameter. I suspect you're running into something similar. Try to isolate any authentication calls you're making, and use a Firefox extension like LiveHTTPHeaders to see if you are undergoing any redirects during the requests. A: When you get that error, presuming you have debug=True in the Django settings and that your application is in development mode in Facebook, you can do View Source and see the entire Django error page that would normally display, including traceback. Facebook comment it out in the HTML so it doesn't show on the front end, but you can copy and paste it into a separate HTML file and view that in your browser to see the nice friendly Django error page which will definitely give you a clue as to what's going wrong.
Auth_token error at Facebook
i have been on this for the last 2 days with no result. i am running my facebook app on my localhost with port-forwarding method. i know my server setup is working fine as i can see the logs on the django runserver and dyndns log as well. django is properly responding to calls as well. the problem is as soon as the app authorizes with my user account, it straight follows to the page that says this: Errors while loading page from application The URL http://amitverma.dyndns.org/facebook_sample/?auth_token=817f8fbe99eff10582b634589de17b84 is not valid. Please try again later. We appreciate your patience as the developers of app_test and Facebook resolve this issue. Thanks! I am making a test app learning from facebook + django tutorial from here and here. I am still getting this error and I have no idea what i am doing wrong... Please help me out.
[ "This often happens with a failed authentication. I'm not sure what the Python client libraries might look like, but with the PHP ones you generally make an authorization call against the library, something like $facebook->require_login().\nWith the PHP library, if this call fails to verify the user's Facebook session, then it automatically outputs HTML that will redirect the browser and try to re-establish the session, hence the auth_token parameter.\nI suspect you're running into something similar. Try to isolate any authentication calls you're making, and use a Firefox extension like LiveHTTPHeaders to see if you are undergoing any redirects during the requests.\n", "When you get that error, presuming you have debug=True in the Django settings and that your application is in development mode in Facebook, you can do View Source and see the entire Django error page that would normally display, including traceback. Facebook comment it out in the HTML so it doesn't show on the front end, but you can copy and paste it into a separate HTML file and view that in your browser to see the nice friendly Django error page which will definitely give you a clue as to what's going wrong.\n" ]
[ 1, 0 ]
[]
[]
[ "django", "facebook", "python" ]
stackoverflow_0001918047_django_facebook_python.txt
Q: Making Windows executables from Django applications I am trying to make a Django website be a simple Windows executable. I've been told that py2exe does not work correctly, both due to Django using __import__, and to its attempting to dispatch manage.py in some obscure way. Is that the case? If so, is there an alternative tool that works better, or is there a way to work around the py2exe issues? A: You can try Pyinstaller. A: PyInstaller trunk has been succesfully used to build Django applications. It has builtin support for many Django magic, but requires a careful setup (have a look at the dedicated wiki page).
Making Windows executables from Django applications
I am trying to make a Django website be a simple Windows executable. I've been told that py2exe does not work correctly, both due to Django using __import__, and to its attempting to dispatch manage.py in some obscure way. Is that the case? If so, is there an alternative tool that works better, or is there a way to work around the py2exe issues?
[ "You can try Pyinstaller.\n", "PyInstaller trunk has been succesfully used to build Django applications. It has builtin support for many Django magic, but requires a careful setup (have a look at the dedicated wiki page).\n" ]
[ 2, 0 ]
[]
[]
[ "django", "py2exe", "python" ]
stackoverflow_0001821632_django_py2exe_python.txt
Q: Python import mechanics I have two related Python 'import' questions. They are easily testable, but I want answers that are language-defined and not implementation-specific, and I'm also interested in style/convention, so I'm asking here instead. 1) If module A imports module B, and module B imports module C, can code in module A reference module C without an explicit import? If so, am I correct in assuming this is bad practice? 2) If I import module A.B.C, does that import modules A and A.B as well? If so, is it by convention better to explicitly import A; import A.B; import A.B.C? A: The first thing you should know is that the Python language is NOT an ISO standard. This is rather different from C/C++, and it means that there's no "proper" way to define a language behaviour - CPython might do something just because it was coded that way, and Jython might do the other way round. about your questions, remember that "importing" a module is a two-part operation: first the module is loaded - if it had never been, e.g. if it wasn't available in sys.modules, then a name is bound to that module in the local namespace. hence: 1) Yes, you can reference whatever you want from module a by providing the proper namespace, e.g. you'll have to do something like B.C.name = "something" And I think this is very rarely done in Python programs and could be considered bad practice since it forces a "transitive dep" - if some module B implementation is refactored and doesn't depend on C anymore, it should continue offering the C module just for satisfying A deps. Of course setting __ all __ can prevent this, and a good practice may be to put __ all __ in all your modules, and export just the symbols you want to be really public. 2) Yes and no. Doing import a.b.c.d performs the first import phase (loading) on all modules, but the second just on a (and, recursively, in b with respect to c, etc) but all the modules in the chain must be referenced by full namespace; after such an import, you can do a.something a.b.something a.b.c.something but you can't do c.something b.something I must admit that kind of usage is pretty rare as well; I generally prefer the "from module import something" way-to-import, and generally you just ask for what you need - such nesting is neither common in libraries, nor its usage is that common. Many times there're "outer packages", just used for organization, which hold modules with classes. It's very likely that a, b, c above are just packages, and d is a module which truly holds classes, functions and other objects. So the proper usage would be: from a.b.c.d import name1, name2, name3 I hope this satifies your curiosity. A: Alan's given a great answer, but I wanted to add that for your question 1 it depends on what you mean by 'imports'. If you use the from C import x syntax, then x becomes available in the namespace of B. If in A you then do import B, you will have access to x from A as B.x. It's not so much bad practice as potentially confusing, and will make debugging etc harder as you won't necessarily know where the objects have come from.
Python import mechanics
I have two related Python 'import' questions. They are easily testable, but I want answers that are language-defined and not implementation-specific, and I'm also interested in style/convention, so I'm asking here instead. 1) If module A imports module B, and module B imports module C, can code in module A reference module C without an explicit import? If so, am I correct in assuming this is bad practice? 2) If I import module A.B.C, does that import modules A and A.B as well? If so, is it by convention better to explicitly import A; import A.B; import A.B.C?
[ "The first thing you should know is that the Python language is NOT an ISO standard. This is rather different from C/C++, and it means that there's no \"proper\" way to define a language behaviour - CPython might do something just because it was coded that way, and Jython might do the other way round.\nabout your questions, remember that \"importing\" a module is a two-part operation: first the module is loaded - if it had never been, e.g. if it wasn't available in sys.modules, then a name is bound to that module in the local namespace.\nhence:\n1) Yes, you can reference whatever you want from module a by providing the proper namespace, e.g. you'll have to do something like\nB.C.name = \"something\"\nAnd I think this is very rarely done in Python programs and could be considered bad practice since it forces a \"transitive dep\" - if some module B implementation is refactored and doesn't depend on C anymore, it should continue offering the C module just for satisfying A deps.\nOf course setting __ all __ can prevent this, and a good practice may be to put __ all __ in all your modules, and export just the symbols you want to be really public.\n2) Yes and no. Doing \nimport a.b.c.d \n\nperforms the first import phase (loading) on all modules, but the second just on a (and, recursively, in b with respect to c, etc) but all the modules in the chain must be referenced by full namespace; after such an import, you can do\na.something\na.b.something\na.b.c.something\n\nbut you can't do \nc.something\nb.something\n\nI must admit that kind of usage is pretty rare as well; I generally prefer the \"from module import something\" way-to-import, and generally you just ask for what you need - such nesting is neither common in libraries, nor its usage is that common.\nMany times there're \"outer packages\", just used for organization, which hold modules with classes. It's very likely that a, b, c above are just packages, and d is a module which truly holds classes, functions and other objects. So the proper usage would be:\nfrom a.b.c.d import name1, name2, name3\n\nI hope this satifies your curiosity.\n", "Alan's given a great answer, but I wanted to add that for your question 1 it depends on what you mean by 'imports'.\nIf you use the from C import x syntax, then x becomes available in the namespace of B. If in A you then do import B, you will have access to x from A as B.x.\nIt's not so much bad practice as potentially confusing, and will make debugging etc harder as you won't necessarily know where the objects have come from.\n" ]
[ 13, 11 ]
[]
[]
[ "coding_style", "conventions", "import", "module", "python" ]
stackoverflow_0001917958_coding_style_conventions_import_module_python.txt
Q: How to store a dynamic List into MySQL column efficiently? I want to store a list of numbers along with some other fields into MySQL. The number of elements in the list is dynamic (some time it could hold about 60 elements) Currently I'm storing the list into a column of varchar type and the following operations are done. e.g. aList = [1234122433,1352435632,2346433334,1234122464] At storing time, aList is coverted to string as below aListStr = str(aList) and at reading time the string is converted back to list as below. aList = eval(aListStr) There are about 10 million rows, and since I'm storing as strings, it occupies lot space. What is the most efficient way to do this? Also what should be the efficient way for storing list of strings instead of numbers? A: Since you wish to store integers, an effective way would be to store them in an INT/DECIMAL column. Create an additional table that will hold these numbers and add an ID column to relate the records to other table(s). Also what should be the efficient way for storing list of strings instead of numbers? Beside what I said, you can convert them to HEX code which will be very easy & take less space. Note that a big VARCHAR may influence badly on the performance. VARCHAR(2) and VARCHAR(50) does matter when actions like sotring are done, since MySQL allocates fixed-size memory slices for them, according to the VARCHAR maximum size. When those slices are too large to store in memory, MySQL will store them on disk. A: MySQL also has a SET type, it works like ENUM but can hold multiple items. Of course you'd have to have a limited list, currently MySQL only supports up to 64 different items. A: I'd be less worried about storage space and more worried about record retrieveal i.e., indexability/searching. For example, I imagine performing a LIKE or REGEXP in a WHERE clause to find a single item in the list will be quite bit more expensive than if you normalized each list item into a row in a separate table. However, if you never need to perform such queries agains these columns, then it just won't matter. A: Since you are using relational database you should know that storing non-atomic values in individual fields breaks even the first normal form. More likely than not you should follow Don's advice and keep those values in related table. I can't say that for certain because I don't know your problem domain. It may well be that choosing RDBMS for this data was a bad choice altogether.
How to store a dynamic List into MySQL column efficiently?
I want to store a list of numbers along with some other fields into MySQL. The number of elements in the list is dynamic (some time it could hold about 60 elements) Currently I'm storing the list into a column of varchar type and the following operations are done. e.g. aList = [1234122433,1352435632,2346433334,1234122464] At storing time, aList is coverted to string as below aListStr = str(aList) and at reading time the string is converted back to list as below. aList = eval(aListStr) There are about 10 million rows, and since I'm storing as strings, it occupies lot space. What is the most efficient way to do this? Also what should be the efficient way for storing list of strings instead of numbers?
[ "Since you wish to store integers, an effective way would be to store them in an INT/DECIMAL column.\nCreate an additional table that will hold these numbers and add an ID column to relate the records to other table(s).\n\nAlso what should be the efficient way\n for storing list of strings instead of\n numbers?\n\nBeside what I said, you can convert them to HEX code which will be very easy & take less space.\nNote that a big VARCHAR may influence badly on the performance.\nVARCHAR(2) and VARCHAR(50) does matter when actions like sotring are done, since MySQL allocates fixed-size memory slices for them, according to the VARCHAR maximum size.\nWhen those slices are too large to store in memory, MySQL will store them on disk.\n", "MySQL also has a SET type, it works like ENUM but can hold multiple items.\nOf course you'd have to have a limited list, currently MySQL only supports up to 64 different items.\n", "I'd be less worried about storage space and more worried about record retrieveal i.e., indexability/searching.\nFor example, I imagine performing a LIKE or REGEXP in a WHERE clause to find a single item in the list will be quite bit more expensive than if you normalized each list item into a row in a separate table.\nHowever, if you never need to perform such queries agains these columns, then it just won't matter.\n", "Since you are using relational database you should know that storing non-atomic values in individual fields breaks even the first normal form. More likely than not you should follow Don's advice and keep those values in related table. I can't say that for certain because I don't know your problem domain. It may well be that choosing RDBMS for this data was a bad choice altogether.\n" ]
[ 2, 1, 0, 0 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0001917106_mysql_python.txt
Q: When using py2app, is there a way to customize the traceback dialog that gets displayed? (Or show a different Cocoa dialog?) Is there an easy way to get any more control over the py2app traceback dialogs, or just a nice way to display GUI messages? If I raise an exception in my py2app script, I get a dialog that says something like this: MyAppName Error MyAppName Error An unexpected error has occurred during execution of the main script MyRaisedError: This is the text that I can control when I raise the error. It has Open Console and Terminate buttons. My script needs to check if a certain DVD is in the drive, if it's not, I want to show an error dialog and quit. I would like to have more control over it than this, as I can only change some of the text and can't control the buttons. I tried calling osascript to do 'display dialog' via applescript, but it gave me an error like this: 0:19: execution error: No user interaction allowed. (-1713) I don't particularly like this way of doing it, but if it's all I can do... I would really prefer not to include a big project like Cocoa Dialogs or something like a PyObjC project... the script itself is very tiny and I can't see adding 10x the meat of my script just to get the dialog. A: Instead of using osascript, you can call display dialog via py-appscript which, if you don't already have it in your python site-library, can be installed via easy_install. This example works inside of a py2app-generated app: #!/usr/bin/env python from osax import * import py2app def doit(): sa = OSAX() sa.display_dialog("Python says hello!", buttons=["Hi!", "Howdy!", "Duuuude!"], default_button=3) if __name__ == '__main__': doit() A: Just put a standard Python try/catch block around the section of code that throws the exception, then use NSAlert to tell your users they need to put the DVD in
When using py2app, is there a way to customize the traceback dialog that gets displayed? (Or show a different Cocoa dialog?)
Is there an easy way to get any more control over the py2app traceback dialogs, or just a nice way to display GUI messages? If I raise an exception in my py2app script, I get a dialog that says something like this: MyAppName Error MyAppName Error An unexpected error has occurred during execution of the main script MyRaisedError: This is the text that I can control when I raise the error. It has Open Console and Terminate buttons. My script needs to check if a certain DVD is in the drive, if it's not, I want to show an error dialog and quit. I would like to have more control over it than this, as I can only change some of the text and can't control the buttons. I tried calling osascript to do 'display dialog' via applescript, but it gave me an error like this: 0:19: execution error: No user interaction allowed. (-1713) I don't particularly like this way of doing it, but if it's all I can do... I would really prefer not to include a big project like Cocoa Dialogs or something like a PyObjC project... the script itself is very tiny and I can't see adding 10x the meat of my script just to get the dialog.
[ "Instead of using osascript, you can call display dialog via py-appscript which, if you don't already have it in your python site-library, can be installed via easy_install. This example works inside of a py2app-generated app:\n#!/usr/bin/env python\nfrom osax import *\nimport py2app\n\ndef doit():\n sa = OSAX()\n sa.display_dialog(\"Python says hello!\",\n buttons=[\"Hi!\", \"Howdy!\", \"Duuuude!\"],\n default_button=3)\n\nif __name__ == '__main__':\n doit()\n\n", "Just put a standard Python try/catch block around the section of code that throws the exception, then use NSAlert to tell your users they need to put the DVD in\n" ]
[ 2, 0 ]
[]
[]
[ "macos", "py2app", "python" ]
stackoverflow_0001917769_macos_py2app_python.txt
Q: Make a tkinter window appear over all other windows #!/usr/bin/env python # Display window with toDisplayText and timeOut of the window. from Tkinter import * def showNotification(notificationTimeout, textToDisplay): ## Create main window root = Tk() Button(root, text=textToDisplay, activebackground="white", bg="white", command=lambda: root.destroy()).pack(side=LEFT) root.update_idletasks() # Remove window decorations root.overrideredirect(1) timeOut = int(notificationTimeout*1000) # Convert to ms from s ## Run appliction root.after(timeOut,root.destroy) root.mainloop() The above code creates a notification, with a timout. However on windows - the notification does not automatically pop up above all other present windows automatically. One has to click on the kill button (the text), and focus it the first time, after which the root window will be displayed above all other windows. Is there a way to make the notification automatically appear above all other windows - on windows? It seems to work on linux just fine (ubuntu 9.10). A: According to this message you should be able to add the following after root.overridedirect(1). A quick test here suggests it should work for you. root.wm_attributes("-topmost", 1)
Make a tkinter window appear over all other windows
#!/usr/bin/env python # Display window with toDisplayText and timeOut of the window. from Tkinter import * def showNotification(notificationTimeout, textToDisplay): ## Create main window root = Tk() Button(root, text=textToDisplay, activebackground="white", bg="white", command=lambda: root.destroy()).pack(side=LEFT) root.update_idletasks() # Remove window decorations root.overrideredirect(1) timeOut = int(notificationTimeout*1000) # Convert to ms from s ## Run appliction root.after(timeOut,root.destroy) root.mainloop() The above code creates a notification, with a timout. However on windows - the notification does not automatically pop up above all other present windows automatically. One has to click on the kill button (the text), and focus it the first time, after which the root window will be displayed above all other windows. Is there a way to make the notification automatically appear above all other windows - on windows? It seems to work on linux just fine (ubuntu 9.10).
[ "According to this message you should be able to add the following after root.overridedirect(1). A quick test here suggests it should work for you.\nroot.wm_attributes(\"-topmost\", 1)\n\n" ]
[ 9 ]
[]
[]
[ "focus", "python", "stack", "tkinter", "windows" ]
stackoverflow_0001918752_focus_python_stack_tkinter_windows.txt
Q: Reading a file via open().read() vs storing it in a variable I've written this small app in Python that will generate paragraphs of dummy text, kind of like this site, except it'll work offline. Right now you're supposed to provide a reasonably long text file (I'm currently using books from Project Gutenberg), which it will call open() and then read() on to get the initial string for the operation, but what's to stop me from just including the whole text file in the program, as a variable? i.e lorem_ipsum = """ ***full text of De finibus bonorum et malorum*** ***no seriously*** ***yeah...*** """ Are there any disadvantages to doing this versus reading it in from a separate text file? A: There's a few problems: Your program becomes really hard to read. You run the risk of """ appearing in the text and blowing everything up You break the whole concept of content existing in the format in which it belongs. The book in question is a text file, it should live in a text file and if Python needs it, it should pull it from there. Otherwise newcomers to the app have to look everywhere for every type of data. not fun.
Reading a file via open().read() vs storing it in a variable
I've written this small app in Python that will generate paragraphs of dummy text, kind of like this site, except it'll work offline. Right now you're supposed to provide a reasonably long text file (I'm currently using books from Project Gutenberg), which it will call open() and then read() on to get the initial string for the operation, but what's to stop me from just including the whole text file in the program, as a variable? i.e lorem_ipsum = """ ***full text of De finibus bonorum et malorum*** ***no seriously*** ***yeah...*** """ Are there any disadvantages to doing this versus reading it in from a separate text file?
[ "There's a few problems:\n\nYour program becomes really hard to read.\nYou run the risk of \"\"\" appearing in the text and blowing everything up\nYou break the whole concept of content existing in the format in which it belongs. The book in question is a text file, it should live in a text file and if Python needs it, it should pull it from there. Otherwise newcomers to the app have to look everywhere for every type of data. not fun.\n\n" ]
[ 12 ]
[]
[]
[ "python" ]
stackoverflow_0001918965_python.txt
Q: how to add all of these values in a python dictionary last one for the night, want to see what clever ways there are with python to add all of the 'count' values from the following type of dictionary: {0: {'count': 1000}, 1: {'count': 2000}} so the end result should be an int value of 3000. A: >>> x = {0: {'count': 1000}, 1: {'count': 2000}} >>> sum(v['count'] for v in x.values()) 3000 A: A shorter one: sum(d[k]['count'] for k in d) A: sum(i['count'] for i in d.values()) A: How about using reduction in python? reduce(lambda x,y: x+y, [v['count'] for v in a.values()])
how to add all of these values in a python dictionary
last one for the night, want to see what clever ways there are with python to add all of the 'count' values from the following type of dictionary: {0: {'count': 1000}, 1: {'count': 2000}} so the end result should be an int value of 3000.
[ ">>> x = {0: {'count': 1000}, 1: {'count': 2000}}\n>>> sum(v['count'] for v in x.values()) \n3000\n\n", "A shorter one:\nsum(d[k]['count'] for k in d)\n\n", "sum(i['count'] for i in d.values())\n\n", "How about using reduction in python?\nreduce(lambda x,y: x+y, [v['count'] for v in a.values()])\n\n" ]
[ 4, 4, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001919054_python.txt
Q: What is a hashtable/dictionary implementation for Python that doesn't store the keys? I'm storing millions, possibly billions of 4 byte values in a hashtable and I don't want to store any of the keys. I expect that only the hashes of the keys and the values will have to be stored. This has to be fast and all kept in RAM. The entries would still be looked up with the key, unlike set()'s. What is an implementation of this for Python? Is there a name for this? Yes, collisions are allowed and can be ignored. (I can make an exception for collisions, the key can be stored for those. Alternatively, collisions can just overwrite the previously stored value.) A: Bloomier filters - space-efficient associative array From the Wikipedia: Chazelle et al. (2004) designed a generalization of Bloom filters that could associate a value with each element that had been inserted, implementing an associative array. Like Bloom filters, these structures achieve a small space overhead by accepting a small probability of false positives. In the case of "Bloomier filters", a false positive is defined as returning a result when the key is not in the map. The map will never return the wrong value for a key that is in the map. A: How about using an ordinary dictionary and instead of doing: d[x]=y use: d[hash(x)]=y To look up: d[hash(foo)] Of course, if there is a hash collision, you may get the wrong value back. A: Its the good old space vs runtime tradeoff: You can have constant time with linear space usage for the keys in a hastable. Or you can store the key implicitly and use log n time by using a binary tree. The (binary) hash of a value gives you the path in the tree where it will be stored. A: Build your own b-tree in RAM. Memory use: (4 bytes) comparison hash value (4 bytes) index of next leaf if hash <= comparison OR if negative index of value (4 bytes) index of next leaf if hash > comparison OR if negative index of value 12 bytes per b-tree node for the b-tree. More overhead for the values (see below). How you structure this in Python - aren't there "native arrays" of 32bit integers upported with almost no extra memory overhead...? what are they called... anyway those. Separate ordered array of subarrays each containing one or more values. The "indexes of value" above are indexes into this big array, allowing retrieval of all values matching the hash. This assumes a 32bit hash. You will need more bytes per b-tree node if you have greater than 2^31-1 entries or a larger hash. BUT Spanner in the works perhaps: Note that you will not be able, if you are not storing the key values, to verify that a hash value looked up corresponds only to your key unless through some algorithmic or organisational mechanism you have guaranteed that no two keys will have the same hash. Quite a serious issue here. Have you considered it? :) A: Although python dictionaries are very efficient, I think that if you're going to store billions of items, you may want to create your own C extension with data structures, optimized for the way you are actually using it (sequential access? completely random? etc). In order to create a C extension, you may want to use SWIG, or something like Pyrex (which I've never used). A: Hash table has to store keys, unless you provide a hash function that gives absolutely no collisions, which is nearly impossible. There is, however, if your keys are string-like, there is a very space-efficient data structure - directed acyclic word graph (DAWG). I don't know any Python implementation though. A: It's not what you asked for buy why not consider Tokyo Cabinet or BerkleyDB for this job? It won't be in memory but you are trading performance for greater storage capacity. You could still keep your list in memory and use the database only to check existence. A: If you're actually storing millions of unique values, why not use a dictionary? Store: d[hash(key)/32] |= 2**(hash(key)%32) Check: (d[hash(key)/32] | 2**(hash(key)%32)) If you have billions of entries, use a numpy array of size (2**32)/32, instead. (Because, after all, you only have 4 billion possible values to store, anyway). A: Would you please tell us more about the keys? I'm wondering if there is any regularity in the keys that we could exploit. If the keys are strings in a small alphabet (example: strings of digits, like phone numbers) you could use a trie data structure: http://en.wikipedia.org/wiki/Trie A: Why not a dictionary + hashlib? >>> import hashlib >>> hashtable = {} >>> def myHash(obj): return hashlib.sha224(obj).hexdigest() >>> hashtable[myHash("foo")] = 'bar' >>> hashtable {'0808f64e60d58979fcb676c96ec938270dea42445aeefcd3a4e6f8db': 'bar'}
What is a hashtable/dictionary implementation for Python that doesn't store the keys?
I'm storing millions, possibly billions of 4 byte values in a hashtable and I don't want to store any of the keys. I expect that only the hashes of the keys and the values will have to be stored. This has to be fast and all kept in RAM. The entries would still be looked up with the key, unlike set()'s. What is an implementation of this for Python? Is there a name for this? Yes, collisions are allowed and can be ignored. (I can make an exception for collisions, the key can be stored for those. Alternatively, collisions can just overwrite the previously stored value.)
[ "Bloomier filters - space-efficient associative array\nFrom the Wikipedia:\n\nChazelle et al. (2004) designed a\n generalization of Bloom filters that\n could associate a value with each\n element that had been inserted,\n implementing an associative array.\n Like Bloom filters, these structures\n achieve a small space overhead by\n accepting a small probability of false\n positives. In the case of \"Bloomier\n filters\", a false positive is defined\n as returning a result when the key is\n not in the map. The map will never\n return the wrong value for a key that\n is in the map.\n\n", "How about using an ordinary dictionary and instead of doing:\nd[x]=y\n\nuse:\nd[hash(x)]=y\n\nTo look up:\nd[hash(foo)]\n\nOf course, if there is a hash collision, you may get the wrong value back.\n", "Its the good old space vs runtime tradeoff: You can have constant time with linear space usage for the keys in a hastable. Or you can store the key implicitly and use log n time by using a binary tree. The (binary) hash of a value gives you the path in the tree where it will be stored.\n", "Build your own b-tree in RAM.\nMemory use:\n(4 bytes) comparison hash value\n(4 bytes) index of next leaf if hash <= comparison OR if negative index of value\n(4 bytes) index of next leaf if hash > comparison OR if negative index of value\n12 bytes per b-tree node for the b-tree. More overhead for the values (see below).\nHow you structure this in Python - aren't there \"native arrays\" of 32bit integers upported with almost no extra memory overhead...? what are they called... anyway those.\nSeparate ordered array of subarrays each containing one or more values. The \"indexes of value\" above are indexes into this big array, allowing retrieval of all values matching the hash.\nThis assumes a 32bit hash. You will need more bytes per b-tree node if you have\ngreater than 2^31-1 entries or a larger hash.\nBUT Spanner in the works perhaps: Note that you will not be able, if you are not storing the key values, to verify that a hash value looked up corresponds only to your key unless through some algorithmic or organisational mechanism you have guaranteed that no two keys will have the same hash. Quite a serious issue here. Have you considered it? :)\n", "Although python dictionaries are very efficient, I think that if you're going to store billions of items, you may want to create your own C extension with data structures, optimized for the way you are actually using it (sequential access? completely random? etc). \nIn order to create a C extension, you may want to use SWIG, or something like Pyrex (which I've never used).\n", "Hash table has to store keys, unless you provide a hash function that gives absolutely no collisions, which is nearly impossible.\nThere is, however, if your keys are string-like, there is a very space-efficient data structure - directed acyclic word graph (DAWG). I don't know any Python implementation though.\n", "It's not what you asked for buy why not consider Tokyo Cabinet or BerkleyDB for this job? It won't be in memory but you are trading performance for greater storage capacity. You could still keep your list in memory and use the database only to check existence.\n", "If you're actually storing millions of unique values, why not use a dictionary?\nStore: d[hash(key)/32] |= 2**(hash(key)%32)\nCheck: (d[hash(key)/32] | 2**(hash(key)%32))\nIf you have billions of entries, use a numpy array of size (2**32)/32, instead. (Because, after all, you only have 4 billion possible values to store, anyway).\n", "Would you please tell us more about the keys? I'm wondering if there is any regularity in the keys that we could exploit.\nIf the keys are strings in a small alphabet (example: strings of digits, like phone numbers) you could use a trie data structure:\nhttp://en.wikipedia.org/wiki/Trie\n", "Why not a dictionary + hashlib?\n>>> import hashlib\n>>> hashtable = {}\n>>> def myHash(obj):\n return hashlib.sha224(obj).hexdigest()\n\n>>> hashtable[myHash(\"foo\")] = 'bar'\n>>> hashtable\n{'0808f64e60d58979fcb676c96ec938270dea42445aeefcd3a4e6f8db': 'bar'}\n\n" ]
[ 5, 3, 3, 2, 2, 1, 1, 1, 1, 0 ]
[]
[]
[ "data_structures", "dictionary", "hashtable", "map", "python" ]
stackoverflow_0001918456_data_structures_dictionary_hashtable_map_python.txt
Q: Nested Methods? Why are they useful? So I'm just learning some new stuff in C# & Python. Turns out both lanuages support nested methods (C# sort of does). Python: def MyMethod(): print 'Hello from a method.' def MyInnerMethod(): print 'Hello from a nested method.' MyInnerMethod() C# (using new features in .NET 3.5):* static void Main() { Console.WriteLine("Hello from main."); Func<int, int> NestedMethod = (x) => { Console.WriteLine("In nested method. Value of x is {0}.", x); return x; }; int result = NestedMethod(3); } So why are nested methods so important? What makes them useful? **The C# code has not been tested. Feel free to edit if it doesn't compile.* A: First, realize I cannot give you a complete list. If you were to ask "why are screwdrivers useful?", I would would talk about screws and paint can lids but would miss their value in termite inspection. When you ask, "Why are nested functions useful?", I can tell you about scoping, closures, and entry points. First, nesting can be an alternative to classes. I recently wrote some rendering code that took a file name for specialized mark-up code and returned a bitmap. This naturally lead to functions named grab_markup_from_filename() and render_text_onto_image() and others. The cleanest organization was one entry point named generate_png_from_markup_filename(). The entry point did its job, using nested functions to accomplish its task. There was no need for a class, because there was no object with state. My alternative was to create a module with private methods hiding my helpers, but it would be messier. def generate_png_from_markup_filename(filename): def grab_markup_from_filename(): ... ... # code that calls grab_markup_from_filename() to make the image return image Second, I use nesting for closures. The most common example is for creating decorators. The trick is that I return a reference to an inner function, so that inner function and the outer parameter value are not garbage collected. def verify_admin(function_to_call): def call_on_verify_admin(*args, **kwargs): if is_admin(global.session.user): return function_to_call(*args, **kwargs) else: throw Exception("Not Admin") return call_on_verify_admin # the return value of verify_admin() use it this way: def update_price(item, price): database.lookup(item).set_field('price', price) update_price = verify_admin(update_price) or, more concisely: @verify_admin def update_price(item, price): database.lookup(item).set_field('price', price) And yes, it should be hard to trace. Remember that "def" is just another statement. So, here are two places nested classes are helpful. There are more. It is a tool. A: Nested methods are useful because there are many cases where you want to pass behaviour around, rather than just data. In many instances, it is clearer and easier to follow, in addition to being easier and faster to write, to just define that behaviour in the body of your method, where you are going to use it. In .NET, LINQ is a great example of this. Suppose you wanted to create a list where each value was double its value in the original list: list.Select(i => i*2) where i => i*2 is equivalent to: Func<int,int> double = delegate(int x) { return x*2; } This is much simpler and clearer than creating a separate function. Further, the function you declare may not have meaning elsewhere (ie, outside the scope of your method). In C#, you can even reference to variables declared inside your method body -- which you cannot do with a non-nested function. Of course, you can also abuse nested functions... A: Nested methods also allow you to control scope of the caller as well as allowing you to access internally created members without them being exposed to other functions in a similar scope (i.e. inside of a class) A: Nested methods increase locality of your code which is a good thing as you don't have to pollute classes with small private methods used only in one place. A: Try this Pythonish pseudocode example for a glimpse at one use-case for this technique: def MyMethod(base): base = expensivePreparation(base) def MyInnerMethod(some_modifier): doSomethingCoolWith(base, some_modifier) return MyInnerMethod process = MyMethod(some_obj) process(arg1) process(arg2) A: Many useful answers here already, but here goes. inner classes: not! nice try, but too much make-work. Nested functions / procs are much quicker and to the point. King Java's [1] classes with one method [2] really suck, and nested functions (or procedures) circumvent such syntactic nonsense. functional decomposition: break a long routine into smaller ones, which are hidden from other places where they aren't used. Pascal supported this eons ago, and I'm pretty sure it wasn't a new invention even then (early 70s). closures: mentioned elsewhere, but useful. use local variables in the enclosing function to initialize the generated function, and return a customized function (or otherwise use the generated code) 1: http://steve-yegge.blogspot.com/2006/03/execution-in-kingdom-of-nouns.html "King Java" 2: http://en.wikipedia.org/wiki/Function_object#In_Java "Function object / functor" A: Along the above mentioned points, these can be treated as Higher order functions, functions that themselves take or return functions. Check out this example: static void Main(string[] args) { Func<int, int> NestedMethod = delegate(int x) { Console.WriteLine("In nested method. Value of x is {0}.", x); return x; }; HigerOrderTest(NestedMethod)(); } private static Action HigerOrderTest(Func<int, int> highFunction) { var sam = highFunction(3); Action DoIt =() => { Console.WriteLine("Output is {0}.", sam); }; return DoIt; } A: You are perhaps already aware of the usefulness of passing functions to other functions, for example, providing a sort() routine with a comparison function, and the obvious examples of map() and filter() and so on. Likewise, it is often useful to receive functions as a result from another function. The most common usage is for closures, but currying is also common. A central benefit of a closure is being able to create a new function at runtime that contains all the temporal information required for its execution at that point in time. In language implementations that don't support closures, such state management is usually done, arguably less elegantly, via classes: object instance variables are set, and then later read when needed. Closures provide a means to bundle the state with the action. So as a basic point of understanding, it may help to think of nested functions as a way to write on-the-spot functions to perform very specific actions where the details of those actions will be known at runtime, but you only want to execute that action at some later time. There are other things that can be done with nested functions, but you have to start somewhere.
Nested Methods? Why are they useful?
So I'm just learning some new stuff in C# & Python. Turns out both lanuages support nested methods (C# sort of does). Python: def MyMethod(): print 'Hello from a method.' def MyInnerMethod(): print 'Hello from a nested method.' MyInnerMethod() C# (using new features in .NET 3.5):* static void Main() { Console.WriteLine("Hello from main."); Func<int, int> NestedMethod = (x) => { Console.WriteLine("In nested method. Value of x is {0}.", x); return x; }; int result = NestedMethod(3); } So why are nested methods so important? What makes them useful? **The C# code has not been tested. Feel free to edit if it doesn't compile.*
[ "First, realize I cannot give you a complete list. If you were to ask \"why are screwdrivers useful?\", I would would talk about screws and paint can lids but would miss their value in termite inspection. When you ask, \"Why are nested functions useful?\", I can tell you about scoping, closures, and entry points.\nFirst, nesting can be an alternative to classes. I recently wrote some rendering code that took a file name for specialized mark-up code and returned a bitmap. This naturally lead to functions named grab_markup_from_filename() and render_text_onto_image() and others. The cleanest organization was one entry point named generate_png_from_markup_filename(). The entry point did its job, using nested functions to accomplish its task. There was no need for a class, because there was no object with state. My alternative was to create a module with private methods hiding my helpers, but it would be messier.\ndef generate_png_from_markup_filename(filename):\n def grab_markup_from_filename():\n ... \n ... # code that calls grab_markup_from_filename() to make the image\n return image\n\nSecond, I use nesting for closures. The most common example is for creating decorators. The trick is that I return a reference to an inner function, so that inner function and the outer parameter value are not garbage collected.\ndef verify_admin(function_to_call):\n def call_on_verify_admin(*args, **kwargs):\n if is_admin(global.session.user):\n return function_to_call(*args, **kwargs)\n else:\n throw Exception(\"Not Admin\")\n return call_on_verify_admin # the return value of verify_admin()\n\nuse it this way:\n def update_price(item, price):\n database.lookup(item).set_field('price', price)\n update_price = verify_admin(update_price)\n\nor, more concisely:\n @verify_admin\n def update_price(item, price):\n database.lookup(item).set_field('price', price)\n\nAnd yes, it should be hard to trace. Remember that \"def\" is just another statement.\nSo, here are two places nested classes are helpful. There are more. It is a tool.\n", "Nested methods are useful because there are many cases where you want to pass behaviour around, rather than just data. In many instances, it is clearer and easier to follow, in addition to being easier and faster to write, to just define that behaviour in the body of your method, where you are going to use it.\nIn .NET, LINQ is a great example of this. Suppose you wanted to create a list where each value was double its value in the original list: \nlist.Select(i => i*2)\n\nwhere i => i*2 is equivalent to:\nFunc<int,int> double = delegate(int x) { return x*2; }\n\nThis is much simpler and clearer than creating a separate function. \nFurther, the function you declare may not have meaning elsewhere (ie, outside the scope of your method). In C#, you can even reference to variables declared inside your method body -- which you cannot do with a non-nested function.\nOf course, you can also abuse nested functions...\n", "Nested methods also allow you to control scope of the caller as well as allowing you to access internally created members without them being exposed to other functions in a similar scope (i.e. inside of a class)\n", "Nested methods increase locality of your code which is a good thing as you don't have to pollute classes with small private methods used only in one place.\n", "Try this Pythonish pseudocode example for a glimpse at one use-case for this technique:\ndef MyMethod(base):\n base = expensivePreparation(base)\n def MyInnerMethod(some_modifier):\n doSomethingCoolWith(base, some_modifier)\n\n return MyInnerMethod\n\nprocess = MyMethod(some_obj)\nprocess(arg1)\nprocess(arg2)\n\n", "Many useful answers here already, but here goes.\n\ninner classes: not! nice try, but too much make-work. Nested functions / procs are much quicker and to the point. King Java's [1] classes with one method [2] really suck, and nested functions (or procedures) circumvent such syntactic nonsense.\nfunctional decomposition: break a long routine into smaller ones, which are hidden from other places where they aren't used. Pascal supported this eons ago, and I'm pretty sure it wasn't a new invention even then (early 70s).\nclosures: mentioned elsewhere, but useful. use local variables in the enclosing function to initialize the generated function, and return a customized function (or otherwise use the generated code)\n\n1: http://steve-yegge.blogspot.com/2006/03/execution-in-kingdom-of-nouns.html \"King Java\"\n2: http://en.wikipedia.org/wiki/Function_object#In_Java \"Function object / functor\"\n", "Along the above mentioned points, these can be treated as Higher order functions, functions that themselves take or return functions.\nCheck out this example:\n static void Main(string[] args)\n {\n\n Func<int, int> NestedMethod = delegate(int x) \n { Console.WriteLine(\"In nested method. Value of x is {0}.\", x); \n return x; \n };\n\n HigerOrderTest(NestedMethod)();\n }\n\n private static Action HigerOrderTest(Func<int, int> highFunction)\n {\n var sam = highFunction(3);\n\n Action DoIt =() =>\n {\n Console.WriteLine(\"Output is {0}.\", sam); \n };\n return DoIt;\n }\n\n", "You are perhaps already aware of the usefulness of passing functions to other functions, for example, providing a sort() routine with a comparison function, and the obvious examples of map() and filter() and so on. Likewise, it is often useful to receive functions as a result from another function. The most common usage is for closures, but currying is also common. \nA central benefit of a closure is being able to create a new function at runtime that contains all the temporal information required for its execution at that point in time. In language implementations that don't support closures, such state management is usually done, arguably less elegantly, via classes: object instance variables are set, and then later read when needed. Closures provide a means to bundle the state with the action.\nSo as a basic point of understanding, it may help to think of nested functions as a way to write on-the-spot functions to perform very specific actions where the details of those actions will be known at runtime, but you only want to execute that action at some later time.\nThere are other things that can be done with nested functions, but you have to start somewhere.\n" ]
[ 17, 7, 5, 5, 3, 1, 1, 0 ]
[]
[]
[ "c#", "python" ]
stackoverflow_0001919372_c#_python.txt
Q: Storing times in Python - Best format? When storing a time in Python (in my case in ZODB, but applies to any DB), what format (epoch, datetime etc) do you use and why? A: The datetime module has the standard types for modern Python handling of dates and times, and I use it because I like standards (I also think it's well designed); I typically also have timezone information via pytz. Most DBs have their own standard way of storing dates and times, of course, but modern Python adapters to/from the DBs typically support datetime (another good reason to use it;-) on the Python side of things -- for example that's what I get with Google App Engine's storage, Python's own embedded SQLite, and so on. A: If the database has a native date-time format, I try to use that even if it involves encoding and decoding. Even if this is not 100% standard such as SQLITE, I would still use the date and time adaptors described near the bottom of the SQLITE3 help page. In all other cases I would use ISO 8601 format unless it was a Python object database that stores some kind of binary encoding of the object. ISO 8601 format is sortable and that is often required in databases for indexing. Also, it is unambiguous so you know that 2009-01-12 was in January, not in December. The people who change the position of month and day, always put the year last, so putting it first stops people from automatically assuming an incorrect format. Of course, you can reformat however you want for display and input in your applications but data in databases is often viewed with other tools, not your application. A: Seconds since epoch is the most compact and portable format for storing time data. Native DATETIME format in MySQL, for example, takes 8 bytes instead of 4 for TIMESTAMP (seconds since epoch). You'd also avoid timezone issues if you need to get the time from clients in multiple geographic locations. Logical operations (for sorting, etc.) are also fastest on integers.
Storing times in Python - Best format?
When storing a time in Python (in my case in ZODB, but applies to any DB), what format (epoch, datetime etc) do you use and why?
[ "The datetime module has the standard types for modern Python handling of dates and times, and I use it because I like standards (I also think it's well designed); I typically also have timezone information via pytz.\nMost DBs have their own standard way of storing dates and times, of course, but modern Python adapters to/from the DBs typically support datetime (another good reason to use it;-) on the Python side of things -- for example that's what I get with Google App Engine's storage, Python's own embedded SQLite, and so on.\n", "If the database has a native date-time format, I try to use that even if it involves encoding and decoding. Even if this is not 100% standard such as SQLITE, I would still use the date and time adaptors described near the bottom of the SQLITE3 help page.\nIn all other cases I would use ISO 8601 format unless it was a Python object database that stores some kind of binary encoding of the object.\nISO 8601 format is sortable and that is often required in databases for indexing. Also, it is unambiguous so you know that 2009-01-12 was in January, not in December. The people who change the position of month and day, always put the year last, so putting it first stops people from automatically assuming an incorrect format.\nOf course, you can reformat however you want for display and input in your applications but data in databases is often viewed with other tools, not your application.\n", "Seconds since epoch is the most compact and portable format for storing time data. Native DATETIME format in MySQL, for example, takes 8 bytes instead of 4 for TIMESTAMP (seconds since epoch). You'd also avoid timezone issues if you need to get the time from clients in multiple geographic locations. Logical operations (for sorting, etc.) are also fastest on integers.\n" ]
[ 5, 5, 0 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0001908670_datetime_python.txt
Q: What's a better way to handle this in Python Simple problem, I have it solved .. but python has a million ways to solve the same problem. I don't want the most terse solution, I just want one that makes more sense than the following: # sql query happens above, returns multiple rows rows = cursor.fetchall() cursor.close() cntdict = {} for row in rows: a, b, c = row[0], row[1], row[2] cntdict = { a : { "b":b, "c":c } } print dict(cntdict) note, a is always unique above. I want a dictionary created from the result set. Later on in my script I need to reference the values in the dictionary for each row that occurred. I'm trying to index the dictionary by making the key the value from the var a. that should point to another dictionary with two more key/value pairs that describe a... unless there's a smarter/shorter way to do it. A: You can do the same thing with a generator expression and the dictionary constructor: dict((row[0], {"b": row[1], "c": row[2]}) for row in rows) And here is the code in action: >>> rows = [[1, 2, 3], [4, 5, 6]] >>> dict((row[0], {"b": row[1], "c": row[2]}) for row in rows) {1: {'c': 3, 'b': 2}, 4: {'c': 6, 'b': 5}} I can't remember if MySQLdb returns rows as list of tuples, if that is the case then you can do this: dict((a, {"b": b, "c": c}) for a, b, c in rows) A: As Nadia alluded to, tuple expansion is really handy when working with query results. Her dict() expressions are really nice in this case, though for other queries when you need to do something different with the results just use tuple expansion in the for loop: for a, b, c in rows: # do something
What's a better way to handle this in Python
Simple problem, I have it solved .. but python has a million ways to solve the same problem. I don't want the most terse solution, I just want one that makes more sense than the following: # sql query happens above, returns multiple rows rows = cursor.fetchall() cursor.close() cntdict = {} for row in rows: a, b, c = row[0], row[1], row[2] cntdict = { a : { "b":b, "c":c } } print dict(cntdict) note, a is always unique above. I want a dictionary created from the result set. Later on in my script I need to reference the values in the dictionary for each row that occurred. I'm trying to index the dictionary by making the key the value from the var a. that should point to another dictionary with two more key/value pairs that describe a... unless there's a smarter/shorter way to do it.
[ "You can do the same thing with a generator expression and the dictionary constructor:\ndict((row[0], {\"b\": row[1], \"c\": row[2]}) for row in rows)\n\nAnd here is the code in action:\n>>> rows = [[1, 2, 3], [4, 5, 6]]\n>>> dict((row[0], {\"b\": row[1], \"c\": row[2]}) for row in rows)\n{1: {'c': 3, 'b': 2}, 4: {'c': 6, 'b': 5}}\n\nI can't remember if MySQLdb returns rows as list of tuples, if that is the case then you can do this:\ndict((a, {\"b\": b, \"c\": c}) for a, b, c in rows)\n\n", "As Nadia alluded to, tuple expansion is really handy when working with query results. Her dict() expressions are really nice in this case, though for other queries when you need to do something different with the results just use tuple expansion in the for loop:\nfor a, b, c in rows:\n # do something\n\n" ]
[ 12, 0 ]
[ "You might want to look into using an ORM to abstract your database. I can't tell for certain from such a short snippet, but it looks like your data might work well with an ORM if you are just going to build a dict out of it anyway.\nMy three favorite ORMs: the one in Django (easy to use, works best with data that is regular), SQLAlchemy (best choice if your database has a complex schema), and Autumn (small and simple, ideal for use with SQLite).\n" ]
[ -2 ]
[ "python" ]
stackoverflow_0001918851_python.txt
Q: TinyMCE Spellchecker in Pylons I've been trying to get the TinyMCE spellchecker working with my Pylons app. My first problem is actually capturing the post data in the first place. Firebug tells me that the following is being sent: {"id":"c0","method":"checkWords","params":["en",["Lorem","ipsum","dolor","sit","amet","consectetur","adipisicing","elit","sed","do","eiusmod","tempor","incididunt","ut","labore","et","dolore","magna","aliqua","Ut","enim","ad","minim","veniam","quis","nostrud","exercitation","ullamco","laboris","nisi","aliquip","ex","ea","commodo","consequat","Duis","aute","irure","in","reprehenderit","voluptate","velit","esse","cillum","eu","fugiat","nulla","pariatur","Excepteur","sint","occaecat","cupidatat","non","proident","sunt","culpa","qui","officia","deserunt","mollit","anim","id","est","laborum"]]} Which looks like a string of JSON. That's fine, I can handle that but it's not coming up in my request.params dict anywhere. Does anyone have any experience in getting this to work with Pylons or some things for me to try? I know spellchecker was intended to work with a PHP backend but that shouldn't throw up any significant barriers, should it? Furthermore can anyone provide any insight as to what the response is supposed to look like? The documentation for this plugin seems to be woefully incomplete. A: That's not really an answer to your question but I hope it will help: You maybe interested to look at django-tinymce as a source of inspiration. The spellchecker is based on PyEnchant
TinyMCE Spellchecker in Pylons
I've been trying to get the TinyMCE spellchecker working with my Pylons app. My first problem is actually capturing the post data in the first place. Firebug tells me that the following is being sent: {"id":"c0","method":"checkWords","params":["en",["Lorem","ipsum","dolor","sit","amet","consectetur","adipisicing","elit","sed","do","eiusmod","tempor","incididunt","ut","labore","et","dolore","magna","aliqua","Ut","enim","ad","minim","veniam","quis","nostrud","exercitation","ullamco","laboris","nisi","aliquip","ex","ea","commodo","consequat","Duis","aute","irure","in","reprehenderit","voluptate","velit","esse","cillum","eu","fugiat","nulla","pariatur","Excepteur","sint","occaecat","cupidatat","non","proident","sunt","culpa","qui","officia","deserunt","mollit","anim","id","est","laborum"]]} Which looks like a string of JSON. That's fine, I can handle that but it's not coming up in my request.params dict anywhere. Does anyone have any experience in getting this to work with Pylons or some things for me to try? I know spellchecker was intended to work with a PHP backend but that shouldn't throw up any significant barriers, should it? Furthermore can anyone provide any insight as to what the response is supposed to look like? The documentation for this plugin seems to be woefully incomplete.
[ "That's not really an answer to your question but I hope it will help:\nYou maybe interested to look at django-tinymce as a source of inspiration. The spellchecker is based on PyEnchant\n" ]
[ 1 ]
[]
[]
[ "pyenchant", "pylons", "python", "spell_checking", "tinymce" ]
stackoverflow_0001920162_pyenchant_pylons_python_spell_checking_tinymce.txt
Q: Fill list with objects and sort (Newbie) I'm new to Python, so please forgive me when using wrong terms :) I'd like to have a list of several "objects", each of them having the same numeric attributes (A, B, C). This list should then be sorted by the value of attribute A. In Java I'd define a Class with my attributes as members, implement Sortable to compare A, put them all in some sort of List and let Collections.sort sort my list. The result should "look" like that: A B C 1 2 3 1 2 4 2 5 1 3 1 1 What is the best way to do something like that in Python? A: class myclass(object): def __init__(self, a, b, c): self.a = a self.b = b self.c = c def __repr__(self): return "(a=%s, b=%s, c=%s)" % (self.a, self.b, self.c) >>> obj1 = myclass(1, 2, 3) >>> obj2 = myclass(1, 2, 4) >>> obj3 = myclass(2, 5, 1) >>> obj4 = myclass(3, 1, 1) >>> print sorted([obj1, obj2, obj3, obj4], key=lambda o: o.a) [(a=1, b=2, c=3), (a=1, b=2, c=4), (a=2, b=5, c=1), (a=3, b=1, c=1)] A: Sorry, If I took your question wrong way. I don't get it very well. So, I will assume like you want to sort by column Lets say x is 2 dimensional array >>> x=[[1, 2, 3], [1, 2, 4], [2, 5, 1], [3, 1, 1]] >>> x [[1, 2, 3], [1, 2, 4], [2, 5, 1], [3, 1, 1]] here is one way to do sorting by each column, using itemgetter from operator import itemgetter >>> sorted(x,key=itemgetter(0)) [[1, 2, 4], [1, 2, 3], [2, 5, 1], [3, 1, 1]] >>> sorted(x,key=itemgetter(1)) [[3, 1, 1], [1, 2, 4], [1, 2, 3], [2, 5, 1]] >>> sorted(x,key=itemgetter(2)) [[3, 1, 1], [2, 5, 1], [1, 2, 3], [1, 2, 4]] If you want in-place sorting, please do like x.sort(key=itemgetter(0)) A: Consider using a namedtuple to create your objects. (Have a look at is-there-a-tuple-data-structure-in-python.) collections.namedtuple(typename, field_names[, verbose]) Returns a new tuple subclass named typename. The new subclass is used to create tuple-like objects that have fields accessible by attribute lookup as well as being indexable and iterable. Instances of the subclass also have a helpful docstring (with typename and field_names) and a helpful repr() method which lists the tuple contents in a name=value format. A simple interactive session with A B C field names. Sorting is straightforward with key=lambda o:o.A: >>> import collections >>> mob=collections.namedtuple('myobj',('A','B','C')) >>> mlist = [mob(3,1,1), mob(1,2,3), mob(1,2,4), mob(2,5,1)] >>> mlist [myobj(A=3, B=1, C=1), myobj(A=1, B=2, C=3), myobj(A=1, B=2, C=4), myobj(A=2, B=5, C=1)] >>> for x in sorted(mlist,key=lambda o:o.A): ... print x ... myobj(A=1, B=2, C=3) myobj(A=1, B=2, C=4) myobj(A=2, B=5, C=1) myobj(A=3, B=1, C=1) >>> A: List = [(3,1,1),(1,2,4),(2,5,1),(1,2,3)] sorted(List) Update: The heart of the answer is actually the sorted built-in. I just put it on two lines to allow for incremental inspection that (a) the data structure chosen is a list of tuples, and (b) the sorting is done by sorted. As a commenter pointed out sorted() will in one go sort by A, then B, then C (whether this is required or not). Other answers make a good point about adding a key-picking function to the call to sorted(), to nail down which element will be used in the comparison. Again, whether this is advantageous or not is for the OP to judge. I wanted to offer a minimal solution. Update1: I shuffled the elements of the list around, so it appeals more to sorting :). A: You can give a comparison function as first argument of the sort of a list See the code below: class Foo: def __init__(self, a, b=0, c=0): self.a = a self.b = b self.c = c def __repr__(self): return "%d %d %d" % (self.a, self.b, self.c) foos = [Foo(2, 5, 1), Foo(1, 2, 4), Foo(3, 1, 1), Foo(1, 2, 3)] def cmp_a(f1, f2): if f1.a == f2.a: return 0 elif f1.a < f2.a: return -1 else: return 1 foos.sort(cmp_a) for f in foos: print f
Fill list with objects and sort (Newbie)
I'm new to Python, so please forgive me when using wrong terms :) I'd like to have a list of several "objects", each of them having the same numeric attributes (A, B, C). This list should then be sorted by the value of attribute A. In Java I'd define a Class with my attributes as members, implement Sortable to compare A, put them all in some sort of List and let Collections.sort sort my list. The result should "look" like that: A B C 1 2 3 1 2 4 2 5 1 3 1 1 What is the best way to do something like that in Python?
[ "class myclass(object):\n def __init__(self, a, b, c):\n self.a = a\n self.b = b\n self.c = c\n\n def __repr__(self):\n return \"(a=%s, b=%s, c=%s)\" % (self.a, self.b, self.c)\n\n>>> obj1 = myclass(1, 2, 3)\n>>> obj2 = myclass(1, 2, 4)\n>>> obj3 = myclass(2, 5, 1)\n>>> obj4 = myclass(3, 1, 1)\n\n>>> print sorted([obj1, obj2, obj3, obj4], key=lambda o: o.a)\n[(a=1, b=2, c=3), (a=1, b=2, c=4), (a=2, b=5, c=1), (a=3, b=1, c=1)]\n\n", "Sorry, If I took your question wrong way. I don't get it very well.\nSo, I will assume like you want to sort by column\nLets say x is 2 dimensional array\n>>> x=[[1, 2, 3], [1, 2, 4], [2, 5, 1], [3, 1, 1]]\n>>> x\n[[1, 2, 3], [1, 2, 4], [2, 5, 1], [3, 1, 1]]\n\nhere is one way to do sorting by each column, using itemgetter\nfrom operator import itemgetter\n\n>>> sorted(x,key=itemgetter(0))\n[[1, 2, 4], [1, 2, 3], [2, 5, 1], [3, 1, 1]]\n>>> sorted(x,key=itemgetter(1))\n[[3, 1, 1], [1, 2, 4], [1, 2, 3], [2, 5, 1]]\n>>> sorted(x,key=itemgetter(2))\n[[3, 1, 1], [2, 5, 1], [1, 2, 3], [1, 2, 4]]\n\nIf you want in-place sorting, please do like x.sort(key=itemgetter(0))\n", "Consider using a namedtuple to create your objects. (Have a look at is-there-a-tuple-data-structure-in-python.)\n\ncollections.namedtuple(typename, field_names[, verbose])\nReturns a new tuple subclass named typename. The new subclass is used to create tuple-like objects that have fields accessible by attribute lookup as well as being indexable and iterable. Instances of the subclass also have a helpful docstring (with typename and field_names) and a helpful repr() method which lists the tuple contents in a name=value format.\n\nA simple interactive session with A B C field names. Sorting is straightforward with\nkey=lambda o:o.A:\n>>> import collections\n>>> mob=collections.namedtuple('myobj',('A','B','C'))\n>>> mlist = [mob(3,1,1), mob(1,2,3), mob(1,2,4), mob(2,5,1)]\n>>> mlist\n[myobj(A=3, B=1, C=1), myobj(A=1, B=2, C=3), myobj(A=1, B=2, C=4), myobj(A=2, B=5, C=1)]\n>>> for x in sorted(mlist,key=lambda o:o.A):\n... print x\n... \nmyobj(A=1, B=2, C=3)\nmyobj(A=1, B=2, C=4)\nmyobj(A=2, B=5, C=1)\nmyobj(A=3, B=1, C=1)\n>>> \n\n", "List = [(3,1,1),(1,2,4),(2,5,1),(1,2,3)]\nsorted(List)\n\nUpdate: The heart of the answer is actually the sorted built-in. I just put it on two lines to allow for incremental inspection that (a) the data structure chosen is a list of tuples, and (b) the sorting is done by sorted. As a commenter pointed out sorted() will in one go sort by A, then B, then C (whether this is required or not). Other answers make a good point about adding a key-picking function to the call to sorted(), to nail down which element will be used in the comparison. Again, whether this is advantageous or not is for the OP to judge. I wanted to offer a minimal solution.\nUpdate1: I shuffled the elements of the list around, so it appeals more to sorting :).\n", "You can give a comparison function as first argument of the sort of a list See the code below:\nclass Foo:\n def __init__(self, a, b=0, c=0):\n self.a = a\n self.b = b\n self.c = c\n\n def __repr__(self):\n return \"%d %d %d\" % (self.a, self.b, self.c)\n\n\nfoos = [Foo(2, 5, 1), Foo(1, 2, 4), Foo(3, 1, 1), Foo(1, 2, 3)]\n\ndef cmp_a(f1, f2): \n if f1.a == f2.a:\n return 0\n elif f1.a < f2.a:\n return -1\n else:\n return 1\n\nfoos.sort(cmp_a)\n\nfor f in foos:\n print f\n\n" ]
[ 6, 4, 3, 2, 2 ]
[]
[]
[ "list", "object", "python", "sorting" ]
stackoverflow_0001920315_list_object_python_sorting.txt
Q: python write CD/DVD iso file I'm making a cross-platform (Windows and OS X) with wxPython that will be compiled to exe later. Is it possible for me to create ISO files for CDs or DVDs in Python to burn a data disc with? Thanks, Chris A: Following 'do not reinvent the wheel' I would try using mkisofs (part of cdrtools) (although originating on Linux, I think there are windows builds floating around the net).
python write CD/DVD iso file
I'm making a cross-platform (Windows and OS X) with wxPython that will be compiled to exe later. Is it possible for me to create ISO files for CDs or DVDs in Python to burn a data disc with? Thanks, Chris
[ "Following 'do not reinvent the wheel' I would try using mkisofs (part of cdrtools) (although originating on Linux, I think there are windows builds floating around the net).\n" ]
[ 1 ]
[]
[]
[ "file", "iso", "python", "system" ]
stackoverflow_0001920246_file_iso_python_system.txt
Q: Is it possible to access an xcf active memory server with python? I'm playing around with the XCF active memory server. Is there a python library to access the contents of the active memory server? Related: How to write data to the ActiveMemory Server used in the XCF system? A: According to their documentation, the answer appears to be "yes". A: According to one of the developers there is an outdated version of a python API for publish and subscribe over XCF. This API is not capable of contacting an active memory server.
Is it possible to access an xcf active memory server with python?
I'm playing around with the XCF active memory server. Is there a python library to access the contents of the active memory server? Related: How to write data to the ActiveMemory Server used in the XCF system?
[ "According to their documentation, the answer appears to be \"yes\".\n", "According to one of the developers there is an outdated version of a python API for publish and subscribe over XCF. This API is not capable of contacting an active memory server. \n" ]
[ 0, 0 ]
[]
[]
[ "active_memory", "python", "xcf" ]
stackoverflow_0001907102_active_memory_python_xcf.txt
Q: Code bacteria: evolving mathematical behavior It would not be my intention to put a link on my blog, but I don't have any other method to clarify what I really mean. The article is quite long, and it's in three parts (1,2,3), but if you are curious, it's worth the reading. A long time ago (5 years, at least) I programmed a python program which generated "mathematical bacteria". These bacteria are python objects with a simple opcode-based genetic code. You can feed them with a number and they return a number, according to the execution of their code. I generate their genetic codes at random, and apply an environmental selection to those objects producing a result similar to a predefined expected value. Then I let them duplicate, introduce mutations, and evolve them. The result is quite interesting, as their genetic code basically learns how to solve simple equations, even for values different for the training dataset. Now, this thing is just a toy. I had time to waste and I wanted to satisfy my curiosity. however, I assume that something, in terms of research, has been made... I am reinventing the wheel here, I hope. Are you aware of more serious attempts at creating in-silico bacteria like the one I programmed? Please note that this is not really "genetic algorithms". Genetic algorithms is when you use evolution/selection to improve a vector of parameters against a given scoring function. This is kind of different. I optimize the code, not the parameters, against a given scoring function. A: If you are optimising the code, perhaps you are engaged in genetic programming? A: The free utility Eureqa is similar in the sense that in can create fitting symbolic functions (much more complicated than simple linear regression, etc.) based on multivariate input data. But, it uses GA to come up with the functions, so I'm not sure if that's exactly what you had in mind. See also the "Download Your Own Robot Scientist" article on Wired for a breakdown of the general idea of how it works. A: Nice article, I would say you're talking about "gene expression programming" rather than "genetic programming", btw. A: Are you familiar with Core Wars? I remember there were a number of code evolvers written for the game which had some success. For example, MicroGP++ is an assembly code generator that can be applied to the Core Wars assembly language (as well as to real problems!).
Code bacteria: evolving mathematical behavior
It would not be my intention to put a link on my blog, but I don't have any other method to clarify what I really mean. The article is quite long, and it's in three parts (1,2,3), but if you are curious, it's worth the reading. A long time ago (5 years, at least) I programmed a python program which generated "mathematical bacteria". These bacteria are python objects with a simple opcode-based genetic code. You can feed them with a number and they return a number, according to the execution of their code. I generate their genetic codes at random, and apply an environmental selection to those objects producing a result similar to a predefined expected value. Then I let them duplicate, introduce mutations, and evolve them. The result is quite interesting, as their genetic code basically learns how to solve simple equations, even for values different for the training dataset. Now, this thing is just a toy. I had time to waste and I wanted to satisfy my curiosity. however, I assume that something, in terms of research, has been made... I am reinventing the wheel here, I hope. Are you aware of more serious attempts at creating in-silico bacteria like the one I programmed? Please note that this is not really "genetic algorithms". Genetic algorithms is when you use evolution/selection to improve a vector of parameters against a given scoring function. This is kind of different. I optimize the code, not the parameters, against a given scoring function.
[ "If you are optimising the code, perhaps you are engaged in genetic programming?\n", "The free utility Eureqa is similar in the sense that in can create fitting symbolic functions (much more complicated than simple linear regression, etc.) based on multivariate input data. But, it uses GA to come up with the functions, so I'm not sure if that's exactly what you had in mind.\nSee also the \"Download Your Own Robot Scientist\" article on Wired for a breakdown of the general idea of how it works.\n", "Nice article,\nI would say you're talking about \"gene expression programming\" rather than \"genetic programming\", btw.\n", "Are you familiar with Core Wars? I remember there were a number of code evolvers written for the game which had some success. For example, MicroGP++ is an assembly code generator that can be applied to the Core Wars assembly language (as well as to real problems!).\n" ]
[ 10, 2, 2, 1 ]
[]
[]
[ "evolutionary_algorithm", "genetic_programming", "python" ]
stackoverflow_0001889810_evolutionary_algorithm_genetic_programming_python.txt
Q: What does Python's GIL have to do with the garbage collector? I just saw this section of Unladen Swallow's documentation come up on Hacker News. Basically, it's the Google engineers saying that they're not optimistic about removing the GIL. However, it seems as though there is discussion about the garbage collector interspersed with this talk about the GIL. Could someone explain the relation to me? A: The really short version is that currently python manages memory with a reference counting+a mark&sweep cycle collector scheme, optimized for latency (instead of throughput). This is all fine when there is only a single mutating thread, but in a multi-threaded system, you need to synchronize all the times you modify refcounts, or else you can have values "fall trough the cracks", and synchronization primitives are quite expensive on contemporary hardware. If refcounts weren't changed so often, this wouldn't be a problem, but pretty much every single operation you do in cpython can cause a refcount to change somewhere, so the options are either GIL, doing refcounts with some kind of synchronization (and literally spend almost all your time on the synch), or ditch the refcounting system for some kind of a real garbage collector. A: Tuna-Fish's answer basically covers it. If you want more details, there was a discussion about how the GIL could be removed without having too much of an effect on the reference counting here: http://mail.python.org/pipermail/python-ideas/2009-October/006264.html A: I just found another point of view on this subject here: http://renesd.blogspot.com/2009/12/python-gil-unladen-swallow-reference.html
What does Python's GIL have to do with the garbage collector?
I just saw this section of Unladen Swallow's documentation come up on Hacker News. Basically, it's the Google engineers saying that they're not optimistic about removing the GIL. However, it seems as though there is discussion about the garbage collector interspersed with this talk about the GIL. Could someone explain the relation to me?
[ "The really short version is that currently python manages memory with a reference counting+a mark&sweep cycle collector scheme, optimized for latency (instead of throughput). \nThis is all fine when there is only a single mutating thread, but in a multi-threaded system, you need to synchronize all the times you modify refcounts, or else you can have values \"fall trough the cracks\", and synchronization primitives are quite expensive on contemporary hardware. \nIf refcounts weren't changed so often, this wouldn't be a problem, but pretty much every single operation you do in cpython can cause a refcount to change somewhere, so the options are either GIL, doing refcounts with some kind of synchronization (and literally spend almost all your time on the synch), or ditch the refcounting system for some kind of a real garbage collector.\n", "Tuna-Fish's answer basically covers it. If you want more details, there was a discussion about how the GIL could be removed without having too much of an effect on the reference counting here: http://mail.python.org/pipermail/python-ideas/2009-October/006264.html\n", "I just found another point of view on this subject here: http://renesd.blogspot.com/2009/12/python-gil-unladen-swallow-reference.html\n" ]
[ 19, 1, 1 ]
[]
[]
[ "garbage_collection", "gil", "python", "unladen_swallow" ]
stackoverflow_0001914605_garbage_collection_gil_python_unladen_swallow.txt
Q: How do I get names of subdirectories of a directory purely in python? I dont want to use commands or any similar module that uses unix shell. Thanks in advance.. A: Use os.walk(): import os, os.path def walk_directories(src): for root, dirs, files in os.walk(src): for dir in dirs: print os.path.join(root, dir) walk_directories(r'c:\temp') A: If you want to do this recursively, going down a tree visiting all the directories, then you can use os.walk like this: for root, directories, files in os.walk("c:\\"): doSomething If you only want the subdirectories you can either call walk once: directories = os.walk("c:\\").next()[1] Or do some sort of filter like this (walk is more stylish/portable): filter(lambda x: os.path.isdir("c:\\"+ x), os.listdir("c:\\"))
How do I get names of subdirectories of a directory purely in python?
I dont want to use commands or any similar module that uses unix shell. Thanks in advance..
[ "Use os.walk():\nimport os, os.path\n\ndef walk_directories(src):\n for root, dirs, files in os.walk(src):\n for dir in dirs:\n print os.path.join(root, dir)\n\nwalk_directories(r'c:\\temp')\n\n", "If you want to do this recursively, going down a tree visiting all the directories, then you can use os.walk like this:\n for root, directories, files in os.walk(\"c:\\\\\"):\n doSomething\n\nIf you only want the subdirectories you can either call walk once:\n directories = os.walk(\"c:\\\\\").next()[1]\n\nOr do some sort of filter like this (walk is more stylish/portable):\n filter(lambda x: os.path.isdir(\"c:\\\\\"+ x), os.listdir(\"c:\\\\\"))\n\n" ]
[ 2, 0 ]
[]
[]
[ "python", "subdirectory" ]
stackoverflow_0001921623_python_subdirectory.txt
Q: Partial evaluation with pyparsing I need to be able to take a formula that uses the OpenDocument formula syntax, parse it into syntax that Python can understand, but without evaluating the variables, and then be able to evaluate the formula many times with changing valuables for the variables. Formulas can be user input, so pyparsing allows me to both effectively handle the formula syntax, and clean user input. There are a number of good examples of pyparsing available, but all the mathematical ones seem to assume that one evaluates everything in the current scope immediately. For context, I am working with a model of the industrial economy (life cycle assessment, or LCA), where these formulas represent the amount of material or energy exchanges between processes. The variable amount can be a function of several parameters, such as geographical location. THe chain of formula and variable references are stored in a directed acyclic graph, so that formulas can always be simply evaluated. Formulas are stored as strings in a database. My questions are: Is it possible to parse a formula such that the parsed evaluation can also be stored in the database (as a string to be evaled, or something else)? Are there alternatives to this approach? Bear in mind that the ideal solution is to parse/write once, and read many times. For example, partially parsing the formula, and then using the ast module, although I don't know how this could work with database storage. Any examples of a project or library similar to this that I could look over? I am not a programmer, just a student trying to finish his thesis while making an open-source LCA software model in my spare time. Is this approach too slow? I would like to be able to do substantial Monte Carlo runs, where each run could involve tens of thousands of formula evaluations (it is a big database). A: 1) Yes, it is possible to pickle the results from parsing your expression, and save that to a database. Then you can just fetch and unpickle the expression, rather than reparse the original again. 2) You can do a quick-and-dirty pass at this just using the compile and eval built-ins, as in the following interactive session: >>> y = compile("m*x+b","","eval") >>> m = 100 >>> x = 5 >>> b = 1 >>> eval(y) 501 Of course, this has the security pitfalls of any eval- or exec-based implementation, in that untrusted or malicious source strings can embed harmful system calls. But if this is your thesis and entirely within your scope of control, just don't do anything foolish. 3) You can get an online example of parsing an expression into a "evaluatable" data structure at the pyparsing wiki's Examples page. Check out simpleBool.py and evalArith.py especially. If you're feeling flush, order a back issue of the May,2008 issue of Python magazine, which has my article "Writing a Simple Interpreter/Compiler with Pyparsing" with a more detailed description of the methods used, plus a description of how pickling and unpickling the parsed results works. 4) The slow part will be the parsing, so you are on the right track in preserving these results in some intermediate and repeatably-evaluatable form. The eval part should be fairly snappy. The second slow part will be in fetching these pickled structures from your database. During your MC run, I would package a single function that takes the selection parameters for an expression, fetches from the database, and unpickles and returns the evaluatable expression. Then once you have this working, use a memoize decorator to cache these query-results pairs, so that any given expression only needs to be fetched/unpickled once. Good luck with your thesis!
Partial evaluation with pyparsing
I need to be able to take a formula that uses the OpenDocument formula syntax, parse it into syntax that Python can understand, but without evaluating the variables, and then be able to evaluate the formula many times with changing valuables for the variables. Formulas can be user input, so pyparsing allows me to both effectively handle the formula syntax, and clean user input. There are a number of good examples of pyparsing available, but all the mathematical ones seem to assume that one evaluates everything in the current scope immediately. For context, I am working with a model of the industrial economy (life cycle assessment, or LCA), where these formulas represent the amount of material or energy exchanges between processes. The variable amount can be a function of several parameters, such as geographical location. THe chain of formula and variable references are stored in a directed acyclic graph, so that formulas can always be simply evaluated. Formulas are stored as strings in a database. My questions are: Is it possible to parse a formula such that the parsed evaluation can also be stored in the database (as a string to be evaled, or something else)? Are there alternatives to this approach? Bear in mind that the ideal solution is to parse/write once, and read many times. For example, partially parsing the formula, and then using the ast module, although I don't know how this could work with database storage. Any examples of a project or library similar to this that I could look over? I am not a programmer, just a student trying to finish his thesis while making an open-source LCA software model in my spare time. Is this approach too slow? I would like to be able to do substantial Monte Carlo runs, where each run could involve tens of thousands of formula evaluations (it is a big database).
[ "1) Yes, it is possible to pickle the results from parsing your expression, and save that to a database. Then you can just fetch and unpickle the expression, rather than reparse the original again. \n2) You can do a quick-and-dirty pass at this just using the compile and eval built-ins, as in the following interactive session:\n>>> y = compile(\"m*x+b\",\"\",\"eval\")\n>>> m = 100\n>>> x = 5\n>>> b = 1\n>>> eval(y)\n501\n\nOf course, this has the security pitfalls of any eval- or exec-based implementation, in that untrusted or malicious source strings can embed harmful system calls. But if this is your thesis and entirely within your scope of control, just don't do anything foolish.\n3) You can get an online example of parsing an expression into a \"evaluatable\" data structure at the pyparsing wiki's Examples page. Check out simpleBool.py and evalArith.py especially. If you're feeling flush, order a back issue of the May,2008 issue of Python magazine, which has my article \"Writing a Simple Interpreter/Compiler with Pyparsing\" with a more detailed description of the methods used, plus a description of how pickling and unpickling the parsed results works.\n4) The slow part will be the parsing, so you are on the right track in preserving these results in some intermediate and repeatably-evaluatable form. The eval part should be fairly snappy. The second slow part will be in fetching these pickled structures from your database. During your MC run, I would package a single function that takes the selection parameters for an expression, fetches from the database, and unpickles and returns the evaluatable expression. Then once you have this working, use a memoize decorator to cache these query-results pairs, so that any given expression only needs to be fetched/unpickled once.\nGood luck with your thesis!\n" ]
[ 4 ]
[]
[]
[ "evaluation", "parsing", "pyparsing", "python" ]
stackoverflow_0001920588_evaluation_parsing_pyparsing_python.txt
Q: XML edit attributes I want to edit the attributes of an element in an XML file. The file looks like <Parameter name="Spec 2 Circumference/Length" type="real" mode="both"> <Value>0.0</Value> <Result>0.0</Result> </Parameter> I want to replace the value and Result attribute with some other value from a text file. Please suggest. Thanks in advance. A: An example using ElementTree. It will replace the Value elements text with some string; the procedure for the Result element is analogue and omitted here: #!/usr/bin/env python xml = """ <Parameter name="Spec 2 Circumference/Length" type="real" mode="both"> <Value>0.0</Value> <Result>0.0</Result> </Parameter> """ from elementtree.ElementTree import fromstring, tostring # read XML, here we read it from a String doc = fromstring(xml) for e in doc.findall('Value'): e.text = 'insert your string from your textfile here!' print tostring(doc) # will result in: # # <Parameter mode="both" name="Spec 2 Circumference/Length" type="real"> # <Value>insert your string from your textfile here!</Value> # <Result>0.0</Result> # </Parameter>
XML edit attributes
I want to edit the attributes of an element in an XML file. The file looks like <Parameter name="Spec 2 Circumference/Length" type="real" mode="both"> <Value>0.0</Value> <Result>0.0</Result> </Parameter> I want to replace the value and Result attribute with some other value from a text file. Please suggest. Thanks in advance.
[ "An example using ElementTree. It will replace the Value elements text with some string; the procedure for the Result element is analogue and omitted here:\n#!/usr/bin/env python\n\nxml = \"\"\"\n<Parameter name=\"Spec 2 Circumference/Length\" type=\"real\" mode=\"both\">\n <Value>0.0</Value> \n <Result>0.0</Result> \n</Parameter>\n\"\"\"\n\nfrom elementtree.ElementTree import fromstring, tostring\n\n# read XML, here we read it from a String\ndoc = fromstring(xml)\n\nfor e in doc.findall('Value'):\n e.text = 'insert your string from your textfile here!'\n\nprint tostring(doc)\n\n# will result in:\n#\n# <Parameter mode=\"both\" name=\"Spec 2 Circumference/Length\" type=\"real\">\n# <Value>insert your string from your textfile here!</Value> \n# <Result>0.0</Result> \n# </Parameter>\n\n" ]
[ 1 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0001921601_python_xml.txt
Q: Expressing an SConscript's Own Dependencies I have an SCons project set up as follows: Project/ SConstruct # "SConscript('stuff/SConscript', variant_dir = 'build') stuff/ SConscript # "import configuration" configuration/ __init__.py Thing.py When building, the SConscript is copied to the build directory, but the "configuration" module is not. Ordinarily, one would express a file dependency with the Depends() function (e.g. Depends(program, object_files)). In this case, though, the SConscript file is itself the "target" of the dependency. How do I express this in my SConscript? A: I have two workarounds for you. I call them workarounds because they don't express the dependency in the SConscript. Do the 'import configuration' from your SConstruct (you'll need to edit sys.path) In stuff/SConscript, add the source directory to sys.path: import sys sys.path += ['%s/stuff' % (Dir('#').abspath)] import configuration A: Firstly, do you really need dependence on your SCons script source files? How often do they change, and if they change is it really so onerous to require that your user does a clean build if they muck with the SConscript.py configuration file(s). If you do require this, are you currently not seeing this? I've found SCons to be rather good at knowing if and how the SConscript.py files have changed. Specifically, if you have any user defined builders with custom action python functions? For my EDA build flow which has scads of user-defined python functions which call the myriad of proprietary EDA tools, if I change any SConstruct.py file, all the results of my custom python builders are assumed to be invalid (must to my chagrin, often). FYI, I'm using release 1.2.0.d20090223.
Expressing an SConscript's Own Dependencies
I have an SCons project set up as follows: Project/ SConstruct # "SConscript('stuff/SConscript', variant_dir = 'build') stuff/ SConscript # "import configuration" configuration/ __init__.py Thing.py When building, the SConscript is copied to the build directory, but the "configuration" module is not. Ordinarily, one would express a file dependency with the Depends() function (e.g. Depends(program, object_files)). In this case, though, the SConscript file is itself the "target" of the dependency. How do I express this in my SConscript?
[ "I have two workarounds for you. I call them workarounds because they don't express the dependency in the SConscript. \n\nDo the 'import configuration' from your SConstruct (you'll need to edit sys.path)\nIn stuff/SConscript, add the source directory to sys.path:\n\n \n import sys\n sys.path += ['%s/stuff' % (Dir('#').abspath)]\n\n import configuration\n\n", "Firstly, do you really need dependence on your SCons script source files? How often do they change, and if they change is it really so onerous to require that your user does a clean build if they muck with the SConscript.py configuration file(s).\nIf you do require this, are you currently not seeing this? I've found SCons to be rather good at knowing if and how the SConscript.py files have changed. Specifically, if you have any user defined builders with custom action python functions? For my EDA build flow which has scads of user-defined python functions which call the myriad of proprietary EDA tools, if I change any SConstruct.py file, all the results of my custom python builders are assumed to be invalid (must to my chagrin, often). FYI, I'm using release 1.2.0.d20090223.\n" ]
[ 1, 0 ]
[]
[]
[ "import", "module", "python", "scons" ]
stackoverflow_0001916251_import_module_python_scons.txt
Q: bulkloader.py --dump without authentication Is there some way or using the bulkloader.py dump and restore functionality without authentication? I have tried using: - url: /remote_api script: $PYTHON_LIB/google/appengine/ext/remote_api/handler.py without the login-parameter, but login still seems to be required. I still get [ERROR ] Exception during authentication I struggled with this for 6 hours yesterday, without any solution. And yes, I have tried GAEBAR. It failed, however when it got to entities that contain up to 1MB (the maximum pr. entity) Blobs. So, I am looking to dump (and restore) for backup-purposes mainly. A: remote_api, which the bulkloader uses, is written to deliberately require authentication, even if you omit the relevant clause in app.yaml. You can override it if you really want, but it's an incredibly bad idea - it would allow any anonymous user to do practically anything they liked to your app!
bulkloader.py --dump without authentication
Is there some way or using the bulkloader.py dump and restore functionality without authentication? I have tried using: - url: /remote_api script: $PYTHON_LIB/google/appengine/ext/remote_api/handler.py without the login-parameter, but login still seems to be required. I still get [ERROR ] Exception during authentication I struggled with this for 6 hours yesterday, without any solution. And yes, I have tried GAEBAR. It failed, however when it got to entities that contain up to 1MB (the maximum pr. entity) Blobs. So, I am looking to dump (and restore) for backup-purposes mainly.
[ "remote_api, which the bulkloader uses, is written to deliberately require authentication, even if you omit the relevant clause in app.yaml. You can override it if you really want, but it's an incredibly bad idea - it would allow any anonymous user to do practically anything they liked to your app!\n" ]
[ 1 ]
[]
[]
[ "backup", "google_app_engine", "python" ]
stackoverflow_0001920936_backup_google_app_engine_python.txt
Q: nested regular expressions in python In perl I can do this: $number = qr/ zero | one | two | three | four | five | six | seven | eight | nine /ix; $foo = qr/ quantity: \s* $number /ix; My actual regular expression is many lines and does two-digit and ordinal numbers (e.g., "twenty-two", "forty-fourth" and "twelve are all complete matches), and I use it in several places. This expression compiles fast, but it is certainly non-trivial. I prefer to compile it once and then add it to other regular expressions, as Perl allows. Is there a way to nest regular expressions in this manner in Python? A: In python, you build regular expressions by passing a string to re.compile. You can "nest" regular expression by just doing regular string manipulation: #!/usr/bin/env python import re number = 'zero | one | two | three | four | five | six | seven | eight | nine' foo = re.compile(' quantity: \s* (%s) '%number,re.VERBOSE|re.IGNORECASE) teststr=' quantity: five ' print(foo.findall(teststr)) # ['five'] A: This is probably not quite the same. But you could do this: import re number = "(?:zero | one | two | three | four | five | six | seven | eight | nine)" foo = "quantity: \s* " + number bar = re.compile(foo, re.I | re.X)
nested regular expressions in python
In perl I can do this: $number = qr/ zero | one | two | three | four | five | six | seven | eight | nine /ix; $foo = qr/ quantity: \s* $number /ix; My actual regular expression is many lines and does two-digit and ordinal numbers (e.g., "twenty-two", "forty-fourth" and "twelve are all complete matches), and I use it in several places. This expression compiles fast, but it is certainly non-trivial. I prefer to compile it once and then add it to other regular expressions, as Perl allows. Is there a way to nest regular expressions in this manner in Python?
[ "In python, you build regular expressions by passing a string to re.compile. \nYou can \"nest\" regular expression by just doing regular string manipulation:\n#!/usr/bin/env python\nimport re\nnumber = 'zero | one | two | three | four | five | six | seven | eight | nine'\nfoo = re.compile(' quantity: \\s* (%s) '%number,re.VERBOSE|re.IGNORECASE)\nteststr=' quantity: five '\nprint(foo.findall(teststr))\n# ['five']\n\n", "This is probably not quite the same. But you could do this:\nimport re\nnumber = \"(?:zero | one | two | three | four | five | six | seven | eight | nine)\"\nfoo = \"quantity: \\s* \" + number\nbar = re.compile(foo, re.I | re.X)\n\n" ]
[ 6, 1 ]
[]
[]
[ "expression", "nested", "python" ]
stackoverflow_0001922261_expression_nested_python.txt
Q: The best solution for distribution website? Ok, I have a question from a "client" perspective. Let's say we are talking about website designed for distribution: products + their logistics info. Definitely less than a 2k rows, rarely changed but often accessed. Typical row with several columns will have to consist of a picture so it might make it a bit "heavy". I was proposed a websited in Django Framework coded in Python with Postgresql database. Is it efficient? Cost-efficient, for such a small purpose is it really needed? and is there a cheaper and also reliable solution? From what I know the porposed solution is efficient for a programmer - loads of features, flexibility, distinction between layers of code-content-graphics. It gives a chance to build rly complicated websites and databases - thus the cost of service is bigger. What i need to know is whether the porposed solution is suitable for such a small project and could not be easily replaced by less complicated languages/frameworks/dmbses like PHP with MySQL etc. Please help :] and sry for not editing the q in the first place A: "What i need to know is whether the porposed solution is suitable for such a small project and could not be easily replaced by less complicated languages/frameworks/dmbses like PHP with MySQL etc. " Yes. It's suitable. No. Nothing is "less complicated" than Django. PHP language may appear less complicated than Python, but you'll do more work to create the site. With Django, you define the model, define the non-administrative views and you're done. For simple sites this can take as little as 20 minutes. The built-in admin is more valuable than you can imagine. MySQL is not "less complicated" that PostgresSQL -- they're the same thing A: I would not comment about Django & Python. But a more simpler way to store images would be to store just the "path" (location in the directory) in the tables, and load the path in your application/framework. A: Website For small webservices you can use micro-frameworks like http://www.sinatrarb.com/ (which is written in ruby); you write simple and useful apps in a few dozens or hundreds of lines. Plug your database in via some object-relational mapper and you should have a working prototype within a few hours/days. PDF For PDF generation, there is some great ruby library by Gregory Brown called prawn ... Addendum A python/django solution isn't complicated/un-effective either ...
The best solution for distribution website?
Ok, I have a question from a "client" perspective. Let's say we are talking about website designed for distribution: products + their logistics info. Definitely less than a 2k rows, rarely changed but often accessed. Typical row with several columns will have to consist of a picture so it might make it a bit "heavy". I was proposed a websited in Django Framework coded in Python with Postgresql database. Is it efficient? Cost-efficient, for such a small purpose is it really needed? and is there a cheaper and also reliable solution? From what I know the porposed solution is efficient for a programmer - loads of features, flexibility, distinction between layers of code-content-graphics. It gives a chance to build rly complicated websites and databases - thus the cost of service is bigger. What i need to know is whether the porposed solution is suitable for such a small project and could not be easily replaced by less complicated languages/frameworks/dmbses like PHP with MySQL etc. Please help :] and sry for not editing the q in the first place
[ "\"What i need to know is whether the porposed solution is suitable for such a small project and could not be easily replaced by less complicated languages/frameworks/dmbses like PHP with MySQL etc.\n\"\nYes. It's suitable.\nNo. Nothing is \"less complicated\" than Django. PHP language may appear less complicated than Python, but you'll do more work to create the site. \nWith Django, you define the model, define the non-administrative views and you're done. For simple sites this can take as little as 20 minutes. The built-in admin is more valuable than you can imagine.\nMySQL is not \"less complicated\" that PostgresSQL -- they're the same thing\n", "I would not comment about Django & Python. But a more simpler way to store images would be to store just the \"path\" (location in the directory) in the tables, and load the path in your application/framework.\n", "Website For small webservices you can use micro-frameworks like http://www.sinatrarb.com/ (which is written in ruby); you write simple and useful apps in a few dozens or hundreds of lines. Plug your database in via some object-relational mapper and you should have a working prototype within a few hours/days.\nPDF For PDF generation, there is some great ruby library by Gregory Brown called prawn ...\nAddendum A python/django solution isn't complicated/un-effective either ...\n" ]
[ 2, 0, 0 ]
[]
[]
[ "django", "postgresql", "python" ]
stackoverflow_0001921559_django_postgresql_python.txt
Q: Parsing a datafile in python (2.5.2) I have a message definition file that looks like this struct1 { field="name" type="string" ignore="false"; field="id" type="int" enums=" 0="val1" 1="val2" "; } struct2 { field = "object" type="struct1"; ... } How can I parse this into a dictionary with keys 'struct1, struct2' and values should be a list of dictionaries, each corresponding to the respective line number so that i can do the following dict['struct1'][0]['type'] // Would return 'string' dict['struct1'][1]['type'] // Would return 'int' dict['struct1'][1]['enums']['0'] // Would return 'val1' dict['struct2'][0]['type'] // Would return 'struct1' and so on.. Also, I can change the format of the definition file and if any of you have suggestions on modifying the definition file format to make it easier to parse, please let me know. Thanks A: Use can use json as file format, it supports (in python lingo) dictionaries and lists. Since json support is native only for python 2.6 and higher, you'll need this library: http://pypi.python.org/pypi/simplejson/2.0.9 { "struct1" [ {"field" : "name", "type" : "string", "ignore" : false }, {"field" : "id", "type" : "int", "0" : "val1", "1" : "val2" } {"field" : "id", "type" : "int", "enums" : { "0": "val1", "1": "val2"}} ] "struct2" [ ... ] } python part (sketched, not tested): >>> import simplejson as json >>> d = json.loads(yourjsonstring) >>> d['struct1'][0]['field'] name >>> d['struct1'][2]['enums']['0'] val1 ... A: Use YAML instead. There is PyYAML library for python. It is heavily used by Google AppEngine. This is just a friendly suggestion :-) Example ( Mapping Scalars to Sequences ): american: - Boston Red Sox - Detroit Tigers - New York Yankees national: - New York Mets - Chicago Cubs - Atlanta Braves There is also JSON of course which has ample support on Python (but tends to hurt my fingers a bit more ;-) A: Might I recommend YAML? IMHO the syntax is more readable for data entry, and then you don't have to write and maintain a parser. Eschew XML -- it is good for marking up text, but not good for data entry since the text isn't human readable with all the duplicate tags everywhere. A: I would simply use Python for the message definition file format. Let your message definition file be a plain Python file: # file messages.py messages = dict( struct1=[ dict(field="name", type="string", ignore=False), dict(field="id", type="int", enums={0: "val1", 1: "val2"}), ], struct2=[ dict(field="object", type="struct1"), ] ) Your program can then import and use that data structure directly: # in your program from messages import messages print messages['struct1'][0]["type"] print messages['struct1'][1]['type'] print messages['struct1'][1]['enums'][0] print messages['struct2'][0]['type'] Using this approach, you let Python do the parsing for you. And you also gain a lot of possibilities. For instance, imagine you (for some strange reason) have a message structure with 1000 fields named "field_N". Using a conventional file format you would have to add 1000 lines of field definitions (unless you build some looping into your config file parser - you are then on your way to creating a programming language anyway). Using Python for this purpose, you could do something like: messages = dict( ... strange_msg=[dict(field="field_%d" % i) for i in range(1000)], ... ) BTW, on Python 2.6, using named tuples instead of dict is an option. Or use on of the numerous "Bunch" classes available (see the Python cookbook for a namedtuple for 2.5). EDIT: Below is code that reads message definition files as specified on the command line. It uses execfile instead of import. # file mainprogram.py def read_messages_from_file(filename): module_dict = {} execfile(filename, module_dict) return module_dict['messages'] if __name__ == "__main__": from pprint import pprint import sys for arg in sys.argv[1:]: messages = read_messages_from_file(arg) pprint(messages) Executing: $ python mainprogram.py messages1 messages2 messages3 will read and print the messages defined in each file. A: Pyparsing is a nice easy to use library. That what I would use. http://pyparsing.wikispaces.com/ A: Since you are at liberty to change the file format, you could change it to any of several formats that have Python libraries to read and write. For example, JSON, YAML, XML, or even the built-in ConfigParser. [struct1] field: name type: string ignore: false # etc.
Parsing a datafile in python (2.5.2)
I have a message definition file that looks like this struct1 { field="name" type="string" ignore="false"; field="id" type="int" enums=" 0="val1" 1="val2" "; } struct2 { field = "object" type="struct1"; ... } How can I parse this into a dictionary with keys 'struct1, struct2' and values should be a list of dictionaries, each corresponding to the respective line number so that i can do the following dict['struct1'][0]['type'] // Would return 'string' dict['struct1'][1]['type'] // Would return 'int' dict['struct1'][1]['enums']['0'] // Would return 'val1' dict['struct2'][0]['type'] // Would return 'struct1' and so on.. Also, I can change the format of the definition file and if any of you have suggestions on modifying the definition file format to make it easier to parse, please let me know. Thanks
[ "Use can use json as file format, it supports (in python lingo) dictionaries and lists. Since json support is native only for python 2.6 and higher, you'll need this library: http://pypi.python.org/pypi/simplejson/2.0.9\n{ \"struct1\" \n [\n {\"field\" : \"name\", \"type\" : \"string\", \"ignore\" : false },\n {\"field\" : \"id\", \"type\" : \"int\", \"0\" : \"val1\", \"1\" : \"val2\" }\n {\"field\" : \"id\", \"type\" : \"int\", \"enums\" : { \"0\": \"val1\", \"1\": \"val2\"}}\n ]\n \"struct2\"\n [ ... ]\n}\n\npython part (sketched, not tested):\n>>> import simplejson as json\n>>> d = json.loads(yourjsonstring)\n>>> d['struct1'][0]['field']\nname\n>>> d['struct1'][2]['enums']['0']\nval1\n...\n\n", "Use YAML instead. There is PyYAML library for python. It is heavily used by Google AppEngine. \nThis is just a friendly suggestion :-)\nExample ( Mapping Scalars to Sequences ):\namerican:\n - Boston Red Sox\n - Detroit Tigers\n - New York Yankees\nnational:\n - New York Mets\n - Chicago Cubs\n - Atlanta Braves\n\nThere is also JSON of course which has ample support on Python (but tends to hurt my fingers a bit more ;-)\n", "Might I recommend YAML? IMHO the syntax is more readable for data entry, and then you don't have to write and maintain a parser. Eschew XML -- it is good for marking up text, but not good for data entry since the text isn't human readable with all the duplicate tags everywhere.\n", "I would simply use Python for the message definition file format.\nLet your message definition file be a plain Python file:\n# file messages.py\nmessages = dict(\n struct1=[\n dict(field=\"name\", type=\"string\", ignore=False),\n dict(field=\"id\", type=\"int\", enums={0: \"val1\", 1: \"val2\"}),\n ],\n struct2=[\n dict(field=\"object\", type=\"struct1\"),\n ]\n )\n\nYour program can then import and use that data structure directly:\n# in your program\nfrom messages import messages\nprint messages['struct1'][0][\"type\"]\nprint messages['struct1'][1]['type']\nprint messages['struct1'][1]['enums'][0]\nprint messages['struct2'][0]['type']\n\nUsing this approach, you let Python do the parsing for you. \nAnd you also gain a lot of possibilities. For instance, imagine you (for some strange reason) have a message structure with 1000 fields named \"field_N\". Using a conventional file format you would have to add 1000 lines of field definitions (unless you build some looping into your config file parser - you are then on your way to creating a programming language anyway). Using Python for this purpose, you could do something like:\nmessages = dict(\n ...\n strange_msg=[dict(field=\"field_%d\" % i) for i in range(1000)],\n ...\n )\n\nBTW, on Python 2.6, using named tuples instead of dict is an option. Or use on of the numerous \"Bunch\" classes available (see the Python cookbook for a namedtuple for 2.5).\nEDIT:\nBelow is code that reads message definition files as specified on the command line. It uses execfile instead of import.\n# file mainprogram.py\n\ndef read_messages_from_file(filename):\n module_dict = {}\n execfile(filename, module_dict)\n return module_dict['messages']\n\nif __name__ == \"__main__\":\n from pprint import pprint\n import sys\n\n for arg in sys.argv[1:]:\n messages = read_messages_from_file(arg)\n pprint(messages)\n\nExecuting:\n$ python mainprogram.py messages1 messages2 messages3\n\nwill read and print the messages defined in each file.\n", "Pyparsing is a nice easy to use library. That what I would use. \nhttp://pyparsing.wikispaces.com/\n", "Since you are at liberty to change the file format, you could change it to any of several formats that have Python libraries to read and write. For example, JSON, YAML, XML, or even the built-in ConfigParser.\n[struct1]\nfield: name\ntype: string\nignore: false\n# etc.\n\n" ]
[ 4, 4, 4, 2, 1, 0 ]
[]
[]
[ "dictionary", "parsing", "python" ]
stackoverflow_0001922426_dictionary_parsing_python.txt
Q: Which editor/IDE should I use for Python? Possible Duplicate: What IDE to use for Python I have Notepad++ and NetBeans 6.8, however I don't know if they work. I know you can edit Python with Notepad++ and compile/run it using the command line thing, but I'm not really sure how. I know NetBeans is a full-featured IDE and you can compile Java programs, but I don't think they support Python? Any ideas? A: Actually, netbeans has some python support right now: http://wiki.netbeans.org/Python. It works (still I prefer a plain text editor). For a list of python IDEs i'd call this list comprehensive: What IDE to use for Python? A: Eclipse with PyDev has been a great combination for me. Great editing experience and more importantly a good debugger. Pylint is supported as well, this will save you lots of headaches. This is all open source too. If you want to do IronPython development though I would add SharpDevelop 3.1.1. It has a drag & drop GUI form designer and overall is very much like Visual Studio, except it's free of course. A: I like PyDev under Eclipse ( and of course Eclipse does Java too). A: I am using eclipse with pydev extension A: Have a look at PythonEditors, there is a huge list of editors/IDEs with python-support. A: You have IDLE installed with Python. It is good editor which serves the purpose well. It is multi windowed, have syntax highlighting and auto complete features. A: I use Komodo Edit for all of my Python work. Actually, I use Komodo Edit for all of my IDE uses save for when I'm working in .Net. It's not really a full on IDE, but it's been perfect for everything I've used it for. It's pretty lightweight, has good syntax highlighting, but doesn't shove a lot of arcane project file overhead at you that you'd need to learn. It's worth having around, in my opinion, even if it doesn't suit your needs for Python. A: Python doesn't need to be compiled - it compiles itself (to bytecode) when you run it. Any text editor will work. Edit in response to comment: Yes, absolutely (although I think NetBeans does support Python). You'll find that IDEs are much less of a requirement when using a dynamic language like Python or Ruby, compared to Java or C#. A: I would go with IntelliJ IDEA, it has a great python plugin. Eclipse with PyDev is also nice, if you like open source. A: I'm certain there are a number of IDEs with Python plugins (Eclipse and Emacs spring to mind) but there are two things you want to look for. The first is support for basic lint checking (little red squiggly concept) through some kind of tool (pylint or pychecker). The second is support for running the Python interpreter embedded into it.
Which editor/IDE should I use for Python?
Possible Duplicate: What IDE to use for Python I have Notepad++ and NetBeans 6.8, however I don't know if they work. I know you can edit Python with Notepad++ and compile/run it using the command line thing, but I'm not really sure how. I know NetBeans is a full-featured IDE and you can compile Java programs, but I don't think they support Python? Any ideas?
[ "Actually, netbeans has some python support right now: http://wiki.netbeans.org/Python. It works (still I prefer a plain text editor).\nFor a list of python IDEs i'd call this list comprehensive: What IDE to use for Python?\n", "Eclipse with PyDev has been a great combination for me. Great editing experience and more importantly a good debugger. Pylint is supported as well, this will save you lots of headaches. This is all open source too. If you want to do IronPython development though I would add SharpDevelop 3.1.1. It has a drag & drop GUI form designer and overall is very much like Visual Studio, except it's free of course. \n", "I like PyDev under Eclipse ( and of course Eclipse does Java too).\n", "I am using eclipse with pydev extension\n", "Have a look at PythonEditors, there is a huge list of editors/IDEs with python-support.\n", "You have IDLE installed with Python. It is good editor which serves the purpose well. It is multi windowed, have syntax highlighting and auto complete features.\n", "I use Komodo Edit for all of my Python work. Actually, I use Komodo Edit for all of my IDE uses save for when I'm working in .Net. It's not really a full on IDE, but it's been perfect for everything I've used it for. It's pretty lightweight, has good syntax highlighting, but doesn't shove a lot of arcane project file overhead at you that you'd need to learn. It's worth having around, in my opinion, even if it doesn't suit your needs for Python.\n", "Python doesn't need to be compiled - it compiles itself (to bytecode) when you run it. Any text editor will work.\nEdit in response to comment: Yes, absolutely (although I think NetBeans does support Python). You'll find that IDEs are much less of a requirement when using a dynamic language like Python or Ruby, compared to Java or C#.\n", "I would go with IntelliJ IDEA, it has a great python plugin. \nEclipse with PyDev is also nice, if you like open source.\n", "I'm certain there are a number of IDEs with Python plugins (Eclipse and Emacs spring to mind) but there are two things you want to look for. The first is support for basic lint checking (little red squiggly concept) through some kind of tool (pylint or pychecker). The second is support for running the Python interpreter embedded into it.\n" ]
[ 4, 4, 3, 3, 2, 1, 1, 1, 0, 0 ]
[]
[]
[ "compilation", "editor", "ide", "python" ]
stackoverflow_0001922356_compilation_editor_ide_python.txt
Q: How to create an Incremental loading webpage I'm writing a page dealing with a large amount of data. It would last forever until my resultant page loaded (nearly infinite) because the data returned is so large. Therefore, I need to implement an incrementally loading page like one at thie url: http://docs.python.org/ Everytime a search term is entered, it will continue to load, and load, until it got some result, it will display incrementally, pretty cool :D. [edit] I am using python CGI (server) + Jquery (client). I have asked a similar question here : Display the result on the webpage as soon as the data is available at server The fact that I am trying to request a script on server ONLY ONE and let the client page incrementally displays out coming results has given me headache. If I don't get in wrong, the long poll, or something like that is not applied to this situation right? I am trying to do flush() thing but perhaps I am missing something here, I can not make it to work :(, the result always comes to client all at once. Plus getting the first few bytes, first few results are very general term. I would really appreciated with one can give me some running code, cuz I am very confusing now. Thanks so much. [edit] As I am trying to stick with call-on-only manner, I manage to shut of the mod_deflate of apache2 but so far I failed. I googled this problem and there comes some cases like myself, it's no luck :(. A: There are various possible ways to do so, but the basic trick is to have the search program return results to the wire before finishing. This is something usually done by explicitly calling a flush() call or equivalent every so many results. Now, to present them you can either Use AJAX: Return a very small page with javascript that will trigger the search, which would modify the DOM with the results as they are being flushed (or make several calls to the search program with a parameter denoting how many results you want and the offset) Use simple HTML: Use HTML that the browsers don't wait to complete render (this translates to avoiding tables, mostly, as tables are usually rendered when the whole table has arrived) Of course, if we knew what are you programming in, you could get more concrete advice. A: I think you'll have to use ajax for that kind of effect. Have a look at this in the Python JavaScript: performSearch : function(query) { // create the required interface elements this.out = $('#search-results'); this.title = $('<h2>' + _('Searching') + '</h2>').appendTo(this.out); this.dots = $('<span></span>').appendTo(this.title); this.status = $('<p style="display: none"></p>').appendTo(this.out); this.output = $('<ul class="search"/>').appendTo(this.out); $('#search-progress').text(_('Preparing search...')); this.startPulse(); etc. A: Sounds like it's AJAX time. When a person submits a query, send an AJAX request to the server to get some results. Display some "loading" message until you have a response. Set a Javascript timer in the page such that it refreshes the results output every few seconds until perhaps some flag is set to where it knows there are no more results, and it can stop refreshing. Have the server store results in the session, perhaps, or in the database temporarily. Your timer can cause an AJAX request to the server to see if any further results have been found and stored in the session/database, and update the HTML output such that it shows all results found thus far. This might be interesting/useful: Groundbreaking AJAX Incremental Search White Paper Released - A Data Matching Engine To The Rescue. A: You don't specify a language or an idea of what kind of data you are displaying or how it's accessed, so this leaves a lot of questions to be answered. Do you want to fetch more data when they scroll to the bottom of the page? Is this just a really slow search? Either way, there are basically two ways to go about this. There is the ajax way, and then there is the "leave an http connection open" way. The ajax way sounds like it makes more sense for this use case. Ajax way. Ajax with dynamic scrolling. There are lots of ajax ways to do this. Here's an interesting method of long polling which is similar. HTTP method using long polling. A: The way to do this is using Javascript to retreive the data after the page has loaded, this is commonly known as "AJAX". If you let us know what platform you are using someone will be able to give you more specific information - there are a lot of toolkits out there that help you out here, you don't have to write the Javascript from scratch A: I would suggest jQuery if you're going to try using Javascript/AJAX. If you've never had any experience with JS, but have some time to read through their getting started guide, this is (IMO) a great place/time to get started. It doesn't take much work at all to get something relatively impressive going. Furthermore, jQueryUI is excellent and has several very useful plugins. My favorite is the tabs plugin, because it allows you to set up a full AJAX website exactly how you'd like. It's also very easily skinned, they actually have a theme builder for it on the website, which you can customize and then download for use wherever. Pretty slick. A recent weekend time waster of mine, We Came As Romans Sucks, utilizes a basic implementation of jQUI's tabs and skinning. Minimal effort with huge gain.
How to create an Incremental loading webpage
I'm writing a page dealing with a large amount of data. It would last forever until my resultant page loaded (nearly infinite) because the data returned is so large. Therefore, I need to implement an incrementally loading page like one at thie url: http://docs.python.org/ Everytime a search term is entered, it will continue to load, and load, until it got some result, it will display incrementally, pretty cool :D. [edit] I am using python CGI (server) + Jquery (client). I have asked a similar question here : Display the result on the webpage as soon as the data is available at server The fact that I am trying to request a script on server ONLY ONE and let the client page incrementally displays out coming results has given me headache. If I don't get in wrong, the long poll, or something like that is not applied to this situation right? I am trying to do flush() thing but perhaps I am missing something here, I can not make it to work :(, the result always comes to client all at once. Plus getting the first few bytes, first few results are very general term. I would really appreciated with one can give me some running code, cuz I am very confusing now. Thanks so much. [edit] As I am trying to stick with call-on-only manner, I manage to shut of the mod_deflate of apache2 but so far I failed. I googled this problem and there comes some cases like myself, it's no luck :(.
[ "There are various possible ways to do so, but the basic trick is to have the search program return results to the wire before finishing. This is something usually done by explicitly calling a flush() call or equivalent every so many results.\nNow, to present them you can either\n\nUse AJAX: Return a very small page with javascript that will trigger the search, which would modify the DOM with the results as they are being flushed (or make several calls to the search program with a parameter denoting how many results you want and the offset)\nUse simple HTML: Use HTML that the browsers don't wait to complete render (this translates to avoiding tables, mostly, as tables are usually rendered when the whole table has arrived)\n\nOf course, if we knew what are you programming in, you could get more concrete advice.\n", "I think you'll have to use ajax for that kind of effect.\nHave a look at this in the Python JavaScript:\nperformSearch : function(query) {\n// create the required interface elements\nthis.out = $('#search-results');\nthis.title = $('<h2>' + _('Searching') + '</h2>').appendTo(this.out);\nthis.dots = $('<span></span>').appendTo(this.title);\nthis.status = $('<p style=\"display: none\"></p>').appendTo(this.out);\nthis.output = $('<ul class=\"search\"/>').appendTo(this.out);\n\n$('#search-progress').text(_('Preparing search...'));\nthis.startPulse();\n\netc.\n", "Sounds like it's AJAX time. When a person submits a query, send an AJAX request to the server to get some results. Display some \"loading\" message until you have a response. Set a Javascript timer in the page such that it refreshes the results output every few seconds until perhaps some flag is set to where it knows there are no more results, and it can stop refreshing. Have the server store results in the session, perhaps, or in the database temporarily. Your timer can cause an AJAX request to the server to see if any further results have been found and stored in the session/database, and update the HTML output such that it shows all results found thus far.\nThis might be interesting/useful: Groundbreaking AJAX Incremental Search White Paper Released - A Data Matching Engine To The Rescue.\n", "You don't specify a language or an idea of what kind of data you are displaying or how it's accessed, so this leaves a lot of questions to be answered. Do you want to fetch more data when they scroll to the bottom of the page? Is this just a really slow search?\nEither way, there are basically two ways to go about this. There is the ajax way, and then there is the \"leave an http connection open\" way. The ajax way sounds like it makes more sense for this use case.\nAjax way. Ajax with dynamic scrolling. There are lots of ajax ways to do this.\nHere's an interesting method of long polling which is similar.\nHTTP method using long polling.\n", "The way to do this is using Javascript to retreive the data after the page has loaded, this is commonly known as \"AJAX\".\nIf you let us know what platform you are using someone will be able to give you more specific information - there are a lot of toolkits out there that help you out here, you don't have to write the Javascript from scratch\n", "I would suggest jQuery if you're going to try using Javascript/AJAX. If you've never had any experience with JS, but have some time to read through their getting started guide, this is (IMO) a great place/time to get started. It doesn't take much work at all to get something relatively impressive going. \n\nFurthermore, jQueryUI is excellent and has several very useful plugins. My favorite is the tabs plugin, because it allows you to set up a full AJAX website exactly how you'd like. It's also very easily skinned, they actually have a theme builder for it on the website, which you can customize and then download for use wherever. Pretty slick. \nA recent weekend time waster of mine, We Came As Romans Sucks, utilizes a basic implementation of jQUI's tabs and skinning. Minimal effort with huge gain.\n" ]
[ 3, 1, 1, 1, 1, 1 ]
[]
[]
[ "jquery", "python" ]
stackoverflow_0001922673_jquery_python.txt
Q: Google Wave Python Tutorial - What next? I just finished working through Google's Wave Robot: Python Tutorial. The API Reference looks a bit imposing. Is there anything else I can look at to get up to speed? A: Have a look at the Python sample bots on the sample gallery : http://wave-samples-gallery.appspot.com/results?language=Python&api=Robots. This can give you ideas of bots to make, and show you good practices, too. The gallery outlines the specific features of the API used by each bot. Also, you could join the Wave API group on http://groups.google.com/group/google-wave-api. There's pretty good talk on there about it. A: Building the robot is fairly straight forward conceptually. The Python API itself however is buggy and hard to work with. Were you able to build a simple robot that responds to commands? That's a start IMHO. A: My suggestion is to try to implement some small program and start experimenting with some features starting from the one that are kind of simple. In this way you build momentum and will adventure in the deepest part of it. Of course reading the code of the api itself will help A LOT, and is python so ... a pleasant lecture.
Google Wave Python Tutorial - What next?
I just finished working through Google's Wave Robot: Python Tutorial. The API Reference looks a bit imposing. Is there anything else I can look at to get up to speed?
[ "Have a look at the Python sample bots on the sample gallery : http://wave-samples-gallery.appspot.com/results?language=Python&api=Robots. This can give you ideas of bots to make, and show you good practices, too. The gallery outlines the specific features of the API used by each bot.\nAlso, you could join the Wave API group on http://groups.google.com/group/google-wave-api. There's pretty good talk on there about it.\n", "Building the robot is fairly straight forward conceptually. The Python API itself however is buggy and hard to work with.\nWere you able to build a simple robot that responds to commands? That's a start IMHO.\n", "My suggestion is to try to implement some small program and start experimenting with some features starting from the one that are kind of simple. In this way you build momentum and will adventure in the deepest part of it. Of course reading the code of the api itself will help A LOT, and is python so ... a pleasant lecture.\n" ]
[ 3, 1, 1 ]
[]
[]
[ "google_app_engine", "google_wave", "python" ]
stackoverflow_0001747198_google_app_engine_google_wave_python.txt
Q: monolithic inheritance vs modular member based OOP design I'm having a hard time making a design decision I have a class in python, that processing form data, this data is very similar to other form data, and so I'm refactoring it into it's own object so it can be reused by the other classes. The delima is weather to make this formprocessor a member of the classes or a parent of the classes. please correct me if this terminology is wrong, here is what I'm torn between: monolithic inheritance based classes: class FormProcessor(object): def post(self): # ... process form data class PageHandler(RequestHandler,FormProcessor): def get(self): # show page or the more modular member based classes: class FormProcessor(object): def process(self): # ... process form data class PageHandler(RequestHandler): def __init__(self): self.processor = FormProcessor() def get(self): # show page def post(self): self.processor.process(self.postdata) I'm leaning toward the second but I'm not sure what the consequences could be down the road in terms of maintainability. The reason I'm leaning toward it is that, I like to think of the processing as an action that takes place, not as a main part of the PageHandler, so this makes sense to make it a member object, instead of a parent. It bothers me that when classes interit functionality it ends up with a very long list of functions on an instance, I'm trying to categorize them better so the program is understandable and reflects the system that it is modeling. look forward to any advice on this issue A: Definitely go for the modular approach. Some of the advantages of taking the modular approach are: It makes your code more readable, i.e. it's more clear what the PageHandler and FormProcessor do It makes it easier and more effective to write unit tests on both of your classes It makes it easier to change the behavior of PageHandler at a later date by using a different implementation of PageHandler In general, stick to the idea that one class does one thing; it's easier to see what you're working with when maintaining your software, as well as making it easier to write (you only have to think about one context at a time then).
monolithic inheritance vs modular member based OOP design
I'm having a hard time making a design decision I have a class in python, that processing form data, this data is very similar to other form data, and so I'm refactoring it into it's own object so it can be reused by the other classes. The delima is weather to make this formprocessor a member of the classes or a parent of the classes. please correct me if this terminology is wrong, here is what I'm torn between: monolithic inheritance based classes: class FormProcessor(object): def post(self): # ... process form data class PageHandler(RequestHandler,FormProcessor): def get(self): # show page or the more modular member based classes: class FormProcessor(object): def process(self): # ... process form data class PageHandler(RequestHandler): def __init__(self): self.processor = FormProcessor() def get(self): # show page def post(self): self.processor.process(self.postdata) I'm leaning toward the second but I'm not sure what the consequences could be down the road in terms of maintainability. The reason I'm leaning toward it is that, I like to think of the processing as an action that takes place, not as a main part of the PageHandler, so this makes sense to make it a member object, instead of a parent. It bothers me that when classes interit functionality it ends up with a very long list of functions on an instance, I'm trying to categorize them better so the program is understandable and reflects the system that it is modeling. look forward to any advice on this issue
[ "Definitely go for the modular approach. Some of the advantages of taking the modular approach are:\n\nIt makes your code more readable, i.e. it's more clear what the PageHandler and FormProcessor do\nIt makes it easier and more effective to write unit tests on both of your classes\nIt makes it easier to change the behavior of PageHandler at a later date by using a different implementation of PageHandler\n\nIn general, stick to the idea that one class does one thing; it's easier to see what you're working with when maintaining your software, as well as making it easier to write (you only have to think about one context at a time then).\n" ]
[ 7 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0001923101_oop_python.txt
Q: IronPython Webframework There seem to be many excellent web frameworks for Python. Has anyone used any of these (Pylons, Web2Py, Django) with IronPython? A: Django has been run on IronPython before, but as a proof-of-concept. I know the IronPython team are interested in Django support as a metric for Python-compatibility. Somewhat related is the possibility to use IronPython with ASP.NET and ASP.NET MVC, which is probably more mature. A: You may want to read this Basically web2py code runs unmodified and out of the box but with IronPython but no CSV module (so no database IO) no third party database drivers (not even SQLite, so no databases at all) no built-in web server (unless you cripple it by removing signals and logging) This is because csv, signals, logging and sqlite are not present in IronPython. An you can see from the thread above there is work underway to find ways around. web2py also runs unmodified on Jython 2.5 beta, without any known limitation, except for a bug with regular expressions in Jython that makes it choke on some templates (re.compile(...).finditer goes in a loop). We are working to find a way around for this as well.
IronPython Webframework
There seem to be many excellent web frameworks for Python. Has anyone used any of these (Pylons, Web2Py, Django) with IronPython?
[ "Django has been run on IronPython before, but as a proof-of-concept. I know the IronPython team are interested in Django support as a metric for Python-compatibility.\nSomewhat related is the possibility to use IronPython with ASP.NET and ASP.NET MVC, which is probably more mature.\n", "You may want to read this\nBasically web2py code runs unmodified and out of the box but with IronPython but\n\nno CSV module (so no database IO)\nno third party database drivers (not even SQLite, so no databases at all)\nno built-in web server (unless you cripple it by removing signals and logging)\n\nThis is because csv, signals, logging and sqlite are not present in IronPython.\nAn you can see from the thread above there is work underway to find ways around.\nweb2py also runs unmodified on Jython 2.5 beta, without any known limitation, except for a bug with regular expressions in Jython that makes it choke on some templates (re.compile(...).finditer goes in a loop). We are working to find a way around for this as well.\n" ]
[ 6, 6 ]
[ "we2py released Feb 5, 2009 \nhttp://www.web2py.com \n\nIncludes a Database Abstraction Layer that works with SQLite, MySQL,\nPostgreSQL, FireBird, MSSQL, Oracle, AND the Google App Engine. \n\n" ]
[ -3 ]
[ "ironpython", "python" ]
stackoverflow_0000437160_ironpython_python.txt
Q: How should I build this Django model to do what I want This is what I had before (but realized that you can't obviously do it in this order: class MasterAdmin(models.Model): """ A permanent admin (one per Account) that shouldn't be deleted. """ admin = models.OneToOneField(AccountAdmin) class Account(models.Model): """ A top-level account in the system. """ masteradmin = models.OneToOneField(MasterAdmin) class AccountAdmin(models.Model): """ An Account admin that can be deleted. This includes limited permissions. """ account = models.ForeignKey(Account) I think you can see what I want to do from the example. I want to have an MasterAccountAdmin which shares the attributes from AccountAdmin. The purpose is that I want to give people the ability to delete an AccountAdmin, but not MasterAccountAdmin. I didn't want to just have an attribute on AccountAdmin called "master = models.BooleanField()". Obviously this example won't work because MasterAdmin is referencing AccountAdmin before its creation, but I wanted to show what I'm trying to achieve. Am I thinking of this all wrong? A: Why not just make is_master a property of AccountAdmin and then override the delete() method to ensure is_master is not true? A: When you have forward references, use the quotes. admin = models.OneToOneField('AccountAdmin') See the docs. If you need to create a relationship on a model that has not yet been defined, you can use the name of the model, rather than the model object itself...
How should I build this Django model to do what I want
This is what I had before (but realized that you can't obviously do it in this order: class MasterAdmin(models.Model): """ A permanent admin (one per Account) that shouldn't be deleted. """ admin = models.OneToOneField(AccountAdmin) class Account(models.Model): """ A top-level account in the system. """ masteradmin = models.OneToOneField(MasterAdmin) class AccountAdmin(models.Model): """ An Account admin that can be deleted. This includes limited permissions. """ account = models.ForeignKey(Account) I think you can see what I want to do from the example. I want to have an MasterAccountAdmin which shares the attributes from AccountAdmin. The purpose is that I want to give people the ability to delete an AccountAdmin, but not MasterAccountAdmin. I didn't want to just have an attribute on AccountAdmin called "master = models.BooleanField()". Obviously this example won't work because MasterAdmin is referencing AccountAdmin before its creation, but I wanted to show what I'm trying to achieve. Am I thinking of this all wrong?
[ "Why not just make is_master a property of AccountAdmin and then override the delete() method to ensure is_master is not true?\n", "When you have forward references, use the quotes.\nadmin = models.OneToOneField('AccountAdmin')\n\nSee the docs.\n\nIf you need to create a relationship on a model that has not yet been defined, you can use the name of the model, rather than the model object itself...\n\n" ]
[ 3, 2 ]
[]
[]
[ "django", "django_models", "foreign_keys", "one_to_one", "python" ]
stackoverflow_0001923551_django_django_models_foreign_keys_one_to_one_python.txt
Q: How to make paramiko wait for transfer to finish? I've tried various ways to upload a file locally to a FTP, ncftpput was really slow compared to lftp so I switched. but what I've noticed is my python script waits for ncftpput to finish but when using lftp, it just uploads the file to the FTP and it continues on with the script.. I am using paramiko to SSH into my web server and uploading a file to another FTP. Is there any way to make it 'wait'? I dont want to use sleep because file sizes are going to vary and its either waiting too long for a small file or not waiting long enough for a big file. Any ideas? or alternatives to lftp/ncftpput?
How to make paramiko wait for transfer to finish?
I've tried various ways to upload a file locally to a FTP, ncftpput was really slow compared to lftp so I switched. but what I've noticed is my python script waits for ncftpput to finish but when using lftp, it just uploads the file to the FTP and it continues on with the script.. I am using paramiko to SSH into my web server and uploading a file to another FTP. Is there any way to make it 'wait'? I dont want to use sleep because file sizes are going to vary and its either waiting too long for a small file or not waiting long enough for a big file. Any ideas? or alternatives to lftp/ncftpput?
[]
[]
[ "See the lftp docs for proper usage of the ftp:sync-mode setting. (You want true.)\n" ]
[ -1 ]
[ "python" ]
stackoverflow_0001923794_python.txt
Q: Get class object __dict__ without special attributes For getting all the defined class attributes I try to go with TheClass.__dict__ but that also gives me the special attributes. Is there a way to get only the self-defined attributes or do I have to "clean" the dict myself? A: Another solution: class _BaseA(object): _intern = object.__dict__.keys() class A(_BaseA): myattribute = 1 print filter(lambda x: x not in A._intern+['__module__'], A.__dict__.keys()) I don't think this is terribly robust and there might still be a better way. This does adress some of the basic issues some of the other answers pointed at: No need for 'name convention' based-filtering Providing your own implementation of magic methods, e.g. __len__ is no problem (define in A). A: You can't clean the __dict__: AttributeError: attribute '__dict__' of 'type' objects is not writable You could rely on naming conventions: class A(object): def __init__(self, arg): self.arg = arg class_attribute = "01" print [ a for a in A.__dict__.keys() if not (a.startswith('__') and a.endswith('__')) ] # => ['class_attribute'] This may not be reliable, since you can of course overwrite or implement special/magic methods like __item__ or __len__ in your class. A: I don't think there's anything simple, and why would there be? There's no language-enforced difference between magic and user-defined attributes. MYYN's solution won't work if you have a user-defined attribute starting with '__'. However, it does suggest a solution based on conventions: if you want to introspect your own classes, you can define your own naming convention, and filter on that. Perhaps if you explain the need we can find a better solution.
Get class object __dict__ without special attributes
For getting all the defined class attributes I try to go with TheClass.__dict__ but that also gives me the special attributes. Is there a way to get only the self-defined attributes or do I have to "clean" the dict myself?
[ "Another solution:\nclass _BaseA(object):\n _intern = object.__dict__.keys()\n\nclass A(_BaseA):\n myattribute = 1\n\nprint filter(lambda x: x not in A._intern+['__module__'], A.__dict__.keys())\n\nI don't think this is terribly robust and there might still be a better way.\nThis does adress some of the basic issues some of the other answers pointed at:\n\nNo need for 'name convention' based-filtering\nProviding your own implementation of magic methods, e.g. __len__ is no problem (define in A).\n\n", "You can't clean the __dict__:\nAttributeError: attribute '__dict__' of 'type' objects is not writable\n\nYou could rely on naming conventions:\nclass A(object):\n def __init__(self, arg):\n self.arg = arg\n\n class_attribute = \"01\" \n\nprint [ a for a in A.__dict__.keys() \n if not (a.startswith('__') and a.endswith('__')) ]\n\n# => ['class_attribute']\n\nThis may not be reliable, since you can of course overwrite or implement special/magic methods like __item__ or __len__ in your class.\n", "I don't think there's anything simple, and why would there be? There's no language-enforced difference between magic and user-defined attributes.\nMYYN's solution won't work if you have a user-defined attribute starting with '__'. However, it does suggest a solution based on conventions: if you want to introspect your own classes, you can define your own naming convention, and filter on that.\nPerhaps if you explain the need we can find a better solution.\n" ]
[ 5, 3, 2 ]
[]
[]
[ "new_style_class", "oop", "python" ]
stackoverflow_0001923130_new_style_class_oop_python.txt
Q: True and 'True' in python condition If: x = 0 b = x==0 and I print b it would print 'true' but if I did: x = 0 b = x ==3 and I printed b it would be false. Instead of it printing false how would I take the boolean value b to print what text I wanted? Let me explain further: bool = all(n > 0 for n in list) if bool != 'True': print 'a value is not greater than zero' But it prints nothing? A: Something like this you mean? x = 0 if x != 3: print "x does not equal 3" A: I think perhaps the following will help alleviate some of your confusion: >>> 0==0 True >>> 'True' 'True' >>> (0==0) == 'True' False >>> (0==0) == True True A: An if statement as other answers suggest is a possibility (and you could add an else clause to print something specific in each case). More direct is an if/else operator: print('equality' if b else 'diversity') You could also use indexing, since False has the int value 0 and True the int value 1: print(['different', 'the same'][b]) but I find that a bit less readable than the if variants. A: Remove the quotes around True: bool = all(n > 0 for n in list) if bool != True: print 'a value is not greater than zero' or, you can also check for False: bool = all(n > 0 for n in list) if bool == False: print 'a value is not greater than zero' There are several other "shortcut" ways of writing it, but since you're a beginner let's not confuse the subject more than necessary. A: >>> x = 0 >>> if not x == 3: print 'x does not equal 3' x does not equal 3 lte me explain further: >>> list = [-1, 1, 2, 3] >>> if not all(n > 0 for n in list): print 'a value is not greater than zero' a value is not greater than zero # => or shorter ... >>> if min(list) < 0: print 'a value is not greater than zero' a value is not greater than zero note that list is a builtin and shouldn't be used as a variable name. >>> list <type 'list'> >>> list = [1, 2, "value not greater than 0"] >>> list [1, 2, "value not greater than 0"] >>> del list >>> list <type 'list'> ... A: a = lambda b :("not true","true")[b == 3] print a(3) will do it for you if you want to put it in a lambda. A: You will need to do the printing yourself, as everyone suggested here. It's worthy to note that some languages (e.g. Scala, Ruby, Groovy) have language features that enable you to write: x should be(3) And that will report: 0 should be 3 but is not. In Groovy, with Spock testing framework, you can write: def "my test": when: x = 0 expect: x == 3 And that would output: Condition not satisfied: x == 3 | | | 0 | 3 false I don't think this possibly cleanly in python though. A: >>> 'True' is not True True 'True' is a string True is a boolean They have nothing to do with each other, except coincidentally. The string value happens to have the same letters as the boolean literal. But that's just a coincidence.
True and 'True' in python condition
If: x = 0 b = x==0 and I print b it would print 'true' but if I did: x = 0 b = x ==3 and I printed b it would be false. Instead of it printing false how would I take the boolean value b to print what text I wanted? Let me explain further: bool = all(n > 0 for n in list) if bool != 'True': print 'a value is not greater than zero' But it prints nothing?
[ "Something like this you mean?\nx = 0\nif x != 3:\n print \"x does not equal 3\"\n\n", "I think perhaps the following will help alleviate some of your confusion:\n>>> 0==0\nTrue\n>>> 'True'\n'True'\n>>> (0==0) == 'True'\nFalse\n>>> (0==0) == True\nTrue\n\n", "An if statement as other answers suggest is a possibility (and you could add an else clause to print something specific in each case). More direct is an if/else operator:\nprint('equality' if b else 'diversity')\n\nYou could also use indexing, since False has the int value 0 and True the int value 1:\nprint(['different', 'the same'][b])\n\nbut I find that a bit less readable than the if variants.\n", "Remove the quotes around True:\nbool = all(n > 0 for n in list) \n\nif bool != True:\n print 'a value is not greater than zero'\n\nor, you can also check for False:\nbool = all(n > 0 for n in list) \n\nif bool == False:\n print 'a value is not greater than zero'\n\nThere are several other \"shortcut\" ways of writing it, but since you're a beginner let's not confuse the subject more than necessary.\n", ">>> x = 0\n>>> if not x == 3: print 'x does not equal 3'\nx does not equal 3\n\nlte me explain further:\n>>> list = [-1, 1, 2, 3]\n>>> if not all(n > 0 for n in list): print 'a value is not greater than zero'\na value is not greater than zero\n\n# => or shorter ...\n>>> if min(list) < 0: print 'a value is not greater than zero'\na value is not greater than zero\n\nnote that list is a builtin and shouldn't be used as a variable name.\n>>> list\n<type 'list'>\n>>> list = [1, 2, \"value not greater than 0\"]\n>>> list\n[1, 2, \"value not greater than 0\"]\n>>> del list\n>>> list\n<type 'list'>\n...\n\n", "a = lambda b :(\"not true\",\"true\")[b == 3]\nprint a(3)\n\nwill do it for you if you want to put it in a lambda.\n", "You will need to do the printing yourself, as everyone suggested here.\nIt's worthy to note that some languages (e.g. Scala, Ruby, Groovy) have language features that enable you to write:\nx should be(3)\n\nAnd that will report:\n0 should be 3 but is not.\n\nIn Groovy, with Spock testing framework, you can write:\ndef \"my test\":\n when: x = 0\n expect: x == 3\n\nAnd that would output:\nCondition not satisfied:\nx == 3\n| | |\n0 | 3\n false\n\nI don't think this possibly cleanly in python though.\n", ">>> 'True' is not True\nTrue\n\n'True' is a string\nTrue is a boolean\nThey have nothing to do with each other, except coincidentally. The string value happens to have the same letters as the boolean literal. But that's just a coincidence.\n" ]
[ 6, 6, 4, 3, 2, 2, 0, 0 ]
[]
[]
[ "boolean", "python", "syntax" ]
stackoverflow_0001922849_boolean_python_syntax.txt
Q: Python lambdas and scoping Given this snippet of code: funcs = [] for x in range(3): funcs.append(lambda: x) print [f() for f in funcs] I would expect it to print [0, 1, 2], but instead it prints [2, 2, 2]. Is there something fundamental I'm missing about how lambdas work with scope? A: This is a frequent question in Python. Basically the scoping is such that when f() is called, it will use the current value of x, not the value of x at the time the lambda is formed. There is a standard workaround: funcs = [] for x in range(10): funcs.append(lambda x=x: x) print [f() for f in funcs] The use of lambda x = x retrieves and saves the current value of x. A: x is bound to the module-level x (which is left over from the for loop). A little clearer: funcs = [] for x in range(10): funcs.append(lambda: x) x = 'Foo' print [f() for f in funcs] # Prints ['Foo', 'Foo', 'Foo', 'Foo', 'Foo', 'Foo', 'Foo', 'Foo', 'Foo', 'Foo'] A: You know the answer: yes. ;) Take comfort, however, as this is a very common discovery for budding pythonistas. When you define a function or lambda that references variables not "created" inside that function, it creates a closure over the variables. The effect is that you get the value of the variable when calling the function, not the value at definition time. (You were expecting the latter.) There are a few ways to deal with this. First is binding extra variables: funcs = [] for x in range(10): funcs.append(lambda x=x: x) print [f() for f in funcs] # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] The second way is a little more formal: from functools import partial funcs = [] for x in range(10): funcs.append(partial(lambda x: x, x)) print [f() for f in funcs] # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Python lambdas and scoping
Given this snippet of code: funcs = [] for x in range(3): funcs.append(lambda: x) print [f() for f in funcs] I would expect it to print [0, 1, 2], but instead it prints [2, 2, 2]. Is there something fundamental I'm missing about how lambdas work with scope?
[ "This is a frequent question in Python. Basically the scoping is such that when f() is called, it will use the current value of x, not the value of x at the time the lambda is formed. There is a standard workaround:\nfuncs = []\nfor x in range(10):\nfuncs.append(lambda x=x: x)\nprint [f() for f in funcs]\n\nThe use of lambda x = x retrieves and saves the current value of x.\n", "x is bound to the module-level x (which is left over from the for loop).\nA little clearer:\nfuncs = []\n\nfor x in range(10):\n funcs.append(lambda: x)\n\nx = 'Foo'\n\nprint [f() for f in funcs]\n\n# Prints ['Foo', 'Foo', 'Foo', 'Foo', 'Foo', 'Foo', 'Foo', 'Foo', 'Foo', 'Foo']\n\n", "You know the answer: yes. ;) Take comfort, however, as this is a very common discovery for budding pythonistas. When you define a function or lambda that references variables not \"created\" inside that function, it creates a closure over the variables. The effect is that you get the value of the variable when calling the function, not the value at definition time. (You were expecting the latter.)\nThere are a few ways to deal with this. First is binding extra variables:\nfuncs = []\nfor x in range(10):\n funcs.append(lambda x=x: x)\nprint [f() for f in funcs]\n# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n\nThe second way is a little more formal:\nfrom functools import partial\nfuncs = []\nfor x in range(10):\n funcs.append(partial(lambda x: x, x))\nprint [f() for f in funcs]\n# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n\n" ]
[ 9, 5, 4 ]
[]
[]
[ "lambda", "python" ]
stackoverflow_0001924214_lambda_python.txt
Q: suggestion required related to rewriting and string manipulation I had to read from a file and for each data between delimiter i need to remove the white space and i have written the following program in jython When i am trying to rewrite ,its rewriting at the end of source file. filesrc = open('c:/FILE/split_doc.txt','r+') for list in filesrc.readlines(): #split the records by the delimiter fields = list.split(',') list = ",".join([s.strip() for s in fields]) filesrc.writelines(list+"\n") filesrc.close() So i did some modification and added file.seek so I can rewrite on the source lines and it worked to some extend except it was adding two extra lines at the end which means some issue with seek part. The modified program is filesrc = open('c:/ODI_FILE/split_doc.txt','r+') lines=0 for list in filesrc.readlines(): #split the records by the delimiter fields = list.split(',') list = ",".join([s.strip() for s in fields]) filesrc.seek(lines) filesrc.writelines(list+"\n") lines += len(list+"\n") filesrc.close() Please help me with the correct logic. The correct source file with extra white spaces 52 ,William ,Kudo ,28/03/199300:00:00 11,Andrew, Andersen,22/02/199900:00:00 12,John ,Galagers,20/04/200000:00:00 13,Jeffrey ,Jeferson,10/06/198800:00:00 20,Jennie,Daumesnil,28/02/198800:00:00 21,Steve,Barrot,24/09/199200:00:00 22,Mary,Carlin,14/03/199500:00:00 30,Paul,Moore,11/03/199900:00:00 This is my wrong output 52,William,Kudo,28/03/199300:00:00 11,Andrew,Andersen,22/02/199900:00:00 12,John,Galagers,20/04/200000:00:00 13,Jeffrey,Jeferson,10/06/198800:00:00 20,Jennie,Daumesnil,28/02/198800:00:00 21,Steve,Barrot,24/09/199200:00:00 22,Mary,Carlin,14/03/199500:00:00 30,Paul,Moore,11/03/199900:00:00 9500:00:00 30,Paul,Moore,11/03/199900:00:00 here the last two lines should not have come Please suggest the required and faster way as this is a sample file and i would have to have make this program work for millions of rows. Is there is way to make this logic work with while loop too ? A: You don't want to write to the same file while you're reading it. It's technically possible, but that path is fraught with trouble and misery. Here's the plain and simple process you should follow: read the whole file into a string then close the file split the string on newlines into a list process each line to remove extra spacing rejoin the list into a string overwrite the source file with the new cleaned data If you don't want to load the whole file into memory at once, then try this process: open the file for reading read line by line write cleaned lines to a new temp output file when all lines are written, delete the original file rename temp file to original name My recommendation is to write it both ways and see what works or doesn't work and which way is faster, rather than assume you can't read it all into memory just because it is millions of lines. Maybe it will work just fine. Also, you can certainly make this work with a while loop as well. To do so, you will want to read the Python docs on the form of a while loop and do some experiments. How you write that loop will depend on how you loaded the file: all at once into a string and then split into a list, or line by line directly from the file. For either case, how do you know how much work the while loop will have to do, how will you advance from one piece of work to the next, and how will you know when its done? If you can answer these, you can write your loop. A: You are overwriting as you go, but your final results are shorter than the original, so you are getting the last X characters of the original bleeding through, where X is the difference in size from the original to the new version. The extra .seek() and truncate() calls in this version will seek to the end of your new output and cut off the rest of the file. filesrc = open('c:/ODI_FILE/split_doc.txt','r+') lines=0 for list in filesrc.readlines(): #split the records by the delimiter fields = list.split(',') list = ",".join([s.strip() for s in fields]) filesrc.seek(lines) filesrc.writelines(list+"\n") lines += len(list+"\n") filesrc.seek(lines) filesrc.truncate() filesrc.close() A: This does not answer your question, but have you considered not doing this with jython? Tried with Sed?
suggestion required related to rewriting and string manipulation
I had to read from a file and for each data between delimiter i need to remove the white space and i have written the following program in jython When i am trying to rewrite ,its rewriting at the end of source file. filesrc = open('c:/FILE/split_doc.txt','r+') for list in filesrc.readlines(): #split the records by the delimiter fields = list.split(',') list = ",".join([s.strip() for s in fields]) filesrc.writelines(list+"\n") filesrc.close() So i did some modification and added file.seek so I can rewrite on the source lines and it worked to some extend except it was adding two extra lines at the end which means some issue with seek part. The modified program is filesrc = open('c:/ODI_FILE/split_doc.txt','r+') lines=0 for list in filesrc.readlines(): #split the records by the delimiter fields = list.split(',') list = ",".join([s.strip() for s in fields]) filesrc.seek(lines) filesrc.writelines(list+"\n") lines += len(list+"\n") filesrc.close() Please help me with the correct logic. The correct source file with extra white spaces 52 ,William ,Kudo ,28/03/199300:00:00 11,Andrew, Andersen,22/02/199900:00:00 12,John ,Galagers,20/04/200000:00:00 13,Jeffrey ,Jeferson,10/06/198800:00:00 20,Jennie,Daumesnil,28/02/198800:00:00 21,Steve,Barrot,24/09/199200:00:00 22,Mary,Carlin,14/03/199500:00:00 30,Paul,Moore,11/03/199900:00:00 This is my wrong output 52,William,Kudo,28/03/199300:00:00 11,Andrew,Andersen,22/02/199900:00:00 12,John,Galagers,20/04/200000:00:00 13,Jeffrey,Jeferson,10/06/198800:00:00 20,Jennie,Daumesnil,28/02/198800:00:00 21,Steve,Barrot,24/09/199200:00:00 22,Mary,Carlin,14/03/199500:00:00 30,Paul,Moore,11/03/199900:00:00 9500:00:00 30,Paul,Moore,11/03/199900:00:00 here the last two lines should not have come Please suggest the required and faster way as this is a sample file and i would have to have make this program work for millions of rows. Is there is way to make this logic work with while loop too ?
[ "You don't want to write to the same file while you're reading it. It's technically possible, but that path is fraught with trouble and misery.\nHere's the plain and simple process you should follow:\n\nread the whole file into a string then close the file\nsplit the string on newlines into a list\nprocess each line to remove extra spacing\nrejoin the list into a string\noverwrite the source file with the new cleaned data\n\nIf you don't want to load the whole file into memory at once, then try this process:\n\nopen the file for reading\nread line by line\nwrite cleaned lines to a new temp output file\nwhen all lines are written, delete the original file\nrename temp file to original name\n\nMy recommendation is to write it both ways and see what works or doesn't work and which way is faster, rather than assume you can't read it all into memory just because it is millions of lines. Maybe it will work just fine.\nAlso, you can certainly make this work with a while loop as well. To do so, you will want to read the Python docs on the form of a while loop and do some experiments. How you write that loop will depend on how you loaded the file: all at once into a string and then split into a list, or line by line directly from the file. For either case, how do you know how much work the while loop will have to do, how will you advance from one piece of work to the next, and how will you know when its done? If you can answer these, you can write your loop.\n", "You are overwriting as you go, but your final results are shorter than the original, so you are getting the last X characters of the original bleeding through, where X is the difference in size from the original to the new version. The extra .seek() and truncate() calls in this version will seek to the end of your new output and cut off the rest of the file.\nfilesrc = open('c:/ODI_FILE/split_doc.txt','r+')\nlines=0\nfor list in filesrc.readlines():\n #split the records by the delimiter\n fields = list.split(',')\n list = \",\".join([s.strip() for s in fields])\n filesrc.seek(lines)\n filesrc.writelines(list+\"\\n\")\n lines += len(list+\"\\n\")\nfilesrc.seek(lines)\nfilesrc.truncate()\nfilesrc.close()\n\n", "This does not answer your question, but have you considered not doing this with jython?\nTried with Sed?\n" ]
[ 1, 0, 0 ]
[]
[]
[ "file", "jython", "python", "rewrite" ]
stackoverflow_0001924043_file_jython_python_rewrite.txt
Q: Multiprocessing launching too many instances of Python VM I am writing some multiprocessing code (Python 2.6.4, WinXP) that spawns processes to run background tasks. In playing around with some trivial examples, I am running into an issue where my code just continuously spawns new processes, even though I only tell it to spawn a fixed number. The program itself runs fine, but if I look in Windows TaskManager, I keep seeing new 'python.exe' processes appear. They just keep spawning more and more as the program runs (eventually starving my machine). For example, I would expect the code below to launch 2 python.exe processes. The first being the program itself, and the second being the child process it spawns. Any idea what I am doing wrong? import time import multiprocessing class Agent(multiprocessing.Process): def __init__(self, i): multiprocessing.Process.__init__(self) self.i = i def run(self): while True: print 'hello from %i' % self.i time.sleep(1) agent = Agent(1) agent.start() A: It looks like you didn't carefully follow the guidelines in the documentation, specifically this section where it talks about "Safe importing of main module". You need to protect your launch code with an if __name__ == '__main__': block or you'll get what you're getting, I believe. I believe it comes down to the multiprocessing module not being able to use os.fork() as it does on Linux, where an already-running process is basically cloned in memory. On Windows (which has no such fork()) it must run a new Python interpreter and tell it to import your main module and then execute the start/run method once that's done. If you have code at "module level", unprotected by the name check, then during the import it starts the whole sequence over again, ad infinitum A: When I run this in Linux with python2.6, I see a maximum of 4 python2.6 processes and I can't guarantee that they're all from this process. They're definitely not filling up the machine. Need new python version? Linux/Windows difference? A: I don't see anything wrong with that. Works fine on Ubuntu 9.10 (Python 2.6.4). Are you sure you don't have cron or something starting multiple copies of your script? Or that the spawned script is not calling anything that would start a new instance, for example as a side effect of import if your code runs directly on import?
Multiprocessing launching too many instances of Python VM
I am writing some multiprocessing code (Python 2.6.4, WinXP) that spawns processes to run background tasks. In playing around with some trivial examples, I am running into an issue where my code just continuously spawns new processes, even though I only tell it to spawn a fixed number. The program itself runs fine, but if I look in Windows TaskManager, I keep seeing new 'python.exe' processes appear. They just keep spawning more and more as the program runs (eventually starving my machine). For example, I would expect the code below to launch 2 python.exe processes. The first being the program itself, and the second being the child process it spawns. Any idea what I am doing wrong? import time import multiprocessing class Agent(multiprocessing.Process): def __init__(self, i): multiprocessing.Process.__init__(self) self.i = i def run(self): while True: print 'hello from %i' % self.i time.sleep(1) agent = Agent(1) agent.start()
[ "It looks like you didn't carefully follow the guidelines in the documentation, specifically this section where it talks about \"Safe importing of main module\".\nYou need to protect your launch code with an if __name__ == '__main__': block or you'll get what you're getting, I believe.\nI believe it comes down to the multiprocessing module not being able to use os.fork() as it does on Linux, where an already-running process is basically cloned in memory. On Windows (which has no such fork()) it must run a new Python interpreter and tell it to import your main module and then execute the start/run method once that's done. If you have code at \"module level\", unprotected by the name check, then during the import it starts the whole sequence over again, ad infinitum\n", "When I run this in Linux with python2.6, I see a maximum of 4 python2.6 processes and I can't guarantee that they're all from this process. They're definitely not filling up the machine.\nNeed new python version? Linux/Windows difference?\n", "I don't see anything wrong with that. Works fine on Ubuntu 9.10 (Python 2.6.4).\nAre you sure you don't have cron or something starting multiple copies of your script? Or that the spawned script is not calling anything that would start a new instance, for example as a side effect of import if your code runs directly on import?\n" ]
[ 23, 0, 0 ]
[]
[]
[ "multiprocessing", "python", "windows" ]
stackoverflow_0001923706_multiprocessing_python_windows.txt
Q: Couple of matplotlib newbie doubts I am just starting to use 'matplotlib' and I have hit upon 2 major roadblocks, which I can't seem to work around from the docs/examples,etc: Here is Python source: #!/usr/bin/python import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt for i in range(0,301): print "Plotting",i # Reading a single column data file l=plt.plotfile("gen"+str(i)) plt.xlabel('Population') plt.ylabel('Function Value') plt.title('Generation'+str(i)) plt.axis([0,500,0,180]) plt.plot() if len(str(i)) == 1: plt.savefig("../images/plot00"+str(i)+".png") if len(str(i)) == 2: plt.savefig("../images/plot0"+str(i)+".png") if len(str(i)) == 3: plt.savefig("../images/plot"+str(i)+".png") plt.clf() Doubt 1: As you can see, I am basically clearing the plot and then saving the new plot every time. I want to keep the range of the Y-axis constant and I am trying to do it via "plt.axis([0,500,0,180])". But it doesn;t seem to work and it is automatically set everytime. Doubt 2: Instead of obtaining the default plot in which the points are joined by continuous lines, I would prefer to obtain a plot of say, '*'. How would I do that? A: As Tim Pietzcker points out, you can shorten if filename code at the end by using string number formatting. filename='plot%03d.png'%i replaces %03d with the integer i padded with up to 3 zero's. In Python2.6+, one can do the same thing with the less pretty but more powerful new string formatting syntax: filename='plot{0:03d}.png'.format(i) To get the points plotted with stars, you can use the option marker='*'. And to get rid of the connecting lines, use linestyle='none'. plt.plotfile(...) plots a figure. The call to plt.plot() plots a second figure overlaid on top of the first figure. The call to plt.plot() seems to modify the axis dimensions, wiping out the effect of plt.axis(...). Fortunately, the fix is simple: simply don't call plt.plot(). You don't need it. #!/usr/bin/env python import matplotlib import matplotlib.pyplot as plt matplotlib.use('Agg') # This can also be set in ~/.matplotlib/matplotlibrc for i in range(0,3): print 'Plotting',i # Reading a single column data file plt.plotfile('gen%s'%i,linestyle='none', marker='*') plt.xlabel('Population') plt.ylabel('Function Value') plt.title('Generation%s'%i) plt.axis([0,500,0,180]) # This (old-style string formatting) also works, especial for Python versions <2.6: # filename='plot%03d.png'%i filename='plot{0:03d}.png'.format(i) print(filename) plt.savefig(filename) # plt.clf() # clear current figure
Couple of matplotlib newbie doubts
I am just starting to use 'matplotlib' and I have hit upon 2 major roadblocks, which I can't seem to work around from the docs/examples,etc: Here is Python source: #!/usr/bin/python import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt for i in range(0,301): print "Plotting",i # Reading a single column data file l=plt.plotfile("gen"+str(i)) plt.xlabel('Population') plt.ylabel('Function Value') plt.title('Generation'+str(i)) plt.axis([0,500,0,180]) plt.plot() if len(str(i)) == 1: plt.savefig("../images/plot00"+str(i)+".png") if len(str(i)) == 2: plt.savefig("../images/plot0"+str(i)+".png") if len(str(i)) == 3: plt.savefig("../images/plot"+str(i)+".png") plt.clf() Doubt 1: As you can see, I am basically clearing the plot and then saving the new plot every time. I want to keep the range of the Y-axis constant and I am trying to do it via "plt.axis([0,500,0,180])". But it doesn;t seem to work and it is automatically set everytime. Doubt 2: Instead of obtaining the default plot in which the points are joined by continuous lines, I would prefer to obtain a plot of say, '*'. How would I do that?
[ "\nAs Tim Pietzcker points out, you can shorten if filename code at the end by\nusing string number formatting.\nfilename='plot%03d.png'%i\n\nreplaces %03d with the integer i padded with up to 3 zero's.\nIn Python2.6+, one can do the same thing with the less pretty but more powerful new string formatting syntax:\nfilename='plot{0:03d}.png'.format(i)\n\n\nTo get the points plotted with stars, you can use the option marker='*'.\nAnd to get rid of the connecting lines, use linestyle='none'.\n\nplt.plotfile(...) plots a figure. The call to plt.plot() plots a second figure overlaid on top of the first figure. The call to plt.plot() seems to modify the axis dimensions, wiping out the effect of plt.axis(...). Fortunately, the fix is simple: simply don't call plt.plot(). You don't need it. \n\n\n#!/usr/bin/env python\nimport matplotlib\nimport matplotlib.pyplot as plt\n\nmatplotlib.use('Agg') # This can also be set in ~/.matplotlib/matplotlibrc\nfor i in range(0,3):\n print 'Plotting',i\n # Reading a single column data file\n plt.plotfile('gen%s'%i,linestyle='none', marker='*')\n\n plt.xlabel('Population')\n plt.ylabel('Function Value')\n plt.title('Generation%s'%i)\n plt.axis([0,500,0,180])\n # This (old-style string formatting) also works, especial for Python versions <2.6:\n # filename='plot%03d.png'%i\n filename='plot{0:03d}.png'.format(i)\n print(filename)\n plt.savefig(filename)\n # plt.clf() # clear current figure\n\n" ]
[ 2 ]
[]
[]
[ "matplotlib", "python", "scientific_computing" ]
stackoverflow_0001924323_matplotlib_python_scientific_computing.txt
Q: Inheritable custom exceptions in python I want to create some custom exceptions for my class. I am trying to figure out the best way to make these exception classes inheritable in derived classes. The tutorial shows how to create the Exception classes. So I did that like this: I created a baseclass.py: class Error(Exception): """Base class for exceptions in BaseClass""" pass class SomeError(Error): """Exection for some error""" def __init__(self, msg): self.msg = msg class OtherError(Error): """Exection for some error""" def __init__(self, msg): self.msg = msg class BaseClass(): """Base test class for testing exceptions""" def dosomething(self): raise SomeError, "Got an error doing something" And a derivedclass.py: from baseclass import BaseClass,SomeError,OtherError class DerivedClass(BaseClass): def doother(self): """Do other thing""" raise OtherError, "Error doing other" Then a test that uses the DerivedClass: #!/usr/bin/python from derivedclass import DerivedClass,SomeError,OtherError """Test from within module""" x = DerivedClass() try: x.dosomething() except SomeError: print "I got some error ok" try: x.doother() except OtherError: print "I got other error ok" So as you can see, I imported the exception classes from the base class into the derived class, then again from the derived class into the program. This seems to work ok, but is not very elegant, and I'm worried about having to make sure and do an import in the derived class module for all the Exception classes. It seems like it would be easy to forget one when creating a new derived class. Then a user of the derived class would get an error if they tried to use it. Is there a better way to do this? Thanks! -Mark A: The custom exceptions has to be imported in all modules its used in. Also, there is an error in derivedclass.py Wrong (because of the way its imported) raise baseclass.OtherError, "Error doing other" Fixed raise OtherError, "Error doing other" A: So as you can see, I imported the exception classes from the base class into the derived class, then again from the derived class into the program. You did not, and cannot, import exceptions (or anything) from classes and into classes. You import things from modules and (usually) into modules. (usually, because you can put import statements in any scope, but it is not recommended) This seems to work ok, but is not very elegant, and I'm worried about having to make sure and do an import in the derived class module for all the Exception classes. It seems like it would be easy to forget one when creating a new derived class. Then a user of the derived class would get an error if they tried to use it. There is no reason the module of the derived class would need to import all the exceptions from the base classes. If you want to make it easy for client code to know where to import exceptions from, just put all your exception in a separate module named "errors" or "exceptions", that's a common idiom in Python. Also, if you have trouble managing your namespace of exceptions, maybe your are being too fine-grained with your exceptions, and you could do with fewer exception classes. A: If the user imports your error classes by name, they'll notice the problem as soon as the import statement tries to execute: ImportError: cannot import name FrotzError File "enduser.py", line 7, in <module> from ptcmark.derivedclass import FrotzError And of course you'll document where they're supposed to get the exception classes from, so they'll just look it up and then change their code to do the right thing: from ptcmark.errors import FrotzError
Inheritable custom exceptions in python
I want to create some custom exceptions for my class. I am trying to figure out the best way to make these exception classes inheritable in derived classes. The tutorial shows how to create the Exception classes. So I did that like this: I created a baseclass.py: class Error(Exception): """Base class for exceptions in BaseClass""" pass class SomeError(Error): """Exection for some error""" def __init__(self, msg): self.msg = msg class OtherError(Error): """Exection for some error""" def __init__(self, msg): self.msg = msg class BaseClass(): """Base test class for testing exceptions""" def dosomething(self): raise SomeError, "Got an error doing something" And a derivedclass.py: from baseclass import BaseClass,SomeError,OtherError class DerivedClass(BaseClass): def doother(self): """Do other thing""" raise OtherError, "Error doing other" Then a test that uses the DerivedClass: #!/usr/bin/python from derivedclass import DerivedClass,SomeError,OtherError """Test from within module""" x = DerivedClass() try: x.dosomething() except SomeError: print "I got some error ok" try: x.doother() except OtherError: print "I got other error ok" So as you can see, I imported the exception classes from the base class into the derived class, then again from the derived class into the program. This seems to work ok, but is not very elegant, and I'm worried about having to make sure and do an import in the derived class module for all the Exception classes. It seems like it would be easy to forget one when creating a new derived class. Then a user of the derived class would get an error if they tried to use it. Is there a better way to do this? Thanks! -Mark
[ "The custom exceptions has to be imported in all modules its used in.\nAlso, there is an error in derivedclass.py\nWrong (because of the way its imported)\nraise baseclass.OtherError, \"Error doing other\"\n\nFixed\nraise OtherError, \"Error doing other\"\n\n", "\nSo as you can see, I imported the\n exception classes from the base class\n into the derived class, then again\n from the derived class into the\n program.\n\nYou did not, and cannot, import exceptions (or anything) from classes and into classes. You import things from modules and (usually) into modules.\n(usually, because you can put import statements in any scope, but it is not recommended)\n\nThis seems to work ok, but is not very\n elegant, and I'm worried about having\n to make sure and do an import in the\n derived class module for all the\n Exception classes. It seems like it\n would be easy to forget one when\n creating a new derived class. Then a\n user of the derived class would get an\n error if they tried to use it.\n\nThere is no reason the module of the derived class would need to import all the exceptions from the base classes. If you want to make it easy for client code to know where to import exceptions from, just put all your exception in a separate module named \"errors\" or \"exceptions\", that's a common idiom in Python.\nAlso, if you have trouble managing your namespace of exceptions, maybe your are being too fine-grained with your exceptions, and you could do with fewer exception classes.\n", "If the user imports your error classes by name, they'll notice the problem as soon as the import statement tries to execute:\nImportError: cannot import name FrotzError\nFile \"enduser.py\", line 7, in <module>\n from ptcmark.derivedclass import FrotzError\n\nAnd of course you'll document where they're supposed to get the exception classes from, so they'll just look it up and then change their code to do the right thing:\nfrom ptcmark.errors import FrotzError\n\n" ]
[ 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001924380_python.txt
Q: Linux group scheduling for user not being applied to setuid-ed process On the 2.6.28-11 Linux kernel, I am using setpriority to bias the amount of cpu time different user processes receive. User 1 is to receive double the CPU power of user 2. Using Linux's setpriority, I have assigned user 2 a lower priority (higher in terms of nice values). When I run the exact same program via the shell with the computer under load, user 2's execution takes twice as long as user 1's. However, if I run the program as root, and then use setuid, seteuid, setgid, setegid, and setgroups to become user 2 (once again the computer is under load with the exact same program being run by user 1 in the same manner), the programs take the exact same amount of time to execute; User 2's process was not being scheduled any less than user 1's. How can I get around this? Do I need to set anything else for the scheduler to realize that the process is now part of a different user? The program being run is in Python. A: Right, this is the designed behavior, even if it's not what you want. You can update your own priority to match what you should have inherited, if you were started normally: /* C */ #include <sys/resource.h> int proc_prio = getpriority(PRIO_PROCESS, getpid()), pgrp_prio = getpriority(PRIO_PGRP, getpgrp()), user_prio = getpriority(PRIO_USER, getuid()); setpriority(PRIO_PROCESS, getpid(), proc_prio < pgrp_prio ? pgrp_prio < user_prio ? user_prio : pgrp_prio : proc_prio < user_prio ? user_prio : proc_prio); # Python import ctypes import os PRIO_PROCESS, PRIO_PGRP, PRIO_USER = 0, 1, 2 libc = ctypes.CDLL('libc.so.6') libc.setpriority(PRIO_PROCESS, os.getpid(), max(libc.getpriority(PRIO_PROCESS, os.getpid()), libc.getpriority(PRIO_PGRP, os.getpgrp()), libc.getpriority(PRIO_USER, os.getuid()))) Or of course you could fix another process's priority, with appropriate privileges.
Linux group scheduling for user not being applied to setuid-ed process
On the 2.6.28-11 Linux kernel, I am using setpriority to bias the amount of cpu time different user processes receive. User 1 is to receive double the CPU power of user 2. Using Linux's setpriority, I have assigned user 2 a lower priority (higher in terms of nice values). When I run the exact same program via the shell with the computer under load, user 2's execution takes twice as long as user 1's. However, if I run the program as root, and then use setuid, seteuid, setgid, setegid, and setgroups to become user 2 (once again the computer is under load with the exact same program being run by user 1 in the same manner), the programs take the exact same amount of time to execute; User 2's process was not being scheduled any less than user 1's. How can I get around this? Do I need to set anything else for the scheduler to realize that the process is now part of a different user? The program being run is in Python.
[ "Right, this is the designed behavior, even if it's not what you want. You can update your own priority to match what you should have inherited, if you were started normally:\n/* C */\n#include <sys/resource.h>\nint proc_prio = getpriority(PRIO_PROCESS, getpid()),\n pgrp_prio = getpriority(PRIO_PGRP, getpgrp()),\n user_prio = getpriority(PRIO_USER, getuid());\nsetpriority(PRIO_PROCESS, getpid(),\n proc_prio < pgrp_prio ? pgrp_prio < user_prio ? user_prio\n : pgrp_prio\n : proc_prio < user_prio ? user_prio\n : proc_prio);\n\n# Python\nimport ctypes\nimport os\nPRIO_PROCESS, PRIO_PGRP, PRIO_USER = 0, 1, 2\nlibc = ctypes.CDLL('libc.so.6')\nlibc.setpriority(PRIO_PROCESS, os.getpid(),\n max(libc.getpriority(PRIO_PROCESS, os.getpid()),\n libc.getpriority(PRIO_PGRP, os.getpgrp()),\n libc.getpriority(PRIO_USER, os.getuid())))\n\nOr of course you could fix another process's priority, with appropriate privileges.\n" ]
[ 2 ]
[]
[]
[ "linux", "python", "scheduler", "scheduling", "setuid" ]
stackoverflow_0001920952_linux_python_scheduler_scheduling_setuid.txt
Q: get datatype length in python by parsing a string I have strings like uint8_t char[5] int[3] How can I write a short function to get the type and length separately in an elegant way for eg uint8_t // return 'uint8_t', '1' char[5] // return 'char', '5' ... A: Let's make it a one-liner: import re def type_and_size(s): return re.split('[][]', s+'[1]', 2)[:2] type_and_size('char') ['char', '1'] type_and_size('char[5]') ['char', '5'] Obviously you can do: type, size = type_and_size('char[5]') A: In [1]: import re In [2]: r = re.compile('([\w_]+)(?:\[(\d+)\])?') In [3]: m = r.match('char[5]') In [4]: m.group(1), m.group(2) or 1 Out[4]: ('char', '5') In [5]: m = r.match('uint8_t') In [6]: m.group(1), m.group(2) or 1 Out[6]: ('uint8_t', 1) Making a function is left as an exercise to the reader. A: import re def parse_type(text): match = re.match(r'(.+)\[(\d+)\]', text) if match: return match.groups() return text, 1 print parse_type('uint8_t') print parse_type('char[5]') print parse_type('int[3]') A: given these tests: >>> s = "char[5]" >>> p = s.split("[") >>> p ['char', '5]'] >>> p[1].strip("]") '5' >>> s = "uint8_t" >>> p = s.split("[") >>> p ['uint8_t'] >>> here's a little function that gives you what you want: def SplitNicely(s): p = s.split("[") if len(p) == 1: size = 1 else: size = int(p[1].strip("]")) return p[0], size more error checking would be useful too
get datatype length in python by parsing a string
I have strings like uint8_t char[5] int[3] How can I write a short function to get the type and length separately in an elegant way for eg uint8_t // return 'uint8_t', '1' char[5] // return 'char', '5' ...
[ "Let's make it a one-liner:\nimport re\n\ndef type_and_size(s):\n return re.split('[][]', s+'[1]', 2)[:2]\n\ntype_and_size('char')\n['char', '1']\n\ntype_and_size('char[5]')\n['char', '5']\n\nObviously you can do:\ntype, size = type_and_size('char[5]')\n\n", "In [1]: import re\nIn [2]: r = re.compile('([\\w_]+)(?:\\[(\\d+)\\])?')\nIn [3]: m = r.match('char[5]') \nIn [4]: m.group(1), m.group(2) or 1\nOut[4]: ('char', '5')\nIn [5]: m = r.match('uint8_t')\nIn [6]: m.group(1), m.group(2) or 1\nOut[6]: ('uint8_t', 1)\n\nMaking a function is left as an exercise to the reader.\n", "import re\n\ndef parse_type(text):\n match = re.match(r'(.+)\\[(\\d+)\\]', text)\n if match:\n return match.groups()\n return text, 1\n\nprint parse_type('uint8_t')\nprint parse_type('char[5]')\nprint parse_type('int[3]')\n\n", "given these tests:\n>>> s = \"char[5]\"\n>>> p = s.split(\"[\")\n>>> p\n['char', '5]']\n>>> p[1].strip(\"]\")\n'5'\n>>> s = \"uint8_t\"\n>>> p = s.split(\"[\")\n>>> p\n['uint8_t']\n>>>\n\nhere's a little function that gives you what you want:\ndef SplitNicely(s):\n p = s.split(\"[\")\n if len(p) == 1:\n size = 1\n else:\n size = int(p[1].strip(\"]\"))\n\n return p[0], size\n\nmore error checking would be useful too\n" ]
[ 3, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001924828_python.txt
Q: Linux USB Mapping Question I'm working on a utility that will auto mount an inserted USB stick on linux. I have tied into D-Bus to receive notification of when a device is inserted, and that works great. However, I need to determine which device in /dev is mapped to the inserted USB stick. I am getting the D-Bus notification and then scanning the USB system with pyUSB ( 0.4 ). I filter for USB_MASS_STORAGE_DEVICE classes, and I can see the device that's been added or removed. I need to mount this device so I can query it for available space and report that to our app so we can determine if enough free space exists so we can write our data. I'm using python for this task. I'm not sure what our target distro will be, only that it will be at least 2.6 edit: My question is: How do I determine which device in /dev maps to the buss-device number I get from pyUSB. A: You should probably ask HAL about that. You say you already get notifications from HAL by D-Bus... It maintains list of USB devices, together with their IDs and device names (block.device property). Here's a nice example of how to get device file name together with the notification of new USB device: How can I listen for 'usb device inserted' events in Linux, in Python? A: Why not use "os" module to mount the file system: os.system ("mount ... ") Or if you want to examine output use "popen": l = op.popen ("mount ....").readlines() A: what about using dmesg output to find out the device name (sdc1 etc...) use it right after dbus tells you something is was inserted in USB. you could do tail dmesg for example
Linux USB Mapping Question
I'm working on a utility that will auto mount an inserted USB stick on linux. I have tied into D-Bus to receive notification of when a device is inserted, and that works great. However, I need to determine which device in /dev is mapped to the inserted USB stick. I am getting the D-Bus notification and then scanning the USB system with pyUSB ( 0.4 ). I filter for USB_MASS_STORAGE_DEVICE classes, and I can see the device that's been added or removed. I need to mount this device so I can query it for available space and report that to our app so we can determine if enough free space exists so we can write our data. I'm using python for this task. I'm not sure what our target distro will be, only that it will be at least 2.6 edit: My question is: How do I determine which device in /dev maps to the buss-device number I get from pyUSB.
[ "You should probably ask HAL about that. You say you already get notifications from HAL by D-Bus... It maintains list of USB devices, together with their IDs and device names (block.device property).\nHere's a nice example of how to get device file name together with the notification of new USB device: How can I listen for 'usb device inserted' events in Linux, in Python?\n", "Why not use \"os\" module to mount the file system:\nos.system (\"mount ... \")\n\nOr if you want to examine output use \"popen\":\nl = op.popen (\"mount ....\").readlines()\n\n", "what about using dmesg output to find out the device name (sdc1 etc...)\nuse it right after dbus tells you something is was inserted in USB. you could do tail dmesg for example\n" ]
[ 2, 0, 0 ]
[]
[]
[ "dbus", "linux", "python", "usb" ]
stackoverflow_0001924646_dbus_linux_python_usb.txt
Q: XML/SWF charts example not working with cherryPy I am trying to use use the XML/SWF Charts library with cherrypy. I want to generate html reports with nice looking charts. I am trying to expose one of the default examples of XML/SWF charts with cherryPy, but for some reason the javascript is not working properly with cherryPy. I created the following python script: import os.path import os.path import cherrypy import os class index: def index(self): return open('sample.html', 'r') index.exposed = True if name == 'main': current_dir = os.path.dirname(os.path.abspath(file)) print current_dir print os.path.join(current_dir, 'data', 'scripts', 'AC_RunActiveContent.js') # Set up site-wide config first so we get a log if errors occur. cherrypy.config.update({'environment': 'production', 'log.error_file': 'site.log', 'log.screen': True}) conf = {'/js/AC_RunActiveContent.js': {'tools.staticfile.on': True, 'tools.staticfile.filename': os.path.join(current_dir, 'data', 'scripts', 'AC_RunActiveContent.js')}} cherrypy.quickstart(index(), '/', config=conf) I have the following directory structure: D:. +---charts_library +---data ¦ +---css ¦ +---scripts +---resources +---button_rollover +---chart_in_swf +---cursor +---full_screen +---preview_scroll +---scroll I put the javascript file and all files needed by the library in the .\data\scripts folder. (I also tried to put these files in the root folder but that didn't work either) the sample html file looks as follows: <HTML> <script language="javascript">AC_FL_RunContent = 0;</script> <script language="javascript"> DetectFlashVer = 0; </script> <script src="AC_RunActiveContent.js" language="javascript"></script> <script language="JavaScript" type="text/javascript"> <!-- var requiredMajorVersion = 9; var requiredMinorVersion = 0; var requiredRevision = 45; --> </script> <BODY bgcolor="#FFFFFF"> <script language="JavaScript" type="text/javascript"> <!-- if (AC_FL_RunContent == 0 || DetectFlashVer == 0) { alert("This page requires AC_RunActiveContent.js."); } else { var hasRightVersion = DetectFlashVer(requiredMajorVersion, requiredMinorVersion, requiredRevision); if(hasRightVersion) { AC_FL_RunContent( 'codebase', 'http: //download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,45,0', 'width', '400', 'height', '250', 'scale', 'noscale', 'salign', 'TL', 'bgcolor', '#777788', 'wmode', 'opaque', 'movie', 'charts', 'src', 'charts', 'FlashVars', 'library_path=charts_library&xml_source=sample.xml', 'id', 'my_chart', 'name', 'my_chart', 'menu', 'true', 'allowFullScreen', 'true', 'allowScriptAccess','sameDomain', 'quality', 'high', 'align', 'middle', 'pluginspage', 'http: //www.macromedia.com/go/getflashplayer', 'play', 'true', 'devicefont', 'false' ); } else { var alternateContent = 'This content requires the Adobe Flash Player. ' + '<u><a href=http: //www.macromedia.com/go/getflash/>Get Flash</a></u>.'; document.write(alternateContent); } } // --> </script> <noscript> <P>This content requires JavaScript.</P> </noscript> </BODY> </HTML> When I double click the sample file it works fine but when I run the python script and browse to the local host address on port 8080 then a popup keeps occuring which shows the following message: "This page requires AC_RunActiveContent.js" I think I did something wrong in my python script but I am not able to find out what I did wrong. Why is the javascript not working in cherryPy while it does work in the sample.html file? Did I forget something? A: conf = {'/js/AC_RunActiveContent.js': {'tools.staticfile.on': True, 'tools.staticfile.filename': os.path.join(current_dir, 'data', 'scripts', 'AC_RunActiveContent.js')}} And later <script src="AC_RunActiveContent.js" language="javascript"></script> My bet is the latter produces a 404. Try changing the line to: <script src="/js/AC_RunActiveContent.js" language="javascript"></script> Oh, and also your HTML could use a <HEAD> element.
XML/SWF charts example not working with cherryPy
I am trying to use use the XML/SWF Charts library with cherrypy. I want to generate html reports with nice looking charts. I am trying to expose one of the default examples of XML/SWF charts with cherryPy, but for some reason the javascript is not working properly with cherryPy. I created the following python script: import os.path import os.path import cherrypy import os class index: def index(self): return open('sample.html', 'r') index.exposed = True if name == 'main': current_dir = os.path.dirname(os.path.abspath(file)) print current_dir print os.path.join(current_dir, 'data', 'scripts', 'AC_RunActiveContent.js') # Set up site-wide config first so we get a log if errors occur. cherrypy.config.update({'environment': 'production', 'log.error_file': 'site.log', 'log.screen': True}) conf = {'/js/AC_RunActiveContent.js': {'tools.staticfile.on': True, 'tools.staticfile.filename': os.path.join(current_dir, 'data', 'scripts', 'AC_RunActiveContent.js')}} cherrypy.quickstart(index(), '/', config=conf) I have the following directory structure: D:. +---charts_library +---data ¦ +---css ¦ +---scripts +---resources +---button_rollover +---chart_in_swf +---cursor +---full_screen +---preview_scroll +---scroll I put the javascript file and all files needed by the library in the .\data\scripts folder. (I also tried to put these files in the root folder but that didn't work either) the sample html file looks as follows: <HTML> <script language="javascript">AC_FL_RunContent = 0;</script> <script language="javascript"> DetectFlashVer = 0; </script> <script src="AC_RunActiveContent.js" language="javascript"></script> <script language="JavaScript" type="text/javascript"> <!-- var requiredMajorVersion = 9; var requiredMinorVersion = 0; var requiredRevision = 45; --> </script> <BODY bgcolor="#FFFFFF"> <script language="JavaScript" type="text/javascript"> <!-- if (AC_FL_RunContent == 0 || DetectFlashVer == 0) { alert("This page requires AC_RunActiveContent.js."); } else { var hasRightVersion = DetectFlashVer(requiredMajorVersion, requiredMinorVersion, requiredRevision); if(hasRightVersion) { AC_FL_RunContent( 'codebase', 'http: //download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,45,0', 'width', '400', 'height', '250', 'scale', 'noscale', 'salign', 'TL', 'bgcolor', '#777788', 'wmode', 'opaque', 'movie', 'charts', 'src', 'charts', 'FlashVars', 'library_path=charts_library&xml_source=sample.xml', 'id', 'my_chart', 'name', 'my_chart', 'menu', 'true', 'allowFullScreen', 'true', 'allowScriptAccess','sameDomain', 'quality', 'high', 'align', 'middle', 'pluginspage', 'http: //www.macromedia.com/go/getflashplayer', 'play', 'true', 'devicefont', 'false' ); } else { var alternateContent = 'This content requires the Adobe Flash Player. ' + '<u><a href=http: //www.macromedia.com/go/getflash/>Get Flash</a></u>.'; document.write(alternateContent); } } // --> </script> <noscript> <P>This content requires JavaScript.</P> </noscript> </BODY> </HTML> When I double click the sample file it works fine but when I run the python script and browse to the local host address on port 8080 then a popup keeps occuring which shows the following message: "This page requires AC_RunActiveContent.js" I think I did something wrong in my python script but I am not able to find out what I did wrong. Why is the javascript not working in cherryPy while it does work in the sample.html file? Did I forget something?
[ "conf = {'/js/AC_RunActiveContent.js':\n {'tools.staticfile.on': True,\n 'tools.staticfile.filename':\n os.path.join(current_dir, 'data', 'scripts', 'AC_RunActiveContent.js')}}\n\nAnd later\n<script src=\"AC_RunActiveContent.js\" language=\"javascript\"></script>\n\nMy bet is the latter produces a 404. Try changing the line to:\n<script src=\"/js/AC_RunActiveContent.js\" language=\"javascript\"></script>\n\nOh, and also your HTML could use a <HEAD> element.\n" ]
[ 1 ]
[]
[]
[ "cherrypy", "javascript", "python", "xml_swf_charts" ]
stackoverflow_0001924973_cherrypy_javascript_python_xml_swf_charts.txt
Q: Use with form.fields.queryset? Is it possible to set a form's ForeignKey field's queryset so that it will take separate queryset's and output them in <optgroup>'s? Here is what I have: views.py form = TemplateFormBasic(initial={'template': digest.template.id}) form.fields['template'].queryset = Template.objects.filter(Q(default=1) | Q(user=request.user)).order_by('name') In my Template model, I have default Templates and User-created templates. I want them to be visibly separated in the <select> box eg. <select> <optgroup label="Default Templates"> <option>Default 1</option> <option>Default 2</option> </optgroup> <optgroup label="User Templates"> <option>User Template 1</option> <option>User Template 2</option> </optgroup> </select> Can this be done? A: I was able to figure it out using the example given on this blog views.py form.fields['template'].choices = templates_as_choices(request) def templates_as_choices(request): templates = [] default = [] user = [] for template in Template.objects.filter(default=1).order_by('name'): default.append([template.id, template.name]) for template in Template.objects.filter(user=request.user).order_by('name'): user.append([template.id, template.name]) templates.append(['Default Templates', default]) templates.append(['User Templates', user]) return templates A: I've done in the past by not using a foreign key on the form, but rather a charfield with choices. A CharField with choices support optgroups. You need to have the choices in this format: ('Group 1',(('1','Yada'),('2','Yada'))), ('Group 2',(('3','Bepety'),('4','Bopity'))) Choices can also be a callable. So I created my own function that traverses the models and builds a tuple like the above.
Use with form.fields.queryset?
Is it possible to set a form's ForeignKey field's queryset so that it will take separate queryset's and output them in <optgroup>'s? Here is what I have: views.py form = TemplateFormBasic(initial={'template': digest.template.id}) form.fields['template'].queryset = Template.objects.filter(Q(default=1) | Q(user=request.user)).order_by('name') In my Template model, I have default Templates and User-created templates. I want them to be visibly separated in the <select> box eg. <select> <optgroup label="Default Templates"> <option>Default 1</option> <option>Default 2</option> </optgroup> <optgroup label="User Templates"> <option>User Template 1</option> <option>User Template 2</option> </optgroup> </select> Can this be done?
[ "I was able to figure it out using the example given on this blog\nviews.py\nform.fields['template'].choices = templates_as_choices(request)\n\ndef templates_as_choices(request):\n templates = []\n default = []\n user = []\n for template in Template.objects.filter(default=1).order_by('name'):\n default.append([template.id, template.name])\n\n for template in Template.objects.filter(user=request.user).order_by('name'):\n user.append([template.id, template.name])\n\n templates.append(['Default Templates', default])\n templates.append(['User Templates', user])\n\n return templates\n\n", "I've done in the past by not using a foreign key on the form, but rather a charfield with choices.\nA CharField with choices support optgroups. You need to have the choices in this format:\n\n('Group 1',(('1','Yada'),('2','Yada'))), ('Group 2',(('3','Bepety'),('4','Bopity')))\n\nChoices can also be a callable. So I created my own function that traverses the models and builds a tuple like the above.\n" ]
[ 10, 4 ]
[]
[]
[ "django", "django_forms", "django_queryset", "python" ]
stackoverflow_0001924704_django_django_forms_django_queryset_python.txt
Q: python, convert a dictionary to a sorted list by value instead of key I have a collections.defaultdict(int) that I'm building to keep count of how many times a key shows up in a set of data. I later want to be able to sort it (obviously by turning it into a list first) in a descending fashion, ordered with the highest values first. I created my dictionary like the following: adict = defaultdict(int) later on I do a bunch of: adict['someval'] += 1 adict['anotherval'] +=1 adict['someval'] += 1 Ideally after that I'd like to get a print out of: someval => 2 anotherval => 1 A: A dict's keys, reverse-sorted by the corresponding values, can best be gotten as sorted(adict, key=adict.get, reverse=True) since you want key/value pairs, you could work on the items as all other answers suggest, or (to use the nifty adict.get bound method instead of itemgetters or weird lambdas;-), [(k, adict[k]) for k in sorted(adict, key=adict.get, reverse=True)] Edit: in terms of performance, there isn't much into it either way: $ python -mtimeit -s'adict=dict((x,x**2) for x in range(-5,6))' '[(k, adict[k]) for k in sorted(adict, key=adict.get, reverse=True)]' 100000 loops, best of 3: 10.8 usec per loop $ python -mtimeit -s'adict=dict((x,x**2) for x in range(-5,6)); from operator import itemgetter' 'sorted(adict.iteritems(), key=itemgetter(1), reverse=True)' 100000 loops, best of 3: 9.66 usec per loop $ python -mtimeit -s'adict=dict((x,x**2) for x in range(-5,6))' 'sorted(adict.iteritems(), key=lambda (k,v): v, reverse=True)' 100000 loops, best of 3: 11.5 usec per loop So, the .get-based solution is smack midway in performance between the two items-based ones -- slightly slower than the itemgetter, slightly faster than the lambda. In "bottleneck" cases, where those microsecond fractions are crucial to you, by all means do focus on that. In normal cases, where this operation is only one step within some bigger task and a microsecond more or less matters little, focusing on the simplicity of the get idiom is, however, also a reasonable alternative. A: To get the dictionary sorted: from operator import itemgetter sorted(adict.iteritems(), key=itemgetter(1), reverse=True) A: Just sort the resulting dict by values: for k, v in sorted(adict.items(), key=lambda kv: kv[1], reverse=True): print("%s => %s" % (k,v)) A: Note: I'm putting this in as an answer so that it gets seen. I don't want upvotes. If you want to upvote anyone, upvote Nadia. The currently accepted answer gives timing results which are based on a trivially small dataset (size == 6 - (-5) == 11). The differences in cost of the various methods are masked by the overhead. A use case like what are the most frequent words in a text or most frequent names in a membership list or census involves much larger datasets. Repeating the experiment with range(-n,n+1) (Windows box, Python 2.6.4, all times in microseconds): n=5: 11.5, 9.34, 11.3 n=50: 65.5, 46.2, 68.1 n=500: 612, 423, 614 These results are NOT "slightly" different. The itemgetter answer is a clear winner on speed. There was also mention of "the simplicity of the get idiom". Putting them close together for ease of comparison: [(k, adict[k]) for k in sorted(adict, key=adict.get, reverse=True)] sorted(adict.iteritems(), key=itemgetter(1), reverse=True) The get idiom not only looks up the dict twice (as J. F. Sebastian has pointed out), it makes one list (result of sorted()) then iterates over that list to create a result list. I'd call that baroque, not simple. YMMV. A: from collections import defaultdict adict = defaultdict(int) adict['a'] += 1 adict['b'] += 3 adict['c'] += 5 adict['d'] += 2 for key, value in sorted(adict.items(), lambda a, b: cmp(a[1], b[1]), reverse=True): print "%r => %r" % (key, value) >>> 'c' => 5 'b' => 3 'd' => 2 'a' => 1   A: If you're using the newest python 2.7 alpha, then you can use the Counter class in collections module: c = Counter() c['someval'] += 1 c['anotherval'] += 1 c['someval'] += 1 print c.most_common() prints in the correct order: [('someval', 2), ('anotherval', 1)] The code used on 2.7 is available already and there's a version adapted to 2.5. Perhaps you want to use it to stay forward compatible with the native stdlib version that is about to be released. A: "Invert" a dictionary. from collections import defaultdict inv_dict = defaultdict( list ) for key, value in adict: inv_dict[value].append( key ) max_value= max( inv_dict.keys() ) The set of keys with the maximum occurrence -- inv_dict[max_value] The set of keys in descending order by occurrence -- for value, key_list in sorted( inv_dict ): print key_list, value
python, convert a dictionary to a sorted list by value instead of key
I have a collections.defaultdict(int) that I'm building to keep count of how many times a key shows up in a set of data. I later want to be able to sort it (obviously by turning it into a list first) in a descending fashion, ordered with the highest values first. I created my dictionary like the following: adict = defaultdict(int) later on I do a bunch of: adict['someval'] += 1 adict['anotherval'] +=1 adict['someval'] += 1 Ideally after that I'd like to get a print out of: someval => 2 anotherval => 1
[ "A dict's keys, reverse-sorted by the corresponding values, can best be gotten as\nsorted(adict, key=adict.get, reverse=True)\n\nsince you want key/value pairs, you could work on the items as all other answers suggest, or (to use the nifty adict.get bound method instead of itemgetters or weird lambdas;-),\n[(k, adict[k]) for k in sorted(adict, key=adict.get, reverse=True)]\n\nEdit: in terms of performance, there isn't much into it either way:\n$ python -mtimeit -s'adict=dict((x,x**2) for x in range(-5,6))' '[(k, adict[k]) for k in sorted(adict, key=adict.get, reverse=True)]'\n100000 loops, best of 3: 10.8 usec per loop\n$ python -mtimeit -s'adict=dict((x,x**2) for x in range(-5,6)); from operator import itemgetter' 'sorted(adict.iteritems(), key=itemgetter(1), reverse=True)'\n100000 loops, best of 3: 9.66 usec per loop\n$ python -mtimeit -s'adict=dict((x,x**2) for x in range(-5,6))' 'sorted(adict.iteritems(), key=lambda (k,v): v, reverse=True)'\n100000 loops, best of 3: 11.5 usec per loop\n\nSo, the .get-based solution is smack midway in performance between the two items-based ones -- slightly slower than the itemgetter, slightly faster than the lambda. In \"bottleneck\" cases, where those microsecond fractions are crucial to you, by all means do focus on that. In normal cases, where this operation is only one step within some bigger task and a microsecond more or less matters little, focusing on the simplicity of the get idiom is, however, also a reasonable alternative.\n", "To get the dictionary sorted:\nfrom operator import itemgetter\n\nsorted(adict.iteritems(), key=itemgetter(1), reverse=True)\n\n", "Just sort the resulting dict by values:\nfor k, v in sorted(adict.items(), key=lambda kv: kv[1], reverse=True):\n print(\"%s => %s\" % (k,v))\n\n", "Note: I'm putting this in as an answer so that it gets seen. I don't want upvotes. If you want to upvote anyone, upvote Nadia.\nThe currently accepted answer gives timing results which are based on a trivially small dataset (size == 6 - (-5) == 11). The differences in cost of the various methods are masked by the overhead. A use case like what are the most frequent words in a text or most frequent names in a membership list or census involves much larger datasets.\nRepeating the experiment with range(-n,n+1) (Windows box, Python 2.6.4, all times in microseconds):\nn=5: 11.5, 9.34, 11.3\nn=50: 65.5, 46.2, 68.1\nn=500: 612, 423, 614 \nThese results are NOT \"slightly\" different. The itemgetter answer is a clear winner on speed.\nThere was also mention of \"the simplicity of the get idiom\". Putting them close together for ease of comparison:\n[(k, adict[k]) for k in sorted(adict, key=adict.get, reverse=True)]\nsorted(adict.iteritems(), key=itemgetter(1), reverse=True)\nThe get idiom not only looks up the dict twice (as J. F. Sebastian has pointed out), it makes one list (result of sorted()) then iterates over that list to create a result list. I'd call that baroque, not simple. YMMV.\n", "from collections import defaultdict\nadict = defaultdict(int)\n\nadict['a'] += 1\nadict['b'] += 3\nadict['c'] += 5\nadict['d'] += 2\n\nfor key, value in sorted(adict.items(), lambda a, b: cmp(a[1], b[1]), reverse=True):\n print \"%r => %r\" % (key, value)\n\n>>> \n'c' => 5\n'b' => 3\n'd' => 2\n'a' => 1\n\n \n", "If you're using the newest python 2.7 alpha, then you can use the Counter class in collections module:\nc = Counter()\n\nc['someval'] += 1\nc['anotherval'] += 1\nc['someval'] += 1\n\nprint c.most_common()\n\nprints in the correct order:\n[('someval', 2), ('anotherval', 1)]\n\nThe code used on 2.7 is available already and there's a version adapted to 2.5. Perhaps you want to use it to stay forward compatible with the native stdlib version that is about to be released.\n", "\"Invert\" a dictionary.\nfrom collections import defaultdict\ninv_dict = defaultdict( list )\nfor key, value in adict:\n inv_dict[value].append( key )\nmax_value= max( inv_dict.keys() )\n\nThe set of keys with the maximum occurrence -- \ninv_dict[max_value] \n\nThe set of keys in descending order by occurrence --\nfor value, key_list in sorted( inv_dict ):\n print key_list, value\n\n" ]
[ 47, 43, 6, 3, 2, 2, 0 ]
[]
[]
[ "python", "sorting" ]
stackoverflow_0001915564_python_sorting.txt
Q: Python, Ruby, Haskell - Do they provide true multithreading? We are planning to write a highly concurrent application in any of the Very-High Level programming languages. 1) Do Python, Ruby, or Haskell support true multithreading? 2) If a program contains threads, will a Virtual Machine automatically assign work to multiple cores (or to physical CPUs if there is more than 1 CPU on the mainboard)? True multithreading = multiple independent threads of execution utilize the resources provided by multiple cores (not by only 1 core). False multithreading = threads emulate multithreaded environments without relying on any native OS capabilities. A: 1) Do Python, Ruby, or Haskell support true multithreading? This has nothing to do with the language. It is a question of the hardware (if the machine only has 1 CPU, it is simply physically impossible to execute two instructions at the same time), the Operating System (again, if the OS doesn't support true multithreading, there is nothing you can do) and the language implementation / execution engine. Unless the language specification explicitly forbids or enforces true multithreading, this has absolutely nothing whatsoever to do with the language. All the languages that you mention, plus all the languages that have been mentioned in the answers so far, have multiple implementations, some of which support true multithreading, some don't, and some are built on top of other execution engines which might or might not support true multithreading. Take Ruby, for example. Here are just some of its implementations and their threading models: MRI: green threads, no true multithreading YARV: OS threads, no true multithreading Rubinius: OS threads, true multithreading MacRuby: OS threads, true multithreading JRuby, XRuby: JVM threads, depends on the JVM (if the JVM supports true multithreading, then JRuby/XRuby does, too, if the JVM doesn't, then there's nothing they can do about it) IronRuby, Ruby.NET: just like JRuby, XRuby, but on the CLI instead of on the JVM See also my answer to another similar question about Ruby. (Note that that answer is more than a year old, and some of it is no longer accurate. Rubinius, for example, uses truly concurrent native threads now, instead of truly concurrent green threads. Also, since then, several new Ruby implementations have emerged, such as BlueRuby, tinyrb, Ruby Go Lightly, Red Sun and SmallRuby.) Similar for Python: CPython: native threads, no true multithreading PyPy: native threads, depends on the execution engine (PyPy can run natively, or on top of a JVM, or on top of a CLI, or on top of another Python execution engine. Whenever the underlying platform supports true multithreading, PyPy does, too.) Unladen Swallow: native threads, currently no true multithreading, but fix is planned Jython: JVM threads, see JRuby IronPython: CLI threads, see IronRuby For Haskell, at least the Glorious Glasgow Haskell Compiler supports true multithreading with native threads. I don't know about UHC, LHC, JHC, YHC, HUGS or all the others. For Erlang, both BEAM and HiPE support true multithreading with green threads. 2) If a program contains threads, will a Virtual Machine automatically assign work to multiple cores (or to physical CPUs if there is more than 1 CPU on the mainboard)? Again: this depends on the Virtual Machine, the Operating System and the hardware. Also, some of the implementations mentioned above, don't even have Virtual Machines. A: The Haskell implementation, GHC, supports multiple mechanisms for parallel execution on shared memory multicore. These mechanisms are described in "Runtime Support for Multicore Haskell". Concretely, the Haskell runtime divides work be N OS threads, distributed over the available compute cores. These N OS threads in turn run M lightweight Haskell threads (sometimes millions of them). In turn, each Haskell thread can take work for a spark queue (there may be billions of sparks). Like so: The runtime schedules work to be executed on separate cores, migrates work, and load balances. The garbage collector is also a parallel one, using each core to collect part of the heap. Unlike Python or Ruby, there's no global interpreter lock, so for that, and other reasons, GHC is particularly good on mulitcore in comparison, e.g. Haskell v Python on the multicore shootout A: The GHC compiler will run your program on multiple OS threads (and thus multiple cores) if you compile with the -threaded option and then pass +RTS -N<x> -RTS at runtime, where <x> = the number of OS threads you want. A: The current version of Ruby 1.9(YARV- C based version) has native threads but has the problem of GIL. As I know Python also has the problem of GIL. However both Jython and JRuby(mature Java implementations of both Ruby and Python) provide native multithreading, no green threads and no GIL. Don't know about Haskell. A: Haskell is thread-capable, in addition you get pure functional language - no side effects A: For real concurrency, you probably want to try Erlang. A: I second the choice of Erlang. Erlang can support distributed highly concurrent programming out of the box. Does not matter whether you callit "multi-threading" or "multi-processing". Two important elements to consider are the level of concurrency and the fact that Erlang processes do not share state. No shared state among processes is a good thing.
Python, Ruby, Haskell - Do they provide true multithreading?
We are planning to write a highly concurrent application in any of the Very-High Level programming languages. 1) Do Python, Ruby, or Haskell support true multithreading? 2) If a program contains threads, will a Virtual Machine automatically assign work to multiple cores (or to physical CPUs if there is more than 1 CPU on the mainboard)? True multithreading = multiple independent threads of execution utilize the resources provided by multiple cores (not by only 1 core). False multithreading = threads emulate multithreaded environments without relying on any native OS capabilities.
[ "\n1) Do Python, Ruby, or Haskell support true multithreading?\n\nThis has nothing to do with the language. It is a question of the hardware (if the machine only has 1 CPU, it is simply physically impossible to execute two instructions at the same time), the Operating System (again, if the OS doesn't support true multithreading, there is nothing you can do) and the language implementation / execution engine.\nUnless the language specification explicitly forbids or enforces true multithreading, this has absolutely nothing whatsoever to do with the language.\nAll the languages that you mention, plus all the languages that have been mentioned in the answers so far, have multiple implementations, some of which support true multithreading, some don't, and some are built on top of other execution engines which might or might not support true multithreading.\nTake Ruby, for example. Here are just some of its implementations and their threading models:\n\nMRI: green threads, no true multithreading\nYARV: OS threads, no true multithreading\nRubinius: OS threads, true multithreading\nMacRuby: OS threads, true multithreading\nJRuby, XRuby: JVM threads, depends on the JVM (if the JVM supports true multithreading, then JRuby/XRuby does, too, if the JVM doesn't, then there's nothing they can do about it)\nIronRuby, Ruby.NET: just like JRuby, XRuby, but on the CLI instead of on the JVM\n\nSee also my answer to another similar question about Ruby. (Note that that answer is more than a year old, and some of it is no longer accurate. Rubinius, for example, uses truly concurrent native threads now, instead of truly concurrent green threads. Also, since then, several new Ruby implementations have emerged, such as BlueRuby, tinyrb, Ruby Go Lightly, Red Sun and SmallRuby.)\nSimilar for Python:\n\nCPython: native threads, no true multithreading\nPyPy: native threads, depends on the execution engine (PyPy can run natively, or on top of a JVM, or on top of a CLI, or on top of another Python execution engine. Whenever the underlying platform supports true multithreading, PyPy does, too.)\nUnladen Swallow: native threads, currently no true multithreading, but fix is planned\nJython: JVM threads, see JRuby\nIronPython: CLI threads, see IronRuby\n\nFor Haskell, at least the Glorious Glasgow Haskell Compiler supports true multithreading with native threads. I don't know about UHC, LHC, JHC, YHC, HUGS or all the others.\nFor Erlang, both BEAM and HiPE support true multithreading with green threads.\n\n2) If a program contains threads, will a Virtual Machine automatically assign work to multiple cores (or to physical CPUs if there is more than 1 CPU on the mainboard)?\n\nAgain: this depends on the Virtual Machine, the Operating System and the hardware. Also, some of the implementations mentioned above, don't even have Virtual Machines.\n", "The Haskell implementation, GHC, supports multiple mechanisms for parallel execution on shared memory multicore. These mechanisms are described in \"Runtime Support for Multicore Haskell\".\nConcretely, the Haskell runtime divides work be N OS threads, distributed over the available compute cores. These N OS threads in turn run M lightweight Haskell threads (sometimes millions of them). In turn, each Haskell thread can take work for a spark queue (there may be billions of sparks). Like so:\n\nThe runtime schedules work to be executed on separate cores, migrates work, and load balances. The garbage collector is also a parallel one, using each core to collect part of the heap.\nUnlike Python or Ruby, there's no global interpreter lock, so for that, and other reasons, GHC is particularly good on mulitcore in comparison, e.g. Haskell v Python on the multicore shootout\n", "The GHC compiler will run your program on multiple OS threads (and thus multiple cores) if you compile with the -threaded option and then pass +RTS -N<x> -RTS at runtime, where <x> = the number of OS threads you want.\n", "The current version of Ruby 1.9(YARV- C based version) has native threads but has the problem of GIL. As I know Python also has the problem of GIL. \nHowever both Jython and JRuby(mature Java implementations of both Ruby and Python) provide native multithreading, no green threads and no GIL. \nDon't know about Haskell.\n", "Haskell is thread-capable, in addition you get pure functional language - no side effects \n", "For real concurrency, you probably want to try Erlang.\n", "I second the choice of Erlang. Erlang can support distributed highly concurrent programming out of the box. Does not matter whether you callit \"multi-threading\" or \"multi-processing\". Two important elements to consider are the level of concurrency and the fact that Erlang processes do not share state. \nNo shared state among processes is a good thing.\n" ]
[ 34, 22, 16, 7, 1, 1, 1 ]
[ "Haskell is suitable for anything.\npython has processing module, which (I think - not sure) helps to avoid GIL problems. (so it suitable for anything too). \nBut my opinion - best way you can do is to select highest level possible language with static type system for big and huge things. Today this languages are: ocaml, haskell, erlang.\nIf you want to develop small thing - python is good. But when things become bigger - all python benefits are eaten by miriads of tests.\nI didn't use ruby. I still thinking that ruby is a toy language. (Or at least there's no reason to teach ruby when you know python - better to read SICP book).\n" ]
[ -2 ]
[ "concurrency", "haskell", "multithreading", "python", "ruby" ]
stackoverflow_0001920805_concurrency_haskell_multithreading_python_ruby.txt
Q: declaring empty class member in python i am trying to read a tree structure file in python. I created a class to hold the tree objects. One of the members should hold the parent object. Since the parentObject member is of the same type as the class itself, I need to declare this as an empty variable of type "self". How do I do that in python? Thank you very much for your help. A: Since the parentObject member is of the same type as the class itself, I need to declare this as an empty variable of type "self". No, you do not need to declare anything in Python. You just define things. And self is not a type, but the conventional name for the first parameter of instance methods, which is set by the language to the object of the method. Here's an example: class Tree(object): def __init__(self, label=None): self.label = label self.parent = None self.children = [] def append(self, node): self.children.append(node) node.parent = self And here's how that could be used: empty_tree = Tree() simple_tree = Tree() simple_tree.append(Tree('hello')) simple_tree.append(Tree('world')) A: In Python, you don't declare variables as having any type. You just assign to them. A single variable can be assigned objects of different types in succession, if you wanted to do so. "self" is not the type but a naming convention used to refer to the current object, like "this" in Java / C++ (except in Python you could call it anything you wanted). A: I assume that for the root node, you want such an object. It's much more Pythonic to say: self.parent = None in your root object, than to create an empty object of type self.__class__. For every other node object in the tree, self.parent should refer to the actual parent node. Remember, in Python you don't have 'variables', you have objects, and there is no need for self.parent to be of same type in all the instances of a class.
declaring empty class member in python
i am trying to read a tree structure file in python. I created a class to hold the tree objects. One of the members should hold the parent object. Since the parentObject member is of the same type as the class itself, I need to declare this as an empty variable of type "self". How do I do that in python? Thank you very much for your help.
[ "\nSince the parentObject member is of\n the same type as the class itself, I\n need to declare this as an empty\n variable of type \"self\".\n\nNo, you do not need to declare anything in Python. You just define things.\nAnd self is not a type, but the conventional name for the first parameter of instance methods, which is set by the language to the object of the method.\nHere's an example:\nclass Tree(object):\n\n def __init__(self, label=None):\n self.label = label\n self.parent = None\n self.children = []\n\n def append(self, node):\n self.children.append(node)\n node.parent = self\n\nAnd here's how that could be used:\nempty_tree = Tree()\n\nsimple_tree = Tree()\nsimple_tree.append(Tree('hello'))\nsimple_tree.append(Tree('world'))\n\n", "In Python, you don't declare variables as having any type. You just assign to them. A single variable can be assigned objects of different types in succession, if you wanted to do so. \"self\" is not the type but a naming convention used to refer to the current object, like \"this\" in Java / C++ (except in Python you could call it anything you wanted).\n", "I assume that for the root node, you want such an object. It's much more Pythonic to say:\nself.parent = None\n\nin your root object, than to create an empty object of type self.__class__. For every other node object in the tree, self.parent should refer to the actual parent node.\nRemember, in Python you don't have 'variables', you have objects, and there is no need for self.parent to be of same type in all the instances of a class.\n" ]
[ 9, 7, 6 ]
[]
[]
[ "python", "variables" ]
stackoverflow_0001925246_python_variables.txt
Q: Searching a file in 3 different ways I have been writing a program that searches a file in 3 different ways. But firstly, to choose which search program to use is differentiated in the command line. For example in the command line I type: Program 1 search: python file.py 'search_term' 'file-to-be-searched' program 2 search: python file.py -z 'number' 'search_term' 'file-to-be-searched' program 3 search: python file.py -x 'search_term' 'file-to-be-searched' All 3 search scripts are in the file.py. The coding I have so far is: import re import sys #program 1 search_term = sys.argv[1] f = sys.argv[2] for line in open(f, 'r'): if re.search(search_term, line): print line, # Program 2 flag = sys.argv[1] num = sys.argv[2] search_term = sys.argv[3] f = sys.argv[4] #program 3 flag = sys.argv[1] search_term = sys.argv[2] f = sys.argv[3] for line in open(f, 'r'): if re.match(search_term, line): print line, Program 1 works fine thats no problem. Program 2, finds the search-term in the file and prints out a number of lines before and after it defined by the 'number' parameter, but i have no idea about how to do this. Program 3 finds the exact match from the search-term and prints out all the lines after the search_term. re.match is inadequate because it only searches from the beginning of a string it does not consider the rest. My final problem how would I differentiate between the three programs? using the flags or no flag from the command line? Any help would be appreciated. Thanks A: First of all you should look at two very useful Python modules: fileinput: Iterate over lines from multiple input streams optparse: A powerful command line option parser fileinput will help you read lines from several files and even modify them if you need. You'll program will be much easier to extend and read with these tools Here is an example: import fileinput import optparse if __name__ == '__main__': parser = optparse.OptionParser() parser.add_option("-z", dest="z", help="Description here") parser.add_option("-x", dest="x", help="Description here") options, args = parser.parse_args() search_term = args[0] for line in fileinput.input(args[1:]): process(line) For matching you can use re.search instead of re.match. An example from the docs: >>> re.match("o", "dog") # No match as "o" is not the first letter of "dog". >>> re.search("o", "dog") # Match as search() looks everywhere in the string. <_sre.SRE_Match object at ...> Edit: answering Jessica's comment say for example in my in my file i had the words: zoo, zoos and zoological. If i typed zoo as my search type all 3 would be retured rather than just zo0 You could wrap the search term in \b to only match the word for example: >>> re.search(r'\bzoo\b', 'test zoo') <_sre.SRE_Match object at 0xb75706e8> >>> re.search(r'\bzoo\b', 'test zoos') >>> re.search(r'\bzoo\b', 'test zoological') \b matches an empty string, but only at the beginning or end of a word. So in your script you can do this: searchterm = r'\b%s\b' % searchterm Note: the r here is important otherwise you have to escape the '\' A: Maybe it's a little to heavy for a short script, but in pythons standard library, you'll encounter the getopt and the more convenient optparse module. getopt This module helps scripts to parse the command line arguments in sys.argv. optparse is a more convenient, flexible, and powerful library for parsing command-line options than the old getopt module. optparse uses a more declarative style of command-line parsing: you create an instance of OptionParser, populate it with options, and parse the command line. optparse allows users to specify options in the conventional GNU/POSIX syntax, and additionally generates usage and help messages for you.
Searching a file in 3 different ways
I have been writing a program that searches a file in 3 different ways. But firstly, to choose which search program to use is differentiated in the command line. For example in the command line I type: Program 1 search: python file.py 'search_term' 'file-to-be-searched' program 2 search: python file.py -z 'number' 'search_term' 'file-to-be-searched' program 3 search: python file.py -x 'search_term' 'file-to-be-searched' All 3 search scripts are in the file.py. The coding I have so far is: import re import sys #program 1 search_term = sys.argv[1] f = sys.argv[2] for line in open(f, 'r'): if re.search(search_term, line): print line, # Program 2 flag = sys.argv[1] num = sys.argv[2] search_term = sys.argv[3] f = sys.argv[4] #program 3 flag = sys.argv[1] search_term = sys.argv[2] f = sys.argv[3] for line in open(f, 'r'): if re.match(search_term, line): print line, Program 1 works fine thats no problem. Program 2, finds the search-term in the file and prints out a number of lines before and after it defined by the 'number' parameter, but i have no idea about how to do this. Program 3 finds the exact match from the search-term and prints out all the lines after the search_term. re.match is inadequate because it only searches from the beginning of a string it does not consider the rest. My final problem how would I differentiate between the three programs? using the flags or no flag from the command line? Any help would be appreciated. Thanks
[ "First of all you should look at two very useful Python modules:\n\nfileinput: Iterate over lines\nfrom multiple input streams\noptparse: A powerful command\nline option parser\n\nfileinput will help you read lines from several files and even modify them if you need. You'll program will be much easier to extend and read with these tools\nHere is an example:\nimport fileinput\nimport optparse\n\nif __name__ == '__main__':\n parser = optparse.OptionParser()\n parser.add_option(\"-z\", dest=\"z\", help=\"Description here\")\n parser.add_option(\"-x\", dest=\"x\", help=\"Description here\")\n options, args = parser.parse_args()\n search_term = args[0]\n for line in fileinput.input(args[1:]):\n process(line)\n\nFor matching you can use re.search instead of re.match. An example from the docs:\n>>> re.match(\"o\", \"dog\") # No match as \"o\" is not the first letter of \"dog\".\n>>> re.search(\"o\", \"dog\") # Match as search() looks everywhere in the string.\n<_sre.SRE_Match object at ...>\n\n\nEdit: answering Jessica's comment\n\nsay for example in my in my file i had\n the words: zoo, zoos and zoological.\n If i typed zoo as my search type all 3\n would be retured rather than just zo0\n\nYou could wrap the search term in \\b to only match the word for example:\n>>> re.search(r'\\bzoo\\b', 'test zoo')\n<_sre.SRE_Match object at 0xb75706e8>\n>>> re.search(r'\\bzoo\\b', 'test zoos')\n>>> re.search(r'\\bzoo\\b', 'test zoological')\n\n\\b matches an empty string, but only at the beginning or end of a word.\nSo in your script you can do this:\nsearchterm = r'\\b%s\\b' % searchterm\n\nNote: the r here is important otherwise you have to escape the '\\'\n", "Maybe it's a little to heavy for a short script, but in pythons standard library, you'll encounter the getopt and the more convenient optparse module.\n\ngetopt This module helps scripts to parse the command line arguments in sys.argv.\noptparse is a more convenient, flexible, and powerful library for parsing command-line options than the old getopt module. optparse uses a more declarative style of command-line parsing: you create an instance of OptionParser, populate it with options, and parse the command line. optparse allows users to specify options in the conventional GNU/POSIX syntax, and additionally generates usage and help messages for you.\n\n" ]
[ 3, 1 ]
[]
[]
[ "file", "python", "search" ]
stackoverflow_0001925284_file_python_search.txt