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: html/javascript automaticly getting link from submit button (maybe automating with python?) I have a website where I have to click a submit button on a form. This gives me a link. I know the link is made up with the paramter that is passed through a hidden value. I was wondering if I could make a python script or something else that would go to the website and click some buttons returning the link that the submit button generates, if so how could I pass the extra parameter that influences the creation of the link? thanks in advance. A: If it is python you're looking for then give the Mechanize library a shot. If you are just extracting small but unique elements of the HTML document then you may as well use regex's with python. To work with the HTML document more pragmatically then BeautifulSoup may be more beneficial, which you can combine with mechanize/python. It's more straightforward than it may initially seem. A: Take a look at this documentation of the urlib2 package. Below is the code you would use, but the documentation explains (very well) what is happening. Excerpt: import urllib import urllib2 url = 'http://www.someserver.com/cgi-bin/register.cgi' values = {'name' : 'Michael Foord', 'location' : 'Northampton', 'language' : 'Python' } data = urllib.urlencode(values) req = urllib2.Request(url, data) response = urllib2.urlopen(req) the_page = response.read() You would need to use an HTML parser like BeautifulSoup to obtain the parameter name and value that is being posted when you click the button. Edit: Yes, you could use mechanize for this as well. You would do something like this (untested): from mechanize import Browser br = Browser() br.open("http://www.example.com/") # this would be your website br.select_form(name="order") # change this to the name of your form response = br.submit() # submits the form, just like if you clicked the submit button print response.geturl() # prints the URL you are looking for You'll need to make this specific to your website/form, but something along these lines should do the trick. Check out the examples/documentation for the ClientForm object if you find you need more control. A: Once you have downloaded your html data with mechanize as other users said, then you could use Beautifulsoup like this: from BeautifulSoup import BeautifulSoup soup = BeautifulSoup(html_data) hidden_tag = soup.find('input',name='hiddenId',type='hidden') hidden_value = hiddenId['value'] then you could forge a POST with urllib2 like this: import urllib import urllib2 url = 'http://yoursite.com' values = {'yourhiddenname' : hidden_value} request = urllib2.Request(url, urllib.urlencode(values)) response = urllib2.urlopen(request) result = response.read()
html/javascript automaticly getting link from submit button (maybe automating with python?)
I have a website where I have to click a submit button on a form. This gives me a link. I know the link is made up with the paramter that is passed through a hidden value. I was wondering if I could make a python script or something else that would go to the website and click some buttons returning the link that the submit button generates, if so how could I pass the extra parameter that influences the creation of the link? thanks in advance.
[ "If it is python you're looking for then give the Mechanize library a shot. If you are just extracting small but unique elements of the HTML document then you may as well use regex's with python. To work with the HTML document more pragmatically then BeautifulSoup may be more beneficial, which you can combine with mechanize/python.\nIt's more straightforward than it may initially seem.\n", "Take a look at this documentation of the urlib2 package. Below is the code you would use, but the documentation explains (very well) what is happening.\nExcerpt:\nimport urllib\nimport urllib2\n\nurl = 'http://www.someserver.com/cgi-bin/register.cgi'\nvalues = {'name' : 'Michael Foord',\n 'location' : 'Northampton',\n 'language' : 'Python' }\n\ndata = urllib.urlencode(values)\nreq = urllib2.Request(url, data)\nresponse = urllib2.urlopen(req)\nthe_page = response.read()\n\nYou would need to use an HTML parser like BeautifulSoup to obtain the parameter name and value that is being posted when you click the button.\nEdit:\nYes, you could use mechanize for this as well. You would do something like this (untested):\nfrom mechanize import Browser\n\nbr = Browser()\nbr.open(\"http://www.example.com/\") # this would be your website\nbr.select_form(name=\"order\") # change this to the name of your form\nresponse = br.submit() # submits the form, just like if you clicked the submit button\nprint response.geturl() # prints the URL you are looking for\n\nYou'll need to make this specific to your website/form, but something along these lines should do the trick.\nCheck out the examples/documentation for the ClientForm object if you find you need more control.\n", "Once you have downloaded your html data with mechanize as other users said, then you could use Beautifulsoup like this:\nfrom BeautifulSoup import BeautifulSoup\nsoup = BeautifulSoup(html_data)\nhidden_tag = soup.find('input',name='hiddenId',type='hidden') \nhidden_value = hiddenId['value']\n\nthen you could forge a POST with urllib2 like this:\nimport urllib\nimport urllib2\nurl = 'http://yoursite.com'\nvalues = {'yourhiddenname' : hidden_value}\nrequest = urllib2.Request(url, urllib.urlencode(values))\nresponse = urllib2.urlopen(request)\nresult = response.read()\n\n" ]
[ 1, 1, 1 ]
[]
[]
[ "automation", "html", "javascript", "python", "webforms" ]
stackoverflow_0002648738_automation_html_javascript_python_webforms.txt
Q: error in a pygame code # INTIALISATION import pygame, math, sys from pygame.locals import * screen = pygame.display.set_mode((1024, 768)) car = pygame.image.load('car.png') clock = pygame.time.Clock() k_up = k_down = k_left = k_right = 0 speed = direction = 0 position = (100, 100) TURN_SPEED = 5 ACCELERATION = 2 MAX_FORWARD_SPEED = 10 MAX_REVERSE_SPEED = ­5 BLACK = (0,0,0) while 1: # USER INPUT clock.tick(30) for event in pygame.event.get(): if not hasattr(event, 'key'): continue down = event.type == KEYDOWN # key down or up? if event.key == K_RIGHT: k_right = down * ­5 elif event.key == K_LEFT: k_left = down * 5 elif event.key == K_UP: k_up = down * 2 elif event.key == K_DOWN: k_down = down * ­2 elif event.key == K_ESCAPE: sys.exit(0) # quit the game screen.fill(BLACK) # SIMULATION # .. new speed and direction based on acceleration and turn speed += (k_up + k_down) if speed > MAX_FORWARD_SPEED: speed = MAX_FORWARD_SPEED if speed < MAX_REVERSE_SPEED: speed = MAX_REVERSE_SPEED direction += (k_right + k_left) # .. new position based on current position, speed and direction x, y = position rad = direction * math.pi / 180 x += ­speed*math.sin(rad) y += ­speed*math.cos(rad) position = (x, y) # RENDERING # .. rotate the car image for direction rotated = pygame.transform.rotate(car, direction) # .. position the car on screen rect = rotated.get_rect() rect.center = position # .. render the car to screen screen.blit(rotated, rect) pygame.display.flip() enter code here the error i get is this Non-ASCII character '\xc2' in file race1.py on line 13, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details Not able to understand what the error is and how to get rid of it? A: You have a non-ASCII character on line 13. Python doesn't accept UTF-8 in source files unless you put a special comment at the top of your file: # encoding: UTF-8 A: As Greg says, you have a non-ascii character in your code - what looks like a minus sign in front of the 5 on line 13. It is called 'soft hyphen'. This character appears in a few locations in your code instead of minus signs. Delete these characters and replace with minus signs. Your code above doesn't show the character. Don't know why. When I copy and paste it into a text editor I can see the character. If you put an encoding comment at the top of you code, for example: # -*- coding: utf-8 -*- You will get a syntax error with the 'soft hyphen'. So you need to replace them all with minus signs. (Then you won't need the encoding comment at the top of the code.)
error in a pygame code
# INTIALISATION import pygame, math, sys from pygame.locals import * screen = pygame.display.set_mode((1024, 768)) car = pygame.image.load('car.png') clock = pygame.time.Clock() k_up = k_down = k_left = k_right = 0 speed = direction = 0 position = (100, 100) TURN_SPEED = 5 ACCELERATION = 2 MAX_FORWARD_SPEED = 10 MAX_REVERSE_SPEED = ­5 BLACK = (0,0,0) while 1: # USER INPUT clock.tick(30) for event in pygame.event.get(): if not hasattr(event, 'key'): continue down = event.type == KEYDOWN # key down or up? if event.key == K_RIGHT: k_right = down * ­5 elif event.key == K_LEFT: k_left = down * 5 elif event.key == K_UP: k_up = down * 2 elif event.key == K_DOWN: k_down = down * ­2 elif event.key == K_ESCAPE: sys.exit(0) # quit the game screen.fill(BLACK) # SIMULATION # .. new speed and direction based on acceleration and turn speed += (k_up + k_down) if speed > MAX_FORWARD_SPEED: speed = MAX_FORWARD_SPEED if speed < MAX_REVERSE_SPEED: speed = MAX_REVERSE_SPEED direction += (k_right + k_left) # .. new position based on current position, speed and direction x, y = position rad = direction * math.pi / 180 x += ­speed*math.sin(rad) y += ­speed*math.cos(rad) position = (x, y) # RENDERING # .. rotate the car image for direction rotated = pygame.transform.rotate(car, direction) # .. position the car on screen rect = rotated.get_rect() rect.center = position # .. render the car to screen screen.blit(rotated, rect) pygame.display.flip() enter code here the error i get is this Non-ASCII character '\xc2' in file race1.py on line 13, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details Not able to understand what the error is and how to get rid of it?
[ "You have a non-ASCII character on line 13. Python doesn't accept UTF-8 in source files unless you put a special comment at the top of your file:\n# encoding: UTF-8\n\n", "As Greg says, you have a non-ascii character in your code - what looks like a minus sign in front of the 5 on line 13. It is called 'soft hyphen'. This character appears in a few locations in your code instead of minus signs. Delete these characters and replace with minus signs.\nYour code above doesn't show the character. Don't know why. When I copy and paste it into a text editor I can see the character.\nIf you put an encoding comment at the top of you code, for example:\n# -*- coding: utf-8 -*-\n\nYou will get a syntax error with the 'soft hyphen'. So you need to replace them all with minus signs. (Then you won't need the encoding comment at the top of the code.)\n" ]
[ 4, 2 ]
[]
[]
[ "python" ]
stackoverflow_0002648800_python.txt
Q: Is django orm & templates thread safe? I'm using django orm and templates to create a background service that is ran as management command. Do you know if django is thread safe? I'd like to use threads to speed up processing. The processing is blocked by I/O not CPU so I don't care about performance hit caused by GIL. A: If you need run jobs in background, you should use celery
Is django orm & templates thread safe?
I'm using django orm and templates to create a background service that is ran as management command. Do you know if django is thread safe? I'd like to use threads to speed up processing. The processing is blocked by I/O not CPU so I don't care about performance hit caused by GIL.
[ "If you need run jobs in background, you should use celery\n" ]
[ 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0002645953_django_django_models_python.txt
Q: SVG to black-and-white I would like to be able to convert SVG documents to black and white. My try is the following Makefile script using 'sed' : %.bw.svg: %.svg sed '/stroke:none/!s/stroke:[^;\"]*/stroke:black/g' $< > $@ This works for lines etc but not for fillings. Basically if the stroke is not invisible (none), then I convert it to black. I would like to do the same for fillings, if not white or invisible, then convert to black. I wonder if it would be too complex to do something like this in a better way, perhaps using XSLT, but I have no experience. Anyone can help ? A: Two options that I would try: 1- Inkscape appears to be able to do it - Inkscape Convert 2- SVG supports a ColorProfile attribute on the SVG element that can reference an ICC Color Profile. I would try to reference a GrayScale color profile there and see what happens. Looks like there is one available here. A: My first thought is that it can be dangerous to manipulate XML (in this case SVG) via sed etc. since it won't escape XML chars properly or respect character encodings. Having said that, your dataset may be sufficiently constrained and limited such that this isn't a particular problem. Considering XPath solutions (inc. XSLT) sounds good since you'll be able to precisely identify the components you want to change. Some implementation of XQuery may be of use here. A very different alternative is XMLStarlet - a command line toolset used for processing XML in scripts. Finally, can you use a programmatic toolset to do this ? Batik would be my first choice (in the Java world). A: I think you need a full CSS parser to do this job for all of SVG; but for "SVG as generated by some particular vector editing application", XSLT containing string editing of the style attributes (as you're doing now, except that it will properly stick to the styles and avoid e.g. <text>) might be adequate. It would be useful if you'd edit your question to explain how your strategy fails for fill colors. A: First of all: Don't try doing this with sed. Editing XML is a little more complex than that. You can use an SVG filter effect on the image. The ColorMatrix filter primitive can desaturate an image.
SVG to black-and-white
I would like to be able to convert SVG documents to black and white. My try is the following Makefile script using 'sed' : %.bw.svg: %.svg sed '/stroke:none/!s/stroke:[^;\"]*/stroke:black/g' $< > $@ This works for lines etc but not for fillings. Basically if the stroke is not invisible (none), then I convert it to black. I would like to do the same for fillings, if not white or invisible, then convert to black. I wonder if it would be too complex to do something like this in a better way, perhaps using XSLT, but I have no experience. Anyone can help ?
[ "Two options that I would try:\n1- Inkscape appears to be able to do it - Inkscape Convert\n2- SVG supports a ColorProfile attribute on the SVG element that can reference an ICC Color Profile. I would try to reference a GrayScale color profile there and see what happens. Looks like there is one available here.\n", "My first thought is that it can be dangerous to manipulate XML (in this case SVG) via sed etc. since it won't escape XML chars properly or respect character encodings. \nHaving said that, your dataset may be sufficiently constrained and limited such that this isn't a particular problem.\nConsidering XPath solutions (inc. XSLT) sounds good since you'll be able to precisely identify the components you want to change. Some implementation of XQuery may be of use here. \nA very different alternative is XMLStarlet - a command line toolset used for processing XML in scripts. \nFinally, can you use a programmatic toolset to do this ? Batik would be my first choice (in the Java world).\n", "I think you need a full CSS parser to do this job for all of SVG; but for \"SVG as generated by some particular vector editing application\", XSLT containing string editing of the style attributes (as you're doing now, except that it will properly stick to the styles and avoid e.g. <text>) might be adequate.\nIt would be useful if you'd edit your question to explain how your strategy fails for fill colors.\n", "First of all: Don't try doing this with sed. Editing XML is a little more complex than that.\nYou can use an SVG filter effect on the image. The ColorMatrix filter primitive can desaturate an image.\n" ]
[ 5, 0, 0, 0 ]
[]
[]
[ "awk", "python", "sed", "svg", "xslt" ]
stackoverflow_0002203241_awk_python_sed_svg_xslt.txt
Q: Long-running stats process - thoughts on language choice? I am on a LAMP stack for a website I am managing. There is a need to roll up usage statistics (a variety of things related to our desktop product). I initially tackled the problem with PHP (being that I had a bunch of classes to work with the data already). All worked well on my dev box which was using 5.3. Long story short, 5.1 memory management seems to suck a lot worse, and I've had to do a lot of fooling to get the long-term roll up scripts to run in a fixed memory space. Our server guys are unwilling to upgrade PHP at this time. I've since moved my dev server back to 5.1 so I don't run into this problem again. For mining of MySQL databases to roll up statistics for different periods and resolutions, potentially running a process that does this all the time in the future (as opposed to on a cron schedule), what language choice do you recommend? I was looking at Python (I know it more or less), Java (don't know it that well), or sticking it out with PHP (know it quite well). Edit: design clarification for commenter Resolutions: The way the rollup script works currently, is I have some classes for defining resolutions and buckets. I have year, month, week, day -- given a "bucket number" each class gives a start and end timestamp that defines the time range for that bucket -- this is based on arbitrary epoch date. The system maintains "complete" records, ie it will complete its rolled up dataset for each resolution since the last time it was run, currently. SQL Strat: The base stats are located in many dissimilar schemas and tables. I do individual queries for each rolled up stat for the most part, then fill one record for insert. Your are suggesting nested subqueries such as: INSERT into rolled_up_stats (someval, someval, someval, ... ) VALUES (SELECT SUM(somestat) from someschema, SELECT AVG(somestat2) from someschema2) Those subqueries will generate temporary tables, right? My experience is that had been slow as molasses in the past. Is it a better approach? Edit 2: Adding some inline responses to the question Language was a bottleneck in the case of 5.1 php -- I was essentially told I made the wrong language choice (though the scripts worked fine on 5.3). You mention python, which I am checking out for this task. To be clear, what I am doing is providing a management tool for usage statistics of a desktop product (the logs are actually written by an EJB server to mysql tables). I do apache log file analysis, as well as more custom web reporting on the web side, but this project is separate. The approach I've taken so far is aggregate tables. I'm not sure what these message queue products could do for me, I'll take a look. To go a bit further -- the data is being used to chart activity over time at the service and the customer level, to allow management to understand how the product is being used. You might select a time period (April 1 to April 10) and retrieve a graph of total minutes of usage of a certain feature at different granularities (hours, days, months etc) depending on the time period selected. Its essentially an after-the-fact analysis of usage. The need seems to be tending towards real-time, however (look at the last hour of usage) A: I have worked on a project to do a similar thing in the past, so I have actual experience with performance. You would be hard pressed to beat the performance of "INSERT ... SELECT" (not "INSERT...VALUES (SELECT ...)". Please see http://dev.mysql.com/doc/refman/5.1/en/insert-select.html The advantage is that if you do that, especially if you keep the roll-up code in MySQL procedures, is that all you need from the outside is just a cron-job to poke the DB into performing the right roll-ups at the right times -- as simple as a shell-script with 'mysql <correct DB arguments etc.> "CALL RollupProcedure"' This way, you are guaranteeing yourself zero memory allocation bugs, as well as having decent performance when the MySQL DB is on a separate machine (no moving of data across machine boundary...) EDIT: Hourly resolution is fine -- just run an hourly cron-job... A: There are a lot of different approaches to this problem, some of which are mentioned here, but what you're doing with the data post-rollup is unclear...? If you want to utilize this data to provide digg-like 'X diggs' buttons on your site, or summary graphs or something like that which needs to be available on some kind of ongoing basis, you can actually utilize memcache for this, and have your code keep the cache key for the particular statistic up to date by incrementing it at the appropriate times. You could also keep aggregation tables in the database, which can work well for more complex reporting. In this case, depending on how much data you have and what your needs are, you might be able to get away with having an hourly table, and then just creating views based on that base table to represent days, weeks, etc. If you have tons and tons of data, and you need aggregate tables, you should look into offloading statistics collection (and perhaps the database queries themselves) to a queue like RabbitMQ or ActiveMQ. On the other side of the queue put a consumer daemon that just sits and runs all the time, updating things in the database (and perhaps the cache) as needed. One thing you might also consider is your web server's logs. I've seen instances where I was able to get a somewhat large portion of the required statistics from the web server logs themselves after just minor tweaks to the log format rules in the config. You can roll the logs every , and then start processing them offline, recording the results in a reporting database. I've done all of these things with Python (I released loghetti for dealing with Apache combined format logs, specifically), though I don't think language is a limiting factor or bottleneck here. Ruby, Perl, Java, Scala, or even awk (in some instances) would work. A: If you are running mostly SQL commands, why not just use MySQL etc on the command line? You could create a simple table that lists aggregate data then run a command like mysql -u[user] -p[pass] < commands.sql to pass SQL in from a file. Or, split the work into smaller chunks and run them sequentially (as PHP files if that's easiest). If you really need it to be a continual long-running process then a programming language like python or java would be better, since you can create a loop and keep it running indefinitely. PHP is not suited for that kind of thing. It would be pretty easy to convert any PHP classes to Java.
Long-running stats process - thoughts on language choice?
I am on a LAMP stack for a website I am managing. There is a need to roll up usage statistics (a variety of things related to our desktop product). I initially tackled the problem with PHP (being that I had a bunch of classes to work with the data already). All worked well on my dev box which was using 5.3. Long story short, 5.1 memory management seems to suck a lot worse, and I've had to do a lot of fooling to get the long-term roll up scripts to run in a fixed memory space. Our server guys are unwilling to upgrade PHP at this time. I've since moved my dev server back to 5.1 so I don't run into this problem again. For mining of MySQL databases to roll up statistics for different periods and resolutions, potentially running a process that does this all the time in the future (as opposed to on a cron schedule), what language choice do you recommend? I was looking at Python (I know it more or less), Java (don't know it that well), or sticking it out with PHP (know it quite well). Edit: design clarification for commenter Resolutions: The way the rollup script works currently, is I have some classes for defining resolutions and buckets. I have year, month, week, day -- given a "bucket number" each class gives a start and end timestamp that defines the time range for that bucket -- this is based on arbitrary epoch date. The system maintains "complete" records, ie it will complete its rolled up dataset for each resolution since the last time it was run, currently. SQL Strat: The base stats are located in many dissimilar schemas and tables. I do individual queries for each rolled up stat for the most part, then fill one record for insert. Your are suggesting nested subqueries such as: INSERT into rolled_up_stats (someval, someval, someval, ... ) VALUES (SELECT SUM(somestat) from someschema, SELECT AVG(somestat2) from someschema2) Those subqueries will generate temporary tables, right? My experience is that had been slow as molasses in the past. Is it a better approach? Edit 2: Adding some inline responses to the question Language was a bottleneck in the case of 5.1 php -- I was essentially told I made the wrong language choice (though the scripts worked fine on 5.3). You mention python, which I am checking out for this task. To be clear, what I am doing is providing a management tool for usage statistics of a desktop product (the logs are actually written by an EJB server to mysql tables). I do apache log file analysis, as well as more custom web reporting on the web side, but this project is separate. The approach I've taken so far is aggregate tables. I'm not sure what these message queue products could do for me, I'll take a look. To go a bit further -- the data is being used to chart activity over time at the service and the customer level, to allow management to understand how the product is being used. You might select a time period (April 1 to April 10) and retrieve a graph of total minutes of usage of a certain feature at different granularities (hours, days, months etc) depending on the time period selected. Its essentially an after-the-fact analysis of usage. The need seems to be tending towards real-time, however (look at the last hour of usage)
[ "I have worked on a project to do a similar thing in the past, so I have actual experience with performance. You would be hard pressed to beat the performance of \"INSERT ... SELECT\" (not \"INSERT...VALUES (SELECT ...)\". Please see http://dev.mysql.com/doc/refman/5.1/en/insert-select.html\nThe advantage is that if you do that, especially if you keep the roll-up code in MySQL procedures, is that all you need from the outside is just a cron-job to poke the DB into performing the right roll-ups at the right times -- as simple as a shell-script with 'mysql <correct DB arguments etc.> \"CALL RollupProcedure\"'\nThis way, you are guaranteeing yourself zero memory allocation bugs, as well as having decent performance when the MySQL DB is on a separate machine (no moving of data across machine boundary...)\nEDIT: Hourly resolution is fine -- just run an hourly cron-job...\n", "There are a lot of different approaches to this problem, some of which are mentioned here, but what you're doing with the data post-rollup is unclear...? \nIf you want to utilize this data to provide digg-like 'X diggs' buttons on your site, or summary graphs or something like that which needs to be available on some kind of ongoing basis, you can actually utilize memcache for this, and have your code keep the cache key for the particular statistic up to date by incrementing it at the appropriate times. \nYou could also keep aggregation tables in the database, which can work well for more complex reporting. In this case, depending on how much data you have and what your needs are, you might be able to get away with having an hourly table, and then just creating views based on that base table to represent days, weeks, etc. \nIf you have tons and tons of data, and you need aggregate tables, you should look into offloading statistics collection (and perhaps the database queries themselves) to a queue like RabbitMQ or ActiveMQ. On the other side of the queue put a consumer daemon that just sits and runs all the time, updating things in the database (and perhaps the cache) as needed. \nOne thing you might also consider is your web server's logs. I've seen instances where I was able to get a somewhat large portion of the required statistics from the web server logs themselves after just minor tweaks to the log format rules in the config. You can roll the logs every , and then start processing them offline, recording the results in a reporting database. \nI've done all of these things with Python (I released loghetti for dealing with Apache combined format logs, specifically), though I don't think language is a limiting factor or bottleneck here. Ruby, Perl, Java, Scala, or even awk (in some instances) would work. \n", "If you are running mostly SQL commands, why not just use MySQL etc on the command line? You could create a simple table that lists aggregate data then run a command like mysql -u[user] -p[pass] < commands.sql to pass SQL in from a file.\nOr, split the work into smaller chunks and run them sequentially (as PHP files if that's easiest).\nIf you really need it to be a continual long-running process then a programming language like python or java would be better, since you can create a loop and keep it running indefinitely. PHP is not suited for that kind of thing. It would be pretty easy to convert any PHP classes to Java.\n" ]
[ 1, 1, 0 ]
[]
[]
[ "java", "long_running_processes", "php", "python", "statistics" ]
stackoverflow_0002647905_java_long_running_processes_php_python_statistics.txt
Q: I need to speed up a function. Should I use cython, ctypes, or something else? I'm having a lot of fun learning Python by writing a genetic programming type of application. I've had some great advice from Torsten Marek, Paul Hankin and Alex Martelli on this site. The program has 4 main functions: generate (randomly) an expression tree. evaluate the fitness of the tree crossbreed mutate As all of generate, crossbreed and mutate call 'evaluate the fitness'. it is the busiest function and is the primary bottleneck speedwise. As is the nature of genetic algorithms, it has to search an immense solution space so the faster the better. I want to speed up each of these functions. I'll start with the fitness evaluator. My question is what is the best way to do this. I've been looking into cython, ctypes and 'linking and embedding'. They are all new to me and quite beyond me at the moment but I look forward to learning one and eventually all of them. The 'fitness function' needs to compare the value of the expression tree to the value of the target expression. So it will consist of a postfix evaluator which will read the tree in a postfix order. I have all the code in python. I need advice on which I should learn and use now: cython, ctypes or linking and embedding. Thank you. A: Ignore everyone elses' answer for now. The first thing you should learn to use is the profiler. Python comes with a profile/cProfile; you should learn how to read the results and analyze where the real bottlenecks is. The goal of optimization is three-fold: reduce the time spent on each call, reduce the number of calls to be made, and reduce memory usage to reduce disk thrashing. The first goal is relatively easy. The profiler will show you the most time-consuming functions and you can go straight to that function to optimize it. The second and third goal is harder since this means you need to change the algorithm to reduce the need to make so much calls. Find the functions that have high number of calls and try to find ways to reduce the need to call them. Utilize the built-in collections, they're very well optimized. If you're doing a lot of number and array processing, you should take a look at pandas, Numpy/Scipy, gmpy third party modules; they're well optimised C libraries for processing arrays/tabular data. Another thing you want to try is PyPy. PyPy can JIT recompile and do much more advanced optimisation than CPython, and it'll work without the need to change your python code. Though well optimised code targeting CPython can look quite different from well optimised code targeting PyPy. Next to try is Cython. Cython is a slightly different language than Python, in fact Cython is actually best described as C with typed Python-like syntax. For parts of your code that is in very tight loops that you can no longer optimize using any other ways, you may want to rewrite it as C extension. Python has a very good support for extending with C. In PyPy, the best way to extend PyPy is with cffi. A: Cython is the quickest to get the job done, either by writing your algorithm directly in Cython, or by writing it in C and bind it to python with Cython. My advice: learn Cython. A: Another great option is boost::python which lets you easily wrap C or C++. Of these possibilities though, since you have python code already written, cython is probably a good thing to try first. Perhaps you won't have to rewrite any code to get a speedup. A: Try to work your fitness function so that it will support memoization. This will replace all calls that are duplicates of previous calls with a quick dict lookup.
I need to speed up a function. Should I use cython, ctypes, or something else?
I'm having a lot of fun learning Python by writing a genetic programming type of application. I've had some great advice from Torsten Marek, Paul Hankin and Alex Martelli on this site. The program has 4 main functions: generate (randomly) an expression tree. evaluate the fitness of the tree crossbreed mutate As all of generate, crossbreed and mutate call 'evaluate the fitness'. it is the busiest function and is the primary bottleneck speedwise. As is the nature of genetic algorithms, it has to search an immense solution space so the faster the better. I want to speed up each of these functions. I'll start with the fitness evaluator. My question is what is the best way to do this. I've been looking into cython, ctypes and 'linking and embedding'. They are all new to me and quite beyond me at the moment but I look forward to learning one and eventually all of them. The 'fitness function' needs to compare the value of the expression tree to the value of the target expression. So it will consist of a postfix evaluator which will read the tree in a postfix order. I have all the code in python. I need advice on which I should learn and use now: cython, ctypes or linking and embedding. Thank you.
[ "Ignore everyone elses' answer for now. The first thing you should learn to use is the profiler. Python comes with a profile/cProfile; you should learn how to read the results and analyze where the real bottlenecks is. The goal of optimization is three-fold: reduce the time spent on each call, reduce the number of calls to be made, and reduce memory usage to reduce disk thrashing.\nThe first goal is relatively easy. The profiler will show you the most time-consuming functions and you can go straight to that function to optimize it.\nThe second and third goal is harder since this means you need to change the algorithm to reduce the need to make so much calls. Find the functions that have high number of calls and try to find ways to reduce the need to call them. Utilize the built-in collections, they're very well optimized.\nIf you're doing a lot of number and array processing, you should take a look at pandas, Numpy/Scipy, gmpy third party modules; they're well optimised C libraries for processing arrays/tabular data. \nAnother thing you want to try is PyPy. PyPy can JIT recompile and do much more advanced optimisation than CPython, and it'll work without the need to change your python code. Though well optimised code targeting CPython can look quite different from well optimised code targeting PyPy. \nNext to try is Cython. Cython is a slightly different language than Python, in fact Cython is actually best described as C with typed Python-like syntax. \nFor parts of your code that is in very tight loops that you can no longer optimize using any other ways, you may want to rewrite it as C extension. Python has a very good support for extending with C. In PyPy, the best way to extend PyPy is with cffi.\n", "Cython is the quickest to get the job done, either by writing your algorithm directly in Cython, or by writing it in C and bind it to python with Cython.\nMy advice: learn Cython.\n", "Another great option is boost::python which lets you easily wrap C or C++.\nOf these possibilities though, since you have python code already written, cython is probably a good thing to try first. Perhaps you won't have to rewrite any code to get a speedup.\n", "Try to work your fitness function so that it will support memoization. This will replace all calls that are duplicates of previous calls with a quick dict lookup.\n" ]
[ 14, 3, 0, 0 ]
[]
[]
[ "ctypes", "cython", "python" ]
stackoverflow_0002647105_ctypes_cython_python.txt
Q: Python: how to design a container with elements that must reference their container (The title is admittedly not that great. Please forgive my English, this is the best I could think of.) I'm writing a python script that will manage email domains and their accounts, and I'm also a newby at OOP design. My two (related?) issues are: the Domain class must do special work to add and remove accounts, like adding/removing them to the underlying implementation how to manage operations on accounts that must go through their container To solve the former issue, I'd add a factory method to the Domain class that'll build an Account instance in that domain, and a 'remove' (anti-factory?) method to handle deletions. For the latter, this seems to me "anti-oop" since what would logically be an operation on an Account (e.g., change password) that must always reference the containing Domain. It seems to me that I must add a reference back to the Domain to the Account and use that to get data (such as the domain name) or call methods on the Domain class. Code example (element uses data from the container) that manages an underlying Vpopmail system: class Account: def __init__(self, name, password, domain): self.name = name self.password = password self.domain = domain def set_password(self, password): os.system('vpasswd %s@%s %s' % (self.name, self.domain.name, password) self.password = password class Domain: def __init__(self, domain_name): self.name = domain_name self.accounts = {} def create_account(self, name, password): os.system('vadduser %s@%s %s' % (name, self.name, password)) account = Account(name, password, self) self.accounts[name] = account def delete_account(self, name): os.system('vdeluser %s@%s' % (name, self.name)) del self.accounts[name] Another option would be for Account.set_password to call a Domain method that would do the actual work - which sounds equally ugly to me. Also note the duplication of data (account name also as dict key), it sounds logical (account names are "primary key" inside a domain) but accounts need to know their own name. EDIT: please note the above code is just a quick example, think of it as pseudo code. It intentionally does not care about error conditions or security issues, and is incomplete in data and methods of the classes (per-user spam settings, auto-responders, forwarders, get mailbox size, etc...). Also, this is an example I had at hand, but I think it could be generalized to other different logical structures similar to trees where nodes must know about their children and children must call into parents (or upper level ancestors) to do things. To me, this sounds logically similar to class inheritance but applied to instances of different types (classes) linked to each other. A: For the operations you've outlined, it's not clear that you need Account at all. The only information it holds that is not already duplicated in Domain is the password. You could just have Domain.accounts being a lookup of username: password instead. Don't multiply identity-bearing classes until you need to. For what it's worth in the general case, yes, when you have objects that are owned by other objects it's quite normal to give them a reference up to their owner and have them communicate upwards as needed. Python doesn't have the notion of inner classes that some languages provide for ownership. (Incidentally, don't concatenate strings into command lines for os.system; this is a serious security risk. See the subprocess module for a safer and easier way to pass parameters.) A: I think that you don't need the methods create/delete account in the Domain class. I would rather have it like this: class Account: def __init__(self, name, password, domain): ... def activate(self): self.domain.add(self) os.system('vadduser %s@%s %s' % (name, self.domain.name, password)) def deactivate(self): self.domain.remove(self) os.system('vdeluser %s@%s' % (name, self.domain.name) If you have many such relations between objects, I believe the standard option is to use a database. One of the most popular for python is SQLAlchemy. It will solve the problem of efficiently storing relationship and looking them up (and much more). But in your example, it's obviously an overkill, and I suppose the only option is to handle that manually as in my code. A: In Python one tends to avoid doing recursive relations, because the garbage collector is usually implemented as a reference counting scheme. Simplest solution: do the operations that need the container in the container. A little bit more convoluted solution: when the container is queried for an object, create a temporary proxy object that holds a reference to both the container and the contained object and implements the interface of the contained; and return it instead of the contained object. A: So, you have domains, and you have accounts, and the real work of your application is managing accounts, including their associations with domains... Why don't you just create a Python "Manager" or "AccountManager" class that can be a puppetmaster for the Domains and the Accounts? It'll remove questions like the one you've posted altogether by introducing an 'objective third party' who can reference any of the other objects and make associations between them at will. class Manager(object): def set_password(self, domain, account, password): os.system('vpasswd %s@%s %s' % (account.name, domain.name, password) account.password = password >>> m = Manager() >>> d = Domain('google.com') >>> a = Account('foouser') >>> m.set_password(d, a, p) Of course, in a real program, you'd create one manager object and then act upon as many domains and accounts as you want with that one instance.
Python: how to design a container with elements that must reference their container
(The title is admittedly not that great. Please forgive my English, this is the best I could think of.) I'm writing a python script that will manage email domains and their accounts, and I'm also a newby at OOP design. My two (related?) issues are: the Domain class must do special work to add and remove accounts, like adding/removing them to the underlying implementation how to manage operations on accounts that must go through their container To solve the former issue, I'd add a factory method to the Domain class that'll build an Account instance in that domain, and a 'remove' (anti-factory?) method to handle deletions. For the latter, this seems to me "anti-oop" since what would logically be an operation on an Account (e.g., change password) that must always reference the containing Domain. It seems to me that I must add a reference back to the Domain to the Account and use that to get data (such as the domain name) or call methods on the Domain class. Code example (element uses data from the container) that manages an underlying Vpopmail system: class Account: def __init__(self, name, password, domain): self.name = name self.password = password self.domain = domain def set_password(self, password): os.system('vpasswd %s@%s %s' % (self.name, self.domain.name, password) self.password = password class Domain: def __init__(self, domain_name): self.name = domain_name self.accounts = {} def create_account(self, name, password): os.system('vadduser %s@%s %s' % (name, self.name, password)) account = Account(name, password, self) self.accounts[name] = account def delete_account(self, name): os.system('vdeluser %s@%s' % (name, self.name)) del self.accounts[name] Another option would be for Account.set_password to call a Domain method that would do the actual work - which sounds equally ugly to me. Also note the duplication of data (account name also as dict key), it sounds logical (account names are "primary key" inside a domain) but accounts need to know their own name. EDIT: please note the above code is just a quick example, think of it as pseudo code. It intentionally does not care about error conditions or security issues, and is incomplete in data and methods of the classes (per-user spam settings, auto-responders, forwarders, get mailbox size, etc...). Also, this is an example I had at hand, but I think it could be generalized to other different logical structures similar to trees where nodes must know about their children and children must call into parents (or upper level ancestors) to do things. To me, this sounds logically similar to class inheritance but applied to instances of different types (classes) linked to each other.
[ "For the operations you've outlined, it's not clear that you need Account at all. The only information it holds that is not already duplicated in Domain is the password. You could just have Domain.accounts being a lookup of username: password instead.\nDon't multiply identity-bearing classes until you need to.\nFor what it's worth in the general case, yes, when you have objects that are owned by other objects it's quite normal to give them a reference up to their owner and have them communicate upwards as needed. Python doesn't have the notion of inner classes that some languages provide for ownership.\n(Incidentally, don't concatenate strings into command lines for os.system; this is a serious security risk. See the subprocess module for a safer and easier way to pass parameters.)\n", "I think that you don't need the methods create/delete account in the Domain class. I would rather have it like this:\nclass Account:\n def __init__(self, name, password, domain):\n ...\n\n def activate(self):\n self.domain.add(self)\n os.system('vadduser %s@%s %s' % (name, self.domain.name, password))\n\n def deactivate(self):\n self.domain.remove(self)\n os.system('vdeluser %s@%s' % (name, self.domain.name)\n\nIf you have many such relations between objects, I believe the standard option is to use a database. One of the most popular for python is SQLAlchemy. It will solve the problem of efficiently storing relationship and looking them up (and much more). But in your example, it's obviously an overkill, and I suppose the only option is to handle that manually as in my code.\n", "In Python one tends to avoid doing recursive relations, because the garbage collector is usually implemented as a reference counting scheme.\nSimplest solution: do the operations that need the container in the container.\nA little bit more convoluted solution: when the container is queried for an object, create a temporary proxy object that holds a reference to both the container and the contained object and implements the interface of the contained; and return it instead of the contained object.\n", "So, you have domains, and you have accounts, and the real work of your application is managing accounts, including their associations with domains... \nWhy don't you just create a Python \"Manager\" or \"AccountManager\" class that can be a puppetmaster for the Domains and the Accounts? It'll remove questions like the one you've posted altogether by introducing an 'objective third party' who can reference any of the other objects and make associations between them at will. \nclass Manager(object):\n def set_password(self, domain, account, password):\n os.system('vpasswd %s@%s %s' % (account.name, domain.name, password)\n account.password = password\n\n>>> m = Manager()\n>>> d = Domain('google.com')\n>>> a = Account('foouser')\n>>> m.set_password(d, a, p)\n\nOf course, in a real program, you'd create one manager object and then act upon as many domains and accounts as you want with that one instance. \n" ]
[ 2, 1, 1, 0 ]
[]
[]
[ "design_patterns", "oop", "python" ]
stackoverflow_0002646744_design_patterns_oop_python.txt
Q: delta-dictionary/dictionary with revision awareness in python? I am looking to create a dictionary with 'roll-back' capabilities in python. The dictionary would start with a revision number of 0, and the revision would be bumped up only by explicit method call. I do not need to delete keys, only add and update key,value pairs, and then roll back. I will never need to 'roll forward', that is, when rolling the dictionary back, all the newer revisions can be discarded, and I can start re-reving up again. thus I want behaviour like: >>> rr = rev_dictionary() >>> rr.rev 0 >>> rr["a"] = 17 >>> rr[('b',23)] = 'foo' >>> rr["a"] 17 >>> rr.rev 0 >>> rr.roll_rev() >>> rr.rev 1 >>> rr["a"] 17 >>> rr["a"] = 0 >>> rr["a"] 0 >>> rr[('b',23)] 'foo' >>> rr.roll_to(0) >>> rr.rev 0 >>> rr["a"] 17 >>> rr.roll_to(1) Exception ... Just to be clear, the state associated with a revision is the state of the dictionary just prior to the roll_rev() method call. thus if I can alter the value associated with a key several times 'within' a revision, and only have the last one remembered. I would like a fairly memory-efficient implementation of this: the memory usage should be proportional to the deltas. Thus simply having a list of copies of the dictionary will not scale for my problem. One should assume the keys are in the tens of thousands, and the revisions are in the hundreds of thousands. We can assume the values are immutable, but need not be numeric. For the case where the values are e.g. integers, there is a fairly straightforward implementation (have a list of dictionaries of the numerical delta from revision to revision). I am not sure how to turn this into the general form. Maybe bootstrap the integer version and add on an array of values? all help appreciated. A: Have just one dictionary, mapping from the key to a list of (revision_number, actual_value) tuples. Current value is the_dict[akey][-1][1]. Rollback merely involves popping the appropriate entries off the end of each list. Update: examples of rollback key1 -> [(10, 'v1-10'), (20, 'v1-20')] Scenario 1: current revision is 30, rollback to 25: nothing happens Scenario 2: current 30, back to 15: pop last entry Scenario 3: current 30, back to 5: pop both entries Update 2: faster rollback (with trade-offs) I think your concern about popping every list is better expressed as "needs to examine every list to see if it needs popping". With a fancier data structure (more memory, more time to maintain the fancy bits in add and update operations) you can reduce the time to roll back. Add an array (indexed by revision number) whose values are lists of the dictionary values that were changed in that revision. # Original rollback code: for rlist in the_dict.itervalues(): if not rlist: continue while rlist[-1][0] > target_revno: rlist.pop() # New rollback code for revno in xrange(current_revno, target_revno, -1): for rlist in delta_index[revno]: assert rlist[-1][0] == revno del rlist[-1] # faster than rlist.pop() del delta_index[target_revno+1:] Update 3: full code for fancier method import collections class RevDict(collections.MutableMapping): def __init__(self): self.current_revno = 0 self.dict = {} self.delta_index = [[]] def __setitem__(self, key, value): if key in self.dict: rlist = self.dict[key] last_revno = rlist[-1][0] rtup = (self.current_revno, value) if last_revno == self.current_revno: rlist[-1] = rtup # delta_index already has an entry for this rlist else: rlist.append(rtup) self.delta_index[self.current_revno].append(rlist) else: rlist = [(self.current_revno, value)] self.dict[key] = rlist self.delta_index[self.current_revno].append(rlist) def __getitem__(self, key): if not key in self.dict: raise KeyError(key) return self.dict[key][-1][1] def new_revision(self): self.current_revno += 1 self.delta_index.append([]) def roll_back(self, target_revno): assert 0 <= target_revno < self.current_revno for revno in xrange(self.current_revno, target_revno, -1): for rlist in self.delta_index[revno]: assert rlist[-1][0] == revno del rlist[-1] del self.delta_index[target_revno+1:] self.current_revno = target_revno def __delitem__(self, key): raise TypeError("RevDict doesn't do del") def keys(self): return self.dict.keys() def __contains__(self, key): return key in self.dict def iteritems(self): for key, rlist in self.dict.iteritems(): yield key, rlist[-1][1] def __len__(self): return len(self.dict) def __iter__(self): return self.dict.iterkeys() A: The deluxe solution would be to use B+Trees with copy-on-write. I used a variation on B+Trees to implement my blist data type (which can be used to very efficiently create revisions of lists, exactly analogous to your problem). The general idea is to store the data in a balanced tree. When you create a new revision, you copy only the root node. If you need to modify a node shared with an older revision, you copy the node and modify the copy instead. That way, the old tree is still completely intact, but you only need memory for the changes (technically, O(k * log n) where k is the number of changes and n is the total number of items). It's non-trivial to implement, though.
delta-dictionary/dictionary with revision awareness in python?
I am looking to create a dictionary with 'roll-back' capabilities in python. The dictionary would start with a revision number of 0, and the revision would be bumped up only by explicit method call. I do not need to delete keys, only add and update key,value pairs, and then roll back. I will never need to 'roll forward', that is, when rolling the dictionary back, all the newer revisions can be discarded, and I can start re-reving up again. thus I want behaviour like: >>> rr = rev_dictionary() >>> rr.rev 0 >>> rr["a"] = 17 >>> rr[('b',23)] = 'foo' >>> rr["a"] 17 >>> rr.rev 0 >>> rr.roll_rev() >>> rr.rev 1 >>> rr["a"] 17 >>> rr["a"] = 0 >>> rr["a"] 0 >>> rr[('b',23)] 'foo' >>> rr.roll_to(0) >>> rr.rev 0 >>> rr["a"] 17 >>> rr.roll_to(1) Exception ... Just to be clear, the state associated with a revision is the state of the dictionary just prior to the roll_rev() method call. thus if I can alter the value associated with a key several times 'within' a revision, and only have the last one remembered. I would like a fairly memory-efficient implementation of this: the memory usage should be proportional to the deltas. Thus simply having a list of copies of the dictionary will not scale for my problem. One should assume the keys are in the tens of thousands, and the revisions are in the hundreds of thousands. We can assume the values are immutable, but need not be numeric. For the case where the values are e.g. integers, there is a fairly straightforward implementation (have a list of dictionaries of the numerical delta from revision to revision). I am not sure how to turn this into the general form. Maybe bootstrap the integer version and add on an array of values? all help appreciated.
[ "Have just one dictionary, mapping from the key to a list of (revision_number, actual_value) tuples. Current value is the_dict[akey][-1][1]. Rollback merely involves popping the appropriate entries off the end of each list.\nUpdate: examples of rollback\nkey1 -> [(10, 'v1-10'), (20, 'v1-20')]\nScenario 1: current revision is 30, rollback to 25: nothing happens\nScenario 2: current 30, back to 15: pop last entry\nScenario 3: current 30, back to 5: pop both entries\nUpdate 2: faster rollback (with trade-offs)\nI think your concern about popping every list is better expressed as \"needs to examine every list to see if it needs popping\". With a fancier data structure (more memory, more time to maintain the fancy bits in add and update operations) you can reduce the time to roll back.\nAdd an array (indexed by revision number) whose values are lists of the dictionary values that were changed in that revision.\n# Original rollback code:\nfor rlist in the_dict.itervalues():\n if not rlist: continue\n while rlist[-1][0] > target_revno:\n rlist.pop()\n\n# New rollback code\nfor revno in xrange(current_revno, target_revno, -1):\n for rlist in delta_index[revno]:\n assert rlist[-1][0] == revno\n del rlist[-1] # faster than rlist.pop() \ndel delta_index[target_revno+1:]\n\nUpdate 3: full code for fancier method\nimport collections\n\nclass RevDict(collections.MutableMapping):\n\n def __init__(self):\n self.current_revno = 0\n self.dict = {}\n self.delta_index = [[]]\n\n def __setitem__(self, key, value):\n if key in self.dict:\n rlist = self.dict[key]\n last_revno = rlist[-1][0]\n rtup = (self.current_revno, value)\n if last_revno == self.current_revno:\n rlist[-1] = rtup\n # delta_index already has an entry for this rlist\n else:\n rlist.append(rtup)\n self.delta_index[self.current_revno].append(rlist)\n else:\n rlist = [(self.current_revno, value)]\n self.dict[key] = rlist\n self.delta_index[self.current_revno].append(rlist)\n\n def __getitem__(self, key):\n if not key in self.dict:\n raise KeyError(key)\n return self.dict[key][-1][1]\n\n def new_revision(self):\n self.current_revno += 1\n self.delta_index.append([])\n\n def roll_back(self, target_revno):\n assert 0 <= target_revno < self.current_revno\n for revno in xrange(self.current_revno, target_revno, -1):\n for rlist in self.delta_index[revno]:\n assert rlist[-1][0] == revno\n del rlist[-1]\n del self.delta_index[target_revno+1:]\n self.current_revno = target_revno\n\n def __delitem__(self, key):\n raise TypeError(\"RevDict doesn't do del\")\n\n def keys(self):\n return self.dict.keys()\n\n def __contains__(self, key):\n return key in self.dict\n\n def iteritems(self):\n for key, rlist in self.dict.iteritems():\n yield key, rlist[-1][1]\n\n def __len__(self):\n return len(self.dict)\n\n def __iter__(self):\n return self.dict.iterkeys()\n\n", "The deluxe solution would be to use B+Trees with copy-on-write. I used a variation on B+Trees to implement my blist data type (which can be used to very efficiently create revisions of lists, exactly analogous to your problem).\nThe general idea is to store the data in a balanced tree. When you create a new revision, you copy only the root node. If you need to modify a node shared with an older revision, you copy the node and modify the copy instead. That way, the old tree is still completely intact, but you only need memory for the changes (technically, O(k * log n) where k is the number of changes and n is the total number of items).\nIt's non-trivial to implement, though.\n" ]
[ 2, 2 ]
[]
[]
[ "data_structures", "dictionary", "persistence", "python", "revision" ]
stackoverflow_0002649221_data_structures_dictionary_persistence_python_revision.txt
Q: google app engine persistent globals I'm looking for a way to keep the equivalent of persistent global variables in app engine (python). What I'm doing is creating a global kind that I initialize once (i.e. when I reset all my database objects when I'm testing). I have things in there like global counters, or the next id to assign certain kinds I create. Is this a decent way to do this sort of thing or is there generally another approach that is used? A: The datastore is the only place you can have guaranteed-persistent data that are also modifiable. So you can have a single large object, or several smaller ones (with a name attribute and others), depending on your desired access patterns -- but live in the datastore it must. You can use memcache for faster cache that usually persists across queries, but any memcache entry could go away any time, so you'll always need it to be backed by the datastore (in particular, any change must go to the datastore, not just to memcache).
google app engine persistent globals
I'm looking for a way to keep the equivalent of persistent global variables in app engine (python). What I'm doing is creating a global kind that I initialize once (i.e. when I reset all my database objects when I'm testing). I have things in there like global counters, or the next id to assign certain kinds I create. Is this a decent way to do this sort of thing or is there generally another approach that is used?
[ "The datastore is the only place you can have guaranteed-persistent data that are also modifiable. So you can have a single large object, or several smaller ones (with a name attribute and others), depending on your desired access patterns -- but live in the datastore it must. You can use memcache for faster cache that usually persists across queries, but any memcache entry could go away any time, so you'll always need it to be backed by the datastore (in particular, any change must go to the datastore, not just to memcache).\n" ]
[ 6 ]
[]
[]
[ "database", "global", "google_app_engine", "python" ]
stackoverflow_0002650014_database_global_google_app_engine_python.txt
Q: Can a native-looking GUI be made with Python I haven't gotten far enough into Python to make GUIs yet, so I thought I'd ask here. Can a python app be made with the windows default style GUI, or will it have its own style? The only screenshots I've seen of a python app running with a GUI had this ugly win95 look to it. A: The "ugly" Windows 95 look is determined by the version of the Common Dialog library. Supplying a manifest file with the executable (probably your Python implementation) makes Windows use of visual styles, instead of the "ugly" look. Read more here: http://msdn.microsoft.com/en-us/library/ms997646.aspx A: You (and the rest of the world, really ;)) should take a look at PyGUI, by Greg Ewing. In his own words, it's "a project to develop a cross-platform pythonic GUI API." Not only that, it attempts to generate native-looking GUIs on each of the three major platforms. When I'd last checked it, more than a year ago, it seemed dead, but now I see there was a new release on February 2010, which is great news. A: There are Python bindings for every major toolkit: GTK+, Qt, Tk, win32/MFC (not fun to use directly), wx (which in turn uses various other toolkits), Windows.Forms (through IronPython)...so in short, yes, probably. If you define exactly what "native" should look like on what platform, someone can probably tell you exactly what you want. My favourite GUI toolkit is GTK (using PyGTK) which is native on Gnome and looks pretty good to me on Windows. A: There are loads of Python GUI libraries, among which, some support Windows. The mentionables here are WxPython, which despite their Win95-type screenshots can support native Windows widges. Additionally, as Mike Graham mentioned, there is support for the great GTK+ through PyWin, whose Windows support has really come a long way their Window's screenshots can indicate the extent to which it is well-integrated with the native widget look-and-feel. PyQt uses the QT Toolkit, which also has good windows support, and, of course, there is always the option of using the Win32 wrappers to access the Windows GUI APIs directly (though, the APIs are quite ugly, which is not the wrappers so much as it is the Win32 APIs; this is probably only worth pursuing if you are already familiar with the Windows APIs). Two more options, somewhat more out of the box, would include leaving CPython behind and leveraging IronPython (which runs on the .NET runtime and hence has access to Windows.Forms, or, to be really obtuse Gtk# via Mono) and Jython (which runs on the JVM and can leverage either the quite messy Swing, which has some native Windows widget support or SWT, which supports native windows widgets). So, all in all, there are lots of options on Python to leverage the native Windowslibrary. A: Yes, you can use PyQt, or PySide (another Qt binding), or wxPython. They all support native look & feel. There's also PyGTK, but gtk apps don't to look so native .. I personally prefer Qt, so I'd suggest PyQt. If you have issues with the GPL, then you can use PySide (LGPL).
Can a native-looking GUI be made with Python
I haven't gotten far enough into Python to make GUIs yet, so I thought I'd ask here. Can a python app be made with the windows default style GUI, or will it have its own style? The only screenshots I've seen of a python app running with a GUI had this ugly win95 look to it.
[ "The \"ugly\" Windows 95 look is determined by the version of the Common Dialog library.\nSupplying a manifest file with the executable (probably your Python implementation) makes Windows use of visual styles, instead of the \"ugly\" look.\nRead more here: http://msdn.microsoft.com/en-us/library/ms997646.aspx\n", "You (and the rest of the world, really ;)) should take a look at PyGUI, by Greg Ewing. In his own words, it's \"a project to develop a cross-platform pythonic GUI API.\" Not only that, it attempts to generate native-looking GUIs on each of the three major platforms.\nWhen I'd last checked it, more than a year ago, it seemed dead, but now I see there was a new release on February 2010, which is great news. \n", "There are Python bindings for every major toolkit: GTK+, Qt, Tk, win32/MFC (not fun to use directly), wx (which in turn uses various other toolkits), Windows.Forms (through IronPython)...so in short, yes, probably.\nIf you define exactly what \"native\" should look like on what platform, someone can probably tell you exactly what you want. My favourite GUI toolkit is GTK (using PyGTK) which is native on Gnome and looks pretty good to me on Windows.\n", "There are loads of Python GUI libraries, among which, some support Windows. The mentionables here are WxPython, which despite their Win95-type screenshots can support native Windows widges. Additionally, as Mike Graham mentioned, there is support for the great GTK+ through PyWin, whose Windows support has really come a long way their Window's screenshots can indicate the extent to which it is well-integrated with the native widget look-and-feel. PyQt uses the QT Toolkit, which also has good windows support, and, of course, there is always the option of using the Win32 wrappers to access the Windows GUI APIs directly (though, the APIs are quite ugly, which is not the wrappers so much as it is the Win32 APIs; this is probably only worth pursuing if you are already familiar with the Windows APIs).\nTwo more options, somewhat more out of the box, would include leaving CPython behind and leveraging IronPython (which runs on the .NET runtime and hence has access to Windows.Forms, or, to be really obtuse Gtk# via Mono) and Jython (which runs on the JVM and can leverage either the quite messy Swing, which has some native Windows widget support or SWT, which supports native windows widgets).\nSo, all in all, there are lots of options on Python to leverage the native Windowslibrary. \n", "Yes, you can use PyQt, or PySide (another Qt binding), or wxPython. They all support native look & feel.\nThere's also PyGTK, but gtk apps don't to look so native ..\nI personally prefer Qt, so I'd suggest PyQt. If you have issues with the GPL, then you can use PySide (LGPL).\n" ]
[ 10, 8, 6, 3, 3 ]
[]
[]
[ "python", "user_interface" ]
stackoverflow_0002649882_python_user_interface.txt
Q: python interactive web data/forms/interface communicating with remote server What's an efficient method (preferably simple as well) for communicating with a remote server and allowing the user to 'interact' with it (IE submit commands, user interface) via the web browser (IE a text box to input commands, and an text area for output, or various command-less abstracted interfaces)? I have the 'standalone' python code finished for communicating and working(terminal/console based right now). My primary concern is with re-factoring the code to suite the web, which involves establishing a connection (python sockets), and maintaining the connection while the user is logged on. some further details: currently using django framework for the basic back end/templates. A: Probably the most efficient would be to set up REST as fmsf said. In general, each command would correspond to an URL with other variables attached: http://example.com/nuclear_warhead/activate/1 http://example.com/nuclear_warhead/activate/2 http://example.com/nuclear_warhead/activate/3 http://example.com/nuclear_warhead/position/1/AtlanticOcean http://example.com/nuclear_warhead/position/2/NorthPole http://example.com/nuclear_warhead/position/3/Moon http://example.com/nuclear_warhead/launch/1 http://example.com/nuclear_warhead/launch/2 http://example.com/nuclear_warhead/launch/3 You could either have these as client actions (they click on a link or submit a form) or as Ajax calls. For Ajax calls, they fill out a complicated form, the form formats it into an acceptable URL with attached data, and sends it to the server. Once the server processes the commands, it returns a result (in XML or JSON format, usually) which is parsed by the browser and displayed on the page. In a full RESTful app, you'd use the different HTTP methods of POST, GET, PUT, and DELETE to handle records http://example.com/secret_document/1 [POST] — creates the document http://example.com/secret_document/1 [PUT] — update the document http://example.com/secret_document/1 [GET] — retrieve the document http://example.com/secret_document/1 [DELETE] — delete the document Not all browsers can support all HTTP methods, however. In terms of implementation, Django is one option but a bit heavyweight for what you're looking for. You might want to look at this article which describes in full how you'd set up a lightweight application for responding to web client requests. You can definitely expand it out to add more functionality. A: If you're using django and want the front-end (html in the browser) to talk with the server it should be easy for you to adapt to AJAX. Here you go :) this will simplify your life A: There is some crazy code in weberror.pdbcapture to do general interactivity through the web. It's implemented as WSGI middleware that basically listens for anyone to ask for input on sys.stdin, and when that happens it starts to get input from the web form and send output back to that same page. You may not want to use it directly, but it gives some ideas if you really want something like a console through the web (which it kind of sounds like you want, I'm not clear).
python interactive web data/forms/interface communicating with remote server
What's an efficient method (preferably simple as well) for communicating with a remote server and allowing the user to 'interact' with it (IE submit commands, user interface) via the web browser (IE a text box to input commands, and an text area for output, or various command-less abstracted interfaces)? I have the 'standalone' python code finished for communicating and working(terminal/console based right now). My primary concern is with re-factoring the code to suite the web, which involves establishing a connection (python sockets), and maintaining the connection while the user is logged on. some further details: currently using django framework for the basic back end/templates.
[ "Probably the most efficient would be to set up REST as fmsf said. In general, each command would correspond to an URL with other variables attached:\nhttp://example.com/nuclear_warhead/activate/1\nhttp://example.com/nuclear_warhead/activate/2\nhttp://example.com/nuclear_warhead/activate/3\nhttp://example.com/nuclear_warhead/position/1/AtlanticOcean\nhttp://example.com/nuclear_warhead/position/2/NorthPole\nhttp://example.com/nuclear_warhead/position/3/Moon\nhttp://example.com/nuclear_warhead/launch/1\nhttp://example.com/nuclear_warhead/launch/2\nhttp://example.com/nuclear_warhead/launch/3\n\nYou could either have these as client actions (they click on a link or submit a form) or as Ajax calls. For Ajax calls, they fill out a complicated form, the form formats it into an acceptable URL with attached data, and sends it to the server. Once the server processes the commands, it returns a result (in XML or JSON format, usually) which is parsed by the browser and displayed on the page.\nIn a full RESTful app, you'd use the different HTTP methods of POST, GET, PUT, and DELETE to handle records\nhttp://example.com/secret_document/1 [POST] — creates the document\nhttp://example.com/secret_document/1 [PUT] — update the document\nhttp://example.com/secret_document/1 [GET] — retrieve the document\nhttp://example.com/secret_document/1 [DELETE] — delete the document\nNot all browsers can support all HTTP methods, however.\nIn terms of implementation, Django is one option but a bit heavyweight for what you're looking for. You might want to look at this article which describes in full how you'd set up a lightweight application for responding to web client requests. You can definitely expand it out to add more functionality.\n", "If you're using django and want the front-end (html in the browser) to talk with the server it should be easy for you to adapt to AJAX.\nHere you go :) this will simplify your life\n", "There is some crazy code in weberror.pdbcapture to do general interactivity through the web. It's implemented as WSGI middleware that basically listens for anyone to ask for input on sys.stdin, and when that happens it starts to get input from the web form and send output back to that same page. You may not want to use it directly, but it gives some ideas if you really want something like a console through the web (which it kind of sounds like you want, I'm not clear).\n" ]
[ 2, 1, 1 ]
[]
[]
[ "django", "javascript", "network_programming", "python" ]
stackoverflow_0002647685_django_javascript_network_programming_python.txt
Q: python remove everything between <div class="comment> .. any... how do you use python 2.6 to remove everything including the <div class="comment"> ....remove all ....</div> i tried various way using re.sub without any success Thank you A: This can be done easily and reliably using an HTML parser like BeautifulSoup: >>> from BeautifulSoup import BeautifulSoup >>> soup = BeautifulSoup('<body><div>1</div><div class="comment"><strong>2</strong></div></body>') >>> for div in soup.findAll('div', 'comment'): ... div.extract() ... <div class="comment"><strong>2</strong></div> >>> soup <body><div>1</div></body> See this question for examples on why parsing HTML using regular expressions is a bad idea. A: With lxml.html: from lxml import html doc = html.fromstring(input) for el in doc.cssselect('div.comment'): el.drop_tree() result = html.tostring(doc) A: You cannot properly parse HTML with regular expressions. Use a HTML parser such as lxml or BeautifulSoup. A: For the record, it is usually a bad idea to process XML with regular expressions. Nevertheless: >>> re.sub('>[^<]*', '>', '<div class="comment> .. any… </div>') '<div class="comment></div>' A: non regex way pat='<div class="comment">' for chunks in htmlstring.split("</div>"): m=chunks.find(pat) if m!=-1: chunks=chunks[:m] print chunks output $ cat file one two <tag> ....</tag> adsfh asdf <div class="comment"> ....remove all ....</div>s sdfds <div class="blah" ....... ..... blah </div> $ ./python.py one two <tag> ....</tag> adsfh asdf s sdfds <div class="blah" ....... ..... blah A: Use Beautiful soup and do something like this to get all of those elements, and then just replace inside tomatosoup = BeautifulSoup(myhtml) tomatochunks = tomatosoup.findall("div", {"class":"comment"} ) for chunk in tomatochunks: #remove the stuff
python remove everything between <div class="comment> .. any...
how do you use python 2.6 to remove everything including the <div class="comment"> ....remove all ....</div> i tried various way using re.sub without any success Thank you
[ "This can be done easily and reliably using an HTML parser like BeautifulSoup:\n>>> from BeautifulSoup import BeautifulSoup\n>>> soup = BeautifulSoup('<body><div>1</div><div class=\"comment\"><strong>2</strong></div></body>')\n>>> for div in soup.findAll('div', 'comment'):\n... div.extract()\n... \n<div class=\"comment\"><strong>2</strong></div>\n>>> soup\n<body><div>1</div></body>\n\nSee this question for examples on why parsing HTML using regular expressions is a bad idea.\n", "With lxml.html:\nfrom lxml import html\ndoc = html.fromstring(input)\nfor el in doc.cssselect('div.comment'):\n el.drop_tree()\nresult = html.tostring(doc)\n\n", "You cannot properly parse HTML with regular expressions. Use a HTML parser such as lxml or BeautifulSoup.\n", "For the record, it is usually a bad idea to process XML with regular expressions. Nevertheless:\n>>> re.sub('>[^<]*', '>', '<div class=\"comment> .. any… </div>')\n'<div class=\"comment></div>'\n\n", "non regex way\npat='<div class=\"comment\">'\nfor chunks in htmlstring.split(\"</div>\"):\n m=chunks.find(pat)\n if m!=-1:\n chunks=chunks[:m]\n print chunks\n\noutput\n$ cat file\none two <tag> ....</tag>\n adsfh asdf <div class=\"comment\"> ....remove\nall ....</div>s sdfds\n<div class=\"blah\" .......\n.....\nblah </div>\n\n$ ./python.py\none two <tag> ....</tag>\n adsfh asdf\ns sdfds\n<div class=\"blah\" .......\n.....\nblah\n\n", "Use Beautiful soup and do something like this to get all of those elements, and then just replace inside\ntomatosoup = BeautifulSoup(myhtml)\n\ntomatochunks = tomatosoup.findall(\"div\", {\"class\":\"comment\"} )\n\nfor chunk in tomatochunks:\n #remove the stuff\n\n" ]
[ 18, 3, 2, 0, 0, 0 ]
[]
[]
[ "class", "html", "python" ]
stackoverflow_0002649751_class_html_python.txt
Q: Lightweight cryptography toolkit(s) for C++ and Python I'm looking to do some basic encryption of server messages which would be encrypted with C++ and decrypted using Python server side. I was wondering if anyone knew if there were good solutions that were simpler or more lightweight than Keyczar. I see that supports both C++ and python, but would using Crypto++ and PyCrypto be simpler for a newbie that just wants to get something up and running for the time being? Or should I use Keyczar for python and Crypto++ for the C++ end? The C++ libraries seem to have dependencies to hundreds of files. A: The C++ libraries seem to have dependencies to hundreds of files. I don't know much about Python, but that is absolutely normal for C++. I'd recommend Crypto++ -- it's a great easy to use library, and it's public domain, meaning you won't have any license problems with it. EDIT: Keep in mind a large library with lots of code does not mean that you're going to pay in terms of object code. If there are functions you don't use (Crypto++ supports hundreds of algorithms) they won't be compiled into the resulting binary.
Lightweight cryptography toolkit(s) for C++ and Python
I'm looking to do some basic encryption of server messages which would be encrypted with C++ and decrypted using Python server side. I was wondering if anyone knew if there were good solutions that were simpler or more lightweight than Keyczar. I see that supports both C++ and python, but would using Crypto++ and PyCrypto be simpler for a newbie that just wants to get something up and running for the time being? Or should I use Keyczar for python and Crypto++ for the C++ end? The C++ libraries seem to have dependencies to hundreds of files.
[ "The C++ libraries seem to have dependencies to hundreds of files.\nI don't know much about Python, but that is absolutely normal for C++. I'd recommend Crypto++ -- it's a great easy to use library, and it's public domain, meaning you won't have any license problems with it.\nEDIT: Keep in mind a large library with lots of code does not mean that you're going to pay in terms of object code. If there are functions you don't use (Crypto++ supports hundreds of algorithms) they won't be compiled into the resulting binary.\n" ]
[ 2 ]
[]
[]
[ "c++", "cryptography", "encryption", "python" ]
stackoverflow_0002650073_c++_cryptography_encryption_python.txt
Q: How do Ruby and Python implement their interactive consoles? When implementing the interpreter for my programming language I first thought of a simple console window which allows the user to enter some code which is then executed as a standalone program as a shell. But there are severe problems: If every line of code the user enters is handled as a standalone program, it has to go through the tokenizer and parser and is then just executed by the interpreter - what about functions then? How can the Python/Ruby interactive consoles (IDLE, irb) "share" the code? How is the code entered handled? Example: >> def x: >> print("Blah") >> >> x() Where is the function stored so it can be called at any time again? How can the interactive console take everything entered as obviously one program without executing everything over and over again? A: For Python, an expression isn't complete until all parentheses, brackets, etc. match up. This is fairly easy to detect. A function/class definition isn't complete until a completely blank line is entered. The compiler then compiles the entered expression or definition, and runs it. Much like a normal function, class, module, etc., the REPL has its own local scope. It's this scope that is used for variables and definitions entered into the REPL. A: You can learn more about the Python interactive console by reading the documentation for the code module: The code module provides facilities to implement read-eval-print loops in Python. Two classes and convenience functions are included which can be used to build applications which provide an interactive interpreter prompt. http://docs.python.org/library/code.html A: Most of these languages use a parser which has a kind of "token stream" -- that is, the parser keeps taking tokens (a string, symbol, operator, etc) from the input stream until it has a full expression, then it returns that parsed expression where it might be compiled to bytecode or otherwise executed. A REPL loop is relatively simple to handle given that structure, as the parser basically asks for more input, and you give the user a prompt and have the user enter more input. You might need a bit of communication from the parser to the reader to make it render things like continuation prompts. Python and Ruby both execute statements immediately, in-order (a function declaration is one statement). So you can execute code statement-by-statement at the interpreter to largely the same effect as in a source file.
How do Ruby and Python implement their interactive consoles?
When implementing the interpreter for my programming language I first thought of a simple console window which allows the user to enter some code which is then executed as a standalone program as a shell. But there are severe problems: If every line of code the user enters is handled as a standalone program, it has to go through the tokenizer and parser and is then just executed by the interpreter - what about functions then? How can the Python/Ruby interactive consoles (IDLE, irb) "share" the code? How is the code entered handled? Example: >> def x: >> print("Blah") >> >> x() Where is the function stored so it can be called at any time again? How can the interactive console take everything entered as obviously one program without executing everything over and over again?
[ "For Python, an expression isn't complete until all parentheses, brackets, etc. match up. This is fairly easy to detect. A function/class definition isn't complete until a completely blank line is entered. The compiler then compiles the entered expression or definition, and runs it.\nMuch like a normal function, class, module, etc., the REPL has its own local scope. It's this scope that is used for variables and definitions entered into the REPL.\n", "You can learn more about the Python interactive console by reading the documentation for the code module:\n\nThe code module provides facilities to implement read-eval-print loops in Python. Two classes and convenience functions are included which can be used to build applications which provide an interactive interpreter prompt.\n\nhttp://docs.python.org/library/code.html\n", "Most of these languages use a parser which has a kind of \"token stream\" -- that is, the parser keeps taking tokens (a string, symbol, operator, etc) from the input stream until it has a full expression, then it returns that parsed expression where it might be compiled to bytecode or otherwise executed. A REPL loop is relatively simple to handle given that structure, as the parser basically asks for more input, and you give the user a prompt and have the user enter more input. You might need a bit of communication from the parser to the reader to make it render things like continuation prompts.\nPython and Ruby both execute statements immediately, in-order (a function declaration is one statement). So you can execute code statement-by-statement at the interpreter to largely the same effect as in a source file.\n" ]
[ 4, 3, 3 ]
[]
[]
[ "command_line_interface", "interactive", "interpreter", "python", "ruby" ]
stackoverflow_0002649250_command_line_interface_interactive_interpreter_python_ruby.txt
Q: How would I merged nested dictionaries in a list in python? for example if i had the result [{'Germany': {"Luge - Men's Singles": 'Gold'}}, {'Germany': {"Luge - Men's Singles": 'Silver'}}, {'Italy': {"Luge - Men's Singles": 'Bronze'}}] [{'Germany': {"Luge - Women's Singles": 'Gold'}}, {'Austria': {"Luge - Women's Singles": 'Silver'}}, {'Germany': {"Luge - Women's Singles": 'Bronze'}}] [{'Austria': {'Luge - Doubles': 'Gold'}}, {'Latvia': {'Luge - Doubles': 'Silver'}}, {'Germany': {'Luge - Doubles': 'Bronze'}}] how would I sort this so that all of the events germany and so on had won could be under one single title. i.e germany would be germany:Luge - Men's Singles: Gold, Silver, Luge - Women's Singles: Gold, Bronze, Luge - Doubles: Bronze. thanks for any help EDIT: this is a straight copy and paste from the python shell now to help confusion: [{'Germany': {"Luge - Men's Singles": 'Gold'}}, {'Germany': {"Luge - Men's Singles": 'Silver'}}, {'Italy': {"Luge - Men's Singles": 'Bronze'}}] [{'Germany': {"Luge - Women's Singles": 'Gold'}}, {'Austria': {"Luge - Women's Singles": 'Silver'}}, {'Germany': {"Luge - Women's Singles": 'Bronze'}}] [{'Austria': {'Luge - Doubles': 'Gold'}}, {'Latvia': {'Luge - Doubles': 'Silver'}}, {'Germany': {'Luge - Doubles': 'Bronze'}}] sorry about that im new to this site. It loops round 3 time one for each different event and i was wondering if i could get the desired from merging it after the final loop? A: import collections merged_result = collections.defaultdict(list) for L in listoflistsofdicts: for d in L: for k in d: merged_result[k].append(d[k]) or if you just have a list of dicts instead of a list of lists of dicts (hard to say from your Q!-), then just the for d in listofdicts: for k in d: merged_result[k].append(d[k]) part of the loop. If you want strings rather than lists as the values of merged_result then after the above code add for k in merged_result: merged_result[k] = ', '.join(merged_result[k]) or, equivalently (but building a new plain dict instead of the defaultdict): merged_result = dict((k, ', '.join(v)) for k, v in merged_result.iteritems()) (this assumes Python 2.* -- in Python 3, use .items instead of .iteritems). Edit: looking at the sample code it looks like it's invalid syntax for a list of list of dicts (missing commas) so I showed how to deal with that, too. A: (Sorry, I really meant this as a comment on Alex Martelli's answer, since mine is based on his; but when I originally posted I didn't have enough reputation to comment) Alex's answer doesn't actually generate the intended result. I don't mean the finer points of having a list of lists of dicts, or the lack of commas between the lists (more on that later). But the original question wanted, as a result, a compilation of all medals by country, by competition. Alex's solution will answer: > 'Germany': [{"Luge - Men's Singles": 'Gold'}, {"Luge - Men's Singles": 'Silver'}, {"Luge - Women's Singles": 'Gold'}, {"Luge - Women's Singles": 'Bronze'}, {'Luge - Doubles': 'Bronze'}] But I believe the original question actually asked for: > 'Germany': [{"Luge - Men's Singles": ['Gold', 'Silver']}, {"Luge - Women's Singles": ['Gold', 'Bronze'}, {'Luge - Doubles': 'Bronze'}] The data in the question is a bit confusing, I see two possibilities: 1) The data shown is actually three different examples, and the task is to merge dict entries within each list, separately. That is, given [{'Germany': {"Luge - Men's Singles": 'Gold'}}, {'Germany': {"Luge - Men's Singles": 'Silver'}}, {'Italy': {"Luge - Men's Singles": 'Bronze'}}] you want ['Germany': {"Luge - Men's Singles": ['Gold', 'Silver'], "Luge - Women's Singles": ['Gold', 'Bronze']}, 'Italy': {"Luge - Men's Singles": ['Bronze']}] , given [{'Germany': {"Luge - Women's Singles": 'Gold'}}, {'Austria': {"Luge - Women's Singles": 'Silver'}}, {'Germany': {"Luge - Women's Singles": 'Bronze'}}] you want ['Germany': {"Luge - Women's Singles": ['Gold', 'Bronze']}, 'Austria': {"Luge - Women's Singles": ['Silver']}] and so on. I gather this is the most likely interpretation of the question. The following code does that: from collections import defaultdict merged = defaultdict(lambda: defaultdict(list)) for d in list_of_dicts: for k in d: for competition, medal in d[k].iteritems(): merged[k][competition].append(medal) Running this for the first of the lists shown above, you get defaultdict(<function <lambda> at 0x1907db0>, {'Italy': defaultdict(<type 'list'>, {"Luge - Men's Singles": ['Bronze']}), 'Germany': defaultdict(<type 'list'>, {"Luge - Men's Singles": ['Gold', 'Silver']})}) 2) The second possibility is that the data in the question is one single list, containing 3 lists, each of these containing dicts. I think this is not what the original question means, but, since I'd already written the code for that, here it is :) from collections import defaultdict merged = defaultdict(lambda: defaultdict(list)) for L in listoflistsofdicts: for d in L: for k in d: for competition, medal in d[k].iteritems(): merged[k][competition].append(medal) Running the code above for the lists shown on the question (with the necessary commas added, you get: defaultdict(<function <lambda> at 0x1904b70>, {'Italy': defaultdict(<type 'list'>, {"Luge - Men's Singles": ['Bronze']}), 'Austria': defaultdict(<type 'list'>, {'Luge - Doubles': ['Gold'], "Luge - Women's Singles": ['Silver']}), 'Latvia': defaultdict(<type 'list'>, {'Luge - Doubles': ['Silver']}), 'Germany': defaultdict(<type 'list'>, {'Luge - Doubles': ['Bronze'], "Luge - Men's Singles": ['Gold', 'Silver'], "Luge - Women's Singles": ['Gold', 'Bronze']}) }) Please note that both of these codes don't sort medal types (i.e., you might end up with ['Gold', 'Silver'] or ['Silver', 'Gold']). Of course, if you get separated lists as used in solution 1), but need a merge of all of them, simply bring them all together in a list, and use solution 2).
How would I merged nested dictionaries in a list in python?
for example if i had the result [{'Germany': {"Luge - Men's Singles": 'Gold'}}, {'Germany': {"Luge - Men's Singles": 'Silver'}}, {'Italy': {"Luge - Men's Singles": 'Bronze'}}] [{'Germany': {"Luge - Women's Singles": 'Gold'}}, {'Austria': {"Luge - Women's Singles": 'Silver'}}, {'Germany': {"Luge - Women's Singles": 'Bronze'}}] [{'Austria': {'Luge - Doubles': 'Gold'}}, {'Latvia': {'Luge - Doubles': 'Silver'}}, {'Germany': {'Luge - Doubles': 'Bronze'}}] how would I sort this so that all of the events germany and so on had won could be under one single title. i.e germany would be germany:Luge - Men's Singles: Gold, Silver, Luge - Women's Singles: Gold, Bronze, Luge - Doubles: Bronze. thanks for any help EDIT: this is a straight copy and paste from the python shell now to help confusion: [{'Germany': {"Luge - Men's Singles": 'Gold'}}, {'Germany': {"Luge - Men's Singles": 'Silver'}}, {'Italy': {"Luge - Men's Singles": 'Bronze'}}] [{'Germany': {"Luge - Women's Singles": 'Gold'}}, {'Austria': {"Luge - Women's Singles": 'Silver'}}, {'Germany': {"Luge - Women's Singles": 'Bronze'}}] [{'Austria': {'Luge - Doubles': 'Gold'}}, {'Latvia': {'Luge - Doubles': 'Silver'}}, {'Germany': {'Luge - Doubles': 'Bronze'}}] sorry about that im new to this site. It loops round 3 time one for each different event and i was wondering if i could get the desired from merging it after the final loop?
[ "import collections\n\nmerged_result = collections.defaultdict(list)\n\nfor L in listoflistsofdicts:\n for d in L:\n for k in d:\n merged_result[k].append(d[k])\n\nor if you just have a list of dicts instead of a list of lists of dicts (hard to say from your Q!-), then just the\n for d in listofdicts:\n for k in d:\n merged_result[k].append(d[k])\n\npart of the loop.\nIf you want strings rather than lists as the values of merged_result then after the above code add\nfor k in merged_result:\n merged_result[k] = ', '.join(merged_result[k])\n\nor, equivalently (but building a new plain dict instead of the defaultdict):\nmerged_result = dict((k, ', '.join(v)) for k, v in merged_result.iteritems())\n\n(this assumes Python 2.* -- in Python 3, use .items instead of .iteritems).\nEdit: looking at the sample code it looks like it's invalid syntax for a list of list of dicts (missing commas) so I showed how to deal with that, too.\n", "(Sorry, I really meant this as a comment on Alex Martelli's answer, since mine is based on his; but when I originally posted I didn't have enough reputation to comment)\nAlex's answer doesn't actually generate the intended result. I don't mean the finer points of having a list of lists of dicts, or the lack of commas between the lists (more on that later). But the original question wanted, as a result, a compilation of all medals by country, by competition. Alex's solution will answer:\n> 'Germany': [{\"Luge - Men's Singles\": 'Gold'},\n {\"Luge - Men's Singles\": 'Silver'},\n {\"Luge - Women's Singles\": 'Gold'},\n {\"Luge - Women's Singles\": 'Bronze'},\n {'Luge - Doubles': 'Bronze'}]\n\nBut I believe the original question actually asked for:\n> 'Germany': [{\"Luge - Men's Singles\": ['Gold', 'Silver']},\n {\"Luge - Women's Singles\": ['Gold', 'Bronze'},\n {'Luge - Doubles': 'Bronze'}]\n\nThe data in the question is a bit confusing, I see two possibilities:\n1) The data shown is actually three different examples, and the task is to merge dict entries within each list, separately. That is, given\n[{'Germany': {\"Luge - Men's Singles\": 'Gold'}}, \n{'Germany': {\"Luge - Men's Singles\": 'Silver'}},\n{'Italy': {\"Luge - Men's Singles\": 'Bronze'}}]\n\nyou want\n['Germany': {\"Luge - Men's Singles\": ['Gold', 'Silver'],\n \"Luge - Women's Singles\": ['Gold', 'Bronze']},\n 'Italy': {\"Luge - Men's Singles\": ['Bronze']}]\n\n, given \n[{'Germany': {\"Luge - Women's Singles\": 'Gold'}},\n{'Austria': {\"Luge - Women's Singles\": 'Silver'}},\n{'Germany': {\"Luge - Women's Singles\": 'Bronze'}}]\n\nyou want\n['Germany': {\"Luge - Women's Singles\": ['Gold', 'Bronze']},\n 'Austria': {\"Luge - Women's Singles\": ['Silver']}]\n\nand so on. I gather this is the most likely interpretation of the question.\nThe following code does that:\nfrom collections import defaultdict\n\nmerged = defaultdict(lambda: defaultdict(list))\nfor d in list_of_dicts:\n for k in d:\n for competition, medal in d[k].iteritems():\n merged[k][competition].append(medal)\n\nRunning this for the first of the lists shown above, you get\ndefaultdict(<function <lambda> at 0x1907db0>,\n {'Italy': defaultdict(<type 'list'>, {\"Luge - Men's Singles\": ['Bronze']}),\n 'Germany': defaultdict(<type 'list'>, {\"Luge - Men's Singles\": ['Gold', 'Silver']})})\n\n2) The second possibility is that the data in the question is one single list, containing 3 lists, each of these containing dicts. I think this is not what the original question means, but, since I'd already written the code for that, here it is :)\nfrom collections import defaultdict\n\nmerged = defaultdict(lambda: defaultdict(list))\nfor L in listoflistsofdicts:\n for d in L:\n for k in d:\n for competition, medal in d[k].iteritems():\n merged[k][competition].append(medal)\n\nRunning the code above for the lists shown on the question (with the necessary commas added, you get:\n defaultdict(<function <lambda> at 0x1904b70>,\n {'Italy': defaultdict(<type 'list'>, {\"Luge - Men's Singles\": ['Bronze']}),\n 'Austria': defaultdict(<type 'list'>, {'Luge - Doubles': ['Gold'],\n \"Luge - Women's Singles\": ['Silver']}),\n 'Latvia': defaultdict(<type 'list'>, {'Luge - Doubles': ['Silver']}),\n 'Germany': defaultdict(<type 'list'>, {'Luge - Doubles': ['Bronze'],\n \"Luge - Men's Singles\": ['Gold', 'Silver'],\n \"Luge - Women's Singles\": ['Gold', 'Bronze']})\n })\n\nPlease note that both of these codes don't sort medal types (i.e., you might end up with ['Gold', 'Silver'] or ['Silver', 'Gold']).\nOf course, if you get separated lists as used in solution 1), but need a merge of all of them, simply bring them all together in a list, and use solution 2).\n" ]
[ 4, 1 ]
[]
[]
[ "add", "dictionary", "merge", "python" ]
stackoverflow_0002646480_add_dictionary_merge_python.txt
Q: Simple non-network concurrency with Twisted I have a problem with using Twisted for simple concurrency in python. The problem is - I don't know how to do it and all online resources are about Twisted networking abilities. So I am turning to SO-gurus for some guidance. Python 2.5 is used. Simplified version of my problem runs as follows: A bunch of scientific data A function that munches on the data and creates output ??? < here enters concurrency, it takes chunks of data from 1 and feeds it to 2 Output from 3 is joined and stored My guess is that Twisted reactor can do the number three job. But how? Thanks a lot for any help and suggestions. upd1: Simple example code. No idea how reactor deals with processes, so I have given it imaginary functions: datum = 'abcdefg' def dataServer(data): for char in data: yield chara def dataWorker(chara): return ord(chara) r = reactor() NUMBER_OF_PROCESSES_AV = 4 serv = dataserver(datum) id = 0 result = array(len(datum)) while r.working(): if NUMBER_OF_PROCESSES_AV > 0: r.addTask(dataWorker(serv.next(), id) NUMBER_OF_PROCESSES_AV -= 1 id += 1 for pr, id in r.finishedProcesses(): result[id] = pr A: As Jean-Paul said, Twisted is great for coordinating multiple processes. However, unless you need to use Twisted, and simply need a distributed processing pool, there are possibly better suited tools out there. One I can think of which hasn't been mentioned is celery. Celery is a distributed task queue - you set up a queue of tasks running a DB, Redis or RabbitMQ (you can choose from a number of free software options), and write a number of compute tasks. These can be arbitrary scientific computing type tasks. Tasks can spawn subtasks (implementing your "joining" step you mention above). You then start as many workers as you need and compute away. I'm a heavy user of Twisted and Celery, so in any case, both options are good. A: To actually compute things concurrently, you'll probably need to employ multiple Python processes. A single Python process can interleave calculations, but it won't execute them in parallel (with a few exceptions). Twisted is a good way to coordinate these multiple processes and collect their results. One library oriented towards solving this task is Ampoule. You can find more information about Ampoule on its Launchpad page: https://launchpad.net/ampoule. A: Do you need Twisted at all? From your description of the problem I'd say that multiprocessing would fit the bill. Create a number of Process objects that are given a reference to a single Queue instance. Get them to start their work and put their results on the Queue. Just use blocking get()s to read the results. A: It seems to me that you are misunderstanding the fundamentals of how Twisted operates. I recommend you give the Twisted Intro a shot by Dave Peticolas. It has been a great help to me, and I've been using Twisted for years! HINT: Everything in Twisted relies on the reactor! (source: krondo.com)
Simple non-network concurrency with Twisted
I have a problem with using Twisted for simple concurrency in python. The problem is - I don't know how to do it and all online resources are about Twisted networking abilities. So I am turning to SO-gurus for some guidance. Python 2.5 is used. Simplified version of my problem runs as follows: A bunch of scientific data A function that munches on the data and creates output ??? < here enters concurrency, it takes chunks of data from 1 and feeds it to 2 Output from 3 is joined and stored My guess is that Twisted reactor can do the number three job. But how? Thanks a lot for any help and suggestions. upd1: Simple example code. No idea how reactor deals with processes, so I have given it imaginary functions: datum = 'abcdefg' def dataServer(data): for char in data: yield chara def dataWorker(chara): return ord(chara) r = reactor() NUMBER_OF_PROCESSES_AV = 4 serv = dataserver(datum) id = 0 result = array(len(datum)) while r.working(): if NUMBER_OF_PROCESSES_AV > 0: r.addTask(dataWorker(serv.next(), id) NUMBER_OF_PROCESSES_AV -= 1 id += 1 for pr, id in r.finishedProcesses(): result[id] = pr
[ "As Jean-Paul said, Twisted is great for coordinating multiple processes. However, unless you need to use Twisted, and simply need a distributed processing pool, there are possibly better suited tools out there.\nOne I can think of which hasn't been mentioned is celery. Celery is a distributed task queue - you set up a queue of tasks running a DB, Redis or RabbitMQ (you can choose from a number of free software options), and write a number of compute tasks. These can be arbitrary scientific computing type tasks. Tasks can spawn subtasks (implementing your \"joining\" step you mention above). You then start as many workers as you need and compute away.\nI'm a heavy user of Twisted and Celery, so in any case, both options are good.\n", "To actually compute things concurrently, you'll probably need to employ multiple Python processes. A single Python process can interleave calculations, but it won't execute them in parallel (with a few exceptions).\nTwisted is a good way to coordinate these multiple processes and collect their results. One library oriented towards solving this task is Ampoule. You can find more information about Ampoule on its Launchpad page: https://launchpad.net/ampoule.\n", "Do you need Twisted at all?\nFrom your description of the problem I'd say that multiprocessing would fit the bill. Create a number of Process objects that are given a reference to a single Queue instance. Get them to start their work and put their results on the Queue. Just use blocking get()s to read the results.\n", "It seems to me that you are misunderstanding the fundamentals of how Twisted operates. I recommend you give the Twisted Intro a shot by Dave Peticolas. It has been a great help to me, and I've been using Twisted for years!\nHINT: Everything in Twisted relies on the reactor!\n\n(source: krondo.com) \n" ]
[ 4, 3, 2, 1 ]
[]
[]
[ "concurrency", "python", "twisted" ]
stackoverflow_0002539599_concurrency_python_twisted.txt
Q: Using the Queue class in Python 2.6 Let's assume I'm stuck using Python 2.6, and can't upgrade (even if that would help). I've written a program that uses the Queue class. My producer is a simple directory listing. My consumer threads pull a file from the queue, and do stuff with it. If the file has already been processed, I skip it. The processed list is generated before all of the threads are started, so it isn't empty. Here's some pseudo-code. import Queue, sys, threading processed = [] def consumer(): while True: file = dirlist.get(block=True) if file in processed: print "Ignoring %s" % file else: # do stuff here dirlist.task_done() dirlist = Queue.Queue() for f in os.listdir("/some/dir"): dirlist.put(f) max_threads = 8 for i in range(max_threads): thr = Thread(target=consumer) thr.start() dirlist.join() The strange behavior I'm getting is that if a thread encounters a file that's already been processed, the thread stalls out and waits until the entire program ends. I've done a little bit of testing, and the first 7 threads (assuming 8 is the max) stop, while the 8th thread keeps processing, one file at a time. But, by doing that, I'm losing the entire reason for threading the application. Am I doing something wrong, or is this the expected behavior of the Queue/threading classes in Python 2.6? A: I tried running your code, and did not see the behavior you describe. However, the program never exits. I recommend changing the .get() call as follows: try: file = dirlist.get(True, 1) except Queue.Empty: return If you want to know which thread is currently executing, you can import the thread module and print thread.get_ident(). I added the following line after the .get(): print file, thread.get_ident() and got the following output: bin 7116328 cygdrive 7116328 cygwin.bat 7149424 cygwin.ico 7116328 dev etc7598568 7149424 fix 7331000 home 7116328lib 7598568sbin 7149424Thumbs.db 7331000 tmp 7107008 usr 7116328 var 7598568proc 7441800 The output is messy because the threads are writing to stdout at the same time. The variety of thread identifiers further confirms that all of the threads are running. Perhaps something is wrong in the real code or your test methodology, but not in the code you posted? A: Since this problem only manifests itself when finding a file that's already been processed, it seems like this is something to do with the processed list itself. Have you tried implementing a simple lock? For example: processed = [] processed_lock = threading.Lock() def consumer(): while True: with processed_lock.acquire(): fileInList = file in processed if fileInList: # ... et cetera Threading tends to cause the strangest bugs, even if they seem like they "shouldn't" happen. Using locks on shared variables is the first step to make sure you don't end up with some kind of race condition that could cause threads to deadlock. Of course, if what you're doing under # do stuff here is CPU-intensive, then Python will only run code from one thread at a time anyway, due to the Global Interpreter Lock. In that case, you may want to switch to the multiprocessing module - it's very similar to threading, though you will need to replace shared variables with another solution (see here for details).
Using the Queue class in Python 2.6
Let's assume I'm stuck using Python 2.6, and can't upgrade (even if that would help). I've written a program that uses the Queue class. My producer is a simple directory listing. My consumer threads pull a file from the queue, and do stuff with it. If the file has already been processed, I skip it. The processed list is generated before all of the threads are started, so it isn't empty. Here's some pseudo-code. import Queue, sys, threading processed = [] def consumer(): while True: file = dirlist.get(block=True) if file in processed: print "Ignoring %s" % file else: # do stuff here dirlist.task_done() dirlist = Queue.Queue() for f in os.listdir("/some/dir"): dirlist.put(f) max_threads = 8 for i in range(max_threads): thr = Thread(target=consumer) thr.start() dirlist.join() The strange behavior I'm getting is that if a thread encounters a file that's already been processed, the thread stalls out and waits until the entire program ends. I've done a little bit of testing, and the first 7 threads (assuming 8 is the max) stop, while the 8th thread keeps processing, one file at a time. But, by doing that, I'm losing the entire reason for threading the application. Am I doing something wrong, or is this the expected behavior of the Queue/threading classes in Python 2.6?
[ "I tried running your code, and did not see the behavior you describe. However, the program never exits. I recommend changing the .get() call as follows:\n try:\n file = dirlist.get(True, 1)\n except Queue.Empty:\n return\n\nIf you want to know which thread is currently executing, you can import the thread module and print thread.get_ident().\nI added the following line after the .get():\n print file, thread.get_ident()\n\nand got the following output:\nbin 7116328\ncygdrive 7116328\n cygwin.bat 7149424\ncygwin.ico 7116328\n dev etc7598568\n7149424\n fix 7331000\n home 7116328lib\n 7598568sbin\n 7149424Thumbs.db\n 7331000\ntmp 7107008\n usr 7116328\nvar 7598568proc\n 7441800\n\nThe output is messy because the threads are writing to stdout at the same time. The variety of thread identifiers further confirms that all of the threads are running.\nPerhaps something is wrong in the real code or your test methodology, but not in the code you posted?\n", "Since this problem only manifests itself when finding a file that's already been processed, it seems like this is something to do with the processed list itself. Have you tried implementing a simple lock? For example:\nprocessed = []\nprocessed_lock = threading.Lock()\n\ndef consumer():\n while True:\n with processed_lock.acquire():\n fileInList = file in processed\n if fileInList:\n # ... et cetera\n\nThreading tends to cause the strangest bugs, even if they seem like they \"shouldn't\" happen. Using locks on shared variables is the first step to make sure you don't end up with some kind of race condition that could cause threads to deadlock.\n\nOf course, if what you're doing under # do stuff here is CPU-intensive, then Python will only run code from one thread at a time anyway, due to the Global Interpreter Lock. In that case, you may want to switch to the multiprocessing module - it's very similar to threading, though you will need to replace shared variables with another solution (see here for details).\n" ]
[ 2, 1 ]
[]
[]
[ "multithreading", "python", "queue" ]
stackoverflow_0002650057_multithreading_python_queue.txt
Q: How to replace by regular expression to lowercase in python I want to search key words (keys would be dynamic) and replace them in a certain format. For example: these data keys = ["cat", "dog", "mouse"] text = "Cat dog cat cloud miracle DOG MouSE" had to be converted to converted_text = "[Cat](cat) [dog](dog) [cat](cat) cloud miracle [DOG](dog) [MouSE](mouse)" Here is my code: keys = "cat|dog|mouse" p = re.compile(u'\\b(?iu)(?P<name>(%s))\\b' % keys) converted_text = re.sub(p, '[\g<name>](\g<name>)', text) And this works fine, only I can't convert last parameter to lower case. This converts like this: converted_text = "[Cat](cat) [dog](dog) [cat](cat) cloud miracle [DOG](DOG) [MouSE](MouSE)" how can i convert the last parameter to lowercase? it seems python can't compile the \L sign. A: You can use a function to do the replacing: pattern = re.compile('|'.join(map(re.escape, keys)), re.IGNORECASE) def format_term(term): return '[%s](%s)' % (term, term.lower()) converted_text = pattern.sub(lambda m: format_term(m.group(0)), text) A: no need to use regex >>> keys = ["cat", "dog", "mouse"] >>> text = "Cat dog cat cloud miracle DOG MouSE" >>> for w in text.split(): ... if w.lower() in keys: ... print "[%s]%s" %(w,w.lower()), ... else: ... print w, ... [Cat]cat [dog]dog [cat]cat cloud miracle [DOG]dog [MouSE]mouse A: From your proposed solution, I assume I don't need to keep the keys as a list (I'll use a set, to make searching faster). This answer also assumes all words in the text are separated by a space (which I'll use to join them back). Give these, you can use: >>> keys = (["cat", "dog", "mouse"]) >>> text = "Cat dog cat cloud miracle DOG MouSE" >>> converted = " ".join(("[%s](%s)" % (word, word.lower()) if word.lower() in keys else word) for word in text.split()) >>> converted '[Cat](cat) [dog](dog) [cat](cat) cloud miracle [DOG](dog) [MouSE](mouse)' Granted, this calls word.lower() twice. You can avoid this (and still use a similar approach) using two list comprehensions (or, actually, generator expressions): >>> converted = " ".join(("[%s](%s)" % (word, lower) if lower in keys else word) for word, lower in ((w, w.lower()) for w in text.split())) >>> converted '[Cat](cat) [dog](dog) [cat](cat) cloud miracle [DOG](dog) [MouSE](mouse)'
How to replace by regular expression to lowercase in python
I want to search key words (keys would be dynamic) and replace them in a certain format. For example: these data keys = ["cat", "dog", "mouse"] text = "Cat dog cat cloud miracle DOG MouSE" had to be converted to converted_text = "[Cat](cat) [dog](dog) [cat](cat) cloud miracle [DOG](dog) [MouSE](mouse)" Here is my code: keys = "cat|dog|mouse" p = re.compile(u'\\b(?iu)(?P<name>(%s))\\b' % keys) converted_text = re.sub(p, '[\g<name>](\g<name>)', text) And this works fine, only I can't convert last parameter to lower case. This converts like this: converted_text = "[Cat](cat) [dog](dog) [cat](cat) cloud miracle [DOG](DOG) [MouSE](MouSE)" how can i convert the last parameter to lowercase? it seems python can't compile the \L sign.
[ "You can use a function to do the replacing:\npattern = re.compile('|'.join(map(re.escape, keys)), re.IGNORECASE)\ndef format_term(term):\n return '[%s](%s)' % (term, term.lower())\n\nconverted_text = pattern.sub(lambda m: format_term(m.group(0)), text)\n\n", "no need to use regex\n>>> keys = [\"cat\", \"dog\", \"mouse\"]\n>>> text = \"Cat dog cat cloud miracle DOG MouSE\"\n>>> for w in text.split():\n... if w.lower() in keys:\n... print \"[%s]%s\" %(w,w.lower()),\n... else:\n... print w,\n...\n[Cat]cat [dog]dog [cat]cat cloud miracle [DOG]dog [MouSE]mouse\n\n", "From your proposed solution, I assume I don't need to keep the keys as a list (I'll use a set, to make searching faster). This answer also assumes all words in the text are separated by a space (which I'll use to join them back). Give these, you can use:\n>>> keys = ([\"cat\", \"dog\", \"mouse\"])\n>>> text = \"Cat dog cat cloud miracle DOG MouSE\"\n>>> converted = \" \".join((\"[%s](%s)\" % (word, word.lower()) if word.lower() in keys else word) for word in text.split())\n>>> converted\n'[Cat](cat) [dog](dog) [cat](cat) cloud miracle [DOG](dog) [MouSE](mouse)'\n\nGranted, this calls word.lower() twice. You can avoid this (and still use a similar approach) using two list comprehensions (or, actually, generator expressions):\n>>> converted = \" \".join((\"[%s](%s)\" % (word, lower) if lower in keys else word) for word, lower in ((w, w.lower()) for w in text.split()))\n>>> converted\n'[Cat](cat) [dog](dog) [cat](cat) cloud miracle [DOG](dog) [MouSE](mouse)'\n\n" ]
[ 11, 3, 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002643737_python_regex.txt
Q: How to give an error when no options are given with optparse I'm try to work out how to use optparse, but I've come to a problem. My script (represented by this simplified example) takes a file, and does different things to it depending on options that are parsed to it. If no options are parsed nothing is done. It makes sense to me that because of this, an error should be given if no options are given by the user. I can't work out how to do this. I've read that options should be optional and not required. Does this mean I am using options in the wrong way? If so, how should I be doing it instead? I can't see any other way of going about it. #!/usr/bin/python from optparse import OptionParser dict = {'name': foo, 'age': bar} parser = OptionParser() parser.add_option("-n", "--name", dest="name") parser.add_option("-a", "--age", dest="age") (options, args) = parser.parse_args() if options.name: dict['name'] = options.name if options.age: dict['age'] = options.age print dict #END A: The required argument to a program is usually given without a flag, i.e.: munch <filename> And not: munch --name <filename> This custom makes sure the user realizes that <filename> is mandatory and not optional. parse_args returns the options object and a list of leftover arguments - those without flags. If that list is short enough for you (i.e. no filename while you expected one), feel free to throw an error, and you could use optparse's capability to show usage, for that. A: I don't know if I'd call it "wrong" necessarily, but yeah, you are using options in a way that isn't intended. (I've done it too, for quick scripts) Consider making the first non-option argument be a command word that specifies what your script should do; if you want to allow multiple actions to be performed by the script, you could take multiple non-option arguments. This is the way that git (or Subversion, or any of many other version control systems) does it, for example: git status to check the status of files, or git stash to save a copy of your work in progress, or git commit to commit changes to the repository. The first non-option argument specifies the action to take. If you do it that way, it'll be easy to see whether no command has been provided by checking the length of args returned from parser.parse_args(). A: the parse_args method will eat up all the options on the commandline (which is the text immediately following the script name that starts with - or -- (and contains a value if that particular option is defined to have a value). Everything left over after all the possible options have been parsed, is called "positional arguments". These can be accessed as the usual sys.argv[1:] list. So args that are not "optional" (as your requirement says), should really be positional args and not part of the "options", ie., they should not be of the form myscript.py --someopt=mandatory but myscript.py --someopt --someotheropt <madatory arg1> <mandatory arg2> Knowing this, you can easily write the correct logic for the sys.argv right after the pars_args call (e.g., throw an error if the remaining argv doesn't have the two mandatory args)
How to give an error when no options are given with optparse
I'm try to work out how to use optparse, but I've come to a problem. My script (represented by this simplified example) takes a file, and does different things to it depending on options that are parsed to it. If no options are parsed nothing is done. It makes sense to me that because of this, an error should be given if no options are given by the user. I can't work out how to do this. I've read that options should be optional and not required. Does this mean I am using options in the wrong way? If so, how should I be doing it instead? I can't see any other way of going about it. #!/usr/bin/python from optparse import OptionParser dict = {'name': foo, 'age': bar} parser = OptionParser() parser.add_option("-n", "--name", dest="name") parser.add_option("-a", "--age", dest="age") (options, args) = parser.parse_args() if options.name: dict['name'] = options.name if options.age: dict['age'] = options.age print dict #END
[ "The required argument to a program is usually given without a flag, i.e.:\nmunch <filename>\n\nAnd not:\nmunch --name <filename>\n\nThis custom makes sure the user realizes that <filename> is mandatory and not optional. parse_args returns the options object and a list of leftover arguments - those without flags. If that list is short enough for you (i.e. no filename while you expected one), feel free to throw an error, and you could use optparse's capability to show usage, for that.\n", "I don't know if I'd call it \"wrong\" necessarily, but yeah, you are using options in a way that isn't intended. (I've done it too, for quick scripts) Consider making the first non-option argument be a command word that specifies what your script should do; if you want to allow multiple actions to be performed by the script, you could take multiple non-option arguments. This is the way that git (or Subversion, or any of many other version control systems) does it, for example:\ngit status\n\nto check the status of files, or\ngit stash\n\nto save a copy of your work in progress, or\ngit commit\n\nto commit changes to the repository. The first non-option argument specifies the action to take. If you do it that way, it'll be easy to see whether no command has been provided by checking the length of args returned from parser.parse_args().\n", "the parse_args method will eat up all the options on the commandline (which is the text immediately following the script name that starts with - or -- (and contains a value if that particular option is defined to have a value). Everything left over after all the possible options have been parsed, is called \"positional arguments\". These can be accessed as the usual sys.argv[1:] list. So args that are not \"optional\" (as your requirement says), should really be positional args and not part of the \"options\", ie., they should not be of the form \nmyscript.py --someopt=mandatory\nbut \nmyscript.py --someopt --someotheropt <madatory arg1> <mandatory arg2>\nKnowing this, you can easily write the correct logic for the sys.argv right after the pars_args call (e.g., throw an error if the remaining argv doesn't have the two mandatory args)\n" ]
[ 2, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002650612_python.txt
Q: python interval i've dev code for wifi scanning in python, now i trying to modify my code so it will scan wifi at specific interval, how this can be done thanks A: You generally have two solutions: schedule to run the python script which refreshes WIFI info at various interval, using crontab or similar external device. keep the [python] program running and use threading.timer to schedule calls to the WIFI checking routine at desired intervals. A: If you want it all within a long-running Python process (as opposed to a more normal cron-run script), the sched module in the Python standard library is probably the best way to schedule periodically repeated execution of a function or other callable (key trick: to schedule periodically, have each execution schedule the next one at appropriate delay -- the very classic, language-independent pattern to turn one-off scheduling into periodic repeats).
python interval
i've dev code for wifi scanning in python, now i trying to modify my code so it will scan wifi at specific interval, how this can be done thanks
[ "You generally have two solutions: \n\nschedule to run the python script which refreshes WIFI info at various interval, using crontab or similar external device.\nkeep the [python] program running and use threading.timer to schedule calls to the WIFI checking routine at desired intervals.\n\n", "If you want it all within a long-running Python process (as opposed to a more normal cron-run script), the sched module in the Python standard library is probably the best way to schedule periodically repeated execution of a function or other callable (key trick: to schedule periodically, have each execution schedule the next one at appropriate delay -- the very classic, language-independent pattern to turn one-off scheduling into periodic repeats).\n" ]
[ 4, 3 ]
[]
[]
[ "intervals", "python" ]
stackoverflow_0002650477_intervals_python.txt
Q: How do I redirect stdin/stdout when I have a sequence of commands in Bash? I've currently got a Bash command being executed (via Python's subprocess.Popen) which is reading from stdin, doing something and outputing to stdout. Something along the lines of: pid = subprocess.Popen( ["-c", "cmd1 | cmd2"], stdin = subprocess.PIPE, stdout = subprocess.PIPE, shell =True ) output_data = pid.communicate( "input data\n" ) Now, what I want to do is to change that to execute another command in that same subshell that will alter the state before the next commands execute, so my shell command line will now (conceptually) be: cmd0; cmd1 | cmd2 Is there any way to have the input sent to cmd1 instead of cmd0 in this scenario? I'm assuming the output will include cmd0's output (which will be empty) followed by cmd2's output. cmd0 shouldn't actually read anything from stdin, does that make a difference in this situation? I know this is probably just a dumb way of doing this, I'm trying to patch in cmd0 without altering the other code too significantly. That said, I'm open to suggestions if there's a much cleaner way to approach this. A: execute cmd0 and cmd1 in a subshell and redirect /dev/null as stdin for cmd0: (cmd0 </dev/null; cmd1) | cmd2 A: I don't think you should have to do anything special. If cmd0 doesn't touch stdin, it'll be intact for cmd1. Try for yourself: ls | ( echo "foo"; sed 's/^/input: /') (Using ls as an arbitrary command to produce a few lines of input for the pipeline) And the additional pipe to cmd2 doesn't affect the input either, of course. A: Ok, I think I may be able to duplicate the stdin file descriptor to a temporary one, close it, run cmd0, then restore it before running cmd1: exec 0>&3; exec 0<&-; cmd0 ; exec 3>&0 ; cmd1 | cmd2 Not sure if it's possible to redirect stdin in this way though, and can't test this at the moment. http://tldp.org/LDP/abs/html/io-redirection.html http://tldp.org/LDP/abs/html/x17601.html
How do I redirect stdin/stdout when I have a sequence of commands in Bash?
I've currently got a Bash command being executed (via Python's subprocess.Popen) which is reading from stdin, doing something and outputing to stdout. Something along the lines of: pid = subprocess.Popen( ["-c", "cmd1 | cmd2"], stdin = subprocess.PIPE, stdout = subprocess.PIPE, shell =True ) output_data = pid.communicate( "input data\n" ) Now, what I want to do is to change that to execute another command in that same subshell that will alter the state before the next commands execute, so my shell command line will now (conceptually) be: cmd0; cmd1 | cmd2 Is there any way to have the input sent to cmd1 instead of cmd0 in this scenario? I'm assuming the output will include cmd0's output (which will be empty) followed by cmd2's output. cmd0 shouldn't actually read anything from stdin, does that make a difference in this situation? I know this is probably just a dumb way of doing this, I'm trying to patch in cmd0 without altering the other code too significantly. That said, I'm open to suggestions if there's a much cleaner way to approach this.
[ "execute cmd0 and cmd1 in a subshell and redirect /dev/null as stdin for cmd0:\n(cmd0 </dev/null; cmd1) | cmd2\n\n", "I don't think you should have to do anything special. If cmd0 doesn't touch stdin, it'll be intact for cmd1. Try for yourself:\nls | ( echo \"foo\"; sed 's/^/input: /')\n\n(Using ls as an arbitrary command to produce a few lines of input for the pipeline)\nAnd the additional pipe to cmd2 doesn't affect the input either, of course.\n", "Ok, I think I may be able to duplicate the stdin file descriptor to a temporary one, close it, run cmd0, then restore it before running cmd1:\nexec 0>&3; exec 0<&-; cmd0 ; exec 3>&0 ; cmd1 | cmd2\n\nNot sure if it's possible to redirect stdin in this way though, and can't test this at the moment.\nhttp://tldp.org/LDP/abs/html/io-redirection.html\nhttp://tldp.org/LDP/abs/html/x17601.html\n" ]
[ 4, 1, 0 ]
[]
[]
[ "bash", "pipe", "python", "subprocess" ]
stackoverflow_0002650759_bash_pipe_python_subprocess.txt
Q: Basic anydbm example generates 'AttributeError: iteritems' I'm attempting a pretty cut & dry example of anydbm: #!/usr/bin/python import anydbm # Open database, creating it if necessary. db = anydbm.open('cache', 'c') # Record some values db['www.python.org'] = 'Python Website' db['www.cnn.com'] = 'Cable News Network' for k, v in db.iteritems(): print k, '\t', v Yet, on my machine (OS X 10.5.8, Python 2.5.1), I get the following error: Traceback (most recent call last): File "./foo.py", line 12, in for k, v in db.iteritems(): AttributeError: iteritems Any suggestions? A: It appears the Apple-supplied Pythons are not built with any third-party database libraries so anydbm results in the use of the default portable dumbdbm implementation which lacks an iteritems method. $ /usr/bin/python2.5 Python 2.5.4 (r254:67916, Feb 11 2010, 00:50:55) [GCC 4.2.1 (Apple Inc. build 5646)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import anydbm >>> db = anydbm.open('cache', 'c') >>> dir(db) ['close', 'get', 'has_key', 'keys', 'setdefault'] The python.org OS X Pythons, on the other hand, are built with a real dbm interface: $ /usr/local/bin/python2.5 Python 2.5.4 (r254:67917, Dec 23 2008, 14:57:27) [GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import anydbm >>> db = anydbm.open('cache2', 'c') >>> dir(db) ['__cmp__', '__contains__', '__del__', '__delitem__', '__doc__', '__getitem__', '__init__', '__iter__', '__len__', '__module__', '__repr__', '__setitem__', '_checkCursor', '_checkOpen', '_closeCursors', '_cursor_refs', '_gen_cref_cleaner', '_make_iter_cursor', 'clear', 'close', 'db', 'dbc', 'first', 'get', 'has_key', 'isOpen', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'last', 'next', 'pop', 'popitem', 'previous', 'saved_dbc_key', 'set_location', 'setdefault', 'sync', 'update', 'values'] >>> db.iteritems() <generator object at 0x481760> >>> db.__module__ 'bsddb' There are some open issues on the Python bug tracker concerning some of the dbm modules inconsistencies.
Basic anydbm example generates 'AttributeError: iteritems'
I'm attempting a pretty cut & dry example of anydbm: #!/usr/bin/python import anydbm # Open database, creating it if necessary. db = anydbm.open('cache', 'c') # Record some values db['www.python.org'] = 'Python Website' db['www.cnn.com'] = 'Cable News Network' for k, v in db.iteritems(): print k, '\t', v Yet, on my machine (OS X 10.5.8, Python 2.5.1), I get the following error: Traceback (most recent call last): File "./foo.py", line 12, in for k, v in db.iteritems(): AttributeError: iteritems Any suggestions?
[ "It appears the Apple-supplied Pythons are not built with any third-party database libraries so anydbm results in the use of the default portable dumbdbm implementation which lacks an iteritems method.\n$ /usr/bin/python2.5\nPython 2.5.4 (r254:67916, Feb 11 2010, 00:50:55) \n[GCC 4.2.1 (Apple Inc. build 5646)] on darwin\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import anydbm\n>>> db = anydbm.open('cache', 'c')\n>>> dir(db)\n['close', 'get', 'has_key', 'keys', 'setdefault']\n\nThe python.org OS X Pythons, on the other hand, are built with a real dbm interface:\n$ /usr/local/bin/python2.5\nPython 2.5.4 (r254:67917, Dec 23 2008, 14:57:27) \n[GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import anydbm\n>>> db = anydbm.open('cache2', 'c')\n>>> dir(db)\n['__cmp__', '__contains__', '__del__', '__delitem__', '__doc__', '__getitem__', '__init__', '__iter__', '__len__', '__module__', '__repr__', '__setitem__', '_checkCursor', '_checkOpen', '_closeCursors', '_cursor_refs', '_gen_cref_cleaner', '_make_iter_cursor', 'clear', 'close', 'db', 'dbc', 'first', 'get', 'has_key', 'isOpen', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'last', 'next', 'pop', 'popitem', 'previous', 'saved_dbc_key', 'set_location', 'setdefault', 'sync', 'update', 'values']\n>>> db.iteritems()\n<generator object at 0x481760>\n>>> db.__module__\n'bsddb'\n\nThere are some open issues on the Python bug tracker concerning some of the dbm modules inconsistencies.\n" ]
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0002650914_python.txt
Q: How can I start using twill? I am sorry I have already asked this question on "Superuser", but nobody answers there, so I deleted it from "Superuser" and decided to post it here. Hope it's not a big crime, especially given the fact that I was firstly advised to use twill here on "StackOverflow" (not on "SuperUser") How do I start using twill? I have just downloaded it, unpacked it and clicked on the setup .py file in the folder. The black window (terminal) appeared for a moment and vanished. (I do have Python 2.5 installed on my computer - along with SDK from Google App Engine) In the twill documentation section it says: Downloading twill The latest release of twill is twill 0.9, released Thursday, December 27th, 2007; it is available for download at http://darcs.idyll.org/~t/projects/twill-0.9.tar.gz. You can also use Python's easy_install to install or upgrade twill. twill works with Python 2.3 or later. To start using twill, install it and then type twill-sh. At the prompt type: go http://www.slashdot.org/ show showforms showhistory I am not clear from this passage what I am supposed to type (only "twill-sh" or "twill-sh" and all the words under that line) and where (I tried typing it in the command prompt window of my computer - to no avail) Can, anyone, please, help me out here? Thank You in advance. Update 1: (This update is a response to the answer given by S.Mark) Hello, S.Mark!!!! I’ve tried to follow Your instructions. Here is what happened: Firstly, I created a folder on my D disk and named it “tmp”. Then I downloaded and extracted twill-0.9 into that folder. So, now the path to this file on my computer was just as same as the one in Your example: D:\tmp\twill-0.9 : (source: narod.ru) (source: narod.ru) Then, I tried to open the command prompt on my computer: (source: narod.ru) (source: narod.ru) (source: narod.ru) (source: narod.ru) (source: narod.ru) Then, following step 2 of Your instructions, I tried to switch to D disk: (source: narod.ru) But for some reason it didn’t work: (source: narod.ru) This Chinese line says something like “This action has been rejected.” Why is it so? Well, I tried to proceed to step 3 anyway, and here is what I’ve got: (source: narod.ru) As far as I can understand, this Chinese line says something like “ ’C:\’ is neither internal nor external command, thus, it cannot be carried out. ” Why is it so? Is there something wrong with my computer? Update 2: (This update is my second response to the answer given by S.Mark) Hello, S.Mark!!! Thank You for Your answer again. Yes, this time it worked when I just typed those parts that You highlighted in Your post. So, when I typed just “d:” in the very beginning, it worked!!! But then, when I typed “python setup.py build”, I got the same error message (“ ’python’is neither an internal or external command; it can’t be carried out. “) : (source: narod.ru) I tried to repeat this command and accidentally omitted the word “python”: (source: narod.ru) When I pressed “Enter” key, the build process seemed to launch - at least what I saw then resembled the step 4 of Your instructions (“start the build process”) very much: (source: narod.ru) (source: narod.ru) (source: narod.ru) But now I am a little bit hesitant about proceeding to step 5 (“Install It”) as I am not sure if what I have done is the right thing. If what I did in step 4 was okay, should I also omit the word “python” in step 5? A side question: How did You manage to put the contents of the terminal into Your post without making screenshots? Is it like there is some way of putting the terminal’s contents into the clipboard? Making screenshots all the time and hosting them prior to posting is quite cumbersome. Update 3: (This update is my third response to S.Mark) S.Mark, hello again!!! (Hope you are not sick and tired of me yet) “…and yeah you could omit python and directly run setup.py because your python installation registered *.py in registry… regarding step 5, you could just run setup.py install” – I followed these words of Yours and install process ran successfully! Thank You. But as for the following steps (“then open python prompt from start menu, and test step 6 and 8”), there wasn’t much success in the Python prompt: (source: narod.ru) Neither was it successful in the usual command prompt (terminal): (source: narod.ru) (It again says in Chinese that python “is neither an internal nor external command and, therefore, can’t be carried out”). Do You have any idea why it didn’t work? “…where is your python installation? C:\Python25?” - Yes, that’s right. “…there is a setting (command prompt properties - easy edit mode) to enable selection of text on the command prompt, could you ask that in superuser.com?” - Sure, I will ask this question there. Thanks for telling me. A: You cannot just double click setup.py You need to open command prompt or shell and go to that folder and need to do python setup.py build python setup.py install install step should automatically do build normally, so only last one will work Edit: ok, here is superuser way of installation steps I have extracted twill-0.9.tar.gz to D:\tmp\twill-0.9 I am on drive C, so I switched to D: C:\>d: Now, change the folder by using cd command C:\>cd D:\tmp\twill-0.9 start the build process D:\tmp\twill-0.9>python setup.py build (WARNING: importing distutils, not setuptools!) D:\data\program\Python26\lib\distutils\dist.py:266: UserWarning: Unknown distribution option: 'entry_points' warnings.warn(msg) D:\data\program\Python26\lib\distutils\dist.py:266: UserWarning: Unknown distribution option: 'test_suite' warnings.warn(msg) running build running build_py creating build creating build\lib creating build\lib\twill ...... running build_scripts creating build\scripts-2.6 copying and adjusting twill-fork -> build\scripts-2.6 Install it D:\tmp\twill-0.9>python setup.py install (WARNING: importing distutils, not setuptools!) running install running build running build_py ...... running install_scripts copying build\scripts-2.6\twill-fork -> D:\data\program\Python26\Scripts running install_egg_info Writing D:\data\program\Python26\Lib\site-packages\twill-0.9-py2.6.egg-info Test for import is or not D:\tmp\twill-0.9>python Python 2.6.5 (r265:79096, Mar 19 2010, 21:48:26) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import twill import re, base64, urlparse, posixpath, md5, sha, sys, copy twill\other_packages\_mechanize_dist\_auth.py:14: DeprecationWarning: the sha module is deprecated; use the hashlib module instead import re, base64, urlparse, posixpath, md5, sha, sys, copy >>> Import was fine, but there is DeprecationWarnings on python 2.6, but this should be ok and should be no warnings at all with python 2.5 confirm its properly imported or not, you will see twill and its functions there, so yes. >>> dir() ['__builtins__', '__doc__', '__name__', '__package__', 'twill'] >>> from twill.commands import * >>> dir() ['__builtins__', '__doc__', '__name__', '__package__', 'add_auth', 'add_extra_header', 'agent', 'back', 'clear_cookies', 'clear_extra_headers', 'code', 'config', 'debug', 'echo', 'exit', 'extend_with', 'fa', 'find', 'follow >>>
How can I start using twill?
I am sorry I have already asked this question on "Superuser", but nobody answers there, so I deleted it from "Superuser" and decided to post it here. Hope it's not a big crime, especially given the fact that I was firstly advised to use twill here on "StackOverflow" (not on "SuperUser") How do I start using twill? I have just downloaded it, unpacked it and clicked on the setup .py file in the folder. The black window (terminal) appeared for a moment and vanished. (I do have Python 2.5 installed on my computer - along with SDK from Google App Engine) In the twill documentation section it says: Downloading twill The latest release of twill is twill 0.9, released Thursday, December 27th, 2007; it is available for download at http://darcs.idyll.org/~t/projects/twill-0.9.tar.gz. You can also use Python's easy_install to install or upgrade twill. twill works with Python 2.3 or later. To start using twill, install it and then type twill-sh. At the prompt type: go http://www.slashdot.org/ show showforms showhistory I am not clear from this passage what I am supposed to type (only "twill-sh" or "twill-sh" and all the words under that line) and where (I tried typing it in the command prompt window of my computer - to no avail) Can, anyone, please, help me out here? Thank You in advance. Update 1: (This update is a response to the answer given by S.Mark) Hello, S.Mark!!!! I’ve tried to follow Your instructions. Here is what happened: Firstly, I created a folder on my D disk and named it “tmp”. Then I downloaded and extracted twill-0.9 into that folder. So, now the path to this file on my computer was just as same as the one in Your example: D:\tmp\twill-0.9 : (source: narod.ru) (source: narod.ru) Then, I tried to open the command prompt on my computer: (source: narod.ru) (source: narod.ru) (source: narod.ru) (source: narod.ru) (source: narod.ru) Then, following step 2 of Your instructions, I tried to switch to D disk: (source: narod.ru) But for some reason it didn’t work: (source: narod.ru) This Chinese line says something like “This action has been rejected.” Why is it so? Well, I tried to proceed to step 3 anyway, and here is what I’ve got: (source: narod.ru) As far as I can understand, this Chinese line says something like “ ’C:\’ is neither internal nor external command, thus, it cannot be carried out. ” Why is it so? Is there something wrong with my computer? Update 2: (This update is my second response to the answer given by S.Mark) Hello, S.Mark!!! Thank You for Your answer again. Yes, this time it worked when I just typed those parts that You highlighted in Your post. So, when I typed just “d:” in the very beginning, it worked!!! But then, when I typed “python setup.py build”, I got the same error message (“ ’python’is neither an internal or external command; it can’t be carried out. “) : (source: narod.ru) I tried to repeat this command and accidentally omitted the word “python”: (source: narod.ru) When I pressed “Enter” key, the build process seemed to launch - at least what I saw then resembled the step 4 of Your instructions (“start the build process”) very much: (source: narod.ru) (source: narod.ru) (source: narod.ru) But now I am a little bit hesitant about proceeding to step 5 (“Install It”) as I am not sure if what I have done is the right thing. If what I did in step 4 was okay, should I also omit the word “python” in step 5? A side question: How did You manage to put the contents of the terminal into Your post without making screenshots? Is it like there is some way of putting the terminal’s contents into the clipboard? Making screenshots all the time and hosting them prior to posting is quite cumbersome. Update 3: (This update is my third response to S.Mark) S.Mark, hello again!!! (Hope you are not sick and tired of me yet) “…and yeah you could omit python and directly run setup.py because your python installation registered *.py in registry… regarding step 5, you could just run setup.py install” – I followed these words of Yours and install process ran successfully! Thank You. But as for the following steps (“then open python prompt from start menu, and test step 6 and 8”), there wasn’t much success in the Python prompt: (source: narod.ru) Neither was it successful in the usual command prompt (terminal): (source: narod.ru) (It again says in Chinese that python “is neither an internal nor external command and, therefore, can’t be carried out”). Do You have any idea why it didn’t work? “…where is your python installation? C:\Python25?” - Yes, that’s right. “…there is a setting (command prompt properties - easy edit mode) to enable selection of text on the command prompt, could you ask that in superuser.com?” - Sure, I will ask this question there. Thanks for telling me.
[ "You cannot just double click setup.py\nYou need to open command prompt or shell and go to that folder\nand need to do\npython setup.py build\npython setup.py install\n\ninstall step should automatically do build normally, so only last one will work\n\nEdit: ok, here is superuser way of installation steps\n\nI have extracted twill-0.9.tar.gz to D:\\tmp\\twill-0.9\nI am on drive C, so I switched to D:\nC:\\>d:\nNow, change the folder by using cd command\nC:\\>cd D:\\tmp\\twill-0.9\nstart the build process\nD:\\tmp\\twill-0.9>python setup.py build\n(WARNING: importing distutils, not setuptools!)\nD:\\data\\program\\Python26\\lib\\distutils\\dist.py:266: UserWarning: Unknown distribution option: 'entry_points'\n warnings.warn(msg)\nD:\\data\\program\\Python26\\lib\\distutils\\dist.py:266: UserWarning: Unknown distribution option: 'test_suite'\n warnings.warn(msg)\nrunning build\nrunning build_py\ncreating build\ncreating build\\lib\ncreating build\\lib\\twill\n......\nrunning build_scripts\ncreating build\\scripts-2.6\ncopying and adjusting twill-fork -> build\\scripts-2.6\nInstall it\nD:\\tmp\\twill-0.9>python setup.py install\n(WARNING: importing distutils, not setuptools!)\nrunning install\nrunning build\nrunning build_py\n......\nrunning install_scripts\ncopying build\\scripts-2.6\\twill-fork -> D:\\data\\program\\Python26\\Scripts\nrunning install_egg_info\nWriting D:\\data\\program\\Python26\\Lib\\site-packages\\twill-0.9-py2.6.egg-info\nTest for import is or not\nD:\\tmp\\twill-0.9>python\nPython 2.6.5 (r265:79096, Mar 19 2010, 21:48:26) [MSC v.1500 32 bit (Intel)] on win32\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information. \n>>> import twill\n import re, base64, urlparse, posixpath, md5, sha, sys, copy\ntwill\\other_packages\\_mechanize_dist\\_auth.py:14: DeprecationWarning: the sha module is deprecated; use the hashlib module instead\n import re, base64, urlparse, posixpath, md5, sha, sys, copy\n>>>\nImport was fine, but there is DeprecationWarnings on python 2.6, but this should be ok and should be no warnings at all with python 2.5\nconfirm its properly imported or not, you will see twill and its functions there, so yes.\n>>> dir()\n['__builtins__', '__doc__', '__name__', '__package__', 'twill']\n>>> from twill.commands import *\n>>> dir()\n['__builtins__', '__doc__', '__name__', '__package__', 'add_auth', 'add_extra_header', 'agent', 'back', 'clear_cookies', 'clear_extra_headers', 'code', 'config', 'debug', 'echo', 'exit', 'extend_with', 'fa', 'find', 'follow\n>>>\n\n" ]
[ 10 ]
[]
[]
[ "installation", "python", "twill" ]
stackoverflow_0002651334_installation_python_twill.txt
Q: how to call a c++ file from python without using any of the spam bindings? i have this encryption algorithm written in C++ , but the values that has to be encrypted are being taken input and stored in a file by a python program . Thus how can i call this c++ program from python? A: Look for the subprocess module. It is the recommended way to invoke processes from within Python. The os.system function is a viable alternative sometimes, if your needs are very simple (no pipes, simple arguments, etc.) A: The os.system function will invoke an arbitrary command-line from python.
how to call a c++ file from python without using any of the spam bindings?
i have this encryption algorithm written in C++ , but the values that has to be encrypted are being taken input and stored in a file by a python program . Thus how can i call this c++ program from python?
[ "Look for the subprocess module. It is the recommended way to invoke processes from within Python. The os.system function is a viable alternative sometimes, if your needs are very simple (no pipes, simple arguments, etc.)\n", "The os.system function will invoke an arbitrary command-line from python.\n" ]
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002651466_python.txt
Q: Django database caching I have a Django form that uses an integer field to lookup a model object by its primary key. The form has a save() method that uses the model object referred to by the integer field. The model's manager's get() method is called twice, once in the clean method and once in the save() method: class MyForm(forms.Form): id_a = fields.IntegerField() def clean_id_a(user_id): id_a = self.cleaned_data['id_a'] try: # here is the first call to get MyModel.objects.get(id=id_a) except User.DoesNotExist: raise ValidationError('Object does not exist') def save(self): id_a = self.cleaned_data['id_a'] # here is the second call to get my_model_object = MyModel.objects.get(id=id_a) # do other stuff I wasn't sure whether this hits the database two times or one time so I returned the object itself in the clean method so that I could avoid a second get() call. Does calling get() hit the database two times? Or is the object cached in the thread? class MyForm(forms.Form): id_a = fields.IntegerField() def clean_id_a(user_id): id_a = self.cleaned_data['id_a'] try: # here is my workaround return MyModel.objects.get(id=id_a) except User.DoesNotExist: raise ValidationError('Object does not exist') def save(self): # looking up the cleaned value returns the model object my_model_object = self.cleaned_data['id_a'] # do other stuff A: No, the value wouldn't be cached. Your second example is the right way to go. (The first snippet actually contains an error, in that nothing is returned from the clean method, so the id_a attribute would end up empty.) A: This query is not cached. get() calls never are. QuerySets on the other hand, are (sometimes) cached after the first evaluation.
Django database caching
I have a Django form that uses an integer field to lookup a model object by its primary key. The form has a save() method that uses the model object referred to by the integer field. The model's manager's get() method is called twice, once in the clean method and once in the save() method: class MyForm(forms.Form): id_a = fields.IntegerField() def clean_id_a(user_id): id_a = self.cleaned_data['id_a'] try: # here is the first call to get MyModel.objects.get(id=id_a) except User.DoesNotExist: raise ValidationError('Object does not exist') def save(self): id_a = self.cleaned_data['id_a'] # here is the second call to get my_model_object = MyModel.objects.get(id=id_a) # do other stuff I wasn't sure whether this hits the database two times or one time so I returned the object itself in the clean method so that I could avoid a second get() call. Does calling get() hit the database two times? Or is the object cached in the thread? class MyForm(forms.Form): id_a = fields.IntegerField() def clean_id_a(user_id): id_a = self.cleaned_data['id_a'] try: # here is my workaround return MyModel.objects.get(id=id_a) except User.DoesNotExist: raise ValidationError('Object does not exist') def save(self): # looking up the cleaned value returns the model object my_model_object = self.cleaned_data['id_a'] # do other stuff
[ "No, the value wouldn't be cached. Your second example is the right way to go. \n(The first snippet actually contains an error, in that nothing is returned from the clean method, so the id_a attribute would end up empty.)\n", "This query is not cached. get() calls never are. QuerySets on the other hand, are (sometimes) cached after the first evaluation.\n" ]
[ 2, 1 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0002651193_django_django_models_python.txt
Q: How to use Python list comprehension (or such) for retrieving rows when using MySQLdb? I use MySQLdb a lot when dealing with my webserver. I often find myself repeating the lines: row = cursor.fetchone() while row: do_processing(row) row = cursor.fetchone() Somehow this strikes me as somewhat un-pythonic. Is there a better, one-line way to accomplish the same thing, along the lines of inline assignment in C: while (row = do_fetch()) { do_processing(row); } I've tried figuring out the syntax using list comprehensions, but I can't seem to figure it out. Any recommendations? Thanks, Erik A: There isn't really a way to get list comprehensions involved in this. You need a loop that terminates when a sentinel value is returned. Fortunately, Python does provide this: for row in iter(cursor.fetchone, None): process(row) The two-argument iter() takes a callable, and a sentinel value that will terminate the iteration. It is a little isoteric, so few people will complain if you instead use the still somewhat more common: while True: row = cursor.fetchone() if row is None: break process(row) (And indeed that style was common even for reading a file line-by-line, before we had generalized iteration.) Some DB-API modules (including apparently now MySQLdb) also make cursors directly iterable, like so: for row in cursor: process(row) That's obviously the prettiest solution, when available :) A: MySQLdb cursors are iterable: cursor.execute(sql,args) for row in cursor: do_processing(row) A: What about: for row in cursor.fetchall(): # do something with row A: SQLalchemy has a bundle of methods that provide more pythonic construction for a goodly number of your use cases - including the production of iterables that are "lazy" in their database accesses.
How to use Python list comprehension (or such) for retrieving rows when using MySQLdb?
I use MySQLdb a lot when dealing with my webserver. I often find myself repeating the lines: row = cursor.fetchone() while row: do_processing(row) row = cursor.fetchone() Somehow this strikes me as somewhat un-pythonic. Is there a better, one-line way to accomplish the same thing, along the lines of inline assignment in C: while (row = do_fetch()) { do_processing(row); } I've tried figuring out the syntax using list comprehensions, but I can't seem to figure it out. Any recommendations? Thanks, Erik
[ "There isn't really a way to get list comprehensions involved in this. You need a loop that terminates when a sentinel value is returned. Fortunately, Python does provide this:\nfor row in iter(cursor.fetchone, None):\n process(row)\n\nThe two-argument iter() takes a callable, and a sentinel value that will terminate the iteration. It is a little isoteric, so few people will complain if you instead use the still somewhat more common:\nwhile True:\n row = cursor.fetchone()\n if row is None:\n break\n process(row)\n\n(And indeed that style was common even for reading a file line-by-line, before we had generalized iteration.)\nSome DB-API modules (including apparently now MySQLdb) also make cursors directly iterable, like so:\nfor row in cursor:\n process(row)\n\nThat's obviously the prettiest solution, when available :)\n", "MySQLdb cursors are iterable:\ncursor.execute(sql,args)\nfor row in cursor:\n do_processing(row)\n\n", "What about:\nfor row in cursor.fetchall():\n # do something with row\n\n", "SQLalchemy has a bundle of methods that provide more pythonic construction for a goodly number of your use cases - including the production of iterables that are \"lazy\" in their database accesses.\n" ]
[ 3, 2, 0, 0 ]
[]
[]
[ "coding_style", "mysql", "python" ]
stackoverflow_0002649484_coding_style_mysql_python.txt
Q: What are the most frustrating Python hacks to unwind, rewrite, etc.? My impression of Python from the short time I've been developing with it is that it's incredible powerful and flexible, but I can't help but feel like "with great power comes great responsibility." So while I've read numerous blog posts about simple and elegant Python snippets that solve a problems, I wonder if there are design patterns or abuses of Python language features that, once built into an application or library, cause the code to be incredibly brittle and near impossible to refactor. So the question is basically what are the most frustrating, but somewhat common, Python "hacks" or language feature abuses that someone can introduce that will cause nightmares for future maintainers of that code? A: Magic that works but not always. For example, when metaclasses are abused to create a DSL. Such DSL could be suitable for most tasks but breaks horribly on a complex (unexpected by author) one. A: Using eval or exec on user input may be the most common abuse of Python features. A: Excessive usage of from module import *. Having a lot of such imports at the module you don't know where each variable came from and have to look though all imported modules. Searching doesn't help much in this case. A: It's not a hack, but there's been a somewhat large issue with Python 2.X's print keyword. People would rely on print to be called for output throughout an entire project, and then when it finally came time to, say, change output to a file and to stdout, they'd have to go in and refactor all those print keywords to another custom output function. Python 3 solved this by making print an actual function rather than a keyword (therefore automatically making output loosely coupled to the rest of the system), so if need be you can replace the original print with a new print that does more than just write to stdout. See PEP3105 for the specific reasoning from Guido and more details. A: ..what are the most frustrating, but somewhat common, Python "hacks" or language feature abuses that someone can introduce that will cause nightmares for future maintainers of that code? Hard to refactor: nested list comprehensions (as in: multiple levels deep). Most people (when learning Python) are fascinated by the power and utility of list comprehensions. This can cause a tendency to over-use them and build deeply nested, complicated ones. Most of the time the same code should have been written with simple loops for readability and maintainability. I consider three levels already too deeply nested. -- And also (not so hard to refactor but mostly irritating): trying to use Python as if it was another language (without it's own specific constructs); e.g.: for i in range(len(mylist)): item = mylist[i] # do stuff with item instead of for i, item in enumerate(mylist): # do stuff with item or even (why do you need the index anyway): for item in mylist: # do stuff with item This includes: reinventing the wheel (badly) when functionality is already (aptly named) in the rich standard library. And type-checking, making stuff impossible to subclass, etc... A: The single biggest issue I've come across is use of double-leading-underscore attributes. The perpetrators are practically always new Python programmers or programmers who prefer another language (in particular Java, for some reason.) Double leading underscores causes the attributes to be name-mangled (using the current class name), avoiding collisions in subclasses. It's too frequently seen as 'private', even though it isn't. (See this answer I once wrote.) The same classes are usually littered with accessors -- not properties, but regular methods called directly -- to get at these name-mangled attributes. The end result is always a horribly convoluted class that's impossible to subclass to specialize or bugfix or monkeypatch or test.
What are the most frustrating Python hacks to unwind, rewrite, etc.?
My impression of Python from the short time I've been developing with it is that it's incredible powerful and flexible, but I can't help but feel like "with great power comes great responsibility." So while I've read numerous blog posts about simple and elegant Python snippets that solve a problems, I wonder if there are design patterns or abuses of Python language features that, once built into an application or library, cause the code to be incredibly brittle and near impossible to refactor. So the question is basically what are the most frustrating, but somewhat common, Python "hacks" or language feature abuses that someone can introduce that will cause nightmares for future maintainers of that code?
[ "Magic that works but not always. For example, when metaclasses are abused to create a DSL. Such DSL could be suitable for most tasks but breaks horribly on a complex (unexpected by author) one.\n", "Using eval or exec on user input may be the most common abuse of Python features. \n", "Excessive usage of from module import *.\nHaving a lot of such imports at the module you don't know where each variable came from and have to look though all imported modules. Searching doesn't help much in this case.\n", "It's not a hack, but there's been a somewhat large issue with Python 2.X's print keyword.\nPeople would rely on print to be called for output throughout an entire project, and then when it finally came time to, say, change output to a file and to stdout, they'd have to go in and refactor all those print keywords to another custom output function.\nPython 3 solved this by making print an actual function rather than a keyword (therefore automatically making output loosely coupled to the rest of the system), so if need be you can replace the original print with a new print that does more than just write to stdout.\nSee PEP3105 for the specific reasoning from Guido and more details.\n", "..what are the most frustrating, but somewhat common, Python \"hacks\" or language feature abuses that someone can introduce that will cause nightmares for future maintainers of that code?\nHard to refactor:\nnested list comprehensions (as in: multiple levels deep).\nMost people (when learning Python) are fascinated by the power and utility of list comprehensions. This can cause a tendency to over-use them and build deeply nested, complicated ones. Most of the time the same code should have been written with simple loops for readability and maintainability. I consider three levels already too deeply nested.\n--\nAnd also (not so hard to refactor but mostly irritating): \ntrying to use Python as if it was another language (without it's own specific constructs); e.g.:\nfor i in range(len(mylist)):\n item = mylist[i]\n # do stuff with item\n\ninstead of\nfor i, item in enumerate(mylist):\n # do stuff with item\n\nor even (why do you need the index anyway):\nfor item in mylist:\n # do stuff with item\n\nThis includes: reinventing the wheel (badly) when functionality is already (aptly named) in the rich standard library.\nAnd type-checking, making stuff impossible to subclass, etc...\n", "The single biggest issue I've come across is use of double-leading-underscore attributes. The perpetrators are practically always new Python programmers or programmers who prefer another language (in particular Java, for some reason.) Double leading underscores causes the attributes to be name-mangled (using the current class name), avoiding collisions in subclasses. It's too frequently seen as 'private', even though it isn't. (See this answer I once wrote.) The same classes are usually littered with accessors -- not properties, but regular methods called directly -- to get at these name-mangled attributes. The end result is always a horribly convoluted class that's impossible to subclass to specialize or bugfix or monkeypatch or test.\n" ]
[ 4, 4, 4, 3, 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0002647288_python.txt
Q: Self Authenticating Links in Django In my web app I would like to be able to email self-authenticating links to users. These links will contain a unique token (uuid). When they click the link the token being present in the query string will be enough to authenticate them and they won't have to enter their username and password. What's the best way to do this? A: That's quite common task if you properly expire your links :) You'll need to implement your own authentication backend. Instead of checking username and password parameters you'll check for auth_link. class AuthLinkBackend(object): def authenticate(auth_link = None): if auth_link: # validate and expire this link, return authenticated user if successful return user Add your backend class to the list of backends (AUTHENTICATION_BACKENDS setting). In the link validation view you should try to authenticate user and if it succeeded, log in him/her: user = auth.authenticate(auth_link=link) if user: auth.login(request, user) A: From a security standpoint, this seems like a really bad idea. That said, it can still be done. I'm hoping you're planning on using this only on something that would be internal or a company intranet of some sort. For a live, on-the-web, legit website, this is probably just asking for trouble. You can handle incoming requests by creating a middleware component to do so. (untested, but the general idea) import base64 class UUIDQueryStringMiddleware(object): def process_request(request): if request.method == 'GET': if not request.user.is_authenticated(): uuid = request.REQUEST.get('u', None) if uuid: username = base64.b64decode(uuid) try: user = User.objects.get(username=username) request.user = user except: pass # Pass the original request back to Django return request You would then need to setup this middleware to run before the auth and sessions middleware runs... MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'yourapp.middleware.UUIDQueryStringMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', ) See this question for more details on encoding/decoding: encrypt & decrypt strings in python I REALLY hope you're not going to use this on a live site. A: To T. Stone's point, end users are notorious for passing links around -- ESPECIALLY those in an intraweb environment. Having something that authenticated the user automatically means that I can almost guarantee that you're going to have at least one person logged in as somebody else. There are better ways, of course, to refresh a user's session from Cookie information, so you at least have a decent idea that they're a valid user attached to a valid browser and can feel SOMEwhat safer in that they aren't likely to hand their laptops about like they might with a link, but yes... to reiterate, what you're trying to do is a VERY bad idea if your app has more than 1 user.
Self Authenticating Links in Django
In my web app I would like to be able to email self-authenticating links to users. These links will contain a unique token (uuid). When they click the link the token being present in the query string will be enough to authenticate them and they won't have to enter their username and password. What's the best way to do this?
[ "That's quite common task if you properly expire your links :) You'll need to implement your own authentication backend. Instead of checking username and password parameters you'll check for auth_link.\nclass AuthLinkBackend(object):\n def authenticate(auth_link = None):\n if auth_link:\n # validate and expire this link, return authenticated user if successful\n return user\n\nAdd your backend class to the list of backends (AUTHENTICATION_BACKENDS setting).\nIn the link validation view you should try to authenticate user and if it succeeded, log in him/her:\nuser = auth.authenticate(auth_link=link)\nif user:\n auth.login(request, user)\n\n", "From a security standpoint, this seems like a really bad idea.\nThat said, it can still be done. I'm hoping you're planning on using this only on something that would be internal or a company intranet of some sort. For a live, on-the-web, legit website, this is probably just asking for trouble.\nYou can handle incoming requests by creating a middleware component to do so. \n(untested, but the general idea)\nimport base64\n\nclass UUIDQueryStringMiddleware(object):\n\n def process_request(request):\n\n if request.method == 'GET':\n if not request.user.is_authenticated():\n uuid = request.REQUEST.get('u', None)\n if uuid:\n username = base64.b64decode(uuid)\n try:\n user = User.objects.get(username=username)\n request.user = user\n except:\n pass\n\n # Pass the original request back to Django\n return request\n\nYou would then need to setup this middleware to run before the auth and sessions middleware runs...\nMIDDLEWARE_CLASSES = (\n 'django.middleware.common.CommonMiddleware',\n 'yourapp.middleware.UUIDQueryStringMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n)\n\nSee this question for more details on encoding/decoding: encrypt & decrypt strings in python\nI REALLY hope you're not going to use this on a live site.\n", "To T. Stone's point, end users are notorious for passing links around -- ESPECIALLY those in an intraweb environment. Having something that authenticated the user automatically means that I can almost guarantee that you're going to have at least one person logged in as somebody else. \nThere are better ways, of course, to refresh a user's session from Cookie information, so you at least have a decent idea that they're a valid user attached to a valid browser and can feel SOMEwhat safer in that they aren't likely to hand their laptops about like they might with a link, but yes... to reiterate, what you're trying to do is a VERY bad idea if your app has more than 1 user.\n" ]
[ 3, 0, 0 ]
[]
[]
[ "authentication", "django", "python" ]
stackoverflow_0002650189_authentication_django_python.txt
Q: fft and array-to-image / image-to-array-conversion I want to make a fourier-transformation of an image. But how can I change the picture to an array? And after this I think I should use numpy.fft.rfft2 for the transformation. And how to change back from the array to the image? Thanks in advance. A: You can use the PIL library to load/save images and convert to/from numpy arrays. import Image, numpy i = Image.open('img.png') i = i.convert('L') #convert to grayscale a = numpy.asarray(i) # a is readonly b = abs(numpy.fft.rfft2(a)) j = Image.fromarray(b) j.save('img2.png') I used abs above because the result of the FFT has complex values so it doesn't really make sense to convert it directly to an image. The conversion to grayscale is done so that the FFT is done on a single channel only - you can choose another way to pick a channel instead, or pass the correct axes parameter to rfft2 and later extract the channel you need. Edit: To also perform an inverse FFT and get back the original image, the following works for me: import Image, numpy i = Image.open('img.png') i = i.convert('L') #convert to grayscale a = numpy.asarray(i) b = numpy.fft.rfft2(a) c = numpy.fft.irfft2(b) j = Image.fromarray(c.astype(numpy.uint8)) j.save('img2.png')
fft and array-to-image / image-to-array-conversion
I want to make a fourier-transformation of an image. But how can I change the picture to an array? And after this I think I should use numpy.fft.rfft2 for the transformation. And how to change back from the array to the image? Thanks in advance.
[ "You can use the PIL library to load/save images and convert to/from numpy arrays.\nimport Image, numpy\ni = Image.open('img.png')\ni = i.convert('L') #convert to grayscale\na = numpy.asarray(i) # a is readonly\n\nb = abs(numpy.fft.rfft2(a))\n\nj = Image.fromarray(b)\nj.save('img2.png')\n\nI used abs above because the result of the FFT has complex values so it doesn't really make sense to convert it directly to an image. The conversion to grayscale is done so that the FFT is done on a single channel only - you can choose another way to pick a channel instead, or pass the correct axes parameter to rfft2 and later extract the channel you need.\nEdit:\nTo also perform an inverse FFT and get back the original image, the following works for me:\nimport Image, numpy\ni = Image.open('img.png')\ni = i.convert('L') #convert to grayscale\na = numpy.asarray(i)\n\nb = numpy.fft.rfft2(a)\nc = numpy.fft.irfft2(b)\n\nj = Image.fromarray(c.astype(numpy.uint8))\nj.save('img2.png')\n\n" ]
[ 12 ]
[]
[]
[ "fft", "image_processing", "python" ]
stackoverflow_0002652415_fft_image_processing_python.txt
Q: matplotlib equivalent for MATLABs truesize() I am new to matplotlib and python and would like to display an image so that 1 pixel of the image is actually represented by 1 pixel in the figure. In MATLAB, this is achieved with the command truesize(). How can I do this in Python? I tried playing around with the imshow() arguments as well as set_dpi() and set_figwidth()/set_figheight(), but with no luck. Thanks. A: If you want to create images right down to the pixel level, why not use PIL in the first place? That way you wouldn't have to programatically calculate your true drawing area by substracting margins, labels and axis widths from the figure extend. A: This hack does what I wanted to do, though it's still not perfect: h = mplt.imshow(img, interpolation='nearest') dpi = h.figure.get_dpi() h.figure.set_figwidth(img.shape[0] / dpi) h.figure.set_figheight(img.shape[1] / dpi) h.figure.canvas.resize(img.shape[1] + 1, img.shape[0] + 1) h.axes.set_position([0, 0, 1, 1]) h.axes.set_xlim(-1, img.shape[1]) h.axes.set_ylim(img.shape[0], -1) It can be generalized to account for a margin around the axes holding the image.
matplotlib equivalent for MATLABs truesize()
I am new to matplotlib and python and would like to display an image so that 1 pixel of the image is actually represented by 1 pixel in the figure. In MATLAB, this is achieved with the command truesize(). How can I do this in Python? I tried playing around with the imshow() arguments as well as set_dpi() and set_figwidth()/set_figheight(), but with no luck. Thanks.
[ "If you want to create images right down to the pixel level, why not use PIL in the first place? That way you wouldn't have to programatically calculate your true drawing area by substracting margins, labels and axis widths from the figure extend.\n", "This hack does what I wanted to do, though it's still not perfect:\nh = mplt.imshow(img, interpolation='nearest')\n\ndpi = h.figure.get_dpi()\nh.figure.set_figwidth(img.shape[0] / dpi)\nh.figure.set_figheight(img.shape[1] / dpi)\nh.figure.canvas.resize(img.shape[1] + 1, img.shape[0] + 1)\n\nh.axes.set_position([0, 0, 1, 1])\nh.axes.set_xlim(-1, img.shape[1])\nh.axes.set_ylim(img.shape[0], -1)\n\nIt can be generalized to account for a margin around the axes holding the image.\n" ]
[ 1, 0 ]
[]
[]
[ "matlab", "matplotlib", "python" ]
stackoverflow_0002645049_matlab_matplotlib_python.txt
Q: Can't iterate over a list class in Python I'm trying to write a simple GUI front end for Plurk using pyplurk. I have successfully got it to create the API connection, log in, and retrieve and display a list of friends. Now I'm trying to retrieve and display a list of Plurks. pyplurk provides a GetNewPlurks function as follows: def GetNewPlurks(self, since): '''Get new plurks since the specified time. Args: since: [datetime.datetime] the timestamp criterion. Returns: A PlurkPostList object or None. ''' offset = jsonizer.conv_datetime(since) status_code, result = self._CallAPI('/Polling/getPlurks', offset=offset) return None if status_code != 200 else \ PlurkPostList(result['plurks'], result['plurk_users'].values()) As you can see this returns a PlurkPostList, which in turn is defined as follows: class PlurkPostList: '''A list of plurks and the set of users that posted them.''' def __init__(self, plurk_json_list, user_json_list=[]): self._plurks = [PlurkPost(p) for p in plurk_json_list] self._users = [PlurkUser(u) for u in user_json_list] def __iter__(self): return self._plurks def GetUsers(self): return self._users def __eq__(self, other): if other.__class__ != PlurkPostList: return False if self._plurks != other._plurks: return False if self._users != other._users: return False return True Now I expected to be able to do something like this: api = plurk_api_urllib2.PlurkAPI(open('api.key').read().strip(), debug_level=1) plurkproxy = PlurkProxy(api, json.loads) user = plurkproxy.Login('my_user', 'my_pass') ps = plurkproxy.GetNewPlurks(datetime.datetime(2009, 12, 12, 0, 0, 0)) print ps for p in ps: print str(p) When I run this, what I actually get is: <plurk.PlurkPostList instance at 0x01E8D738> from the "print ps", then: for p in ps: TypeError: __iter__ returned non-iterator of type 'list' I don't understand - surely a list is iterable? Where am I going wrong - how do I access the Plurks in the PlurkPostList? A: When you define your own __iter__ method, you should realize that that __iter__ method should return an iterator, not an iterable. You are returning a list, not an iterator to a list, so it fails. You can fix it by doing return iter(self._plurks), for example. If you wanted to do something a little more complex, like process each item in self._plurks as it's being iterated over, the usual trick is to make your __iter__ method be a generator. That way, the returnvalue of the call to __iter__ is the generator, which is an iterator: def __iter__(self): for item in self._plurks: yield process(item) A: The __iter__ method should return an object which implements the next() method. A list does not have a next() method, but it has an __iter__ method, which returns a listiterator object. The listiterator object has a next() method. You should write: def __iter__(self): return iter(self._plurks) A: As an alternative, you can also define the next() function and have __iter__() return self. See Build a Basic Python Iterator for a nice example.
Can't iterate over a list class in Python
I'm trying to write a simple GUI front end for Plurk using pyplurk. I have successfully got it to create the API connection, log in, and retrieve and display a list of friends. Now I'm trying to retrieve and display a list of Plurks. pyplurk provides a GetNewPlurks function as follows: def GetNewPlurks(self, since): '''Get new plurks since the specified time. Args: since: [datetime.datetime] the timestamp criterion. Returns: A PlurkPostList object or None. ''' offset = jsonizer.conv_datetime(since) status_code, result = self._CallAPI('/Polling/getPlurks', offset=offset) return None if status_code != 200 else \ PlurkPostList(result['plurks'], result['plurk_users'].values()) As you can see this returns a PlurkPostList, which in turn is defined as follows: class PlurkPostList: '''A list of plurks and the set of users that posted them.''' def __init__(self, plurk_json_list, user_json_list=[]): self._plurks = [PlurkPost(p) for p in plurk_json_list] self._users = [PlurkUser(u) for u in user_json_list] def __iter__(self): return self._plurks def GetUsers(self): return self._users def __eq__(self, other): if other.__class__ != PlurkPostList: return False if self._plurks != other._plurks: return False if self._users != other._users: return False return True Now I expected to be able to do something like this: api = plurk_api_urllib2.PlurkAPI(open('api.key').read().strip(), debug_level=1) plurkproxy = PlurkProxy(api, json.loads) user = plurkproxy.Login('my_user', 'my_pass') ps = plurkproxy.GetNewPlurks(datetime.datetime(2009, 12, 12, 0, 0, 0)) print ps for p in ps: print str(p) When I run this, what I actually get is: <plurk.PlurkPostList instance at 0x01E8D738> from the "print ps", then: for p in ps: TypeError: __iter__ returned non-iterator of type 'list' I don't understand - surely a list is iterable? Where am I going wrong - how do I access the Plurks in the PlurkPostList?
[ "When you define your own __iter__ method, you should realize that that __iter__ method should return an iterator, not an iterable. You are returning a list, not an iterator to a list, so it fails. You can fix it by doing return iter(self._plurks), for example.\nIf you wanted to do something a little more complex, like process each item in self._plurks as it's being iterated over, the usual trick is to make your __iter__ method be a generator. That way, the returnvalue of the call to __iter__ is the generator, which is an iterator:\ndef __iter__(self):\n for item in self._plurks:\n yield process(item)\n\n", "The __iter__ method should return an object which implements the next() method.\nA list does not have a next() method, but it has an __iter__ method, which returns a listiterator object. The listiterator object has a next() method.\nYou should write:\ndef __iter__(self):\n return iter(self._plurks)\n\n", "As an alternative, you can also define the next() function and have __iter__() return self. See Build a Basic Python Iterator for a nice example.\n" ]
[ 14, 5, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002652761_python.txt
Q: Create matplotlib legend out of the figure I added the legend this way: leg = fig.legend((l0,l1,l2,l3,l4,l5,l6), ('0 Cl : r2, slope, origin', '1 Cl :'+str(r1b)+' , '+str(m1)+' , '+str(b1), '2 Cl :'+str(r2b)+' , '+str(m2)+' , '+str(b2), '3 Cl :'+str(r3b)+' , '+str(m3)+' , '+str(b3), '4 Cl :'+str(r4b)+' , '+str(m4)+' , '+str(b4), '5 Cl :'+str(r5b)+' , '+str(m5)+' , '+str(b5), '6 Cl :'+str(r6b)+' , '+str(m6)+' , '+str(b6), ), 'upper right') but the legend appears inside the plot. How can I tell matplotlib to put it to the right of the plot and at the right? A: did you try: fig.legend((plot1,plot2), (lab1,lab2), 'right') 'right' shows the legend at the right of the axes as for the second question (help for a command) you could look at the matplotlib demos (for example http://matplotlib.sourceforge.net/examples/api/legend_demo.html and API (for example, http://matplotlib.sourceforge.net/api/figure_api.html#module-matplotlib.figure)
Create matplotlib legend out of the figure
I added the legend this way: leg = fig.legend((l0,l1,l2,l3,l4,l5,l6), ('0 Cl : r2, slope, origin', '1 Cl :'+str(r1b)+' , '+str(m1)+' , '+str(b1), '2 Cl :'+str(r2b)+' , '+str(m2)+' , '+str(b2), '3 Cl :'+str(r3b)+' , '+str(m3)+' , '+str(b3), '4 Cl :'+str(r4b)+' , '+str(m4)+' , '+str(b4), '5 Cl :'+str(r5b)+' , '+str(m5)+' , '+str(b5), '6 Cl :'+str(r6b)+' , '+str(m6)+' , '+str(b6), ), 'upper right') but the legend appears inside the plot. How can I tell matplotlib to put it to the right of the plot and at the right?
[ "did you try:\nfig.legend((plot1,plot2), (lab1,lab2), 'right')\n\n'right' shows the legend at the right of the axes\nas for the second question (help for a command) you could look at the matplotlib demos (for example http://matplotlib.sourceforge.net/examples/api/legend_demo.html and API (for example, http://matplotlib.sourceforge.net/api/figure_api.html#module-matplotlib.figure)\n" ]
[ 3 ]
[]
[]
[ "matplotlib", "numpy", "python" ]
stackoverflow_0002652624_matplotlib_numpy_python.txt
Q: How to convert SVG images for use with Pisa / XHTML2PDF? I'm using Pisa/XHTML2PDF to generate PDFs on the fly in Django. Unfortunately, I need to include SVG images as well, which I don't believe is an easy task. What's the best way to go about either a) converting the SVGs to PNG / JPG (in Python) or b) including SVGs in the PDF export from Pisa? A: There's the Java based Apache Batik SVG toolkit. In a similar question regarding C# it was proposed using the command line version of Inkscape for this. For Python, here's a useful suggestion from this discussion thread: import rsvg from gtk import gdk h = rsvg.Handle('svg-file.svg') pixbuf = h.get_pixbuf() pixbuf.save('foobar.png', 'png') the step from gtk import gdk, suggested by Lukasz, is necessary and has to precede creation of the pixbuf, otherwise you will not get the save method, as observed by the original poster. A: "I got rsvg working, but here's what I get when I try to save: AttributeError: 'gtk.gdk.Pixbuf' object has no attribute 'save' – Nick Sergeant Apr 25 '09 at 0:10" You need to import gdk to have access to pixbuf methods: import rsvg from gtk import gdk h = rsvg.Handle('svg-file.svg') pixbuf = h.get_pixbuf() pixbuf.save('foobar.png', 'png') And to convert from string that contains svg data: import rsvg from gtk import gdk h = rsvg.Handle() h.write(svg_string) h.close() pixbuf = h.get_pixbuf() pixbuf.save('foobar.png', 'png')
How to convert SVG images for use with Pisa / XHTML2PDF?
I'm using Pisa/XHTML2PDF to generate PDFs on the fly in Django. Unfortunately, I need to include SVG images as well, which I don't believe is an easy task. What's the best way to go about either a) converting the SVGs to PNG / JPG (in Python) or b) including SVGs in the PDF export from Pisa?
[ "There's the Java based Apache Batik SVG toolkit.\nIn a similar question regarding C# it was proposed using the command line version of Inkscape for this.\nFor Python, here's a useful suggestion from this discussion thread:\nimport rsvg\nfrom gtk import gdk\nh = rsvg.Handle('svg-file.svg')\npixbuf = h.get_pixbuf()\npixbuf.save('foobar.png', 'png')\n\nthe step from gtk import gdk, suggested by Lukasz, is necessary and has to precede creation of the pixbuf, otherwise you will not get the save method, as observed by the original poster.\n", "\"I got rsvg working, but here's what I get when I try to save: AttributeError: 'gtk.gdk.Pixbuf' object has no attribute 'save' – Nick Sergeant Apr 25 '09 at 0:10\"\nYou need to import gdk to have access to pixbuf methods:\nimport rsvg\nfrom gtk import gdk\nh = rsvg.Handle('svg-file.svg')\npixbuf = h.get_pixbuf()\npixbuf.save('foobar.png', 'png')\n\nAnd to convert from string that contains svg data:\nimport rsvg\nfrom gtk import gdk\nh = rsvg.Handle()\nh.write(svg_string)\nh.close()\npixbuf = h.get_pixbuf()\npixbuf.save('foobar.png', 'png')\n\n" ]
[ 2, 1 ]
[]
[]
[ "pdf", "pdf_generation", "pisa", "python", "svg" ]
stackoverflow_0000787287_pdf_pdf_generation_pisa_python_svg.txt
Q: Python Tkinter comparing PhotoImage objects In a simple LightsOut game, when I click on a light I need to toggle the image on a button. I'm doing this with Tkinter, so I thought I'd just check and see what image is currently on the button (either 'on.gif' or 'off.gif') and set it to the other one, like this: def click(self,x,y): if self.buttons[x][y].image == self.on: self.buttons[x][y].config(image=self.off) self.buttons[x][y].image == self.off else: self.buttons[x][y].config(image=self.on) self.buttons[x][y].image == self.on This ends up always being True - I can turn a light off, but never turn it back on. Did some research, realized that I should probably be using cmp: def click(self,x,y): if cmp(self.buttons[x][y].image,self.on) == 0: self.buttons[x][y].config(image=self.off) self.buttons[x][y].image == self.off else: self.buttons[x][y].config(image=self.on) self.buttons[x][y].image == self.on But that gave me the exact same result. Both self.on and self.off are PhotoImage objects. Aside from keeping a separate set of lists which tracks what type of light is in each position and redrawing them every click, is there a way to directly compare two PhotoImage objects like this? A: Pointers self.buttons[x][y].image == self.off, are you sure you want "==" instead of "=" Comparing images to get what state you are in is not a good way, instead use a variable e.g self._isLightOn and toggle it when you change states, based on this variable set correct images, or text or whatever.
Python Tkinter comparing PhotoImage objects
In a simple LightsOut game, when I click on a light I need to toggle the image on a button. I'm doing this with Tkinter, so I thought I'd just check and see what image is currently on the button (either 'on.gif' or 'off.gif') and set it to the other one, like this: def click(self,x,y): if self.buttons[x][y].image == self.on: self.buttons[x][y].config(image=self.off) self.buttons[x][y].image == self.off else: self.buttons[x][y].config(image=self.on) self.buttons[x][y].image == self.on This ends up always being True - I can turn a light off, but never turn it back on. Did some research, realized that I should probably be using cmp: def click(self,x,y): if cmp(self.buttons[x][y].image,self.on) == 0: self.buttons[x][y].config(image=self.off) self.buttons[x][y].image == self.off else: self.buttons[x][y].config(image=self.on) self.buttons[x][y].image == self.on But that gave me the exact same result. Both self.on and self.off are PhotoImage objects. Aside from keeping a separate set of lists which tracks what type of light is in each position and redrawing them every click, is there a way to directly compare two PhotoImage objects like this?
[ "Pointers\n\nself.buttons[x][y].image == self.off, are you sure you want \"==\" instead of \"=\"\nComparing images to get what state you are in is not a good way, instead use a variable e.g self._isLightOn and toggle it when you change states, based on this variable set correct images, or text or whatever.\n\n" ]
[ 3 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0002653119_python_tkinter.txt
Q: Is there an equivalent in Scala to Python's more general map function? I know that Scala's Lists have a map implementation with signature (f: (A) => B):List[B] and a foreach implementation with signature (f: (A) => Unit):Unit but I'm looking for something that accepts multiple iterables the same way that the Python map accepts multiple iterables. I'm looking for something with a signature of (f: (A,B) => C, Iterable[A], Iterable[B] ):Iterable[C] or equivalent. Is there a library where this exists or a comparable way of doing similar? Edit: As suggested below I could do val output = myList zip( otherList ) map( x => x(0) + x(1) ) but that creates a temporary list in between steps. If the commentor would post I could upvote him (hint, hint) but is there another way? A: In scala 2.8, there is a method called zipped in Tuple2 & Tuple3 which avoid to create temporary collection. Here is some sample use case: Welcome to Scala version 2.8.0.r21561-b20100414020114 (Java HotSpot(TM) Client VM, Java 1.6.0_18). Type in expressions to have them evaluated. Type :help for more information. scala> val xs = 0 to 9 xs: scala.collection.immutable.Range.Inclusive with scala.collection.immutable.Range.ByOne = Range(0, 1, 2, 3, 4, 5, 6, 7, 8, 9) scala> val ys = List.range(0,10) ys: List[Int] = List(0, 1, 2, 3, 4, 5, 6, 7, 8, 9) scala> val zs = Array.range(0,10) zs: Array[Int] = Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9) scala> (xs,ys).zipped.map{ _+_ } res1: scala.collection.immutable.IndexedSeq[Int] = Vector(0, 2, 4, 6, 8, 10, 12, 14, 16, 18) scala> (zs,ys,xs).zipped.map{ _+_+_ } res2: Array[Int] = Array(0, 3, 6, 9, 12, 15, 18, 21, 24, 27) scala> There is a zip method in both Tuple2 and Tuple3. xs.zip(ys) is the same as (xs,ys).zip Note: There is also some shortage in (xs,ys).zip and (xs,ys).zipped, make sure that xs can't be a INFINITE Stream. Go to Ticket #2634 for more information. I have a post in nabble.com some days ago which shows my opinions about how to fix this ticket. A: The function you're looking for is usually called zipWith. It's unfortunately not provided in the standard libraries, but it's pretty easy to write: def zipWith[A,B,C](f: (A,B) => C, a: Iterable[A], b: Iterable[B]) = new Iterable[C] { def elements = (a.elements zip b.elements) map f.tupled } This will traverse only once, since the implementations for zip and map on iterators are fully lazy. But why stop at Iterable? This has an even more general form. We could declare an interface for all data structures that can be zipped this way. trait Zip[F[_]] { def zipWith[A,B,C](f: (A,B) => C, a: F[A], b: F[B]): F[C] } For example, we can zip functions: trait Reader[A] { type Read[B] = (A => B) } def readerZip[T] = new Zip[Reader[T]#Read] { def zipWith[A,B,C](f: (A,B) => C, a: T => A, b: T => B): T => C = (t: T) => f(a(t),b(t)) } There turns out to be an even more general expression of this type. In general, type constructors that allow an implementation of this interface are applicative functors trait Applicative[F[_]] { def pure[A](a: A): F[A] def map[A,B](f: A => B, a: F[A]): F[B] def ap[A,B](f: F[A => B], a: F[A]): F[B] } An implementation of zipWith is then just this: def zipWith[F[_],A,B,C](f: A => B => C, a: F[A], b: F[B]) (implicit m: Applicative[F]) = m.ap(m.map(f,a), b) This generalises to functions of any arity: m.ap(m.ap(m.ap(m.map(f,a), b), c), d) The Scalaz library provides Applicative instances for a lot of data structures in the standard library. Also, convenient syntax is provided for ap. In Scalaz, this function is called <*>: def zipWith[F[_]:Applicative,A,B,C](f: A => B => C, a: F[A], b: F[B]) = (a map f) <*> b A: There is a method map2 in the List object in Scala 2.7 (and 2.8, but it's deprecated in favor of zipped). You use it like so: List.map2( List(1,2,3) , List(4,5,6) ) { _ * _ } // Gives List(4,10,18) Eastsun's already shown how to use zipped in 2.8 (which works on all collections, not just lists). A: Well, I don't know the syntax (f: (A,B) => C, Iterable[A], Iterable[B] ):Iterable[C] (and I know nothing of Scala), but if I had to guess, it would mean "A function f taking two iterable arguments A and B and returning an iterable C". I'm not sure if this implies that all iterables yield the same number of items. In Python, I think you're looking for the zip function: >>> A = range(10, 15) >>> B = range(1000, 1500, 100) >>> zip(A, B) [(10, 1000), (11, 1100), (12, 1200), (13, 1300), (14, 1400)] >>> [a + b for a,b in zip(A, B)] [1010, 1111, 1212, 1313, 1414] zip's output is only as long as the shortest iterable: >>> A=range(10, 12) >>> zip(A, B) [(10, 1000), (11, 1100)] Anyway, some built-in Python functions everyone needs to know but easily misses: enumerate, map, reduce, and zip. filter used to be on that list, but it's clearer and more flexible to use a list comprehension these days.
Is there an equivalent in Scala to Python's more general map function?
I know that Scala's Lists have a map implementation with signature (f: (A) => B):List[B] and a foreach implementation with signature (f: (A) => Unit):Unit but I'm looking for something that accepts multiple iterables the same way that the Python map accepts multiple iterables. I'm looking for something with a signature of (f: (A,B) => C, Iterable[A], Iterable[B] ):Iterable[C] or equivalent. Is there a library where this exists or a comparable way of doing similar? Edit: As suggested below I could do val output = myList zip( otherList ) map( x => x(0) + x(1) ) but that creates a temporary list in between steps. If the commentor would post I could upvote him (hint, hint) but is there another way?
[ "In scala 2.8, there is a method called zipped in Tuple2 & Tuple3 which avoid to create temporary collection.\nHere is some sample use case:\nWelcome to Scala version 2.8.0.r21561-b20100414020114 (Java HotSpot(TM) Client VM, Java 1.6.0_18).\nType in expressions to have them evaluated.\nType :help for more information.\n\nscala> val xs = 0 to 9\nxs: scala.collection.immutable.Range.Inclusive with scala.collection.immutable.Range.ByOne = Range(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)\n\nscala> val ys = List.range(0,10)\nys: List[Int] = List(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)\n\nscala> val zs = Array.range(0,10)\nzs: Array[Int] = Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)\n\nscala> (xs,ys).zipped.map{ _+_ }\nres1: scala.collection.immutable.IndexedSeq[Int] = Vector(0, 2, 4, 6, 8, 10, 12, 14, 16, 18)\n\nscala> (zs,ys,xs).zipped.map{ _+_+_ }\nres2: Array[Int] = Array(0, 3, 6, 9, 12, 15, 18, 21, 24, 27)\n\nscala>\n\nThere is a zip method in both Tuple2 and Tuple3. \nxs.zip(ys) is the same as (xs,ys).zip\nNote: There is also some shortage in (xs,ys).zip and (xs,ys).zipped, make sure that xs can't be a INFINITE Stream. Go to Ticket #2634 for more information.\nI have a post in nabble.com some days ago which shows my opinions about how to fix this ticket.\n", "The function you're looking for is usually called zipWith. It's unfortunately not provided in the standard libraries, but it's pretty easy to write:\ndef zipWith[A,B,C](f: (A,B) => C, a: Iterable[A], b: Iterable[B]) =\n new Iterable[C] {\n def elements = (a.elements zip b.elements) map f.tupled\n }\n\nThis will traverse only once, since the implementations for zip and map on iterators are fully lazy.\nBut why stop at Iterable? This has an even more general form. We could declare an interface for all data structures that can be zipped this way.\ntrait Zip[F[_]] {\n def zipWith[A,B,C](f: (A,B) => C, a: F[A], b: F[B]): F[C]\n}\n\nFor example, we can zip functions:\ntrait Reader[A] {\n type Read[B] = (A => B)\n}\n\ndef readerZip[T] = new Zip[Reader[T]#Read] {\n def zipWith[A,B,C](f: (A,B) => C, a: T => A, b: T => B): T => C =\n (t: T) => f(a(t),b(t))\n}\n\nThere turns out to be an even more general expression of this type. In general, type constructors that allow an implementation of this interface are applicative functors\ntrait Applicative[F[_]] {\n def pure[A](a: A): F[A]\n def map[A,B](f: A => B, a: F[A]): F[B]\n def ap[A,B](f: F[A => B], a: F[A]): F[B]\n}\n\nAn implementation of zipWith is then just this:\ndef zipWith[F[_],A,B,C](f: A => B => C, a: F[A], b: F[B])\n (implicit m: Applicative[F]) =\n m.ap(m.map(f,a), b)\n\nThis generalises to functions of any arity:\n m.ap(m.ap(m.ap(m.map(f,a), b), c), d)\n\nThe Scalaz library provides Applicative instances for a lot of data structures in the standard library. Also, convenient syntax is provided for ap. In Scalaz, this function is called <*>:\ndef zipWith[F[_]:Applicative,A,B,C](f: A => B => C, a: F[A], b: F[B]) =\n (a map f) <*> b\n\n", "There is a method map2 in the List object in Scala 2.7 (and 2.8, but it's deprecated in favor of zipped). You use it like so:\nList.map2( List(1,2,3) , List(4,5,6) ) { _ * _ } // Gives List(4,10,18)\n\nEastsun's already shown how to use zipped in 2.8 (which works on all collections, not just lists).\n", "Well, I don't know the syntax (f: (A,B) => C, Iterable[A], Iterable[B] ):Iterable[C] (and I know nothing of Scala), but if I had to guess, it would mean \"A function f taking two iterable arguments A and B and returning an iterable C\". I'm not sure if this implies that all iterables yield the same number of items.\nIn Python, I think you're looking for the zip function:\n>>> A = range(10, 15)\n>>> B = range(1000, 1500, 100)\n>>> zip(A, B)\n[(10, 1000), (11, 1100), (12, 1200), (13, 1300), (14, 1400)]\n>>> [a + b for a,b in zip(A, B)]\n[1010, 1111, 1212, 1313, 1414]\n\nzip's output is only as long as the shortest iterable:\n>>> A=range(10, 12)\n>>> zip(A, B)\n[(10, 1000), (11, 1100)]\n\nAnyway, some built-in Python functions everyone needs to know but easily misses: enumerate, map, reduce, and zip. filter used to be on that list, but it's clearer and more flexible to use a list comprehension these days.\n" ]
[ 12, 11, 3, 2 ]
[]
[]
[ "applicative", "iterable", "python", "scala" ]
stackoverflow_0002650156_applicative_iterable_python_scala.txt
Q: Inexpensive ways to add seek to a filetype object PdfFileReader reads the content from a pdf file to create an object. I am querying the pdf from a cdn via urllib.urlopen(), this provides me a file like object, which has no seek. PdfFileReader, however uses seek. What is the simple way to create a PdfFileReader object from a pdf downloaded via url. Now, what can I do to avoid writing to disk and reading it again via file(). Thanks in advance. A: You could use the .read() method to read in the entire data of the file, and then create your own File-like object (most likely via StringIO) to provide access to it. A: There isn't really an inexpensive, ready-to-use way to do this. The simplest way is to read all data and put it into a StringIO object. That does, however, require you read everything first, which may or may not be what you want. If you want something that only reads as necessary, and then stores what was read (or perhaps just a portion of what was read) then you will have to write it yourself. You may want to see the source for the StringIO module (or the io module, in Python 2.6) for some examples. A: I suspect you may be optimising prematurely here. Most modern systems will cache files in memory for a significant period of time before they flush them to disk, so if you write the data to a temporary file, read it back in, then close and delete the file you may find that there's no significant disc traffic (unless it really is 100MB). You might want to look at using tempfile.TemporaryFile() which creates a temporary file that is automatically deleted when closed, or else tempfile.SpooledTemporaryFile() which explicitly holds it all in memory until it exceeds a particular size.
Inexpensive ways to add seek to a filetype object
PdfFileReader reads the content from a pdf file to create an object. I am querying the pdf from a cdn via urllib.urlopen(), this provides me a file like object, which has no seek. PdfFileReader, however uses seek. What is the simple way to create a PdfFileReader object from a pdf downloaded via url. Now, what can I do to avoid writing to disk and reading it again via file(). Thanks in advance.
[ "You could use the .read() method to read in the entire data of the file, and then create your own File-like object (most likely via StringIO) to provide access to it.\n", "There isn't really an inexpensive, ready-to-use way to do this. The simplest way is to read all data and put it into a StringIO object. That does, however, require you read everything first, which may or may not be what you want.\nIf you want something that only reads as necessary, and then stores what was read (or perhaps just a portion of what was read) then you will have to write it yourself. You may want to see the source for the StringIO module (or the io module, in Python 2.6) for some examples.\n", "I suspect you may be optimising prematurely here.\nMost modern systems will cache files in memory for a significant period of time before they flush them to disk, so if you write the data to a temporary file, read it back in, then close and delete the file you may find that there's no significant disc traffic (unless it really is 100MB).\nYou might want to look at using tempfile.TemporaryFile() which creates a temporary file that is automatically deleted when closed, or else tempfile.SpooledTemporaryFile() which explicitly holds it all in memory until it exceeds a particular size.\n" ]
[ 1, 1, 1 ]
[]
[]
[ "file", "file_type", "python", "urllib" ]
stackoverflow_0002653079_file_file_type_python_urllib.txt
Q: Cython code doesn't work I wrote some Python code and it worked fine when using the "python". I then converted it to C using "Cython" and used distutils to compile it to a shared library. I then changed some of the code to Cython so it would run faster. But when I imported the .so module and tried to use the command I had "cdef"ed it said that the command didn't exist. Original code: import time as t def time(function): t1 = t.time() function() t2 = t.time() return t2 - t1 New code: import time as t cdef time(function): t1 = t.time() function() t2 = t.time() return t2 - t1 I tried using "cdef int time" but I got the same result. Any advice? A: cdef functions are not exposed to Python. cpdef is provided to provide a Python wrapper to a C function defined in Cython. Also, you're probably better off using timeit than bothering with implementing this.
Cython code doesn't work
I wrote some Python code and it worked fine when using the "python". I then converted it to C using "Cython" and used distutils to compile it to a shared library. I then changed some of the code to Cython so it would run faster. But when I imported the .so module and tried to use the command I had "cdef"ed it said that the command didn't exist. Original code: import time as t def time(function): t1 = t.time() function() t2 = t.time() return t2 - t1 New code: import time as t cdef time(function): t1 = t.time() function() t2 = t.time() return t2 - t1 I tried using "cdef int time" but I got the same result. Any advice?
[ "cdef functions are not exposed to Python. cpdef is provided to provide a Python wrapper to a C function defined in Cython.\nAlso, you're probably better off using timeit than bothering with implementing this.\n" ]
[ 2 ]
[]
[]
[ "cython", "function", "python" ]
stackoverflow_0002653712_cython_function_python.txt
Q: Importing a submodule given a module object I am given a module as an object, and I need to import a submodule from it. Like this: import logging x = logging Now I want to import logging.handlers using only x and not the name "logging". (This is because I am doing some dynamic imports and won't know the name of the module.) How do I do this? If I do import x.handlers it fails. A: Try: __import__('%s.handlers' % x.__name__) Note that this will return a reference to logging, which you probably won't care about. It will create x.handlers though. A: You can use built-in function __import__: http://docs.python.org/library/functions.html#import
Importing a submodule given a module object
I am given a module as an object, and I need to import a submodule from it. Like this: import logging x = logging Now I want to import logging.handlers using only x and not the name "logging". (This is because I am doing some dynamic imports and won't know the name of the module.) How do I do this? If I do import x.handlers it fails.
[ "Try:\n__import__('%s.handlers' % x.__name__)\n\nNote that this will return a reference to logging, which you probably won't care about. It will create x.handlers though.\n", "You can use built-in function __import__:\nhttp://docs.python.org/library/functions.html#import\n" ]
[ 5, 0 ]
[]
[]
[ "dynamic", "import", "python" ]
stackoverflow_0002654046_dynamic_import_python.txt
Q: Double linking array in Python Since I'm pretty new this question'll certainly sound stupid but I have no idea about how to approach this. I'm trying take a list of nodes and for each of the nodes I want to create an array of predecessors and successors in the ordered array of all nodes. Currently my code looks like this: nodes = self.peers.keys() nodes.sort() peers = {} numPeers = len(nodes) for i in nodes: peers[i] = [self.coordinator] for i in range(0,len(nodes)): peers[nodes[i%numPeers]].append(nodes[(i+1)%numPeers]) peers[nodes[(i+1)%numPeers]].append(nodes[i%numPeers]) # peers[nodes[i%numPeers]].append(nodes[(i+4)%numPeers]) # peers[nodes[(i+4)%numPeers]].append(nodes[i%numPeers]) The last two lines should later be used to create a skip graph, but that's not really important. The problem is that it doesn't really work reliably, sometimes a predecessor or a successor is skipped, and instead the next one is used, and so forth. Is this correct at all or is there a better way to do this? Basically I need to get the array indices with certain offsets from each other. Any ideas? A: I would almost bet that when the error occurs, the values in nodes have duplicates, which would cause your dictionary in peers to get mixed up. Your code assumes the values in nodes are unique.
Double linking array in Python
Since I'm pretty new this question'll certainly sound stupid but I have no idea about how to approach this. I'm trying take a list of nodes and for each of the nodes I want to create an array of predecessors and successors in the ordered array of all nodes. Currently my code looks like this: nodes = self.peers.keys() nodes.sort() peers = {} numPeers = len(nodes) for i in nodes: peers[i] = [self.coordinator] for i in range(0,len(nodes)): peers[nodes[i%numPeers]].append(nodes[(i+1)%numPeers]) peers[nodes[(i+1)%numPeers]].append(nodes[i%numPeers]) # peers[nodes[i%numPeers]].append(nodes[(i+4)%numPeers]) # peers[nodes[(i+4)%numPeers]].append(nodes[i%numPeers]) The last two lines should later be used to create a skip graph, but that's not really important. The problem is that it doesn't really work reliably, sometimes a predecessor or a successor is skipped, and instead the next one is used, and so forth. Is this correct at all or is there a better way to do this? Basically I need to get the array indices with certain offsets from each other. Any ideas?
[ "I would almost bet that when the error occurs, the values in nodes have duplicates, which would cause your dictionary in peers to get mixed up. Your code assumes the values in nodes are unique.\n" ]
[ 2 ]
[]
[]
[ "arrays", "indexing", "overlay", "p2p", "python" ]
stackoverflow_0002653702_arrays_indexing_overlay_p2p_python.txt
Q: Error on windows using session from appengine-utilities I ran across an odd problem while trying to transfer a project to a windows machine. In my project I use a session handler (http://gaeutilities.appspot.com/session) it works fine on my mac but on windows I get: Traceback (most recent call last): File "C:\Program Files (x86)\Google\google_appengine\google\appengine\ext\webapp__init__.py", line 510, in call handler.get(*groups) File "C:\Development\Byggmax.Affiliate\bmaffiliate\admin.py", line 29, in get session = Session() File "C:\Development\Byggmax.Affiliate\bmaffiliate\appengine_utilities\sessions.py", line 547, in init self.cookie.load(string_cookie) File "C:\Python26\lib\Cookie.py", line 628, in load for k, v in rawdata.items(): AttributeError: 'unicode' object has no attribute 'items' Anyone familiar with the Session Handler that knows anything of this? All help are welcome! ..fredrik A: The bug is pretty clear by glancing at the sources, although perfectly OS-independent. In sessions.py lines 544-547: string_cookie = os.environ.get(u"HTTP_COOKIE", u"") self.cookie = Cookie.SimpleCookie() self.output_cookie = Cookie.SimpleCookie() self.cookie.load(string_cookie) lines 544 makes it very likely that string_cookie is unicode (though it might be a byte string from the environment, those u"" mean that the sessions.py author is trying hard to get it as unicode!-). Meanwhile in Cookie.py lines 624-628: if type(rawdata) == type(""): self.__ParseString(rawdata) else: # self.update() wouldn't call our custom __setitem__ for k, v in rawdata.items(): line 624 only parses a byte string: anything else (including a unicode string!) is treated like a dict (whence the crash). Obviously this Cookie.py is emphatically not the one this sessions.py was developed for. So what can possibly have happened...? Well, we do know of course that App Engine is strictly Python 2.5 and the Cookie.py we showed is that of Python 2.6. So let's look at Cookie.py in 2.5 (lines 618-621 in this version): if type(rawdata) == type(""): self.__ParseString(rawdata) else: self.update(rawdata) so in 2.5, given an empty unicode string, the cookie (which subclasses dict) does self.update(u'')... which is an innocuous no-op. The comment in 2.6 shows why the maintainer of Cookie.py switched to the current loop... which breaks when rawdata's u''. Long story short: install Python 2.5 on your Windows machine, and use that version with the GAE SDK, not the 2.6 you're currently using -- unless you truly love debugging of extremely subtle version differences where an incorrect use was innocuous in 2.5 but breaks in 2.6, like this one;-). Also enter a bug about this in the gaeutilities tracker, since that call to load with an empty unicode string is simply wrong, even though in 2.5 it happens to be innocuous. Specifically, get the appropriate Windows msi of 2.5.4 from here, depending on whether you have a 32-bit or 64-bit version of Windows. A: Followed the link to this post from the issue posted on the projects issue tracker. As posted there, my response is I won't be focusing on applying updates to make the project work with Python 2.6. However, I will put a little more emphasis on taking a look at the call to load with an empty unicode string.
Error on windows using session from appengine-utilities
I ran across an odd problem while trying to transfer a project to a windows machine. In my project I use a session handler (http://gaeutilities.appspot.com/session) it works fine on my mac but on windows I get: Traceback (most recent call last): File "C:\Program Files (x86)\Google\google_appengine\google\appengine\ext\webapp__init__.py", line 510, in call handler.get(*groups) File "C:\Development\Byggmax.Affiliate\bmaffiliate\admin.py", line 29, in get session = Session() File "C:\Development\Byggmax.Affiliate\bmaffiliate\appengine_utilities\sessions.py", line 547, in init self.cookie.load(string_cookie) File "C:\Python26\lib\Cookie.py", line 628, in load for k, v in rawdata.items(): AttributeError: 'unicode' object has no attribute 'items' Anyone familiar with the Session Handler that knows anything of this? All help are welcome! ..fredrik
[ "The bug is pretty clear by glancing at the sources, although perfectly OS-independent. In sessions.py lines 544-547:\n string_cookie = os.environ.get(u\"HTTP_COOKIE\", u\"\")\n self.cookie = Cookie.SimpleCookie()\n self.output_cookie = Cookie.SimpleCookie()\n self.cookie.load(string_cookie)\n\nlines 544 makes it very likely that string_cookie is unicode (though it might be a byte string from the environment, those u\"\" mean that the sessions.py author is trying hard to get it as unicode!-). Meanwhile in Cookie.py lines 624-628:\nif type(rawdata) == type(\"\"):\n self.__ParseString(rawdata)\nelse:\n # self.update() wouldn't call our custom __setitem__\n for k, v in rawdata.items():\n\nline 624 only parses a byte string: anything else (including a unicode string!) is treated like a dict (whence the crash).\nObviously this Cookie.py is emphatically not the one this sessions.py was developed for. So what can possibly have happened...? Well, we do know of course that App Engine is strictly Python 2.5 and the Cookie.py we showed is that of Python 2.6. So let's look at Cookie.py in 2.5 (lines 618-621 in this version):\n if type(rawdata) == type(\"\"):\n self.__ParseString(rawdata)\n else:\n self.update(rawdata)\n\nso in 2.5, given an empty unicode string, the cookie (which subclasses dict) does self.update(u'')... which is an innocuous no-op. The comment in 2.6 shows why the maintainer of Cookie.py switched to the current loop... which breaks when rawdata's u''.\nLong story short: install Python 2.5 on your Windows machine, and use that version with the GAE SDK, not the 2.6 you're currently using -- unless you truly love debugging of extremely subtle version differences where an incorrect use was innocuous in 2.5 but breaks in 2.6, like this one;-). Also enter a bug about this in the gaeutilities tracker, since that call to load with an empty unicode string is simply wrong, even though in 2.5 it happens to be innocuous.\nSpecifically, get the appropriate Windows msi of 2.5.4 from here, depending on whether you have a 32-bit or 64-bit version of Windows.\n", "Followed the link to this post from the issue posted on the projects issue tracker. As posted there, my response is I won't be focusing on applying updates to make the project work with Python 2.6. However, I will put a little more emphasis on taking a look at the call to load with an empty unicode string. \n" ]
[ 11, 1 ]
[]
[]
[ "google_app_engine", "python", "session" ]
stackoverflow_0002652820_google_app_engine_python_session.txt
Q: access variables of other functions in python, how can i access the variables of one function into another function, is it possible, i tried the global variable method but that doesn't work for me. can someone help me, how to access the variables from one function to another function. A: If you want to share data between functions then create a class and turn the functions into methods on the class. A: Don't try to do this. Explicit is better than implicit - if your function needs access to certain variables, pass them in. If it needs to change a value in the calling function, return the new value.
access variables of other functions
in python, how can i access the variables of one function into another function, is it possible, i tried the global variable method but that doesn't work for me. can someone help me, how to access the variables from one function to another function.
[ "If you want to share data between functions then create a class and turn the functions into methods on the class. \n", "Don't try to do this. Explicit is better than implicit - if your function needs access to certain variables, pass them in. If it needs to change a value in the calling function, return the new value.\n" ]
[ 1, 0 ]
[]
[]
[ "function", "global_variables", "python", "variables" ]
stackoverflow_0002654484_function_global_variables_python_variables.txt
Q: Is there a production ready web application framework in Python? I heard lots of good opinions about Python language. They say it's mature, expressive etc... I'm looking for production-ready enterprise application frameworks in Python. By "production ready" I mean : supports objective-relational mapping with caching and declarative desciption (like JPA, Hibernate etc..) controls oriented user interface support - no HTML templates but something like JSF (RichFaces, Icefaces) or GWT, Vaadin, ZK component decomposition and dependency injection (like EJB or Spring) unit and integration testing good IDE support clustering, modularity etc (like Terracota, OSGi etc..) there are successful applications written in it by companies like IBM, Oracle etc (I mean real business applications not Twitter) could have commercial support Is it possible at all in Python world ? Or only choices are : use Python and write everything from the bottom (too expensice) stick to Java EE buy .NET stack A: Django seems like the obvious choice. It is by far the most stable and developed framework, used by several large corporations. Because it is a Python framework, it can generally use any Python module, as well as the many modules that have been made for Django. It should fulfill all of your needs, and is not terribly difficult to learn/deploy. A: For the context, I work at a large private bank in Switzerland, writing Enterprise applications on the J2EE stack. There are plenty of "Production Ready" web frameworks in Python. And there are plenty of large Python-based websites out there. That said, I think Python is a poor choice for an Enterprisy application. It can be used as a glue language, or a scripting language (our deployment scripts are Python). The showstopper for me is backward compatibility (Python 3.x isn't backward compatible with Python 2.x). The Python philosopy seems to be more to innovate and make the language better, smoother, and not necessarily to support programs written 10 years ago. On the Web framework side, I love Django, but it is definitely much too young and it evolves too rapidly to be used in the enterprise. I don't have much experience with other Python-based frameworks. If you want an enterprise-oriented framework, you'll have to stay with enterprise stacks (Java / .Net). On the other hand, even in the Java world, there is a tendency to use frameworks that are less enterprisy. Think Spring vs EJB2 or EJB3 being much lighter weight than EJB2. Or think Flex (which is far from an enterprise framework in my view) being used more and more in the enterprise. So if your enterprise is openminded enough, ready to jump into the future, using Django, RoR or other modern Web 2.0, community driven, Open Source, next generation, active record based frameworks ... might not be that much of a stretch ... And finally, to answer a few of your points directly : support of ORM / caching / ... : yes, but most solutions are based on active record, which is fine for 90% of what you might want to do, but is definitly not as complete / complex as JPA / Hibernate control-oriented UI : no, and you wont find a standard, so you wont find 3rd party components. The closest you might get is integration with jQuery or other JS UI frameworks dependency injection : There is a port of Spring to Python, maintained by SpringSource. But DI is not in the Python philosophy. The same problem will be resolved with functions, default arguments and closures. And we might argue that the Pythonic solution is cleaner than the Java way ... unit / integration tests : very good support, multiple test frameworks. Still, support is not as good as Java where we have tons of tools around testing. good IDE support : there are technical limitations to the ammount of support you can provide to a dynamic language, but at least both Eclipse and Netbeans have great support for Python. clustering / modularity : clustering will be resolved with a "share nothing infrastructure" and/or distributed caching. There are no solutions for modularity (in the OSGI sense) as far as I know. But I would challenge that very often OSGI is a solution for a problem we dont have in the enterprise ... A: Check out Zope ... A: As mentioned, django is perhaps the most stable python web application framework. To answer your points in turn: supports objective-relational mapping with caching and declarative desciption (like JPA, Hibernate etc..). Yes, see django models controls oriented user interface support - no HTML templates but something like JSF (RichFaces, Icefaces) or GWT, Vaadin, ZK. No. django templates are there but you could add some other view layer quite easily. component decomposition and dependency injection (like EJB or Spring). Not sure as I haven't used EJB. unit and integration testing. Yes, see django testing. good IDE support. Pretty good. See eclipse + pydev clustering, modularity etc (like Terracota, OSGi etc..). Don't know. there are successful applications written in it by companies like IBM, Oracle etc (I mean real business applications not Twitter). Mostly news organisations like LA Times and Washington Post. could have commercial support. There are a few like this. A: Have you had a look at Jython? Jython is an implementation of Python for the Java Virtual Machine. It is possible to run Django on Jython: Django on Jython and to use Jython and Django with a Java EE application server: Django on Glassfish. If you haven't definitely selected Python yet, you might take a look at Groovy with either Wicket or Grails as the web application framework. A: What about Plone? visit http://www.plone.org for more information. Used in many enterprise level applications. Some organizations using Plone: CIA, FBI, NASA, Oxfam, Brazilian Federal Government, Novell, the list goes on. For information about deployed solutions and case studies visit www.plone.net
Is there a production ready web application framework in Python?
I heard lots of good opinions about Python language. They say it's mature, expressive etc... I'm looking for production-ready enterprise application frameworks in Python. By "production ready" I mean : supports objective-relational mapping with caching and declarative desciption (like JPA, Hibernate etc..) controls oriented user interface support - no HTML templates but something like JSF (RichFaces, Icefaces) or GWT, Vaadin, ZK component decomposition and dependency injection (like EJB or Spring) unit and integration testing good IDE support clustering, modularity etc (like Terracota, OSGi etc..) there are successful applications written in it by companies like IBM, Oracle etc (I mean real business applications not Twitter) could have commercial support Is it possible at all in Python world ? Or only choices are : use Python and write everything from the bottom (too expensice) stick to Java EE buy .NET stack
[ "Django seems like the obvious choice. It is by far the most stable and developed framework, used by several large corporations.\nBecause it is a Python framework, it can generally use any Python module, as well as the many modules that have been made for Django.\nIt should fulfill all of your needs, and is not terribly difficult to learn/deploy.\n", "For the context, I work at a large private bank in Switzerland, writing Enterprise applications on the J2EE stack.\nThere are plenty of \"Production Ready\" web frameworks in Python. And there are plenty of large Python-based websites out there.\nThat said, I think Python is a poor choice for an Enterprisy application. It can be used as a glue language, or a scripting language (our deployment scripts are Python). The showstopper for me is backward compatibility (Python 3.x isn't backward compatible with Python 2.x). The Python philosopy seems to be more to innovate and make the language better, smoother, and not necessarily to support programs written 10 years ago.\nOn the Web framework side, I love Django, but it is definitely much too young and it evolves too rapidly to be used in the enterprise. I don't have much experience with other Python-based frameworks.\nIf you want an enterprise-oriented framework, you'll have to stay with enterprise stacks (Java / .Net).\nOn the other hand, even in the Java world, there is a tendency to use frameworks that are less enterprisy. Think Spring vs EJB2 or EJB3 being much lighter weight than EJB2. Or think Flex (which is far from an enterprise framework in my view) being used more and more in the enterprise. So if your enterprise is openminded enough, ready to jump into the future, using Django, RoR or other modern Web 2.0, community driven, Open Source, next generation, active record based frameworks ... might not be that much of a stretch ...\nAnd finally, to answer a few of your points directly :\n\nsupport of ORM / caching / ... : yes, but most solutions are based on active record, which is fine for 90% of what you might want to do, but is definitly not as complete / complex as JPA / Hibernate\ncontrol-oriented UI : no, and you wont find a standard, so you wont find 3rd party components. The closest you might get is integration with jQuery or other JS UI frameworks\ndependency injection : There is a port of Spring to Python, maintained by SpringSource. But DI is not in the Python philosophy. The same problem will be resolved with functions, default arguments and closures. And we might argue that the Pythonic solution is cleaner than the Java way ...\nunit / integration tests : very good support, multiple test frameworks. Still, support is not as good as Java where we have tons of tools around testing.\ngood IDE support : there are technical limitations to the ammount of support you can provide to a dynamic language, but at least both Eclipse and Netbeans have great support for Python.\nclustering / modularity : clustering will be resolved with a \"share nothing infrastructure\" and/or distributed caching. There are no solutions for modularity (in the OSGI sense) as far as I know. But I would challenge that very often OSGI is a solution for a problem we dont have in the enterprise ...\n\n", "Check out Zope ...\n", "As mentioned, django is perhaps the most stable python web application framework. To answer your points in turn:\n\nsupports objective-relational mapping with caching and declarative desciption (like JPA, Hibernate etc..). Yes, see django models\ncontrols oriented user interface support - no HTML templates but something like JSF (RichFaces, Icefaces) or GWT, Vaadin, ZK. No. django templates are there but you could add some other view layer quite easily.\ncomponent decomposition and dependency injection (like EJB or Spring). Not sure as I haven't used EJB.\nunit and integration testing. Yes, see django testing.\ngood IDE support. Pretty good. See eclipse + pydev\nclustering, modularity etc (like Terracota, OSGi etc..). Don't know.\nthere are successful applications written in it by companies like IBM, Oracle etc (I mean real business applications not Twitter). Mostly news organisations like LA Times and Washington Post.\ncould have commercial support. There are a few like this.\n\n", "Have you had a look at Jython? Jython is an implementation of Python for the Java Virtual Machine. It is possible to run Django on Jython: \nDjango on Jython and to use Jython and Django with a Java EE application server: Django on Glassfish.\nIf you haven't definitely selected Python yet, you might take a look at Groovy with either Wicket or Grails as the web application framework.\n", "What about Plone? visit http://www.plone.org for more information. Used in many enterprise level applications.\nSome organizations using Plone:\nCIA, FBI, NASA, Oxfam, Brazilian Federal Government, Novell, the list goes on.\nFor information about deployed solutions and case studies visit www.plone.net\n" ]
[ 27, 15, 5, 4, 1, 1 ]
[]
[]
[ "python", "web_applications" ]
stackoverflow_0002643321_python_web_applications.txt
Q: Is Django a good choice for a security critical application? Is Django a good choice for a security critical application? I am asking this because most of the online banking software is built using Java. Is there any real reason for this? A: Actually, the security in Java and Python is the same. Digest-only password handling, cookies that timeout rapidly, careful deletion of sessions, multi-factor authentication. None of this is unique to a Java framework or a Python framework like Django. Django, indeed, has a security backend architecture that allows you to add your own LDAP (or AD) connection, possibly changing the digest technique used. Django has a Profile model where you can keep additional authentication factors. Django offers a few standard decorators for view function authorization checking. Since Python is so flexible, you can trivially write your own decorator functions to layer in different or additional authentication checking. Security is a number of first-class features in Django. A: Probably the reason behind Java is not in the in the security. I think Java is more used in large development companies and banks usually resort to them for their development needs (which probably are not only related to the web site but creep deeper in the backend). So, I see no security reasons, mostly cultural ones. A: The reasons for building banking apps in Java are not related to security, at least IMHO. They are related to: Java is the COBOL of the 21st century, so there is a lot of legacy code that would have to be rewritten and that takes time. Basically banking apps are old apps, they were built in java some ten years ago and nobody wants to throw all the old code away (which BTW is almost always a bad decision), some people believe that a static typed language is somewhat "safer" than the dynamic typed language. This is, IMHO, not true (take for instance collections prior to Java 5). A: I find your connection between Java and banking wrong ended. Most Banking Software has terrible security. And much banking software is written in Java. Does ths mean Java makes it more difficult to write secure software than other languages? Probably it's not Java's fault that there is so little quality security (and safety) wise in Banking software. Actually, like the other posters mention, the choice of your Language usually has very little consequences for your security - unless you select one of the few languages where only hotshot coders can write secure code in (C and PHP come to mind). Many huge E-Commerce sites are written in Python, Ruby and Perl using various frameworks. And I would argue that the security requirements for merchants are much higher than the requirements of the banking industry. That is because merchants have to provide security and good user experience, while banking customers are willing to put up with unusable interfaces SecureID tokens and whatever. So yes: Django is up to the task. A: You should not rely the security of the application on the framework. even though Django does come in with a pretty good number of measures against classical security issues, it can not guarantee that your application will be secure, you need much more than a programming Framework to get a security critical application. I'd say yes, Django is a good choice as long as you know its powers and limitations and are aware of the security flaws of every application. A: You can build a secure application with Django just as you can with any popular Java framework. One part where Java does shine is its extensive cryptographic library. For the minimal encryption tasks that are required by Django, Python’s cryptographic services are sufficient, however its lack of strong block ciphers make the encryption mechanism in Django insecure for data at rest. Python does natively support secure hashing algorithms to include SHA1, SHA224, SHA256, SHA384, and SHA512, however Django’s authentication mechanism has yet to be updated to use anything other than SHA1, making it potentially vulnerable to cryptographic analysis. A: Are you referring to the fact that the complete application is built in Java, or just the part you see in your browser? If the latter, the reason is probably because in the context of webpages, Java applets can be downloaded and run.
Is Django a good choice for a security critical application?
Is Django a good choice for a security critical application? I am asking this because most of the online banking software is built using Java. Is there any real reason for this?
[ "Actually, the security in Java and Python is the same. Digest-only password handling, cookies that timeout rapidly, careful deletion of sessions, multi-factor authentication. None of this is unique to a Java framework or a Python framework like Django.\nDjango, indeed, has a security backend architecture that allows you to add your own LDAP (or AD) connection, possibly changing the digest technique used. \nDjango has a Profile model where you can keep additional authentication factors.\nDjango offers a few standard decorators for view function authorization checking. Since Python is so flexible, you can trivially write your own decorator functions to layer in different or additional authentication checking.\nSecurity is a number of first-class features in Django.\n", "Probably the reason behind Java is not in the in the security. I think Java is more used in large development companies and banks usually resort to them for their development needs (which probably are not only related to the web site but creep deeper in the backend).\nSo, I see no security reasons, mostly cultural ones.\n", "The reasons for building banking apps in Java are not related to security, at least IMHO. They are related to:\n\nJava is the COBOL of the 21st century, so there is a lot of legacy code that would have to be rewritten and that takes time. Basically banking apps are old apps, they were built in java some ten years ago and nobody wants to throw all the old code away (which BTW is almost always a bad decision),\nsome people believe that a static typed language is somewhat \"safer\" than the dynamic typed language. This is, IMHO, not true (take for instance collections prior to Java 5).\n\n", "I find your connection between Java and banking wrong ended.\nMost Banking Software has terrible security. And much banking software is written in Java. Does ths mean Java makes it more difficult to write secure software than other languages?\nProbably it's not Java's fault that there is so little quality security (and safety) wise in Banking software. Actually, like the other posters mention, the choice of your Language usually has very little consequences for your security - unless you select one of the few languages where only hotshot coders can write secure code in (C and PHP come to mind).\nMany huge E-Commerce sites are written in Python, Ruby and Perl using various frameworks. And I would argue that the security requirements for merchants are much higher than the requirements of the banking industry. That is because merchants have to provide security and good user experience, while banking customers are willing to put up with unusable interfaces SecureID tokens and whatever.\nSo yes: Django is up to the task.\n", "You should not rely the security of the application on the framework. even though Django does come in with a pretty good number of measures against classical security issues, it can not guarantee that your application will be secure, you need much more than a programming Framework to get a security critical application.\nI'd say yes, Django is a good choice as long as you know its powers and limitations and are aware of the security flaws of every application.\n", "You can build a secure application with Django just as you can with any popular Java framework. One part where Java does shine is its extensive cryptographic library.\nFor the minimal encryption tasks that are required by Django, Python’s cryptographic services are sufficient, however its lack of strong block ciphers make the encryption mechanism in Django insecure for data at rest.\nPython does natively support secure hashing algorithms to include SHA1, SHA224,\nSHA256, SHA384, and SHA512, however Django’s authentication mechanism has yet\nto be updated to use anything other than SHA1, making it potentially vulnerable to cryptographic analysis.\n", "Are you referring to the fact that the complete application is built in Java, or just the part you see in your browser? If the latter, the reason is probably because in the context of webpages, Java applets can be downloaded and run.\n" ]
[ 30, 17, 8, 4, 1, 1, 0 ]
[]
[]
[ "django", "python", "security" ]
stackoverflow_0000498630_django_python_security.txt
Q: Does sending a dictionary through a multiprocessing.queue mutate it somehow? I have a setup where I send a dictionary through a multiprocessing.queue and do some stuff with it. I was getting an odd "dictionary size changed while iterating over it" error when I wasn't changing anything in the dictionary. Here's the traceback, although it's not terribly helpful: Traceback (most recent call last): File "/usr/lib/python2.6/multiprocessing/queues.py", line 242, in _feed send(obj) RuntimeError: dictionary changed size during iteration So I tried changing the dictionary to an immutable dictionary to see where it was getting altered. Here's the traceback I got: Traceback (most recent call last): File "/home/jason/src/interface_dev/jiva_interface/jiva_interface/delta.py", line 54, in main msg = self.recv() File "/home/jason/src/interface_dev/jiva_interface/jiva_interface/process/__init__.py", line 65, in recv return self.inqueue.get(timeout=timeout) File "/usr/lib/python2.6/multiprocessing/queues.py", line 91, in get res = self._recv() File "build/bdist.linux-i686/egg/pysistence/persistent_dict.py", line 22, in not_implemented_method raise NotImplementedError, 'Cannot set values in a PDict' NotImplementedError: Cannot set values in a PDict This is a bit odd, because as far as I can tell, I'm not doing anything other than getting it from the queue. Could someone shed some light on what's happening here? A: There was a bug fixed quite recently where a garbage collection could change the size of a dictionary that contained weak references and that could trigger the "dictionary changed size during iteration" error. I don't know if that is your problem but the multiprocessing package does use weak references. See http://bugs.python.org/issue7105
Does sending a dictionary through a multiprocessing.queue mutate it somehow?
I have a setup where I send a dictionary through a multiprocessing.queue and do some stuff with it. I was getting an odd "dictionary size changed while iterating over it" error when I wasn't changing anything in the dictionary. Here's the traceback, although it's not terribly helpful: Traceback (most recent call last): File "/usr/lib/python2.6/multiprocessing/queues.py", line 242, in _feed send(obj) RuntimeError: dictionary changed size during iteration So I tried changing the dictionary to an immutable dictionary to see where it was getting altered. Here's the traceback I got: Traceback (most recent call last): File "/home/jason/src/interface_dev/jiva_interface/jiva_interface/delta.py", line 54, in main msg = self.recv() File "/home/jason/src/interface_dev/jiva_interface/jiva_interface/process/__init__.py", line 65, in recv return self.inqueue.get(timeout=timeout) File "/usr/lib/python2.6/multiprocessing/queues.py", line 91, in get res = self._recv() File "build/bdist.linux-i686/egg/pysistence/persistent_dict.py", line 22, in not_implemented_method raise NotImplementedError, 'Cannot set values in a PDict' NotImplementedError: Cannot set values in a PDict This is a bit odd, because as far as I can tell, I'm not doing anything other than getting it from the queue. Could someone shed some light on what's happening here?
[ "There was a bug fixed quite recently where a garbage collection could change the size of a dictionary that contained weak references and that could trigger the \"dictionary changed size during iteration\" error. I don't know if that is your problem but the multiprocessing package does use weak references.\nSee http://bugs.python.org/issue7105\n" ]
[ 2 ]
[]
[]
[ "dictionary", "multiprocessing", "python", "queue" ]
stackoverflow_0002653698_dictionary_multiprocessing_python_queue.txt
Q: Python: Convert format string to regular expression The users of my app can configure the layout of certain files via a format string. For example, the config value the user specifies might be: layout = '%(group)s/foo-%(locale)s/file.txt' I now need to find all such files that already exist. This seems easy enough using the glob module: glob_pattern = layout % {'group': '*', 'locale': '*'} glob.glob(glob_pattern) However, now comes the hard part: Given the list of glob results, I need to get all those filename-parts that matched a given placeholder, for example all the different "locale" values. I thought I would generate a regular expression for the format string that I could then match against the list of glob results (or then possibly skipping glob and doing all the matching myself). But I can't find a nice way to create the regex with both the proper group captures, and escaping the rest of the input. For example, this might give me a regex that matches the locales: regex = layout % {'group': '.*', 'locale': (.*)} But to be sure the regex is valid, I need to pass it through re.escape(), which then also escapes the regex syntax I have just inserted. Calling re.escape() first ruins the format string. I know there's fnmatch.translate(), which would even give me a regex - but not one that returns the proper groups. Is there a good way to do this, without a hack like replacing the placeholders with a regex-safe unique value etc.? Is there possibly some way (a third party library perhaps?) that allows dissecting a format string in a more flexible way, for example splitting the string at the placeholder locations? A: Since you are using named placeholders, I'd use named groups. This seems to work: import re UNIQ='_UNIQUE_STRING_' class MarkPlaceholders(dict): def __getitem__(self, key): return UNIQ+('(?P<%s>.*?)'%key)+UNIQ def format_to_re(format): parts = (format % MarkPlaceholders()).split(UNIQ) for i in range(0, len(parts), 2): parts[i] = re.escape(parts[i]) return ''.join(parts) and then to test: >>> layout = '%(group)s/foo-%(locale)s/file.txt' >>> print format_to_re(layout) (?P<group>.*?)\/foo\-(?P<locale>.*?)\/file\.txt >>> pattern = re.compile(format_to_re(layout)) >>> print pattern.match('something/foo-en-gb/file.txt').groupdict() {'locale': 'en-gb', 'group': 'something'} A: You can try this; it works around your escaping problems. unique = '_UNIQUE_STRING_' assert unique not in layout regexp = re.escape(layout % {'group': unique, 'locale': unique}).replace(unique, '(.*)')
Python: Convert format string to regular expression
The users of my app can configure the layout of certain files via a format string. For example, the config value the user specifies might be: layout = '%(group)s/foo-%(locale)s/file.txt' I now need to find all such files that already exist. This seems easy enough using the glob module: glob_pattern = layout % {'group': '*', 'locale': '*'} glob.glob(glob_pattern) However, now comes the hard part: Given the list of glob results, I need to get all those filename-parts that matched a given placeholder, for example all the different "locale" values. I thought I would generate a regular expression for the format string that I could then match against the list of glob results (or then possibly skipping glob and doing all the matching myself). But I can't find a nice way to create the regex with both the proper group captures, and escaping the rest of the input. For example, this might give me a regex that matches the locales: regex = layout % {'group': '.*', 'locale': (.*)} But to be sure the regex is valid, I need to pass it through re.escape(), which then also escapes the regex syntax I have just inserted. Calling re.escape() first ruins the format string. I know there's fnmatch.translate(), which would even give me a regex - but not one that returns the proper groups. Is there a good way to do this, without a hack like replacing the placeholders with a regex-safe unique value etc.? Is there possibly some way (a third party library perhaps?) that allows dissecting a format string in a more flexible way, for example splitting the string at the placeholder locations?
[ "Since you are using named placeholders, I'd use named groups. This seems to work:\nimport re\nUNIQ='_UNIQUE_STRING_'\nclass MarkPlaceholders(dict):\n def __getitem__(self, key):\n return UNIQ+('(?P<%s>.*?)'%key)+UNIQ\n\ndef format_to_re(format):\n parts = (format % MarkPlaceholders()).split(UNIQ)\n for i in range(0, len(parts), 2):\n parts[i] = re.escape(parts[i])\n return ''.join(parts)\n\nand then to test:\n>>> layout = '%(group)s/foo-%(locale)s/file.txt'\n>>> print format_to_re(layout)\n(?P<group>.*?)\\/foo\\-(?P<locale>.*?)\\/file\\.txt\n>>> pattern = re.compile(format_to_re(layout))\n>>> print pattern.match('something/foo-en-gb/file.txt').groupdict()\n{'locale': 'en-gb', 'group': 'something'}\n\n", "You can try this; it works around your escaping problems.\nunique = '_UNIQUE_STRING_'\nassert unique not in layout\nregexp = re.escape(layout % {'group': unique, 'locale': unique}).replace(unique, '(.*)')\n\n" ]
[ 2, 1 ]
[]
[]
[ "formatting", "python", "regex" ]
stackoverflow_0002654856_formatting_python_regex.txt
Q: What's the equivalent of Ruby's class @@variable in Python? In Ruby 1.9, I can use its class variable like the following: class Sample @@count = 0 def initialize @@count += 1 end def count @@count end end sample = Sample.new puts sample.count # Output: 1 sample2 = Sample.new puts sample2.count # Output: 2 How can I achieve the above in Python 2.5+ ? A: class Sample(object): _count = 0 def __init__(self): Sample._count += 1 @property def count(self): return Sample._count The use is a bit different from Ruby; e.g. if you have this code in module a.py, >>> import a >>> x = a.Sample() >>> print x.count 1 >>> y = a.Sample() >>> print x.count 2 having a Sample.count "class property" (with the same name as the instance property) would be a bit tricky in Python (feasible, but not worth the bother IMHO).
What's the equivalent of Ruby's class @@variable in Python?
In Ruby 1.9, I can use its class variable like the following: class Sample @@count = 0 def initialize @@count += 1 end def count @@count end end sample = Sample.new puts sample.count # Output: 1 sample2 = Sample.new puts sample2.count # Output: 2 How can I achieve the above in Python 2.5+ ?
[ "class Sample(object):\n _count = 0\n\n def __init__(self):\n Sample._count += 1\n\n @property\n def count(self):\n return Sample._count\n\nThe use is a bit different from Ruby; e.g. if you have this code in module a.py,\n>>> import a\n>>> x = a.Sample()\n>>> print x.count\n1\n>>> y = a.Sample()\n>>> print x.count\n2\n\nhaving a Sample.count \"class property\" (with the same name as the instance property) would be a bit tricky in Python (feasible, but not worth the bother IMHO).\n" ]
[ 6 ]
[]
[]
[ "class_variables", "python", "ruby" ]
stackoverflow_0002655104_class_variables_python_ruby.txt
Q: django link format words joined with hypens href="http://www.torontolife.com/daily/daily-dish/restauranto/2010/03/10/best-new-restaurants-2010-james-chatto-names-five-honourable-mentions/">Best new restaurants 2010: honourable mentions does django have built in mechanism to format links above i mean words joined with hypens how can i achieve this ? A: At a lower level, Django provides a function to transform an arbitrary string into a slug: >>> from django.template.defaultfilters import slugify >>> print slugify('Hello, World!') hello-world And because slugify is a default template filter, you can always use this in your templates like so: {{ foo.name|slugify }} A: The "words joined with hypens" thing you're talking about is known as a slug. It is a unique string identifier used to access a specific resource. Django does provide support for using this type of resource-to-URL mapping. There is a built in SlugField which you can use to store the unique string for each resource Django's url routing scheme supports "accepting" slugs To get started doing something like this, you're going to need to understand how the Django framework works overall. I'd recommend checking out the Django Book. It includes a full (and free) tutorial to get you started on how to use these types of things.
django link format words joined with hypens
href="http://www.torontolife.com/daily/daily-dish/restauranto/2010/03/10/best-new-restaurants-2010-james-chatto-names-five-honourable-mentions/">Best new restaurants 2010: honourable mentions does django have built in mechanism to format links above i mean words joined with hypens how can i achieve this ?
[ "At a lower level, Django provides a function to transform an arbitrary string into a slug:\n>>> from django.template.defaultfilters import slugify\n>>> print slugify('Hello, World!')\nhello-world\n\nAnd because slugify is a default template filter, you can always use this in your templates like so:\n{{ foo.name|slugify }}\n\n", "The \"words joined with hypens\" thing you're talking about is known as a slug. It is a unique string identifier used to access a specific resource.\nDjango does provide support for using this type of resource-to-URL mapping.\n\nThere is a built in SlugField which you can use to store the unique string for each resource\nDjango's url routing scheme supports \"accepting\" slugs\n\nTo get started doing something like this, you're going to need to understand how the Django framework works overall. I'd recommend checking out the Django Book. It includes a full (and free) tutorial to get you started on how to use these types of things.\n" ]
[ 4, 3 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002655086_django_python.txt
Q: Stop execution of python script when parent Bash shell script is killed I'm working on a Bash shell script that runs several Python scripts like so: cd ${SCRIPT_PATH} python -u ${SCRIPT_NAME} ${SCRIPT_ARGS} >> $JOBLOG 2>&1 At one point, I killed the shell script (using kill PID), but the Python script continued running, even after the script terminated. I thought these would die as soon as the main script died. What am I misunderstanding about Bash scripting, and what can I do to get the functionality I'm looking for? Thanks in advance! A: You need to install a signal handler to take care of your child processes: trap "echo killing childs; pkill -P $$" EXIT A: Children should be sent SIGHUP when the parent process dies - however: a) The child process can ignore SIGHUP, or handle it a non-fatal manner. b) The Child could disassociate itself from the parent process by fork() and becoming a process group leader. You could just exec the python code, so that the shell is replaced with the python.
Stop execution of python script when parent Bash shell script is killed
I'm working on a Bash shell script that runs several Python scripts like so: cd ${SCRIPT_PATH} python -u ${SCRIPT_NAME} ${SCRIPT_ARGS} >> $JOBLOG 2>&1 At one point, I killed the shell script (using kill PID), but the Python script continued running, even after the script terminated. I thought these would die as soon as the main script died. What am I misunderstanding about Bash scripting, and what can I do to get the functionality I'm looking for? Thanks in advance!
[ "You need to install a signal handler to take care of your child processes:\ntrap \"echo killing childs; pkill -P $$\" EXIT\n\n", "Children should be sent SIGHUP when the parent process dies - however:\na) The child process can ignore SIGHUP, or handle it a non-fatal manner.\nb) The Child could disassociate itself from the parent process by fork() and becoming a process group leader.\nYou could just exec the python code, so that the shell is replaced with the python.\n" ]
[ 2, 1 ]
[]
[]
[ "bash", "python", "shell" ]
stackoverflow_0002655403_bash_python_shell.txt
Q: Is it approproate it use django signals within the same app Trying to add email notification to my app in the cleanest way possible. When certain fields of a model change, app should send a notification to a user. Here's my old solution: from django.contrib.auth import User class MyModel(models.Model): user = models.ForeignKey(User) field_a = models.CharField() field_b = models.CharField() def save(self, *args, **kwargs): old = self.__class__.objects.get(pk=self.pk) if self.pk else None super(MyModel, self).save(*args, **kwargs) if old and old.field_b != self.field_b: self.notify("b-changed") # Sevelar more events here # ... def notify(self, event) subj, text = self._prepare_notification(event) send_mail(subj, body, settings.DEFAULT_FROM_EMAIL, [self.user.email], fail_silently=True) This worked fine while I had one or two notification types, but after that just felt wrong to have so much code in my save() method. So, I changed code to signal-based: from django.db.models import signals def remember_old(sender, instance, **kwargs): """pre_save hanlder to save clean copy of original record into `old` attribute """ instance.old = None if instance.pk: try: instance.old = sender.objects.get(pk=instance.pk) except ObjectDoesNotExist: pass def on_mymodel_save(sender, instance, created, **kwargs): old = instance.old if old and old.field_b != instance.field_b: self.notify("b-changed") # Sevelar more events here # ... signals.pre_save.connect(remember_old, sender=MyModel, dispatch_uid="mymodel-remember-old") signals.post_save.connect(on_mymodel_save, sender=MyModel, dispatch_uid="mymodel-on-save") The benefit is that I can separate event handlers into different module, reducing size of models.py and I can enable/disable them individually. The downside is that this solution is more code and signal handlers are separated from model itself and unknowing reader can miss them altogether. So, colleagues, do you think it's worth it? A: I think it's a good idea. The "Custom Signals for Uncoupled Design" talk from the most recent DjangoCon is a great resource of what is possible and appropriate with signals in Django. A: I think using signals here is a good design decision. The notification isn't part of the save, it's a consequence of the save. Dealing with these types of consequences is the reason Django provides signals.
Is it approproate it use django signals within the same app
Trying to add email notification to my app in the cleanest way possible. When certain fields of a model change, app should send a notification to a user. Here's my old solution: from django.contrib.auth import User class MyModel(models.Model): user = models.ForeignKey(User) field_a = models.CharField() field_b = models.CharField() def save(self, *args, **kwargs): old = self.__class__.objects.get(pk=self.pk) if self.pk else None super(MyModel, self).save(*args, **kwargs) if old and old.field_b != self.field_b: self.notify("b-changed") # Sevelar more events here # ... def notify(self, event) subj, text = self._prepare_notification(event) send_mail(subj, body, settings.DEFAULT_FROM_EMAIL, [self.user.email], fail_silently=True) This worked fine while I had one or two notification types, but after that just felt wrong to have so much code in my save() method. So, I changed code to signal-based: from django.db.models import signals def remember_old(sender, instance, **kwargs): """pre_save hanlder to save clean copy of original record into `old` attribute """ instance.old = None if instance.pk: try: instance.old = sender.objects.get(pk=instance.pk) except ObjectDoesNotExist: pass def on_mymodel_save(sender, instance, created, **kwargs): old = instance.old if old and old.field_b != instance.field_b: self.notify("b-changed") # Sevelar more events here # ... signals.pre_save.connect(remember_old, sender=MyModel, dispatch_uid="mymodel-remember-old") signals.post_save.connect(on_mymodel_save, sender=MyModel, dispatch_uid="mymodel-on-save") The benefit is that I can separate event handlers into different module, reducing size of models.py and I can enable/disable them individually. The downside is that this solution is more code and signal handlers are separated from model itself and unknowing reader can miss them altogether. So, colleagues, do you think it's worth it?
[ "I think it's a good idea. The \"Custom Signals for Uncoupled Design\" talk from the most recent DjangoCon is a great resource of what is possible and appropriate with signals in Django. \n", "I think using signals here is a good design decision. The notification isn't part of the save, it's a consequence of the save. Dealing with these types of consequences is the reason Django provides signals. \n" ]
[ 4, 3 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002655226_django_python.txt
Q: Writing a DBMS in Python I'm working on a basic DBMS as a pet project and planning to prototype in Python. I figure there's a reason there are only a few Python databases, and my gut agrees that my favorite language will be too slow to act as an honest performing database, but I'm looking forward to using it to learn what I need quickly. Would someone please contradict me? Is Python as ill-suited right now for this sort of thing as I think? EDIT 4/16- I've posted another getting-started-on-this-project type question if anyone is interested. (Non-Relational) DBMS Design Resource A: It's doubtful that anything you create as a pet project is going to turn out to be popular. Presumably you are mostly doing this as a learning experience and for fun. Given these facts, there's no reason to stop yourself so early just because you think there might be performance problems. Just do it and have fun with it. The idea of a pure Python database will at least be academically interesting to others. You can always do some performance profiling to find the bottlenecks and use the usual approaches in speeding things up (CPython, Cython, ctypes, etc.) Don't be so quick to dismiss Python's huge benefits that you get in return for the performance hit. Namely rapid development. A: If performance isn't a huge issue there's no reason Python can't do what you need, it certainly has all of the tools to do so. Designing a database certainly isn't a trivial undertaking, of course, but assuming you have the know-how and Python-fu to put in everything you need (of course, being helped by all of us here at SO ;) ) then the basic building blocks are all there. For reference, there's at least one DBMS written in pure Python that I know of: KirbyBase
Writing a DBMS in Python
I'm working on a basic DBMS as a pet project and planning to prototype in Python. I figure there's a reason there are only a few Python databases, and my gut agrees that my favorite language will be too slow to act as an honest performing database, but I'm looking forward to using it to learn what I need quickly. Would someone please contradict me? Is Python as ill-suited right now for this sort of thing as I think? EDIT 4/16- I've posted another getting-started-on-this-project type question if anyone is interested. (Non-Relational) DBMS Design Resource
[ "It's doubtful that anything you create as a pet project is going to turn out to be popular. Presumably you are mostly doing this as a learning experience and for fun.\nGiven these facts, there's no reason to stop yourself so early just because you think there might be performance problems. Just do it and have fun with it. The idea of a pure Python database will at least be academically interesting to others.\nYou can always do some performance profiling to find the bottlenecks and use the usual approaches in speeding things up (CPython, Cython, ctypes, etc.)\nDon't be so quick to dismiss Python's huge benefits that you get in return for the performance hit. Namely rapid development.\n", "If performance isn't a huge issue there's no reason Python can't do what you need, it certainly has all of the tools to do so. Designing a database certainly isn't a trivial undertaking, of course, but assuming you have the know-how and Python-fu to put in everything you need (of course, being helped by all of us here at SO ;) ) then the basic building blocks are all there.\nFor reference, there's at least one DBMS written in pure Python that I know of: KirbyBase\n" ]
[ 4, 1 ]
[]
[]
[ "database", "performance", "prototype", "python" ]
stackoverflow_0002655748_database_performance_prototype_python.txt
Q: Accessing data entered into multiple Django forms and generating them onto a new URL I have a projects page where users can start up new projects. Each project has two forms. The two forms are: class ProjectForm(forms.Form): Title = forms.CharField(max_length=100, widget=_hfill) class SsdForm(forms.Form): Status = forms.ModelChoiceField(queryset=P.ProjectStatus.objects.all()) With their respective models as follows: class Project(DeleteFlagModel): Title = models.CharField(max_length=100) class Ssd(models.Model): Status = models.ForeignKey(ProjectStatus) Now when a user fills out these two forms, the data is saved into the database. What I want to do is access this data and generate it onto a new URL. So I want to get the "Title" and the "Status" from these two forms and then show them on a new page for that one project. I don't want the "Title" and "Status" from all the projects to show up, just for one project at a time. If this makes sense, how would I do this? I'm very new to Django and Python (though I've read the Django tutorials) so I need as much help as possible. Thanks in advance Edit: The ProjectStatus code is (under models): class ProjectStatus(models.Model): Name = models.CharField(max_length=30) def __unicode__(self): return self.Name A: You don't seem to have any relationship between Project and SSD. Without that, there's no way of telling that any particular SSD object is a member of a particular project. I presume that there are other fields on these models, otherwise there's no point in having SSD as a separate model - status should just be a field on the Project model. But once you've got a relationship between Project and SSD, you can just get the project and then show its related SSD objects in one go by using the relationship: proj = Project.objects.get(pk=myvalue) for ssd in proj.ssd_set.all(): print ssd.Status Also, those forms are plain forms, instead of ModelForms. What happens to the data in them? If they were modelforms, you could save it by just calling form.save().
Accessing data entered into multiple Django forms and generating them onto a new URL
I have a projects page where users can start up new projects. Each project has two forms. The two forms are: class ProjectForm(forms.Form): Title = forms.CharField(max_length=100, widget=_hfill) class SsdForm(forms.Form): Status = forms.ModelChoiceField(queryset=P.ProjectStatus.objects.all()) With their respective models as follows: class Project(DeleteFlagModel): Title = models.CharField(max_length=100) class Ssd(models.Model): Status = models.ForeignKey(ProjectStatus) Now when a user fills out these two forms, the data is saved into the database. What I want to do is access this data and generate it onto a new URL. So I want to get the "Title" and the "Status" from these two forms and then show them on a new page for that one project. I don't want the "Title" and "Status" from all the projects to show up, just for one project at a time. If this makes sense, how would I do this? I'm very new to Django and Python (though I've read the Django tutorials) so I need as much help as possible. Thanks in advance Edit: The ProjectStatus code is (under models): class ProjectStatus(models.Model): Name = models.CharField(max_length=30) def __unicode__(self): return self.Name
[ "You don't seem to have any relationship between Project and SSD. Without that, there's no way of telling that any particular SSD object is a member of a particular project. I presume that there are other fields on these models, otherwise there's no point in having SSD as a separate model - status should just be a field on the Project model.\nBut once you've got a relationship between Project and SSD, you can just get the project and then show its related SSD objects in one go by using the relationship:\nproj = Project.objects.get(pk=myvalue)\nfor ssd in proj.ssd_set.all():\n print ssd.Status\n\nAlso, those forms are plain forms, instead of ModelForms. What happens to the data in them? If they were modelforms, you could save it by just calling form.save().\n" ]
[ 1 ]
[]
[]
[ "django", "mysql", "python" ]
stackoverflow_0002655537_django_mysql_python.txt
Q: Identifying that a variable is a new-style class in Python? I'm using Python 2.x and I'm wondering if there's a way to tell if a variable is a new-style class? I know that if it's an old-style class that I can do the following to find out. import types class oldclass: pass def test(): o = oldclass() if type(o) is types.InstanceType: print 'Is old-style' else: print 'Is NOT old-style' But I haven't been able to find anything that works for new-style classes. I found this question, but the proposed solutions don't seem to work as expected, because simple values as are identified as classes. import inspect def newclass(object): pass def test(): n = newclass() if inspect.isclass(n): print 'Is class' else: print 'Is NOT class' if inspect.isclass(type(n)): print 'Is class' else: print 'Is NOT class' if inspect.isclass(type(1)): print 'Is class' else: print 'Is NOT class' if isinstance(n, object): print 'Is class' else: print 'Is NOT class' if isinstance(1, object): print 'Is class' else: print 'Is NOT class' So is there anyway to do something like this? Or is everything in Python just a class and there's no way to get around that? A: I think what you are asking is: "Can I test if a class was defined in Python code as a new-style class?". Technically simple types such as int are new-style classes, but it is still possible to distinguish classes written in Python from the built-in types. Here's something that works, although it's a bit of a hack: def is_new_style(cls): return hasattr(cls, '__class__') \ and \ ('__dict__' in dir(cls) or hasattr(cls, '__slots__')) class new_style(object): pass class old_style(): pass print is_new_style(int) print is_new_style(new_style) print is_new_style(old_style) Output from Python 2.6: False True False Here's a different way to do it: def is_new_style(cls): return str(cls).startswith('<class ') A: I believe this suffices: def is_new_style_class(klass): return issubclass(klass, object) def is_new_style_class_instance(instance): return issubclass(instance.__class__, object) Typically, you only need the is_new_style_class function for your purposes. Everything not a class will throw a TypeError, so you might want to update it to: def is_new_style_class(klass): try: return issubclass(klass, object) except TypeError: return False Examples: >>> class New(object): pass ... >>> is_new_style_class(New) True >>> class Old: pass ... >>> is_new_style_class(Old) False >>> is_new_style_class(1) False >>> is_new_style_class(int) True int, being a type, is by definition a new-style class (see Unifying types and classes in Python 2.2 ), or —if you prefer— new-style classes are by definition types. A: It's not that "everything is a class": what you're bumping into is that "everything is an object" (that is, every (new-style) thing descends from "object"). But new-style classes are a "type" themselves (actually, the were introduced to bring classes and types together). So you can try checking for import types type(o) == types.TypeType Does that solve your problem?
Identifying that a variable is a new-style class in Python?
I'm using Python 2.x and I'm wondering if there's a way to tell if a variable is a new-style class? I know that if it's an old-style class that I can do the following to find out. import types class oldclass: pass def test(): o = oldclass() if type(o) is types.InstanceType: print 'Is old-style' else: print 'Is NOT old-style' But I haven't been able to find anything that works for new-style classes. I found this question, but the proposed solutions don't seem to work as expected, because simple values as are identified as classes. import inspect def newclass(object): pass def test(): n = newclass() if inspect.isclass(n): print 'Is class' else: print 'Is NOT class' if inspect.isclass(type(n)): print 'Is class' else: print 'Is NOT class' if inspect.isclass(type(1)): print 'Is class' else: print 'Is NOT class' if isinstance(n, object): print 'Is class' else: print 'Is NOT class' if isinstance(1, object): print 'Is class' else: print 'Is NOT class' So is there anyway to do something like this? Or is everything in Python just a class and there's no way to get around that?
[ "I think what you are asking is: \"Can I test if a class was defined in Python code as a new-style class?\". Technically simple types such as int are new-style classes, but it is still possible to distinguish classes written in Python from the built-in types.\nHere's something that works, although it's a bit of a hack:\ndef is_new_style(cls):\n return hasattr(cls, '__class__') \\\n and \\\n ('__dict__' in dir(cls) or hasattr(cls, '__slots__'))\n\n\nclass new_style(object):\n pass\n\nclass old_style():\n pass\n\nprint is_new_style(int)\nprint is_new_style(new_style)\nprint is_new_style(old_style)\n\nOutput from Python 2.6:\nFalse\nTrue\nFalse\n\nHere's a different way to do it:\ndef is_new_style(cls):\n return str(cls).startswith('<class ')\n\n", "I believe this suffices:\ndef is_new_style_class(klass):\n return issubclass(klass, object)\n\ndef is_new_style_class_instance(instance):\n return issubclass(instance.__class__, object)\n\nTypically, you only need the is_new_style_class function for your purposes. Everything not a class will throw a TypeError, so you might want to update it to:\ndef is_new_style_class(klass):\n try:\n return issubclass(klass, object)\n except TypeError:\n return False\n\nExamples:\n>>> class New(object): pass\n... \n>>> is_new_style_class(New)\nTrue\n>>> class Old: pass\n... \n>>> is_new_style_class(Old)\nFalse\n>>> is_new_style_class(1)\nFalse\n>>> is_new_style_class(int)\nTrue\n\nint, being a type, is by definition a new-style class (see Unifying types and classes in Python 2.2 ), or —if you prefer— new-style classes are by definition types.\n", "It's not that \"everything is a class\": what you're bumping into is that \"everything is an object\" (that is, every (new-style) thing descends from \"object\").\nBut new-style classes are a \"type\" themselves (actually, the were introduced to bring classes and types together). So you can try checking for\nimport types\n\ntype(o) == types.TypeType\n\nDoes that solve your problem?\n" ]
[ 7, 2, 1 ]
[ "Checking for old-style classes is really easy. Just check type(cls) is types.ClassType. Checking for new-style classes is also easy, isinstance(cls, type). Note that the built-in types are also new-style classes.\nThere seems to be no trivial way to distinguish built-ins from classes written in Python. New-style classes with __slots__ also don't have __dict__, just like int or str. Checking if str(cls) matches the expected pattern fails if the classes metaclass overrides the __str__ method. Some other ways that also don't work:\n\ncls.__module__ == '__builtin__' (you can reassign __module__ on classes)\nnot any(value is cls for value in vars(__builtins__).values()) (you can add stuff to the __builtin__ module).\n\nThe fact that unification of builtin and userdefined types is so good that distinguishing them is non-trivial problem should imply to you the underlying point. You really shouldn't have to distinguish between them. It doesn't matter what the object is if it implements the expected protocol.\n" ]
[ -1 ]
[ "class", "python", "python_2.x" ]
stackoverflow_0002654622_class_python_python_2.x.txt
Q: Error with python decorator I get this error object has no attribute 'im_func' with this class Test(object): def __init__(self, f): self.func = f def __call__( self, *args ): return self.func(*args) pylons code: class TestController(BaseController): @Test def index(self): return 'hello world' full error: File '/env/lib/python2.5/site-packages/WebError-0.10.2-py2.5.egg/weberror/evalexception.py', line 431 in respond app_iter = self.application(environ, detect_start_response) File '/env/lib/python2.5/site-packages/repoze.who-1.0.18-py2.5.egg/repoze/who/middleware.py', line 107 in __call__ app_iter = app(environ, wrapper.wrap_start_response) File '/env/lib/python2.5/site-packages/Beaker-1.5.3-py2.5.egg/beaker/middleware.py', line 73 in __call__ return self.app(environ, start_response) File '/env/lib/python2.5/site-packages/Beaker-1.5.3-py2.5.egg/beaker/middleware.py', line 152 in __call__ return self.wrap_app(environ, session_start_response) File '/env/lib/python2.5/site-packages/Routes-1.10.3-py2.5.egg/routes/middleware.py', line 130 in __call__ response = self.app(environ, start_response) File '/env/lib/python2.5/site-packages/Pylons-0.9.7-py2.5.egg/pylons/wsgiapp.py', line 125 in __call__ response = self.dispatch(controller, environ, start_response) File '/env/lib/python2.5/site-packages/Pylons-0.9.7-py2.5.egg/pylons/wsgiapp.py', line 324 in dispatch return controller(environ, start_response) File '/project/lib/base.py', line 18 in __call__ return WSGIController.__call__(self, environ, start_response) File '/env/lib/python2.5/site-packages/Pylons-0.9.7-py2.5.egg/pylons/controllers/core.py', line 221 in __call__ response = self._dispatch_call() File '/env/lib/python2.5/site-packages/Pylons-0.9.7-py2.5.egg/pylons/controllers/core.py', line 172 in _dispatch_call response = self._inspect_call(func) File '/env/lib/python2.5/site-packages/Pylons-0.9.7-py2.5.egg/pylons/controllers/core.py', line 80 in _inspect_call argspec = cached_argspecs[func.im_func] AttributeError: 'Test' object has no attribute 'im_func' A: TestController.index ends up an instance of Test, with no access to the TestController object. Also, only user defined methods (which must be functions, not objects) have an im_func attribute. You'll need to instantiate Test and have its __call__ method return a function so that it can be passed the TestController instance. class Test(object): def __call__( self, f): def wrapper(self, *args, **kwargs): # anything in the old Test.__call__ goes here. return f(self, *args, **kwargs) return wrapper class TestController(BaseController): @Test() def index(self): return 'hello world' What's happening A decorator: @decorator def foo(...): is equivalent to: def foo(...): ... foo = decorator(foo) In your original code, @Test def index(self): creates an instance of Test and passes index to the constructor. The resulting object is assigned to the index property of TestController. class TestController(BaseController) def index(self): ... index = Test(index) Test.__call__ doesn't get invoked until you try to call TestController.index. With tc an instance of TestController, tc.index() is equivalent to tc.index.__call__() or Test.__call__(tc.index). The problem is that within the call to Test.__call__, we've lost the reference to tc. It didn't exist when Test.index was defined, so there's no way of saving it. Moreover, it looks like Pylons performs some magic on the methods and it expects tc.index to be a user defined method (which has an im_func property), not an object (which doesn`t). The approach I show you changes when Test.__call__ is invoked and the type of TestController.index. class Test(object): def __call__( self, f): # if done properly, __call__ will get invoked when the decorated method # is defined, not when it's invoked print 'Test.__call__' def wrapper(self, *args, **kwargs): # wrapper will get invoked instead of the decorated method print 'wrapper in Test.__call__' return f(self, *args, **kwargs) return wrapper The definition of TestController.index is equivalent to: class TestController(BaseController): def index(self): ... index = Test()(index) # note: Test.__call__ is invoked here. # 'index' is now 'wrapper' from Test.__call__ tc = TestController tc.index() # wrapper from Test.__call__ is invoked here Because TestController.index is a function rather than an object, tc.index() is equivalent to TestController.index(tc), and we don't lose the reference to tc. A: See http://pylonshq.com/project/pylonshq/ticket/589 ? Is there any monkeypatching or other weirdness going on when you call it? Full traceback and source for the caller would really help here. A: To understand why this does not work as you expect, you have to understand how methods work in Python. When an attribute is looked up, its __get__ method is called (if it exists) and what that returns is used instead of the attribute itself. The main use for this is implementing methods, special sorts of methods (like classmethods), properties and the like. There are similarly hooks for setting and deleting attributes, and it's all explained on http://www.python.org/download/releases/2.2.3/descrintro/ Functions already have __get__ magic built in, so they work as methods automatically, making a bound method passing the current instance when they are looked up. A class you defines does not automatically have this, so you have to define it manually, as such: from functools import partial class Test(object): def __init__(self, f): self.func = f def __call__(self, *args): return self.func(*args) def __get__(self, obj, objtype=None): if obj is not None: # Then the method was called on an instance, not the class itself return partial(self, obj) # Some people might find it easier to phrase this # partial(self.func, obj) in this case, which would be equivalent. I # prefer doing partial(self, obj) since then I can place all the # logic for calling in one place. else: # The method was called on the class, not a particular instance, # so we're not going to do anything special. Functions return # unbound methods (which typecheck their first arguments) in this # case, which I've always thought was an iffy approach. return self class Foo(object): @Test def bar(self): return "hello world" f = Foo() print f.bar() As far as the actual error you are getting, I'm not 100% sure why you do. I wonder if it is not Pylons weirdness I don't know about. The entirety of the relevant file(s) and the full traceback can go a long way to helping people diagnose problems.
Error with python decorator
I get this error object has no attribute 'im_func' with this class Test(object): def __init__(self, f): self.func = f def __call__( self, *args ): return self.func(*args) pylons code: class TestController(BaseController): @Test def index(self): return 'hello world' full error: File '/env/lib/python2.5/site-packages/WebError-0.10.2-py2.5.egg/weberror/evalexception.py', line 431 in respond app_iter = self.application(environ, detect_start_response) File '/env/lib/python2.5/site-packages/repoze.who-1.0.18-py2.5.egg/repoze/who/middleware.py', line 107 in __call__ app_iter = app(environ, wrapper.wrap_start_response) File '/env/lib/python2.5/site-packages/Beaker-1.5.3-py2.5.egg/beaker/middleware.py', line 73 in __call__ return self.app(environ, start_response) File '/env/lib/python2.5/site-packages/Beaker-1.5.3-py2.5.egg/beaker/middleware.py', line 152 in __call__ return self.wrap_app(environ, session_start_response) File '/env/lib/python2.5/site-packages/Routes-1.10.3-py2.5.egg/routes/middleware.py', line 130 in __call__ response = self.app(environ, start_response) File '/env/lib/python2.5/site-packages/Pylons-0.9.7-py2.5.egg/pylons/wsgiapp.py', line 125 in __call__ response = self.dispatch(controller, environ, start_response) File '/env/lib/python2.5/site-packages/Pylons-0.9.7-py2.5.egg/pylons/wsgiapp.py', line 324 in dispatch return controller(environ, start_response) File '/project/lib/base.py', line 18 in __call__ return WSGIController.__call__(self, environ, start_response) File '/env/lib/python2.5/site-packages/Pylons-0.9.7-py2.5.egg/pylons/controllers/core.py', line 221 in __call__ response = self._dispatch_call() File '/env/lib/python2.5/site-packages/Pylons-0.9.7-py2.5.egg/pylons/controllers/core.py', line 172 in _dispatch_call response = self._inspect_call(func) File '/env/lib/python2.5/site-packages/Pylons-0.9.7-py2.5.egg/pylons/controllers/core.py', line 80 in _inspect_call argspec = cached_argspecs[func.im_func] AttributeError: 'Test' object has no attribute 'im_func'
[ "TestController.index ends up an instance of Test, with no access to the TestController object. Also, only user defined methods (which must be functions, not objects) have an im_func attribute. You'll need to instantiate Test and have its __call__ method return a function so that it can be passed the TestController instance.\nclass Test(object):\n def __call__( self, f):\n def wrapper(self, *args, **kwargs):\n # anything in the old Test.__call__ goes here.\n return f(self, *args, **kwargs)\n return wrapper\n\nclass TestController(BaseController):\n @Test()\n def index(self):\n return 'hello world'\n\nWhat's happening\nA decorator:\n@decorator\ndef foo(...):\n\nis equivalent to:\ndef foo(...):\n ...\nfoo = decorator(foo)\n\nIn your original code,\n @Test\n def index(self):\n\ncreates an instance of Test and passes index to the constructor. The resulting object is assigned to the index property of TestController.\nclass TestController(BaseController)\n def index(self):\n ...\n index = Test(index)\n\nTest.__call__ doesn't get invoked until you try to call TestController.index. With tc an instance of TestController, tc.index() is equivalent to tc.index.__call__() or Test.__call__(tc.index). \nThe problem is that within the call to Test.__call__, we've lost the reference to tc. It didn't exist when Test.index was defined, so there's no way of saving it. Moreover, it looks like Pylons performs some magic on the methods and it expects tc.index to be a user defined method (which has an im_func property), not an object (which doesn`t).\nThe approach I show you changes when Test.__call__ is invoked and the type of TestController.index.\nclass Test(object):\n def __call__( self, f):\n # if done properly, __call__ will get invoked when the decorated method \n # is defined, not when it's invoked\n print 'Test.__call__'\n def wrapper(self, *args, **kwargs):\n # wrapper will get invoked instead of the decorated method\n print 'wrapper in Test.__call__'\n return f(self, *args, **kwargs)\n return wrapper\n\nThe definition of TestController.index is equivalent to:\nclass TestController(BaseController):\n def index(self):\n ...\n index = Test()(index) # note: Test.__call__ is invoked here.\n # 'index' is now 'wrapper' from Test.__call__\n\ntc = TestController\ntc.index() # wrapper from Test.__call__ is invoked here\n\nBecause TestController.index is a function rather than an object, tc.index() is equivalent to TestController.index(tc), and we don't lose the reference to tc.\n", "See http://pylonshq.com/project/pylonshq/ticket/589 ?\nIs there any monkeypatching or other weirdness going on when you call it?\nFull traceback and source for the caller would really help here.\n", "To understand why this does not work as you expect, you have to understand how methods work in Python. When an attribute is looked up, its __get__ method is called (if it exists) and what that returns is used instead of the attribute itself. The main use for this is implementing methods, special sorts of methods (like classmethods), properties and the like. There are similarly hooks for setting and deleting attributes, and it's all explained on http://www.python.org/download/releases/2.2.3/descrintro/\nFunctions already have __get__ magic built in, so they work as methods automatically, making a bound method passing the current instance when they are looked up. A class you defines does not automatically have this, so you have to define it manually, as such:\nfrom functools import partial\nclass Test(object):\n def __init__(self, f):\n self.func = f\n\n def __call__(self, *args):\n return self.func(*args)\n\n def __get__(self, obj, objtype=None):\n if obj is not None:\n # Then the method was called on an instance, not the class itself\n return partial(self, obj)\n # Some people might find it easier to phrase this \n # partial(self.func, obj) in this case, which would be equivalent. I \n # prefer doing partial(self, obj) since then I can place all the \n # logic for calling in one place.\n else:\n # The method was called on the class, not a particular instance, \n # so we're not going to do anything special. Functions return \n # unbound methods (which typecheck their first arguments) in this \n # case, which I've always thought was an iffy approach.\n return self\n\nclass Foo(object):\n @Test\n def bar(self):\n return \"hello world\"\n\nf = Foo()\nprint f.bar()\n\nAs far as the actual error you are getting, I'm not 100% sure why you do. I wonder if it is not Pylons weirdness I don't know about. The entirety of the relevant file(s) and the full traceback can go a long way to helping people diagnose problems.\n" ]
[ 4, 1, 1 ]
[]
[]
[ "decorator", "python" ]
stackoverflow_0002655383_decorator_python.txt
Q: filtering elements from list of lists in Python? I want to filter elements from a list of lists, and iterate over the elements of each element using a lambda. For example, given the list: a = [[1,2,3],[4,5,6]] suppose that I want to keep only elements where the sum of the list is greater than N. I tried writing: filter(lambda x, y, z: x + y + z >= N, a) but I get the error: <lambda>() takes exactly 3 arguments (1 given) How can I iterate while assigning values of each element to x, y, and z? Something like zip, but for arbitrarily long lists. thanks, p.s. I know I can write this using: filter(lambda x: sum(x)..., a) but that's not the point, imagine that these were not numbers but arbitrary elements and I wanted to assign their values to variable names. A: Using lambda with filter is sort of silly when we have other techniques available. In this case I would probably solve the specific problem this way (or using the equivalent generator expression) >>> a = [[1, 2, 3], [4, 5, 6]] >>> [item for item in a if sum(item) > 10] [[4, 5, 6]] or, if I needed to unpack, like >>> [(x, y, z) for x, y, z in a if (x + y) ** z > 30] [(4, 5, 6)] If I really needed a function, I could use argument tuple unpacking (which is removed in Python 3.x, by the way, since people don't use it much): lambda (x, y, z): x + y + z takes a tuple and unpacks its three items as x, y, and z. (Note that you can also use this in def, i.e.: def f((x, y, z)): return x + y + z.) You can, of course, use assignment style unpacking (def f(item): x, y, z = item; return x + y + z) and indexing (lambda item: item[0] + item[1] + item[2]) in all versions of Python. A: You can explicitly name the sublist elements (assuming there's always a fixed number of them), by giving lambda a tuple as its argument: >>> a = [[1,2,3],[4,5,6]] >>> N = 10 >>> filter(lambda (i, j, k): i + j + k > N, a) [[4, 5, 6]] If you specify "lambda i, j, k" as you tried to do, you're saying lambda will receive three arguments. But filter will give lambda each element of a, that is, one sublist at a time (thus the error you got). By enclosing the arguments to lambda in parenthesis, you're saying that lambda will receive one argument, but you're also naming each of its components. A: You can do something like >>> a=[[1,2,3],[4,5,6]] >>> filter(lambda (x,y,z),: x+y+z>6, a) [[4, 5, 6]] Using the deconstruction syntax. A: How about this? filter(lambda b : reduce(lambda x, y : x + y, b) >= N, a) This isn't answering the question asked, I know, but it works for arbitrarily-long lists, and arbitrarily-long sublists, and supports any operation that works under reduce(). A: Try something like this: filter(lambda a: a[0] + a[1] + a[2] >= N, a) A: Use a function instead of a lambda, then myVar = a[0], etc. A: Ok, obviously you know that you can use sum. The goal of what you are trying to do seems a bit vague, but I think that the optional parameter syntax might help you out, or at least give you some inspiration. If you place a * before a parameter, it creates a tuple of all of itself and all of the remaining parameters. If you place a ** before it, you get a dictionary. To see this: def print_test(a,b,c,*d): print a print b print c print d print_test(1,2,3,4,5,6) prints 1 2 3 (4, 5, 6) You can use this syntax with lambda too. Like I said, I'm not sure exactly what you are trying to do, but it sounds like this might help. I don't think you can get local variable assignments in lambda without some hacking, but maybe you can use this to assign the values to variables somehow. Edit: Ah, I understand what you are looking for moreso now. I think you want: lambda (a, b, c): a+b+c > N
filtering elements from list of lists in Python?
I want to filter elements from a list of lists, and iterate over the elements of each element using a lambda. For example, given the list: a = [[1,2,3],[4,5,6]] suppose that I want to keep only elements where the sum of the list is greater than N. I tried writing: filter(lambda x, y, z: x + y + z >= N, a) but I get the error: <lambda>() takes exactly 3 arguments (1 given) How can I iterate while assigning values of each element to x, y, and z? Something like zip, but for arbitrarily long lists. thanks, p.s. I know I can write this using: filter(lambda x: sum(x)..., a) but that's not the point, imagine that these were not numbers but arbitrary elements and I wanted to assign their values to variable names.
[ "Using lambda with filter is sort of silly when we have other techniques available.\nIn this case I would probably solve the specific problem this way (or using the equivalent generator expression)\n>>> a = [[1, 2, 3], [4, 5, 6]]\n>>> [item for item in a if sum(item) > 10]\n[[4, 5, 6]]\n\nor, if I needed to unpack, like\n>>> [(x, y, z) for x, y, z in a if (x + y) ** z > 30]\n[(4, 5, 6)]\n\n\nIf I really needed a function, I could use argument tuple unpacking (which is removed in Python 3.x, by the way, since people don't use it much): lambda (x, y, z): x + y + z takes a tuple and unpacks its three items as x, y, and z. (Note that you can also use this in def, i.e.: def f((x, y, z)): return x + y + z.) \nYou can, of course, use assignment style unpacking (def f(item): x, y, z = item; return x + y + z) and indexing (lambda item: item[0] + item[1] + item[2]) in all versions of Python.\n", "You can explicitly name the sublist elements (assuming there's always a fixed number of them), by giving lambda a tuple as its argument:\n>>> a = [[1,2,3],[4,5,6]]\n>>> N = 10\n>>> filter(lambda (i, j, k): i + j + k > N, a)\n[[4, 5, 6]]\n\nIf you specify \"lambda i, j, k\" as you tried to do, you're saying lambda will receive three arguments. But filter will give lambda each element of a, that is, one sublist at a time (thus the error you got). By enclosing the arguments to lambda in parenthesis, you're saying that lambda will receive one argument, but you're also naming each of its components. \n", "You can do something like\n>>> a=[[1,2,3],[4,5,6]]\n>>> filter(lambda (x,y,z),: x+y+z>6, a)\n[[4, 5, 6]]\n\nUsing the deconstruction syntax.\n", "How about this?\n\nfilter(lambda b : reduce(lambda x, y : x + y, b) >= N, a)\n\nThis isn't answering the question asked, I know, but it works for arbitrarily-long lists, and arbitrarily-long sublists, and supports any operation that works under reduce().\n", "Try something like this:\nfilter(lambda a: a[0] + a[1] + a[2] >= N, a)\n\n", "Use a function instead of a lambda, then myVar = a[0], etc.\n", "Ok, obviously you know that you can use sum. The goal of what you are trying to do seems a bit vague, but I think that the optional parameter syntax might help you out, or at least give you some inspiration. If you place a * before a parameter, it creates a tuple of all of itself and all of the remaining parameters. If you place a ** before it, you get a dictionary.\nTo see this:\ndef print_test(a,b,c,*d):\n print a\n print b\n print c\n print d\n\nprint_test(1,2,3,4,5,6)\n\nprints\n1\n2\n3\n(4, 5, 6)\n\nYou can use this syntax with lambda too.\nLike I said, I'm not sure exactly what you are trying to do, but it sounds like this might help. I don't think you can get local variable assignments in lambda without some hacking, but maybe you can use this to assign the values to variables somehow.\nEdit: Ah, I understand what you are looking for moreso now. I think you want:\nlambda (a, b, c): a+b+c > N\n\n" ]
[ 40, 11, 1, 1, 0, 0, 0 ]
[]
[]
[ "list", "list_comprehension", "python" ]
stackoverflow_0002655956_list_list_comprehension_python.txt
Q: Python Qlistview output dir i wish make little gui with pyqt4 that show the output of "dir c:\windows\" line by line I'm looking for QlistView but i don't understand how do it. Can anyone help me? A: import os for root, dirs, files in os.walk(r'C:\windows'): //add your QlistView add codes here A: Try QListWidget instead of QListView. QListWidget extends QListView and adds some very helpful methods like addItems. I'm going to assume you know how to create the GUI part of the application using Designer. If you have a QListWidget object qlistwidget, the code would be: values = os.listdir("c:\\windows") qlist = QtCore.QStringList(map(QtCore.QString, values)) qlistwidget.addItems(qlist)
Python Qlistview output dir
i wish make little gui with pyqt4 that show the output of "dir c:\windows\" line by line I'm looking for QlistView but i don't understand how do it. Can anyone help me?
[ "import os\nfor root, dirs, files in os.walk(r'C:\\windows'):\n //add your QlistView add codes here\n\n", "Try QListWidget instead of QListView. QListWidget extends QListView and adds some very helpful methods like addItems.\nI'm going to assume you know how to create the GUI part of the application using Designer.\nIf you have a QListWidget object qlistwidget, the code would be:\nvalues = os.listdir(\"c:\\\\windows\")\n\nqlist = QtCore.QStringList(map(QtCore.QString, values))\nqlistwidget.addItems(qlist)\n\n" ]
[ 1, 0 ]
[]
[]
[ "pyqt4", "python", "qlistview" ]
stackoverflow_0002653898_pyqt4_python_qlistview.txt
Q: Adding a font for use in ReportLab I'm trying to add a font to the python ReportLab so that I can use it for a function. The function is using canvas.Canvas to draw a bunch of text in a PDF, nothing complicated, but I need to add a fixed width font for layout issues. When I tried to register a font using what little info I could find, that seemed to work. But when I tried to call .addFont('fontname') from my Canvas object I keep getting "PDFDocument instance has no attribute 'addFont'" Is the function just not implemented? How do I get access to fonts other than the 10 or so default ones that are listed in .getAvailableFonts? Thanks. Some example code of what I'm trying to make happen: from reportlab.pdfgen import canvas c = canvas.Canvas('label.pdf') c.addFont('TestFont') #This throws the error listed above, regardless of what argument I use (whether it refers to a font or not). c.drawString(1,1,'test data here') c.showPage() c.save() To register the font, I tried from reportlab.lib.fonts import addMapping from reportlab.pdfbase import pdfmetrics pdfmetrics.registerFont(TTFont('TestFont', 'ghettomarquee.ttf')) addMapping('TestFont', 0, 0, 'TestFont') where 'ghettomarquee.ttf' was just a random font I had lying around. A: c.setFont('TestFont') c.drawString(1,1,'test data here') setFont to set the font name you're going to use, and drawString. ReportLab will automatically embed the font if you use it in the document, you don't have to manually add it after you've registered the font globally under a name.
Adding a font for use in ReportLab
I'm trying to add a font to the python ReportLab so that I can use it for a function. The function is using canvas.Canvas to draw a bunch of text in a PDF, nothing complicated, but I need to add a fixed width font for layout issues. When I tried to register a font using what little info I could find, that seemed to work. But when I tried to call .addFont('fontname') from my Canvas object I keep getting "PDFDocument instance has no attribute 'addFont'" Is the function just not implemented? How do I get access to fonts other than the 10 or so default ones that are listed in .getAvailableFonts? Thanks. Some example code of what I'm trying to make happen: from reportlab.pdfgen import canvas c = canvas.Canvas('label.pdf') c.addFont('TestFont') #This throws the error listed above, regardless of what argument I use (whether it refers to a font or not). c.drawString(1,1,'test data here') c.showPage() c.save() To register the font, I tried from reportlab.lib.fonts import addMapping from reportlab.pdfbase import pdfmetrics pdfmetrics.registerFont(TTFont('TestFont', 'ghettomarquee.ttf')) addMapping('TestFont', 0, 0, 'TestFont') where 'ghettomarquee.ttf' was just a random font I had lying around.
[ "c.setFont('TestFont')\nc.drawString(1,1,'test data here')\n\nsetFont to set the font name you're going to use, and drawString.\nReportLab will automatically embed the font if you use it in the document, you don't have to manually add it after you've registered the font globally under a name.\n" ]
[ 8 ]
[]
[]
[ "fonts", "python", "reportlab" ]
stackoverflow_0002656145_fonts_python_reportlab.txt
Q: Django, How authenticate user with first name and last name? i want to authenticate users using firstname and lastname This is the code i am using user = auth.authenticate(first_name=firstname,last_name=lastname,password=password) it keep coming up with NoneType: None i have checked the firstname and lastname plus password seen to be correct? what i am doing wrong? thanks A: The difficulty here is that normally you'd handle this by creating a custom authentication backend that implements authenticate and get_user. However, the function signature for authenticate is: def authenticate(self, username=None, password=None): Everywhere in Django that would be calling this will be passing only 2 parameters, username and password. This means that using any of the generic authentication forms and things like the admin interface will break if this is done any other way. The only work around I could see, and this is kind of sketchy, is if the username were to be typed as a single entry with a string "First Last" (delimited by a space) in place of the username. You could then separate it out and use that value... (this is all untested, but you get the idea) class FirstLastNameBackend(object): def authenticate(self, username=None, password=None): first, last = username.split(' ', 1) try: user = User.objects.get(first_name=first, last_name=last) if user: # Check if the password is correct # check if the user is active # etc., etc. return user except: pass return None def get_user(self, user_id): try: return User.objects.get(pk=user_id) except: return None The django doc provides a lot of helpful details on doing a custom backend: User auth with custom backend On a side note, something to be careful of is last names that have a space(s) in them, like "de la Cruz". If you specify 1 for maxsplit on the split function, you'll avoid this problem. A: Building a little from @T. Stone's idea. Why not have them register with their First and Last name and you just concatenate them together and use that as their username?. And everytime you have them login you setup your view to combine the two fields again and use that string. You won't be able to use some of the auto forms they can produce for you but that's not a big deal. I'd just combine the two strings, lowercase them and slap that as the username and do the same for every login instance. A: You can use any parameters in backend authentication function, i.e.: class FirstLastNameBackend(object): def authenticate(self, first_name=None, last_name=None, password=None): pass #your user auth code goes here In order to authenticate user you call user = auth.authenticate(first_name=firstname, last_name=lastname, password=password) One drawback, however, that you'll need to implement your own log in form and this authentication won't be supported in admin interface. A: I like the idea of not making users remember a username, but I think a better solution to that is to have their email address be their user name. Is it fair for you to assume in your specific application that no two users will have the same first and last name? If that's not a fair assumption, how will your system handle that?
Django, How authenticate user with first name and last name?
i want to authenticate users using firstname and lastname This is the code i am using user = auth.authenticate(first_name=firstname,last_name=lastname,password=password) it keep coming up with NoneType: None i have checked the firstname and lastname plus password seen to be correct? what i am doing wrong? thanks
[ "The difficulty here is that normally you'd handle this by creating a custom authentication backend that implements authenticate and get_user. However, the function signature for authenticate is:\ndef authenticate(self, username=None, password=None):\n\nEverywhere in Django that would be calling this will be passing only 2 parameters, username and password. This means that using any of the generic authentication forms and things like the admin interface will break if this is done any other way.\nThe only work around I could see, and this is kind of sketchy, is if the username were to be typed as a single entry with a string \"First Last\" (delimited by a space) in place of the username. You could then separate it out and use that value...\n(this is all untested, but you get the idea)\nclass FirstLastNameBackend(object):\n def authenticate(self, username=None, password=None):\n first, last = username.split(' ', 1)\n try:\n user = User.objects.get(first_name=first, last_name=last)\n if user:\n # Check if the password is correct\n # check if the user is active\n # etc., etc.\n return user\n except:\n pass\n return None\n\n def get_user(self, user_id):\n try:\n return User.objects.get(pk=user_id)\n except:\n return None\n\nThe django doc provides a lot of helpful details on doing a custom backend: User auth with custom backend\nOn a side note, something to be careful of is last names that have a space(s) in them, like \"de la Cruz\". If you specify 1 for maxsplit on the split function, you'll avoid this problem.\n", "Building a little from @T. Stone's idea. Why not have them register with their First and Last name and you just concatenate them together and use that as their username?. And everytime you have them login you setup your view to combine the two fields again and use that string.\nYou won't be able to use some of the auto forms they can produce for you but that's not a big deal. I'd just combine the two strings, lowercase them and slap that as the username and do the same for every login instance.\n", "You can use any parameters in backend authentication function, i.e.:\nclass FirstLastNameBackend(object):\n def authenticate(self, first_name=None, last_name=None, password=None):\n pass #your user auth code goes here\n\nIn order to authenticate user you call \nuser = auth.authenticate(first_name=firstname,\n last_name=lastname,\n password=password)\n\nOne drawback, however, that you'll need to implement your own log in form and this authentication won't be supported in admin interface.\n", "I like the idea of not making users remember a username, but I think a better solution to that is to have their email address be their user name. Is it fair for you to assume in your specific application that no two users will have the same first and last name? If that's not a fair assumption, how will your system handle that?\n" ]
[ 3, 2, 2, 1 ]
[]
[]
[ "django", "django_admin", "django_models", "python" ]
stackoverflow_0002650106_django_django_admin_django_models_python.txt
Q: Cleaner way to get user name in pylons with repoze.name in mako template, i use this ${request.environ['repoze.who.identity']['user']} and the render in controller: render('file.html') can i write this better without passing in parameter everytime? A: Well, you can auto add the varible in the base controller in /lib/base.py. This will add it to every controller in your pylons application automatically. I'm using repoze.what and what I do is in base.py I put: # if there's no user set, just setup a blank instance c.current_user = auth.get_user(User()) And that's just a convienence function I wrote into an auth lib. User() is a blank instance of the User model so that the template has something and won't throw a invalid key error. def get_user(default): """Return the user object from the `repoze.who` Metadata Plugin :param default: default item to send back if user not logged in Since we might not be logged in and template choke on trying to output None/empty data we can pass in a blank User object to get back as a default and the templates should work ok with default empty values on that """ if 'repoze.who.identity' in request.environ: return request.environ['repoze.who.identity']['user'] else: return default
Cleaner way to get user name in pylons with repoze.name
in mako template, i use this ${request.environ['repoze.who.identity']['user']} and the render in controller: render('file.html') can i write this better without passing in parameter everytime?
[ "Well, you can auto add the varible in the base controller in /lib/base.py. This will add it to every controller in your pylons application automatically. I'm using repoze.what and what I do is in base.py I put:\n# if there's no user set, just setup a blank instance\nc.current_user = auth.get_user(User()) \n\nAnd that's just a convienence function I wrote into an auth lib. User() is a blank instance of the User model so that the template has something and won't throw a invalid key error. \ndef get_user(default):\n \"\"\"Return the user object from the `repoze.who` Metadata Plugin\n\n :param default: default item to send back if user not logged in\n\n Since we might not be logged in and template choke on trying to output\n None/empty data we can pass in a blank User object to get back as a default\n and the templates should work ok with default empty values on that\n\n \"\"\"\n if 'repoze.who.identity' in request.environ:\n return request.environ['repoze.who.identity']['user']\n else:\n return default\n\n" ]
[ 2 ]
[]
[]
[ "pylons", "python" ]
stackoverflow_0002656066_pylons_python.txt
Q: Handle incorrect user/password repoze.who gracefully in Python/Pylons im using FriendlyFormPlugin, but would like to retrieve the username that was input as part of the request.params, but its no longer there when i check. this way i can set the default for username if the password is incorrect. thanks A: I think what you need to do is to setup a post login handler action when you setup the middleware. In that action you can then check params, set a session var, etc. I had to hook into here in order to create a message to the user that their login had failed. I check for a 'login_failed' param on the login form. def post_login(self): """ Handle logic post a user's login I want to create a login_handler that's redirected to after login. This would check - if user was logged in, if not then send back to login - if user is admin, go to job list - adjust the max age on the existing cookie to XX remember me timeframe """ if auth.check(not_anonymous()): log.debug('checked auth') else: # login failed, redirect back to login log.debug('failed auth') redirect_to(controller="root", action="login", login_failed=True) # expire this cookie into the future ck = request.cookies['authtkt'] response.set_cookie('authtkt', ck, max_age=60*60*24*7, path='/' ) redirect_to(controller="job", action="list") In response for more details, too big to add as another comment: So I've got a few things you can look at. First, this is my docs I'm writing as a repoze 'summary' to help explain to other devs how this stuff works/terminology used: http://72.14.191.199/docs/morpylons/auth_overview.html I started out using the repoze sql quickstart plugin: http://code.gustavonarea.net/repoze.what-quickstart/ I then ripped out their setup_sql_auth and modified it for our own needs since we do both SQL and LDAP auth in our apps. Go make sure to look at the plugin source for setup_sql_auth and go through it until you really understand what it's doing. and since you asked on middleware config... app = setup_morpace_auth(app, User, Group, Permission, meta.Session, post_login_url='/root/post_login', post_logout_url='/login', log_level='debug', log_file='stdout' )
Handle incorrect user/password repoze.who gracefully in Python/Pylons
im using FriendlyFormPlugin, but would like to retrieve the username that was input as part of the request.params, but its no longer there when i check. this way i can set the default for username if the password is incorrect. thanks
[ "I think what you need to do is to setup a post login handler action when you setup the middleware. In that action you can then check params, set a session var, etc. I had to hook into here in order to create a message to the user that their login had failed. I check for a 'login_failed' param on the login form. \n def post_login(self):\n \"\"\" Handle logic post a user's login\n\n I want to create a login_handler that's redirected to after login. This would\n check \n\n - if user was logged in, if not then send back to login\n - if user is admin, go to job list\n - adjust the max age on the existing cookie to XX remember me timeframe\n\n \"\"\"\n if auth.check(not_anonymous()):\n log.debug('checked auth')\n else:\n # login failed, redirect back to login\n log.debug('failed auth')\n redirect_to(controller=\"root\", action=\"login\", login_failed=True)\n\n # expire this cookie into the future\n ck = request.cookies['authtkt']\n response.set_cookie('authtkt', ck,\n max_age=60*60*24*7,\n path='/'\n )\n\n redirect_to(controller=\"job\", action=\"list\")\n\nIn response for more details, too big to add as another comment:\nSo I've got a few things you can look at. First, this is my docs I'm writing as a repoze 'summary' to help explain to other devs how this stuff works/terminology used:\nhttp://72.14.191.199/docs/morpylons/auth_overview.html\nI started out using the repoze sql quickstart plugin:\nhttp://code.gustavonarea.net/repoze.what-quickstart/\nI then ripped out their setup_sql_auth and modified it for our own needs since we do both SQL and LDAP auth in our apps. Go make sure to look at the plugin source for setup_sql_auth and go through it until you really understand what it's doing. \nand since you asked on middleware config...\n app = setup_morpace_auth(app, User, Group, Permission, meta.Session,\n post_login_url='/root/post_login',\n post_logout_url='/login',\n log_level='debug',\n log_file='stdout'\n )\n\n" ]
[ 3 ]
[]
[]
[ "pylons", "python", "repoze.who" ]
stackoverflow_0002656374_pylons_python_repoze.who.txt
Q: Preserve time stamp when shrinking an image My digital camera takes pictures with a very high resolution, and I have a PIL script to shrink them to 800x600 (or 600x800). However, it would be nice for the resultant file to retain the original timestamp. I noticed in the docs that I can use a File object instead of a name in PIL's image save method, but I don't know if that will help or not. My code is basically name, ext = os.path.splitext(filename) # open an image file (.bmp,.jpg,.png,.gif) you have in the working folder image = Image.open(filename) width = 800 height = 600 w, h = image.size if h > w: width = 600 height = 800 name = name + ".jpg" shunken = image.resize((width, height), Image.ANTIALIAS) shunken.save(name) Thank you for any help you can give! A: Use shutil.copystat It appears that PIL does not save EXIF metadata. To copy the EXIF data using Python you could use pyexiv2. This is how Phatch, a batch photo resizer program written in Python, deals with EXIF data, for example. I'm not sure if you're using Ubuntu, but if so, installation is easy since pyexiv2 is provided by python-pyexiv2 package. Edit: If you don't mind losing the EXIF metadata, and would simply like to use the EXIF datetime stamp as the resized image's modification date, then you can do it without the pyexiv2 package, thus saving you an extra dependency. Here's how: import os import time import Image import ExifTags # This is provided by PIL img=Image.open(filename,'r') PIL can read EXIF data, but cannot yet write EXIF data. We can access the data using the _getexif() method: d = dict((ExifTags.TAGS[k], v) for k, v in img._getexif().items()) print(d['DateTimeOriginal']) Parsing the timestamp may depend on what format the camera uses. This works for my camera; YMMV. The dateutils package allows you to parse a wide variety of timestamps without you having to pre-specify the format, but that's another story. timestamp=time.strptime(d['DateTimeOriginal'],"%Y:%m:%d %H:%M:%S") Here's an alternative way to swap the width and height: w, h = img.size width,height = 800,600 if h > w: width,height = height,width Resizing the image, and using os.utime to fix the atime and mtime: filename = filename + "-800x600.jpg" shunken = img.resize((width, height), Image.ANTIALIAS) shunken.save(filename) st = os.stat(filename) os.utime(filename,(st.st_atime,time.mktime(timestamp)))
Preserve time stamp when shrinking an image
My digital camera takes pictures with a very high resolution, and I have a PIL script to shrink them to 800x600 (or 600x800). However, it would be nice for the resultant file to retain the original timestamp. I noticed in the docs that I can use a File object instead of a name in PIL's image save method, but I don't know if that will help or not. My code is basically name, ext = os.path.splitext(filename) # open an image file (.bmp,.jpg,.png,.gif) you have in the working folder image = Image.open(filename) width = 800 height = 600 w, h = image.size if h > w: width = 600 height = 800 name = name + ".jpg" shunken = image.resize((width, height), Image.ANTIALIAS) shunken.save(name) Thank you for any help you can give!
[ "Use shutil.copystat\nIt appears that PIL does not save EXIF metadata.\nTo copy the EXIF data using Python you could use\npyexiv2. This is how Phatch, a batch photo resizer program written in Python, deals with EXIF data, for example.\nI'm not sure if you're using Ubuntu, but if so, installation is easy since pyexiv2 is provided by python-pyexiv2 package.\nEdit: If you don't mind losing the EXIF metadata, and would simply like to use the EXIF datetime stamp as the resized image's modification date, then you can do it without the pyexiv2 package, thus saving you an extra dependency. Here's how:\nimport os\nimport time\nimport Image\nimport ExifTags # This is provided by PIL\nimg=Image.open(filename,'r')\n\nPIL can read EXIF data, but cannot yet write EXIF data. We can access the data using the _getexif() method:\nd = dict((ExifTags.TAGS[k], v) for k, v in img._getexif().items())\nprint(d['DateTimeOriginal'])\n\nParsing the timestamp may depend on what format the camera uses. This works for my camera; YMMV. The dateutils package allows you to parse a wide variety of timestamps without you having to pre-specify the format, but that's another story.\ntimestamp=time.strptime(d['DateTimeOriginal'],\"%Y:%m:%d %H:%M:%S\")\n\nHere's an alternative way to swap the width and height:\nw, h = img.size\nwidth,height = 800,600\nif h > w: width,height = height,width\n\nResizing the image, and using os.utime to fix the atime and mtime:\nfilename = filename + \"-800x600.jpg\"\nshunken = img.resize((width, height), Image.ANTIALIAS)\nshunken.save(filename)\nst = os.stat(filename)\nos.utime(filename,(st.st_atime,time.mktime(timestamp)))\n\n" ]
[ 5 ]
[]
[]
[ "python", "python_imaging_library" ]
stackoverflow_0002656900_python_python_imaging_library.txt
Q: python os.execvp() trying to display mysql tables gives 1049 error - Unknown database error I have a question related to MySQL and Python. This command works on the shell, but not when I use os.execvp. $./mysql -D test -e "show tables" +----------------+ | Tables_in_test | +----------------+ | sample | +----------------+ The corresponding piece of code in python would be def execute(): args = [] args.extend(sys.argv[1:]) args.extend([MYSQL, '-D test -e "show tables"']) print args os.execvp(args[0], args) child_pid = os.fork() if child_pid == 0: os.execvp(args[0], args) else: os.wait() The output of this is: [./mysql', '-D test -e "show tables"'] ERROR 1049 (42000): Unknown database ' test -e "show tables"' I am not sure if this is a problem with the Python syntax or not. Also, the same command works with an os.system call. os.system(MYSQL + ' -D test -e "show tables"') Please let me know how to get this working. A: Each of your separate parameters needs to be a separate element in the list of parameters. args.extend([MYSQL, '-D test', '-e "show tables"']) A: Try: args.extend([MYSQL, '-D', 'test', '-e', 'show tables']) You might also be interested in the subprocess module if you weren't aware of it: >>> import subprocess as subp >>> print subp.Popen(["mysql", '-D', 'mysql', '-e', 'show tables'], stdout=subp.PIPE).communicate()[0] Tables_in_mysql columns_priv db func help_category help_keyword help_relation ... Or just subp.call([MYSQL, ...]) and you don't have to fork+exec yourself, exit status is the return value IIRC.
python os.execvp() trying to display mysql tables gives 1049 error - Unknown database error
I have a question related to MySQL and Python. This command works on the shell, but not when I use os.execvp. $./mysql -D test -e "show tables" +----------------+ | Tables_in_test | +----------------+ | sample | +----------------+ The corresponding piece of code in python would be def execute(): args = [] args.extend(sys.argv[1:]) args.extend([MYSQL, '-D test -e "show tables"']) print args os.execvp(args[0], args) child_pid = os.fork() if child_pid == 0: os.execvp(args[0], args) else: os.wait() The output of this is: [./mysql', '-D test -e "show tables"'] ERROR 1049 (42000): Unknown database ' test -e "show tables"' I am not sure if this is a problem with the Python syntax or not. Also, the same command works with an os.system call. os.system(MYSQL + ' -D test -e "show tables"') Please let me know how to get this working.
[ "Each of your separate parameters needs to be a separate element in the list of parameters.\nargs.extend([MYSQL, '-D test', '-e \"show tables\"'])\n\n", "Try:\nargs.extend([MYSQL, '-D', 'test', '-e', 'show tables'])\n\nYou might also be interested in the subprocess module if you weren't aware of it:\n>>> import subprocess as subp\n>>> print subp.Popen([\"mysql\", '-D', 'mysql', '-e', 'show tables'], stdout=subp.PIPE).communicate()[0]\nTables_in_mysql\ncolumns_priv\ndb\nfunc\nhelp_category\nhelp_keyword\nhelp_relation\n...\n\nOr just subp.call([MYSQL, ...]) and you don't have to fork+exec yourself, exit status is the return value IIRC.\n" ]
[ 0, 0 ]
[]
[]
[ "mysql", "mysql_error_1049", "python" ]
stackoverflow_0002654148_mysql_mysql_error_1049_python.txt
Q: Attribute References in Python I do Java programming and recently started learning Python via the official documentation. I see that we can dynamically add data attributes to an instance object unlike in Java: class House: pass my_house = House() my_house.number = 40 my_house.rooms = 8 my_house.garden = 1 My question is, in what situations is this feature used? What are the advantages and disadvantages compared to the way it is done in Java? A: It can also be used when dynamically creating classes; see for instance this tutorial: http://onlamp.com/pub/a/python/2003/04/17/metaclasses.html?page=1 or this one on Mix-ins, a programming technique that uses this capability to provide better encapsulation and modularity to object oriented code: http://www.linuxjournal.com/article/4540 The first tutorial uses setattr(classname, "propertyname", value) instead of the classname.property = value syntax, but they are the same. A: It's not often done from outside of the class unless the object is being used as a bucket of sorts. It's done an awful lot inside __init__() of course, to provide values to attributes that will be used elsewhere. Oh, and speaking of Java...
Attribute References in Python
I do Java programming and recently started learning Python via the official documentation. I see that we can dynamically add data attributes to an instance object unlike in Java: class House: pass my_house = House() my_house.number = 40 my_house.rooms = 8 my_house.garden = 1 My question is, in what situations is this feature used? What are the advantages and disadvantages compared to the way it is done in Java?
[ "It can also be used when dynamically creating classes; see for instance this tutorial:\nhttp://onlamp.com/pub/a/python/2003/04/17/metaclasses.html?page=1\nor this one on Mix-ins, a programming technique that uses this capability to provide better encapsulation and modularity to object oriented code: \nhttp://www.linuxjournal.com/article/4540\nThe first tutorial uses setattr(classname, \"propertyname\", value) instead of the classname.property = value syntax, but they are the same.\n", "It's not often done from outside of the class unless the object is being used as a bucket of sorts. It's done an awful lot inside __init__() of course, to provide values to attributes that will be used elsewhere.\nOh, and speaking of Java...\n" ]
[ 2, 1 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0002656922_oop_python.txt
Q: Python Expand Tabs Length Calculation I'm confused by how the length of a string is calculated when expandtabs is used. I thought expandtabs replaces tabs with the appropriate number of spaces (with the default number of spaces per tab being 8). However, when I ran the commands using strings of varying lengths and varying numbers of tabs, the length calculation was different than I thought it would be (i.e., each tab didn't always result in the string length being increased by 8 for each instance of "/t"). Below is a detailed script output with comments explaining what I thought should be the result of the command executed above. Would someone please explain the how the length is calculated when expand tabs is used? IDLE 2.6.5 >>> s = '\t' >>> print len(s) 1 >>> #the length of the string without expandtabs was one (1 tab counted as a single space), as expected. >>> print len(s.expandtabs()) 8 >>> #the length of the string with expandtabs was eight (1 tab counted as eight spaces). >>> s = '\t\t' >>> print len(s) 2 >>> #the length of the string without expandtabs was 2 (2 tabs, each counted as a single space). >>> print len(s.expandtabs()) 16 >>> #the length of the string with expandtabs was 16 (2 tabs counted as 8 spaces each). >>> s = 'abc\tabc' >>> print len(s) 7 >>> #the length of the string without expandtabs was seven (6 characters and 1 tab counted as a single space). >>> print len(s.expandtabs()) 11 >>> #the length of the string with expandtabs was NOT 14 (6 characters and one 8 space tabs). >>> s = 'abc\tabc\tabc' >>> print len(s) 11 >>> #the length of the string without expandtabs was 11 (9 characters and 2 tabs counted as a single space). >>> print len(s.expandtabs()) 19 >>> #the length of the string with expandtabs was NOT 25 (9 characters and two 8 space tabs). >>> A: Like when you are entering tabs in a text-editor, the tab character increases the length to the next multiple of 8. So: '\t' by itself is 8, obviously. '\t\t' is 16. 'abc\tabc' starts at 3 characters, then a tab pushes it up to 8, and then the last 'abc' pushes it from 8 to 11... 'abc\tabc\tabc' likewise starts at 3, tab bumps it to 8, another 'abc' goes to 11, then another tab pushes it to 16, and the final 'abc' brings the length to 19. A: The tab increments the column pointer to the next multiple of 8: >>> 'abc\tabc'.expandtabs().replace(' ', '*') 'abc*****abc'
Python Expand Tabs Length Calculation
I'm confused by how the length of a string is calculated when expandtabs is used. I thought expandtabs replaces tabs with the appropriate number of spaces (with the default number of spaces per tab being 8). However, when I ran the commands using strings of varying lengths and varying numbers of tabs, the length calculation was different than I thought it would be (i.e., each tab didn't always result in the string length being increased by 8 for each instance of "/t"). Below is a detailed script output with comments explaining what I thought should be the result of the command executed above. Would someone please explain the how the length is calculated when expand tabs is used? IDLE 2.6.5 >>> s = '\t' >>> print len(s) 1 >>> #the length of the string without expandtabs was one (1 tab counted as a single space), as expected. >>> print len(s.expandtabs()) 8 >>> #the length of the string with expandtabs was eight (1 tab counted as eight spaces). >>> s = '\t\t' >>> print len(s) 2 >>> #the length of the string without expandtabs was 2 (2 tabs, each counted as a single space). >>> print len(s.expandtabs()) 16 >>> #the length of the string with expandtabs was 16 (2 tabs counted as 8 spaces each). >>> s = 'abc\tabc' >>> print len(s) 7 >>> #the length of the string without expandtabs was seven (6 characters and 1 tab counted as a single space). >>> print len(s.expandtabs()) 11 >>> #the length of the string with expandtabs was NOT 14 (6 characters and one 8 space tabs). >>> s = 'abc\tabc\tabc' >>> print len(s) 11 >>> #the length of the string without expandtabs was 11 (9 characters and 2 tabs counted as a single space). >>> print len(s.expandtabs()) 19 >>> #the length of the string with expandtabs was NOT 25 (9 characters and two 8 space tabs). >>>
[ "Like when you are entering tabs in a text-editor, the tab character increases the length to the next multiple of 8.\nSo:\n\n'\\t' by itself is 8, obviously.\n'\\t\\t' is 16.\n'abc\\tabc' starts at 3 characters, then a tab pushes it up to 8, and then the last 'abc' pushes it from 8 to 11...\n'abc\\tabc\\tabc' likewise starts at 3, tab bumps it to 8, another 'abc' goes to 11, then another tab pushes it to 16, and the final 'abc' brings the length to 19.\n\n", "The tab increments the column pointer to the next multiple of 8:\n>>> 'abc\\tabc'.expandtabs().replace(' ', '*')\n'abc*****abc'\n\n" ]
[ 9, 6 ]
[]
[]
[ "python", "tabs" ]
stackoverflow_0002656997_python_tabs.txt
Q: How do I automatically rebuild the Sphinx index under django-sphinx? I just setup django-sphinx, and it is working beautifully. I am now able to search my model and get amazing results. The one problem is that I have to build the index by hand using the indexer command. That means every time I add new content, I have to manually hit the command line to rebuild the search index. That is just not acceptable. I could make a cron job that automatically runs the indexer command every so often, but that's far from optimal. New data won't be indexed until the cron runs again. In addition, the indexer will run unnecessarily most times as my site doesn't have data being added very often. How do I set it up so that the Sphinx index will automatically rebuild itself whenever data is added to or modified in a searchable django model? A: There are basically two primary strategies for building search indexes: Indexer internal to a database server, which indexes on the fly as records are inserted or deleted. Indexer external to the database (which may or may not be a RDMS which is why I leave off the word server), which indexes periodically. The first strategy has the obvious advantage of being closer to real-time but possibly a huge disadvantage in performance. Most database servers with internal indexers have performance problems (or else missing features), see for example Jeff Atwood discussing performance problems in SQL Server 2008 in his blog post about adding a second server for stackoverflow. The second strategy isn't as real-time but generally has best performance, Unfortunately this also means, because it isn't built-in, it has to be invoked externally somehow. Obviously you have no choice with Sphinx, it being an external indexer. You must invoke the sphinx indexer from cron or some other scheduling mechanism. To speed up indexing just run it often from cron. If that causes performance issues then you need to implement a live-update strategy which involves indexing new records very frequently into a delta index and then periodically merging the delta index into the primary index. This would be done external to Django so it doesn't affect anything in django-sphinx. A: The above sounds right to me, though I'll mention that you could call the indexer from your save function for the object. It'd probably get called a LOT, but it could work. Just call it as you would any external command.
How do I automatically rebuild the Sphinx index under django-sphinx?
I just setup django-sphinx, and it is working beautifully. I am now able to search my model and get amazing results. The one problem is that I have to build the index by hand using the indexer command. That means every time I add new content, I have to manually hit the command line to rebuild the search index. That is just not acceptable. I could make a cron job that automatically runs the indexer command every so often, but that's far from optimal. New data won't be indexed until the cron runs again. In addition, the indexer will run unnecessarily most times as my site doesn't have data being added very often. How do I set it up so that the Sphinx index will automatically rebuild itself whenever data is added to or modified in a searchable django model?
[ "There are basically two primary strategies for building search indexes:\n\nIndexer internal to a database server, which indexes on the fly as records are inserted or deleted.\nIndexer external to the database (which may or may not be a RDMS which is why I leave off the word server), which indexes periodically.\n\nThe first strategy has the obvious advantage of being closer to real-time but possibly a huge disadvantage in performance. Most database servers with internal indexers have performance problems (or else missing features), see for example Jeff Atwood discussing performance problems in SQL Server 2008 in his blog post about adding a second server for stackoverflow.\nThe second strategy isn't as real-time but generally has best performance, Unfortunately this also means, because it isn't built-in, it has to be invoked externally somehow.\nObviously you have no choice with Sphinx, it being an external indexer. You must invoke the sphinx indexer from cron or some other scheduling mechanism.\nTo speed up indexing just run it often from cron. If that causes performance issues then you need to implement a live-update strategy which involves indexing new records very frequently into a delta index and then periodically merging the delta index into the primary index. This would be done external to Django so it doesn't affect anything in django-sphinx.\n", "The above sounds right to me, though I'll mention that you could call the indexer from your save function for the object.\nIt'd probably get called a LOT, but it could work. Just call it as you would any external command.\n" ]
[ 5, 0 ]
[]
[]
[ "django", "django_sphinx", "python", "search", "sphinx" ]
stackoverflow_0001653071_django_django_sphinx_python_search_sphinx.txt
Q: What is the advantage of using Python Virtualbox API? what is the advantage of using a python virtualbox API instead of using XPCOM? A: The advantage is that pyvb is lot easier to work with. On the contrary the documentation for the python API of XPCOM doesn't exist, and the API is not pythonic at all. You can't do introspection to find methods/attributes of an object, etc. So you have to check the C++ source to find how it works or some python scripts already written (like vboxshell.py and VBoxWebSrv.py). On the other hand pyvb is really just python wrapper that call VirtuaBoxManager on the command line. I don't know if it's a real disadvantage or not? A: I would generally recommend against either one. If you need to use virtualization programmatically, take a look at libvirt, which gives you cross platform and cross hypervisor support; which lets you do kvm/xen/vz/vmware later on. That said, the SOAP api is using two extra abstraction layers (the client and server side of the HTTP transaction), which is pretty clearly then just calling the XPCOM interface. If you need local host only support, use XPCOM. The extra indirection of libvirt/SOAP doesn't help you. If you need to access virtualbox on a various hosts across multiple client machines, use SOAP or libvirt If you want cross platform support, or to run your code on Linux, use libvirt. A: From sun's site on VirtualBox python APIs: SOAP allows to control remote VMs over HTTP, while XPCOM is much more high-performing and exposes certain functionality not available with SOAP. They use very different technologies (SOAP is procedural, while XPCOM is OOP), but as it is ultimately API to the same functionality of the VirtualBox, we kept in bindings original semantics, so other that connection establishment, code could be written in such a way that people may not care what communication channel with VirtualBox instance is used. From that article, I'm having trouble seeing the difference between "python virtualbox API" and "XPCOM". Could you provide a link to the API you're thinking of?
What is the advantage of using Python Virtualbox API?
what is the advantage of using a python virtualbox API instead of using XPCOM?
[ "The advantage is that pyvb is lot easier to work with.\nOn the contrary the documentation for the python API of XPCOM doesn't exist, and the API is not pythonic at all. You can't do introspection to find methods/attributes of an object, etc. So you have to check the C++ source to find how it works or some python scripts already written (like vboxshell.py and VBoxWebSrv.py).\nOn the other hand pyvb is really just python wrapper that call VirtuaBoxManager on the command line. I don't know if it's a real disadvantage or not?\n", "I would generally recommend against either one. If you need to use virtualization programmatically, take a look at libvirt, which gives you cross platform and cross hypervisor support; which lets you do kvm/xen/vz/vmware later on.\nThat said, the SOAP api is using two extra abstraction layers (the client and server side of the HTTP transaction), which is pretty clearly then just calling the XPCOM interface.\nIf you need local host only support, use XPCOM. The extra indirection of libvirt/SOAP doesn't help you.\nIf you need to access virtualbox on a various hosts across multiple client machines, use SOAP or libvirt\nIf you want cross platform support, or to run your code on Linux, use libvirt.\n", "From sun's site on VirtualBox python APIs:\n\nSOAP allows to control remote VMs over\nHTTP, while XPCOM is much more\nhigh-performing and exposes certain\nfunctionality not available with SOAP.\nThey use very different technologies\n(SOAP is procedural, while XPCOM is\nOOP), but as it is ultimately API to\nthe same functionality of the\nVirtualBox, we kept in bindings\noriginal semantics, so other that\nconnection establishment, code could\nbe written in such a way that people\nmay not care what communication\nchannel with VirtualBox instance is\nused.\n\nFrom that article, I'm having trouble seeing the difference between \"python virtualbox API\" and \"XPCOM\". Could you provide a link to the API you're thinking of?\n" ]
[ 8, 5, 1 ]
[]
[]
[ "python", "virtualbox", "xpcom" ]
stackoverflow_0002652146_python_virtualbox_xpcom.txt
Q: Indexing CSV file contents in Python I have a very large CSV file contaning only two fields (id,url). I want to do some indexing on the url field with python, I know that there are some tools like Whoosh or Pylucene. but I can't get the examples to work. can someone help me with this? A: PyLucene is very easy to work with, but as you haven't posted your example i am not sure what problem you are facing. Alternatively when you have only key:value type of data, may be better than Pylucene would be DB like Berkeley DB(python bindings pybsddb). It will work like python dictionary and should be more or as fast as lucene, you can try that. A: file.csv contents: a,b d,f g,h Python script that loads it all into one giant dictionary: #Python 3.1 giant_dict = {id.strip(): url.strip() for id, url in (line.split(',') for line in open('file.csv', 'r'))} print(giant_dict) {'a': 'b', 'd': 'f', 'g': 'h'}
Indexing CSV file contents in Python
I have a very large CSV file contaning only two fields (id,url). I want to do some indexing on the url field with python, I know that there are some tools like Whoosh or Pylucene. but I can't get the examples to work. can someone help me with this?
[ "PyLucene is very easy to work with, but as you haven't posted your example i am not sure what problem you are facing.\nAlternatively when you have only key:value type of data, may be better than Pylucene would be DB like Berkeley DB(python bindings pybsddb). It will work like python dictionary and should be more or as fast as lucene, you can try that.\n", "file.csv contents:\na,b\nd,f\ng,h\n\nPython script that loads it all into one giant dictionary:\n#Python 3.1\ngiant_dict = {id.strip(): url.strip() for id, url in (line.split(',') for line in open('file.csv', 'r'))}\n\nprint(giant_dict)\n{'a': 'b', 'd': 'f', 'g': 'h'}\n\n" ]
[ 1, 0 ]
[]
[]
[ "full_text_indexing", "indexing", "python", "whoosh" ]
stackoverflow_0002656607_full_text_indexing_indexing_python_whoosh.txt
Q: How to fix this python program? import math def p(n): return 393000*((288200/393000)^n * math.exp(-(288200/393000)))/math.factorial(n) print p(3) When I run it, I get the following error message: Traceback (most recent call last): File "poisson.py", line 6, in <module> print p(3) File "poisson.py", line 4, in p return 393000*((288200/393000)^n * math.exp(-(288200/393000)))/math.factoria l(n) TypeError: unsupported operand type(s) for ^: 'int' and 'float' A: Replace ^ with ** in (288200/393000)^n Bear in mind that 288200/393000 Returns 0 Maybe you should try using decimal numbers: import math def p(n): a = 393000.0 # <-- notice the .0 b = 288200.0 c = b / a return a * ( c**n * math.exp(-c) )/ math.factorial(n) print p(3) Returns: 12406.890756 A: Is the ^ supposed to mean exponentiation? If so, use ** instead. A: You can also use math.pow: >>> import math >>> math.pow(3,2) 9.0 Though actually it looks like maybe this isn't the best idea, since math.pow is more for C extension compatibility, and doesn't handle all the cases that ** does: >>> 2**3000 1230231922161117176931558813276752514640713895736833715766118029160058800614672948775360067838593459582429649254051804908512884180898236823585082482065348331234959350355845017413023320111360666922624728239756880416434478315693675013413090757208690376793296658810662941824493488451726505303712916005346747908623702673480919353936813105736620402352744776903840477883651100322409301983488363802930540482487909763484098253940728685132044408863734754271212592471778643949486688511721051561970432780747454823776808464180697103083861812184348565522740195796682622205511845512080552010310050255801589349645928001133745474220715013683413907542779063759833876101354235184245096670042160720629411581502371248008430447184842098610320580417992206662247328722122088513643683907670360209162653670641130936997002170500675501374723998766005827579300723253474890612250135171889174899079911291512399773872178519018229989376L vs. >>> import math >>> math.pow(2, 3000) Traceback (most recent call last): File "<stdin>", line 1, in <module> OverflowError: math range error see http://mail.python.org/pipermail/python-list/2003-November/236169.html for a little more detail EDIT: In response to your question as to why it returns 0.0, that's because you are raising 0 to a power - you are using / for division, which by default is integer division and will truncate. use from __future__ import division to get floating point divison.
How to fix this python program?
import math def p(n): return 393000*((288200/393000)^n * math.exp(-(288200/393000)))/math.factorial(n) print p(3) When I run it, I get the following error message: Traceback (most recent call last): File "poisson.py", line 6, in <module> print p(3) File "poisson.py", line 4, in p return 393000*((288200/393000)^n * math.exp(-(288200/393000)))/math.factoria l(n) TypeError: unsupported operand type(s) for ^: 'int' and 'float'
[ "Replace ^ with ** in \n(288200/393000)^n\n\nBear in mind that \n288200/393000\n\nReturns 0 \nMaybe you should try using decimal numbers:\nimport math\n\ndef p(n):\n a = 393000.0 # <-- notice the .0 \n b = 288200.0\n c = b / a\n return a * ( c**n * math.exp(-c) )/ math.factorial(n)\n\nprint p(3)\n\nReturns:\n12406.890756\n\n", "Is the ^ supposed to mean exponentiation? If so, use ** instead.\n", "You can also use math.pow:\n>>> import math\n>>> math.pow(3,2)\n9.0\n\nThough actually it looks like maybe this isn't the best idea, since math.pow is more for C extension compatibility, and doesn't handle all the cases that ** does:\n>>> 2**3000\n1230231922161117176931558813276752514640713895736833715766118029160058800614672948775360067838593459582429649254051804908512884180898236823585082482065348331234959350355845017413023320111360666922624728239756880416434478315693675013413090757208690376793296658810662941824493488451726505303712916005346747908623702673480919353936813105736620402352744776903840477883651100322409301983488363802930540482487909763484098253940728685132044408863734754271212592471778643949486688511721051561970432780747454823776808464180697103083861812184348565522740195796682622205511845512080552010310050255801589349645928001133745474220715013683413907542779063759833876101354235184245096670042160720629411581502371248008430447184842098610320580417992206662247328722122088513643683907670360209162653670641130936997002170500675501374723998766005827579300723253474890612250135171889174899079911291512399773872178519018229989376L\n\nvs.\n>>> import math\n>>> math.pow(2, 3000)\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nOverflowError: math range error\n\nsee http://mail.python.org/pipermail/python-list/2003-November/236169.html for a little more detail\nEDIT: In response to your question as to why it returns 0.0, that's because you are raising 0 to a power - you are using / for division, which by default is integer division and will truncate. use from __future__ import division to get floating point divison.\n" ]
[ 5, 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0002657319_python.txt
Q: jar to python module I am using an API which provides a Java version but not a Python version. I can switch to Java as right now I am only prototyping. but is there a quick way to convert the functionality of API packaged in a jar to a python module? A: Did you look into Jython?
jar to python module
I am using an API which provides a Java version but not a Python version. I can switch to Java as right now I am only prototyping. but is there a quick way to convert the functionality of API packaged in a jar to a python module?
[ "Did you look into Jython?\n" ]
[ 3 ]
[]
[]
[ "jar", "java", "port", "python" ]
stackoverflow_0002657882_jar_java_port_python.txt
Q: Django - how to write users and profiles handling in best way? I am writing simple site that requires users and profiles to be handled. The first initial thought is to use django's build in user handling, but then the user model is too narrow and does not contain fields that I need. The documentation mentions user profiles, but user profiles section has been removed from djangobook covering django 1.0 (ideally, the solution should work with django 1.2), and the Internet is full of different solutions, not making the choice easier (like user model inheritance, user profiles and django signals, and so on). I would like to know, how to write this in good, modern, fast and secure way. Should I try to extend django builtin user model, or maybe should I create my own user model wide enough to keep all the information I need? Below you may find some specifications and expectations from the working solution: users should be able to register and authenticate every user should have profile (or model with all required fields) users dont need django builtin admin panel, but they need to edit their profiles/models via simple web form Please, let me know how do you solve those issues in your applications, and what is the best current way to handle users with django. Any links to articles/blogs or code examples are highly appreciated! A: users should be able to register and authenticate django.contrib.auth is the module you want. Be sure to check the docs for custom login forms. every user should have profile (or model with all required fields) You need to set settings.AUTH_PROFILE_MODULE, as noted by others. Information about setting up the user profile model is available for the latest version, 1.1, and 1.0. It hasn't been dropped. users dont need django builtin admin panel, but they need to edit their profiles/models via simple web form You can create a form and view just like you would for any other app; maybe make a "user control panel" app for handling these things. Your views would then interact with the django.contrib.auth.models.User and django.contrib.auth.models.Group models. You can set this up to do whatever you need. EDIT: Responding to your questions-in-the-form-of-an-answer (paging Alex Trebek)... The second version of djangobook, covering django 1.0 (that is way closer to 1.2 than 0.96) no longer has that information anywhere, what makes me highly confused - has anything changed? Is there other, better, more secure way to handle users and their profiles? Therefore this question asked. I wouldn't recommend djangobook as a reference; it's out of date on this topic. User profiles exist and I'm using them in my Django 1.1.1 site; I'm even populating them from NIS. Please use the links I provided above. They go directly to the actual Django documentation and are authoritative. By the way, I forgot to ask, if the way you all refer to (that is AUTH_PROFILE_MODULE) will create automatically upon registration Answered in the docs. and require the profile to exist upon any action (user withoud existing, filled profile should not exists, this is why I was thinking about extending User model somehow)? The profile needs to exist if User.get_profile() is called. Will it get updated as well (people are mentioning 'signals' on various blogs related to this subject)? It's like any other model: it only gets updated when you change the fields and call save(). The signal part is how you hook in a function to create a profile for a new User: from django.db.models.signals import post_save from django.contrib.auth import User from myUserProfileApp import UserProfile def make_user_profile(sender, **kwargs): if 'created' not in kwargs or not kwargs['created']: return # Assumes that the `ForeignKey(User)` field in "UserProfile" is named "user". profile = UserProfile(user=kwargs["instance"]) # Set anything else you need to in the profile, then... profile.save() post_save.connect(make_user_profile, sender=User, weak=False) This only creates a new profile for a new User. Existing Users need to have profiles manually added: $ ./manage.py shell >>> from django.contrib.auth import User >>> from myUserProfileApp import UserProfile >>> for u in User.objects.all(): ... UserProfile(user=u).save() # Add other params as needed. ... If you have some users with profiles and some without, you'll need to do a bit more work: >>> for u in User.objects.all(): ... try: ... UserProfile(user=u).save() # Add other params as needed. ... except: ... pass A: Seems to me like the current version of the Django docs and the Django book both have sections for this. http://docs.djangoproject.com/en/dev/topics/auth/#auth-profiles talks about using AUTH_PROFILE_MODULE to specify the model class that will store extra user information http://www.djangobook.com/en/1.0/chapter12/#cn222 as does this A: Django supports a UserProfile model (of your own creation) right out of the box. You can assign this in your settings.py file with: AUTH_PROFILE_MODULE. That being said, I will agree with you that it is a little confusing at first. How I handled it was to create my own UserProfile model with the fields I wanted and hook it into the Django User model via the settings (above). I believe this is the preferred way and probably better than extending the base User model. You can access your profile through User.get_profile(). There are a couple projects on github that are UserProfile oriented. If you wanted some code examples, you could look there. A: Thank you all for your answers! I know that django dev documentation mentions user profiles, but does it very briefly (roughly few lines) and links to djangobook containing information about user profiles, but... to its first version, covering django 0.96. The second version of djangobook, covering django 1.0 (that is way closer to 1.2 than 0.96) no longer has that information anywhere, what makes me highly confused - has anything changed? Is there other, better, more secure way to handle users and their profiles? Therefore this question asked.
Django - how to write users and profiles handling in best way?
I am writing simple site that requires users and profiles to be handled. The first initial thought is to use django's build in user handling, but then the user model is too narrow and does not contain fields that I need. The documentation mentions user profiles, but user profiles section has been removed from djangobook covering django 1.0 (ideally, the solution should work with django 1.2), and the Internet is full of different solutions, not making the choice easier (like user model inheritance, user profiles and django signals, and so on). I would like to know, how to write this in good, modern, fast and secure way. Should I try to extend django builtin user model, or maybe should I create my own user model wide enough to keep all the information I need? Below you may find some specifications and expectations from the working solution: users should be able to register and authenticate every user should have profile (or model with all required fields) users dont need django builtin admin panel, but they need to edit their profiles/models via simple web form Please, let me know how do you solve those issues in your applications, and what is the best current way to handle users with django. Any links to articles/blogs or code examples are highly appreciated!
[ "\nusers should be able to register and authenticate\n\ndjango.contrib.auth is the module you want. Be sure to check the docs for custom login forms.\n\nevery user should have profile (or model with all required fields)\n\nYou need to set settings.AUTH_PROFILE_MODULE, as noted by others.\nInformation about setting up the user profile model is available for the latest version, 1.1, and 1.0. It hasn't been dropped.\n\nusers dont need django builtin admin panel, but they need to edit their profiles/models via simple web form\n\nYou can create a form and view just like you would for any other app; maybe make a \"user control panel\" app for handling these things. Your views would then interact with the django.contrib.auth.models.User and django.contrib.auth.models.Group models. You can set this up to do whatever you need.\nEDIT: Responding to your questions-in-the-form-of-an-answer (paging Alex Trebek)...\n\nThe second version of djangobook, covering django 1.0 (that is way closer to 1.2 than 0.96) no longer has that information anywhere, what makes me highly confused - has anything changed? Is there other, better, more secure way to handle users and their profiles? Therefore this question asked.\n\nI wouldn't recommend djangobook as a reference; it's out of date on this topic. User profiles exist and I'm using them in my Django 1.1.1 site; I'm even populating them from NIS.\nPlease use the links I provided above. They go directly to the actual Django documentation and are authoritative.\n\nBy the way, I forgot to ask, if the way you all refer to (that is AUTH_PROFILE_MODULE) will create automatically upon registration\n\nAnswered in the docs.\n\nand require the profile to exist upon any action (user withoud existing, filled profile should not exists, this is why I was thinking about extending User model somehow)?\n\nThe profile needs to exist if User.get_profile() is called.\n\nWill it get updated as well (people are mentioning 'signals' on various blogs related to this subject)?\n\nIt's like any other model: it only gets updated when you change the fields and call save().\nThe signal part is how you hook in a function to create a profile for a new User:\nfrom django.db.models.signals import post_save\nfrom django.contrib.auth import User\nfrom myUserProfileApp import UserProfile\n\ndef make_user_profile(sender, **kwargs):\n if 'created' not in kwargs or not kwargs['created']:\n return\n\n # Assumes that the `ForeignKey(User)` field in \"UserProfile\" is named \"user\".\n profile = UserProfile(user=kwargs[\"instance\"])\n # Set anything else you need to in the profile, then...\n profile.save()\n\npost_save.connect(make_user_profile, sender=User, weak=False)\n\nThis only creates a new profile for a new User. Existing Users need to have profiles manually added:\n$ ./manage.py shell\n>>> from django.contrib.auth import User\n>>> from myUserProfileApp import UserProfile\n>>> for u in User.objects.all():\n... UserProfile(user=u).save() # Add other params as needed.\n...\n\nIf you have some users with profiles and some without, you'll need to do a bit more work:\n>>> for u in User.objects.all():\n... try:\n... UserProfile(user=u).save() # Add other params as needed.\n... except:\n... pass\n\n", "Seems to me like the current version of the Django docs and the Django book both have sections for this.\n\nhttp://docs.djangoproject.com/en/dev/topics/auth/#auth-profiles talks about using AUTH_PROFILE_MODULE to specify the model class that will store extra user information\nhttp://www.djangobook.com/en/1.0/chapter12/#cn222 as does this\n\n", "Django supports a UserProfile model (of your own creation) right out of the box. You can assign this in your settings.py file with: AUTH_PROFILE_MODULE. That being said, I will agree with you that it is a little confusing at first. \nHow I handled it was to create my own UserProfile model with the fields I wanted and hook it into the Django User model via the settings (above). I believe this is the preferred way and probably better than extending the base User model. \nYou can access your profile through User.get_profile().\nThere are a couple projects on github that are UserProfile oriented. If you wanted some code examples, you could look there.\n", "Thank you all for your answers! I know that django dev documentation mentions user profiles, but does it very briefly (roughly few lines) and links to djangobook containing information about user profiles, but... to its first version, covering django 0.96. The second version of djangobook, covering django 1.0 (that is way closer to 1.2 than 0.96) no longer has that information anywhere, what makes me highly confused - has anything changed? Is there other, better, more secure way to handle users and their profiles? Therefore this question asked.\n" ]
[ 12, 2, 0, 0 ]
[]
[]
[ "django", "profiles", "python" ]
stackoverflow_0002654689_django_profiles_python.txt
Q: How can I detect if the caller passed any variables to my function in Python? I guess the subject sounds pretty stupid, so I'll show some code: def foo(**kwargs): # How can you detect the difference between (**{}) and ()? pass foo(**{}) foo() Is there any way to detect inside of foo, how the method was called? Update 1 Because there were some comments why you possible want to do something, I'll try to explain some background. super(MyClass, self).foo(*args, **kwargs) sucks - a lot of wasteful duplication. I want to write 'self.super()'. In this case, just call the super class and hand over all parameters that the calling method got as well. Works like a charm. Now the problematic magic part: I want to say 'self.super(something)' and in this case, only 'something' is passed to the super method. Works for most cases. This is where it breaks: def foo(self, fnord=42, *args, **kwargs): self.super(*args, **kwargs) So the super method should get the arguments that the calling method - however if *args, **kwargs are empty, currently the library can not detect this condition and passed all arguments including 'fnord'... Of course I could use self.super.foo(*args, **kwargs) as an alternative syntax but that's lame :-) PS: Yes, I know p3k's super, but still not nice and it does not work with Python 2.x... Update 2 Actually even Python's ast module removes the **{} (ast.parse('foo(**{})')) so it looks like this happens so early in the parsing process that you can not get this information later on... So in the end I have either to give up on that specific problem (raising an AmbiguousSyntaxError) or to use text parsing as proposed by ~unutbu. Re-thinking my approach, the latter might actually feasable because I only need to know if it is self.super(\s*), self.super(\S+). A: This hack only works with CPython. import traceback def foo(**kwargs): # stack is a list of 4-tuples: (filename, line number, function name, text) # see http://docs.python.org/library/traceback.html#module-traceback (filename,line_number,function_name,text)=traceback.extract_stack()[-2] print('foo was called: %s'%text) foo(**{}) # foo was called: foo(**{}) foo() # foo was called: foo() As an example of how this might be useful: def pv(var): (filename,line_number,function_name,text)=traceback.extract_stack()[-2] print('%s: %s'%(text[text.find('(')+1:-1],var)) x=5 pv(x) # x: 5 Notice that pv is called with just the value x, but it prints both the "name" of the variable (as it was called), and the value of a variable. Sometimes I use this when debugging and am too lazy to write out the full print statement. A: In your update to your original question you wrote you want to be able to do something like this: def foo(self, fnord=42, *args, **kwargs): self.super(*args, **kwargs) Does this do what you want? def foo(self, fnord=42, *args, **kwargs): self.super(fnord=fnord, *args, **kwargs) A: So basically it is not possible to do that with the provided Python modules. I had to fall-back to plain-text regexes which work for me pretty well given the simplicity of my requirements.
How can I detect if the caller passed any variables to my function in Python?
I guess the subject sounds pretty stupid, so I'll show some code: def foo(**kwargs): # How can you detect the difference between (**{}) and ()? pass foo(**{}) foo() Is there any way to detect inside of foo, how the method was called? Update 1 Because there were some comments why you possible want to do something, I'll try to explain some background. super(MyClass, self).foo(*args, **kwargs) sucks - a lot of wasteful duplication. I want to write 'self.super()'. In this case, just call the super class and hand over all parameters that the calling method got as well. Works like a charm. Now the problematic magic part: I want to say 'self.super(something)' and in this case, only 'something' is passed to the super method. Works for most cases. This is where it breaks: def foo(self, fnord=42, *args, **kwargs): self.super(*args, **kwargs) So the super method should get the arguments that the calling method - however if *args, **kwargs are empty, currently the library can not detect this condition and passed all arguments including 'fnord'... Of course I could use self.super.foo(*args, **kwargs) as an alternative syntax but that's lame :-) PS: Yes, I know p3k's super, but still not nice and it does not work with Python 2.x... Update 2 Actually even Python's ast module removes the **{} (ast.parse('foo(**{})')) so it looks like this happens so early in the parsing process that you can not get this information later on... So in the end I have either to give up on that specific problem (raising an AmbiguousSyntaxError) or to use text parsing as proposed by ~unutbu. Re-thinking my approach, the latter might actually feasable because I only need to know if it is self.super(\s*), self.super(\S+).
[ "This hack only works with CPython. \nimport traceback\n\ndef foo(**kwargs):\n # stack is a list of 4-tuples: (filename, line number, function name, text)\n # see http://docs.python.org/library/traceback.html#module-traceback\n\n (filename,line_number,function_name,text)=traceback.extract_stack()[-2]\n print('foo was called: %s'%text)\n\nfoo(**{})\n# foo was called: foo(**{})\nfoo()\n# foo was called: foo()\n\nAs an example of how this might be useful:\ndef pv(var):\n (filename,line_number,function_name,text)=traceback.extract_stack()[-2]\n print('%s: %s'%(text[text.find('(')+1:-1],var))\n\nx=5\npv(x)\n# x: 5\n\nNotice that pv is called with just the value x, but\nit prints both the \"name\" of the variable (as it was called), and the value of a variable. Sometimes I use this when debugging and am too lazy to write out the full print statement.\n", "In your update to your original question you wrote you want to be able to do something like this:\ndef foo(self, fnord=42, *args, **kwargs):\n self.super(*args, **kwargs)\n\nDoes this do what you want?\ndef foo(self, fnord=42, *args, **kwargs):\n self.super(fnord=fnord, *args, **kwargs)\n\n", "So basically it is not possible to do that with the provided Python modules. I had to fall-back to plain-text regexes which work for me pretty well given the simplicity of my requirements.\n" ]
[ 0, 0, 0 ]
[]
[]
[ "inspect", "python" ]
stackoverflow_0002529491_inspect_python.txt
Q: Qt: How to autoexpand parents of a new QTreeView item when using a QSortFilterProxyModel I'm making an app wherein the user can add new data to a QTreeModel at any time. The parent under which it gets placed is automatically expanded to show the new item: self.tree = DiceModel(headers) self.treeView.setModel(self.tree) expand_node = self.tree.addRoll() #addRoll makes a node, adds it, and returns the (parent) note to be expanded self.treeView.expand(expand_node) This works as desired. If I add a QSortFilterProxyModel to the mix: self.tree = DiceModel(headers) self.sort = DiceSort(self.tree) self.treeView.setModel(self.sort) expand_node = self.tree.addRoll() #addRoll makes a node, adds it, and returns the (parent) note to be expanded self.treeView.expand(expand_node) the parent no longer expands. Any idea what I am doing wrong? A: I believe you should map your expanding item index into the proxy model item index before calling expand for it. QSortFilterProxyModel::mapFromSource method should do what you need. Please check if an example below would work for you (it's c++, let me know if you're having troubles converting it to python): // create models QStandardItemModel* model = new (QStandardItemModel); QSortFilterProxyModel* proxyModel = new QSortFilterProxyModel(this); proxyModel->setSourceModel(model); // set model ui->treeView->setModel(proxyModel); ui->treeView->setSortingEnabled(true); // generate items QStandardItem* parentItem0 = model->invisibleRootItem(); QModelIndex index = parentItem0->index(); for (int i = 0; i < 4; ++i) { QStandardItem* item = new QStandardItem(QString("new item %0").arg(i)); parentItem0->appendRow(item); parentItem0 = item; // expand items using proxyModel->mapFromSource ui->treeView->expand(proxyModel->mapFromSource(item->index())); // line below doesn't work for you //ui->treeView->expand(item->index()); } hope this helps, regards
Qt: How to autoexpand parents of a new QTreeView item when using a QSortFilterProxyModel
I'm making an app wherein the user can add new data to a QTreeModel at any time. The parent under which it gets placed is automatically expanded to show the new item: self.tree = DiceModel(headers) self.treeView.setModel(self.tree) expand_node = self.tree.addRoll() #addRoll makes a node, adds it, and returns the (parent) note to be expanded self.treeView.expand(expand_node) This works as desired. If I add a QSortFilterProxyModel to the mix: self.tree = DiceModel(headers) self.sort = DiceSort(self.tree) self.treeView.setModel(self.sort) expand_node = self.tree.addRoll() #addRoll makes a node, adds it, and returns the (parent) note to be expanded self.treeView.expand(expand_node) the parent no longer expands. Any idea what I am doing wrong?
[ "I believe you should map your expanding item index into the proxy model item index before calling expand for it. QSortFilterProxyModel::mapFromSource method should do what you need. Please check if an example below would work for you (it's c++, let me know if you're having troubles converting it to python): \n// create models\nQStandardItemModel* model = new (QStandardItemModel);\nQSortFilterProxyModel* proxyModel = new QSortFilterProxyModel(this);\nproxyModel->setSourceModel(model);\n\n// set model\nui->treeView->setModel(proxyModel); \nui->treeView->setSortingEnabled(true);\n\n// generate items\nQStandardItem* parentItem0 = model->invisibleRootItem();\nQModelIndex index = parentItem0->index();\nfor (int i = 0; i < 4; ++i)\n{\n QStandardItem* item = new QStandardItem(QString(\"new item %0\").arg(i));\n parentItem0->appendRow(item);\n parentItem0 = item;\n\n // expand items using proxyModel->mapFromSource \n ui->treeView->expand(proxyModel->mapFromSource(item->index()));\n // line below doesn't work for you\n //ui->treeView->expand(item->index());\n}\n\nhope this helps, regards\n" ]
[ 2 ]
[]
[]
[ "pyqt", "pyqt4", "python", "qt" ]
stackoverflow_0002657380_pyqt_pyqt4_python_qt.txt
Q: python django automated data addition I have a script which reads data from a csv file. I need to store the data into a database which has already been created as $ python manage.py syncdb so, that automated data entry is possible in an easier manner, as available in the django shell. A: You have to set up a django environment to use in your script, afterwards your python script can work with django models just as in the 'real' site: The easiest way to do this: set the DJANGO_SETTINGS_MODULE environment variable (e.g. export DJANGO_SETTINGS_MODULE=mysite.settings ). Then your script can do things like: from app.models import MyModel a = MyModel(field=value) a.save() There are also some other ways, where you have to write some additional code in your script, I prefer these because they do not require an environment variable: 1) setup_environ: from django.core.management import setup_environ import mysite.settings setup_environ(mysite.settings) 2) Create settings on the flow: from django.conf import settings settings.configure(DEBUG=False, DATABASE_NAME="mydb", ...)
python django automated data addition
I have a script which reads data from a csv file. I need to store the data into a database which has already been created as $ python manage.py syncdb so, that automated data entry is possible in an easier manner, as available in the django shell.
[ "You have to set up a django environment to use in your script, afterwards your python script can work with django models just as in the 'real' site:\nThe easiest way to do this: set the DJANGO_SETTINGS_MODULE environment variable (e.g. export DJANGO_SETTINGS_MODULE=mysite.settings ). Then your script can do things like:\nfrom app.models import MyModel\n\na = MyModel(field=value)\na.save()\n\nThere are also some other ways, where you have to write some additional code in your script, I prefer these because they do not require an environment variable:\n1) setup_environ:\nfrom django.core.management import setup_environ\nimport mysite.settings\nsetup_environ(mysite.settings)\n\n2) Create settings on the flow:\nfrom django.conf import settings\nsettings.configure(DEBUG=False, DATABASE_NAME=\"mydb\", ...)\n\n" ]
[ 1 ]
[]
[]
[ "automation", "database", "django", "python" ]
stackoverflow_0002658527_automation_database_django_python.txt
Q: execute python file from another file I have a python file that has functions and classes. now I am writting another program (in another file). and I want to start the new file with running the old file (with the function and classes). I have tried using exec(path_2_oldFile.pyw) but it didn't work. thanks for any help Ariel A: Ideally you should try and import the first file into the new as a module using the import statement: http://effbot.org/zone/import-confusion.htm You'll need to make sure that your original module is on the python path somewhere. If it is in the same directory as the new file this should just work.
execute python file from another file
I have a python file that has functions and classes. now I am writting another program (in another file). and I want to start the new file with running the old file (with the function and classes). I have tried using exec(path_2_oldFile.pyw) but it didn't work. thanks for any help Ariel
[ "Ideally you should try and import the first file into the new as a module using the import statement:\nhttp://effbot.org/zone/import-confusion.htm\nYou'll need to make sure that your original module is on the python path somewhere. If it is in the same directory as the new file this should just work.\n" ]
[ 1 ]
[]
[]
[ "exec", "import", "python" ]
stackoverflow_0002658612_exec_import_python.txt
Q: write in file is not complete without quitting the IDLE(Python GUI) I want to write something in a file. for example, fo=open('C:\\Python\\readline_test.txt','a') for i in range(3): st='abc'+'\n' fo.write(st) fo.close then I open this python file in IDLE, and click "Run Module". There is no error message but I find the writing is not complete if I didn't quit IDLE. How can I complete the file writing without quitting the IDLE? Thanks. (I use Python 2.6.2 on Windows XP.) A: Maybe a typo, but it should be: fo.close() Then it should work. Alternative you can use the with statement syntax (better example): with open('C:\\Python\\readline_test.txt','a') as fo: for i in range(3): fo.write('abc'+'\n') The file is automatically closed when leaving the with block. (Instead of 'abc'+'\n', just write 'abc\n') A: You can try using fo.flush() and mayby os.fsync() after writing to file object to ensure that all file operations are flushed to disk.
write in file is not complete without quitting the IDLE(Python GUI)
I want to write something in a file. for example, fo=open('C:\\Python\\readline_test.txt','a') for i in range(3): st='abc'+'\n' fo.write(st) fo.close then I open this python file in IDLE, and click "Run Module". There is no error message but I find the writing is not complete if I didn't quit IDLE. How can I complete the file writing without quitting the IDLE? Thanks. (I use Python 2.6.2 on Windows XP.)
[ "Maybe a typo, but it should be:\nfo.close()\n\nThen it should work.\nAlternative you can use the with statement syntax (better example):\nwith open('C:\\\\Python\\\\readline_test.txt','a') as fo:\n for i in range(3):\n fo.write('abc'+'\\n')\n\nThe file is automatically closed when leaving the with block.\n(Instead of 'abc'+'\\n', just write 'abc\\n')\n", "You can try using\nfo.flush()\n\nand mayby\nos.fsync()\n\nafter writing to file object to ensure that all file operations are flushed to disk.\n" ]
[ 8, 0 ]
[]
[]
[ "file", "python", "python_idle" ]
stackoverflow_0002658707_file_python_python_idle.txt
Q: Passing sql results to views hard-codes views to database column names I just realized that i may not be following best practices in regards to the MVC pattern. My issue is that my views "know" information about my database Here's my situation in psuedo code... My controller invokes a method from my model and passes it directly to the view view.records = tableGateway.getRecords() // gets array of records view.display() in my view each records as record print record.name print record.address ... In my view i have record.name and record.address, info that's hard-coded to my database. Is this bad? What other ways around it are there other than iterating over everything in the controller and basically rewriting the records collection. And that just seems silly. Thanks EDIT Heres an actual view <?php foreach( $categories as $category ): ?> <tr> <td><?php echo $category['name'] ?> </td> <td><?php echo $category['fields'] ?> </td> <td><?php echo $category['records'] ?></td> <td><a href="/category/view/<?php echo $category['id'] ?>/<?php echo url::title( $category['name'] ) ?>/">View</a></td> </tr> <?php endforeach; ?> So a simple loop through the data won't work, i need to capture certain fields of the sql result in my view. Is there a way around this? It makes me feel dirty. A: I'd say it's not bad to have such info hardcoded if you need to have it quick and dirty. But consider having generic class for views with method that takes your data from db and some array describing which columns to use. Then in the children classes (UserView, PostView, WhateverTableNameView) you could call this base method with array containing "Name", "Address" etc. Pardon me if I am talking Python gibberish, I came to this question from PHP tag ;) More or less like this class BaseView { public function display(& $data, array $columnNames) { foreach($data as $row) { foreach($columnNames as $c) { echo $row->$c; // or $row[$c] or whatever your data is, I'm assuming objects } echo "\n"; } } class UserView extends BaseView{ public function display(& $data) { parent::display($data, array('Name', 'Address'); } } The nice things here: Need one more column? Make sure you query for it, then modify 1 line in UserView. Need to have text for HTML column labels (<th> stuff) - it's already here. $data could be resource descriptor (think while($rs.nextRow())) and not neccessarily full array that might occupy a lot of memory and take time to pass around from one function to another. if you go for nice looking HTML tables around these records, you have unified look & feel across application as there's only one place where you define them. If for some reason this doesn't appeal to you, the truly generic solution is to have indexes instead of column names. $data[$i][0], $data[$i][1] and so on... Most database APIs offer possibility to query for columns as names, as numbers or both. For PHP + MySQL see examples on http://www.php.net/manual/en/function.mysql-fetch-array.php But this will bite you in the a$$ sooner or later because you lose metadata info. Let's say you want later to wrap your "names" into links: echo '<a href="user/',$record['id'],'">',$record['name'],'</a>'; Good luck doing this in reusable way without column names... A: With getters/setters and a piece of code to map the record fields to them you can remove this, but you'll add some complexity. The real question is: Do i need to rename field names at all? With some planning/thinking/feedback it shouldn't be hard to find appropriate names for your fields that survive the applications lifetime. However, if the semantics of the field change you should add a new field. This has also the advantage that you can clearly document the deprecation of it and lead the programmer to the new one.
Passing sql results to views hard-codes views to database column names
I just realized that i may not be following best practices in regards to the MVC pattern. My issue is that my views "know" information about my database Here's my situation in psuedo code... My controller invokes a method from my model and passes it directly to the view view.records = tableGateway.getRecords() // gets array of records view.display() in my view each records as record print record.name print record.address ... In my view i have record.name and record.address, info that's hard-coded to my database. Is this bad? What other ways around it are there other than iterating over everything in the controller and basically rewriting the records collection. And that just seems silly. Thanks EDIT Heres an actual view <?php foreach( $categories as $category ): ?> <tr> <td><?php echo $category['name'] ?> </td> <td><?php echo $category['fields'] ?> </td> <td><?php echo $category['records'] ?></td> <td><a href="/category/view/<?php echo $category['id'] ?>/<?php echo url::title( $category['name'] ) ?>/">View</a></td> </tr> <?php endforeach; ?> So a simple loop through the data won't work, i need to capture certain fields of the sql result in my view. Is there a way around this? It makes me feel dirty.
[ "I'd say it's not bad to have such info hardcoded if you need to have it quick and dirty.\nBut consider having generic class for views with method that takes your data from db and some array describing which columns to use. Then in the children classes (UserView, PostView, WhateverTableNameView) you could call this base method with array containing \"Name\", \"Address\" etc.\nPardon me if I am talking Python gibberish, I came to this question from PHP tag ;) More or less like this\nclass BaseView {\n public function display(& $data, array $columnNames) {\n foreach($data as $row) {\n foreach($columnNames as $c) {\n echo $row->$c; // or $row[$c] or whatever your data is, I'm assuming objects\n }\n echo \"\\n\";\n }\n}\n\nclass UserView extends BaseView{\n public function display(& $data) {\n parent::display($data, array('Name', 'Address');\n }\n}\n\nThe nice things here:\n\nNeed one more column? Make sure you query for it, then modify 1 line in UserView.\nNeed to have text for HTML column labels (<th> stuff) - it's already here.\n$data could be resource descriptor (think while($rs.nextRow())) and not neccessarily full array that might occupy a lot of memory and take time to pass around from one function to another.\nif you go for nice looking HTML tables around these records, you have unified look & feel across application as there's only one place where you define them.\n\n\nIf for some reason this doesn't appeal to you, the truly generic solution is to have indexes instead of column names. $data[$i][0], $data[$i][1] and so on... Most database APIs offer possibility to query for columns as names, as numbers or both. For PHP + MySQL see examples on http://www.php.net/manual/en/function.mysql-fetch-array.php\nBut this will bite you in the a$$ sooner or later because you lose metadata info. Let's say you want later to wrap your \"names\" into links:\necho '<a href=\"user/',$record['id'],'\">',$record['name'],'</a>';\n\nGood luck doing this in reusable way without column names...\n", "With getters/setters and a piece of code to map the record fields to them you can remove this, but you'll add some complexity.\nThe real question is: Do i need to rename field names at all?\nWith some planning/thinking/feedback it shouldn't be hard to find appropriate names for your fields that survive the applications lifetime. However, if the semantics of the field change you should add a new field. This has also the advantage that you can clearly document the deprecation of it and lead the programmer to the new one.\n" ]
[ 1, 1 ]
[]
[]
[ "model_view_controller", "php", "python" ]
stackoverflow_0002657336_model_view_controller_php_python.txt
Q: Regexp for extracting data in parenthesis and commas So, i have this : "( ABC,2004 )" And I would need to extract ABC in a variable and 2004 in another. So what I have for now is this: In: re.compile(r'([^)]*,').findall("( ABC,2004 )") Out: ['( ABC,'] A: If your inputs are always like that (begin with "( ", end with " )"), you can have your values as: input_text.strip(" ()").split(",") >>> "( ABC,2004 )".strip(" ()").split(",") ['ABC', '2004'] This will consume any parentheses at the edges inside the outer parentheses. Also, if the commas can be surrounded/succeeded by spaces, you can: [item.strip() for item in input_text.strip(" ()").split(",")] A: Try just looking for "word" characters: >> re.compile(r'\w+').findall("( ABC,2004 )") ['ABC', '2004']
Regexp for extracting data in parenthesis and commas
So, i have this : "( ABC,2004 )" And I would need to extract ABC in a variable and 2004 in another. So what I have for now is this: In: re.compile(r'([^)]*,').findall("( ABC,2004 )") Out: ['( ABC,']
[ "If your inputs are always like that (begin with \"( \", end with \" )\"), you can have your values as:\ninput_text.strip(\" ()\").split(\",\")\n\n>>> \"( ABC,2004 )\".strip(\" ()\").split(\",\")\n['ABC', '2004']\n\nThis will consume any parentheses at the edges inside the outer parentheses.\nAlso, if the commas can be surrounded/succeeded by spaces, you can:\n[item.strip() for item in input_text.strip(\" ()\").split(\",\")]\n\n", "Try just looking for \"word\" characters:\n>> re.compile(r'\\w+').findall(\"( ABC,2004 )\")\n['ABC', '2004']\n\n" ]
[ 5, 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002658622_python_regex.txt
Q: News feed APIs for general news I'm building a database + tool that scours news feeds for a certain term. For example "food poisoning from nuts". I want to scour social media sites, news sites, major news aggregators, etc... for that term. Question 1: What are some of the news aggregator APIs out there? Question 2: How Would you go about coding and receiving only the latest news from the API? Edit Added schematic: alt text http://koopics.com/news_parser.jpg A: Do you know Yahoo! Pipes? It's a very flexible feed aggregator, and you can manipulate it using YQL, which is quite powerful and has a Python librabry, python-yql :). YQL also has specific "tables" for Twitter and other services and news sources, so, depending on what you want, you might not even need Pipes. There's a quick example of Pipes + YQL usage at http://blog.ouseful.info/2009/04/27/using-yql-with-yahoo-pipes/ , but you can play around with them at the YQL Console. So, that's your "Question 1". But, using YQL, "Question 2" (if I understood it correctly) comes naturally, as you use it almost like regular SQL, imposing limits, ordering etc. A: Have you tried Universtal Feed Parser ?? A: Google has a news feeds api but I think it is only for non commercial use http://www.google.com/support/news/bin/answer.py?answer=59255&hl=en A: If you've got monetary support backing your project, Reuters has news data feeds that you can subscribe to on a monthly basis.
News feed APIs for general news
I'm building a database + tool that scours news feeds for a certain term. For example "food poisoning from nuts". I want to scour social media sites, news sites, major news aggregators, etc... for that term. Question 1: What are some of the news aggregator APIs out there? Question 2: How Would you go about coding and receiving only the latest news from the API? Edit Added schematic: alt text http://koopics.com/news_parser.jpg
[ "Do you know Yahoo! Pipes? It's a very flexible feed aggregator, and you can manipulate it using YQL, which is quite powerful and has a Python librabry, python-yql :). YQL also has specific \"tables\" for Twitter and other services and news sources, so, depending on what you want, you might not even need Pipes.\nThere's a quick example of Pipes + YQL usage at http://blog.ouseful.info/2009/04/27/using-yql-with-yahoo-pipes/ , but you can play around with them at the YQL Console.\nSo, that's your \"Question 1\". But, using YQL, \"Question 2\" (if I understood it correctly) comes naturally, as you use it almost like regular SQL, imposing limits, ordering etc.\n", "Have you tried Universtal Feed Parser ??\n", "Google has a news feeds api but I think it is only for non commercial use\nhttp://www.google.com/support/news/bin/answer.py?answer=59255&hl=en\n", "If you've got monetary support backing your project, Reuters has news data feeds that you can subscribe to on a monthly basis.\n" ]
[ 4, 1, 0, 0 ]
[]
[]
[ "c++", "feed", "postgresql", "python" ]
stackoverflow_0002652692_c++_feed_postgresql_python.txt
Q: In my virtualenv, I need to use sudo for all commands I set up a virtualenv, which is working, but for some reason I need to use sudo for commands as simple as mkdir. Obviously I did something incorrectly. Any idea what it might be? Thanks A: Check the directory permissions and owner and give: $ sudo chown -R me:me virtualenvdir $ sudo chmod -R a+rX virtualenvdir change me with your username, typically $USER, and virtualenvdir with your virtualenv's work directory. A: The commands cd test sudo virtualenv python creates a directory called python which is owned by root. drwxr-xr-x 5 root root 4096 2010-04-17 11:40 python That would force you to use sudo for simple things like making a directory inside the python directory. The fix would be to delete the python directory (saving data first if necessary) and issue the command virtualenv python without the sudo.
In my virtualenv, I need to use sudo for all commands
I set up a virtualenv, which is working, but for some reason I need to use sudo for commands as simple as mkdir. Obviously I did something incorrectly. Any idea what it might be? Thanks
[ "Check the directory permissions and owner and give:\n$ sudo chown -R me:me virtualenvdir\n$ sudo chmod -R a+rX virtualenvdir\n\nchange me with your username, typically $USER, and virtualenvdir with your virtualenv's work directory.\n", "The commands\ncd test\nsudo virtualenv python\n\ncreates a directory called python which is owned by root.\ndrwxr-xr-x 5 root root 4096 2010-04-17 11:40 python\n\nThat would force you to use sudo for simple things like making a directory inside the python directory.\nThe fix would be to delete the python directory (saving data first if necessary) and issue the command\nvirtualenv python\n\nwithout the sudo.\n" ]
[ 15, 4 ]
[]
[]
[ "python", "sudo", "virtualenv" ]
stackoverflow_0002658902_python_sudo_virtualenv.txt
Q: My QFileSystemModel doesn't work as expected in PyQt EDIT2: model.hasChildren(parentIndex) returns True, but model.rowCount(parentIndex) returns 0. Is QFileSystemModel just fubar in PyQt? EDIT: With a bit of adaptation this all works exactly as it should if I use QDirModel. This is deprecated, but maybe QFileSystemModel hasn't been fully implemented in PyQt? I'm learning the Qt Model/View architecture at the moment, and I've found something that doesn't work as I'd expect it to. I've got the following code (adapted from Qt Model Classes): from PyQt4 import QtCore, QtGui model = QtGui.QFileSystemModel() parentIndex = model.index(QtCore.QDir.currentPath()) print model.isDir(parentIndex) #prints True print model.data(parentIndex).toString() #prints name of current directory rows = model.rowCount(parentIndex) print rows #prints 0 (even though the current directory has directory and file children) The question: Is this a problem with PyQt, have I just done something wrong, or am I completely misunderstanding QFileSystemModel? According to the documentation, model.rowCount(parentIndex) should return the number of children in the current directory. (I'm running this under Ubuntu with Python 2.6) The QFileSystemModel docs say that it needs an instance of a Gui application, so I've also placed the above code in a QWidget as follows, but with the same result: import sys from PyQt4 import QtCore, QtGui class Widget(QtGui.QWidget): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) model = QtGui.QFileSystemModel() parentIndex = model.index(QtCore.QDir.currentPath()) print model.isDir(parentIndex) print model.data(parentIndex).toString() rows = model.rowCount(parentIndex) print rows def main(): app = QtGui.QApplication(sys.argv) widget = Widget() widget.show() sys.exit(app.exec_()) if __name__ == '__main__': main() A: I've solved it. The reason to use QFileSystemModel as opposed to QDirModel is because QFileSystemModel loads the data from the filesystem in a separate thread. The problem with that is that if you try to print the number of children just after it's been constructed is that it won't have loaded the children yet. The way to fix the above code is to add the following: self.timer = QtCore.QTimer(self) self.timer.singleShot(1, self.printRowCount) to the end of the constructor, and add a printRowCount method which will print the correct number of children. Phew. A: Since you've already figured it out, just a couple of extra thoughts on what was going on with your model: QFileSystemModel::rowCount returns rows from the visibleChildren collection; I guess you're correctly identified the problem: at the time when you're checking row count it was not yet populated. I've changed your example without using timers; pls, check if it works for you: class Widget(QtGui.QWidget): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.model = QtGui.QFileSystemModel() self.model.setRootPath(QtCore.QDir.currentPath()) def checkParent(self): parentIndex = self.model.index(QtCore.QDir.currentPath()) print self.model.isDir(parentIndex) print self.model.data(parentIndex).toString() rows = self.model.rowCount(parentIndex) print "row count:", rows def main(): app = QtGui.QApplication(sys.argv) widget = Widget() widget.show() app.processEvents(QtCore.QEventLoop.AllEvents) widget.checkParent() sys.exit(app.exec_()) if __name__ == '__main__': main() I believe your code should work correctly on any UI event after widget constructed is shown on the screen regards
My QFileSystemModel doesn't work as expected in PyQt
EDIT2: model.hasChildren(parentIndex) returns True, but model.rowCount(parentIndex) returns 0. Is QFileSystemModel just fubar in PyQt? EDIT: With a bit of adaptation this all works exactly as it should if I use QDirModel. This is deprecated, but maybe QFileSystemModel hasn't been fully implemented in PyQt? I'm learning the Qt Model/View architecture at the moment, and I've found something that doesn't work as I'd expect it to. I've got the following code (adapted from Qt Model Classes): from PyQt4 import QtCore, QtGui model = QtGui.QFileSystemModel() parentIndex = model.index(QtCore.QDir.currentPath()) print model.isDir(parentIndex) #prints True print model.data(parentIndex).toString() #prints name of current directory rows = model.rowCount(parentIndex) print rows #prints 0 (even though the current directory has directory and file children) The question: Is this a problem with PyQt, have I just done something wrong, or am I completely misunderstanding QFileSystemModel? According to the documentation, model.rowCount(parentIndex) should return the number of children in the current directory. (I'm running this under Ubuntu with Python 2.6) The QFileSystemModel docs say that it needs an instance of a Gui application, so I've also placed the above code in a QWidget as follows, but with the same result: import sys from PyQt4 import QtCore, QtGui class Widget(QtGui.QWidget): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) model = QtGui.QFileSystemModel() parentIndex = model.index(QtCore.QDir.currentPath()) print model.isDir(parentIndex) print model.data(parentIndex).toString() rows = model.rowCount(parentIndex) print rows def main(): app = QtGui.QApplication(sys.argv) widget = Widget() widget.show() sys.exit(app.exec_()) if __name__ == '__main__': main()
[ "I've solved it.\nThe reason to use QFileSystemModel as opposed to QDirModel is because QFileSystemModel loads the data from the filesystem in a separate thread. The problem with that is that if you try to print the number of children just after it's been constructed is that it won't have loaded the children yet. The way to fix the above code is to add the following:\nself.timer = QtCore.QTimer(self)\nself.timer.singleShot(1, self.printRowCount)\n\nto the end of the constructor, and add a printRowCount method which will print the correct number of children. Phew.\n", "Since you've already figured it out, just a couple of extra thoughts on what was going on with your model: QFileSystemModel::rowCount returns rows from the visibleChildren collection; I guess you're correctly identified the problem: at the time when you're checking row count it was not yet populated. I've changed your example without using timers; pls, check if it works for you:\nclass Widget(QtGui.QWidget):\n def __init__(self, parent=None):\n QtGui.QWidget.__init__(self, parent)\n\n self.model = QtGui.QFileSystemModel()\n self.model.setRootPath(QtCore.QDir.currentPath())\n\n def checkParent(self):\n parentIndex = self.model.index(QtCore.QDir.currentPath()) \n\n print self.model.isDir(parentIndex)\n print self.model.data(parentIndex).toString()\n\n rows = self.model.rowCount(parentIndex)\n print \"row count:\", rows\n\ndef main():\n app = QtGui.QApplication(sys.argv)\n widget = Widget()\n widget.show()\n app.processEvents(QtCore.QEventLoop.AllEvents) \n widget.checkParent()\n sys.exit(app.exec_())\n\nif __name__ == '__main__':\n main()\n\nI believe your code should work correctly on any UI event after widget constructed is shown on the screen\nregards\n" ]
[ 2, 1 ]
[]
[]
[ "pyqt", "python", "qfilesystemmodel", "qt" ]
stackoverflow_0002658467_pyqt_python_qfilesystemmodel_qt.txt
Q: Get localized language name from locale code How can I get localized language name by specified locale code in python? For example: >> get_language_name('ja') >> ('Japanese', u'日本語') A: The Babel package can help: >>> from babel import Locale >>> locale = Locale('ja', 'JP') >>> print locale.display_name 日本語 (日本) There is also PyICU, a Python wrapper for the ICU library.
Get localized language name from locale code
How can I get localized language name by specified locale code in python? For example: >> get_language_name('ja') >> ('Japanese', u'日本語')
[ "The Babel package can help:\n>>> from babel import Locale\n>>> locale = Locale('ja', 'JP')\n>>> print locale.display_name\n日本語 (日本)\n\nThere is also PyICU, a Python wrapper for the ICU library.\n" ]
[ 13 ]
[]
[]
[ "locale", "python" ]
stackoverflow_0002657787_locale_python.txt
Q: Generate and merge data with python multiprocessing I have a list of starting data. I want to apply a function to the starting data that creates a few pieces of new data for each element in the starting data. Some pieces of the new data are the same and I want to remove them. The sequential version is essentially: def create_new_data_for(datum): """make a list of new data from some old datum""" return [datum.modified_copy(k) for k in datum.k_list] data = [some list of data] #some data to start with #generate a list of new data from the old data, we'll reduce it next newdata = [] for d in data: newdata.extend(create_new_data_for(d)) #now reduce the data under ".matches(other)" reduced = [] for d in newdata: for seen in reduced: if d.matches(seen): break #so we haven't seen anything like d yet seen.append(d) #now reduced is finished and is what we want! I want to speed this up with multiprocessing. I was thinking that I could use a multiprocessing.Queue for the generation. Each process would just put the stuff it creates on, and when the processes are reducing the data, they can just get the data from the Queue. But I'm not sure how to have the different process loop over reduced and modify it without any race conditions or other issues. What is the best way to do this safely? or is there a different way to accomplish this goal better? A: I would use a multiprocessing Lock (similar to a threading lock) which is provided in the std lib. Here's an example from the standard documentation. from multiprocessing import Process, Lock def f(l, i): l.acquire() print 'hello world', i l.release() if __name__ == '__main__': lock = Lock() for num in range(10): Process(target=f, args=(lock, num)).start() To avoid race conditions, be sure to call "mylock.acquire()" before doing any modification, and "mylock.release()" when you're done.
Generate and merge data with python multiprocessing
I have a list of starting data. I want to apply a function to the starting data that creates a few pieces of new data for each element in the starting data. Some pieces of the new data are the same and I want to remove them. The sequential version is essentially: def create_new_data_for(datum): """make a list of new data from some old datum""" return [datum.modified_copy(k) for k in datum.k_list] data = [some list of data] #some data to start with #generate a list of new data from the old data, we'll reduce it next newdata = [] for d in data: newdata.extend(create_new_data_for(d)) #now reduce the data under ".matches(other)" reduced = [] for d in newdata: for seen in reduced: if d.matches(seen): break #so we haven't seen anything like d yet seen.append(d) #now reduced is finished and is what we want! I want to speed this up with multiprocessing. I was thinking that I could use a multiprocessing.Queue for the generation. Each process would just put the stuff it creates on, and when the processes are reducing the data, they can just get the data from the Queue. But I'm not sure how to have the different process loop over reduced and modify it without any race conditions or other issues. What is the best way to do this safely? or is there a different way to accomplish this goal better?
[ "I would use a multiprocessing Lock (similar to a threading lock) which is provided in the std lib.\nHere's an example from the standard documentation.\nfrom multiprocessing import Process, Lock\n\ndef f(l, i):\n l.acquire()\n print 'hello world', i\n l.release()\n\nif __name__ == '__main__':\n lock = Lock()\n\n for num in range(10):\n Process(target=f, args=(lock, num)).start()\n\nTo avoid race conditions, be sure to call \"mylock.acquire()\" before doing any modification, and \"mylock.release()\" when you're done.\n" ]
[ 1 ]
[]
[]
[ "multiprocessing", "parallel_processing", "python" ]
stackoverflow_0002659588_multiprocessing_parallel_processing_python.txt
Q: Call to MATLAB function in a Python program Possible Duplicate: Calling MATLAB functions from python I wrote MATLAB code (that easily could be implemented as a function) that convert a series of BMP files to AVI files. I want a Python program to call to this program/function. How do I do it? A: Take a look at mlabwrap. Mlabwrap is a high-level Python-to-MATLAB® bridge that lets MATLAB look like a normal Python library.
Call to MATLAB function in a Python program
Possible Duplicate: Calling MATLAB functions from python I wrote MATLAB code (that easily could be implemented as a function) that convert a series of BMP files to AVI files. I want a Python program to call to this program/function. How do I do it?
[ "Take a look at mlabwrap. Mlabwrap is a high-level Python-to-MATLAB® bridge that lets MATLAB look like a normal Python library.\n" ]
[ 2 ]
[]
[]
[ "matlab", "python" ]
stackoverflow_0002659661_matlab_python.txt
Q: efficiently list items in tuples starting at end I'd like to list the items in a tuple in Python starting with the back and go to front. Similar to: foo_t = tuple(int(f) for f in foo) print foo, foo_t[len(foo_t)-1] ... I believe this should be possible without Try ...-4, except ...-3. Thoughts? suggestions? A: You can print tuple(reversed(foo_t)), or use list in lieu of tuple, or print ' '.join(str(x) for x in reversed(foo_t)) and many variants. You could also use foo_t[::-1], but I think the reversed builtin is more readable. A: First, a general tip: in Python you never need to write foo_t[len(foo_t)-1]. You can just write foo_t[-1] and Python will do the right thing. To answer your question, you could do: for foo in reversed(foo_t): print foo, # Omits the newline print # All done, now print the newline or: print ' '.join(map(str, reversed(foo_t)) In Python 3, it's as easy as: print(*reversed(foo_t))
efficiently list items in tuples starting at end
I'd like to list the items in a tuple in Python starting with the back and go to front. Similar to: foo_t = tuple(int(f) for f in foo) print foo, foo_t[len(foo_t)-1] ... I believe this should be possible without Try ...-4, except ...-3. Thoughts? suggestions?
[ "You can print tuple(reversed(foo_t)), or use list in lieu of tuple, or \nprint ' '.join(str(x) for x in reversed(foo_t))\n\nand many variants. You could also use foo_t[::-1], but I think the reversed builtin is more readable.\n", "First, a general tip: in Python you never need to write foo_t[len(foo_t)-1]. You can just write foo_t[-1] and Python will do the right thing.\nTo answer your question, you could do:\nfor foo in reversed(foo_t):\n print foo, # Omits the newline\nprint # All done, now print the newline\n\nor:\nprint ' '.join(map(str, reversed(foo_t))\n\nIn Python 3, it's as easy as:\nprint(*reversed(foo_t))\n\n" ]
[ 6, 2 ]
[]
[]
[ "python", "tuples" ]
stackoverflow_0002659556_python_tuples.txt
Q: Idiomatic Python: 'times' loop Say I have a function foo that I want to call n times. In Ruby, I would write: n.times { foo } In Python, I could write: for _ in xrange(n): foo() But that seems like a hacky way of doing things. My question: Is there an idiomatic way of doing this in Python? A: You've already shown the idiomatic way: for _ in range(n): # or xrange if you are on 2.X foo() Not sure what is "hackish" about this. If you have a more specific use case in mind, please provide more details, and there might be something better suited to what you are doing. A: If you want the times method, and you need to use it on your own functions, try this: def times(self, n, *args, **kwargs): for _ in range(n): self.__call__(*args, **kwargs) import new def repeatable(func): func.times = new.instancemethod(times, func, func.__class__) return func now add a @repeatable decorator to any method you need a times method on: @repeatable def foo(bar): print bar foo.times(4, "baz") #outputs 4 lines of "baz" A: Fastest, cleanest is itertools.repeat: import itertools for _ in itertools.repeat(None, n): foo() A: The question pre-supposes that calling foo() n times is an a priori necessary thing. Where did n come from? Is it the length of something iterable? Then iterate over the iterable. As I am picking up Python, I find that I'm using few to no arbitrary values; there is some more salient meaning behind your n that got lost when it became an integer. Earlier today I happened upon Nicklaus Wirth's provocative paper for IEEE Computer entitled Good Ideas - Through the Looking Glass (archived version for future readers). In section 4 he brings a different slant on programming constructs that everyone (including himself) has taken for granted but that hold expressive flaws: "The generality of Algol’s for statement should have been a warning signal to all future designers to always keep the primary purpose of a construct in mind, and to be weary of exaggerated generality and complexity, which may easily become counter-productive." The algol for is equivalent to the C/Java for, it just does too much. That paper is a useful read if only because it makes one not take for granted so much that we so readily do. So perhaps a better question is "Why would you need a loop that executes an arbitrary number of times?"
Idiomatic Python: 'times' loop
Say I have a function foo that I want to call n times. In Ruby, I would write: n.times { foo } In Python, I could write: for _ in xrange(n): foo() But that seems like a hacky way of doing things. My question: Is there an idiomatic way of doing this in Python?
[ "You've already shown the idiomatic way:\nfor _ in range(n): # or xrange if you are on 2.X\n foo()\n\nNot sure what is \"hackish\" about this. If you have a more specific use case in mind, please provide more details, and there might be something better suited to what you are doing.\n", "If you want the times method, and you need to use it on your own functions, try this:\ndef times(self, n, *args, **kwargs):\n for _ in range(n):\n self.__call__(*args, **kwargs)\n\nimport new\ndef repeatable(func):\n func.times = new.instancemethod(times, func, func.__class__)\n return func\n\nnow add a @repeatable decorator to any method you need a times method on:\n@repeatable\ndef foo(bar):\n print bar\n\nfoo.times(4, \"baz\") #outputs 4 lines of \"baz\"\n\n", "Fastest, cleanest is itertools.repeat:\nimport itertools\n\nfor _ in itertools.repeat(None, n):\n foo()\n\n", "The question pre-supposes that calling foo() n times is an a priori necessary thing. Where did n come from? Is it the length of something iterable? Then iterate over the iterable. As I am picking up Python, I find that I'm using few to no arbitrary values; there is some more salient meaning behind your n that got lost when it became an integer.\nEarlier today I happened upon Nicklaus Wirth's provocative paper for IEEE Computer entitled Good Ideas - Through the Looking Glass (archived version for future readers). In section 4 he brings a different slant on programming constructs that everyone (including himself) has taken for granted but that hold expressive flaws:\n\n\"The generality of Algol’s for\n statement should have been a warning\n signal to all future designers to\n always keep the primary purpose of a\n construct in mind, and to be weary of\n exaggerated generality and complexity,\n which may easily become\n counter-productive.\"\n\nThe algol for is equivalent to the C/Java for, it just does too much. That paper is a useful read if only because it makes one not take for granted so much that we so readily do. So perhaps a better question is \"Why would you need a loop that executes an arbitrary number of times?\"\n" ]
[ 44, 17, 16, 10 ]
[]
[]
[ "idioms", "loops", "python" ]
stackoverflow_0002657068_idioms_loops_python.txt
Q: django filebrowser extensions problem I've set django filebrowser's debug to True and wrote the extension restrictions in the model. pdf = FileBrowseField("PDF", max_length=200, directory="documents/", extensions=['.pdf', '.doc', '.txt'], format='Document', blank=True, null=True) In django admin it shows correctly with debug info. Directory documents/ Extensions ['.pdf', '.doc', '.txt'] Format Document But when I call the filebrowser, it allows all file extensions to be uploaded. How can I restrict filebrowser to upload only certain filetypes that I want? Thanks everyone A: In filebrowser/fb_seettings define them as a dictionary called EXTENSIONS. EXTENSIONS = { 'Folder':[''], 'Image':['.jpg', '.jpeg', '.gif','.png','.tif','.tiff'], 'Zip':['.zip', '.rar'], 'Video':['.mov','.wmv','.mpeg','.mpg','.avi','.rm'], 'Document':['.pdf','.doc','.rtf','.txt','.xls','.csv'], 'Sound':['.mp3','.mp4','.wav','.aiff','.midi'], 'Code':['.html','.py','.js','.css'] } Edit: If you want if in your FileBrowserField: pdf = FileBrowseField("PDF", max_length=200, initial_directory="documents/", extensions_allowed={'Documents':['.pdf', '.doc', '.txt']}, format="Documents", blank=True, null=True)
django filebrowser extensions problem
I've set django filebrowser's debug to True and wrote the extension restrictions in the model. pdf = FileBrowseField("PDF", max_length=200, directory="documents/", extensions=['.pdf', '.doc', '.txt'], format='Document', blank=True, null=True) In django admin it shows correctly with debug info. Directory documents/ Extensions ['.pdf', '.doc', '.txt'] Format Document But when I call the filebrowser, it allows all file extensions to be uploaded. How can I restrict filebrowser to upload only certain filetypes that I want? Thanks everyone
[ "In filebrowser/fb_seettings define them as a dictionary called EXTENSIONS.\nEXTENSIONS = {\n 'Folder':[''],\n 'Image':['.jpg', '.jpeg', '.gif','.png','.tif','.tiff'],\n 'Zip':['.zip', '.rar'],\n 'Video':['.mov','.wmv','.mpeg','.mpg','.avi','.rm'],\n 'Document':['.pdf','.doc','.rtf','.txt','.xls','.csv'],\n 'Sound':['.mp3','.mp4','.wav','.aiff','.midi'],\n 'Code':['.html','.py','.js','.css']\n}\n\nEdit: If you want if in your FileBrowserField:\npdf = FileBrowseField(\"PDF\", max_length=200, initial_directory=\"documents/\", extensions_allowed={'Documents':['.pdf', '.doc', '.txt']}, format=\"Documents\", blank=True, null=True)\n\n" ]
[ 1 ]
[]
[]
[ "django", "django_filebrowser", "python", "uploadify" ]
stackoverflow_0002659787_django_django_filebrowser_python_uploadify.txt
Q: Can't parse a 1904 date in ARPA format (email date) I'm processing an IMAP mailbox and running into trouble parsing the dates using the mxDateTime package. In particular, early dates like "Fri, 1 Jan 1904 00:43:25 -0400" is causing trouble: >>> import mx.DateTime >>> import mx.DateTime.ARPA >>> mx.DateTime.ARPA.ParseDateTimeUTC("Fri, 1 Jan 1904 00:43:25 -0400").gmtoffset() Traceback (most recent call last): File "<interactive input>", line 1, in <module> Error: cannot convert value to a time value >>> mx.DateTime.ARPA.ParseDateTimeUTC("Thu, 1 Jan 2009 00:43:25 -0400").gmtoffset() <mx.DateTime.DateTimeDelta object for '-08:00:00.00' at 1497b60> >>> Note that an almost identical date from 2009 works fine. I can't find any description of date limitations in mxDateTime itself. Any ideas why this might be? Thx, Ramon A: Is it possible that the mxDateTime object only handles datetimes which fall after the Unix Epoch? A: Figured it out with the help of the eGenix folks. It is an Epoch problem, but you can work around it by manually extracting the timezone offset and then re-applying explicitly: >>> s = "Wed, 1 Jan 1969 00:43:25 -0400" >>> delta = ParseDateTime(s) - ParseDateTimeUTC(s) Traceback (most recent call last): File "<interactive input>", line 1, in <module> NameError: name 'ParseDateTime' is not defined >>> delta = mx.DateTime.ARPA.ParseDateTime(s) - mx.DateTime.ARPA.ParseDateTimeUTC(s) >>> mx.DateTime.ARPA.str(mx.DateTime.ARPA.ParseDateTime(s), delta) 'Wed, 01 Jan 1969 00:43:25 -0400' >>> Thanks everyone!
Can't parse a 1904 date in ARPA format (email date)
I'm processing an IMAP mailbox and running into trouble parsing the dates using the mxDateTime package. In particular, early dates like "Fri, 1 Jan 1904 00:43:25 -0400" is causing trouble: >>> import mx.DateTime >>> import mx.DateTime.ARPA >>> mx.DateTime.ARPA.ParseDateTimeUTC("Fri, 1 Jan 1904 00:43:25 -0400").gmtoffset() Traceback (most recent call last): File "<interactive input>", line 1, in <module> Error: cannot convert value to a time value >>> mx.DateTime.ARPA.ParseDateTimeUTC("Thu, 1 Jan 2009 00:43:25 -0400").gmtoffset() <mx.DateTime.DateTimeDelta object for '-08:00:00.00' at 1497b60> >>> Note that an almost identical date from 2009 works fine. I can't find any description of date limitations in mxDateTime itself. Any ideas why this might be? Thx, Ramon
[ "Is it possible that the mxDateTime object only handles datetimes which fall after the Unix Epoch?\n", "Figured it out with the help of the eGenix folks. It is an Epoch problem, but you can work around it by manually extracting the timezone offset and then re-applying explicitly:\n>>> s = \"Wed, 1 Jan 1969 00:43:25 -0400\"\n>>> delta = ParseDateTime(s) - ParseDateTimeUTC(s)\nTraceback (most recent call last):\n File \"<interactive input>\", line 1, in <module>\n NameError: name 'ParseDateTime' is not defined\n>>> delta = mx.DateTime.ARPA.ParseDateTime(s) - mx.DateTime.ARPA.ParseDateTimeUTC(s)\n>>> mx.DateTime.ARPA.str(mx.DateTime.ARPA.ParseDateTime(s), delta)\n'Wed, 01 Jan 1969 00:43:25 -0400'\n>>>\n\nThanks everyone!\n" ]
[ 2, 0 ]
[]
[]
[ "datetime", "email", "parsing", "python" ]
stackoverflow_0002648992_datetime_email_parsing_python.txt
Q: pylibmc: undefined symbol: memcached_server_list There is a problem when I used the pylibmc. When I "import pylibmc", then I'll get some error following: ImportError: /usr/local/python2.6/lib/python2.6/site-packages/_pylibmc.so: undefined symbol: memcached_server_list. My enviroment are Python 2.6.5, libmemcached 0.39, memcached 1.4.5 So, how can I solve it? Thanks very much. UPDATE 1: I read the pylibmc doc again, and found this: libmemcached 0.32 or later (last test with 0.38). Then I guest maybe my libmemcached is too newer to avaliable. UPDATE 2: I test the libmemcached 0.38, there is another error in _pylibmc.so: Undefined symbol: memcached_server_count. A: There appears to be some confusion about the symbol memcached_server_list: libmemcached 0.38 exposes it, but 0.39 does not. The symbol has even been removed from the documentation. pylibmc relies on memcached_server_list for its get_stats() method. I suspect pylibmc should be using memcached_server_cursor instead. So I think we can say that pylibmc 1.0 requires libmemcached <= 0.38. A: Sounds like linker issues. What system is this on? How is _pylibmc.so linked to libmemcached.so? Can you provide the commands run by your build phase, and perhaps the ldd output? A: I was having the same problem and I got it working by using libmemcached 0.34 and then setting the environment variable LD_LIBRARY_PATH to /usr/local/lib (where the libmemcache library was stored).
pylibmc: undefined symbol: memcached_server_list
There is a problem when I used the pylibmc. When I "import pylibmc", then I'll get some error following: ImportError: /usr/local/python2.6/lib/python2.6/site-packages/_pylibmc.so: undefined symbol: memcached_server_list. My enviroment are Python 2.6.5, libmemcached 0.39, memcached 1.4.5 So, how can I solve it? Thanks very much. UPDATE 1: I read the pylibmc doc again, and found this: libmemcached 0.32 or later (last test with 0.38). Then I guest maybe my libmemcached is too newer to avaliable. UPDATE 2: I test the libmemcached 0.38, there is another error in _pylibmc.so: Undefined symbol: memcached_server_count.
[ "There appears to be some confusion about the symbol memcached_server_list: libmemcached 0.38 exposes it, but 0.39 does not. The symbol has even been removed from the documentation. pylibmc relies on memcached_server_list for its get_stats() method. I suspect pylibmc should be using memcached_server_cursor instead.\nSo I think we can say that pylibmc 1.0 requires libmemcached <= 0.38.\n", "Sounds like linker issues. What system is this on? How is _pylibmc.so linked to libmemcached.so? Can you provide the commands run by your build phase, and perhaps the ldd output?\n", "I was having the same problem and I got it working by using libmemcached 0.34 and then setting the environment variable LD_LIBRARY_PATH to /usr/local/lib (where the libmemcache library was stored).\n" ]
[ 1, 0, 0 ]
[]
[]
[ "memcached", "python" ]
stackoverflow_0002612515_memcached_python.txt
Q: In python, how do I drag and drop 1 or more files onto my script as arguments with absolute path? (for windows, linux, and mac) I am writing a simple Python script with no GUI. I want to be able to drag and drop multiple files onto my python script and have access to their absolute paths inside of the script. How do I do this in Mac, Linux, and windows? For times sake, just Mac will be fine for now. I've googled this question and only found one related one but it was too confusing. I am currently running Mac OS X Snow Leopard. Any help is much appreciated. Thanks! A: For OS X, the most straightforward way is to have your script run as part of an application bundle (.app). You can use something like py2app to build a python application. Another approach might be to use Automator or AppleScript to create an app that takes the input parameters and passes them to the python script. An example of Automator usage is here. A: Usually when you drag a file onto a script/executable, the OS passes the path to that file as a command-line argument. Check sys.argv A: This really is independent of python. It depends entirely on which file browser you're using and how it supports drag and drop.
In python, how do I drag and drop 1 or more files onto my script as arguments with absolute path? (for windows, linux, and mac)
I am writing a simple Python script with no GUI. I want to be able to drag and drop multiple files onto my python script and have access to their absolute paths inside of the script. How do I do this in Mac, Linux, and windows? For times sake, just Mac will be fine for now. I've googled this question and only found one related one but it was too confusing. I am currently running Mac OS X Snow Leopard. Any help is much appreciated. Thanks!
[ "For OS X, the most straightforward way is to have your script run as part of an application bundle (.app). You can use something like py2app to build a python application. Another approach might be to use Automator or AppleScript to create an app that takes the input parameters and passes them to the python script. An example of Automator usage is here.\n", "Usually when you drag a file onto a script/executable, the OS passes the path to that file as a command-line argument. Check sys.argv\n", "This really is independent of python. It depends entirely on which file browser you're using and how it supports drag and drop.\n" ]
[ 3, 1, 1 ]
[]
[]
[ "arguments", "drag_and_drop", "python", "scripting" ]
stackoverflow_0002660291_arguments_drag_and_drop_python_scripting.txt
Q: How do I view this in an easy format to read? (JSON) https://search.twitter.com/search.json?q=doug How do I read this like VIEW SOURCE, so that I know what I'm looking at? Is there a website that can prettify it for me? BTW, I use python A: Parse it, then use pprint: data = json.load(...) pprint.pprint(data) A: You can also use something like http://hurl.it. A: Personally, I use JSONView for Firefox, which does a good job formatting and colour-highlighting JSON.
How do I view this in an easy format to read? (JSON)
https://search.twitter.com/search.json?q=doug How do I read this like VIEW SOURCE, so that I know what I'm looking at? Is there a website that can prettify it for me? BTW, I use python
[ "Parse it, then use pprint:\ndata = json.load(...)\npprint.pprint(data)\n\n", "You can also use something like http://hurl.it.\n", "Personally, I use JSONView for Firefox, which does a good job formatting and colour-highlighting JSON.\n" ]
[ 2, 1, 1 ]
[ "Insert a carriage return after every comma with your favorite search and replace utility. If you know Python then you shouldn't have any trouble getting it even prettier than that. \n" ]
[ -1 ]
[ "http", "json", "python", "twitter", "xml" ]
stackoverflow_0002576265_http_json_python_twitter_xml.txt
Q: Why do socket.makefile objects fail after the first read for UDP sockets? I'm using the socket.makefile method to create a file-like object on a UDP socket for the purposes of reading. When I receive a UDP packet, I can read the entire contents of the packet all at once by using the read method, but if I try to split it up into multiple reads, my program hangs. Here's a program which demonstrates this problem: import socket from sys import argv SERVER_ADDR = ("localhost", 12345) sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind(SERVER_ADDR) f = sock.makefile("rb") sock.sendto("HelloWorld", SERVER_ADDR) if "--all" in argv: print f.read(10) else: print f.read(5) print f.read(5) If I run the above program with the --all option, then it works perfectly and prints HelloWorld. If I run it without that option, it prints Hello and then hangs on the second read. I do not have this problem with socket.makefile objects when using TCP sockets. Why is this happening and what can I do to stop it? A: You're sending 1 packet, but call read twice. The 2. read will not read anything as there's no new packets to read/receive. read on a udp socket reads one packet and discards the rest of the data if you didn't read all of the bytes. UDP is not stream oriented, it is message/datagram oriented. UDP does not map to the concept of a file. a "file" is just a stream of bytes, not a collection of packets, and it has an end. That's much like TCP, you read bytes from it - it does not matter how many reads you use to read the data, and you can detect the end of it.
Why do socket.makefile objects fail after the first read for UDP sockets?
I'm using the socket.makefile method to create a file-like object on a UDP socket for the purposes of reading. When I receive a UDP packet, I can read the entire contents of the packet all at once by using the read method, but if I try to split it up into multiple reads, my program hangs. Here's a program which demonstrates this problem: import socket from sys import argv SERVER_ADDR = ("localhost", 12345) sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind(SERVER_ADDR) f = sock.makefile("rb") sock.sendto("HelloWorld", SERVER_ADDR) if "--all" in argv: print f.read(10) else: print f.read(5) print f.read(5) If I run the above program with the --all option, then it works perfectly and prints HelloWorld. If I run it without that option, it prints Hello and then hangs on the second read. I do not have this problem with socket.makefile objects when using TCP sockets. Why is this happening and what can I do to stop it?
[ "You're sending 1 packet, but call read twice. The 2. read will not read anything as there's no new packets to read/receive. read on a udp socket reads one packet and discards the rest of the data if you didn't read all of the bytes. UDP is not stream oriented, it is message/datagram oriented.\nUDP does not map to the concept of a file. a \"file\" is just a stream of bytes, not a collection of packets, and it has an end. That's much like TCP, you read bytes from it - it does not matter how many reads you use to read the data, and you can detect the end of it.\n" ]
[ 2 ]
[]
[]
[ "python", "sockets", "udp" ]
stackoverflow_0002660389_python_sockets_udp.txt
Q: django select max field from mysql when column is varchar Using Django 1.1, I am trying to select the maximum value from a varchar column (in MySQL.) The data stored in the column looks like: 9001 9002 9017 9624 10104 11823 (In reality, the numbers are much bigger than this.) This worked until the numbers incremented above 10000: Feedback.objects.filter(est__pk=est_id).aggregate(sid=Max('sid')) Now, that same line would return 9624 instead of 11823. I'm able to run a query directly in the DB that gives me what I need, but I can't figure out the best way to do this in Django. The query would be: select max(sid+0) from Feedback; Any help would be much appreciated. Thanks! A: In the spirit of "any help would be much appreciated", you should figure out why it stopped working inside Django (but apparently not inside MySQL) - at 10,000. What is the query that is being generated? See this question for how to find that out. I suspect it is because you're adding the +0 to make the sort numeric in your query. I don't think Django supports this naturally, so you have two options: People will undoubtedly want to know why you're storing a number and asking for the maximum of it in a VARCHAR column. You could change the column to a numeric data type. You could do what you have to do whenever you want to make some custom SQL call and Django doesn't yet support it: write your own raw SQL. Edit: You could also patch Django, but this might be a MySQL specific thing, so option #2 is probably your best bet.
django select max field from mysql when column is varchar
Using Django 1.1, I am trying to select the maximum value from a varchar column (in MySQL.) The data stored in the column looks like: 9001 9002 9017 9624 10104 11823 (In reality, the numbers are much bigger than this.) This worked until the numbers incremented above 10000: Feedback.objects.filter(est__pk=est_id).aggregate(sid=Max('sid')) Now, that same line would return 9624 instead of 11823. I'm able to run a query directly in the DB that gives me what I need, but I can't figure out the best way to do this in Django. The query would be: select max(sid+0) from Feedback; Any help would be much appreciated. Thanks!
[ "In the spirit of \"any help would be much appreciated\", you should figure out why it stopped working inside Django (but apparently not inside MySQL) - at 10,000.\nWhat is the query that is being generated? See this question for how to find that out.\nI suspect it is because you're adding the +0 to make the sort numeric in your query. I don't think Django supports this naturally, so you have two options:\n\nPeople will undoubtedly want to know why you're storing a number and asking for the maximum of it in a VARCHAR column. You could change the column to a numeric data type.\nYou could do what you have to do whenever you want to make some custom SQL call and Django doesn't yet support it: write your own raw SQL.\nEdit: You could also patch Django, but this might be a MySQL specific thing, so option #2 is probably your best bet.\n\n" ]
[ 1 ]
[]
[]
[ "django", "max", "mysql", "python", "varchar" ]
stackoverflow_0002660489_django_max_mysql_python_varchar.txt
Q: reuse generators I want to check the central limit with dices. Roll D dices. Sum the results. Repeat the same thing for N times. Change D and repeat. There's no need to store random values so I want to use only generators. The problem is that the generators are consumed; I can't reuse them many times. Now my code uses explicit for and I don't like it. dice_numbers = (1, 2, 10, 100, 1000) repetitions = 10000 for dice_number in dice_numbers: # how many dice to sum sum_container = [] for r in range(repetitions): rool_sum = sum((random.randint(1,6) for _ in range(dice_number))) sum_container.append(rool_sum) plot_histogram(sum_container) I want to create something like for r in repetitions: rools_generator = (random.randint(1,6) for _ in range(dice_number) sum_generator = (sum(rools_generator) for _ in range(r)) but the second time I reuse rools_generator it is consumed. Do I need to construct a generator class? A: You could do it like this: for r in repetitions: make_rools_generator = lambda: (random.randint(1,6) for _ in range(dice_number)) sum_generator = (sum(make_rools_generator()) for _ in range(r)) This creates a function called make_rools_generator that, when called, creates a new generator that supplied the dice rolls. A: I think you may be working too hard, and you are definitely creating unnecessary lists with range(). In the spirit of being a little more explicit than the genexprs above: import random def die_roller(throws): """generates throws rolls of a die""" for _ in xrange(throws): yield random.randint(1, 6) roller = die_roller(10) print type(roller) # => <type 'generator'> print list(roller) # => [6, 6, 3, 1, 6, 3, 1, 5, 4, 4] print sum(roller) # roller was exhausted, generates null list thus 0 sum big_roller = die_roller(10**5) print sum(big_roller) # => 3500238 I think that gets you the rudiments of what you are looking for. A: What about this: list(list((sum((random.randint(1,6) for _ in range(dn))) for __ in range(10000))) for dn in (1, 2, 10, 100, 1000))
reuse generators
I want to check the central limit with dices. Roll D dices. Sum the results. Repeat the same thing for N times. Change D and repeat. There's no need to store random values so I want to use only generators. The problem is that the generators are consumed; I can't reuse them many times. Now my code uses explicit for and I don't like it. dice_numbers = (1, 2, 10, 100, 1000) repetitions = 10000 for dice_number in dice_numbers: # how many dice to sum sum_container = [] for r in range(repetitions): rool_sum = sum((random.randint(1,6) for _ in range(dice_number))) sum_container.append(rool_sum) plot_histogram(sum_container) I want to create something like for r in repetitions: rools_generator = (random.randint(1,6) for _ in range(dice_number) sum_generator = (sum(rools_generator) for _ in range(r)) but the second time I reuse rools_generator it is consumed. Do I need to construct a generator class?
[ "You could do it like this:\nfor r in repetitions:\n make_rools_generator = lambda: (random.randint(1,6) for _ in range(dice_number))\n sum_generator = (sum(make_rools_generator()) for _ in range(r))\n\nThis creates a function called make_rools_generator that, when called, creates a new generator that supplied the dice rolls.\n", "I think you may be working too hard, and you are definitely creating unnecessary lists with range(). In the spirit of being a little more explicit than the genexprs above:\nimport random\n\ndef die_roller(throws):\n \"\"\"generates throws rolls of a die\"\"\"\n for _ in xrange(throws):\n yield random.randint(1, 6)\n\nroller = die_roller(10)\nprint type(roller) # => <type 'generator'>\nprint list(roller) # => [6, 6, 3, 1, 6, 3, 1, 5, 4, 4]\nprint sum(roller) # roller was exhausted, generates null list thus 0 sum\n\nbig_roller = die_roller(10**5)\nprint sum(big_roller) # => 3500238\n\nI think that gets you the rudiments of what you are looking for.\n", "What about this:\nlist(list((sum((random.randint(1,6) for _ in range(dn))) for __ in range(10000))) for dn in (1, 2, 10, 100, 1000))\n\n" ]
[ 5, 2, 0 ]
[]
[]
[ "generator", "python" ]
stackoverflow_0002660350_generator_python.txt
Q: Adding a method to a function object at runtime I read a question earlier asking if there was a times method in Python, that would allow a function to be called n times in a row. Everyone suggested for _ in range(n): foo() but I wanted to try and code a different solution using a function decorator. Here's what I have: def times(self, n, *args, **kwargs): for _ in range(n): self.__call__(*args, **kwargs) import new def repeatable(func): func.times = new.instancemethod(times, func, func.__class__) @repeatable def threeArgs(one, two, three): print one, two, three threeArgs.times(7, "one", two="rawr", three="foo") When I run the program, I get the following exception: Traceback (most recent call last): File "", line 244, in run_nodebug File "C:\py\repeatable.py", line 24, in threeArgs.times(7, "one", two="rawr", three="foo") AttributeError: 'NoneType' object has no attribute 'times' So I suppose the decorator didn't work? How can I fix this? A: Your decorator should return the function object: def repeatable(func): func.times = new.instancemethod(times, func, func.__class__) return func Now it returns nothing, so you actually change threeArgs in a None This is because this: @decorator def func(...): ... is more or less the same as: def func(...): .... func = decorator(func) A: You're missing a return func statement at the end of your repeatable decorator. A: Have you considered not adding it to specific functions and instead allowing its use with any function? def times(n, func, *args, **kwds): return [func(*args, **kwds) for _ in xrange(n)] (I'm returning a list of return values, but you could write it to ignore them, similar to the for-loop you have in the question.) Then where you would, with your version, use: threeArgs.times(7, "one", two="rawr", three="foo") You instead use: times(7, threeArgs, "one", two="rawr", three="foo")
Adding a method to a function object at runtime
I read a question earlier asking if there was a times method in Python, that would allow a function to be called n times in a row. Everyone suggested for _ in range(n): foo() but I wanted to try and code a different solution using a function decorator. Here's what I have: def times(self, n, *args, **kwargs): for _ in range(n): self.__call__(*args, **kwargs) import new def repeatable(func): func.times = new.instancemethod(times, func, func.__class__) @repeatable def threeArgs(one, two, three): print one, two, three threeArgs.times(7, "one", two="rawr", three="foo") When I run the program, I get the following exception: Traceback (most recent call last): File "", line 244, in run_nodebug File "C:\py\repeatable.py", line 24, in threeArgs.times(7, "one", two="rawr", three="foo") AttributeError: 'NoneType' object has no attribute 'times' So I suppose the decorator didn't work? How can I fix this?
[ "Your decorator should return the function object:\ndef repeatable(func):\n func.times = new.instancemethod(times, func, func.__class__)\n return func\n\nNow it returns nothing, so you actually change threeArgs in a None\nThis is because this:\n@decorator\ndef func(...):\n ...\n\nis more or less the same as:\ndef func(...):\n ....\nfunc = decorator(func)\n\n", "You're missing a return func statement at the end of your repeatable decorator.\n", "Have you considered not adding it to specific functions and instead allowing its use with any function?\ndef times(n, func, *args, **kwds):\n return [func(*args, **kwds) for _ in xrange(n)]\n\n(I'm returning a list of return values, but you could write it to ignore them, similar to the for-loop you have in the question.)\nThen where you would, with your version, use:\nthreeArgs.times(7, \"one\", two=\"rawr\", three=\"foo\")\n\nYou instead use:\ntimes(7, threeArgs, \"one\", two=\"rawr\", three=\"foo\")\n\n" ]
[ 3, 1, 0 ]
[]
[]
[ "decorator", "function", "python" ]
stackoverflow_0002660093_decorator_function_python.txt
Q: Django: Named URLs / Same Template, Different Named URL I have a webapp that lists all of my artists, albums and songs when the appropriate link is clicked. I make extensive use of generic views (object_list/detail) and named urls but I am coming across an annoyance. I have three templates that pretty much output the exact same html that look just like this: {% extends "base.html" %} {% block content %} <div id="content"> <ul id="starts-with"> {% for starts_with in starts_with_list %} <li><a href="{% url song_list_x starts_with %}">{{ starts_with|upper }}</a></li> {% endfor %} </ul> <ul> {% for song in songs_list %} <li>{{ song.title }}</li> {% endfor %} </ul> </div> {% endblock content %} My artist and album template look pretty much the same and I'd like to combine the three template's into one. The fact that my variables start with song can easily be changed to the default obj. It's my <ul id="starts-with"> named url I don't know how to correct. Obviously I want it to link to a specific album/artist/song using the named urls in my urls.py but I don't know how to make it context aware. Any suggestions? urls.py: urlpatterns = patterns('tlkmusic.apps.tlkmusic_base.views', # (r'^$', index), url(r'^artists/$', artist_list, name='artist_list'), url(r'^artists/(?P<starts_with>\w)/$', artist_list, name='artist_list_x'), url(r'^artist/(?P<artist_id>\d+)/$', artist_detail, name='artist_detail'), url(r'^albums/$', album_list, name='album_list'), url(r'^albums/(?P<starts_with>\w)/$', album_list, name='album_list_x'), url(r'^album/(?P<album_id>\w)/$', album_detail, name='album_detail'), url(r'^songs/$', song_list, name='song_list'), url(r'^songs/(?P<starts_with>\w)/$', song_list, name='song_list_x'), url(r'^song/(?P<song_id>\w)/$', song_detail, name='song_detail'), ) A: You could define url patterns for a generic object_type instead of individually for artists, albums and songs: urlpatterns = patterns('tlkmusic.apps.tlkmusic_base.views', # (r'^$', index), url(r'^(?P<object_type>\w+)/$', music_object_list, name='music_object_list'), url(r'^(?P<object_type>\w+)/(?P<starts_with>\w)/$', music_object_list, name='music_object_list_x'), url(r'^(?P<object_type>\w+)/(?P<object_id>\d+)/$', music_object_detail, name='music_object_detail'), ) Then in your template, your url tag becomes {% url music_object_list_x object_type starts_with %} * You may find you only need one view, music_object_list. If you find you need different functions for each object type, then call the individual functions in music_object_list. def music_object_list(request, object_type, starts_with=None): if object_type == 'artists': return artist_list(request, starts_with=starts_with) elif object_type == 'albums': return album_list(request, starts_with=starts_with) ... If you are using django.views.generic.list_detail.object_list, then remember to add object_type to the extra_context dictionary. This will add object_type to the template context, allowing the url tag to work. extra_context = {'object_type': 'songs', ...} * This is the new url tag syntax for Django 1.2. For older versions you would use a comma. {% url music_object_list_x object_type,starts_with %} See the docs (Current, 1.1) for more information
Django: Named URLs / Same Template, Different Named URL
I have a webapp that lists all of my artists, albums and songs when the appropriate link is clicked. I make extensive use of generic views (object_list/detail) and named urls but I am coming across an annoyance. I have three templates that pretty much output the exact same html that look just like this: {% extends "base.html" %} {% block content %} <div id="content"> <ul id="starts-with"> {% for starts_with in starts_with_list %} <li><a href="{% url song_list_x starts_with %}">{{ starts_with|upper }}</a></li> {% endfor %} </ul> <ul> {% for song in songs_list %} <li>{{ song.title }}</li> {% endfor %} </ul> </div> {% endblock content %} My artist and album template look pretty much the same and I'd like to combine the three template's into one. The fact that my variables start with song can easily be changed to the default obj. It's my <ul id="starts-with"> named url I don't know how to correct. Obviously I want it to link to a specific album/artist/song using the named urls in my urls.py but I don't know how to make it context aware. Any suggestions? urls.py: urlpatterns = patterns('tlkmusic.apps.tlkmusic_base.views', # (r'^$', index), url(r'^artists/$', artist_list, name='artist_list'), url(r'^artists/(?P<starts_with>\w)/$', artist_list, name='artist_list_x'), url(r'^artist/(?P<artist_id>\d+)/$', artist_detail, name='artist_detail'), url(r'^albums/$', album_list, name='album_list'), url(r'^albums/(?P<starts_with>\w)/$', album_list, name='album_list_x'), url(r'^album/(?P<album_id>\w)/$', album_detail, name='album_detail'), url(r'^songs/$', song_list, name='song_list'), url(r'^songs/(?P<starts_with>\w)/$', song_list, name='song_list_x'), url(r'^song/(?P<song_id>\w)/$', song_detail, name='song_detail'), )
[ "You could define url patterns for a generic object_type instead of individually for artists, albums and songs:\nurlpatterns = patterns('tlkmusic.apps.tlkmusic_base.views',\n # (r'^$', index),\n url(r'^(?P<object_type>\\w+)/$', music_object_list, name='music_object_list'),\n url(r'^(?P<object_type>\\w+)/(?P<starts_with>\\w)/$', music_object_list, name='music_object_list_x'),\n url(r'^(?P<object_type>\\w+)/(?P<object_id>\\d+)/$', music_object_detail, name='music_object_detail'),\n\n)\n\nThen in your template, your url tag becomes\n{% url music_object_list_x object_type starts_with %} *\n\nYou may find you only need one view, music_object_list. If you find you need different functions for each object type, then call the individual functions in music_object_list. \ndef music_object_list(request, object_type, starts_with=None):\n if object_type == 'artists':\n return artist_list(request, starts_with=starts_with)\n elif object_type == 'albums':\n return album_list(request, starts_with=starts_with)\n ...\n\nIf you are using django.views.generic.list_detail.object_list, then remember to add object_type to the extra_context dictionary. This will add object_type to the template context, allowing the url tag to work.\nextra_context = {'object_type': 'songs', ...}\n\n\n* This is the new url tag syntax for Django 1.2. For older versions you would use a comma.\n{% url music_object_list_x object_type,starts_with %}\n\nSee the docs (Current, 1.1) for more information\n" ]
[ 3 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0002660404_django_django_templates_python.txt
Q: Optimizing Python code with many attribute and dictionary lookups I have written a program in Python which spends a large amount of time looking up attributes of objects and values from dictionary keys. I would like to know if there's any way I can optimize these lookup times, potentially with a C extension, to reduce the time of execution, or if I need to simply re-implement the program in a compiled language. The program implements some algorithms using a graph. It runs prohibitively slowly on our data sets, so I profiled the code with cProfile using a reduced data set that could actually complete. The vast majority of the time is being burned in one function, and specifically in two statements, generator expressions, within the function: The generator expression at line 202 is neighbors_in_selected_nodes = (neighbor for neighbor in node_neighbors if neighbor in selected_nodes) and the generator expression at line 204 is neighbor_z_scores = (interaction_graph.node[neighbor]['weight'] for neighbor in neighbors_in_selected_nodes) The source code for this function of context provided below. selected_nodes is a set of nodes in the interaction_graph, which is a NetworkX Graph instance. node_neighbors is an iterator from Graph.neighbors_iter(). Graph itself uses dictionaries for storing nodes and edges. Its Graph.node attribute is a dictionary which stores nodes and their attributes (e.g., 'weight') in dictionaries belonging to each node. Each of these lookups should be amortized constant time (i.e., O(1)), however, I am still paying a large penalty for the lookups. Is there some way which I can speed up these lookups (e.g., by writing parts of this as a C extension), or do I need to move the program to a compiled language? Below is the full source code for the function that provides the context; the vast majority of execution time is spent within this function. def calculate_node_z_prime( node, interaction_graph, selected_nodes ): """Calculates a z'-score for a given node. The z'-score is based on the z-scores (weights) of the neighbors of the given node, and proportional to the z-score (weight) of the given node. Specifically, we find the maximum z-score of all neighbors of the given node that are also members of the given set of selected nodes, multiply this z-score by the z-score of the given node, and return this value as the z'-score for the given node. If the given node has no neighbors in the interaction graph, the z'-score is defined as zero. Returns the z'-score as zero or a positive floating point value. :Parameters: - `node`: the node for which to compute the z-prime score - `interaction_graph`: graph containing the gene-gene or gene product-gene product interactions - `selected_nodes`: a `set` of nodes fitting some criterion of interest (e.g., annotated with a term of interest) """ node_neighbors = interaction_graph.neighbors_iter(node) neighbors_in_selected_nodes = (neighbor for neighbor in node_neighbors if neighbor in selected_nodes) neighbor_z_scores = (interaction_graph.node[neighbor]['weight'] for neighbor in neighbors_in_selected_nodes) try: max_z_score = max(neighbor_z_scores) # max() throws a ValueError if its argument has no elements; in this # case, we need to set the max_z_score to zero except ValueError, e: # Check to make certain max() raised this error if 'max()' in e.args[0]: max_z_score = 0 else: raise e z_prime = interaction_graph.node[node]['weight'] * max_z_score return z_prime Here are the top couple of calls according to cProfiler, sorted by time. ncalls tottime percall cumtime percall filename:lineno(function) 156067701 352.313 0.000 642.072 0.000 bpln_contextual.py:204(<genexpr>) 156067701 289.759 0.000 289.759 0.000 bpln_contextual.py:202(<genexpr>) 13963893 174.047 0.000 816.119 0.000 {max} 13963885 69.804 0.000 936.754 0.000 bpln_contextual.py:171(calculate_node_z_prime) 7116883 61.982 0.000 61.982 0.000 {method 'update' of 'set' objects} A: How about keeping the iteration order of interaction_graph.neighbors_iter(node) sorted (or partially sorted using collections.heapq)? Since you're just trying to find the max value, you can iterate node_neighbors in descending order, the first node that is in selected_node must be the max in selected_node. Second, how often will selected_node changes? If it changes rarely, you can save a lot of iterations by having a list of "interaction_graph.node[neighbor] for x in selected_node" instead of having to rebuild this list every time. EDIT: to reply on the comments A sort() would take O(n log n) Not necessarily, you're looking too much at your textbook. Despite what your textbook says, you can sometimes break the O(n log n) barrier by exploiting certain structure of your data. If you keep your list of neighbors in a naturally sorted data structure in the first place (e.g. heapq, binary tree), you don't need to re-sort at every iteration. Of course this is a space-time tradeoff, since you will need to store redundant lists of neighbors and there is code complexity to ensure that the list of neighbors is updated when the neighbors changes. Also, python's list.sort(), which uses timsort algorithm, is very fast for nearly sorted data (could average O(n) in certain cases). It still doesn't break O(n log n), that much has been proven to be mathematically impossible. You need to profile before dismissing a solution as not likely to improve performance. When doing extreme optimizations, you will likely find that in certain very special edge cases old and slow bubble sort may win over a glorified quicksort or mergesort. A: I don't see why your "weight" lookups have to be in the form of ["weight"] (nodes are dictionaries?) instead of .weight (nodes are objects). If your nodes are objects, and don't have a lot of fields, you can take advantage of the __slots__ directive to optimize their storage: class Node(object): # ... class stuff goes here ... __slots__ = ('weight',) # tuple of member names. EDIT: So I looked at the NetworkX link you provided, and there are several things that bother me. First is that, right at the top, the definition of "dictionary" is "FIXME". Overall, it seems insistent on using dictionaries, rather than using classes that can be subclassed, to store attributes. While attribute lookup on an object may be essentially a dictionary lookup, I don't see how working with an object can be worse. If anything, it could be better since an object attribute lookup is more likely to be optimized, because: object attribute lookups are so common, the keyspace for object attributes is far more restricted than for dictionary keys, thus an optimized comparison algorithm can be used in the search, and objects have the __slots__ optimization for exactly these cases, where you have an object with only a couple fields and need optimized access to them. I frequently use __slots__ on classes that represent coordinates, for example. A tree node would seem, to me, another obvious use. So that's why when I read: node A node can be any hashable Python object except None. I think, okay, no problem, but then immediately following is node attribute Nodes can have arbitrary Python objects assigned as attributes by using keyword/value pairs when adding a node or assigning to the G.node[n] attribute dictionary for the specified node n. I think, if a node needs attributes, why would it be stored separately? Why not just put it in the node? Is writing a class with contentString and weight members detrimental? Edges seem even crazier, since they're dictated to be tuples and not objects which you could subclass. So I'm rather lost as to the design decisions behind NetworkX. If you're stuck with it, I'd recommend moving attributes from those dictionaries into the actual nodes, or if that's not an option, using integers for keys into your attribute dictionary instead of strings, so searches use a much faster comparison algorithm. Finally, what if you combined your generators: neighbor_z_scores = (interaction_graph.node[neighbor]['weight'] for neighbor in node_neighbors if neighbor in selected_nodes) A: Try just directly accessing the dict and catch KeyErrors, it might be faster depending on your hit/miss ratio: # cache this object ignode = interaction_graph.node neighbor_z_scores = [] for neighbor in node_neighbors: try: neighbor_z_scores.append(ignode[neighbor]['weight']) except KeyError: pass or with the getdefault and list comprehension: sentinel = object() # cache this object ignode = interaction_graph.node neighbor_z_scores = (ignode[neighbor]['weight'] for neighbor in node_neighbors) # using identity testing, it's slightly faster neighbor_z_scores = (neighbor for neighbor in neighbor_z_scores if neighbor is not sentinel) A: Without looking deeply into your code, try adding a little speed with itertools. Add these at the module level: import itertools as it, operator as op GET_WEIGHT= op.attrgetter('weight') Change: neighbors_in_selected_nodes = (neighbor for neighbor in node_neighbors if neighbor in selected_nodes) into: neighbors_in_selected_nodes = it.ifilter(selected_node.__contains__, node_neighbors) and: neighbor_z_scores = (interaction_graph.node[neighbor]['weight'] for neighbor in neighbors_in_selected_nodes) into: neighbor_z_scores = ( it.imap( GET_WEIGHT, it.imap( interaction_graph.node.__getitem__, neighbors_in_selected_nodes) ) ) Do these help?
Optimizing Python code with many attribute and dictionary lookups
I have written a program in Python which spends a large amount of time looking up attributes of objects and values from dictionary keys. I would like to know if there's any way I can optimize these lookup times, potentially with a C extension, to reduce the time of execution, or if I need to simply re-implement the program in a compiled language. The program implements some algorithms using a graph. It runs prohibitively slowly on our data sets, so I profiled the code with cProfile using a reduced data set that could actually complete. The vast majority of the time is being burned in one function, and specifically in two statements, generator expressions, within the function: The generator expression at line 202 is neighbors_in_selected_nodes = (neighbor for neighbor in node_neighbors if neighbor in selected_nodes) and the generator expression at line 204 is neighbor_z_scores = (interaction_graph.node[neighbor]['weight'] for neighbor in neighbors_in_selected_nodes) The source code for this function of context provided below. selected_nodes is a set of nodes in the interaction_graph, which is a NetworkX Graph instance. node_neighbors is an iterator from Graph.neighbors_iter(). Graph itself uses dictionaries for storing nodes and edges. Its Graph.node attribute is a dictionary which stores nodes and their attributes (e.g., 'weight') in dictionaries belonging to each node. Each of these lookups should be amortized constant time (i.e., O(1)), however, I am still paying a large penalty for the lookups. Is there some way which I can speed up these lookups (e.g., by writing parts of this as a C extension), or do I need to move the program to a compiled language? Below is the full source code for the function that provides the context; the vast majority of execution time is spent within this function. def calculate_node_z_prime( node, interaction_graph, selected_nodes ): """Calculates a z'-score for a given node. The z'-score is based on the z-scores (weights) of the neighbors of the given node, and proportional to the z-score (weight) of the given node. Specifically, we find the maximum z-score of all neighbors of the given node that are also members of the given set of selected nodes, multiply this z-score by the z-score of the given node, and return this value as the z'-score for the given node. If the given node has no neighbors in the interaction graph, the z'-score is defined as zero. Returns the z'-score as zero or a positive floating point value. :Parameters: - `node`: the node for which to compute the z-prime score - `interaction_graph`: graph containing the gene-gene or gene product-gene product interactions - `selected_nodes`: a `set` of nodes fitting some criterion of interest (e.g., annotated with a term of interest) """ node_neighbors = interaction_graph.neighbors_iter(node) neighbors_in_selected_nodes = (neighbor for neighbor in node_neighbors if neighbor in selected_nodes) neighbor_z_scores = (interaction_graph.node[neighbor]['weight'] for neighbor in neighbors_in_selected_nodes) try: max_z_score = max(neighbor_z_scores) # max() throws a ValueError if its argument has no elements; in this # case, we need to set the max_z_score to zero except ValueError, e: # Check to make certain max() raised this error if 'max()' in e.args[0]: max_z_score = 0 else: raise e z_prime = interaction_graph.node[node]['weight'] * max_z_score return z_prime Here are the top couple of calls according to cProfiler, sorted by time. ncalls tottime percall cumtime percall filename:lineno(function) 156067701 352.313 0.000 642.072 0.000 bpln_contextual.py:204(<genexpr>) 156067701 289.759 0.000 289.759 0.000 bpln_contextual.py:202(<genexpr>) 13963893 174.047 0.000 816.119 0.000 {max} 13963885 69.804 0.000 936.754 0.000 bpln_contextual.py:171(calculate_node_z_prime) 7116883 61.982 0.000 61.982 0.000 {method 'update' of 'set' objects}
[ "How about keeping the iteration order of interaction_graph.neighbors_iter(node) sorted (or partially sorted using collections.heapq)? Since you're just trying to find the max value, you can iterate node_neighbors in descending order, the first node that is in selected_node must be the max in selected_node.\nSecond, how often will selected_node changes? If it changes rarely, you can save a lot of iterations by having a list of \"interaction_graph.node[neighbor] for x in selected_node\" instead of having to rebuild this list every time.\nEDIT: to reply on the comments\n\nA sort() would take O(n log n)\n\nNot necessarily, you're looking too much at your textbook. Despite what your textbook says, you can sometimes break the O(n log n) barrier by exploiting certain structure of your data. If you keep your list of neighbors in a naturally sorted data structure in the first place (e.g. heapq, binary tree), you don't need to re-sort at every iteration. Of course this is a space-time tradeoff, since you will need to store redundant lists of neighbors and there is code complexity to ensure that the list of neighbors is updated when the neighbors changes.\nAlso, python's list.sort(), which uses timsort algorithm, is very fast for nearly sorted data (could average O(n) in certain cases). It still doesn't break O(n log n), that much has been proven to be mathematically impossible.\nYou need to profile before dismissing a solution as not likely to improve performance. When doing extreme optimizations, you will likely find that in certain very special edge cases old and slow bubble sort may win over a glorified quicksort or mergesort.\n", "I don't see why your \"weight\" lookups have to be in the form of [\"weight\"] (nodes are dictionaries?) instead of .weight (nodes are objects).\nIf your nodes are objects, and don't have a lot of fields, you can take advantage of the __slots__ directive to optimize their storage:\nclass Node(object):\n # ... class stuff goes here ...\n\n __slots__ = ('weight',) # tuple of member names.\n\nEDIT: So I looked at the NetworkX link you provided, and there are several things that bother me. First is that, right at the top, the definition of \"dictionary\" is \"FIXME\".\nOverall, it seems insistent on using dictionaries, rather than using classes that can be subclassed, to store attributes. While attribute lookup on an object may be essentially a dictionary lookup, I don't see how working with an object can be worse. If anything, it could be better since an object attribute lookup is more likely to be optimized, because:\n\nobject attribute lookups are so common,\nthe keyspace for object attributes is far more restricted than for dictionary keys, thus an optimized comparison algorithm can be used in the search, and\nobjects have the __slots__ optimization for exactly these cases, where you have an object with only a couple fields and need optimized access to them.\n\nI frequently use __slots__ on classes that represent coordinates, for example. A tree node would seem, to me, another obvious use.\nSo that's why when I read:\n\nnode\n A node can be any hashable Python object except None.\n\nI think, okay, no problem, but then immediately following is\n\nnode attribute\n Nodes can have arbitrary Python objects assigned as attributes by using keyword/value pairs when adding a node or assigning to the G.node[n] attribute dictionary for the specified node n.\n\nI think, if a node needs attributes, why would it be stored separately? Why not just put it in the node? Is writing a class with contentString and weight members detrimental? Edges seem even crazier, since they're dictated to be tuples and not objects which you could subclass.\nSo I'm rather lost as to the design decisions behind NetworkX.\nIf you're stuck with it, I'd recommend moving attributes from those dictionaries into the actual nodes, or if that's not an option, using integers for keys into your attribute dictionary instead of strings, so searches use a much faster comparison algorithm.\nFinally, what if you combined your generators:\nneighbor_z_scores = (interaction_graph.node[neighbor]['weight'] for\n neighbor in node_neighbors if neighbor in selected_nodes)\n\n", "Try just directly accessing the dict and catch KeyErrors, it might be faster depending on your hit/miss ratio:\n# cache this object\nignode = interaction_graph.node\nneighbor_z_scores = []\nfor neighbor in node_neighbors:\n try:\n neighbor_z_scores.append(ignode[neighbor]['weight'])\n except KeyError:\n pass\n\nor with the getdefault and list comprehension:\nsentinel = object()\n# cache this object \nignode = interaction_graph.node\n\nneighbor_z_scores = (ignode[neighbor]['weight'] for neighbor in node_neighbors)\n# using identity testing, it's slightly faster\nneighbor_z_scores = (neighbor for neighbor in neighbor_z_scores if neighbor is not sentinel)\n\n", "Without looking deeply into your code, try adding a little speed with itertools.\nAdd these at the module level:\nimport itertools as it, operator as op\nGET_WEIGHT= op.attrgetter('weight')\n\nChange:\nneighbors_in_selected_nodes = (neighbor for neighbor in\n node_neighbors if neighbor in selected_nodes)\n\ninto:\nneighbors_in_selected_nodes = it.ifilter(selected_node.__contains__, node_neighbors)\n\nand:\nneighbor_z_scores = (interaction_graph.node[neighbor]['weight'] for\n neighbor in neighbors_in_selected_nodes)\n\ninto:\nneighbor_z_scores = (\n it.imap(\n GET_WEIGHT,\n it.imap(\n interaction_graph.node.__getitem__,\n neighbors_in_selected_nodes)\n )\n)\n\nDo these help?\n" ]
[ 1, 1, 0, 0 ]
[]
[]
[ "dictionary", "optimization", "profiling", "python" ]
stackoverflow_0002580158_dictionary_optimization_profiling_python.txt
Q: pdftotext can't find any of the files to convert when called within a python script i have a python script which keeps crashing on: subprocess.call(["pdftotext", pdf_filename]) the error being: OSError: [Errno 2] No such file or directory the absolute path to the filename (which i am storing in a log file as i debug) is fine; on the command line, if i type pdftotext <pdf_filename_goes_here> it works for any of the alledgedly bad file names. but when called using subprocess in python i keep getting that error. what is going on??? also, i tried on the python interpreter, and it worked! >>> import subprocess >>> subprocess.call(["pdftotext", "/path/to/file/test.pdf"]) 0 >>> update: just to make it known to everyone, i also tried: subprocess.call(["/usr/bin/pdftotext", "/path/to/file/test.pdf"]) which also gave the same error. and ive used /usr/bin/pdftotext test.pdf directly and it worked so i know that's the correct path to the pdftotext executable. any other suggestions? A: You'll also get that error if it can't find the executable on path...try using a full path to pdftotext as well, and look at how the $PATH for subprocess.call is set.
pdftotext can't find any of the files to convert when called within a python script
i have a python script which keeps crashing on: subprocess.call(["pdftotext", pdf_filename]) the error being: OSError: [Errno 2] No such file or directory the absolute path to the filename (which i am storing in a log file as i debug) is fine; on the command line, if i type pdftotext <pdf_filename_goes_here> it works for any of the alledgedly bad file names. but when called using subprocess in python i keep getting that error. what is going on??? also, i tried on the python interpreter, and it worked! >>> import subprocess >>> subprocess.call(["pdftotext", "/path/to/file/test.pdf"]) 0 >>> update: just to make it known to everyone, i also tried: subprocess.call(["/usr/bin/pdftotext", "/path/to/file/test.pdf"]) which also gave the same error. and ive used /usr/bin/pdftotext test.pdf directly and it worked so i know that's the correct path to the pdftotext executable. any other suggestions?
[ "You'll also get that error if it can't find the executable on path...try using a full path to pdftotext as well, and look at how the $PATH for subprocess.call is set.\n" ]
[ 1 ]
[]
[]
[ "pdftotext", "python" ]
stackoverflow_0002660803_pdftotext_python.txt
Q: Tkinter layout question Tricky to explain with words so I'll use a picture. A: row 0, column 0 B: row 0, column 1 C: row 1, column 0, span 2 A: Try: A: row 0, column 0, sticky=W B: row 0, column 1, sticky=W C: row 1, column 0, span 3 grid_columnconfigure(2, weight=4) A: What you can't see in that picture is the big element D in the third slot of the 3-element hbox that's in the first slot of the 2-element vbox.
Tkinter layout question
Tricky to explain with words so I'll use a picture. A: row 0, column 0 B: row 0, column 1 C: row 1, column 0, span 2
[ "Try:\nA: row 0, column 0, sticky=W\nB: row 0, column 1, sticky=W\nC: row 1, column 0, span 3\ngrid_columnconfigure(2, weight=4)\n\n", "What you can't see in that picture is the big element D in the third slot of the 3-element hbox that's in the first slot of the 2-element vbox.\n" ]
[ 2, 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0002660895_python_tkinter.txt
Q: Unexplained Django error. Diagnosis anyone? I have a django project I keep on github. It worked perfectly fine on my laptop. I downloaded it on my desktop and tried to "python manage.py runserver" or even "python manage.py shell" I get a Error: No module named messages No other messages, no stack trace, nothing..Anyone have any idea whats going on? Thanks. A: I have come across similar errors a number of times. They have been the result of python not being able to find the django or project files in the path. This is exceptionally annoying when django gets installed or referenced to one version of python when you have multiple python installs on the machine. It may help to explicitly choose which python version you are using, ie python2.5 manage.py runserver or python2.6 manage.py runserver. Make sure you have your project in your PYTHONPATH.
Unexplained Django error. Diagnosis anyone?
I have a django project I keep on github. It worked perfectly fine on my laptop. I downloaded it on my desktop and tried to "python manage.py runserver" or even "python manage.py shell" I get a Error: No module named messages No other messages, no stack trace, nothing..Anyone have any idea whats going on? Thanks.
[ "I have come across similar errors a number of times. They have been the result of python not being able to find the django or project files in the path. This is exceptionally annoying when django gets installed or referenced to one version of python when you have multiple python installs on the machine. It may help to explicitly choose which python version you are using, ie python2.5 manage.py runserver or python2.6 manage.py runserver.\nMake sure you have your project in your PYTHONPATH.\n" ]
[ 6 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002661015_django_python.txt
Q: How to access external object within event handler? As the title says, I'm grabbing the cursor location within a motion triggered event handler in Tkinter. I'd like to update an existing label widget with the location. However, I cannot for the life of me figure out how to edit the Label text field (or any external object for that matter) within the event handler. From what I understand, event is the only argument passed to the handler, which means I can't pass the label object. How do I access objects outside of the handler? A: Tkinter won't pass around objects in event handler, and anyway how it would know in which object you are interested in? Instead it is your responsibility to access the objects you wish to update from event handler, e.g. your event handler could be simple function and it could access global object, or it can be a method of an object and can access that object via self. Here is a way using global objects from Tkinter import * root = Tk() frame = Frame(root) frame.configure(width=300,height=300) def onmotion(event): root.title("Mouse at %s,%s"%(event.x, event.y)) frame.bind("<Motion>", onmotion) frame.pack() root.title("Event test") root.mainloop() Same thing can be done in an object oriented way from Tkinter import * class MyFrame(Frame): def __init__(self, root): Frame.__init__(self, root) self.parent = root self.configure(width=300,height=300) self.pack() self.bind("<Motion>", self.onmotion) def onmotion(self, event): self.parent.title("Mouse at %s,%s"%(event.x, event.y)) root = Tk() frame = MyFrame(root) root.title("Event test") root.mainloop()
How to access external object within event handler?
As the title says, I'm grabbing the cursor location within a motion triggered event handler in Tkinter. I'd like to update an existing label widget with the location. However, I cannot for the life of me figure out how to edit the Label text field (or any external object for that matter) within the event handler. From what I understand, event is the only argument passed to the handler, which means I can't pass the label object. How do I access objects outside of the handler?
[ "Tkinter won't pass around objects in event handler, and anyway how it would know in which object you are interested in? \nInstead it is your responsibility to access the objects you wish to update from event handler, e.g. your event handler could be simple function and it could access global object, or it can be a method of an object and can access that object via self.\nHere is a way using global objects\nfrom Tkinter import *\n\nroot = Tk()\nframe = Frame(root)\nframe.configure(width=300,height=300)\n\ndef onmotion(event):\n root.title(\"Mouse at %s,%s\"%(event.x, event.y))\n\nframe.bind(\"<Motion>\", onmotion)\nframe.pack()\nroot.title(\"Event test\")\nroot.mainloop()\n\nSame thing can be done in an object oriented way\nfrom Tkinter import *\n\nclass MyFrame(Frame):\n def __init__(self, root):\n Frame.__init__(self, root)\n self.parent = root\n self.configure(width=300,height=300)\n self.pack()\n self.bind(\"<Motion>\", self.onmotion)\n\n def onmotion(self, event):\n self.parent.title(\"Mouse at %s,%s\"%(event.x, event.y))\n\nroot = Tk()\nframe = MyFrame(root)\nroot.title(\"Event test\")\nroot.mainloop()\n\n" ]
[ 3 ]
[]
[]
[ "events", "handler", "python", "tkinter", "user_interface" ]
stackoverflow_0002660881_events_handler_python_tkinter_user_interface.txt
Q: AJAX based remote Online text editor I'm looking to install an online text editor on my server, that I can link to svn. I would like to have some form of syntax highlighting, keyboard shortcuts, and perhaps some text complete. Languages, python, php, sql, and C++ are a minimum ... any suggestions? A: you should have a look at https://mozillalabs.com/bespin/ I've tried it and decided not to use it, but only because it's web-based, the same reason why I use googledocs only when I really need to. If you don't want to build a public service, you may use the approach I like. That is to install your favourite editor/IDE at the server and start ssh server. From the client, connect with enabled X forwarding (to connect from Windows, use Xming an portablePuTTY). A: I don't know of any browser-based client-server editors like that, assuming I understand correctly what you are trying to do. Two things come to mind: Since it's a long-solved problem and generally fairly trivial task to configure a svn server and there are plenty of text editors / IDEs out there with svn client interfaces, why re-invent the wheel? If you must or really want to and have gobs of time, go wild and crazy perhaps by starting with a simple existing Python-based editor (Leo perhaps?) or roll you own and/or existing syntax highlighting packages, like Pygments, find a way to split it into a client-server architecture with some AJAX glue between them, and port the front-end client part to run under Pyjamas, a framework for running a subset of Python as JavaScript, and to use a browser as the GUI. And let us know how it turns out!
AJAX based remote Online text editor
I'm looking to install an online text editor on my server, that I can link to svn. I would like to have some form of syntax highlighting, keyboard shortcuts, and perhaps some text complete. Languages, python, php, sql, and C++ are a minimum ... any suggestions?
[ "you should have a look at https://mozillalabs.com/bespin/ \nI've tried it and decided not to use it, but only because it's web-based, the same reason why I use googledocs only when I really need to. \nIf you don't want to build a public service, you may use the approach I like. That is to install your favourite editor/IDE at the server and start ssh server. From the client, connect with enabled X forwarding (to connect from Windows, use Xming an portablePuTTY).\n", "I don't know of any browser-based client-server editors like that, assuming I understand correctly what you are trying to do.\nTwo things come to mind:\n\nSince it's a long-solved problem\nand generally fairly trivial task to\nconfigure a svn server\nand there are plenty of\ntext editors / IDEs out there with\nsvn client interfaces, why re-invent\nthe wheel?\nIf you must or really want to\nand have gobs of time, go wild and\ncrazy perhaps by starting with a\nsimple existing Python-based editor\n(Leo perhaps?) or roll you own\nand/or existing syntax highlighting\npackages, like Pygments, find a way to split it into a client-server\narchitecture with some AJAX glue between them, and\nport the front-end client part to run under\nPyjamas, a framework for\nrunning a subset of Python as\nJavaScript, and to use a browser as the GUI. And let us know how it\nturns out!\n\n" ]
[ 2, 1 ]
[]
[]
[ "ide", "python", "text_editor" ]
stackoverflow_0002660886_ide_python_text_editor.txt